1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
7 #include <linux/sched/mm.h>
9 #include <linux/slab.h>
10 #include <linux/buffer_head.h>
11 #include <linux/blkdev.h>
12 #include <linux/ratelimit.h>
13 #include <linux/kthread.h>
14 #include <linux/raid/pq.h>
15 #include <linux/semaphore.h>
16 #include <linux/uuid.h>
17 #include <linux/list_sort.h>
20 #include "extent_map.h"
22 #include "transaction.h"
23 #include "print-tree.h"
26 #include "async-thread.h"
27 #include "check-integrity.h"
28 #include "rcu-string.h"
29 #include "dev-replace.h"
31 #include "tree-checker.h"
32 #include "space-info.h"
33 #include "block-group.h"
35 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
36 [BTRFS_RAID_RAID10] = {
39 .devs_max = 0, /* 0 == as many as possible */
41 .tolerated_failures = 1,
45 .raid_name = "raid10",
46 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
47 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
49 [BTRFS_RAID_RAID1] = {
54 .tolerated_failures = 1,
59 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
60 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
67 .tolerated_failures = 0,
72 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
75 [BTRFS_RAID_RAID0] = {
80 .tolerated_failures = 0,
85 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
88 [BTRFS_RAID_SINGLE] = {
93 .tolerated_failures = 0,
97 .raid_name = "single",
101 [BTRFS_RAID_RAID5] = {
106 .tolerated_failures = 1,
110 .raid_name = "raid5",
111 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
112 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
114 [BTRFS_RAID_RAID6] = {
119 .tolerated_failures = 2,
123 .raid_name = "raid6",
124 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
125 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
129 const char *btrfs_bg_type_to_raid_name(u64 flags)
131 const int index = btrfs_bg_flags_to_raid_index(flags);
133 if (index >= BTRFS_NR_RAID_TYPES)
136 return btrfs_raid_array[index].raid_name;
140 * Fill @buf with textual description of @bg_flags, no more than @size_buf
141 * bytes including terminating null byte.
143 void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
148 u64 flags = bg_flags;
149 u32 size_bp = size_buf;
156 #define DESCRIBE_FLAG(flag, desc) \
158 if (flags & (flag)) { \
159 ret = snprintf(bp, size_bp, "%s|", (desc)); \
160 if (ret < 0 || ret >= size_bp) \
168 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
169 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
170 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
172 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
173 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
174 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
175 btrfs_raid_array[i].raid_name);
179 ret = snprintf(bp, size_bp, "0x%llx|", flags);
183 if (size_bp < size_buf)
184 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
187 * The text is trimmed, it's up to the caller to provide sufficiently
193 static int init_first_rw_device(struct btrfs_trans_handle *trans);
194 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
195 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
196 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
197 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
198 enum btrfs_map_op op,
199 u64 logical, u64 *length,
200 struct btrfs_bio **bbio_ret,
201 int mirror_num, int need_raid_map);
207 * There are several mutexes that protect manipulation of devices and low-level
208 * structures like chunks but not block groups, extents or files
210 * uuid_mutex (global lock)
211 * ------------------------
212 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
213 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
214 * device) or requested by the device= mount option
216 * the mutex can be very coarse and can cover long-running operations
218 * protects: updates to fs_devices counters like missing devices, rw devices,
219 * seeding, structure cloning, opening/closing devices at mount/umount time
221 * global::fs_devs - add, remove, updates to the global list
223 * does not protect: manipulation of the fs_devices::devices list in general
224 * but in mount context it could be used to exclude list modifications by eg.
227 * btrfs_device::name - renames (write side), read is RCU
229 * fs_devices::device_list_mutex (per-fs, with RCU)
230 * ------------------------------------------------
231 * protects updates to fs_devices::devices, ie. adding and deleting
233 * simple list traversal with read-only actions can be done with RCU protection
235 * may be used to exclude some operations from running concurrently without any
236 * modifications to the list (see write_all_supers)
238 * Is not required at mount and close times, because our device list is
239 * protected by the uuid_mutex at that point.
243 * protects balance structures (status, state) and context accessed from
244 * several places (internally, ioctl)
248 * protects chunks, adding or removing during allocation, trim or when a new
249 * device is added/removed. Additionally it also protects post_commit_list of
250 * individual devices, since they can be added to the transaction's
251 * post_commit_list only with chunk_mutex held.
255 * a big lock that is held by the cleaner thread and prevents running subvolume
256 * cleaning together with relocation or delayed iputs
269 * Exclusive operations, BTRFS_FS_EXCL_OP
270 * ======================================
272 * Maintains the exclusivity of the following operations that apply to the
273 * whole filesystem and cannot run in parallel.
278 * - Device replace (*)
281 * The device operations (as above) can be in one of the following states:
287 * Only device operations marked with (*) can go into the Paused state for the
290 * - ioctl (only Balance can be Paused through ioctl)
291 * - filesystem remounted as read-only
292 * - filesystem unmounted and mounted as read-only
293 * - system power-cycle and filesystem mounted as read-only
294 * - filesystem or device errors leading to forced read-only
296 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
297 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
298 * A device operation in Paused or Running state can be canceled or resumed
299 * either by ioctl (Balance only) or when remounted as read-write.
300 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
304 DEFINE_MUTEX(uuid_mutex);
305 static LIST_HEAD(fs_uuids);
306 struct list_head *btrfs_get_fs_uuids(void)
312 * alloc_fs_devices - allocate struct btrfs_fs_devices
313 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
314 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
316 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
317 * The returned struct is not linked onto any lists and can be destroyed with
318 * kfree() right away.
320 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
321 const u8 *metadata_fsid)
323 struct btrfs_fs_devices *fs_devs;
325 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
327 return ERR_PTR(-ENOMEM);
329 mutex_init(&fs_devs->device_list_mutex);
331 INIT_LIST_HEAD(&fs_devs->devices);
332 INIT_LIST_HEAD(&fs_devs->alloc_list);
333 INIT_LIST_HEAD(&fs_devs->fs_list);
335 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
338 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
340 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
345 void btrfs_free_device(struct btrfs_device *device)
347 WARN_ON(!list_empty(&device->post_commit_list));
348 rcu_string_free(device->name);
349 extent_io_tree_release(&device->alloc_state);
350 bio_put(device->flush_bio);
354 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
356 struct btrfs_device *device;
358 WARN_ON(fs_devices->opened);
359 while (!list_empty(&fs_devices->devices)) {
360 device = list_entry(fs_devices->devices.next,
361 struct btrfs_device, dev_list);
362 list_del(&device->dev_list);
363 btrfs_free_device(device);
368 void __exit btrfs_cleanup_fs_uuids(void)
370 struct btrfs_fs_devices *fs_devices;
372 while (!list_empty(&fs_uuids)) {
373 fs_devices = list_entry(fs_uuids.next,
374 struct btrfs_fs_devices, fs_list);
375 list_del(&fs_devices->fs_list);
376 free_fs_devices(fs_devices);
381 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
382 * Returned struct is not linked onto any lists and must be destroyed using
385 static struct btrfs_device *__alloc_device(void)
387 struct btrfs_device *dev;
389 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
391 return ERR_PTR(-ENOMEM);
394 * Preallocate a bio that's always going to be used for flushing device
395 * barriers and matches the device lifespan
397 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
398 if (!dev->flush_bio) {
400 return ERR_PTR(-ENOMEM);
403 INIT_LIST_HEAD(&dev->dev_list);
404 INIT_LIST_HEAD(&dev->dev_alloc_list);
405 INIT_LIST_HEAD(&dev->post_commit_list);
407 spin_lock_init(&dev->io_lock);
409 atomic_set(&dev->reada_in_flight, 0);
410 atomic_set(&dev->dev_stats_ccnt, 0);
411 btrfs_device_data_ordered_init(dev);
412 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
413 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
414 extent_io_tree_init(NULL, &dev->alloc_state, 0, NULL);
419 static noinline struct btrfs_fs_devices *find_fsid(
420 const u8 *fsid, const u8 *metadata_fsid)
422 struct btrfs_fs_devices *fs_devices;
428 * Handle scanned device having completed its fsid change but
429 * belonging to a fs_devices that was created by first scanning
430 * a device which didn't have its fsid/metadata_uuid changed
431 * at all and the CHANGING_FSID_V2 flag set.
433 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
434 if (fs_devices->fsid_change &&
435 memcmp(metadata_fsid, fs_devices->fsid,
436 BTRFS_FSID_SIZE) == 0 &&
437 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
438 BTRFS_FSID_SIZE) == 0) {
443 * Handle scanned device having completed its fsid change but
444 * belonging to a fs_devices that was created by a device that
445 * has an outdated pair of fsid/metadata_uuid and
446 * CHANGING_FSID_V2 flag set.
448 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
449 if (fs_devices->fsid_change &&
450 memcmp(fs_devices->metadata_uuid,
451 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
452 memcmp(metadata_fsid, fs_devices->metadata_uuid,
453 BTRFS_FSID_SIZE) == 0) {
459 /* Handle non-split brain cases */
460 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
462 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
463 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
464 BTRFS_FSID_SIZE) == 0)
467 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
475 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
476 int flush, struct block_device **bdev,
477 struct buffer_head **bh)
481 *bdev = blkdev_get_by_path(device_path, flags, holder);
484 ret = PTR_ERR(*bdev);
489 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
490 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
492 blkdev_put(*bdev, flags);
495 invalidate_bdev(*bdev);
496 *bh = btrfs_read_dev_super(*bdev);
499 blkdev_put(*bdev, flags);
511 static void requeue_list(struct btrfs_pending_bios *pending_bios,
512 struct bio *head, struct bio *tail)
515 struct bio *old_head;
517 old_head = pending_bios->head;
518 pending_bios->head = head;
519 if (pending_bios->tail)
520 tail->bi_next = old_head;
522 pending_bios->tail = tail;
526 * we try to collect pending bios for a device so we don't get a large
527 * number of procs sending bios down to the same device. This greatly
528 * improves the schedulers ability to collect and merge the bios.
530 * But, it also turns into a long list of bios to process and that is sure
531 * to eventually make the worker thread block. The solution here is to
532 * make some progress and then put this work struct back at the end of
533 * the list if the block device is congested. This way, multiple devices
534 * can make progress from a single worker thread.
536 static noinline void run_scheduled_bios(struct btrfs_device *device)
538 struct btrfs_fs_info *fs_info = device->fs_info;
540 struct backing_dev_info *bdi;
541 struct btrfs_pending_bios *pending_bios;
545 unsigned long num_run;
546 unsigned long batch_run = 0;
547 unsigned long last_waited = 0;
549 int sync_pending = 0;
550 struct blk_plug plug;
553 * this function runs all the bios we've collected for
554 * a particular device. We don't want to wander off to
555 * another device without first sending all of these down.
556 * So, setup a plug here and finish it off before we return
558 blk_start_plug(&plug);
560 bdi = device->bdev->bd_bdi;
563 spin_lock(&device->io_lock);
568 /* take all the bios off the list at once and process them
569 * later on (without the lock held). But, remember the
570 * tail and other pointers so the bios can be properly reinserted
571 * into the list if we hit congestion
573 if (!force_reg && device->pending_sync_bios.head) {
574 pending_bios = &device->pending_sync_bios;
577 pending_bios = &device->pending_bios;
581 pending = pending_bios->head;
582 tail = pending_bios->tail;
583 WARN_ON(pending && !tail);
586 * if pending was null this time around, no bios need processing
587 * at all and we can stop. Otherwise it'll loop back up again
588 * and do an additional check so no bios are missed.
590 * device->running_pending is used to synchronize with the
593 if (device->pending_sync_bios.head == NULL &&
594 device->pending_bios.head == NULL) {
596 device->running_pending = 0;
599 device->running_pending = 1;
602 pending_bios->head = NULL;
603 pending_bios->tail = NULL;
605 spin_unlock(&device->io_lock);
610 /* we want to work on both lists, but do more bios on the
611 * sync list than the regular list
614 pending_bios != &device->pending_sync_bios &&
615 device->pending_sync_bios.head) ||
616 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
617 device->pending_bios.head)) {
618 spin_lock(&device->io_lock);
619 requeue_list(pending_bios, pending, tail);
624 pending = pending->bi_next;
627 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
630 * if we're doing the sync list, record that our
631 * plug has some sync requests on it
633 * If we're doing the regular list and there are
634 * sync requests sitting around, unplug before
637 if (pending_bios == &device->pending_sync_bios) {
639 } else if (sync_pending) {
640 blk_finish_plug(&plug);
641 blk_start_plug(&plug);
645 btrfsic_submit_bio(cur);
652 * we made progress, there is more work to do and the bdi
653 * is now congested. Back off and let other work structs
656 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
657 fs_info->fs_devices->open_devices > 1) {
658 struct io_context *ioc;
660 ioc = current->io_context;
663 * the main goal here is that we don't want to
664 * block if we're going to be able to submit
665 * more requests without blocking.
667 * This code does two great things, it pokes into
668 * the elevator code from a filesystem _and_
669 * it makes assumptions about how batching works.
671 if (ioc && ioc->nr_batch_requests > 0 &&
672 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
674 ioc->last_waited == last_waited)) {
676 * we want to go through our batch of
677 * requests and stop. So, we copy out
678 * the ioc->last_waited time and test
679 * against it before looping
681 last_waited = ioc->last_waited;
685 spin_lock(&device->io_lock);
686 requeue_list(pending_bios, pending, tail);
687 device->running_pending = 1;
689 spin_unlock(&device->io_lock);
690 btrfs_queue_work(fs_info->submit_workers,
700 spin_lock(&device->io_lock);
701 if (device->pending_bios.head || device->pending_sync_bios.head)
703 spin_unlock(&device->io_lock);
706 blk_finish_plug(&plug);
709 static void pending_bios_fn(struct btrfs_work *work)
711 struct btrfs_device *device;
713 device = container_of(work, struct btrfs_device, work);
714 run_scheduled_bios(device);
718 * Check if the device in the path matches the device in the given struct device.
721 * true If it is the same device.
722 * false If it is not the same device or on error.
724 static bool device_matched(const struct btrfs_device *device, const char *path)
727 struct block_device *bdev_old;
728 struct block_device *bdev_new;
731 * If we are looking for a device with the matching dev_t, then skip
732 * device without a name (a missing device).
737 device_name = kzalloc(BTRFS_PATH_NAME_MAX, GFP_KERNEL);
742 scnprintf(device_name, BTRFS_PATH_NAME_MAX, "%s", rcu_str_deref(device->name));
745 bdev_old = lookup_bdev(device_name);
747 if (IS_ERR(bdev_old))
750 bdev_new = lookup_bdev(path);
751 if (IS_ERR(bdev_new))
754 if (bdev_old == bdev_new)
761 * Search and remove all stale (devices which are not mounted) devices.
762 * When both inputs are NULL, it will search and release all stale devices.
763 * path: Optional. When provided will it release all unmounted devices
764 * matching this path only.
765 * skip_dev: Optional. Will skip this device when searching for the stale
767 * Return: 0 for success or if @path is NULL.
768 * -EBUSY if @path is a mounted device.
769 * -ENOENT if @path does not match any device in the list.
771 static int btrfs_free_stale_devices(const char *path,
772 struct btrfs_device *skip_device)
774 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
775 struct btrfs_device *device, *tmp_device;
778 lockdep_assert_held(&uuid_mutex);
783 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
785 mutex_lock(&fs_devices->device_list_mutex);
786 list_for_each_entry_safe(device, tmp_device,
787 &fs_devices->devices, dev_list) {
788 if (skip_device && skip_device == device)
790 if (path && !device_matched(device, path))
792 if (fs_devices->opened) {
793 /* for an already deleted device return 0 */
794 if (path && ret != 0)
799 /* delete the stale device */
800 fs_devices->num_devices--;
801 list_del(&device->dev_list);
802 btrfs_free_device(device);
805 if (fs_devices->num_devices == 0)
808 mutex_unlock(&fs_devices->device_list_mutex);
810 if (fs_devices->num_devices == 0) {
811 btrfs_sysfs_remove_fsid(fs_devices);
812 list_del(&fs_devices->fs_list);
813 free_fs_devices(fs_devices);
821 * This is only used on mount, and we are protected from competing things
822 * messing with our fs_devices by the uuid_mutex, thus we do not need the
823 * fs_devices->device_list_mutex here.
825 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
826 struct btrfs_device *device, fmode_t flags,
829 struct request_queue *q;
830 struct block_device *bdev;
831 struct buffer_head *bh;
832 struct btrfs_super_block *disk_super;
841 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
846 disk_super = (struct btrfs_super_block *)bh->b_data;
847 devid = btrfs_stack_device_id(&disk_super->dev_item);
848 if (devid != device->devid)
851 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
854 device->generation = btrfs_super_generation(disk_super);
856 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
857 if (btrfs_super_incompat_flags(disk_super) &
858 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
860 "BTRFS: Invalid seeding and uuid-changed device detected\n");
864 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
865 fs_devices->seeding = 1;
867 if (bdev_read_only(bdev))
868 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
870 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
873 q = bdev_get_queue(bdev);
874 if (!blk_queue_nonrot(q))
875 fs_devices->rotating = 1;
878 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
879 device->mode = flags;
881 fs_devices->open_devices++;
882 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
883 device->devid != BTRFS_DEV_REPLACE_DEVID) {
884 fs_devices->rw_devices++;
885 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
893 blkdev_put(bdev, flags);
898 u8 *btrfs_sb_fsid_ptr(struct btrfs_super_block *sb)
900 bool has_metadata_uuid = (btrfs_super_incompat_flags(sb) &
901 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
903 return has_metadata_uuid ? sb->metadata_uuid : sb->fsid;
907 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
908 * being created with a disk that has already completed its fsid change.
910 static struct btrfs_fs_devices *find_fsid_inprogress(
911 struct btrfs_super_block *disk_super)
913 struct btrfs_fs_devices *fs_devices;
915 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
916 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
917 BTRFS_FSID_SIZE) != 0 &&
918 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
919 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
928 static struct btrfs_fs_devices *find_fsid_changed(
929 struct btrfs_super_block *disk_super)
931 struct btrfs_fs_devices *fs_devices;
934 * Handles the case where scanned device is part of an fs that had
935 * multiple successful changes of FSID but curently device didn't
936 * observe it. Meaning our fsid will be different than theirs. We need
937 * to handle two subcases :
938 * 1 - The fs still continues to have different METADATA/FSID uuids.
939 * 2 - The fs is switched back to its original FSID (METADATA/FSID
942 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
944 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
945 BTRFS_FSID_SIZE) != 0 &&
946 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
947 BTRFS_FSID_SIZE) == 0 &&
948 memcmp(fs_devices->fsid, disk_super->fsid,
949 BTRFS_FSID_SIZE) != 0)
952 /* Unchanged UUIDs */
953 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
954 BTRFS_FSID_SIZE) == 0 &&
955 memcmp(fs_devices->fsid, disk_super->metadata_uuid,
956 BTRFS_FSID_SIZE) == 0)
963 static struct btrfs_fs_devices *find_fsid_reverted_metadata(
964 struct btrfs_super_block *disk_super)
966 struct btrfs_fs_devices *fs_devices;
969 * Handle the case where the scanned device is part of an fs whose last
970 * metadata UUID change reverted it to the original FSID. At the same
971 * time * fs_devices was first created by another constitutent device
972 * which didn't fully observe the operation. This results in an
973 * btrfs_fs_devices created with metadata/fsid different AND
974 * btrfs_fs_devices::fsid_change set AND the metadata_uuid of the
975 * fs_devices equal to the FSID of the disk.
977 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
978 if (memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
979 BTRFS_FSID_SIZE) != 0 &&
980 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
981 BTRFS_FSID_SIZE) == 0 &&
982 fs_devices->fsid_change)
989 * Add new device to list of registered devices
992 * device pointer which was just added or updated when successful
993 * error pointer when failed
995 static noinline struct btrfs_device *device_list_add(const char *path,
996 struct btrfs_super_block *disk_super,
997 bool *new_device_added)
999 struct btrfs_device *device;
1000 struct btrfs_fs_devices *fs_devices = NULL;
1001 struct rcu_string *name;
1002 u64 found_transid = btrfs_super_generation(disk_super);
1003 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
1004 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
1005 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
1006 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
1007 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
1009 if (fsid_change_in_progress) {
1010 if (!has_metadata_uuid) {
1012 * When we have an image which has CHANGING_FSID_V2 set
1013 * it might belong to either a filesystem which has
1014 * disks with completed fsid change or it might belong
1015 * to fs with no UUID changes in effect, handle both.
1017 fs_devices = find_fsid_inprogress(disk_super);
1019 fs_devices = find_fsid(disk_super->fsid, NULL);
1021 fs_devices = find_fsid_changed(disk_super);
1023 } else if (has_metadata_uuid) {
1024 fs_devices = find_fsid(disk_super->fsid,
1025 disk_super->metadata_uuid);
1027 fs_devices = find_fsid_reverted_metadata(disk_super);
1029 fs_devices = find_fsid(disk_super->fsid, NULL);
1034 if (has_metadata_uuid)
1035 fs_devices = alloc_fs_devices(disk_super->fsid,
1036 disk_super->metadata_uuid);
1038 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
1040 if (IS_ERR(fs_devices))
1041 return ERR_CAST(fs_devices);
1043 fs_devices->fsid_change = fsid_change_in_progress;
1045 mutex_lock(&fs_devices->device_list_mutex);
1046 list_add(&fs_devices->fs_list, &fs_uuids);
1050 mutex_lock(&fs_devices->device_list_mutex);
1051 device = btrfs_find_device(fs_devices, devid,
1052 disk_super->dev_item.uuid, NULL, false);
1055 * If this disk has been pulled into an fs devices created by
1056 * a device which had the CHANGING_FSID_V2 flag then replace the
1057 * metadata_uuid/fsid values of the fs_devices.
1059 if (fs_devices->fsid_change &&
1060 found_transid > fs_devices->latest_generation) {
1061 memcpy(fs_devices->fsid, disk_super->fsid,
1064 if (has_metadata_uuid)
1065 memcpy(fs_devices->metadata_uuid,
1066 disk_super->metadata_uuid,
1069 memcpy(fs_devices->metadata_uuid,
1070 disk_super->fsid, BTRFS_FSID_SIZE);
1072 fs_devices->fsid_change = false;
1077 if (fs_devices->opened) {
1078 mutex_unlock(&fs_devices->device_list_mutex);
1079 return ERR_PTR(-EBUSY);
1082 device = btrfs_alloc_device(NULL, &devid,
1083 disk_super->dev_item.uuid);
1084 if (IS_ERR(device)) {
1085 mutex_unlock(&fs_devices->device_list_mutex);
1086 /* we can safely leave the fs_devices entry around */
1090 name = rcu_string_strdup(path, GFP_NOFS);
1092 btrfs_free_device(device);
1093 mutex_unlock(&fs_devices->device_list_mutex);
1094 return ERR_PTR(-ENOMEM);
1096 rcu_assign_pointer(device->name, name);
1098 list_add_rcu(&device->dev_list, &fs_devices->devices);
1099 fs_devices->num_devices++;
1101 device->fs_devices = fs_devices;
1102 *new_device_added = true;
1104 if (disk_super->label[0])
1105 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
1106 disk_super->label, devid, found_transid, path);
1108 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
1109 disk_super->fsid, devid, found_transid, path);
1111 } else if (!device->name || strcmp(device->name->str, path)) {
1113 * When FS is already mounted.
1114 * 1. If you are here and if the device->name is NULL that
1115 * means this device was missing at time of FS mount.
1116 * 2. If you are here and if the device->name is different
1117 * from 'path' that means either
1118 * a. The same device disappeared and reappeared with
1119 * different name. or
1120 * b. The missing-disk-which-was-replaced, has
1123 * We must allow 1 and 2a above. But 2b would be a spurious
1124 * and unintentional.
1126 * Further in case of 1 and 2a above, the disk at 'path'
1127 * would have missed some transaction when it was away and
1128 * in case of 2a the stale bdev has to be updated as well.
1129 * 2b must not be allowed at all time.
1133 * For now, we do allow update to btrfs_fs_device through the
1134 * btrfs dev scan cli after FS has been mounted. We're still
1135 * tracking a problem where systems fail mount by subvolume id
1136 * when we reject replacement on a mounted FS.
1138 if (!fs_devices->opened && found_transid < device->generation) {
1140 * That is if the FS is _not_ mounted and if you
1141 * are here, that means there is more than one
1142 * disk with same uuid and devid.We keep the one
1143 * with larger generation number or the last-in if
1144 * generation are equal.
1146 mutex_unlock(&fs_devices->device_list_mutex);
1147 return ERR_PTR(-EEXIST);
1151 * We are going to replace the device path for a given devid,
1152 * make sure it's the same device if the device is mounted
1155 struct block_device *path_bdev;
1157 path_bdev = lookup_bdev(path);
1158 if (IS_ERR(path_bdev)) {
1159 mutex_unlock(&fs_devices->device_list_mutex);
1160 return ERR_CAST(path_bdev);
1163 if (device->bdev != path_bdev) {
1165 mutex_unlock(&fs_devices->device_list_mutex);
1167 * device->fs_info may not be reliable here, so
1168 * pass in a NULL instead. This avoids a
1169 * possible use-after-free when the fs_info and
1170 * fs_info->sb are already torn down.
1172 btrfs_warn_in_rcu(NULL,
1173 "duplicate device %s devid %llu generation %llu scanned by %s (%d)",
1174 path, devid, found_transid,
1176 task_pid_nr(current));
1177 return ERR_PTR(-EEXIST);
1180 btrfs_info_in_rcu(device->fs_info,
1181 "devid %llu device path %s changed to %s scanned by %s (%d)",
1182 devid, rcu_str_deref(device->name),
1183 path, current->comm,
1184 task_pid_nr(current));
1187 name = rcu_string_strdup(path, GFP_NOFS);
1189 mutex_unlock(&fs_devices->device_list_mutex);
1190 return ERR_PTR(-ENOMEM);
1192 rcu_string_free(device->name);
1193 rcu_assign_pointer(device->name, name);
1194 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1195 fs_devices->missing_devices--;
1196 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1201 * Unmount does not free the btrfs_device struct but would zero
1202 * generation along with most of the other members. So just update
1203 * it back. We need it to pick the disk with largest generation
1206 if (!fs_devices->opened) {
1207 device->generation = found_transid;
1208 fs_devices->latest_generation = max_t(u64, found_transid,
1209 fs_devices->latest_generation);
1212 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
1214 mutex_unlock(&fs_devices->device_list_mutex);
1218 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
1220 struct btrfs_fs_devices *fs_devices;
1221 struct btrfs_device *device;
1222 struct btrfs_device *orig_dev;
1225 lockdep_assert_held(&uuid_mutex);
1227 fs_devices = alloc_fs_devices(orig->fsid, NULL);
1228 if (IS_ERR(fs_devices))
1231 fs_devices->total_devices = orig->total_devices;
1233 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
1234 struct rcu_string *name;
1236 device = btrfs_alloc_device(NULL, &orig_dev->devid,
1238 if (IS_ERR(device)) {
1239 ret = PTR_ERR(device);
1244 * This is ok to do without rcu read locked because we hold the
1245 * uuid mutex so nothing we touch in here is going to disappear.
1247 if (orig_dev->name) {
1248 name = rcu_string_strdup(orig_dev->name->str,
1251 btrfs_free_device(device);
1255 rcu_assign_pointer(device->name, name);
1258 list_add(&device->dev_list, &fs_devices->devices);
1259 device->fs_devices = fs_devices;
1260 fs_devices->num_devices++;
1264 free_fs_devices(fs_devices);
1265 return ERR_PTR(ret);
1269 * After we have read the system tree and know devids belonging to
1270 * this filesystem, remove the device which does not belong there.
1272 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
1274 struct btrfs_device *device, *next;
1275 struct btrfs_device *latest_dev = NULL;
1277 mutex_lock(&uuid_mutex);
1279 /* This is the initialized path, it is safe to release the devices. */
1280 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1281 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
1282 &device->dev_state)) {
1283 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1284 &device->dev_state) &&
1285 !test_bit(BTRFS_DEV_STATE_MISSING,
1286 &device->dev_state) &&
1288 device->generation > latest_dev->generation)) {
1289 latest_dev = device;
1295 * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID,
1296 * in btrfs_init_dev_replace() so just continue.
1298 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1302 blkdev_put(device->bdev, device->mode);
1303 device->bdev = NULL;
1304 fs_devices->open_devices--;
1306 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1307 list_del_init(&device->dev_alloc_list);
1308 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1309 fs_devices->rw_devices--;
1311 list_del_init(&device->dev_list);
1312 fs_devices->num_devices--;
1313 btrfs_free_device(device);
1316 if (fs_devices->seed) {
1317 fs_devices = fs_devices->seed;
1321 fs_devices->latest_bdev = latest_dev->bdev;
1323 mutex_unlock(&uuid_mutex);
1326 static void btrfs_close_bdev(struct btrfs_device *device)
1331 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1332 sync_blockdev(device->bdev);
1333 invalidate_bdev(device->bdev);
1336 blkdev_put(device->bdev, device->mode);
1339 static void btrfs_close_one_device(struct btrfs_device *device)
1341 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1342 struct btrfs_device *new_device;
1343 struct rcu_string *name;
1346 fs_devices->open_devices--;
1348 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1349 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1350 list_del_init(&device->dev_alloc_list);
1351 fs_devices->rw_devices--;
1354 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1355 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
1357 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1358 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1359 fs_devices->missing_devices--;
1362 btrfs_close_bdev(device);
1364 new_device = btrfs_alloc_device(NULL, &device->devid,
1366 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1368 /* Safe because we are under uuid_mutex */
1370 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1371 BUG_ON(!name); /* -ENOMEM */
1372 rcu_assign_pointer(new_device->name, name);
1375 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1376 new_device->fs_devices = device->fs_devices;
1379 btrfs_free_device(device);
1382 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1384 struct btrfs_device *device, *tmp;
1386 if (--fs_devices->opened > 0)
1389 mutex_lock(&fs_devices->device_list_mutex);
1390 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1391 btrfs_close_one_device(device);
1393 mutex_unlock(&fs_devices->device_list_mutex);
1395 WARN_ON(fs_devices->open_devices);
1396 WARN_ON(fs_devices->rw_devices);
1397 fs_devices->opened = 0;
1398 fs_devices->seeding = 0;
1403 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1405 struct btrfs_fs_devices *seed_devices = NULL;
1408 mutex_lock(&uuid_mutex);
1409 ret = close_fs_devices(fs_devices);
1410 if (!fs_devices->opened) {
1411 seed_devices = fs_devices->seed;
1412 fs_devices->seed = NULL;
1415 * If the struct btrfs_fs_devices is not assembled with any
1416 * other device, it can be re-initialized during the next mount
1417 * without the needing device-scan step. Therefore, it can be
1420 if (fs_devices->num_devices == 1) {
1421 list_del(&fs_devices->fs_list);
1422 free_fs_devices(fs_devices);
1425 mutex_unlock(&uuid_mutex);
1427 while (seed_devices) {
1428 fs_devices = seed_devices;
1429 seed_devices = fs_devices->seed;
1430 close_fs_devices(fs_devices);
1431 free_fs_devices(fs_devices);
1436 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1437 fmode_t flags, void *holder)
1439 struct btrfs_device *device;
1440 struct btrfs_device *latest_dev = NULL;
1443 flags |= FMODE_EXCL;
1445 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1446 /* Just open everything we can; ignore failures here */
1447 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1451 device->generation > latest_dev->generation)
1452 latest_dev = device;
1454 if (fs_devices->open_devices == 0) {
1458 fs_devices->opened = 1;
1459 fs_devices->latest_bdev = latest_dev->bdev;
1460 fs_devices->total_rw_bytes = 0;
1465 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1467 struct btrfs_device *dev1, *dev2;
1469 dev1 = list_entry(a, struct btrfs_device, dev_list);
1470 dev2 = list_entry(b, struct btrfs_device, dev_list);
1472 if (dev1->devid < dev2->devid)
1474 else if (dev1->devid > dev2->devid)
1479 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1480 fmode_t flags, void *holder)
1484 lockdep_assert_held(&uuid_mutex);
1486 * The device_list_mutex cannot be taken here in case opening the
1487 * underlying device takes further locks like bd_mutex.
1489 * We also don't need the lock here as this is called during mount and
1490 * exclusion is provided by uuid_mutex
1493 if (fs_devices->opened) {
1494 fs_devices->opened++;
1497 list_sort(NULL, &fs_devices->devices, devid_cmp);
1498 ret = open_fs_devices(fs_devices, flags, holder);
1504 static void btrfs_release_disk_super(struct page *page)
1510 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1512 struct btrfs_super_block **disk_super)
1517 /* make sure our super fits in the device */
1518 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1521 /* make sure our super fits in the page */
1522 if (sizeof(**disk_super) > PAGE_SIZE)
1525 /* make sure our super doesn't straddle pages on disk */
1526 index = bytenr >> PAGE_SHIFT;
1527 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1530 /* pull in the page with our super */
1531 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1534 if (IS_ERR_OR_NULL(*page))
1539 /* align our pointer to the offset of the super block */
1540 *disk_super = p + offset_in_page(bytenr);
1542 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1543 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1544 btrfs_release_disk_super(*page);
1548 if ((*disk_super)->label[0] &&
1549 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1550 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1555 int btrfs_forget_devices(const char *path)
1559 mutex_lock(&uuid_mutex);
1560 ret = btrfs_free_stale_devices(strlen(path) ? path : NULL, NULL);
1561 mutex_unlock(&uuid_mutex);
1567 * Look for a btrfs signature on a device. This may be called out of the mount path
1568 * and we are not allowed to call set_blocksize during the scan. The superblock
1569 * is read via pagecache
1571 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1574 struct btrfs_super_block *disk_super;
1575 bool new_device_added = false;
1576 struct btrfs_device *device = NULL;
1577 struct block_device *bdev;
1581 lockdep_assert_held(&uuid_mutex);
1584 * we would like to check all the supers, but that would make
1585 * a btrfs mount succeed after a mkfs from a different FS.
1586 * So, we need to add a special mount option to scan for
1587 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1589 bytenr = btrfs_sb_offset(0);
1592 * Avoid using flag |= FMODE_EXCL here, as the systemd-udev may
1593 * initiate the device scan which may race with the user's mount
1594 * or mkfs command, resulting in failure.
1595 * Since the device scan is solely for reading purposes, there is
1596 * no need for FMODE_EXCL. Additionally, the devices are read again
1597 * during the mount process. It is ok to get some inconsistent
1598 * values temporarily, as the device paths of the fsid are the only
1599 * required information for assembling the volume.
1601 bdev = blkdev_get_by_path(path, flags, holder);
1603 return ERR_CAST(bdev);
1605 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1606 device = ERR_PTR(-EINVAL);
1607 goto error_bdev_put;
1610 device = device_list_add(path, disk_super, &new_device_added);
1611 if (!IS_ERR(device)) {
1612 if (new_device_added)
1613 btrfs_free_stale_devices(path, device);
1616 btrfs_release_disk_super(page);
1619 blkdev_put(bdev, flags);
1625 * Try to find a chunk that intersects [start, start + len] range and when one
1626 * such is found, record the end of it in *start
1628 static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1631 u64 physical_start, physical_end;
1633 lockdep_assert_held(&device->fs_info->chunk_mutex);
1635 if (!find_first_extent_bit(&device->alloc_state, *start,
1636 &physical_start, &physical_end,
1637 CHUNK_ALLOCATED, NULL)) {
1639 if (in_range(physical_start, *start, len) ||
1640 in_range(*start, physical_start,
1641 physical_end - physical_start)) {
1642 *start = physical_end + 1;
1651 * find_free_dev_extent_start - find free space in the specified device
1652 * @device: the device which we search the free space in
1653 * @num_bytes: the size of the free space that we need
1654 * @search_start: the position from which to begin the search
1655 * @start: store the start of the free space.
1656 * @len: the size of the free space. that we find, or the size
1657 * of the max free space if we don't find suitable free space
1659 * this uses a pretty simple search, the expectation is that it is
1660 * called very infrequently and that a given device has a small number
1663 * @start is used to store the start of the free space if we find. But if we
1664 * don't find suitable free space, it will be used to store the start position
1665 * of the max free space.
1667 * @len is used to store the size of the free space that we find.
1668 * But if we don't find suitable free space, it is used to store the size of
1669 * the max free space.
1671 * NOTE: This function will search *commit* root of device tree, and does extra
1672 * check to ensure dev extents are not double allocated.
1673 * This makes the function safe to allocate dev extents but may not report
1674 * correct usable device space, as device extent freed in current transaction
1675 * is not reported as avaiable.
1677 static int find_free_dev_extent_start(struct btrfs_device *device,
1678 u64 num_bytes, u64 search_start, u64 *start,
1681 struct btrfs_fs_info *fs_info = device->fs_info;
1682 struct btrfs_root *root = fs_info->dev_root;
1683 struct btrfs_key key;
1684 struct btrfs_dev_extent *dev_extent;
1685 struct btrfs_path *path;
1690 u64 search_end = device->total_bytes;
1693 struct extent_buffer *l;
1696 * We don't want to overwrite the superblock on the drive nor any area
1697 * used by the boot loader (grub for example), so we make sure to start
1698 * at an offset of at least 1MB.
1700 search_start = max_t(u64, search_start, SZ_1M);
1702 path = btrfs_alloc_path();
1706 max_hole_start = search_start;
1710 if (search_start >= search_end ||
1711 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1716 path->reada = READA_FORWARD;
1717 path->search_commit_root = 1;
1718 path->skip_locking = 1;
1720 key.objectid = device->devid;
1721 key.offset = search_start;
1722 key.type = BTRFS_DEV_EXTENT_KEY;
1724 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1728 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1733 while (search_start < search_end) {
1735 slot = path->slots[0];
1736 if (slot >= btrfs_header_nritems(l)) {
1737 ret = btrfs_next_leaf(root, path);
1745 btrfs_item_key_to_cpu(l, &key, slot);
1747 if (key.objectid < device->devid)
1750 if (key.objectid > device->devid)
1753 if (key.type != BTRFS_DEV_EXTENT_KEY)
1756 if (key.offset > search_end)
1759 if (key.offset > search_start) {
1760 hole_size = key.offset - search_start;
1763 * Have to check before we set max_hole_start, otherwise
1764 * we could end up sending back this offset anyway.
1766 if (contains_pending_extent(device, &search_start,
1768 if (key.offset >= search_start)
1769 hole_size = key.offset - search_start;
1774 if (hole_size > max_hole_size) {
1775 max_hole_start = search_start;
1776 max_hole_size = hole_size;
1780 * If this free space is greater than which we need,
1781 * it must be the max free space that we have found
1782 * until now, so max_hole_start must point to the start
1783 * of this free space and the length of this free space
1784 * is stored in max_hole_size. Thus, we return
1785 * max_hole_start and max_hole_size and go back to the
1788 if (hole_size >= num_bytes) {
1794 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1795 extent_end = key.offset + btrfs_dev_extent_length(l,
1797 if (extent_end > search_start)
1798 search_start = extent_end;
1805 * At this point, search_start should be the end of
1806 * allocated dev extents, and when shrinking the device,
1807 * search_end may be smaller than search_start.
1809 if (search_end > search_start) {
1810 hole_size = search_end - search_start;
1812 if (contains_pending_extent(device, &search_start, hole_size)) {
1813 btrfs_release_path(path);
1817 if (hole_size > max_hole_size) {
1818 max_hole_start = search_start;
1819 max_hole_size = hole_size;
1824 if (max_hole_size < num_bytes)
1829 ASSERT(max_hole_start + max_hole_size <= search_end);
1831 btrfs_free_path(path);
1832 *start = max_hole_start;
1834 *len = max_hole_size;
1838 int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
1839 u64 *start, u64 *len)
1841 /* FIXME use last free of some kind */
1842 return find_free_dev_extent_start(device, num_bytes, 0, start, len);
1845 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1846 struct btrfs_device *device,
1847 u64 start, u64 *dev_extent_len)
1849 struct btrfs_fs_info *fs_info = device->fs_info;
1850 struct btrfs_root *root = fs_info->dev_root;
1852 struct btrfs_path *path;
1853 struct btrfs_key key;
1854 struct btrfs_key found_key;
1855 struct extent_buffer *leaf = NULL;
1856 struct btrfs_dev_extent *extent = NULL;
1858 path = btrfs_alloc_path();
1862 key.objectid = device->devid;
1864 key.type = BTRFS_DEV_EXTENT_KEY;
1866 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1868 ret = btrfs_previous_item(root, path, key.objectid,
1869 BTRFS_DEV_EXTENT_KEY);
1872 leaf = path->nodes[0];
1873 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1874 extent = btrfs_item_ptr(leaf, path->slots[0],
1875 struct btrfs_dev_extent);
1876 BUG_ON(found_key.offset > start || found_key.offset +
1877 btrfs_dev_extent_length(leaf, extent) < start);
1879 btrfs_release_path(path);
1881 } else if (ret == 0) {
1882 leaf = path->nodes[0];
1883 extent = btrfs_item_ptr(leaf, path->slots[0],
1884 struct btrfs_dev_extent);
1886 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1890 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1892 ret = btrfs_del_item(trans, root, path);
1894 btrfs_handle_fs_error(fs_info, ret,
1895 "Failed to remove dev extent item");
1897 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1900 btrfs_free_path(path);
1904 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1905 struct btrfs_device *device,
1906 u64 chunk_offset, u64 start, u64 num_bytes)
1909 struct btrfs_path *path;
1910 struct btrfs_fs_info *fs_info = device->fs_info;
1911 struct btrfs_root *root = fs_info->dev_root;
1912 struct btrfs_dev_extent *extent;
1913 struct extent_buffer *leaf;
1914 struct btrfs_key key;
1916 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1917 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1918 path = btrfs_alloc_path();
1922 key.objectid = device->devid;
1924 key.type = BTRFS_DEV_EXTENT_KEY;
1925 ret = btrfs_insert_empty_item(trans, root, path, &key,
1930 leaf = path->nodes[0];
1931 extent = btrfs_item_ptr(leaf, path->slots[0],
1932 struct btrfs_dev_extent);
1933 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1934 BTRFS_CHUNK_TREE_OBJECTID);
1935 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1936 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1937 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1939 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1940 btrfs_mark_buffer_dirty(leaf);
1942 btrfs_free_path(path);
1946 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1948 struct extent_map_tree *em_tree;
1949 struct extent_map *em;
1953 em_tree = &fs_info->mapping_tree;
1954 read_lock(&em_tree->lock);
1955 n = rb_last(&em_tree->map.rb_root);
1957 em = rb_entry(n, struct extent_map, rb_node);
1958 ret = em->start + em->len;
1960 read_unlock(&em_tree->lock);
1965 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1969 struct btrfs_key key;
1970 struct btrfs_key found_key;
1971 struct btrfs_path *path;
1973 path = btrfs_alloc_path();
1977 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1978 key.type = BTRFS_DEV_ITEM_KEY;
1979 key.offset = (u64)-1;
1981 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1987 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
1992 ret = btrfs_previous_item(fs_info->chunk_root, path,
1993 BTRFS_DEV_ITEMS_OBJECTID,
1994 BTRFS_DEV_ITEM_KEY);
1998 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2000 *devid_ret = found_key.offset + 1;
2004 btrfs_free_path(path);
2009 * the device information is stored in the chunk root
2010 * the btrfs_device struct should be fully filled in
2012 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
2013 struct btrfs_device *device)
2016 struct btrfs_path *path;
2017 struct btrfs_dev_item *dev_item;
2018 struct extent_buffer *leaf;
2019 struct btrfs_key key;
2022 path = btrfs_alloc_path();
2026 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2027 key.type = BTRFS_DEV_ITEM_KEY;
2028 key.offset = device->devid;
2030 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
2031 &key, sizeof(*dev_item));
2035 leaf = path->nodes[0];
2036 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2038 btrfs_set_device_id(leaf, dev_item, device->devid);
2039 btrfs_set_device_generation(leaf, dev_item, 0);
2040 btrfs_set_device_type(leaf, dev_item, device->type);
2041 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2042 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2043 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2044 btrfs_set_device_total_bytes(leaf, dev_item,
2045 btrfs_device_get_disk_total_bytes(device));
2046 btrfs_set_device_bytes_used(leaf, dev_item,
2047 btrfs_device_get_bytes_used(device));
2048 btrfs_set_device_group(leaf, dev_item, 0);
2049 btrfs_set_device_seek_speed(leaf, dev_item, 0);
2050 btrfs_set_device_bandwidth(leaf, dev_item, 0);
2051 btrfs_set_device_start_offset(leaf, dev_item, 0);
2053 ptr = btrfs_device_uuid(dev_item);
2054 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
2055 ptr = btrfs_device_fsid(dev_item);
2056 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
2057 ptr, BTRFS_FSID_SIZE);
2058 btrfs_mark_buffer_dirty(leaf);
2062 btrfs_free_path(path);
2067 * Function to update ctime/mtime for a given device path.
2068 * Mainly used for ctime/mtime based probe like libblkid.
2070 static void update_dev_time(const char *path_name)
2074 filp = filp_open(path_name, O_RDWR, 0);
2077 file_update_time(filp);
2078 filp_close(filp, NULL);
2081 static int btrfs_rm_dev_item(struct btrfs_device *device)
2083 struct btrfs_root *root = device->fs_info->chunk_root;
2085 struct btrfs_path *path;
2086 struct btrfs_key key;
2087 struct btrfs_trans_handle *trans;
2089 path = btrfs_alloc_path();
2093 trans = btrfs_start_transaction(root, 0);
2094 if (IS_ERR(trans)) {
2095 btrfs_free_path(path);
2096 return PTR_ERR(trans);
2098 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2099 key.type = BTRFS_DEV_ITEM_KEY;
2100 key.offset = device->devid;
2102 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2106 btrfs_abort_transaction(trans, ret);
2107 btrfs_end_transaction(trans);
2111 ret = btrfs_del_item(trans, root, path);
2113 btrfs_abort_transaction(trans, ret);
2114 btrfs_end_transaction(trans);
2118 btrfs_free_path(path);
2120 ret = btrfs_commit_transaction(trans);
2125 * Verify that @num_devices satisfies the RAID profile constraints in the whole
2126 * filesystem. It's up to the caller to adjust that number regarding eg. device
2129 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
2137 seq = read_seqbegin(&fs_info->profiles_lock);
2139 all_avail = fs_info->avail_data_alloc_bits |
2140 fs_info->avail_system_alloc_bits |
2141 fs_info->avail_metadata_alloc_bits;
2142 } while (read_seqretry(&fs_info->profiles_lock, seq));
2144 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2145 if (!(all_avail & btrfs_raid_array[i].bg_flag))
2148 if (num_devices < btrfs_raid_array[i].devs_min) {
2149 int ret = btrfs_raid_array[i].mindev_error;
2159 static struct btrfs_device * btrfs_find_next_active_device(
2160 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
2162 struct btrfs_device *next_device;
2164 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
2165 if (next_device != device &&
2166 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
2167 && next_device->bdev)
2175 * Helper function to check if the given device is part of s_bdev / latest_bdev
2176 * and replace it with the provided or the next active device, in the context
2177 * where this function called, there should be always be another device (or
2178 * this_dev) which is active.
2180 void btrfs_assign_next_active_device(struct btrfs_device *device,
2181 struct btrfs_device *this_dev)
2183 struct btrfs_fs_info *fs_info = device->fs_info;
2184 struct btrfs_device *next_device;
2187 next_device = this_dev;
2189 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
2191 ASSERT(next_device);
2193 if (fs_info->sb->s_bdev &&
2194 (fs_info->sb->s_bdev == device->bdev))
2195 fs_info->sb->s_bdev = next_device->bdev;
2197 if (fs_info->fs_devices->latest_bdev == device->bdev)
2198 fs_info->fs_devices->latest_bdev = next_device->bdev;
2202 * Return btrfs_fs_devices::num_devices excluding the device that's being
2203 * currently replaced.
2205 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
2207 u64 num_devices = fs_info->fs_devices->num_devices;
2209 down_read(&fs_info->dev_replace.rwsem);
2210 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
2211 ASSERT(num_devices > 1);
2214 up_read(&fs_info->dev_replace.rwsem);
2219 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
2222 struct btrfs_device *device;
2223 struct btrfs_fs_devices *cur_devices;
2224 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2229 * The device list in fs_devices is accessed without locks (neither
2230 * uuid_mutex nor device_list_mutex) as it won't change on a mounted
2231 * filesystem and another device rm cannot run.
2233 num_devices = btrfs_num_devices(fs_info);
2235 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2239 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
2241 if (IS_ERR(device)) {
2242 if (PTR_ERR(device) == -ENOENT &&
2243 device_path && strcmp(device_path, "missing") == 0)
2244 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2246 ret = PTR_ERR(device);
2250 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2251 btrfs_warn_in_rcu(fs_info,
2252 "cannot remove device %s (devid %llu) due to active swapfile",
2253 rcu_str_deref(device->name), device->devid);
2258 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2259 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
2263 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2264 fs_info->fs_devices->rw_devices == 1) {
2265 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
2269 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2270 mutex_lock(&fs_info->chunk_mutex);
2271 list_del_init(&device->dev_alloc_list);
2272 device->fs_devices->rw_devices--;
2273 mutex_unlock(&fs_info->chunk_mutex);
2276 ret = btrfs_shrink_device(device, 0);
2278 btrfs_reada_remove_dev(device);
2283 * TODO: the superblock still includes this device in its num_devices
2284 * counter although write_all_supers() is not locked out. This
2285 * could give a filesystem state which requires a degraded mount.
2287 ret = btrfs_rm_dev_item(device);
2291 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2292 btrfs_scrub_cancel_dev(device);
2295 * the device list mutex makes sure that we don't change
2296 * the device list while someone else is writing out all
2297 * the device supers. Whoever is writing all supers, should
2298 * lock the device list mutex before getting the number of
2299 * devices in the super block (super_copy). Conversely,
2300 * whoever updates the number of devices in the super block
2301 * (super_copy) should hold the device list mutex.
2305 * In normal cases the cur_devices == fs_devices. But in case
2306 * of deleting a seed device, the cur_devices should point to
2307 * its own fs_devices listed under the fs_devices->seed.
2309 cur_devices = device->fs_devices;
2310 mutex_lock(&fs_devices->device_list_mutex);
2311 list_del_rcu(&device->dev_list);
2313 cur_devices->num_devices--;
2314 cur_devices->total_devices--;
2315 /* Update total_devices of the parent fs_devices if it's seed */
2316 if (cur_devices != fs_devices)
2317 fs_devices->total_devices--;
2319 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2320 cur_devices->missing_devices--;
2322 btrfs_assign_next_active_device(device, NULL);
2325 cur_devices->open_devices--;
2326 /* remove sysfs entry */
2327 btrfs_sysfs_rm_device_link(fs_devices, device);
2330 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2331 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2332 mutex_unlock(&fs_devices->device_list_mutex);
2335 * at this point, the device is zero sized and detached from
2336 * the devices list. All that's left is to zero out the old
2337 * supers and free the device.
2339 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2340 btrfs_scratch_superblocks(device->bdev, device->name->str);
2342 btrfs_close_bdev(device);
2344 btrfs_free_device(device);
2346 if (cur_devices->open_devices == 0) {
2347 while (fs_devices) {
2348 if (fs_devices->seed == cur_devices) {
2349 fs_devices->seed = cur_devices->seed;
2352 fs_devices = fs_devices->seed;
2354 cur_devices->seed = NULL;
2355 close_fs_devices(cur_devices);
2356 free_fs_devices(cur_devices);
2363 btrfs_reada_undo_remove_dev(device);
2364 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2365 mutex_lock(&fs_info->chunk_mutex);
2366 list_add(&device->dev_alloc_list,
2367 &fs_devices->alloc_list);
2368 device->fs_devices->rw_devices++;
2369 mutex_unlock(&fs_info->chunk_mutex);
2374 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2376 struct btrfs_fs_devices *fs_devices;
2378 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2381 * in case of fs with no seed, srcdev->fs_devices will point
2382 * to fs_devices of fs_info. However when the dev being replaced is
2383 * a seed dev it will point to the seed's local fs_devices. In short
2384 * srcdev will have its correct fs_devices in both the cases.
2386 fs_devices = srcdev->fs_devices;
2388 list_del_rcu(&srcdev->dev_list);
2389 list_del(&srcdev->dev_alloc_list);
2390 fs_devices->num_devices--;
2391 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2392 fs_devices->missing_devices--;
2394 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2395 fs_devices->rw_devices--;
2398 fs_devices->open_devices--;
2401 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2403 struct btrfs_fs_info *fs_info = srcdev->fs_info;
2404 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2406 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2407 /* zero out the old super if it is writable */
2408 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2411 btrfs_close_bdev(srcdev);
2413 btrfs_free_device(srcdev);
2415 /* if this is no devs we rather delete the fs_devices */
2416 if (!fs_devices->num_devices) {
2417 struct btrfs_fs_devices *tmp_fs_devices;
2420 * On a mounted FS, num_devices can't be zero unless it's a
2421 * seed. In case of a seed device being replaced, the replace
2422 * target added to the sprout FS, so there will be no more
2423 * device left under the seed FS.
2425 ASSERT(fs_devices->seeding);
2427 tmp_fs_devices = fs_info->fs_devices;
2428 while (tmp_fs_devices) {
2429 if (tmp_fs_devices->seed == fs_devices) {
2430 tmp_fs_devices->seed = fs_devices->seed;
2433 tmp_fs_devices = tmp_fs_devices->seed;
2435 fs_devices->seed = NULL;
2436 close_fs_devices(fs_devices);
2437 free_fs_devices(fs_devices);
2441 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2443 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2446 mutex_lock(&fs_devices->device_list_mutex);
2448 btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2451 fs_devices->open_devices--;
2453 fs_devices->num_devices--;
2455 btrfs_assign_next_active_device(tgtdev, NULL);
2457 list_del_rcu(&tgtdev->dev_list);
2459 mutex_unlock(&fs_devices->device_list_mutex);
2462 * The update_dev_time() with in btrfs_scratch_superblocks()
2463 * may lead to a call to btrfs_show_devname() which will try
2464 * to hold device_list_mutex. And here this device
2465 * is already out of device list, so we don't have to hold
2466 * the device_list_mutex lock.
2468 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2470 btrfs_close_bdev(tgtdev);
2472 btrfs_free_device(tgtdev);
2475 static struct btrfs_device *btrfs_find_device_by_path(
2476 struct btrfs_fs_info *fs_info, const char *device_path)
2479 struct btrfs_super_block *disk_super;
2482 struct block_device *bdev;
2483 struct buffer_head *bh;
2484 struct btrfs_device *device;
2486 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2487 fs_info->bdev_holder, 0, &bdev, &bh);
2489 return ERR_PTR(ret);
2490 disk_super = (struct btrfs_super_block *)bh->b_data;
2491 devid = btrfs_stack_device_id(&disk_super->dev_item);
2492 dev_uuid = disk_super->dev_item.uuid;
2493 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2494 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2495 disk_super->metadata_uuid, true);
2497 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2498 disk_super->fsid, true);
2502 device = ERR_PTR(-ENOENT);
2503 blkdev_put(bdev, FMODE_READ);
2508 * Lookup a device given by device id, or the path if the id is 0.
2510 struct btrfs_device *btrfs_find_device_by_devspec(
2511 struct btrfs_fs_info *fs_info, u64 devid,
2512 const char *device_path)
2514 struct btrfs_device *device;
2517 device = btrfs_find_device(fs_info->fs_devices, devid, NULL,
2520 return ERR_PTR(-ENOENT);
2524 if (!device_path || !device_path[0])
2525 return ERR_PTR(-EINVAL);
2527 if (strcmp(device_path, "missing") == 0) {
2528 /* Find first missing device */
2529 list_for_each_entry(device, &fs_info->fs_devices->devices,
2531 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2532 &device->dev_state) && !device->bdev)
2535 return ERR_PTR(-ENOENT);
2538 return btrfs_find_device_by_path(fs_info, device_path);
2542 * does all the dirty work required for changing file system's UUID.
2544 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2546 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2547 struct btrfs_fs_devices *old_devices;
2548 struct btrfs_fs_devices *seed_devices;
2549 struct btrfs_super_block *disk_super = fs_info->super_copy;
2550 struct btrfs_device *device;
2553 lockdep_assert_held(&uuid_mutex);
2554 if (!fs_devices->seeding)
2557 seed_devices = alloc_fs_devices(NULL, NULL);
2558 if (IS_ERR(seed_devices))
2559 return PTR_ERR(seed_devices);
2561 old_devices = clone_fs_devices(fs_devices);
2562 if (IS_ERR(old_devices)) {
2563 kfree(seed_devices);
2564 return PTR_ERR(old_devices);
2567 list_add(&old_devices->fs_list, &fs_uuids);
2569 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2570 seed_devices->opened = 1;
2571 INIT_LIST_HEAD(&seed_devices->devices);
2572 INIT_LIST_HEAD(&seed_devices->alloc_list);
2573 mutex_init(&seed_devices->device_list_mutex);
2575 mutex_lock(&fs_devices->device_list_mutex);
2576 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2578 list_for_each_entry(device, &seed_devices->devices, dev_list)
2579 device->fs_devices = seed_devices;
2581 mutex_lock(&fs_info->chunk_mutex);
2582 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2583 mutex_unlock(&fs_info->chunk_mutex);
2585 fs_devices->seeding = 0;
2586 fs_devices->num_devices = 0;
2587 fs_devices->open_devices = 0;
2588 fs_devices->missing_devices = 0;
2589 fs_devices->rotating = 0;
2590 fs_devices->seed = seed_devices;
2592 generate_random_uuid(fs_devices->fsid);
2593 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2594 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2595 mutex_unlock(&fs_devices->device_list_mutex);
2597 super_flags = btrfs_super_flags(disk_super) &
2598 ~BTRFS_SUPER_FLAG_SEEDING;
2599 btrfs_set_super_flags(disk_super, super_flags);
2605 * Store the expected generation for seed devices in device items.
2607 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2609 struct btrfs_fs_info *fs_info = trans->fs_info;
2610 struct btrfs_root *root = fs_info->chunk_root;
2611 struct btrfs_path *path;
2612 struct extent_buffer *leaf;
2613 struct btrfs_dev_item *dev_item;
2614 struct btrfs_device *device;
2615 struct btrfs_key key;
2616 u8 fs_uuid[BTRFS_FSID_SIZE];
2617 u8 dev_uuid[BTRFS_UUID_SIZE];
2621 path = btrfs_alloc_path();
2625 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2627 key.type = BTRFS_DEV_ITEM_KEY;
2630 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2634 leaf = path->nodes[0];
2636 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2637 ret = btrfs_next_leaf(root, path);
2642 leaf = path->nodes[0];
2643 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2644 btrfs_release_path(path);
2648 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2649 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2650 key.type != BTRFS_DEV_ITEM_KEY)
2653 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2654 struct btrfs_dev_item);
2655 devid = btrfs_device_id(leaf, dev_item);
2656 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2658 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2660 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2662 BUG_ON(!device); /* Logic error */
2664 if (device->fs_devices->seeding) {
2665 btrfs_set_device_generation(leaf, dev_item,
2666 device->generation);
2667 btrfs_mark_buffer_dirty(leaf);
2675 btrfs_free_path(path);
2679 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2681 struct btrfs_root *root = fs_info->dev_root;
2682 struct request_queue *q;
2683 struct btrfs_trans_handle *trans;
2684 struct btrfs_device *device;
2685 struct block_device *bdev;
2686 struct super_block *sb = fs_info->sb;
2687 struct rcu_string *name;
2688 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2689 u64 orig_super_total_bytes;
2690 u64 orig_super_num_devices;
2691 int seeding_dev = 0;
2693 bool unlocked = false;
2695 if (sb_rdonly(sb) && !fs_devices->seeding)
2698 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2699 fs_info->bdev_holder);
2701 return PTR_ERR(bdev);
2703 if (fs_devices->seeding) {
2705 down_write(&sb->s_umount);
2706 mutex_lock(&uuid_mutex);
2709 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2711 mutex_lock(&fs_devices->device_list_mutex);
2712 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2713 if (device->bdev == bdev) {
2716 &fs_devices->device_list_mutex);
2720 mutex_unlock(&fs_devices->device_list_mutex);
2722 device = btrfs_alloc_device(fs_info, NULL, NULL);
2723 if (IS_ERR(device)) {
2724 /* we can safely leave the fs_devices entry around */
2725 ret = PTR_ERR(device);
2729 name = rcu_string_strdup(device_path, GFP_KERNEL);
2732 goto error_free_device;
2734 rcu_assign_pointer(device->name, name);
2736 trans = btrfs_start_transaction(root, 0);
2737 if (IS_ERR(trans)) {
2738 ret = PTR_ERR(trans);
2739 goto error_free_device;
2742 q = bdev_get_queue(bdev);
2743 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2744 device->generation = trans->transid;
2745 device->io_width = fs_info->sectorsize;
2746 device->io_align = fs_info->sectorsize;
2747 device->sector_size = fs_info->sectorsize;
2748 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2749 fs_info->sectorsize);
2750 device->disk_total_bytes = device->total_bytes;
2751 device->commit_total_bytes = device->total_bytes;
2752 device->fs_info = fs_info;
2753 device->bdev = bdev;
2754 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2755 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2756 device->mode = FMODE_EXCL;
2757 device->dev_stats_valid = 1;
2758 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2761 sb->s_flags &= ~SB_RDONLY;
2762 ret = btrfs_prepare_sprout(fs_info);
2764 btrfs_abort_transaction(trans, ret);
2769 device->fs_devices = fs_devices;
2771 mutex_lock(&fs_devices->device_list_mutex);
2772 mutex_lock(&fs_info->chunk_mutex);
2773 list_add_rcu(&device->dev_list, &fs_devices->devices);
2774 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2775 fs_devices->num_devices++;
2776 fs_devices->open_devices++;
2777 fs_devices->rw_devices++;
2778 fs_devices->total_devices++;
2779 fs_devices->total_rw_bytes += device->total_bytes;
2781 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2783 if (!blk_queue_nonrot(q))
2784 fs_devices->rotating = 1;
2786 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2787 btrfs_set_super_total_bytes(fs_info->super_copy,
2788 round_down(orig_super_total_bytes + device->total_bytes,
2789 fs_info->sectorsize));
2791 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2792 btrfs_set_super_num_devices(fs_info->super_copy,
2793 orig_super_num_devices + 1);
2796 * we've got more storage, clear any full flags on the space
2799 btrfs_clear_space_info_full(fs_info);
2801 mutex_unlock(&fs_info->chunk_mutex);
2803 /* Add sysfs device entry */
2804 btrfs_sysfs_add_device_link(fs_devices, device);
2806 mutex_unlock(&fs_devices->device_list_mutex);
2809 mutex_lock(&fs_info->chunk_mutex);
2810 ret = init_first_rw_device(trans);
2811 mutex_unlock(&fs_info->chunk_mutex);
2813 btrfs_abort_transaction(trans, ret);
2818 ret = btrfs_add_dev_item(trans, device);
2820 btrfs_abort_transaction(trans, ret);
2825 ret = btrfs_finish_sprout(trans);
2827 btrfs_abort_transaction(trans, ret);
2831 btrfs_sysfs_update_sprout_fsid(fs_devices,
2832 fs_info->fs_devices->fsid);
2835 ret = btrfs_commit_transaction(trans);
2838 mutex_unlock(&uuid_mutex);
2839 up_write(&sb->s_umount);
2842 if (ret) /* transaction commit */
2845 ret = btrfs_relocate_sys_chunks(fs_info);
2847 btrfs_handle_fs_error(fs_info, ret,
2848 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2849 trans = btrfs_attach_transaction(root);
2850 if (IS_ERR(trans)) {
2851 if (PTR_ERR(trans) == -ENOENT)
2853 ret = PTR_ERR(trans);
2857 ret = btrfs_commit_transaction(trans);
2861 * Now that we have written a new super block to this device, check all
2862 * other fs_devices list if device_path alienates any other scanned
2864 * We can ignore the return value as it typically returns -EINVAL and
2865 * only succeeds if the device was an alien.
2867 btrfs_forget_devices(device_path);
2869 /* Update ctime/mtime for blkid or udev */
2870 update_dev_time(device_path);
2875 btrfs_sysfs_rm_device_link(fs_devices, device);
2876 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2877 mutex_lock(&fs_info->chunk_mutex);
2878 list_del_rcu(&device->dev_list);
2879 list_del(&device->dev_alloc_list);
2880 fs_info->fs_devices->num_devices--;
2881 fs_info->fs_devices->open_devices--;
2882 fs_info->fs_devices->rw_devices--;
2883 fs_info->fs_devices->total_devices--;
2884 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2885 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2886 btrfs_set_super_total_bytes(fs_info->super_copy,
2887 orig_super_total_bytes);
2888 btrfs_set_super_num_devices(fs_info->super_copy,
2889 orig_super_num_devices);
2890 mutex_unlock(&fs_info->chunk_mutex);
2891 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2894 sb->s_flags |= SB_RDONLY;
2896 btrfs_end_transaction(trans);
2898 btrfs_free_device(device);
2900 blkdev_put(bdev, FMODE_EXCL);
2901 if (seeding_dev && !unlocked) {
2902 mutex_unlock(&uuid_mutex);
2903 up_write(&sb->s_umount);
2908 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2909 struct btrfs_device *device)
2912 struct btrfs_path *path;
2913 struct btrfs_root *root = device->fs_info->chunk_root;
2914 struct btrfs_dev_item *dev_item;
2915 struct extent_buffer *leaf;
2916 struct btrfs_key key;
2918 path = btrfs_alloc_path();
2922 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2923 key.type = BTRFS_DEV_ITEM_KEY;
2924 key.offset = device->devid;
2926 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2935 leaf = path->nodes[0];
2936 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2938 btrfs_set_device_id(leaf, dev_item, device->devid);
2939 btrfs_set_device_type(leaf, dev_item, device->type);
2940 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2941 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2942 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2943 btrfs_set_device_total_bytes(leaf, dev_item,
2944 btrfs_device_get_disk_total_bytes(device));
2945 btrfs_set_device_bytes_used(leaf, dev_item,
2946 btrfs_device_get_bytes_used(device));
2947 btrfs_mark_buffer_dirty(leaf);
2950 btrfs_free_path(path);
2954 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2955 struct btrfs_device *device, u64 new_size)
2957 struct btrfs_fs_info *fs_info = device->fs_info;
2958 struct btrfs_super_block *super_copy = fs_info->super_copy;
2962 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2965 new_size = round_down(new_size, fs_info->sectorsize);
2967 mutex_lock(&fs_info->chunk_mutex);
2968 old_total = btrfs_super_total_bytes(super_copy);
2969 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2971 if (new_size <= device->total_bytes ||
2972 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2973 mutex_unlock(&fs_info->chunk_mutex);
2977 btrfs_set_super_total_bytes(super_copy,
2978 round_down(old_total + diff, fs_info->sectorsize));
2979 device->fs_devices->total_rw_bytes += diff;
2981 btrfs_device_set_total_bytes(device, new_size);
2982 btrfs_device_set_disk_total_bytes(device, new_size);
2983 btrfs_clear_space_info_full(device->fs_info);
2984 if (list_empty(&device->post_commit_list))
2985 list_add_tail(&device->post_commit_list,
2986 &trans->transaction->dev_update_list);
2987 mutex_unlock(&fs_info->chunk_mutex);
2989 return btrfs_update_device(trans, device);
2992 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2994 struct btrfs_fs_info *fs_info = trans->fs_info;
2995 struct btrfs_root *root = fs_info->chunk_root;
2997 struct btrfs_path *path;
2998 struct btrfs_key key;
3000 path = btrfs_alloc_path();
3004 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3005 key.offset = chunk_offset;
3006 key.type = BTRFS_CHUNK_ITEM_KEY;
3008 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3011 else if (ret > 0) { /* Logic error or corruption */
3012 btrfs_handle_fs_error(fs_info, -ENOENT,
3013 "Failed lookup while freeing chunk.");
3018 ret = btrfs_del_item(trans, root, path);
3020 btrfs_handle_fs_error(fs_info, ret,
3021 "Failed to delete chunk item.");
3023 btrfs_free_path(path);
3027 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3029 struct btrfs_super_block *super_copy = fs_info->super_copy;
3030 struct btrfs_disk_key *disk_key;
3031 struct btrfs_chunk *chunk;
3038 struct btrfs_key key;
3040 mutex_lock(&fs_info->chunk_mutex);
3041 array_size = btrfs_super_sys_array_size(super_copy);
3043 ptr = super_copy->sys_chunk_array;
3046 while (cur < array_size) {
3047 disk_key = (struct btrfs_disk_key *)ptr;
3048 btrfs_disk_key_to_cpu(&key, disk_key);
3050 len = sizeof(*disk_key);
3052 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
3053 chunk = (struct btrfs_chunk *)(ptr + len);
3054 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
3055 len += btrfs_chunk_item_size(num_stripes);
3060 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
3061 key.offset == chunk_offset) {
3062 memmove(ptr, ptr + len, array_size - (cur + len));
3064 btrfs_set_super_sys_array_size(super_copy, array_size);
3070 mutex_unlock(&fs_info->chunk_mutex);
3075 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
3076 * @logical: Logical block offset in bytes.
3077 * @length: Length of extent in bytes.
3079 * Return: Chunk mapping or ERR_PTR.
3081 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
3082 u64 logical, u64 length)
3084 struct extent_map_tree *em_tree;
3085 struct extent_map *em;
3087 em_tree = &fs_info->mapping_tree;
3088 read_lock(&em_tree->lock);
3089 em = lookup_extent_mapping(em_tree, logical, length);
3090 read_unlock(&em_tree->lock);
3093 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
3095 return ERR_PTR(-EINVAL);
3098 if (em->start > logical || em->start + em->len < logical) {
3100 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
3101 logical, length, em->start, em->start + em->len);
3102 free_extent_map(em);
3103 return ERR_PTR(-EINVAL);
3106 /* callers are responsible for dropping em's ref. */
3110 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3112 struct btrfs_fs_info *fs_info = trans->fs_info;
3113 struct extent_map *em;
3114 struct map_lookup *map;
3115 u64 dev_extent_len = 0;
3117 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3119 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
3122 * This is a logic error, but we don't want to just rely on the
3123 * user having built with ASSERT enabled, so if ASSERT doesn't
3124 * do anything we still error out.
3129 map = em->map_lookup;
3130 mutex_lock(&fs_info->chunk_mutex);
3131 check_system_chunk(trans, map->type);
3132 mutex_unlock(&fs_info->chunk_mutex);
3135 * Take the device list mutex to prevent races with the final phase of
3136 * a device replace operation that replaces the device object associated
3137 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
3139 mutex_lock(&fs_devices->device_list_mutex);
3140 for (i = 0; i < map->num_stripes; i++) {
3141 struct btrfs_device *device = map->stripes[i].dev;
3142 ret = btrfs_free_dev_extent(trans, device,
3143 map->stripes[i].physical,
3146 mutex_unlock(&fs_devices->device_list_mutex);
3147 btrfs_abort_transaction(trans, ret);
3151 if (device->bytes_used > 0) {
3152 mutex_lock(&fs_info->chunk_mutex);
3153 btrfs_device_set_bytes_used(device,
3154 device->bytes_used - dev_extent_len);
3155 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3156 btrfs_clear_space_info_full(fs_info);
3157 mutex_unlock(&fs_info->chunk_mutex);
3160 ret = btrfs_update_device(trans, device);
3162 mutex_unlock(&fs_devices->device_list_mutex);
3163 btrfs_abort_transaction(trans, ret);
3167 mutex_unlock(&fs_devices->device_list_mutex);
3169 ret = btrfs_free_chunk(trans, chunk_offset);
3171 btrfs_abort_transaction(trans, ret);
3175 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
3177 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3178 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3180 btrfs_abort_transaction(trans, ret);
3185 ret = btrfs_remove_block_group(trans, chunk_offset, em);
3187 btrfs_abort_transaction(trans, ret);
3193 free_extent_map(em);
3197 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3199 struct btrfs_root *root = fs_info->chunk_root;
3200 struct btrfs_trans_handle *trans;
3204 * Prevent races with automatic removal of unused block groups.
3205 * After we relocate and before we remove the chunk with offset
3206 * chunk_offset, automatic removal of the block group can kick in,
3207 * resulting in a failure when calling btrfs_remove_chunk() below.
3209 * Make sure to acquire this mutex before doing a tree search (dev
3210 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3211 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3212 * we release the path used to search the chunk/dev tree and before
3213 * the current task acquires this mutex and calls us.
3215 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3217 /* step one, relocate all the extents inside this chunk */
3218 btrfs_scrub_pause(fs_info);
3219 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3220 btrfs_scrub_continue(fs_info);
3224 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3226 if (IS_ERR(trans)) {
3227 ret = PTR_ERR(trans);
3228 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3233 * step two, delete the device extents and the
3234 * chunk tree entries
3236 ret = btrfs_remove_chunk(trans, chunk_offset);
3237 btrfs_end_transaction(trans);
3241 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3243 struct btrfs_root *chunk_root = fs_info->chunk_root;
3244 struct btrfs_path *path;
3245 struct extent_buffer *leaf;
3246 struct btrfs_chunk *chunk;
3247 struct btrfs_key key;
3248 struct btrfs_key found_key;
3250 bool retried = false;
3254 path = btrfs_alloc_path();
3259 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3260 key.offset = (u64)-1;
3261 key.type = BTRFS_CHUNK_ITEM_KEY;
3264 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3265 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3267 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3270 BUG_ON(ret == 0); /* Corruption */
3272 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3275 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3281 leaf = path->nodes[0];
3282 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3284 chunk = btrfs_item_ptr(leaf, path->slots[0],
3285 struct btrfs_chunk);
3286 chunk_type = btrfs_chunk_type(leaf, chunk);
3287 btrfs_release_path(path);
3289 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3290 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3296 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3298 if (found_key.offset == 0)
3300 key.offset = found_key.offset - 1;
3303 if (failed && !retried) {
3307 } else if (WARN_ON(failed && retried)) {
3311 btrfs_free_path(path);
3316 * return 1 : allocate a data chunk successfully,
3317 * return <0: errors during allocating a data chunk,
3318 * return 0 : no need to allocate a data chunk.
3320 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3323 struct btrfs_block_group_cache *cache;
3327 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3329 chunk_type = cache->flags;
3330 btrfs_put_block_group(cache);
3332 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3333 spin_lock(&fs_info->data_sinfo->lock);
3334 bytes_used = fs_info->data_sinfo->bytes_used;
3335 spin_unlock(&fs_info->data_sinfo->lock);
3338 struct btrfs_trans_handle *trans;
3341 trans = btrfs_join_transaction(fs_info->tree_root);
3343 return PTR_ERR(trans);
3345 ret = btrfs_force_chunk_alloc(trans,
3346 BTRFS_BLOCK_GROUP_DATA);
3347 btrfs_end_transaction(trans);
3356 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3357 struct btrfs_balance_control *bctl)
3359 struct btrfs_root *root = fs_info->tree_root;
3360 struct btrfs_trans_handle *trans;
3361 struct btrfs_balance_item *item;
3362 struct btrfs_disk_balance_args disk_bargs;
3363 struct btrfs_path *path;
3364 struct extent_buffer *leaf;
3365 struct btrfs_key key;
3368 path = btrfs_alloc_path();
3372 trans = btrfs_start_transaction_fallback_global_rsv(root, 0);
3373 if (IS_ERR(trans)) {
3374 btrfs_free_path(path);
3375 return PTR_ERR(trans);
3378 key.objectid = BTRFS_BALANCE_OBJECTID;
3379 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3382 ret = btrfs_insert_empty_item(trans, root, path, &key,
3387 leaf = path->nodes[0];
3388 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3390 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3392 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3393 btrfs_set_balance_data(leaf, item, &disk_bargs);
3394 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3395 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3396 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3397 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3399 btrfs_set_balance_flags(leaf, item, bctl->flags);
3401 btrfs_mark_buffer_dirty(leaf);
3403 btrfs_free_path(path);
3404 err = btrfs_commit_transaction(trans);
3410 static int del_balance_item(struct btrfs_fs_info *fs_info)
3412 struct btrfs_root *root = fs_info->tree_root;
3413 struct btrfs_trans_handle *trans;
3414 struct btrfs_path *path;
3415 struct btrfs_key key;
3418 path = btrfs_alloc_path();
3422 trans = btrfs_start_transaction(root, 0);
3423 if (IS_ERR(trans)) {
3424 btrfs_free_path(path);
3425 return PTR_ERR(trans);
3428 key.objectid = BTRFS_BALANCE_OBJECTID;
3429 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3432 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3440 ret = btrfs_del_item(trans, root, path);
3442 btrfs_free_path(path);
3443 err = btrfs_commit_transaction(trans);
3450 * This is a heuristic used to reduce the number of chunks balanced on
3451 * resume after balance was interrupted.
3453 static void update_balance_args(struct btrfs_balance_control *bctl)
3456 * Turn on soft mode for chunk types that were being converted.
3458 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3459 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3460 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3461 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3462 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3463 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3466 * Turn on usage filter if is not already used. The idea is
3467 * that chunks that we have already balanced should be
3468 * reasonably full. Don't do it for chunks that are being
3469 * converted - that will keep us from relocating unconverted
3470 * (albeit full) chunks.
3472 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3473 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3474 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3475 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3476 bctl->data.usage = 90;
3478 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3479 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3480 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3481 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3482 bctl->sys.usage = 90;
3484 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3485 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3486 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3487 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3488 bctl->meta.usage = 90;
3493 * Clear the balance status in fs_info and delete the balance item from disk.
3495 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3497 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3500 BUG_ON(!fs_info->balance_ctl);
3502 spin_lock(&fs_info->balance_lock);
3503 fs_info->balance_ctl = NULL;
3504 spin_unlock(&fs_info->balance_lock);
3507 ret = del_balance_item(fs_info);
3509 btrfs_handle_fs_error(fs_info, ret, NULL);
3513 * Balance filters. Return 1 if chunk should be filtered out
3514 * (should not be balanced).
3516 static int chunk_profiles_filter(u64 chunk_type,
3517 struct btrfs_balance_args *bargs)
3519 chunk_type = chunk_to_extended(chunk_type) &
3520 BTRFS_EXTENDED_PROFILE_MASK;
3522 if (bargs->profiles & chunk_type)
3528 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3529 struct btrfs_balance_args *bargs)
3531 struct btrfs_block_group_cache *cache;
3533 u64 user_thresh_min;
3534 u64 user_thresh_max;
3537 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3538 chunk_used = btrfs_block_group_used(&cache->item);
3540 if (bargs->usage_min == 0)
3541 user_thresh_min = 0;
3543 user_thresh_min = div_factor_fine(cache->key.offset,
3546 if (bargs->usage_max == 0)
3547 user_thresh_max = 1;
3548 else if (bargs->usage_max > 100)
3549 user_thresh_max = cache->key.offset;
3551 user_thresh_max = div_factor_fine(cache->key.offset,
3554 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3557 btrfs_put_block_group(cache);
3561 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3562 u64 chunk_offset, struct btrfs_balance_args *bargs)
3564 struct btrfs_block_group_cache *cache;
3565 u64 chunk_used, user_thresh;
3568 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3569 chunk_used = btrfs_block_group_used(&cache->item);
3571 if (bargs->usage_min == 0)
3573 else if (bargs->usage > 100)
3574 user_thresh = cache->key.offset;
3576 user_thresh = div_factor_fine(cache->key.offset,
3579 if (chunk_used < user_thresh)
3582 btrfs_put_block_group(cache);
3586 static int chunk_devid_filter(struct extent_buffer *leaf,
3587 struct btrfs_chunk *chunk,
3588 struct btrfs_balance_args *bargs)
3590 struct btrfs_stripe *stripe;
3591 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3594 for (i = 0; i < num_stripes; i++) {
3595 stripe = btrfs_stripe_nr(chunk, i);
3596 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3603 static u64 calc_data_stripes(u64 type, int num_stripes)
3605 const int index = btrfs_bg_flags_to_raid_index(type);
3606 const int ncopies = btrfs_raid_array[index].ncopies;
3607 const int nparity = btrfs_raid_array[index].nparity;
3610 return num_stripes - nparity;
3612 return num_stripes / ncopies;
3615 /* [pstart, pend) */
3616 static int chunk_drange_filter(struct extent_buffer *leaf,
3617 struct btrfs_chunk *chunk,
3618 struct btrfs_balance_args *bargs)
3620 struct btrfs_stripe *stripe;
3621 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3628 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3631 type = btrfs_chunk_type(leaf, chunk);
3632 factor = calc_data_stripes(type, num_stripes);
3634 for (i = 0; i < num_stripes; i++) {
3635 stripe = btrfs_stripe_nr(chunk, i);
3636 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3639 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3640 stripe_length = btrfs_chunk_length(leaf, chunk);
3641 stripe_length = div_u64(stripe_length, factor);
3643 if (stripe_offset < bargs->pend &&
3644 stripe_offset + stripe_length > bargs->pstart)
3651 /* [vstart, vend) */
3652 static int chunk_vrange_filter(struct extent_buffer *leaf,
3653 struct btrfs_chunk *chunk,
3655 struct btrfs_balance_args *bargs)
3657 if (chunk_offset < bargs->vend &&
3658 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3659 /* at least part of the chunk is inside this vrange */
3665 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3666 struct btrfs_chunk *chunk,
3667 struct btrfs_balance_args *bargs)
3669 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3671 if (bargs->stripes_min <= num_stripes
3672 && num_stripes <= bargs->stripes_max)
3678 static int chunk_soft_convert_filter(u64 chunk_type,
3679 struct btrfs_balance_args *bargs)
3681 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3684 chunk_type = chunk_to_extended(chunk_type) &
3685 BTRFS_EXTENDED_PROFILE_MASK;
3687 if (bargs->target == chunk_type)
3693 static int should_balance_chunk(struct extent_buffer *leaf,
3694 struct btrfs_chunk *chunk, u64 chunk_offset)
3696 struct btrfs_fs_info *fs_info = leaf->fs_info;
3697 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3698 struct btrfs_balance_args *bargs = NULL;
3699 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3702 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3703 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3707 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3708 bargs = &bctl->data;
3709 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3711 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3712 bargs = &bctl->meta;
3714 /* profiles filter */
3715 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3716 chunk_profiles_filter(chunk_type, bargs)) {
3721 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3722 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3724 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3725 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3730 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3731 chunk_devid_filter(leaf, chunk, bargs)) {
3735 /* drange filter, makes sense only with devid filter */
3736 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3737 chunk_drange_filter(leaf, chunk, bargs)) {
3742 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3743 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3747 /* stripes filter */
3748 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3749 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3753 /* soft profile changing mode */
3754 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3755 chunk_soft_convert_filter(chunk_type, bargs)) {
3760 * limited by count, must be the last filter
3762 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3763 if (bargs->limit == 0)
3767 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3769 * Same logic as the 'limit' filter; the minimum cannot be
3770 * determined here because we do not have the global information
3771 * about the count of all chunks that satisfy the filters.
3773 if (bargs->limit_max == 0)
3782 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3784 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3785 struct btrfs_root *chunk_root = fs_info->chunk_root;
3787 struct btrfs_chunk *chunk;
3788 struct btrfs_path *path = NULL;
3789 struct btrfs_key key;
3790 struct btrfs_key found_key;
3791 struct extent_buffer *leaf;
3794 int enospc_errors = 0;
3795 bool counting = true;
3796 /* The single value limit and min/max limits use the same bytes in the */
3797 u64 limit_data = bctl->data.limit;
3798 u64 limit_meta = bctl->meta.limit;
3799 u64 limit_sys = bctl->sys.limit;
3803 int chunk_reserved = 0;
3805 path = btrfs_alloc_path();
3811 /* zero out stat counters */
3812 spin_lock(&fs_info->balance_lock);
3813 memset(&bctl->stat, 0, sizeof(bctl->stat));
3814 spin_unlock(&fs_info->balance_lock);
3818 * The single value limit and min/max limits use the same bytes
3821 bctl->data.limit = limit_data;
3822 bctl->meta.limit = limit_meta;
3823 bctl->sys.limit = limit_sys;
3825 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3826 key.offset = (u64)-1;
3827 key.type = BTRFS_CHUNK_ITEM_KEY;
3830 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3831 atomic_read(&fs_info->balance_cancel_req)) {
3836 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3837 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3839 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3844 * this shouldn't happen, it means the last relocate
3848 BUG(); /* FIXME break ? */
3850 ret = btrfs_previous_item(chunk_root, path, 0,
3851 BTRFS_CHUNK_ITEM_KEY);
3853 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3858 leaf = path->nodes[0];
3859 slot = path->slots[0];
3860 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3862 if (found_key.objectid != key.objectid) {
3863 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3867 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3868 chunk_type = btrfs_chunk_type(leaf, chunk);
3871 spin_lock(&fs_info->balance_lock);
3872 bctl->stat.considered++;
3873 spin_unlock(&fs_info->balance_lock);
3876 ret = should_balance_chunk(leaf, chunk, found_key.offset);
3878 btrfs_release_path(path);
3880 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3885 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3886 spin_lock(&fs_info->balance_lock);
3887 bctl->stat.expected++;
3888 spin_unlock(&fs_info->balance_lock);
3890 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3892 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3894 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3901 * Apply limit_min filter, no need to check if the LIMITS
3902 * filter is used, limit_min is 0 by default
3904 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3905 count_data < bctl->data.limit_min)
3906 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3907 count_meta < bctl->meta.limit_min)
3908 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3909 count_sys < bctl->sys.limit_min)) {
3910 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3914 if (!chunk_reserved) {
3916 * We may be relocating the only data chunk we have,
3917 * which could potentially end up with losing data's
3918 * raid profile, so lets allocate an empty one in
3921 ret = btrfs_may_alloc_data_chunk(fs_info,
3924 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3926 } else if (ret == 1) {
3931 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3932 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3933 if (ret == -ENOSPC) {
3935 } else if (ret == -ETXTBSY) {
3937 "skipping relocation of block group %llu due to active swapfile",
3943 spin_lock(&fs_info->balance_lock);
3944 bctl->stat.completed++;
3945 spin_unlock(&fs_info->balance_lock);
3948 if (found_key.offset == 0)
3950 key.offset = found_key.offset - 1;
3954 btrfs_release_path(path);
3959 btrfs_free_path(path);
3960 if (enospc_errors) {
3961 btrfs_info(fs_info, "%d enospc errors during balance",
3971 * alloc_profile_is_valid - see if a given profile is valid and reduced
3972 * @flags: profile to validate
3973 * @extended: if true @flags is treated as an extended profile
3975 static int alloc_profile_is_valid(u64 flags, int extended)
3977 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3978 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3980 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3982 /* 1) check that all other bits are zeroed */
3986 /* 2) see if profile is reduced */
3988 return !extended; /* "0" is valid for usual profiles */
3990 /* true if exactly one bit set */
3992 * Don't use is_power_of_2(unsigned long) because it won't work
3993 * for the single profile (1ULL << 48) on 32-bit CPUs.
3995 return flags != 0 && (flags & (flags - 1)) == 0;
3998 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
4000 /* cancel requested || normal exit path */
4001 return atomic_read(&fs_info->balance_cancel_req) ||
4002 (atomic_read(&fs_info->balance_pause_req) == 0 &&
4003 atomic_read(&fs_info->balance_cancel_req) == 0);
4006 /* Non-zero return value signifies invalidity */
4007 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
4010 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4011 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
4012 (bctl_arg->target & ~allowed)));
4016 * Fill @buf with textual description of balance filter flags @bargs, up to
4017 * @size_buf including the terminating null. The output may be trimmed if it
4018 * does not fit into the provided buffer.
4020 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
4024 u32 size_bp = size_buf;
4026 u64 flags = bargs->flags;
4027 char tmp_buf[128] = {'\0'};
4032 #define CHECK_APPEND_NOARG(a) \
4034 ret = snprintf(bp, size_bp, (a)); \
4035 if (ret < 0 || ret >= size_bp) \
4036 goto out_overflow; \
4041 #define CHECK_APPEND_1ARG(a, v1) \
4043 ret = snprintf(bp, size_bp, (a), (v1)); \
4044 if (ret < 0 || ret >= size_bp) \
4045 goto out_overflow; \
4050 #define CHECK_APPEND_2ARG(a, v1, v2) \
4052 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
4053 if (ret < 0 || ret >= size_bp) \
4054 goto out_overflow; \
4059 if (flags & BTRFS_BALANCE_ARGS_CONVERT)
4060 CHECK_APPEND_1ARG("convert=%s,",
4061 btrfs_bg_type_to_raid_name(bargs->target));
4063 if (flags & BTRFS_BALANCE_ARGS_SOFT)
4064 CHECK_APPEND_NOARG("soft,");
4066 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
4067 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
4069 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
4072 if (flags & BTRFS_BALANCE_ARGS_USAGE)
4073 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
4075 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
4076 CHECK_APPEND_2ARG("usage=%u..%u,",
4077 bargs->usage_min, bargs->usage_max);
4079 if (flags & BTRFS_BALANCE_ARGS_DEVID)
4080 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
4082 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
4083 CHECK_APPEND_2ARG("drange=%llu..%llu,",
4084 bargs->pstart, bargs->pend);
4086 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
4087 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
4088 bargs->vstart, bargs->vend);
4090 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
4091 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
4093 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
4094 CHECK_APPEND_2ARG("limit=%u..%u,",
4095 bargs->limit_min, bargs->limit_max);
4097 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
4098 CHECK_APPEND_2ARG("stripes=%u..%u,",
4099 bargs->stripes_min, bargs->stripes_max);
4101 #undef CHECK_APPEND_2ARG
4102 #undef CHECK_APPEND_1ARG
4103 #undef CHECK_APPEND_NOARG
4107 if (size_bp < size_buf)
4108 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
4113 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
4115 u32 size_buf = 1024;
4116 char tmp_buf[192] = {'\0'};
4119 u32 size_bp = size_buf;
4121 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4123 buf = kzalloc(size_buf, GFP_KERNEL);
4129 #define CHECK_APPEND_1ARG(a, v1) \
4131 ret = snprintf(bp, size_bp, (a), (v1)); \
4132 if (ret < 0 || ret >= size_bp) \
4133 goto out_overflow; \
4138 if (bctl->flags & BTRFS_BALANCE_FORCE)
4139 CHECK_APPEND_1ARG("%s", "-f ");
4141 if (bctl->flags & BTRFS_BALANCE_DATA) {
4142 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4143 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4146 if (bctl->flags & BTRFS_BALANCE_METADATA) {
4147 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4148 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4151 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4152 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4153 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4156 #undef CHECK_APPEND_1ARG
4160 if (size_bp < size_buf)
4161 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4162 btrfs_info(fs_info, "balance: %s %s",
4163 (bctl->flags & BTRFS_BALANCE_RESUME) ?
4164 "resume" : "start", buf);
4170 * Should be called with balance mutexe held
4172 int btrfs_balance(struct btrfs_fs_info *fs_info,
4173 struct btrfs_balance_control *bctl,
4174 struct btrfs_ioctl_balance_args *bargs)
4176 u64 meta_target, data_target;
4182 bool reducing_integrity;
4185 if (btrfs_fs_closing(fs_info) ||
4186 atomic_read(&fs_info->balance_pause_req) ||
4187 atomic_read(&fs_info->balance_cancel_req)) {
4192 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4193 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4197 * In case of mixed groups both data and meta should be picked,
4198 * and identical options should be given for both of them.
4200 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4201 if (mixed && (bctl->flags & allowed)) {
4202 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4203 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4204 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4206 "balance: mixed groups data and metadata options must be the same");
4213 * rw_devices will not change at the moment, device add/delete/replace
4214 * are excluded by EXCL_OP
4216 num_devices = fs_info->fs_devices->rw_devices;
4219 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4220 * special bit for it, to make it easier to distinguish. Thus we need
4221 * to set it manually, or balance would refuse the profile.
4223 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
4224 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4225 if (num_devices >= btrfs_raid_array[i].devs_min)
4226 allowed |= btrfs_raid_array[i].bg_flag;
4228 if (validate_convert_profile(&bctl->data, allowed)) {
4230 "balance: invalid convert data profile %s",
4231 btrfs_bg_type_to_raid_name(bctl->data.target));
4235 if (validate_convert_profile(&bctl->meta, allowed)) {
4237 "balance: invalid convert metadata profile %s",
4238 btrfs_bg_type_to_raid_name(bctl->meta.target));
4242 if (validate_convert_profile(&bctl->sys, allowed)) {
4244 "balance: invalid convert system profile %s",
4245 btrfs_bg_type_to_raid_name(bctl->sys.target));
4251 * Allow to reduce metadata or system integrity only if force set for
4252 * profiles with redundancy (copies, parity)
4255 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4256 if (btrfs_raid_array[i].ncopies >= 2 ||
4257 btrfs_raid_array[i].tolerated_failures >= 1)
4258 allowed |= btrfs_raid_array[i].bg_flag;
4261 seq = read_seqbegin(&fs_info->profiles_lock);
4263 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4264 (fs_info->avail_system_alloc_bits & allowed) &&
4265 !(bctl->sys.target & allowed)) ||
4266 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4267 (fs_info->avail_metadata_alloc_bits & allowed) &&
4268 !(bctl->meta.target & allowed)))
4269 reducing_integrity = true;
4271 reducing_integrity = false;
4273 /* if we're not converting, the target field is uninitialized */
4274 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4275 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4276 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4277 bctl->data.target : fs_info->avail_data_alloc_bits;
4278 } while (read_seqretry(&fs_info->profiles_lock, seq));
4280 if (reducing_integrity) {
4281 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4283 "balance: force reducing metadata integrity");
4286 "balance: reduces metadata integrity, use --force if you want this");
4292 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4293 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4295 "balance: metadata profile %s has lower redundancy than data profile %s",
4296 btrfs_bg_type_to_raid_name(meta_target),
4297 btrfs_bg_type_to_raid_name(data_target));
4300 if (fs_info->send_in_progress) {
4301 btrfs_warn_rl(fs_info,
4302 "cannot run balance while send operations are in progress (%d in progress)",
4303 fs_info->send_in_progress);
4308 ret = insert_balance_item(fs_info, bctl);
4309 if (ret && ret != -EEXIST)
4312 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4313 BUG_ON(ret == -EEXIST);
4314 BUG_ON(fs_info->balance_ctl);
4315 spin_lock(&fs_info->balance_lock);
4316 fs_info->balance_ctl = bctl;
4317 spin_unlock(&fs_info->balance_lock);
4319 BUG_ON(ret != -EEXIST);
4320 spin_lock(&fs_info->balance_lock);
4321 update_balance_args(bctl);
4322 spin_unlock(&fs_info->balance_lock);
4325 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4326 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4327 describe_balance_start_or_resume(fs_info);
4328 mutex_unlock(&fs_info->balance_mutex);
4330 ret = __btrfs_balance(fs_info);
4332 mutex_lock(&fs_info->balance_mutex);
4333 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req))
4334 btrfs_info(fs_info, "balance: paused");
4336 * Balance can be canceled by:
4338 * - Regular cancel request
4339 * Then ret == -ECANCELED and balance_cancel_req > 0
4341 * - Fatal signal to "btrfs" process
4342 * Either the signal caught by wait_reserve_ticket() and callers
4343 * got -EINTR, or caught by btrfs_should_cancel_balance() and
4345 * Either way, in this case balance_cancel_req = 0, and
4346 * ret == -EINTR or ret == -ECANCELED.
4348 * So here we only check the return value to catch canceled balance.
4350 else if (ret == -ECANCELED || ret == -EINTR)
4351 btrfs_info(fs_info, "balance: canceled");
4353 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4355 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4358 memset(bargs, 0, sizeof(*bargs));
4359 btrfs_update_ioctl_balance_args(fs_info, bargs);
4362 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4363 balance_need_close(fs_info)) {
4364 reset_balance_state(fs_info);
4365 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4368 wake_up(&fs_info->balance_wait_q);
4372 if (bctl->flags & BTRFS_BALANCE_RESUME)
4373 reset_balance_state(fs_info);
4376 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4381 static int balance_kthread(void *data)
4383 struct btrfs_fs_info *fs_info = data;
4386 sb_start_write(fs_info->sb);
4387 mutex_lock(&fs_info->balance_mutex);
4388 if (fs_info->balance_ctl)
4389 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4390 mutex_unlock(&fs_info->balance_mutex);
4391 sb_end_write(fs_info->sb);
4396 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4398 struct task_struct *tsk;
4400 mutex_lock(&fs_info->balance_mutex);
4401 if (!fs_info->balance_ctl) {
4402 mutex_unlock(&fs_info->balance_mutex);
4405 mutex_unlock(&fs_info->balance_mutex);
4407 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4408 btrfs_info(fs_info, "balance: resume skipped");
4413 * A ro->rw remount sequence should continue with the paused balance
4414 * regardless of who pauses it, system or the user as of now, so set
4417 spin_lock(&fs_info->balance_lock);
4418 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4419 spin_unlock(&fs_info->balance_lock);
4421 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4422 return PTR_ERR_OR_ZERO(tsk);
4425 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4427 struct btrfs_balance_control *bctl;
4428 struct btrfs_balance_item *item;
4429 struct btrfs_disk_balance_args disk_bargs;
4430 struct btrfs_path *path;
4431 struct extent_buffer *leaf;
4432 struct btrfs_key key;
4435 path = btrfs_alloc_path();
4439 key.objectid = BTRFS_BALANCE_OBJECTID;
4440 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4443 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4446 if (ret > 0) { /* ret = -ENOENT; */
4451 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4457 leaf = path->nodes[0];
4458 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4460 bctl->flags = btrfs_balance_flags(leaf, item);
4461 bctl->flags |= BTRFS_BALANCE_RESUME;
4463 btrfs_balance_data(leaf, item, &disk_bargs);
4464 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4465 btrfs_balance_meta(leaf, item, &disk_bargs);
4466 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4467 btrfs_balance_sys(leaf, item, &disk_bargs);
4468 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4471 * This should never happen, as the paused balance state is recovered
4472 * during mount without any chance of other exclusive ops to collide.
4474 * This gives the exclusive op status to balance and keeps in paused
4475 * state until user intervention (cancel or umount). If the ownership
4476 * cannot be assigned, show a message but do not fail. The balance
4477 * is in a paused state and must have fs_info::balance_ctl properly
4480 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
4482 "balance: cannot set exclusive op status, resume manually");
4484 btrfs_release_path(path);
4486 mutex_lock(&fs_info->balance_mutex);
4487 BUG_ON(fs_info->balance_ctl);
4488 spin_lock(&fs_info->balance_lock);
4489 fs_info->balance_ctl = bctl;
4490 spin_unlock(&fs_info->balance_lock);
4491 mutex_unlock(&fs_info->balance_mutex);
4493 btrfs_free_path(path);
4497 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4501 mutex_lock(&fs_info->balance_mutex);
4502 if (!fs_info->balance_ctl) {
4503 mutex_unlock(&fs_info->balance_mutex);
4507 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4508 atomic_inc(&fs_info->balance_pause_req);
4509 mutex_unlock(&fs_info->balance_mutex);
4511 wait_event(fs_info->balance_wait_q,
4512 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4514 mutex_lock(&fs_info->balance_mutex);
4515 /* we are good with balance_ctl ripped off from under us */
4516 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4517 atomic_dec(&fs_info->balance_pause_req);
4522 mutex_unlock(&fs_info->balance_mutex);
4526 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4528 mutex_lock(&fs_info->balance_mutex);
4529 if (!fs_info->balance_ctl) {
4530 mutex_unlock(&fs_info->balance_mutex);
4535 * A paused balance with the item stored on disk can be resumed at
4536 * mount time if the mount is read-write. Otherwise it's still paused
4537 * and we must not allow cancelling as it deletes the item.
4539 if (sb_rdonly(fs_info->sb)) {
4540 mutex_unlock(&fs_info->balance_mutex);
4544 atomic_inc(&fs_info->balance_cancel_req);
4546 * if we are running just wait and return, balance item is
4547 * deleted in btrfs_balance in this case
4549 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4550 mutex_unlock(&fs_info->balance_mutex);
4551 wait_event(fs_info->balance_wait_q,
4552 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4553 mutex_lock(&fs_info->balance_mutex);
4555 mutex_unlock(&fs_info->balance_mutex);
4557 * Lock released to allow other waiters to continue, we'll
4558 * reexamine the status again.
4560 mutex_lock(&fs_info->balance_mutex);
4562 if (fs_info->balance_ctl) {
4563 reset_balance_state(fs_info);
4564 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4565 btrfs_info(fs_info, "balance: canceled");
4569 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4570 atomic_dec(&fs_info->balance_cancel_req);
4571 mutex_unlock(&fs_info->balance_mutex);
4575 static int btrfs_uuid_scan_kthread(void *data)
4577 struct btrfs_fs_info *fs_info = data;
4578 struct btrfs_root *root = fs_info->tree_root;
4579 struct btrfs_key key;
4580 struct btrfs_path *path = NULL;
4582 struct extent_buffer *eb;
4584 struct btrfs_root_item root_item;
4586 struct btrfs_trans_handle *trans = NULL;
4588 path = btrfs_alloc_path();
4595 key.type = BTRFS_ROOT_ITEM_KEY;
4599 ret = btrfs_search_forward(root, &key, path,
4600 BTRFS_OLDEST_GENERATION);
4607 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4608 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4609 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4610 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4613 eb = path->nodes[0];
4614 slot = path->slots[0];
4615 item_size = btrfs_item_size_nr(eb, slot);
4616 if (item_size < sizeof(root_item))
4619 read_extent_buffer(eb, &root_item,
4620 btrfs_item_ptr_offset(eb, slot),
4621 (int)sizeof(root_item));
4622 if (btrfs_root_refs(&root_item) == 0)
4625 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4626 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4630 btrfs_release_path(path);
4632 * 1 - subvol uuid item
4633 * 1 - received_subvol uuid item
4635 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4636 if (IS_ERR(trans)) {
4637 ret = PTR_ERR(trans);
4645 btrfs_release_path(path);
4646 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4647 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4648 BTRFS_UUID_KEY_SUBVOL,
4651 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4657 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4658 ret = btrfs_uuid_tree_add(trans,
4659 root_item.received_uuid,
4660 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4663 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4670 btrfs_release_path(path);
4672 ret = btrfs_end_transaction(trans);
4678 if (key.offset < (u64)-1) {
4680 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4682 key.type = BTRFS_ROOT_ITEM_KEY;
4683 } else if (key.objectid < (u64)-1) {
4685 key.type = BTRFS_ROOT_ITEM_KEY;
4694 btrfs_free_path(path);
4695 if (trans && !IS_ERR(trans))
4696 btrfs_end_transaction(trans);
4698 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4700 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4701 up(&fs_info->uuid_tree_rescan_sem);
4706 * Callback for btrfs_uuid_tree_iterate().
4708 * 0 check succeeded, the entry is not outdated.
4709 * < 0 if an error occurred.
4710 * > 0 if the check failed, which means the caller shall remove the entry.
4712 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4713 u8 *uuid, u8 type, u64 subid)
4715 struct btrfs_key key;
4717 struct btrfs_root *subvol_root;
4719 if (type != BTRFS_UUID_KEY_SUBVOL &&
4720 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4723 key.objectid = subid;
4724 key.type = BTRFS_ROOT_ITEM_KEY;
4725 key.offset = (u64)-1;
4726 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4727 if (IS_ERR(subvol_root)) {
4728 ret = PTR_ERR(subvol_root);
4735 case BTRFS_UUID_KEY_SUBVOL:
4736 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4739 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4740 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4750 static int btrfs_uuid_rescan_kthread(void *data)
4752 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4756 * 1st step is to iterate through the existing UUID tree and
4757 * to delete all entries that contain outdated data.
4758 * 2nd step is to add all missing entries to the UUID tree.
4760 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4762 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4763 up(&fs_info->uuid_tree_rescan_sem);
4766 return btrfs_uuid_scan_kthread(data);
4769 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4771 struct btrfs_trans_handle *trans;
4772 struct btrfs_root *tree_root = fs_info->tree_root;
4773 struct btrfs_root *uuid_root;
4774 struct task_struct *task;
4781 trans = btrfs_start_transaction(tree_root, 2);
4783 return PTR_ERR(trans);
4785 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
4786 if (IS_ERR(uuid_root)) {
4787 ret = PTR_ERR(uuid_root);
4788 btrfs_abort_transaction(trans, ret);
4789 btrfs_end_transaction(trans);
4793 fs_info->uuid_root = uuid_root;
4795 ret = btrfs_commit_transaction(trans);
4799 down(&fs_info->uuid_tree_rescan_sem);
4800 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4802 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4803 btrfs_warn(fs_info, "failed to start uuid_scan task");
4804 up(&fs_info->uuid_tree_rescan_sem);
4805 return PTR_ERR(task);
4811 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4813 struct task_struct *task;
4815 down(&fs_info->uuid_tree_rescan_sem);
4816 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4818 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4819 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4820 up(&fs_info->uuid_tree_rescan_sem);
4821 return PTR_ERR(task);
4828 * shrinking a device means finding all of the device extents past
4829 * the new size, and then following the back refs to the chunks.
4830 * The chunk relocation code actually frees the device extent
4832 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4834 struct btrfs_fs_info *fs_info = device->fs_info;
4835 struct btrfs_root *root = fs_info->dev_root;
4836 struct btrfs_trans_handle *trans;
4837 struct btrfs_dev_extent *dev_extent = NULL;
4838 struct btrfs_path *path;
4844 bool retried = false;
4845 struct extent_buffer *l;
4846 struct btrfs_key key;
4847 struct btrfs_super_block *super_copy = fs_info->super_copy;
4848 u64 old_total = btrfs_super_total_bytes(super_copy);
4849 u64 old_size = btrfs_device_get_total_bytes(device);
4853 new_size = round_down(new_size, fs_info->sectorsize);
4855 diff = round_down(old_size - new_size, fs_info->sectorsize);
4857 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4860 path = btrfs_alloc_path();
4864 path->reada = READA_BACK;
4866 trans = btrfs_start_transaction(root, 0);
4867 if (IS_ERR(trans)) {
4868 btrfs_free_path(path);
4869 return PTR_ERR(trans);
4872 mutex_lock(&fs_info->chunk_mutex);
4874 btrfs_device_set_total_bytes(device, new_size);
4875 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4876 device->fs_devices->total_rw_bytes -= diff;
4877 atomic64_sub(diff, &fs_info->free_chunk_space);
4881 * Once the device's size has been set to the new size, ensure all
4882 * in-memory chunks are synced to disk so that the loop below sees them
4883 * and relocates them accordingly.
4885 if (contains_pending_extent(device, &start, diff)) {
4886 mutex_unlock(&fs_info->chunk_mutex);
4887 ret = btrfs_commit_transaction(trans);
4891 mutex_unlock(&fs_info->chunk_mutex);
4892 btrfs_end_transaction(trans);
4896 key.objectid = device->devid;
4897 key.offset = (u64)-1;
4898 key.type = BTRFS_DEV_EXTENT_KEY;
4901 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4902 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4904 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4908 ret = btrfs_previous_item(root, path, 0, key.type);
4910 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4915 btrfs_release_path(path);
4920 slot = path->slots[0];
4921 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4923 if (key.objectid != device->devid) {
4924 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4925 btrfs_release_path(path);
4929 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4930 length = btrfs_dev_extent_length(l, dev_extent);
4932 if (key.offset + length <= new_size) {
4933 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4934 btrfs_release_path(path);
4938 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4939 btrfs_release_path(path);
4942 * We may be relocating the only data chunk we have,
4943 * which could potentially end up with losing data's
4944 * raid profile, so lets allocate an empty one in
4947 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4949 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4953 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4954 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4955 if (ret == -ENOSPC) {
4958 if (ret == -ETXTBSY) {
4960 "could not shrink block group %llu due to active swapfile",
4965 } while (key.offset-- > 0);
4967 if (failed && !retried) {
4971 } else if (failed && retried) {
4976 /* Shrinking succeeded, else we would be at "done". */
4977 trans = btrfs_start_transaction(root, 0);
4978 if (IS_ERR(trans)) {
4979 ret = PTR_ERR(trans);
4983 mutex_lock(&fs_info->chunk_mutex);
4984 /* Clear all state bits beyond the shrunk device size */
4985 clear_extent_bits(&device->alloc_state, new_size, (u64)-1,
4988 btrfs_device_set_disk_total_bytes(device, new_size);
4989 if (list_empty(&device->post_commit_list))
4990 list_add_tail(&device->post_commit_list,
4991 &trans->transaction->dev_update_list);
4993 WARN_ON(diff > old_total);
4994 btrfs_set_super_total_bytes(super_copy,
4995 round_down(old_total - diff, fs_info->sectorsize));
4996 mutex_unlock(&fs_info->chunk_mutex);
4998 /* Now btrfs_update_device() will change the on-disk size. */
4999 ret = btrfs_update_device(trans, device);
5001 btrfs_abort_transaction(trans, ret);
5002 btrfs_end_transaction(trans);
5004 ret = btrfs_commit_transaction(trans);
5007 btrfs_free_path(path);
5009 mutex_lock(&fs_info->chunk_mutex);
5010 btrfs_device_set_total_bytes(device, old_size);
5011 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
5012 device->fs_devices->total_rw_bytes += diff;
5013 atomic64_add(diff, &fs_info->free_chunk_space);
5014 mutex_unlock(&fs_info->chunk_mutex);
5019 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
5020 struct btrfs_key *key,
5021 struct btrfs_chunk *chunk, int item_size)
5023 struct btrfs_super_block *super_copy = fs_info->super_copy;
5024 struct btrfs_disk_key disk_key;
5028 mutex_lock(&fs_info->chunk_mutex);
5029 array_size = btrfs_super_sys_array_size(super_copy);
5030 if (array_size + item_size + sizeof(disk_key)
5031 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
5032 mutex_unlock(&fs_info->chunk_mutex);
5036 ptr = super_copy->sys_chunk_array + array_size;
5037 btrfs_cpu_key_to_disk(&disk_key, key);
5038 memcpy(ptr, &disk_key, sizeof(disk_key));
5039 ptr += sizeof(disk_key);
5040 memcpy(ptr, chunk, item_size);
5041 item_size += sizeof(disk_key);
5042 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
5043 mutex_unlock(&fs_info->chunk_mutex);
5049 * sort the devices in descending order by max_avail, total_avail
5051 static int btrfs_cmp_device_info(const void *a, const void *b)
5053 const struct btrfs_device_info *di_a = a;
5054 const struct btrfs_device_info *di_b = b;
5056 if (di_a->max_avail > di_b->max_avail)
5058 if (di_a->max_avail < di_b->max_avail)
5060 if (di_a->total_avail > di_b->total_avail)
5062 if (di_a->total_avail < di_b->total_avail)
5067 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
5069 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
5072 btrfs_set_fs_incompat(info, RAID56);
5075 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
5076 u64 start, u64 type)
5078 struct btrfs_fs_info *info = trans->fs_info;
5079 struct btrfs_fs_devices *fs_devices = info->fs_devices;
5080 struct btrfs_device *device;
5081 struct map_lookup *map = NULL;
5082 struct extent_map_tree *em_tree;
5083 struct extent_map *em;
5084 struct btrfs_device_info *devices_info = NULL;
5086 int num_stripes; /* total number of stripes to allocate */
5087 int data_stripes; /* number of stripes that count for
5089 int sub_stripes; /* sub_stripes info for map */
5090 int dev_stripes; /* stripes per dev */
5091 int devs_max; /* max devs to use */
5092 int devs_min; /* min devs needed */
5093 int devs_increment; /* ndevs has to be a multiple of this */
5094 int ncopies; /* how many copies to data has */
5095 int nparity; /* number of stripes worth of bytes to
5096 store parity information */
5098 u64 max_stripe_size;
5107 BUG_ON(!alloc_profile_is_valid(type, 0));
5109 if (list_empty(&fs_devices->alloc_list)) {
5110 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5111 btrfs_debug(info, "%s: no writable device", __func__);
5115 index = btrfs_bg_flags_to_raid_index(type);
5117 sub_stripes = btrfs_raid_array[index].sub_stripes;
5118 dev_stripes = btrfs_raid_array[index].dev_stripes;
5119 devs_max = btrfs_raid_array[index].devs_max;
5121 devs_max = BTRFS_MAX_DEVS(info);
5122 devs_min = btrfs_raid_array[index].devs_min;
5123 devs_increment = btrfs_raid_array[index].devs_increment;
5124 ncopies = btrfs_raid_array[index].ncopies;
5125 nparity = btrfs_raid_array[index].nparity;
5127 if (type & BTRFS_BLOCK_GROUP_DATA) {
5128 max_stripe_size = SZ_1G;
5129 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
5130 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5131 /* for larger filesystems, use larger metadata chunks */
5132 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
5133 max_stripe_size = SZ_1G;
5135 max_stripe_size = SZ_256M;
5136 max_chunk_size = max_stripe_size;
5137 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5138 max_stripe_size = SZ_32M;
5139 max_chunk_size = 2 * max_stripe_size;
5140 devs_max = min_t(int, devs_max, BTRFS_MAX_DEVS_SYS_CHUNK);
5142 btrfs_err(info, "invalid chunk type 0x%llx requested",
5147 /* We don't want a chunk larger than 10% of writable space */
5148 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
5151 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5157 * in the first pass through the devices list, we gather information
5158 * about the available holes on each device.
5161 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5165 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5167 "BTRFS: read-only device in alloc_list\n");
5171 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5172 &device->dev_state) ||
5173 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5176 if (device->total_bytes > device->bytes_used)
5177 total_avail = device->total_bytes - device->bytes_used;
5181 /* If there is no space on this device, skip it. */
5182 if (total_avail == 0)
5185 ret = find_free_dev_extent(device,
5186 max_stripe_size * dev_stripes,
5187 &dev_offset, &max_avail);
5188 if (ret && ret != -ENOSPC)
5192 max_avail = max_stripe_size * dev_stripes;
5194 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
5195 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5197 "%s: devid %llu has no free space, have=%llu want=%u",
5198 __func__, device->devid, max_avail,
5199 BTRFS_STRIPE_LEN * dev_stripes);
5203 if (ndevs == fs_devices->rw_devices) {
5204 WARN(1, "%s: found more than %llu devices\n",
5205 __func__, fs_devices->rw_devices);
5208 devices_info[ndevs].dev_offset = dev_offset;
5209 devices_info[ndevs].max_avail = max_avail;
5210 devices_info[ndevs].total_avail = total_avail;
5211 devices_info[ndevs].dev = device;
5216 * now sort the devices by hole size / available space
5218 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5219 btrfs_cmp_device_info, NULL);
5221 /* round down to number of usable stripes */
5222 ndevs = round_down(ndevs, devs_increment);
5224 if (ndevs < devs_min) {
5226 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5228 "%s: not enough devices with free space: have=%d minimum required=%d",
5229 __func__, ndevs, devs_min);
5234 ndevs = min(ndevs, devs_max);
5237 * The primary goal is to maximize the number of stripes, so use as
5238 * many devices as possible, even if the stripes are not maximum sized.
5240 * The DUP profile stores more than one stripe per device, the
5241 * max_avail is the total size so we have to adjust.
5243 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
5244 num_stripes = ndevs * dev_stripes;
5247 * this will have to be fixed for RAID1 and RAID10 over
5250 data_stripes = (num_stripes - nparity) / ncopies;
5253 * Use the number of data stripes to figure out how big this chunk
5254 * is really going to be in terms of logical address space,
5255 * and compare that answer with the max chunk size. If it's higher,
5256 * we try to reduce stripe_size.
5258 if (stripe_size * data_stripes > max_chunk_size) {
5260 * Reduce stripe_size, round it up to a 16MB boundary again and
5261 * then use it, unless it ends up being even bigger than the
5262 * previous value we had already.
5264 stripe_size = min(round_up(div_u64(max_chunk_size,
5265 data_stripes), SZ_16M),
5269 /* align to BTRFS_STRIPE_LEN */
5270 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
5272 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
5277 map->num_stripes = num_stripes;
5279 for (i = 0; i < ndevs; ++i) {
5280 for (j = 0; j < dev_stripes; ++j) {
5281 int s = i * dev_stripes + j;
5282 map->stripes[s].dev = devices_info[i].dev;
5283 map->stripes[s].physical = devices_info[i].dev_offset +
5287 map->stripe_len = BTRFS_STRIPE_LEN;
5288 map->io_align = BTRFS_STRIPE_LEN;
5289 map->io_width = BTRFS_STRIPE_LEN;
5291 map->sub_stripes = sub_stripes;
5293 chunk_size = stripe_size * data_stripes;
5295 trace_btrfs_chunk_alloc(info, map, start, chunk_size);
5297 em = alloc_extent_map();
5303 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5304 em->map_lookup = map;
5306 em->len = chunk_size;
5307 em->block_start = 0;
5308 em->block_len = em->len;
5309 em->orig_block_len = stripe_size;
5311 em_tree = &info->mapping_tree;
5312 write_lock(&em_tree->lock);
5313 ret = add_extent_mapping(em_tree, em, 0);
5315 write_unlock(&em_tree->lock);
5316 free_extent_map(em);
5319 write_unlock(&em_tree->lock);
5321 ret = btrfs_make_block_group(trans, 0, type, start, chunk_size);
5323 goto error_del_extent;
5325 for (i = 0; i < map->num_stripes; i++) {
5326 struct btrfs_device *dev = map->stripes[i].dev;
5328 btrfs_device_set_bytes_used(dev, dev->bytes_used + stripe_size);
5329 if (list_empty(&dev->post_commit_list))
5330 list_add_tail(&dev->post_commit_list,
5331 &trans->transaction->dev_update_list);
5334 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
5336 free_extent_map(em);
5337 check_raid56_incompat_flag(info, type);
5339 kfree(devices_info);
5343 write_lock(&em_tree->lock);
5344 remove_extent_mapping(em_tree, em);
5345 write_unlock(&em_tree->lock);
5347 /* One for our allocation */
5348 free_extent_map(em);
5349 /* One for the tree reference */
5350 free_extent_map(em);
5352 kfree(devices_info);
5356 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
5357 u64 chunk_offset, u64 chunk_size)
5359 struct btrfs_fs_info *fs_info = trans->fs_info;
5360 struct btrfs_root *extent_root = fs_info->extent_root;
5361 struct btrfs_root *chunk_root = fs_info->chunk_root;
5362 struct btrfs_key key;
5363 struct btrfs_device *device;
5364 struct btrfs_chunk *chunk;
5365 struct btrfs_stripe *stripe;
5366 struct extent_map *em;
5367 struct map_lookup *map;
5374 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
5378 map = em->map_lookup;
5379 item_size = btrfs_chunk_item_size(map->num_stripes);
5380 stripe_size = em->orig_block_len;
5382 chunk = kzalloc(item_size, GFP_NOFS);
5389 * Take the device list mutex to prevent races with the final phase of
5390 * a device replace operation that replaces the device object associated
5391 * with the map's stripes, because the device object's id can change
5392 * at any time during that final phase of the device replace operation
5393 * (dev-replace.c:btrfs_dev_replace_finishing()).
5395 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5396 for (i = 0; i < map->num_stripes; i++) {
5397 device = map->stripes[i].dev;
5398 dev_offset = map->stripes[i].physical;
5400 ret = btrfs_update_device(trans, device);
5403 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5404 dev_offset, stripe_size);
5409 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5413 stripe = &chunk->stripe;
5414 for (i = 0; i < map->num_stripes; i++) {
5415 device = map->stripes[i].dev;
5416 dev_offset = map->stripes[i].physical;
5418 btrfs_set_stack_stripe_devid(stripe, device->devid);
5419 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5420 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5423 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5425 btrfs_set_stack_chunk_length(chunk, chunk_size);
5426 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5427 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5428 btrfs_set_stack_chunk_type(chunk, map->type);
5429 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5430 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5431 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5432 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5433 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5435 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5436 key.type = BTRFS_CHUNK_ITEM_KEY;
5437 key.offset = chunk_offset;
5439 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5440 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5442 * TODO: Cleanup of inserted chunk root in case of
5445 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5450 free_extent_map(em);
5455 * Chunk allocation falls into two parts. The first part does work
5456 * that makes the new allocated chunk usable, but does not do any operation
5457 * that modifies the chunk tree. The second part does the work that
5458 * requires modifying the chunk tree. This division is important for the
5459 * bootstrap process of adding storage to a seed btrfs.
5461 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5465 lockdep_assert_held(&trans->fs_info->chunk_mutex);
5466 chunk_offset = find_next_chunk(trans->fs_info);
5467 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5470 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5472 struct btrfs_fs_info *fs_info = trans->fs_info;
5474 u64 sys_chunk_offset;
5478 chunk_offset = find_next_chunk(fs_info);
5479 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5480 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5484 sys_chunk_offset = find_next_chunk(fs_info);
5485 alloc_profile = btrfs_system_alloc_profile(fs_info);
5486 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5490 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5492 const int index = btrfs_bg_flags_to_raid_index(map->type);
5494 return btrfs_raid_array[index].tolerated_failures;
5497 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5499 struct extent_map *em;
5500 struct map_lookup *map;
5505 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5509 map = em->map_lookup;
5510 for (i = 0; i < map->num_stripes; i++) {
5511 if (test_bit(BTRFS_DEV_STATE_MISSING,
5512 &map->stripes[i].dev->dev_state)) {
5516 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5517 &map->stripes[i].dev->dev_state)) {
5524 * If the number of missing devices is larger than max errors,
5525 * we can not write the data into that chunk successfully, so
5528 if (miss_ndevs > btrfs_chunk_max_errors(map))
5531 free_extent_map(em);
5535 void btrfs_mapping_tree_free(struct extent_map_tree *tree)
5537 struct extent_map *em;
5540 write_lock(&tree->lock);
5541 em = lookup_extent_mapping(tree, 0, (u64)-1);
5543 remove_extent_mapping(tree, em);
5544 write_unlock(&tree->lock);
5548 free_extent_map(em);
5549 /* once for the tree */
5550 free_extent_map(em);
5554 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5556 struct extent_map *em;
5557 struct map_lookup *map;
5560 em = btrfs_get_chunk_map(fs_info, logical, len);
5563 * We could return errors for these cases, but that could get
5564 * ugly and we'd probably do the same thing which is just not do
5565 * anything else and exit, so return 1 so the callers don't try
5566 * to use other copies.
5570 map = em->map_lookup;
5571 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1_MASK))
5572 ret = map->num_stripes;
5573 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5574 ret = map->sub_stripes;
5575 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5577 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5579 * There could be two corrupted data stripes, we need
5580 * to loop retry in order to rebuild the correct data.
5582 * Fail a stripe at a time on every retry except the
5583 * stripe under reconstruction.
5585 ret = map->num_stripes;
5588 free_extent_map(em);
5590 down_read(&fs_info->dev_replace.rwsem);
5591 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5592 fs_info->dev_replace.tgtdev)
5594 up_read(&fs_info->dev_replace.rwsem);
5599 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5602 struct extent_map *em;
5603 struct map_lookup *map;
5604 unsigned long len = fs_info->sectorsize;
5606 em = btrfs_get_chunk_map(fs_info, logical, len);
5608 if (!WARN_ON(IS_ERR(em))) {
5609 map = em->map_lookup;
5610 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5611 len = map->stripe_len * nr_data_stripes(map);
5612 free_extent_map(em);
5617 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5619 struct extent_map *em;
5620 struct map_lookup *map;
5623 em = btrfs_get_chunk_map(fs_info, logical, len);
5625 if(!WARN_ON(IS_ERR(em))) {
5626 map = em->map_lookup;
5627 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5629 free_extent_map(em);
5634 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5635 struct map_lookup *map, int first,
5636 int dev_replace_is_ongoing)
5640 int preferred_mirror;
5642 struct btrfs_device *srcdev;
5645 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)));
5647 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5648 num_stripes = map->sub_stripes;
5650 num_stripes = map->num_stripes;
5652 preferred_mirror = first + current->pid % num_stripes;
5654 if (dev_replace_is_ongoing &&
5655 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5656 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5657 srcdev = fs_info->dev_replace.srcdev;
5662 * try to avoid the drive that is the source drive for a
5663 * dev-replace procedure, only choose it if no other non-missing
5664 * mirror is available
5666 for (tolerance = 0; tolerance < 2; tolerance++) {
5667 if (map->stripes[preferred_mirror].dev->bdev &&
5668 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5669 return preferred_mirror;
5670 for (i = first; i < first + num_stripes; i++) {
5671 if (map->stripes[i].dev->bdev &&
5672 (tolerance || map->stripes[i].dev != srcdev))
5677 /* we couldn't find one that doesn't fail. Just return something
5678 * and the io error handling code will clean up eventually
5680 return preferred_mirror;
5683 static inline int parity_smaller(u64 a, u64 b)
5688 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5689 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5691 struct btrfs_bio_stripe s;
5698 for (i = 0; i < num_stripes - 1; i++) {
5699 if (parity_smaller(bbio->raid_map[i],
5700 bbio->raid_map[i+1])) {
5701 s = bbio->stripes[i];
5702 l = bbio->raid_map[i];
5703 bbio->stripes[i] = bbio->stripes[i+1];
5704 bbio->raid_map[i] = bbio->raid_map[i+1];
5705 bbio->stripes[i+1] = s;
5706 bbio->raid_map[i+1] = l;
5714 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5716 struct btrfs_bio *bbio = kzalloc(
5717 /* the size of the btrfs_bio */
5718 sizeof(struct btrfs_bio) +
5719 /* plus the variable array for the stripes */
5720 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5721 /* plus the variable array for the tgt dev */
5722 sizeof(int) * (real_stripes) +
5724 * plus the raid_map, which includes both the tgt dev
5727 sizeof(u64) * (total_stripes),
5728 GFP_NOFS|__GFP_NOFAIL);
5730 atomic_set(&bbio->error, 0);
5731 refcount_set(&bbio->refs, 1);
5736 void btrfs_get_bbio(struct btrfs_bio *bbio)
5738 WARN_ON(!refcount_read(&bbio->refs));
5739 refcount_inc(&bbio->refs);
5742 void btrfs_put_bbio(struct btrfs_bio *bbio)
5746 if (refcount_dec_and_test(&bbio->refs))
5750 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5752 * Please note that, discard won't be sent to target device of device
5755 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5756 u64 logical, u64 *length_ret,
5757 struct btrfs_bio **bbio_ret)
5759 struct extent_map *em;
5760 struct map_lookup *map;
5761 struct btrfs_bio *bbio;
5762 u64 length = *length_ret;
5766 u64 stripe_end_offset;
5773 u32 sub_stripes = 0;
5774 u64 stripes_per_dev = 0;
5775 u32 remaining_stripes = 0;
5776 u32 last_stripe = 0;
5780 /* discard always return a bbio */
5783 em = btrfs_get_chunk_map(fs_info, logical, length);
5787 map = em->map_lookup;
5788 /* we don't discard raid56 yet */
5789 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5794 offset = logical - em->start;
5795 length = min_t(u64, em->start + em->len - logical, length);
5796 *length_ret = length;
5798 stripe_len = map->stripe_len;
5800 * stripe_nr counts the total number of stripes we have to stride
5801 * to get to this block
5803 stripe_nr = div64_u64(offset, stripe_len);
5805 /* stripe_offset is the offset of this block in its stripe */
5806 stripe_offset = offset - stripe_nr * stripe_len;
5808 stripe_nr_end = round_up(offset + length, map->stripe_len);
5809 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5810 stripe_cnt = stripe_nr_end - stripe_nr;
5811 stripe_end_offset = stripe_nr_end * map->stripe_len -
5814 * after this, stripe_nr is the number of stripes on this
5815 * device we have to walk to find the data, and stripe_index is
5816 * the number of our device in the stripe array
5820 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5821 BTRFS_BLOCK_GROUP_RAID10)) {
5822 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5825 sub_stripes = map->sub_stripes;
5827 factor = map->num_stripes / sub_stripes;
5828 num_stripes = min_t(u64, map->num_stripes,
5829 sub_stripes * stripe_cnt);
5830 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5831 stripe_index *= sub_stripes;
5832 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5833 &remaining_stripes);
5834 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5835 last_stripe *= sub_stripes;
5836 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
5837 BTRFS_BLOCK_GROUP_DUP)) {
5838 num_stripes = map->num_stripes;
5840 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5844 bbio = alloc_btrfs_bio(num_stripes, 0);
5850 for (i = 0; i < num_stripes; i++) {
5851 bbio->stripes[i].physical =
5852 map->stripes[stripe_index].physical +
5853 stripe_offset + stripe_nr * map->stripe_len;
5854 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5856 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5857 BTRFS_BLOCK_GROUP_RAID10)) {
5858 bbio->stripes[i].length = stripes_per_dev *
5861 if (i / sub_stripes < remaining_stripes)
5862 bbio->stripes[i].length +=
5866 * Special for the first stripe and
5869 * |-------|...|-------|
5873 if (i < sub_stripes)
5874 bbio->stripes[i].length -=
5877 if (stripe_index >= last_stripe &&
5878 stripe_index <= (last_stripe +
5880 bbio->stripes[i].length -=
5883 if (i == sub_stripes - 1)
5886 bbio->stripes[i].length = length;
5890 if (stripe_index == map->num_stripes) {
5897 bbio->map_type = map->type;
5898 bbio->num_stripes = num_stripes;
5900 free_extent_map(em);
5905 * In dev-replace case, for repair case (that's the only case where the mirror
5906 * is selected explicitly when calling btrfs_map_block), blocks left of the
5907 * left cursor can also be read from the target drive.
5909 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5911 * For READ, it also needs to be supported using the same mirror number.
5913 * If the requested block is not left of the left cursor, EIO is returned. This
5914 * can happen because btrfs_num_copies() returns one more in the dev-replace
5917 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5918 u64 logical, u64 length,
5919 u64 srcdev_devid, int *mirror_num,
5922 struct btrfs_bio *bbio = NULL;
5924 int index_srcdev = 0;
5926 u64 physical_of_found = 0;
5930 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5931 logical, &length, &bbio, 0, 0);
5933 ASSERT(bbio == NULL);
5937 num_stripes = bbio->num_stripes;
5938 if (*mirror_num > num_stripes) {
5940 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5941 * that means that the requested area is not left of the left
5944 btrfs_put_bbio(bbio);
5949 * process the rest of the function using the mirror_num of the source
5950 * drive. Therefore look it up first. At the end, patch the device
5951 * pointer to the one of the target drive.
5953 for (i = 0; i < num_stripes; i++) {
5954 if (bbio->stripes[i].dev->devid != srcdev_devid)
5958 * In case of DUP, in order to keep it simple, only add the
5959 * mirror with the lowest physical address
5962 physical_of_found <= bbio->stripes[i].physical)
5967 physical_of_found = bbio->stripes[i].physical;
5970 btrfs_put_bbio(bbio);
5976 *mirror_num = index_srcdev + 1;
5977 *physical = physical_of_found;
5981 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5982 struct btrfs_bio **bbio_ret,
5983 struct btrfs_dev_replace *dev_replace,
5984 int *num_stripes_ret, int *max_errors_ret)
5986 struct btrfs_bio *bbio = *bbio_ret;
5987 u64 srcdev_devid = dev_replace->srcdev->devid;
5988 int tgtdev_indexes = 0;
5989 int num_stripes = *num_stripes_ret;
5990 int max_errors = *max_errors_ret;
5993 if (op == BTRFS_MAP_WRITE) {
5994 int index_where_to_add;
5997 * duplicate the write operations while the dev replace
5998 * procedure is running. Since the copying of the old disk to
5999 * the new disk takes place at run time while the filesystem is
6000 * mounted writable, the regular write operations to the old
6001 * disk have to be duplicated to go to the new disk as well.
6003 * Note that device->missing is handled by the caller, and that
6004 * the write to the old disk is already set up in the stripes
6007 index_where_to_add = num_stripes;
6008 for (i = 0; i < num_stripes; i++) {
6009 if (bbio->stripes[i].dev->devid == srcdev_devid) {
6010 /* write to new disk, too */
6011 struct btrfs_bio_stripe *new =
6012 bbio->stripes + index_where_to_add;
6013 struct btrfs_bio_stripe *old =
6016 new->physical = old->physical;
6017 new->length = old->length;
6018 new->dev = dev_replace->tgtdev;
6019 bbio->tgtdev_map[i] = index_where_to_add;
6020 index_where_to_add++;
6025 num_stripes = index_where_to_add;
6026 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
6027 int index_srcdev = 0;
6029 u64 physical_of_found = 0;
6032 * During the dev-replace procedure, the target drive can also
6033 * be used to read data in case it is needed to repair a corrupt
6034 * block elsewhere. This is possible if the requested area is
6035 * left of the left cursor. In this area, the target drive is a
6036 * full copy of the source drive.
6038 for (i = 0; i < num_stripes; i++) {
6039 if (bbio->stripes[i].dev->devid == srcdev_devid) {
6041 * In case of DUP, in order to keep it simple,
6042 * only add the mirror with the lowest physical
6046 physical_of_found <=
6047 bbio->stripes[i].physical)
6051 physical_of_found = bbio->stripes[i].physical;
6055 struct btrfs_bio_stripe *tgtdev_stripe =
6056 bbio->stripes + num_stripes;
6058 tgtdev_stripe->physical = physical_of_found;
6059 tgtdev_stripe->length =
6060 bbio->stripes[index_srcdev].length;
6061 tgtdev_stripe->dev = dev_replace->tgtdev;
6062 bbio->tgtdev_map[index_srcdev] = num_stripes;
6069 *num_stripes_ret = num_stripes;
6070 *max_errors_ret = max_errors;
6071 bbio->num_tgtdevs = tgtdev_indexes;
6075 static bool need_full_stripe(enum btrfs_map_op op)
6077 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
6081 * btrfs_get_io_geometry - calculates the geomery of a particular (address, len)
6082 * tuple. This information is used to calculate how big a
6083 * particular bio can get before it straddles a stripe.
6085 * @fs_info - the filesystem
6086 * @logical - address that we want to figure out the geometry of
6087 * @len - the length of IO we are going to perform, starting at @logical
6088 * @op - type of operation - write or read
6089 * @io_geom - pointer used to return values
6091 * Returns < 0 in case a chunk for the given logical address cannot be found,
6092 * usually shouldn't happen unless @logical is corrupted, 0 otherwise.
6094 int btrfs_get_io_geometry(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6095 u64 logical, u64 len, struct btrfs_io_geometry *io_geom)
6097 struct extent_map *em;
6098 struct map_lookup *map;
6103 u64 raid56_full_stripe_start = (u64)-1;
6107 ASSERT(op != BTRFS_MAP_DISCARD);
6109 em = btrfs_get_chunk_map(fs_info, logical, len);
6113 map = em->map_lookup;
6114 /* Offset of this logical address in the chunk */
6115 offset = logical - em->start;
6116 /* Len of a stripe in a chunk */
6117 stripe_len = map->stripe_len;
6118 /* Stripe wher this block falls in */
6119 stripe_nr = div64_u64(offset, stripe_len);
6120 /* Offset of stripe in the chunk */
6121 stripe_offset = stripe_nr * stripe_len;
6122 if (offset < stripe_offset) {
6124 "stripe math has gone wrong, stripe_offset=%llu offset=%llu start=%llu logical=%llu stripe_len=%llu",
6125 stripe_offset, offset, em->start, logical, stripe_len);
6130 /* stripe_offset is the offset of this block in its stripe */
6131 stripe_offset = offset - stripe_offset;
6132 data_stripes = nr_data_stripes(map);
6134 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6135 u64 max_len = stripe_len - stripe_offset;
6138 * In case of raid56, we need to know the stripe aligned start
6140 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6141 unsigned long full_stripe_len = stripe_len * data_stripes;
6142 raid56_full_stripe_start = offset;
6145 * Allow a write of a full stripe, but make sure we
6146 * don't allow straddling of stripes
6148 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
6150 raid56_full_stripe_start *= full_stripe_len;
6153 * For writes to RAID[56], allow a full stripeset across
6154 * all disks. For other RAID types and for RAID[56]
6155 * reads, just allow a single stripe (on a single disk).
6157 if (op == BTRFS_MAP_WRITE) {
6158 max_len = stripe_len * data_stripes -
6159 (offset - raid56_full_stripe_start);
6162 len = min_t(u64, em->len - offset, max_len);
6164 len = em->len - offset;
6168 io_geom->offset = offset;
6169 io_geom->stripe_len = stripe_len;
6170 io_geom->stripe_nr = stripe_nr;
6171 io_geom->stripe_offset = stripe_offset;
6172 io_geom->raid56_stripe_offset = raid56_full_stripe_start;
6176 free_extent_map(em);
6180 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
6181 enum btrfs_map_op op,
6182 u64 logical, u64 *length,
6183 struct btrfs_bio **bbio_ret,
6184 int mirror_num, int need_raid_map)
6186 struct extent_map *em;
6187 struct map_lookup *map;
6197 int tgtdev_indexes = 0;
6198 struct btrfs_bio *bbio = NULL;
6199 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6200 int dev_replace_is_ongoing = 0;
6201 int num_alloc_stripes;
6202 int patch_the_first_stripe_for_dev_replace = 0;
6203 u64 physical_to_patch_in_first_stripe = 0;
6204 u64 raid56_full_stripe_start = (u64)-1;
6205 struct btrfs_io_geometry geom;
6209 if (op == BTRFS_MAP_DISCARD)
6210 return __btrfs_map_block_for_discard(fs_info, logical,
6213 ret = btrfs_get_io_geometry(fs_info, op, logical, *length, &geom);
6217 em = btrfs_get_chunk_map(fs_info, logical, *length);
6218 ASSERT(!IS_ERR(em));
6219 map = em->map_lookup;
6222 stripe_len = geom.stripe_len;
6223 stripe_nr = geom.stripe_nr;
6224 stripe_offset = geom.stripe_offset;
6225 raid56_full_stripe_start = geom.raid56_stripe_offset;
6226 data_stripes = nr_data_stripes(map);
6228 down_read(&dev_replace->rwsem);
6229 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6231 * Hold the semaphore for read during the whole operation, write is
6232 * requested at commit time but must wait.
6234 if (!dev_replace_is_ongoing)
6235 up_read(&dev_replace->rwsem);
6237 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6238 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6239 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6240 dev_replace->srcdev->devid,
6242 &physical_to_patch_in_first_stripe);
6246 patch_the_first_stripe_for_dev_replace = 1;
6247 } else if (mirror_num > map->num_stripes) {
6253 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6254 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6256 if (!need_full_stripe(op))
6258 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
6259 if (need_full_stripe(op))
6260 num_stripes = map->num_stripes;
6261 else if (mirror_num)
6262 stripe_index = mirror_num - 1;
6264 stripe_index = find_live_mirror(fs_info, map, 0,
6265 dev_replace_is_ongoing);
6266 mirror_num = stripe_index + 1;
6269 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6270 if (need_full_stripe(op)) {
6271 num_stripes = map->num_stripes;
6272 } else if (mirror_num) {
6273 stripe_index = mirror_num - 1;
6278 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6279 u32 factor = map->num_stripes / map->sub_stripes;
6281 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6282 stripe_index *= map->sub_stripes;
6284 if (need_full_stripe(op))
6285 num_stripes = map->sub_stripes;
6286 else if (mirror_num)
6287 stripe_index += mirror_num - 1;
6289 int old_stripe_index = stripe_index;
6290 stripe_index = find_live_mirror(fs_info, map,
6292 dev_replace_is_ongoing);
6293 mirror_num = stripe_index - old_stripe_index + 1;
6296 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6297 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6298 /* push stripe_nr back to the start of the full stripe */
6299 stripe_nr = div64_u64(raid56_full_stripe_start,
6300 stripe_len * data_stripes);
6302 /* RAID[56] write or recovery. Return all stripes */
6303 num_stripes = map->num_stripes;
6304 max_errors = nr_parity_stripes(map);
6306 *length = map->stripe_len;
6311 * Mirror #0 or #1 means the original data block.
6312 * Mirror #2 is RAID5 parity block.
6313 * Mirror #3 is RAID6 Q block.
6315 stripe_nr = div_u64_rem(stripe_nr,
6316 data_stripes, &stripe_index);
6318 stripe_index = data_stripes + mirror_num - 2;
6320 /* We distribute the parity blocks across stripes */
6321 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6323 if (!need_full_stripe(op) && mirror_num <= 1)
6328 * after this, stripe_nr is the number of stripes on this
6329 * device we have to walk to find the data, and stripe_index is
6330 * the number of our device in the stripe array
6332 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6334 mirror_num = stripe_index + 1;
6336 if (stripe_index >= map->num_stripes) {
6338 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6339 stripe_index, map->num_stripes);
6344 num_alloc_stripes = num_stripes;
6345 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6346 if (op == BTRFS_MAP_WRITE)
6347 num_alloc_stripes <<= 1;
6348 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6349 num_alloc_stripes++;
6350 tgtdev_indexes = num_stripes;
6353 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6358 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
6359 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
6361 /* build raid_map */
6362 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6363 (need_full_stripe(op) || mirror_num > 1)) {
6367 bbio->raid_map = (u64 *)((void *)bbio->stripes +
6368 sizeof(struct btrfs_bio_stripe) *
6370 sizeof(int) * tgtdev_indexes);
6372 /* Work out the disk rotation on this stripe-set */
6373 div_u64_rem(stripe_nr, num_stripes, &rot);
6375 /* Fill in the logical address of each stripe */
6376 tmp = stripe_nr * data_stripes;
6377 for (i = 0; i < data_stripes; i++)
6378 bbio->raid_map[(i+rot) % num_stripes] =
6379 em->start + (tmp + i) * map->stripe_len;
6381 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6382 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6383 bbio->raid_map[(i+rot+1) % num_stripes] =
6388 for (i = 0; i < num_stripes; i++) {
6389 bbio->stripes[i].physical =
6390 map->stripes[stripe_index].physical +
6392 stripe_nr * map->stripe_len;
6393 bbio->stripes[i].dev =
6394 map->stripes[stripe_index].dev;
6398 if (need_full_stripe(op))
6399 max_errors = btrfs_chunk_max_errors(map);
6402 sort_parity_stripes(bbio, num_stripes);
6404 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6405 need_full_stripe(op)) {
6406 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
6411 bbio->map_type = map->type;
6412 bbio->num_stripes = num_stripes;
6413 bbio->max_errors = max_errors;
6414 bbio->mirror_num = mirror_num;
6417 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6418 * mirror_num == num_stripes + 1 && dev_replace target drive is
6419 * available as a mirror
6421 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6422 WARN_ON(num_stripes > 1);
6423 bbio->stripes[0].dev = dev_replace->tgtdev;
6424 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6425 bbio->mirror_num = map->num_stripes + 1;
6428 if (dev_replace_is_ongoing) {
6429 lockdep_assert_held(&dev_replace->rwsem);
6430 /* Unlock and let waiting writers proceed */
6431 up_read(&dev_replace->rwsem);
6433 free_extent_map(em);
6437 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6438 u64 logical, u64 *length,
6439 struct btrfs_bio **bbio_ret, int mirror_num)
6441 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6445 /* For Scrub/replace */
6446 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6447 u64 logical, u64 *length,
6448 struct btrfs_bio **bbio_ret)
6450 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6453 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
6454 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
6456 struct extent_map *em;
6457 struct map_lookup *map;
6465 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
6469 map = em->map_lookup;
6471 rmap_len = map->stripe_len;
6473 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6474 length = div_u64(length, map->num_stripes / map->sub_stripes);
6475 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6476 length = div_u64(length, map->num_stripes);
6477 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6478 length = div_u64(length, nr_data_stripes(map));
6479 rmap_len = map->stripe_len * nr_data_stripes(map);
6482 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
6483 BUG_ON(!buf); /* -ENOMEM */
6485 for (i = 0; i < map->num_stripes; i++) {
6486 if (map->stripes[i].physical > physical ||
6487 map->stripes[i].physical + length <= physical)
6490 stripe_nr = physical - map->stripes[i].physical;
6491 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
6493 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6494 stripe_nr = stripe_nr * map->num_stripes + i;
6495 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
6496 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6497 stripe_nr = stripe_nr * map->num_stripes + i;
6498 } /* else if RAID[56], multiply by nr_data_stripes().
6499 * Alternatively, just use rmap_len below instead of
6500 * map->stripe_len */
6502 bytenr = chunk_start + stripe_nr * rmap_len;
6503 WARN_ON(nr >= map->num_stripes);
6504 for (j = 0; j < nr; j++) {
6505 if (buf[j] == bytenr)
6509 WARN_ON(nr >= map->num_stripes);
6516 *stripe_len = rmap_len;
6518 free_extent_map(em);
6522 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6524 bio->bi_private = bbio->private;
6525 bio->bi_end_io = bbio->end_io;
6528 btrfs_put_bbio(bbio);
6531 static void btrfs_end_bio(struct bio *bio)
6533 struct btrfs_bio *bbio = bio->bi_private;
6534 int is_orig_bio = 0;
6536 if (bio->bi_status) {
6537 atomic_inc(&bbio->error);
6538 if (bio->bi_status == BLK_STS_IOERR ||
6539 bio->bi_status == BLK_STS_TARGET) {
6540 unsigned int stripe_index =
6541 btrfs_io_bio(bio)->stripe_index;
6542 struct btrfs_device *dev;
6544 BUG_ON(stripe_index >= bbio->num_stripes);
6545 dev = bbio->stripes[stripe_index].dev;
6547 if (bio_op(bio) == REQ_OP_WRITE)
6548 btrfs_dev_stat_inc_and_print(dev,
6549 BTRFS_DEV_STAT_WRITE_ERRS);
6550 else if (!(bio->bi_opf & REQ_RAHEAD))
6551 btrfs_dev_stat_inc_and_print(dev,
6552 BTRFS_DEV_STAT_READ_ERRS);
6553 if (bio->bi_opf & REQ_PREFLUSH)
6554 btrfs_dev_stat_inc_and_print(dev,
6555 BTRFS_DEV_STAT_FLUSH_ERRS);
6560 if (bio == bbio->orig_bio)
6563 btrfs_bio_counter_dec(bbio->fs_info);
6565 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6568 bio = bbio->orig_bio;
6571 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6572 /* only send an error to the higher layers if it is
6573 * beyond the tolerance of the btrfs bio
6575 if (atomic_read(&bbio->error) > bbio->max_errors) {
6576 bio->bi_status = BLK_STS_IOERR;
6579 * this bio is actually up to date, we didn't
6580 * go over the max number of errors
6582 bio->bi_status = BLK_STS_OK;
6585 btrfs_end_bbio(bbio, bio);
6586 } else if (!is_orig_bio) {
6592 * see run_scheduled_bios for a description of why bios are collected for
6595 * This will add one bio to the pending list for a device and make sure
6596 * the work struct is scheduled.
6598 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6601 struct btrfs_fs_info *fs_info = device->fs_info;
6602 int should_queue = 1;
6603 struct btrfs_pending_bios *pending_bios;
6605 /* don't bother with additional async steps for reads, right now */
6606 if (bio_op(bio) == REQ_OP_READ) {
6607 btrfsic_submit_bio(bio);
6611 WARN_ON(bio->bi_next);
6612 bio->bi_next = NULL;
6614 spin_lock(&device->io_lock);
6615 if (op_is_sync(bio->bi_opf))
6616 pending_bios = &device->pending_sync_bios;
6618 pending_bios = &device->pending_bios;
6620 if (pending_bios->tail)
6621 pending_bios->tail->bi_next = bio;
6623 pending_bios->tail = bio;
6624 if (!pending_bios->head)
6625 pending_bios->head = bio;
6626 if (device->running_pending)
6629 spin_unlock(&device->io_lock);
6632 btrfs_queue_work(fs_info->submit_workers, &device->work);
6635 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6636 u64 physical, int dev_nr, int async)
6638 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6639 struct btrfs_fs_info *fs_info = bbio->fs_info;
6641 bio->bi_private = bbio;
6642 btrfs_io_bio(bio)->stripe_index = dev_nr;
6643 bio->bi_end_io = btrfs_end_bio;
6644 bio->bi_iter.bi_sector = physical >> 9;
6645 btrfs_debug_in_rcu(fs_info,
6646 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6647 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6648 (u_long)dev->bdev->bd_dev, rcu_str_deref(dev->name), dev->devid,
6649 bio->bi_iter.bi_size);
6650 bio_set_dev(bio, dev->bdev);
6652 btrfs_bio_counter_inc_noblocked(fs_info);
6655 btrfs_schedule_bio(dev, bio);
6657 btrfsic_submit_bio(bio);
6660 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6662 atomic_inc(&bbio->error);
6663 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6664 /* Should be the original bio. */
6665 WARN_ON(bio != bbio->orig_bio);
6667 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6668 bio->bi_iter.bi_sector = logical >> 9;
6669 if (atomic_read(&bbio->error) > bbio->max_errors)
6670 bio->bi_status = BLK_STS_IOERR;
6672 bio->bi_status = BLK_STS_OK;
6673 btrfs_end_bbio(bbio, bio);
6677 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6678 int mirror_num, int async_submit)
6680 struct btrfs_device *dev;
6681 struct bio *first_bio = bio;
6682 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6688 struct btrfs_bio *bbio = NULL;
6690 length = bio->bi_iter.bi_size;
6691 map_length = length;
6693 btrfs_bio_counter_inc_blocked(fs_info);
6694 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6695 &map_length, &bbio, mirror_num, 1);
6697 btrfs_bio_counter_dec(fs_info);
6698 return errno_to_blk_status(ret);
6701 total_devs = bbio->num_stripes;
6702 bbio->orig_bio = first_bio;
6703 bbio->private = first_bio->bi_private;
6704 bbio->end_io = first_bio->bi_end_io;
6705 bbio->fs_info = fs_info;
6706 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6708 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6709 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6710 /* In this case, map_length has been set to the length of
6711 a single stripe; not the whole write */
6712 if (bio_op(bio) == REQ_OP_WRITE) {
6713 ret = raid56_parity_write(fs_info, bio, bbio,
6716 ret = raid56_parity_recover(fs_info, bio, bbio,
6717 map_length, mirror_num, 1);
6720 btrfs_bio_counter_dec(fs_info);
6721 return errno_to_blk_status(ret);
6724 if (map_length < length) {
6726 "mapping failed logical %llu bio len %llu len %llu",
6727 logical, length, map_length);
6731 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6732 dev = bbio->stripes[dev_nr].dev;
6733 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6735 (bio_op(first_bio) == REQ_OP_WRITE &&
6736 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6737 bbio_error(bbio, first_bio, logical);
6741 if (dev_nr < total_devs - 1)
6742 bio = btrfs_bio_clone(first_bio);
6746 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6747 dev_nr, async_submit);
6749 btrfs_bio_counter_dec(fs_info);
6754 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6757 * If devid and uuid are both specified, the match must be exact, otherwise
6758 * only devid is used.
6760 * If @seed is true, traverse through the seed devices.
6762 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6763 u64 devid, u8 *uuid, u8 *fsid,
6766 struct btrfs_device *device;
6768 while (fs_devices) {
6770 !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6771 list_for_each_entry(device, &fs_devices->devices,
6773 if (device->devid == devid &&
6774 (!uuid || memcmp(device->uuid, uuid,
6775 BTRFS_UUID_SIZE) == 0))
6780 fs_devices = fs_devices->seed;
6787 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6788 u64 devid, u8 *dev_uuid)
6790 struct btrfs_device *device;
6791 unsigned int nofs_flag;
6794 * We call this under the chunk_mutex, so we want to use NOFS for this
6795 * allocation, however we don't want to change btrfs_alloc_device() to
6796 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6799 nofs_flag = memalloc_nofs_save();
6800 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6801 memalloc_nofs_restore(nofs_flag);
6805 list_add(&device->dev_list, &fs_devices->devices);
6806 device->fs_devices = fs_devices;
6807 fs_devices->num_devices++;
6809 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6810 fs_devices->missing_devices++;
6816 * btrfs_alloc_device - allocate struct btrfs_device
6817 * @fs_info: used only for generating a new devid, can be NULL if
6818 * devid is provided (i.e. @devid != NULL).
6819 * @devid: a pointer to devid for this device. If NULL a new devid
6821 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6824 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6825 * on error. Returned struct is not linked onto any lists and must be
6826 * destroyed with btrfs_free_device.
6828 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6832 struct btrfs_device *dev;
6835 if (WARN_ON(!devid && !fs_info))
6836 return ERR_PTR(-EINVAL);
6838 dev = __alloc_device();
6847 ret = find_next_devid(fs_info, &tmp);
6849 btrfs_free_device(dev);
6850 return ERR_PTR(ret);
6856 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6858 generate_random_uuid(dev->uuid);
6860 btrfs_init_work(&dev->work, pending_bios_fn, NULL, NULL);
6865 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6866 u64 devid, u8 *uuid, bool error)
6869 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6872 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6876 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
6878 int index = btrfs_bg_flags_to_raid_index(type);
6879 int ncopies = btrfs_raid_array[index].ncopies;
6882 switch (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6883 case BTRFS_BLOCK_GROUP_RAID5:
6884 data_stripes = num_stripes - 1;
6886 case BTRFS_BLOCK_GROUP_RAID6:
6887 data_stripes = num_stripes - 2;
6890 data_stripes = num_stripes / ncopies;
6893 return div_u64(chunk_len, data_stripes);
6896 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
6897 struct btrfs_chunk *chunk)
6899 struct btrfs_fs_info *fs_info = leaf->fs_info;
6900 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6901 struct map_lookup *map;
6902 struct extent_map *em;
6906 u8 uuid[BTRFS_UUID_SIZE];
6911 logical = key->offset;
6912 length = btrfs_chunk_length(leaf, chunk);
6913 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6916 * Only need to verify chunk item if we're reading from sys chunk array,
6917 * as chunk item in tree block is already verified by tree-checker.
6919 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6920 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
6925 read_lock(&map_tree->lock);
6926 em = lookup_extent_mapping(map_tree, logical, 1);
6927 read_unlock(&map_tree->lock);
6929 /* already mapped? */
6930 if (em && em->start <= logical && em->start + em->len > logical) {
6931 free_extent_map(em);
6934 free_extent_map(em);
6937 em = alloc_extent_map();
6940 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6942 free_extent_map(em);
6946 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6947 em->map_lookup = map;
6948 em->start = logical;
6951 em->block_start = 0;
6952 em->block_len = em->len;
6954 map->num_stripes = num_stripes;
6955 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6956 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6957 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6958 map->type = btrfs_chunk_type(leaf, chunk);
6959 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6960 map->verified_stripes = 0;
6961 em->orig_block_len = calc_stripe_length(map->type, em->len,
6963 for (i = 0; i < num_stripes; i++) {
6964 map->stripes[i].physical =
6965 btrfs_stripe_offset_nr(leaf, chunk, i);
6966 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6967 read_extent_buffer(leaf, uuid, (unsigned long)
6968 btrfs_stripe_dev_uuid_nr(chunk, i),
6970 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
6971 devid, uuid, NULL, true);
6972 if (!map->stripes[i].dev &&
6973 !btrfs_test_opt(fs_info, DEGRADED)) {
6974 free_extent_map(em);
6975 btrfs_report_missing_device(fs_info, devid, uuid, true);
6978 if (!map->stripes[i].dev) {
6979 map->stripes[i].dev =
6980 add_missing_dev(fs_info->fs_devices, devid,
6982 if (IS_ERR(map->stripes[i].dev)) {
6983 free_extent_map(em);
6985 "failed to init missing dev %llu: %ld",
6986 devid, PTR_ERR(map->stripes[i].dev));
6987 return PTR_ERR(map->stripes[i].dev);
6989 btrfs_report_missing_device(fs_info, devid, uuid, false);
6991 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6992 &(map->stripes[i].dev->dev_state));
6996 write_lock(&map_tree->lock);
6997 ret = add_extent_mapping(map_tree, em, 0);
6998 write_unlock(&map_tree->lock);
7001 "failed to add chunk map, start=%llu len=%llu: %d",
7002 em->start, em->len, ret);
7004 free_extent_map(em);
7009 static void fill_device_from_item(struct extent_buffer *leaf,
7010 struct btrfs_dev_item *dev_item,
7011 struct btrfs_device *device)
7015 device->devid = btrfs_device_id(leaf, dev_item);
7016 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
7017 device->total_bytes = device->disk_total_bytes;
7018 device->commit_total_bytes = device->disk_total_bytes;
7019 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
7020 device->commit_bytes_used = device->bytes_used;
7021 device->type = btrfs_device_type(leaf, dev_item);
7022 device->io_align = btrfs_device_io_align(leaf, dev_item);
7023 device->io_width = btrfs_device_io_width(leaf, dev_item);
7024 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
7025 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
7026 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
7028 ptr = btrfs_device_uuid(dev_item);
7029 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
7032 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
7035 struct btrfs_fs_devices *fs_devices;
7038 lockdep_assert_held(&uuid_mutex);
7041 fs_devices = fs_info->fs_devices->seed;
7042 while (fs_devices) {
7043 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
7046 fs_devices = fs_devices->seed;
7049 fs_devices = find_fsid(fsid, NULL);
7051 if (!btrfs_test_opt(fs_info, DEGRADED))
7052 return ERR_PTR(-ENOENT);
7054 fs_devices = alloc_fs_devices(fsid, NULL);
7055 if (IS_ERR(fs_devices))
7058 fs_devices->seeding = 1;
7059 fs_devices->opened = 1;
7063 fs_devices = clone_fs_devices(fs_devices);
7064 if (IS_ERR(fs_devices))
7067 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
7069 free_fs_devices(fs_devices);
7070 fs_devices = ERR_PTR(ret);
7074 if (!fs_devices->seeding) {
7075 close_fs_devices(fs_devices);
7076 free_fs_devices(fs_devices);
7077 fs_devices = ERR_PTR(-EINVAL);
7081 fs_devices->seed = fs_info->fs_devices->seed;
7082 fs_info->fs_devices->seed = fs_devices;
7087 static int read_one_dev(struct extent_buffer *leaf,
7088 struct btrfs_dev_item *dev_item)
7090 struct btrfs_fs_info *fs_info = leaf->fs_info;
7091 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7092 struct btrfs_device *device;
7095 u8 fs_uuid[BTRFS_FSID_SIZE];
7096 u8 dev_uuid[BTRFS_UUID_SIZE];
7098 devid = btrfs_device_id(leaf, dev_item);
7099 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
7101 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
7104 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
7105 fs_devices = open_seed_devices(fs_info, fs_uuid);
7106 if (IS_ERR(fs_devices))
7107 return PTR_ERR(fs_devices);
7110 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
7113 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7114 btrfs_report_missing_device(fs_info, devid,
7119 device = add_missing_dev(fs_devices, devid, dev_uuid);
7120 if (IS_ERR(device)) {
7122 "failed to add missing dev %llu: %ld",
7123 devid, PTR_ERR(device));
7124 return PTR_ERR(device);
7126 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
7128 if (!device->bdev) {
7129 if (!btrfs_test_opt(fs_info, DEGRADED)) {
7130 btrfs_report_missing_device(fs_info,
7131 devid, dev_uuid, true);
7134 btrfs_report_missing_device(fs_info, devid,
7138 if (!device->bdev &&
7139 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
7141 * this happens when a device that was properly setup
7142 * in the device info lists suddenly goes bad.
7143 * device->bdev is NULL, and so we have to set
7144 * device->missing to one here
7146 device->fs_devices->missing_devices++;
7147 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
7150 /* Move the device to its own fs_devices */
7151 if (device->fs_devices != fs_devices) {
7152 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
7153 &device->dev_state));
7155 list_move(&device->dev_list, &fs_devices->devices);
7156 device->fs_devices->num_devices--;
7157 fs_devices->num_devices++;
7159 device->fs_devices->missing_devices--;
7160 fs_devices->missing_devices++;
7162 device->fs_devices = fs_devices;
7166 if (device->fs_devices != fs_info->fs_devices) {
7167 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
7168 if (device->generation !=
7169 btrfs_device_generation(leaf, dev_item))
7173 fill_device_from_item(leaf, dev_item, device);
7174 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
7175 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
7176 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7177 device->fs_devices->total_rw_bytes += device->total_bytes;
7178 atomic64_add(device->total_bytes - device->bytes_used,
7179 &fs_info->free_chunk_space);
7185 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7187 struct btrfs_root *root = fs_info->tree_root;
7188 struct btrfs_super_block *super_copy = fs_info->super_copy;
7189 struct extent_buffer *sb;
7190 struct btrfs_disk_key *disk_key;
7191 struct btrfs_chunk *chunk;
7193 unsigned long sb_array_offset;
7200 struct btrfs_key key;
7202 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7204 * This will create extent buffer of nodesize, superblock size is
7205 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
7206 * overallocate but we can keep it as-is, only the first page is used.
7208 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
7211 set_extent_buffer_uptodate(sb);
7212 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
7214 * The sb extent buffer is artificial and just used to read the system array.
7215 * set_extent_buffer_uptodate() call does not properly mark all it's
7216 * pages up-to-date when the page is larger: extent does not cover the
7217 * whole page and consequently check_page_uptodate does not find all
7218 * the page's extents up-to-date (the hole beyond sb),
7219 * write_extent_buffer then triggers a WARN_ON.
7221 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
7222 * but sb spans only this function. Add an explicit SetPageUptodate call
7223 * to silence the warning eg. on PowerPC 64.
7225 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
7226 SetPageUptodate(sb->pages[0]);
7228 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7229 array_size = btrfs_super_sys_array_size(super_copy);
7231 array_ptr = super_copy->sys_chunk_array;
7232 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7235 while (cur_offset < array_size) {
7236 disk_key = (struct btrfs_disk_key *)array_ptr;
7237 len = sizeof(*disk_key);
7238 if (cur_offset + len > array_size)
7239 goto out_short_read;
7241 btrfs_disk_key_to_cpu(&key, disk_key);
7244 sb_array_offset += len;
7247 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
7248 chunk = (struct btrfs_chunk *)sb_array_offset;
7250 * At least one btrfs_chunk with one stripe must be
7251 * present, exact stripe count check comes afterwards
7253 len = btrfs_chunk_item_size(1);
7254 if (cur_offset + len > array_size)
7255 goto out_short_read;
7257 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7260 "invalid number of stripes %u in sys_array at offset %u",
7261 num_stripes, cur_offset);
7266 type = btrfs_chunk_type(sb, chunk);
7267 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7269 "invalid chunk type %llu in sys_array at offset %u",
7275 len = btrfs_chunk_item_size(num_stripes);
7276 if (cur_offset + len > array_size)
7277 goto out_short_read;
7279 ret = read_one_chunk(&key, sb, chunk);
7284 "unexpected item type %u in sys_array at offset %u",
7285 (u32)key.type, cur_offset);
7290 sb_array_offset += len;
7293 clear_extent_buffer_uptodate(sb);
7294 free_extent_buffer_stale(sb);
7298 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7300 clear_extent_buffer_uptodate(sb);
7301 free_extent_buffer_stale(sb);
7306 * Check if all chunks in the fs are OK for read-write degraded mount
7308 * If the @failing_dev is specified, it's accounted as missing.
7310 * Return true if all chunks meet the minimal RW mount requirements.
7311 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7313 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7314 struct btrfs_device *failing_dev)
7316 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
7317 struct extent_map *em;
7321 read_lock(&map_tree->lock);
7322 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
7323 read_unlock(&map_tree->lock);
7324 /* No chunk at all? Return false anyway */
7330 struct map_lookup *map;
7335 map = em->map_lookup;
7337 btrfs_get_num_tolerated_disk_barrier_failures(
7339 for (i = 0; i < map->num_stripes; i++) {
7340 struct btrfs_device *dev = map->stripes[i].dev;
7342 if (!dev || !dev->bdev ||
7343 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7344 dev->last_flush_error)
7346 else if (failing_dev && failing_dev == dev)
7349 if (missing > max_tolerated) {
7352 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7353 em->start, missing, max_tolerated);
7354 free_extent_map(em);
7358 next_start = extent_map_end(em);
7359 free_extent_map(em);
7361 read_lock(&map_tree->lock);
7362 em = lookup_extent_mapping(map_tree, next_start,
7363 (u64)(-1) - next_start);
7364 read_unlock(&map_tree->lock);
7370 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7372 struct btrfs_root *root = fs_info->chunk_root;
7373 struct btrfs_path *path;
7374 struct extent_buffer *leaf;
7375 struct btrfs_key key;
7376 struct btrfs_key found_key;
7381 path = btrfs_alloc_path();
7386 * uuid_mutex is needed only if we are mounting a sprout FS
7387 * otherwise we don't need it.
7389 mutex_lock(&uuid_mutex);
7392 * It is possible for mount and umount to race in such a way that
7393 * we execute this code path, but open_fs_devices failed to clear
7394 * total_rw_bytes. We certainly want it cleared before reading the
7395 * device items, so clear it here.
7397 fs_info->fs_devices->total_rw_bytes = 0;
7400 * Read all device items, and then all the chunk items. All
7401 * device items are found before any chunk item (their object id
7402 * is smaller than the lowest possible object id for a chunk
7403 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7405 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7408 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7412 leaf = path->nodes[0];
7413 slot = path->slots[0];
7414 if (slot >= btrfs_header_nritems(leaf)) {
7415 ret = btrfs_next_leaf(root, path);
7422 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7423 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7424 struct btrfs_dev_item *dev_item;
7425 dev_item = btrfs_item_ptr(leaf, slot,
7426 struct btrfs_dev_item);
7427 ret = read_one_dev(leaf, dev_item);
7431 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7432 struct btrfs_chunk *chunk;
7433 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7434 mutex_lock(&fs_info->chunk_mutex);
7435 ret = read_one_chunk(&found_key, leaf, chunk);
7436 mutex_unlock(&fs_info->chunk_mutex);
7444 * After loading chunk tree, we've got all device information,
7445 * do another round of validation checks.
7447 if (total_dev != fs_info->fs_devices->total_devices) {
7449 "super block num_devices %llu mismatch with DEV_ITEM count %llu, will be repaired on next transaction commit",
7450 btrfs_super_num_devices(fs_info->super_copy),
7452 fs_info->fs_devices->total_devices = total_dev;
7453 btrfs_set_super_num_devices(fs_info->super_copy, total_dev);
7455 if (btrfs_super_total_bytes(fs_info->super_copy) <
7456 fs_info->fs_devices->total_rw_bytes) {
7458 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7459 btrfs_super_total_bytes(fs_info->super_copy),
7460 fs_info->fs_devices->total_rw_bytes);
7466 mutex_unlock(&uuid_mutex);
7468 btrfs_free_path(path);
7472 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7474 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7475 struct btrfs_device *device;
7477 while (fs_devices) {
7478 mutex_lock(&fs_devices->device_list_mutex);
7479 list_for_each_entry(device, &fs_devices->devices, dev_list)
7480 device->fs_info = fs_info;
7481 mutex_unlock(&fs_devices->device_list_mutex);
7483 fs_devices = fs_devices->seed;
7487 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7488 const struct btrfs_dev_stats_item *ptr,
7493 read_extent_buffer(eb, &val,
7494 offsetof(struct btrfs_dev_stats_item, values) +
7495 ((unsigned long)ptr) + (index * sizeof(u64)),
7500 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7501 struct btrfs_dev_stats_item *ptr,
7504 write_extent_buffer(eb, &val,
7505 offsetof(struct btrfs_dev_stats_item, values) +
7506 ((unsigned long)ptr) + (index * sizeof(u64)),
7510 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7512 struct btrfs_key key;
7513 struct btrfs_root *dev_root = fs_info->dev_root;
7514 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7515 struct extent_buffer *eb;
7518 struct btrfs_device *device;
7519 struct btrfs_path *path = NULL;
7522 path = btrfs_alloc_path();
7526 mutex_lock(&fs_devices->device_list_mutex);
7527 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7529 struct btrfs_dev_stats_item *ptr;
7531 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7532 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7533 key.offset = device->devid;
7534 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7536 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7537 btrfs_dev_stat_set(device, i, 0);
7538 device->dev_stats_valid = 1;
7539 btrfs_release_path(path);
7542 slot = path->slots[0];
7543 eb = path->nodes[0];
7544 item_size = btrfs_item_size_nr(eb, slot);
7546 ptr = btrfs_item_ptr(eb, slot,
7547 struct btrfs_dev_stats_item);
7549 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7550 if (item_size >= (1 + i) * sizeof(__le64))
7551 btrfs_dev_stat_set(device, i,
7552 btrfs_dev_stats_value(eb, ptr, i));
7554 btrfs_dev_stat_set(device, i, 0);
7557 device->dev_stats_valid = 1;
7558 btrfs_dev_stat_print_on_load(device);
7559 btrfs_release_path(path);
7561 mutex_unlock(&fs_devices->device_list_mutex);
7563 btrfs_free_path(path);
7564 return ret < 0 ? ret : 0;
7567 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7568 struct btrfs_device *device)
7570 struct btrfs_fs_info *fs_info = trans->fs_info;
7571 struct btrfs_root *dev_root = fs_info->dev_root;
7572 struct btrfs_path *path;
7573 struct btrfs_key key;
7574 struct extent_buffer *eb;
7575 struct btrfs_dev_stats_item *ptr;
7579 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7580 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7581 key.offset = device->devid;
7583 path = btrfs_alloc_path();
7586 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7588 btrfs_warn_in_rcu(fs_info,
7589 "error %d while searching for dev_stats item for device %s",
7590 ret, rcu_str_deref(device->name));
7595 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7596 /* need to delete old one and insert a new one */
7597 ret = btrfs_del_item(trans, dev_root, path);
7599 btrfs_warn_in_rcu(fs_info,
7600 "delete too small dev_stats item for device %s failed %d",
7601 rcu_str_deref(device->name), ret);
7608 /* need to insert a new item */
7609 btrfs_release_path(path);
7610 ret = btrfs_insert_empty_item(trans, dev_root, path,
7611 &key, sizeof(*ptr));
7613 btrfs_warn_in_rcu(fs_info,
7614 "insert dev_stats item for device %s failed %d",
7615 rcu_str_deref(device->name), ret);
7620 eb = path->nodes[0];
7621 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7622 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7623 btrfs_set_dev_stats_value(eb, ptr, i,
7624 btrfs_dev_stat_read(device, i));
7625 btrfs_mark_buffer_dirty(eb);
7628 btrfs_free_path(path);
7633 * called from commit_transaction. Writes all changed device stats to disk.
7635 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7637 struct btrfs_fs_info *fs_info = trans->fs_info;
7638 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7639 struct btrfs_device *device;
7643 mutex_lock(&fs_devices->device_list_mutex);
7644 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7645 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7646 if (!device->dev_stats_valid || stats_cnt == 0)
7651 * There is a LOAD-LOAD control dependency between the value of
7652 * dev_stats_ccnt and updating the on-disk values which requires
7653 * reading the in-memory counters. Such control dependencies
7654 * require explicit read memory barriers.
7656 * This memory barriers pairs with smp_mb__before_atomic in
7657 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7658 * barrier implied by atomic_xchg in
7659 * btrfs_dev_stats_read_and_reset
7663 ret = update_dev_stat_item(trans, device);
7665 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7667 mutex_unlock(&fs_devices->device_list_mutex);
7672 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7674 btrfs_dev_stat_inc(dev, index);
7675 btrfs_dev_stat_print_on_error(dev);
7678 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7680 if (!dev->dev_stats_valid)
7682 btrfs_err_rl_in_rcu(dev->fs_info,
7683 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7684 rcu_str_deref(dev->name),
7685 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7686 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7687 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7688 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7689 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7692 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7696 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7697 if (btrfs_dev_stat_read(dev, i) != 0)
7699 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7700 return; /* all values == 0, suppress message */
7702 btrfs_info_in_rcu(dev->fs_info,
7703 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7704 rcu_str_deref(dev->name),
7705 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7706 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7707 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7708 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7709 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7712 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7713 struct btrfs_ioctl_get_dev_stats *stats)
7715 struct btrfs_device *dev;
7716 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7719 mutex_lock(&fs_devices->device_list_mutex);
7720 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL,
7722 mutex_unlock(&fs_devices->device_list_mutex);
7725 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7727 } else if (!dev->dev_stats_valid) {
7728 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7730 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7731 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7732 if (stats->nr_items > i)
7734 btrfs_dev_stat_read_and_reset(dev, i);
7736 btrfs_dev_stat_set(dev, i, 0);
7738 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7739 current->comm, task_pid_nr(current));
7741 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7742 if (stats->nr_items > i)
7743 stats->values[i] = btrfs_dev_stat_read(dev, i);
7745 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7746 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7750 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7752 struct buffer_head *bh;
7753 struct btrfs_super_block *disk_super;
7759 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7762 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7765 disk_super = (struct btrfs_super_block *)bh->b_data;
7767 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7768 set_buffer_dirty(bh);
7769 sync_dirty_buffer(bh);
7773 /* Notify udev that device has changed */
7774 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7776 /* Update ctime/mtime for device path for libblkid */
7777 update_dev_time(device_path);
7781 * Update the size and bytes used for each device where it changed. This is
7782 * delayed since we would otherwise get errors while writing out the
7785 * Must be invoked during transaction commit.
7787 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7789 struct btrfs_device *curr, *next;
7791 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7793 if (list_empty(&trans->dev_update_list))
7797 * We don't need the device_list_mutex here. This list is owned by the
7798 * transaction and the transaction must complete before the device is
7801 mutex_lock(&trans->fs_info->chunk_mutex);
7802 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7804 list_del_init(&curr->post_commit_list);
7805 curr->commit_total_bytes = curr->disk_total_bytes;
7806 curr->commit_bytes_used = curr->bytes_used;
7808 mutex_unlock(&trans->fs_info->chunk_mutex);
7811 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7813 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7814 while (fs_devices) {
7815 fs_devices->fs_info = fs_info;
7816 fs_devices = fs_devices->seed;
7820 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7822 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7823 while (fs_devices) {
7824 fs_devices->fs_info = NULL;
7825 fs_devices = fs_devices->seed;
7830 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7832 int btrfs_bg_type_to_factor(u64 flags)
7834 const int index = btrfs_bg_flags_to_raid_index(flags);
7836 return btrfs_raid_array[index].ncopies;
7841 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7842 u64 chunk_offset, u64 devid,
7843 u64 physical_offset, u64 physical_len)
7845 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7846 struct extent_map *em;
7847 struct map_lookup *map;
7848 struct btrfs_device *dev;
7854 read_lock(&em_tree->lock);
7855 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7856 read_unlock(&em_tree->lock);
7860 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7861 physical_offset, devid);
7866 map = em->map_lookup;
7867 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7868 if (physical_len != stripe_len) {
7870 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7871 physical_offset, devid, em->start, physical_len,
7877 for (i = 0; i < map->num_stripes; i++) {
7878 if (map->stripes[i].dev->devid == devid &&
7879 map->stripes[i].physical == physical_offset) {
7881 if (map->verified_stripes >= map->num_stripes) {
7883 "too many dev extents for chunk %llu found",
7888 map->verified_stripes++;
7894 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7895 physical_offset, devid);
7899 /* Make sure no dev extent is beyond device bondary */
7900 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
7902 btrfs_err(fs_info, "failed to find devid %llu", devid);
7907 /* It's possible this device is a dummy for seed device */
7908 if (dev->disk_total_bytes == 0) {
7909 dev = btrfs_find_device(fs_info->fs_devices->seed, devid, NULL,
7912 btrfs_err(fs_info, "failed to find seed devid %llu",
7919 if (physical_offset + physical_len > dev->disk_total_bytes) {
7921 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7922 devid, physical_offset, physical_len,
7923 dev->disk_total_bytes);
7928 free_extent_map(em);
7932 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7934 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7935 struct extent_map *em;
7936 struct rb_node *node;
7939 read_lock(&em_tree->lock);
7940 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7941 em = rb_entry(node, struct extent_map, rb_node);
7942 if (em->map_lookup->num_stripes !=
7943 em->map_lookup->verified_stripes) {
7945 "chunk %llu has missing dev extent, have %d expect %d",
7946 em->start, em->map_lookup->verified_stripes,
7947 em->map_lookup->num_stripes);
7953 read_unlock(&em_tree->lock);
7958 * Ensure that all dev extents are mapped to correct chunk, otherwise
7959 * later chunk allocation/free would cause unexpected behavior.
7961 * NOTE: This will iterate through the whole device tree, which should be of
7962 * the same size level as the chunk tree. This slightly increases mount time.
7964 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7966 struct btrfs_path *path;
7967 struct btrfs_root *root = fs_info->dev_root;
7968 struct btrfs_key key;
7970 u64 prev_dev_ext_end = 0;
7974 key.type = BTRFS_DEV_EXTENT_KEY;
7977 path = btrfs_alloc_path();
7981 path->reada = READA_FORWARD;
7982 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7986 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7987 ret = btrfs_next_item(root, path);
7990 /* No dev extents at all? Not good */
7997 struct extent_buffer *leaf = path->nodes[0];
7998 struct btrfs_dev_extent *dext;
7999 int slot = path->slots[0];
8001 u64 physical_offset;
8005 btrfs_item_key_to_cpu(leaf, &key, slot);
8006 if (key.type != BTRFS_DEV_EXTENT_KEY)
8008 devid = key.objectid;
8009 physical_offset = key.offset;
8011 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
8012 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
8013 physical_len = btrfs_dev_extent_length(leaf, dext);
8015 /* Check if this dev extent overlaps with the previous one */
8016 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
8018 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
8019 devid, physical_offset, prev_dev_ext_end);
8024 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
8025 physical_offset, physical_len);
8029 prev_dev_ext_end = physical_offset + physical_len;
8031 ret = btrfs_next_item(root, path);
8040 /* Ensure all chunks have corresponding dev extents */
8041 ret = verify_chunk_dev_extent_mapping(fs_info);
8043 btrfs_free_path(path);
8048 * Check whether the given block group or device is pinned by any inode being
8049 * used as a swapfile.
8051 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
8053 struct btrfs_swapfile_pin *sp;
8054 struct rb_node *node;
8056 spin_lock(&fs_info->swapfile_pins_lock);
8057 node = fs_info->swapfile_pins.rb_node;
8059 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
8061 node = node->rb_left;
8062 else if (ptr > sp->ptr)
8063 node = node->rb_right;
8067 spin_unlock(&fs_info->swapfile_pins_lock);
8068 return node != NULL;