btrfs: constify map parameter for nr_parity_stripes and nr_data_stripes
[linux/fpc-iii.git] / fs / btrfs / volumes.c
blobeb737bcd7aac6493e2040f2ab1345ce55dfa88bd
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Copyright (C) 2007 Oracle. All rights reserved.
4 */
6 #include <linux/sched.h>
7 #include <linux/bio.h>
8 #include <linux/slab.h>
9 #include <linux/buffer_head.h>
10 #include <linux/blkdev.h>
11 #include <linux/ratelimit.h>
12 #include <linux/kthread.h>
13 #include <linux/raid/pq.h>
14 #include <linux/semaphore.h>
15 #include <linux/uuid.h>
16 #include <linux/list_sort.h>
17 #include "ctree.h"
18 #include "extent_map.h"
19 #include "disk-io.h"
20 #include "transaction.h"
21 #include "print-tree.h"
22 #include "volumes.h"
23 #include "raid56.h"
24 #include "async-thread.h"
25 #include "check-integrity.h"
26 #include "rcu-string.h"
27 #include "math.h"
28 #include "dev-replace.h"
29 #include "sysfs.h"
30 #include "tree-checker.h"
32 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
33 [BTRFS_RAID_RAID10] = {
34 .sub_stripes = 2,
35 .dev_stripes = 1,
36 .devs_max = 0, /* 0 == as many as possible */
37 .devs_min = 4,
38 .tolerated_failures = 1,
39 .devs_increment = 2,
40 .ncopies = 2,
41 .nparity = 0,
42 .raid_name = "raid10",
43 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
44 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
46 [BTRFS_RAID_RAID1] = {
47 .sub_stripes = 1,
48 .dev_stripes = 1,
49 .devs_max = 2,
50 .devs_min = 2,
51 .tolerated_failures = 1,
52 .devs_increment = 2,
53 .ncopies = 2,
54 .nparity = 0,
55 .raid_name = "raid1",
56 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
57 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
59 [BTRFS_RAID_DUP] = {
60 .sub_stripes = 1,
61 .dev_stripes = 2,
62 .devs_max = 1,
63 .devs_min = 1,
64 .tolerated_failures = 0,
65 .devs_increment = 1,
66 .ncopies = 2,
67 .nparity = 0,
68 .raid_name = "dup",
69 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
70 .mindev_error = 0,
72 [BTRFS_RAID_RAID0] = {
73 .sub_stripes = 1,
74 .dev_stripes = 1,
75 .devs_max = 0,
76 .devs_min = 2,
77 .tolerated_failures = 0,
78 .devs_increment = 1,
79 .ncopies = 1,
80 .nparity = 0,
81 .raid_name = "raid0",
82 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
83 .mindev_error = 0,
85 [BTRFS_RAID_SINGLE] = {
86 .sub_stripes = 1,
87 .dev_stripes = 1,
88 .devs_max = 1,
89 .devs_min = 1,
90 .tolerated_failures = 0,
91 .devs_increment = 1,
92 .ncopies = 1,
93 .nparity = 0,
94 .raid_name = "single",
95 .bg_flag = 0,
96 .mindev_error = 0,
98 [BTRFS_RAID_RAID5] = {
99 .sub_stripes = 1,
100 .dev_stripes = 1,
101 .devs_max = 0,
102 .devs_min = 2,
103 .tolerated_failures = 1,
104 .devs_increment = 1,
105 .ncopies = 1,
106 .nparity = 1,
107 .raid_name = "raid5",
108 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
109 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
111 [BTRFS_RAID_RAID6] = {
112 .sub_stripes = 1,
113 .dev_stripes = 1,
114 .devs_max = 0,
115 .devs_min = 3,
116 .tolerated_failures = 2,
117 .devs_increment = 1,
118 .ncopies = 1,
119 .nparity = 2,
120 .raid_name = "raid6",
121 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
122 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
126 const char *btrfs_bg_type_to_raid_name(u64 flags)
128 const int index = btrfs_bg_flags_to_raid_index(flags);
130 if (index >= BTRFS_NR_RAID_TYPES)
131 return NULL;
133 return btrfs_raid_array[index].raid_name;
137 * Fill @buf with textual description of @bg_flags, no more than @size_buf
138 * bytes including terminating null byte.
140 void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
142 int i;
143 int ret;
144 char *bp = buf;
145 u64 flags = bg_flags;
146 u32 size_bp = size_buf;
148 if (!flags) {
149 strcpy(bp, "NONE");
150 return;
153 #define DESCRIBE_FLAG(flag, desc) \
154 do { \
155 if (flags & (flag)) { \
156 ret = snprintf(bp, size_bp, "%s|", (desc)); \
157 if (ret < 0 || ret >= size_bp) \
158 goto out_overflow; \
159 size_bp -= ret; \
160 bp += ret; \
161 flags &= ~(flag); \
163 } while (0)
165 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
166 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
167 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
169 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
170 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
171 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
172 btrfs_raid_array[i].raid_name);
173 #undef DESCRIBE_FLAG
175 if (flags) {
176 ret = snprintf(bp, size_bp, "0x%llx|", flags);
177 size_bp -= ret;
180 if (size_bp < size_buf)
181 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
184 * The text is trimmed, it's up to the caller to provide sufficiently
185 * large buffer
187 out_overflow:;
190 static int init_first_rw_device(struct btrfs_trans_handle *trans);
191 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
192 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
193 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
194 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
195 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
196 enum btrfs_map_op op,
197 u64 logical, u64 *length,
198 struct btrfs_bio **bbio_ret,
199 int mirror_num, int need_raid_map);
202 * Device locking
203 * ==============
205 * There are several mutexes that protect manipulation of devices and low-level
206 * structures like chunks but not block groups, extents or files
208 * uuid_mutex (global lock)
209 * ------------------------
210 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
211 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
212 * device) or requested by the device= mount option
214 * the mutex can be very coarse and can cover long-running operations
216 * protects: updates to fs_devices counters like missing devices, rw devices,
217 * seeding, structure cloning, opening/closing devices at mount/umount time
219 * global::fs_devs - add, remove, updates to the global list
221 * does not protect: manipulation of the fs_devices::devices list!
223 * btrfs_device::name - renames (write side), read is RCU
225 * fs_devices::device_list_mutex (per-fs, with RCU)
226 * ------------------------------------------------
227 * protects updates to fs_devices::devices, ie. adding and deleting
229 * simple list traversal with read-only actions can be done with RCU protection
231 * may be used to exclude some operations from running concurrently without any
232 * modifications to the list (see write_all_supers)
234 * balance_mutex
235 * -------------
236 * protects balance structures (status, state) and context accessed from
237 * several places (internally, ioctl)
239 * chunk_mutex
240 * -----------
241 * protects chunks, adding or removing during allocation, trim or when a new
242 * device is added/removed
244 * cleaner_mutex
245 * -------------
246 * a big lock that is held by the cleaner thread and prevents running subvolume
247 * cleaning together with relocation or delayed iputs
250 * Lock nesting
251 * ============
253 * uuid_mutex
254 * volume_mutex
255 * device_list_mutex
256 * chunk_mutex
257 * balance_mutex
260 * Exclusive operations, BTRFS_FS_EXCL_OP
261 * ======================================
263 * Maintains the exclusivity of the following operations that apply to the
264 * whole filesystem and cannot run in parallel.
266 * - Balance (*)
267 * - Device add
268 * - Device remove
269 * - Device replace (*)
270 * - Resize
272 * The device operations (as above) can be in one of the following states:
274 * - Running state
275 * - Paused state
276 * - Completed state
278 * Only device operations marked with (*) can go into the Paused state for the
279 * following reasons:
281 * - ioctl (only Balance can be Paused through ioctl)
282 * - filesystem remounted as read-only
283 * - filesystem unmounted and mounted as read-only
284 * - system power-cycle and filesystem mounted as read-only
285 * - filesystem or device errors leading to forced read-only
287 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
288 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
289 * A device operation in Paused or Running state can be canceled or resumed
290 * either by ioctl (Balance only) or when remounted as read-write.
291 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
292 * completed.
295 DEFINE_MUTEX(uuid_mutex);
296 static LIST_HEAD(fs_uuids);
297 struct list_head *btrfs_get_fs_uuids(void)
299 return &fs_uuids;
303 * alloc_fs_devices - allocate struct btrfs_fs_devices
304 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
305 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
307 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
308 * The returned struct is not linked onto any lists and can be destroyed with
309 * kfree() right away.
311 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
312 const u8 *metadata_fsid)
314 struct btrfs_fs_devices *fs_devs;
316 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
317 if (!fs_devs)
318 return ERR_PTR(-ENOMEM);
320 mutex_init(&fs_devs->device_list_mutex);
322 INIT_LIST_HEAD(&fs_devs->devices);
323 INIT_LIST_HEAD(&fs_devs->alloc_list);
324 INIT_LIST_HEAD(&fs_devs->fs_list);
325 if (fsid)
326 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
328 if (metadata_fsid)
329 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
330 else if (fsid)
331 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
333 return fs_devs;
336 void btrfs_free_device(struct btrfs_device *device)
338 WARN_ON(!list_empty(&device->post_commit_list));
339 rcu_string_free(device->name);
340 extent_io_tree_release(&device->alloc_state);
341 bio_put(device->flush_bio);
342 kfree(device);
345 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
347 struct btrfs_device *device;
348 WARN_ON(fs_devices->opened);
349 while (!list_empty(&fs_devices->devices)) {
350 device = list_entry(fs_devices->devices.next,
351 struct btrfs_device, dev_list);
352 list_del(&device->dev_list);
353 btrfs_free_device(device);
355 kfree(fs_devices);
358 static void btrfs_kobject_uevent(struct block_device *bdev,
359 enum kobject_action action)
361 int ret;
363 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
364 if (ret)
365 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
366 action,
367 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
368 &disk_to_dev(bdev->bd_disk)->kobj);
371 void __exit btrfs_cleanup_fs_uuids(void)
373 struct btrfs_fs_devices *fs_devices;
375 while (!list_empty(&fs_uuids)) {
376 fs_devices = list_entry(fs_uuids.next,
377 struct btrfs_fs_devices, fs_list);
378 list_del(&fs_devices->fs_list);
379 free_fs_devices(fs_devices);
384 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
385 * Returned struct is not linked onto any lists and must be destroyed using
386 * btrfs_free_device.
388 static struct btrfs_device *__alloc_device(void)
390 struct btrfs_device *dev;
392 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
393 if (!dev)
394 return ERR_PTR(-ENOMEM);
397 * Preallocate a bio that's always going to be used for flushing device
398 * barriers and matches the device lifespan
400 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
401 if (!dev->flush_bio) {
402 kfree(dev);
403 return ERR_PTR(-ENOMEM);
406 INIT_LIST_HEAD(&dev->dev_list);
407 INIT_LIST_HEAD(&dev->dev_alloc_list);
408 INIT_LIST_HEAD(&dev->post_commit_list);
410 spin_lock_init(&dev->io_lock);
412 atomic_set(&dev->reada_in_flight, 0);
413 atomic_set(&dev->dev_stats_ccnt, 0);
414 btrfs_device_data_ordered_init(dev);
415 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
416 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
417 extent_io_tree_init(NULL, &dev->alloc_state, 0, NULL);
419 return dev;
422 static noinline struct btrfs_fs_devices *find_fsid(
423 const u8 *fsid, const u8 *metadata_fsid)
425 struct btrfs_fs_devices *fs_devices;
427 ASSERT(fsid);
429 if (metadata_fsid) {
431 * Handle scanned device having completed its fsid change but
432 * belonging to a fs_devices that was created by first scanning
433 * a device which didn't have its fsid/metadata_uuid changed
434 * at all and the CHANGING_FSID_V2 flag set.
436 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
437 if (fs_devices->fsid_change &&
438 memcmp(metadata_fsid, fs_devices->fsid,
439 BTRFS_FSID_SIZE) == 0 &&
440 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
441 BTRFS_FSID_SIZE) == 0) {
442 return fs_devices;
446 * Handle scanned device having completed its fsid change but
447 * belonging to a fs_devices that was created by a device that
448 * has an outdated pair of fsid/metadata_uuid and
449 * CHANGING_FSID_V2 flag set.
451 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
452 if (fs_devices->fsid_change &&
453 memcmp(fs_devices->metadata_uuid,
454 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
455 memcmp(metadata_fsid, fs_devices->metadata_uuid,
456 BTRFS_FSID_SIZE) == 0) {
457 return fs_devices;
462 /* Handle non-split brain cases */
463 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
464 if (metadata_fsid) {
465 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
466 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
467 BTRFS_FSID_SIZE) == 0)
468 return fs_devices;
469 } else {
470 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
471 return fs_devices;
474 return NULL;
477 static int
478 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
479 int flush, struct block_device **bdev,
480 struct buffer_head **bh)
482 int ret;
484 *bdev = blkdev_get_by_path(device_path, flags, holder);
486 if (IS_ERR(*bdev)) {
487 ret = PTR_ERR(*bdev);
488 goto error;
491 if (flush)
492 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
493 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
494 if (ret) {
495 blkdev_put(*bdev, flags);
496 goto error;
498 invalidate_bdev(*bdev);
499 *bh = btrfs_read_dev_super(*bdev);
500 if (IS_ERR(*bh)) {
501 ret = PTR_ERR(*bh);
502 blkdev_put(*bdev, flags);
503 goto error;
506 return 0;
508 error:
509 *bdev = NULL;
510 *bh = NULL;
511 return ret;
514 static void requeue_list(struct btrfs_pending_bios *pending_bios,
515 struct bio *head, struct bio *tail)
518 struct bio *old_head;
520 old_head = pending_bios->head;
521 pending_bios->head = head;
522 if (pending_bios->tail)
523 tail->bi_next = old_head;
524 else
525 pending_bios->tail = tail;
529 * we try to collect pending bios for a device so we don't get a large
530 * number of procs sending bios down to the same device. This greatly
531 * improves the schedulers ability to collect and merge the bios.
533 * But, it also turns into a long list of bios to process and that is sure
534 * to eventually make the worker thread block. The solution here is to
535 * make some progress and then put this work struct back at the end of
536 * the list if the block device is congested. This way, multiple devices
537 * can make progress from a single worker thread.
539 static noinline void run_scheduled_bios(struct btrfs_device *device)
541 struct btrfs_fs_info *fs_info = device->fs_info;
542 struct bio *pending;
543 struct backing_dev_info *bdi;
544 struct btrfs_pending_bios *pending_bios;
545 struct bio *tail;
546 struct bio *cur;
547 int again = 0;
548 unsigned long num_run;
549 unsigned long batch_run = 0;
550 unsigned long last_waited = 0;
551 int force_reg = 0;
552 int sync_pending = 0;
553 struct blk_plug plug;
556 * this function runs all the bios we've collected for
557 * a particular device. We don't want to wander off to
558 * another device without first sending all of these down.
559 * So, setup a plug here and finish it off before we return
561 blk_start_plug(&plug);
563 bdi = device->bdev->bd_bdi;
565 loop:
566 spin_lock(&device->io_lock);
568 loop_lock:
569 num_run = 0;
571 /* take all the bios off the list at once and process them
572 * later on (without the lock held). But, remember the
573 * tail and other pointers so the bios can be properly reinserted
574 * into the list if we hit congestion
576 if (!force_reg && device->pending_sync_bios.head) {
577 pending_bios = &device->pending_sync_bios;
578 force_reg = 1;
579 } else {
580 pending_bios = &device->pending_bios;
581 force_reg = 0;
584 pending = pending_bios->head;
585 tail = pending_bios->tail;
586 WARN_ON(pending && !tail);
589 * if pending was null this time around, no bios need processing
590 * at all and we can stop. Otherwise it'll loop back up again
591 * and do an additional check so no bios are missed.
593 * device->running_pending is used to synchronize with the
594 * schedule_bio code.
596 if (device->pending_sync_bios.head == NULL &&
597 device->pending_bios.head == NULL) {
598 again = 0;
599 device->running_pending = 0;
600 } else {
601 again = 1;
602 device->running_pending = 1;
605 pending_bios->head = NULL;
606 pending_bios->tail = NULL;
608 spin_unlock(&device->io_lock);
610 while (pending) {
612 rmb();
613 /* we want to work on both lists, but do more bios on the
614 * sync list than the regular list
616 if ((num_run > 32 &&
617 pending_bios != &device->pending_sync_bios &&
618 device->pending_sync_bios.head) ||
619 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
620 device->pending_bios.head)) {
621 spin_lock(&device->io_lock);
622 requeue_list(pending_bios, pending, tail);
623 goto loop_lock;
626 cur = pending;
627 pending = pending->bi_next;
628 cur->bi_next = NULL;
630 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
633 * if we're doing the sync list, record that our
634 * plug has some sync requests on it
636 * If we're doing the regular list and there are
637 * sync requests sitting around, unplug before
638 * we add more
640 if (pending_bios == &device->pending_sync_bios) {
641 sync_pending = 1;
642 } else if (sync_pending) {
643 blk_finish_plug(&plug);
644 blk_start_plug(&plug);
645 sync_pending = 0;
648 btrfsic_submit_bio(cur);
649 num_run++;
650 batch_run++;
652 cond_resched();
655 * we made progress, there is more work to do and the bdi
656 * is now congested. Back off and let other work structs
657 * run instead
659 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
660 fs_info->fs_devices->open_devices > 1) {
661 struct io_context *ioc;
663 ioc = current->io_context;
666 * the main goal here is that we don't want to
667 * block if we're going to be able to submit
668 * more requests without blocking.
670 * This code does two great things, it pokes into
671 * the elevator code from a filesystem _and_
672 * it makes assumptions about how batching works.
674 if (ioc && ioc->nr_batch_requests > 0 &&
675 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
676 (last_waited == 0 ||
677 ioc->last_waited == last_waited)) {
679 * we want to go through our batch of
680 * requests and stop. So, we copy out
681 * the ioc->last_waited time and test
682 * against it before looping
684 last_waited = ioc->last_waited;
685 cond_resched();
686 continue;
688 spin_lock(&device->io_lock);
689 requeue_list(pending_bios, pending, tail);
690 device->running_pending = 1;
692 spin_unlock(&device->io_lock);
693 btrfs_queue_work(fs_info->submit_workers,
694 &device->work);
695 goto done;
699 cond_resched();
700 if (again)
701 goto loop;
703 spin_lock(&device->io_lock);
704 if (device->pending_bios.head || device->pending_sync_bios.head)
705 goto loop_lock;
706 spin_unlock(&device->io_lock);
708 done:
709 blk_finish_plug(&plug);
712 static void pending_bios_fn(struct btrfs_work *work)
714 struct btrfs_device *device;
716 device = container_of(work, struct btrfs_device, work);
717 run_scheduled_bios(device);
720 static bool device_path_matched(const char *path, struct btrfs_device *device)
722 int found;
724 rcu_read_lock();
725 found = strcmp(rcu_str_deref(device->name), path);
726 rcu_read_unlock();
728 return found == 0;
732 * Search and remove all stale (devices which are not mounted) devices.
733 * When both inputs are NULL, it will search and release all stale devices.
734 * path: Optional. When provided will it release all unmounted devices
735 * matching this path only.
736 * skip_dev: Optional. Will skip this device when searching for the stale
737 * devices.
738 * Return: 0 for success or if @path is NULL.
739 * -EBUSY if @path is a mounted device.
740 * -ENOENT if @path does not match any device in the list.
742 static int btrfs_free_stale_devices(const char *path,
743 struct btrfs_device *skip_device)
745 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
746 struct btrfs_device *device, *tmp_device;
747 int ret = 0;
749 if (path)
750 ret = -ENOENT;
752 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
754 mutex_lock(&fs_devices->device_list_mutex);
755 list_for_each_entry_safe(device, tmp_device,
756 &fs_devices->devices, dev_list) {
757 if (skip_device && skip_device == device)
758 continue;
759 if (path && !device->name)
760 continue;
761 if (path && !device_path_matched(path, device))
762 continue;
763 if (fs_devices->opened) {
764 /* for an already deleted device return 0 */
765 if (path && ret != 0)
766 ret = -EBUSY;
767 break;
770 /* delete the stale device */
771 fs_devices->num_devices--;
772 list_del(&device->dev_list);
773 btrfs_free_device(device);
775 ret = 0;
776 if (fs_devices->num_devices == 0)
777 break;
779 mutex_unlock(&fs_devices->device_list_mutex);
781 if (fs_devices->num_devices == 0) {
782 btrfs_sysfs_remove_fsid(fs_devices);
783 list_del(&fs_devices->fs_list);
784 free_fs_devices(fs_devices);
788 return ret;
791 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
792 struct btrfs_device *device, fmode_t flags,
793 void *holder)
795 struct request_queue *q;
796 struct block_device *bdev;
797 struct buffer_head *bh;
798 struct btrfs_super_block *disk_super;
799 u64 devid;
800 int ret;
802 if (device->bdev)
803 return -EINVAL;
804 if (!device->name)
805 return -EINVAL;
807 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
808 &bdev, &bh);
809 if (ret)
810 return ret;
812 disk_super = (struct btrfs_super_block *)bh->b_data;
813 devid = btrfs_stack_device_id(&disk_super->dev_item);
814 if (devid != device->devid)
815 goto error_brelse;
817 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
818 goto error_brelse;
820 device->generation = btrfs_super_generation(disk_super);
822 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
823 if (btrfs_super_incompat_flags(disk_super) &
824 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
825 pr_err(
826 "BTRFS: Invalid seeding and uuid-changed device detected\n");
827 goto error_brelse;
830 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
831 fs_devices->seeding = 1;
832 } else {
833 if (bdev_read_only(bdev))
834 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
835 else
836 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
839 q = bdev_get_queue(bdev);
840 if (!blk_queue_nonrot(q))
841 fs_devices->rotating = 1;
843 device->bdev = bdev;
844 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
845 device->mode = flags;
847 fs_devices->open_devices++;
848 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
849 device->devid != BTRFS_DEV_REPLACE_DEVID) {
850 fs_devices->rw_devices++;
851 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
853 brelse(bh);
855 return 0;
857 error_brelse:
858 brelse(bh);
859 blkdev_put(bdev, flags);
861 return -EINVAL;
865 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
866 * being created with a disk that has already completed its fsid change.
868 static struct btrfs_fs_devices *find_fsid_inprogress(
869 struct btrfs_super_block *disk_super)
871 struct btrfs_fs_devices *fs_devices;
873 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
874 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
875 BTRFS_FSID_SIZE) != 0 &&
876 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
877 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
878 return fs_devices;
882 return NULL;
886 static struct btrfs_fs_devices *find_fsid_changed(
887 struct btrfs_super_block *disk_super)
889 struct btrfs_fs_devices *fs_devices;
892 * Handles the case where scanned device is part of an fs that had
893 * multiple successful changes of FSID but curently device didn't
894 * observe it. Meaning our fsid will be different than theirs.
896 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
897 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
898 BTRFS_FSID_SIZE) != 0 &&
899 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
900 BTRFS_FSID_SIZE) == 0 &&
901 memcmp(fs_devices->fsid, disk_super->fsid,
902 BTRFS_FSID_SIZE) != 0) {
903 return fs_devices;
907 return NULL;
910 * Add new device to list of registered devices
912 * Returns:
913 * device pointer which was just added or updated when successful
914 * error pointer when failed
916 static noinline struct btrfs_device *device_list_add(const char *path,
917 struct btrfs_super_block *disk_super,
918 bool *new_device_added)
920 struct btrfs_device *device;
921 struct btrfs_fs_devices *fs_devices = NULL;
922 struct rcu_string *name;
923 u64 found_transid = btrfs_super_generation(disk_super);
924 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
925 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
926 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
927 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
928 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
930 if (fsid_change_in_progress) {
931 if (!has_metadata_uuid) {
933 * When we have an image which has CHANGING_FSID_V2 set
934 * it might belong to either a filesystem which has
935 * disks with completed fsid change or it might belong
936 * to fs with no UUID changes in effect, handle both.
938 fs_devices = find_fsid_inprogress(disk_super);
939 if (!fs_devices)
940 fs_devices = find_fsid(disk_super->fsid, NULL);
941 } else {
942 fs_devices = find_fsid_changed(disk_super);
944 } else if (has_metadata_uuid) {
945 fs_devices = find_fsid(disk_super->fsid,
946 disk_super->metadata_uuid);
947 } else {
948 fs_devices = find_fsid(disk_super->fsid, NULL);
952 if (!fs_devices) {
953 if (has_metadata_uuid)
954 fs_devices = alloc_fs_devices(disk_super->fsid,
955 disk_super->metadata_uuid);
956 else
957 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
959 if (IS_ERR(fs_devices))
960 return ERR_CAST(fs_devices);
962 fs_devices->fsid_change = fsid_change_in_progress;
964 mutex_lock(&fs_devices->device_list_mutex);
965 list_add(&fs_devices->fs_list, &fs_uuids);
967 device = NULL;
968 } else {
969 mutex_lock(&fs_devices->device_list_mutex);
970 device = btrfs_find_device(fs_devices, devid,
971 disk_super->dev_item.uuid, NULL, false);
974 * If this disk has been pulled into an fs devices created by
975 * a device which had the CHANGING_FSID_V2 flag then replace the
976 * metadata_uuid/fsid values of the fs_devices.
978 if (has_metadata_uuid && fs_devices->fsid_change &&
979 found_transid > fs_devices->latest_generation) {
980 memcpy(fs_devices->fsid, disk_super->fsid,
981 BTRFS_FSID_SIZE);
982 memcpy(fs_devices->metadata_uuid,
983 disk_super->metadata_uuid, BTRFS_FSID_SIZE);
985 fs_devices->fsid_change = false;
989 if (!device) {
990 if (fs_devices->opened) {
991 mutex_unlock(&fs_devices->device_list_mutex);
992 return ERR_PTR(-EBUSY);
995 device = btrfs_alloc_device(NULL, &devid,
996 disk_super->dev_item.uuid);
997 if (IS_ERR(device)) {
998 mutex_unlock(&fs_devices->device_list_mutex);
999 /* we can safely leave the fs_devices entry around */
1000 return device;
1003 name = rcu_string_strdup(path, GFP_NOFS);
1004 if (!name) {
1005 btrfs_free_device(device);
1006 mutex_unlock(&fs_devices->device_list_mutex);
1007 return ERR_PTR(-ENOMEM);
1009 rcu_assign_pointer(device->name, name);
1011 list_add_rcu(&device->dev_list, &fs_devices->devices);
1012 fs_devices->num_devices++;
1014 device->fs_devices = fs_devices;
1015 *new_device_added = true;
1017 if (disk_super->label[0])
1018 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
1019 disk_super->label, devid, found_transid, path);
1020 else
1021 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
1022 disk_super->fsid, devid, found_transid, path);
1024 } else if (!device->name || strcmp(device->name->str, path)) {
1026 * When FS is already mounted.
1027 * 1. If you are here and if the device->name is NULL that
1028 * means this device was missing at time of FS mount.
1029 * 2. If you are here and if the device->name is different
1030 * from 'path' that means either
1031 * a. The same device disappeared and reappeared with
1032 * different name. or
1033 * b. The missing-disk-which-was-replaced, has
1034 * reappeared now.
1036 * We must allow 1 and 2a above. But 2b would be a spurious
1037 * and unintentional.
1039 * Further in case of 1 and 2a above, the disk at 'path'
1040 * would have missed some transaction when it was away and
1041 * in case of 2a the stale bdev has to be updated as well.
1042 * 2b must not be allowed at all time.
1046 * For now, we do allow update to btrfs_fs_device through the
1047 * btrfs dev scan cli after FS has been mounted. We're still
1048 * tracking a problem where systems fail mount by subvolume id
1049 * when we reject replacement on a mounted FS.
1051 if (!fs_devices->opened && found_transid < device->generation) {
1053 * That is if the FS is _not_ mounted and if you
1054 * are here, that means there is more than one
1055 * disk with same uuid and devid.We keep the one
1056 * with larger generation number or the last-in if
1057 * generation are equal.
1059 mutex_unlock(&fs_devices->device_list_mutex);
1060 return ERR_PTR(-EEXIST);
1064 * We are going to replace the device path for a given devid,
1065 * make sure it's the same device if the device is mounted
1067 if (device->bdev) {
1068 struct block_device *path_bdev;
1070 path_bdev = lookup_bdev(path);
1071 if (IS_ERR(path_bdev)) {
1072 mutex_unlock(&fs_devices->device_list_mutex);
1073 return ERR_CAST(path_bdev);
1076 if (device->bdev != path_bdev) {
1077 bdput(path_bdev);
1078 mutex_unlock(&fs_devices->device_list_mutex);
1079 btrfs_warn_in_rcu(device->fs_info,
1080 "duplicate device fsid:devid for %pU:%llu old:%s new:%s",
1081 disk_super->fsid, devid,
1082 rcu_str_deref(device->name), path);
1083 return ERR_PTR(-EEXIST);
1085 bdput(path_bdev);
1086 btrfs_info_in_rcu(device->fs_info,
1087 "device fsid %pU devid %llu moved old:%s new:%s",
1088 disk_super->fsid, devid,
1089 rcu_str_deref(device->name), path);
1092 name = rcu_string_strdup(path, GFP_NOFS);
1093 if (!name) {
1094 mutex_unlock(&fs_devices->device_list_mutex);
1095 return ERR_PTR(-ENOMEM);
1097 rcu_string_free(device->name);
1098 rcu_assign_pointer(device->name, name);
1099 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1100 fs_devices->missing_devices--;
1101 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1106 * Unmount does not free the btrfs_device struct but would zero
1107 * generation along with most of the other members. So just update
1108 * it back. We need it to pick the disk with largest generation
1109 * (as above).
1111 if (!fs_devices->opened) {
1112 device->generation = found_transid;
1113 fs_devices->latest_generation = max_t(u64, found_transid,
1114 fs_devices->latest_generation);
1117 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
1119 mutex_unlock(&fs_devices->device_list_mutex);
1120 return device;
1123 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
1125 struct btrfs_fs_devices *fs_devices;
1126 struct btrfs_device *device;
1127 struct btrfs_device *orig_dev;
1129 fs_devices = alloc_fs_devices(orig->fsid, NULL);
1130 if (IS_ERR(fs_devices))
1131 return fs_devices;
1133 mutex_lock(&orig->device_list_mutex);
1134 fs_devices->total_devices = orig->total_devices;
1136 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
1137 struct rcu_string *name;
1139 device = btrfs_alloc_device(NULL, &orig_dev->devid,
1140 orig_dev->uuid);
1141 if (IS_ERR(device))
1142 goto error;
1145 * This is ok to do without rcu read locked because we hold the
1146 * uuid mutex so nothing we touch in here is going to disappear.
1148 if (orig_dev->name) {
1149 name = rcu_string_strdup(orig_dev->name->str,
1150 GFP_KERNEL);
1151 if (!name) {
1152 btrfs_free_device(device);
1153 goto error;
1155 rcu_assign_pointer(device->name, name);
1158 list_add(&device->dev_list, &fs_devices->devices);
1159 device->fs_devices = fs_devices;
1160 fs_devices->num_devices++;
1162 mutex_unlock(&orig->device_list_mutex);
1163 return fs_devices;
1164 error:
1165 mutex_unlock(&orig->device_list_mutex);
1166 free_fs_devices(fs_devices);
1167 return ERR_PTR(-ENOMEM);
1171 * After we have read the system tree and know devids belonging to
1172 * this filesystem, remove the device which does not belong there.
1174 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
1176 struct btrfs_device *device, *next;
1177 struct btrfs_device *latest_dev = NULL;
1179 mutex_lock(&uuid_mutex);
1180 again:
1181 /* This is the initialized path, it is safe to release the devices. */
1182 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1183 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
1184 &device->dev_state)) {
1185 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1186 &device->dev_state) &&
1187 (!latest_dev ||
1188 device->generation > latest_dev->generation)) {
1189 latest_dev = device;
1191 continue;
1194 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
1196 * In the first step, keep the device which has
1197 * the correct fsid and the devid that is used
1198 * for the dev_replace procedure.
1199 * In the second step, the dev_replace state is
1200 * read from the device tree and it is known
1201 * whether the procedure is really active or
1202 * not, which means whether this device is
1203 * used or whether it should be removed.
1205 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1206 &device->dev_state)) {
1207 continue;
1210 if (device->bdev) {
1211 blkdev_put(device->bdev, device->mode);
1212 device->bdev = NULL;
1213 fs_devices->open_devices--;
1215 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1216 list_del_init(&device->dev_alloc_list);
1217 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1218 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1219 &device->dev_state))
1220 fs_devices->rw_devices--;
1222 list_del_init(&device->dev_list);
1223 fs_devices->num_devices--;
1224 btrfs_free_device(device);
1227 if (fs_devices->seed) {
1228 fs_devices = fs_devices->seed;
1229 goto again;
1232 fs_devices->latest_bdev = latest_dev->bdev;
1234 mutex_unlock(&uuid_mutex);
1237 static void btrfs_close_bdev(struct btrfs_device *device)
1239 if (!device->bdev)
1240 return;
1242 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1243 sync_blockdev(device->bdev);
1244 invalidate_bdev(device->bdev);
1247 blkdev_put(device->bdev, device->mode);
1250 static void btrfs_close_one_device(struct btrfs_device *device)
1252 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1253 struct btrfs_device *new_device;
1254 struct rcu_string *name;
1256 if (device->bdev)
1257 fs_devices->open_devices--;
1259 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1260 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1261 list_del_init(&device->dev_alloc_list);
1262 fs_devices->rw_devices--;
1265 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1266 fs_devices->missing_devices--;
1268 btrfs_close_bdev(device);
1270 new_device = btrfs_alloc_device(NULL, &device->devid,
1271 device->uuid);
1272 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1274 /* Safe because we are under uuid_mutex */
1275 if (device->name) {
1276 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1277 BUG_ON(!name); /* -ENOMEM */
1278 rcu_assign_pointer(new_device->name, name);
1281 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1282 new_device->fs_devices = device->fs_devices;
1284 synchronize_rcu();
1285 btrfs_free_device(device);
1288 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1290 struct btrfs_device *device, *tmp;
1292 if (--fs_devices->opened > 0)
1293 return 0;
1295 mutex_lock(&fs_devices->device_list_mutex);
1296 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1297 btrfs_close_one_device(device);
1299 mutex_unlock(&fs_devices->device_list_mutex);
1301 WARN_ON(fs_devices->open_devices);
1302 WARN_ON(fs_devices->rw_devices);
1303 fs_devices->opened = 0;
1304 fs_devices->seeding = 0;
1306 return 0;
1309 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1311 struct btrfs_fs_devices *seed_devices = NULL;
1312 int ret;
1314 mutex_lock(&uuid_mutex);
1315 ret = close_fs_devices(fs_devices);
1316 if (!fs_devices->opened) {
1317 seed_devices = fs_devices->seed;
1318 fs_devices->seed = NULL;
1320 mutex_unlock(&uuid_mutex);
1322 while (seed_devices) {
1323 fs_devices = seed_devices;
1324 seed_devices = fs_devices->seed;
1325 close_fs_devices(fs_devices);
1326 free_fs_devices(fs_devices);
1328 return ret;
1331 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1332 fmode_t flags, void *holder)
1334 struct btrfs_device *device;
1335 struct btrfs_device *latest_dev = NULL;
1336 int ret = 0;
1338 flags |= FMODE_EXCL;
1340 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1341 /* Just open everything we can; ignore failures here */
1342 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1343 continue;
1345 if (!latest_dev ||
1346 device->generation > latest_dev->generation)
1347 latest_dev = device;
1349 if (fs_devices->open_devices == 0) {
1350 ret = -EINVAL;
1351 goto out;
1353 fs_devices->opened = 1;
1354 fs_devices->latest_bdev = latest_dev->bdev;
1355 fs_devices->total_rw_bytes = 0;
1356 out:
1357 return ret;
1360 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1362 struct btrfs_device *dev1, *dev2;
1364 dev1 = list_entry(a, struct btrfs_device, dev_list);
1365 dev2 = list_entry(b, struct btrfs_device, dev_list);
1367 if (dev1->devid < dev2->devid)
1368 return -1;
1369 else if (dev1->devid > dev2->devid)
1370 return 1;
1371 return 0;
1374 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1375 fmode_t flags, void *holder)
1377 int ret;
1379 lockdep_assert_held(&uuid_mutex);
1381 mutex_lock(&fs_devices->device_list_mutex);
1382 if (fs_devices->opened) {
1383 fs_devices->opened++;
1384 ret = 0;
1385 } else {
1386 list_sort(NULL, &fs_devices->devices, devid_cmp);
1387 ret = open_fs_devices(fs_devices, flags, holder);
1389 mutex_unlock(&fs_devices->device_list_mutex);
1391 return ret;
1394 static void btrfs_release_disk_super(struct page *page)
1396 kunmap(page);
1397 put_page(page);
1400 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1401 struct page **page,
1402 struct btrfs_super_block **disk_super)
1404 void *p;
1405 pgoff_t index;
1407 /* make sure our super fits in the device */
1408 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1409 return 1;
1411 /* make sure our super fits in the page */
1412 if (sizeof(**disk_super) > PAGE_SIZE)
1413 return 1;
1415 /* make sure our super doesn't straddle pages on disk */
1416 index = bytenr >> PAGE_SHIFT;
1417 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1418 return 1;
1420 /* pull in the page with our super */
1421 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1422 index, GFP_KERNEL);
1424 if (IS_ERR_OR_NULL(*page))
1425 return 1;
1427 p = kmap(*page);
1429 /* align our pointer to the offset of the super block */
1430 *disk_super = p + offset_in_page(bytenr);
1432 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1433 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1434 btrfs_release_disk_super(*page);
1435 return 1;
1438 if ((*disk_super)->label[0] &&
1439 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1440 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1442 return 0;
1445 int btrfs_forget_devices(const char *path)
1447 int ret;
1449 mutex_lock(&uuid_mutex);
1450 ret = btrfs_free_stale_devices(strlen(path) ? path : NULL, NULL);
1451 mutex_unlock(&uuid_mutex);
1453 return ret;
1457 * Look for a btrfs signature on a device. This may be called out of the mount path
1458 * and we are not allowed to call set_blocksize during the scan. The superblock
1459 * is read via pagecache
1461 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1462 void *holder)
1464 struct btrfs_super_block *disk_super;
1465 bool new_device_added = false;
1466 struct btrfs_device *device = NULL;
1467 struct block_device *bdev;
1468 struct page *page;
1469 u64 bytenr;
1471 lockdep_assert_held(&uuid_mutex);
1474 * we would like to check all the supers, but that would make
1475 * a btrfs mount succeed after a mkfs from a different FS.
1476 * So, we need to add a special mount option to scan for
1477 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1479 bytenr = btrfs_sb_offset(0);
1480 flags |= FMODE_EXCL;
1482 bdev = blkdev_get_by_path(path, flags, holder);
1483 if (IS_ERR(bdev))
1484 return ERR_CAST(bdev);
1486 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1487 device = ERR_PTR(-EINVAL);
1488 goto error_bdev_put;
1491 device = device_list_add(path, disk_super, &new_device_added);
1492 if (!IS_ERR(device)) {
1493 if (new_device_added)
1494 btrfs_free_stale_devices(path, device);
1497 btrfs_release_disk_super(page);
1499 error_bdev_put:
1500 blkdev_put(bdev, flags);
1502 return device;
1506 * Try to find a chunk that intersects [start, start + len] range and when one
1507 * such is found, record the end of it in *start
1509 static bool contains_pending_extent(struct btrfs_device *device, u64 *start,
1510 u64 len)
1512 u64 physical_start, physical_end;
1514 lockdep_assert_held(&device->fs_info->chunk_mutex);
1516 if (!find_first_extent_bit(&device->alloc_state, *start,
1517 &physical_start, &physical_end,
1518 CHUNK_ALLOCATED, NULL)) {
1520 if (in_range(physical_start, *start, len) ||
1521 in_range(*start, physical_start,
1522 physical_end - physical_start)) {
1523 *start = physical_end + 1;
1524 return true;
1527 return false;
1532 * find_free_dev_extent_start - find free space in the specified device
1533 * @device: the device which we search the free space in
1534 * @num_bytes: the size of the free space that we need
1535 * @search_start: the position from which to begin the search
1536 * @start: store the start of the free space.
1537 * @len: the size of the free space. that we find, or the size
1538 * of the max free space if we don't find suitable free space
1540 * this uses a pretty simple search, the expectation is that it is
1541 * called very infrequently and that a given device has a small number
1542 * of extents
1544 * @start is used to store the start of the free space if we find. But if we
1545 * don't find suitable free space, it will be used to store the start position
1546 * of the max free space.
1548 * @len is used to store the size of the free space that we find.
1549 * But if we don't find suitable free space, it is used to store the size of
1550 * the max free space.
1552 int find_free_dev_extent_start(struct btrfs_device *device, u64 num_bytes,
1553 u64 search_start, u64 *start, u64 *len)
1555 struct btrfs_fs_info *fs_info = device->fs_info;
1556 struct btrfs_root *root = fs_info->dev_root;
1557 struct btrfs_key key;
1558 struct btrfs_dev_extent *dev_extent;
1559 struct btrfs_path *path;
1560 u64 hole_size;
1561 u64 max_hole_start;
1562 u64 max_hole_size;
1563 u64 extent_end;
1564 u64 search_end = device->total_bytes;
1565 int ret;
1566 int slot;
1567 struct extent_buffer *l;
1570 * We don't want to overwrite the superblock on the drive nor any area
1571 * used by the boot loader (grub for example), so we make sure to start
1572 * at an offset of at least 1MB.
1574 search_start = max_t(u64, search_start, SZ_1M);
1576 path = btrfs_alloc_path();
1577 if (!path)
1578 return -ENOMEM;
1580 max_hole_start = search_start;
1581 max_hole_size = 0;
1583 again:
1584 if (search_start >= search_end ||
1585 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1586 ret = -ENOSPC;
1587 goto out;
1590 path->reada = READA_FORWARD;
1591 path->search_commit_root = 1;
1592 path->skip_locking = 1;
1594 key.objectid = device->devid;
1595 key.offset = search_start;
1596 key.type = BTRFS_DEV_EXTENT_KEY;
1598 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1599 if (ret < 0)
1600 goto out;
1601 if (ret > 0) {
1602 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1603 if (ret < 0)
1604 goto out;
1607 while (1) {
1608 l = path->nodes[0];
1609 slot = path->slots[0];
1610 if (slot >= btrfs_header_nritems(l)) {
1611 ret = btrfs_next_leaf(root, path);
1612 if (ret == 0)
1613 continue;
1614 if (ret < 0)
1615 goto out;
1617 break;
1619 btrfs_item_key_to_cpu(l, &key, slot);
1621 if (key.objectid < device->devid)
1622 goto next;
1624 if (key.objectid > device->devid)
1625 break;
1627 if (key.type != BTRFS_DEV_EXTENT_KEY)
1628 goto next;
1630 if (key.offset > search_start) {
1631 hole_size = key.offset - search_start;
1634 * Have to check before we set max_hole_start, otherwise
1635 * we could end up sending back this offset anyway.
1637 if (contains_pending_extent(device, &search_start,
1638 hole_size)) {
1639 if (key.offset >= search_start)
1640 hole_size = key.offset - search_start;
1641 else
1642 hole_size = 0;
1645 if (hole_size > max_hole_size) {
1646 max_hole_start = search_start;
1647 max_hole_size = hole_size;
1651 * If this free space is greater than which we need,
1652 * it must be the max free space that we have found
1653 * until now, so max_hole_start must point to the start
1654 * of this free space and the length of this free space
1655 * is stored in max_hole_size. Thus, we return
1656 * max_hole_start and max_hole_size and go back to the
1657 * caller.
1659 if (hole_size >= num_bytes) {
1660 ret = 0;
1661 goto out;
1665 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1666 extent_end = key.offset + btrfs_dev_extent_length(l,
1667 dev_extent);
1668 if (extent_end > search_start)
1669 search_start = extent_end;
1670 next:
1671 path->slots[0]++;
1672 cond_resched();
1676 * At this point, search_start should be the end of
1677 * allocated dev extents, and when shrinking the device,
1678 * search_end may be smaller than search_start.
1680 if (search_end > search_start) {
1681 hole_size = search_end - search_start;
1683 if (contains_pending_extent(device, &search_start, hole_size)) {
1684 btrfs_release_path(path);
1685 goto again;
1688 if (hole_size > max_hole_size) {
1689 max_hole_start = search_start;
1690 max_hole_size = hole_size;
1694 /* See above. */
1695 if (max_hole_size < num_bytes)
1696 ret = -ENOSPC;
1697 else
1698 ret = 0;
1700 out:
1701 btrfs_free_path(path);
1702 *start = max_hole_start;
1703 if (len)
1704 *len = max_hole_size;
1705 return ret;
1708 int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
1709 u64 *start, u64 *len)
1711 /* FIXME use last free of some kind */
1712 return find_free_dev_extent_start(device, num_bytes, 0, start, len);
1715 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1716 struct btrfs_device *device,
1717 u64 start, u64 *dev_extent_len)
1719 struct btrfs_fs_info *fs_info = device->fs_info;
1720 struct btrfs_root *root = fs_info->dev_root;
1721 int ret;
1722 struct btrfs_path *path;
1723 struct btrfs_key key;
1724 struct btrfs_key found_key;
1725 struct extent_buffer *leaf = NULL;
1726 struct btrfs_dev_extent *extent = NULL;
1728 path = btrfs_alloc_path();
1729 if (!path)
1730 return -ENOMEM;
1732 key.objectid = device->devid;
1733 key.offset = start;
1734 key.type = BTRFS_DEV_EXTENT_KEY;
1735 again:
1736 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1737 if (ret > 0) {
1738 ret = btrfs_previous_item(root, path, key.objectid,
1739 BTRFS_DEV_EXTENT_KEY);
1740 if (ret)
1741 goto out;
1742 leaf = path->nodes[0];
1743 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1744 extent = btrfs_item_ptr(leaf, path->slots[0],
1745 struct btrfs_dev_extent);
1746 BUG_ON(found_key.offset > start || found_key.offset +
1747 btrfs_dev_extent_length(leaf, extent) < start);
1748 key = found_key;
1749 btrfs_release_path(path);
1750 goto again;
1751 } else if (ret == 0) {
1752 leaf = path->nodes[0];
1753 extent = btrfs_item_ptr(leaf, path->slots[0],
1754 struct btrfs_dev_extent);
1755 } else {
1756 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1757 goto out;
1760 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1762 ret = btrfs_del_item(trans, root, path);
1763 if (ret) {
1764 btrfs_handle_fs_error(fs_info, ret,
1765 "Failed to remove dev extent item");
1766 } else {
1767 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1769 out:
1770 btrfs_free_path(path);
1771 return ret;
1774 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1775 struct btrfs_device *device,
1776 u64 chunk_offset, u64 start, u64 num_bytes)
1778 int ret;
1779 struct btrfs_path *path;
1780 struct btrfs_fs_info *fs_info = device->fs_info;
1781 struct btrfs_root *root = fs_info->dev_root;
1782 struct btrfs_dev_extent *extent;
1783 struct extent_buffer *leaf;
1784 struct btrfs_key key;
1786 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1787 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1788 path = btrfs_alloc_path();
1789 if (!path)
1790 return -ENOMEM;
1792 key.objectid = device->devid;
1793 key.offset = start;
1794 key.type = BTRFS_DEV_EXTENT_KEY;
1795 ret = btrfs_insert_empty_item(trans, root, path, &key,
1796 sizeof(*extent));
1797 if (ret)
1798 goto out;
1800 leaf = path->nodes[0];
1801 extent = btrfs_item_ptr(leaf, path->slots[0],
1802 struct btrfs_dev_extent);
1803 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1804 BTRFS_CHUNK_TREE_OBJECTID);
1805 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1806 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1807 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1809 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1810 btrfs_mark_buffer_dirty(leaf);
1811 out:
1812 btrfs_free_path(path);
1813 return ret;
1816 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1818 struct extent_map_tree *em_tree;
1819 struct extent_map *em;
1820 struct rb_node *n;
1821 u64 ret = 0;
1823 em_tree = &fs_info->mapping_tree;
1824 read_lock(&em_tree->lock);
1825 n = rb_last(&em_tree->map.rb_root);
1826 if (n) {
1827 em = rb_entry(n, struct extent_map, rb_node);
1828 ret = em->start + em->len;
1830 read_unlock(&em_tree->lock);
1832 return ret;
1835 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1836 u64 *devid_ret)
1838 int ret;
1839 struct btrfs_key key;
1840 struct btrfs_key found_key;
1841 struct btrfs_path *path;
1843 path = btrfs_alloc_path();
1844 if (!path)
1845 return -ENOMEM;
1847 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1848 key.type = BTRFS_DEV_ITEM_KEY;
1849 key.offset = (u64)-1;
1851 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1852 if (ret < 0)
1853 goto error;
1855 BUG_ON(ret == 0); /* Corruption */
1857 ret = btrfs_previous_item(fs_info->chunk_root, path,
1858 BTRFS_DEV_ITEMS_OBJECTID,
1859 BTRFS_DEV_ITEM_KEY);
1860 if (ret) {
1861 *devid_ret = 1;
1862 } else {
1863 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1864 path->slots[0]);
1865 *devid_ret = found_key.offset + 1;
1867 ret = 0;
1868 error:
1869 btrfs_free_path(path);
1870 return ret;
1874 * the device information is stored in the chunk root
1875 * the btrfs_device struct should be fully filled in
1877 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1878 struct btrfs_device *device)
1880 int ret;
1881 struct btrfs_path *path;
1882 struct btrfs_dev_item *dev_item;
1883 struct extent_buffer *leaf;
1884 struct btrfs_key key;
1885 unsigned long ptr;
1887 path = btrfs_alloc_path();
1888 if (!path)
1889 return -ENOMEM;
1891 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1892 key.type = BTRFS_DEV_ITEM_KEY;
1893 key.offset = device->devid;
1895 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1896 &key, sizeof(*dev_item));
1897 if (ret)
1898 goto out;
1900 leaf = path->nodes[0];
1901 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1903 btrfs_set_device_id(leaf, dev_item, device->devid);
1904 btrfs_set_device_generation(leaf, dev_item, 0);
1905 btrfs_set_device_type(leaf, dev_item, device->type);
1906 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1907 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1908 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1909 btrfs_set_device_total_bytes(leaf, dev_item,
1910 btrfs_device_get_disk_total_bytes(device));
1911 btrfs_set_device_bytes_used(leaf, dev_item,
1912 btrfs_device_get_bytes_used(device));
1913 btrfs_set_device_group(leaf, dev_item, 0);
1914 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1915 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1916 btrfs_set_device_start_offset(leaf, dev_item, 0);
1918 ptr = btrfs_device_uuid(dev_item);
1919 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1920 ptr = btrfs_device_fsid(dev_item);
1921 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1922 ptr, BTRFS_FSID_SIZE);
1923 btrfs_mark_buffer_dirty(leaf);
1925 ret = 0;
1926 out:
1927 btrfs_free_path(path);
1928 return ret;
1932 * Function to update ctime/mtime for a given device path.
1933 * Mainly used for ctime/mtime based probe like libblkid.
1935 static void update_dev_time(const char *path_name)
1937 struct file *filp;
1939 filp = filp_open(path_name, O_RDWR, 0);
1940 if (IS_ERR(filp))
1941 return;
1942 file_update_time(filp);
1943 filp_close(filp, NULL);
1946 static int btrfs_rm_dev_item(struct btrfs_device *device)
1948 struct btrfs_root *root = device->fs_info->chunk_root;
1949 int ret;
1950 struct btrfs_path *path;
1951 struct btrfs_key key;
1952 struct btrfs_trans_handle *trans;
1954 path = btrfs_alloc_path();
1955 if (!path)
1956 return -ENOMEM;
1958 trans = btrfs_start_transaction(root, 0);
1959 if (IS_ERR(trans)) {
1960 btrfs_free_path(path);
1961 return PTR_ERR(trans);
1963 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1964 key.type = BTRFS_DEV_ITEM_KEY;
1965 key.offset = device->devid;
1967 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1968 if (ret) {
1969 if (ret > 0)
1970 ret = -ENOENT;
1971 btrfs_abort_transaction(trans, ret);
1972 btrfs_end_transaction(trans);
1973 goto out;
1976 ret = btrfs_del_item(trans, root, path);
1977 if (ret) {
1978 btrfs_abort_transaction(trans, ret);
1979 btrfs_end_transaction(trans);
1982 out:
1983 btrfs_free_path(path);
1984 if (!ret)
1985 ret = btrfs_commit_transaction(trans);
1986 return ret;
1990 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1991 * filesystem. It's up to the caller to adjust that number regarding eg. device
1992 * replace.
1994 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1995 u64 num_devices)
1997 u64 all_avail;
1998 unsigned seq;
1999 int i;
2001 do {
2002 seq = read_seqbegin(&fs_info->profiles_lock);
2004 all_avail = fs_info->avail_data_alloc_bits |
2005 fs_info->avail_system_alloc_bits |
2006 fs_info->avail_metadata_alloc_bits;
2007 } while (read_seqretry(&fs_info->profiles_lock, seq));
2009 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2010 if (!(all_avail & btrfs_raid_array[i].bg_flag))
2011 continue;
2013 if (num_devices < btrfs_raid_array[i].devs_min) {
2014 int ret = btrfs_raid_array[i].mindev_error;
2016 if (ret)
2017 return ret;
2021 return 0;
2024 static struct btrfs_device * btrfs_find_next_active_device(
2025 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
2027 struct btrfs_device *next_device;
2029 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
2030 if (next_device != device &&
2031 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
2032 && next_device->bdev)
2033 return next_device;
2036 return NULL;
2040 * Helper function to check if the given device is part of s_bdev / latest_bdev
2041 * and replace it with the provided or the next active device, in the context
2042 * where this function called, there should be always be another device (or
2043 * this_dev) which is active.
2045 void btrfs_assign_next_active_device(struct btrfs_device *device,
2046 struct btrfs_device *this_dev)
2048 struct btrfs_fs_info *fs_info = device->fs_info;
2049 struct btrfs_device *next_device;
2051 if (this_dev)
2052 next_device = this_dev;
2053 else
2054 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
2055 device);
2056 ASSERT(next_device);
2058 if (fs_info->sb->s_bdev &&
2059 (fs_info->sb->s_bdev == device->bdev))
2060 fs_info->sb->s_bdev = next_device->bdev;
2062 if (fs_info->fs_devices->latest_bdev == device->bdev)
2063 fs_info->fs_devices->latest_bdev = next_device->bdev;
2067 * Return btrfs_fs_devices::num_devices excluding the device that's being
2068 * currently replaced.
2070 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
2072 u64 num_devices = fs_info->fs_devices->num_devices;
2074 down_read(&fs_info->dev_replace.rwsem);
2075 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
2076 ASSERT(num_devices > 1);
2077 num_devices--;
2079 up_read(&fs_info->dev_replace.rwsem);
2081 return num_devices;
2084 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
2085 u64 devid)
2087 struct btrfs_device *device;
2088 struct btrfs_fs_devices *cur_devices;
2089 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2090 u64 num_devices;
2091 int ret = 0;
2093 mutex_lock(&uuid_mutex);
2095 num_devices = btrfs_num_devices(fs_info);
2097 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2098 if (ret)
2099 goto out;
2101 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
2103 if (IS_ERR(device)) {
2104 if (PTR_ERR(device) == -ENOENT &&
2105 strcmp(device_path, "missing") == 0)
2106 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2107 else
2108 ret = PTR_ERR(device);
2109 goto out;
2112 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2113 btrfs_warn_in_rcu(fs_info,
2114 "cannot remove device %s (devid %llu) due to active swapfile",
2115 rcu_str_deref(device->name), device->devid);
2116 ret = -ETXTBSY;
2117 goto out;
2120 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2121 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
2122 goto out;
2125 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2126 fs_info->fs_devices->rw_devices == 1) {
2127 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
2128 goto out;
2131 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2132 mutex_lock(&fs_info->chunk_mutex);
2133 list_del_init(&device->dev_alloc_list);
2134 device->fs_devices->rw_devices--;
2135 mutex_unlock(&fs_info->chunk_mutex);
2138 mutex_unlock(&uuid_mutex);
2139 ret = btrfs_shrink_device(device, 0);
2140 mutex_lock(&uuid_mutex);
2141 if (ret)
2142 goto error_undo;
2145 * TODO: the superblock still includes this device in its num_devices
2146 * counter although write_all_supers() is not locked out. This
2147 * could give a filesystem state which requires a degraded mount.
2149 ret = btrfs_rm_dev_item(device);
2150 if (ret)
2151 goto error_undo;
2153 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2154 btrfs_scrub_cancel_dev(device);
2157 * the device list mutex makes sure that we don't change
2158 * the device list while someone else is writing out all
2159 * the device supers. Whoever is writing all supers, should
2160 * lock the device list mutex before getting the number of
2161 * devices in the super block (super_copy). Conversely,
2162 * whoever updates the number of devices in the super block
2163 * (super_copy) should hold the device list mutex.
2167 * In normal cases the cur_devices == fs_devices. But in case
2168 * of deleting a seed device, the cur_devices should point to
2169 * its own fs_devices listed under the fs_devices->seed.
2171 cur_devices = device->fs_devices;
2172 mutex_lock(&fs_devices->device_list_mutex);
2173 list_del_rcu(&device->dev_list);
2175 cur_devices->num_devices--;
2176 cur_devices->total_devices--;
2177 /* Update total_devices of the parent fs_devices if it's seed */
2178 if (cur_devices != fs_devices)
2179 fs_devices->total_devices--;
2181 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2182 cur_devices->missing_devices--;
2184 btrfs_assign_next_active_device(device, NULL);
2186 if (device->bdev) {
2187 cur_devices->open_devices--;
2188 /* remove sysfs entry */
2189 btrfs_sysfs_rm_device_link(fs_devices, device);
2192 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2193 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2194 mutex_unlock(&fs_devices->device_list_mutex);
2197 * at this point, the device is zero sized and detached from
2198 * the devices list. All that's left is to zero out the old
2199 * supers and free the device.
2201 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2202 btrfs_scratch_superblocks(device->bdev, device->name->str);
2204 btrfs_close_bdev(device);
2205 synchronize_rcu();
2206 btrfs_free_device(device);
2208 if (cur_devices->open_devices == 0) {
2209 while (fs_devices) {
2210 if (fs_devices->seed == cur_devices) {
2211 fs_devices->seed = cur_devices->seed;
2212 break;
2214 fs_devices = fs_devices->seed;
2216 cur_devices->seed = NULL;
2217 close_fs_devices(cur_devices);
2218 free_fs_devices(cur_devices);
2221 out:
2222 mutex_unlock(&uuid_mutex);
2223 return ret;
2225 error_undo:
2226 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2227 mutex_lock(&fs_info->chunk_mutex);
2228 list_add(&device->dev_alloc_list,
2229 &fs_devices->alloc_list);
2230 device->fs_devices->rw_devices++;
2231 mutex_unlock(&fs_info->chunk_mutex);
2233 goto out;
2236 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2238 struct btrfs_fs_devices *fs_devices;
2240 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2243 * in case of fs with no seed, srcdev->fs_devices will point
2244 * to fs_devices of fs_info. However when the dev being replaced is
2245 * a seed dev it will point to the seed's local fs_devices. In short
2246 * srcdev will have its correct fs_devices in both the cases.
2248 fs_devices = srcdev->fs_devices;
2250 list_del_rcu(&srcdev->dev_list);
2251 list_del(&srcdev->dev_alloc_list);
2252 fs_devices->num_devices--;
2253 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2254 fs_devices->missing_devices--;
2256 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2257 fs_devices->rw_devices--;
2259 if (srcdev->bdev)
2260 fs_devices->open_devices--;
2263 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2265 struct btrfs_fs_info *fs_info = srcdev->fs_info;
2266 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2268 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2269 /* zero out the old super if it is writable */
2270 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2273 btrfs_close_bdev(srcdev);
2274 synchronize_rcu();
2275 btrfs_free_device(srcdev);
2277 /* if this is no devs we rather delete the fs_devices */
2278 if (!fs_devices->num_devices) {
2279 struct btrfs_fs_devices *tmp_fs_devices;
2282 * On a mounted FS, num_devices can't be zero unless it's a
2283 * seed. In case of a seed device being replaced, the replace
2284 * target added to the sprout FS, so there will be no more
2285 * device left under the seed FS.
2287 ASSERT(fs_devices->seeding);
2289 tmp_fs_devices = fs_info->fs_devices;
2290 while (tmp_fs_devices) {
2291 if (tmp_fs_devices->seed == fs_devices) {
2292 tmp_fs_devices->seed = fs_devices->seed;
2293 break;
2295 tmp_fs_devices = tmp_fs_devices->seed;
2297 fs_devices->seed = NULL;
2298 close_fs_devices(fs_devices);
2299 free_fs_devices(fs_devices);
2303 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2305 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2307 WARN_ON(!tgtdev);
2308 mutex_lock(&fs_devices->device_list_mutex);
2310 btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2312 if (tgtdev->bdev)
2313 fs_devices->open_devices--;
2315 fs_devices->num_devices--;
2317 btrfs_assign_next_active_device(tgtdev, NULL);
2319 list_del_rcu(&tgtdev->dev_list);
2321 mutex_unlock(&fs_devices->device_list_mutex);
2324 * The update_dev_time() with in btrfs_scratch_superblocks()
2325 * may lead to a call to btrfs_show_devname() which will try
2326 * to hold device_list_mutex. And here this device
2327 * is already out of device list, so we don't have to hold
2328 * the device_list_mutex lock.
2330 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2332 btrfs_close_bdev(tgtdev);
2333 synchronize_rcu();
2334 btrfs_free_device(tgtdev);
2337 static struct btrfs_device *btrfs_find_device_by_path(
2338 struct btrfs_fs_info *fs_info, const char *device_path)
2340 int ret = 0;
2341 struct btrfs_super_block *disk_super;
2342 u64 devid;
2343 u8 *dev_uuid;
2344 struct block_device *bdev;
2345 struct buffer_head *bh;
2346 struct btrfs_device *device;
2348 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2349 fs_info->bdev_holder, 0, &bdev, &bh);
2350 if (ret)
2351 return ERR_PTR(ret);
2352 disk_super = (struct btrfs_super_block *)bh->b_data;
2353 devid = btrfs_stack_device_id(&disk_super->dev_item);
2354 dev_uuid = disk_super->dev_item.uuid;
2355 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2356 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2357 disk_super->metadata_uuid, true);
2358 else
2359 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2360 disk_super->fsid, true);
2362 brelse(bh);
2363 if (!device)
2364 device = ERR_PTR(-ENOENT);
2365 blkdev_put(bdev, FMODE_READ);
2366 return device;
2370 * Lookup a device given by device id, or the path if the id is 0.
2372 struct btrfs_device *btrfs_find_device_by_devspec(
2373 struct btrfs_fs_info *fs_info, u64 devid,
2374 const char *device_path)
2376 struct btrfs_device *device;
2378 if (devid) {
2379 device = btrfs_find_device(fs_info->fs_devices, devid, NULL,
2380 NULL, true);
2381 if (!device)
2382 return ERR_PTR(-ENOENT);
2383 return device;
2386 if (!device_path || !device_path[0])
2387 return ERR_PTR(-EINVAL);
2389 if (strcmp(device_path, "missing") == 0) {
2390 /* Find first missing device */
2391 list_for_each_entry(device, &fs_info->fs_devices->devices,
2392 dev_list) {
2393 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2394 &device->dev_state) && !device->bdev)
2395 return device;
2397 return ERR_PTR(-ENOENT);
2400 return btrfs_find_device_by_path(fs_info, device_path);
2404 * does all the dirty work required for changing file system's UUID.
2406 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2408 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2409 struct btrfs_fs_devices *old_devices;
2410 struct btrfs_fs_devices *seed_devices;
2411 struct btrfs_super_block *disk_super = fs_info->super_copy;
2412 struct btrfs_device *device;
2413 u64 super_flags;
2415 lockdep_assert_held(&uuid_mutex);
2416 if (!fs_devices->seeding)
2417 return -EINVAL;
2419 seed_devices = alloc_fs_devices(NULL, NULL);
2420 if (IS_ERR(seed_devices))
2421 return PTR_ERR(seed_devices);
2423 old_devices = clone_fs_devices(fs_devices);
2424 if (IS_ERR(old_devices)) {
2425 kfree(seed_devices);
2426 return PTR_ERR(old_devices);
2429 list_add(&old_devices->fs_list, &fs_uuids);
2431 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2432 seed_devices->opened = 1;
2433 INIT_LIST_HEAD(&seed_devices->devices);
2434 INIT_LIST_HEAD(&seed_devices->alloc_list);
2435 mutex_init(&seed_devices->device_list_mutex);
2437 mutex_lock(&fs_devices->device_list_mutex);
2438 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2439 synchronize_rcu);
2440 list_for_each_entry(device, &seed_devices->devices, dev_list)
2441 device->fs_devices = seed_devices;
2443 mutex_lock(&fs_info->chunk_mutex);
2444 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2445 mutex_unlock(&fs_info->chunk_mutex);
2447 fs_devices->seeding = 0;
2448 fs_devices->num_devices = 0;
2449 fs_devices->open_devices = 0;
2450 fs_devices->missing_devices = 0;
2451 fs_devices->rotating = 0;
2452 fs_devices->seed = seed_devices;
2454 generate_random_uuid(fs_devices->fsid);
2455 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2456 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2457 mutex_unlock(&fs_devices->device_list_mutex);
2459 super_flags = btrfs_super_flags(disk_super) &
2460 ~BTRFS_SUPER_FLAG_SEEDING;
2461 btrfs_set_super_flags(disk_super, super_flags);
2463 return 0;
2467 * Store the expected generation for seed devices in device items.
2469 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2471 struct btrfs_fs_info *fs_info = trans->fs_info;
2472 struct btrfs_root *root = fs_info->chunk_root;
2473 struct btrfs_path *path;
2474 struct extent_buffer *leaf;
2475 struct btrfs_dev_item *dev_item;
2476 struct btrfs_device *device;
2477 struct btrfs_key key;
2478 u8 fs_uuid[BTRFS_FSID_SIZE];
2479 u8 dev_uuid[BTRFS_UUID_SIZE];
2480 u64 devid;
2481 int ret;
2483 path = btrfs_alloc_path();
2484 if (!path)
2485 return -ENOMEM;
2487 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2488 key.offset = 0;
2489 key.type = BTRFS_DEV_ITEM_KEY;
2491 while (1) {
2492 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2493 if (ret < 0)
2494 goto error;
2496 leaf = path->nodes[0];
2497 next_slot:
2498 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2499 ret = btrfs_next_leaf(root, path);
2500 if (ret > 0)
2501 break;
2502 if (ret < 0)
2503 goto error;
2504 leaf = path->nodes[0];
2505 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2506 btrfs_release_path(path);
2507 continue;
2510 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2511 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2512 key.type != BTRFS_DEV_ITEM_KEY)
2513 break;
2515 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2516 struct btrfs_dev_item);
2517 devid = btrfs_device_id(leaf, dev_item);
2518 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2519 BTRFS_UUID_SIZE);
2520 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2521 BTRFS_FSID_SIZE);
2522 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2523 fs_uuid, true);
2524 BUG_ON(!device); /* Logic error */
2526 if (device->fs_devices->seeding) {
2527 btrfs_set_device_generation(leaf, dev_item,
2528 device->generation);
2529 btrfs_mark_buffer_dirty(leaf);
2532 path->slots[0]++;
2533 goto next_slot;
2535 ret = 0;
2536 error:
2537 btrfs_free_path(path);
2538 return ret;
2541 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2543 struct btrfs_root *root = fs_info->dev_root;
2544 struct request_queue *q;
2545 struct btrfs_trans_handle *trans;
2546 struct btrfs_device *device;
2547 struct block_device *bdev;
2548 struct super_block *sb = fs_info->sb;
2549 struct rcu_string *name;
2550 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2551 u64 orig_super_total_bytes;
2552 u64 orig_super_num_devices;
2553 int seeding_dev = 0;
2554 int ret = 0;
2555 bool unlocked = false;
2557 if (sb_rdonly(sb) && !fs_devices->seeding)
2558 return -EROFS;
2560 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2561 fs_info->bdev_holder);
2562 if (IS_ERR(bdev))
2563 return PTR_ERR(bdev);
2565 if (fs_devices->seeding) {
2566 seeding_dev = 1;
2567 down_write(&sb->s_umount);
2568 mutex_lock(&uuid_mutex);
2571 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2573 mutex_lock(&fs_devices->device_list_mutex);
2574 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2575 if (device->bdev == bdev) {
2576 ret = -EEXIST;
2577 mutex_unlock(
2578 &fs_devices->device_list_mutex);
2579 goto error;
2582 mutex_unlock(&fs_devices->device_list_mutex);
2584 device = btrfs_alloc_device(fs_info, NULL, NULL);
2585 if (IS_ERR(device)) {
2586 /* we can safely leave the fs_devices entry around */
2587 ret = PTR_ERR(device);
2588 goto error;
2591 name = rcu_string_strdup(device_path, GFP_KERNEL);
2592 if (!name) {
2593 ret = -ENOMEM;
2594 goto error_free_device;
2596 rcu_assign_pointer(device->name, name);
2598 trans = btrfs_start_transaction(root, 0);
2599 if (IS_ERR(trans)) {
2600 ret = PTR_ERR(trans);
2601 goto error_free_device;
2604 q = bdev_get_queue(bdev);
2605 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2606 device->generation = trans->transid;
2607 device->io_width = fs_info->sectorsize;
2608 device->io_align = fs_info->sectorsize;
2609 device->sector_size = fs_info->sectorsize;
2610 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2611 fs_info->sectorsize);
2612 device->disk_total_bytes = device->total_bytes;
2613 device->commit_total_bytes = device->total_bytes;
2614 device->fs_info = fs_info;
2615 device->bdev = bdev;
2616 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2617 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2618 device->mode = FMODE_EXCL;
2619 device->dev_stats_valid = 1;
2620 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2622 if (seeding_dev) {
2623 sb->s_flags &= ~SB_RDONLY;
2624 ret = btrfs_prepare_sprout(fs_info);
2625 if (ret) {
2626 btrfs_abort_transaction(trans, ret);
2627 goto error_trans;
2631 device->fs_devices = fs_devices;
2633 mutex_lock(&fs_devices->device_list_mutex);
2634 mutex_lock(&fs_info->chunk_mutex);
2635 list_add_rcu(&device->dev_list, &fs_devices->devices);
2636 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2637 fs_devices->num_devices++;
2638 fs_devices->open_devices++;
2639 fs_devices->rw_devices++;
2640 fs_devices->total_devices++;
2641 fs_devices->total_rw_bytes += device->total_bytes;
2643 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2645 if (!blk_queue_nonrot(q))
2646 fs_devices->rotating = 1;
2648 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2649 btrfs_set_super_total_bytes(fs_info->super_copy,
2650 round_down(orig_super_total_bytes + device->total_bytes,
2651 fs_info->sectorsize));
2653 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2654 btrfs_set_super_num_devices(fs_info->super_copy,
2655 orig_super_num_devices + 1);
2657 /* add sysfs device entry */
2658 btrfs_sysfs_add_device_link(fs_devices, device);
2661 * we've got more storage, clear any full flags on the space
2662 * infos
2664 btrfs_clear_space_info_full(fs_info);
2666 mutex_unlock(&fs_info->chunk_mutex);
2667 mutex_unlock(&fs_devices->device_list_mutex);
2669 if (seeding_dev) {
2670 mutex_lock(&fs_info->chunk_mutex);
2671 ret = init_first_rw_device(trans);
2672 mutex_unlock(&fs_info->chunk_mutex);
2673 if (ret) {
2674 btrfs_abort_transaction(trans, ret);
2675 goto error_sysfs;
2679 ret = btrfs_add_dev_item(trans, device);
2680 if (ret) {
2681 btrfs_abort_transaction(trans, ret);
2682 goto error_sysfs;
2685 if (seeding_dev) {
2686 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2688 ret = btrfs_finish_sprout(trans);
2689 if (ret) {
2690 btrfs_abort_transaction(trans, ret);
2691 goto error_sysfs;
2694 /* Sprouting would change fsid of the mounted root,
2695 * so rename the fsid on the sysfs
2697 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2698 fs_info->fs_devices->fsid);
2699 if (kobject_rename(&fs_devices->fsid_kobj, fsid_buf))
2700 btrfs_warn(fs_info,
2701 "sysfs: failed to create fsid for sprout");
2704 ret = btrfs_commit_transaction(trans);
2706 if (seeding_dev) {
2707 mutex_unlock(&uuid_mutex);
2708 up_write(&sb->s_umount);
2709 unlocked = true;
2711 if (ret) /* transaction commit */
2712 return ret;
2714 ret = btrfs_relocate_sys_chunks(fs_info);
2715 if (ret < 0)
2716 btrfs_handle_fs_error(fs_info, ret,
2717 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2718 trans = btrfs_attach_transaction(root);
2719 if (IS_ERR(trans)) {
2720 if (PTR_ERR(trans) == -ENOENT)
2721 return 0;
2722 ret = PTR_ERR(trans);
2723 trans = NULL;
2724 goto error_sysfs;
2726 ret = btrfs_commit_transaction(trans);
2729 /* Update ctime/mtime for libblkid */
2730 update_dev_time(device_path);
2731 return ret;
2733 error_sysfs:
2734 btrfs_sysfs_rm_device_link(fs_devices, device);
2735 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2736 mutex_lock(&fs_info->chunk_mutex);
2737 list_del_rcu(&device->dev_list);
2738 list_del(&device->dev_alloc_list);
2739 fs_info->fs_devices->num_devices--;
2740 fs_info->fs_devices->open_devices--;
2741 fs_info->fs_devices->rw_devices--;
2742 fs_info->fs_devices->total_devices--;
2743 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2744 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2745 btrfs_set_super_total_bytes(fs_info->super_copy,
2746 orig_super_total_bytes);
2747 btrfs_set_super_num_devices(fs_info->super_copy,
2748 orig_super_num_devices);
2749 mutex_unlock(&fs_info->chunk_mutex);
2750 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2751 error_trans:
2752 if (seeding_dev)
2753 sb->s_flags |= SB_RDONLY;
2754 if (trans)
2755 btrfs_end_transaction(trans);
2756 error_free_device:
2757 btrfs_free_device(device);
2758 error:
2759 blkdev_put(bdev, FMODE_EXCL);
2760 if (seeding_dev && !unlocked) {
2761 mutex_unlock(&uuid_mutex);
2762 up_write(&sb->s_umount);
2764 return ret;
2767 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2768 struct btrfs_device *device)
2770 int ret;
2771 struct btrfs_path *path;
2772 struct btrfs_root *root = device->fs_info->chunk_root;
2773 struct btrfs_dev_item *dev_item;
2774 struct extent_buffer *leaf;
2775 struct btrfs_key key;
2777 path = btrfs_alloc_path();
2778 if (!path)
2779 return -ENOMEM;
2781 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2782 key.type = BTRFS_DEV_ITEM_KEY;
2783 key.offset = device->devid;
2785 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2786 if (ret < 0)
2787 goto out;
2789 if (ret > 0) {
2790 ret = -ENOENT;
2791 goto out;
2794 leaf = path->nodes[0];
2795 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2797 btrfs_set_device_id(leaf, dev_item, device->devid);
2798 btrfs_set_device_type(leaf, dev_item, device->type);
2799 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2800 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2801 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2802 btrfs_set_device_total_bytes(leaf, dev_item,
2803 btrfs_device_get_disk_total_bytes(device));
2804 btrfs_set_device_bytes_used(leaf, dev_item,
2805 btrfs_device_get_bytes_used(device));
2806 btrfs_mark_buffer_dirty(leaf);
2808 out:
2809 btrfs_free_path(path);
2810 return ret;
2813 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2814 struct btrfs_device *device, u64 new_size)
2816 struct btrfs_fs_info *fs_info = device->fs_info;
2817 struct btrfs_super_block *super_copy = fs_info->super_copy;
2818 u64 old_total;
2819 u64 diff;
2821 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2822 return -EACCES;
2824 new_size = round_down(new_size, fs_info->sectorsize);
2826 mutex_lock(&fs_info->chunk_mutex);
2827 old_total = btrfs_super_total_bytes(super_copy);
2828 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2830 if (new_size <= device->total_bytes ||
2831 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2832 mutex_unlock(&fs_info->chunk_mutex);
2833 return -EINVAL;
2836 btrfs_set_super_total_bytes(super_copy,
2837 round_down(old_total + diff, fs_info->sectorsize));
2838 device->fs_devices->total_rw_bytes += diff;
2840 btrfs_device_set_total_bytes(device, new_size);
2841 btrfs_device_set_disk_total_bytes(device, new_size);
2842 btrfs_clear_space_info_full(device->fs_info);
2843 if (list_empty(&device->post_commit_list))
2844 list_add_tail(&device->post_commit_list,
2845 &trans->transaction->dev_update_list);
2846 mutex_unlock(&fs_info->chunk_mutex);
2848 return btrfs_update_device(trans, device);
2851 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2853 struct btrfs_fs_info *fs_info = trans->fs_info;
2854 struct btrfs_root *root = fs_info->chunk_root;
2855 int ret;
2856 struct btrfs_path *path;
2857 struct btrfs_key key;
2859 path = btrfs_alloc_path();
2860 if (!path)
2861 return -ENOMEM;
2863 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2864 key.offset = chunk_offset;
2865 key.type = BTRFS_CHUNK_ITEM_KEY;
2867 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2868 if (ret < 0)
2869 goto out;
2870 else if (ret > 0) { /* Logic error or corruption */
2871 btrfs_handle_fs_error(fs_info, -ENOENT,
2872 "Failed lookup while freeing chunk.");
2873 ret = -ENOENT;
2874 goto out;
2877 ret = btrfs_del_item(trans, root, path);
2878 if (ret < 0)
2879 btrfs_handle_fs_error(fs_info, ret,
2880 "Failed to delete chunk item.");
2881 out:
2882 btrfs_free_path(path);
2883 return ret;
2886 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2888 struct btrfs_super_block *super_copy = fs_info->super_copy;
2889 struct btrfs_disk_key *disk_key;
2890 struct btrfs_chunk *chunk;
2891 u8 *ptr;
2892 int ret = 0;
2893 u32 num_stripes;
2894 u32 array_size;
2895 u32 len = 0;
2896 u32 cur;
2897 struct btrfs_key key;
2899 mutex_lock(&fs_info->chunk_mutex);
2900 array_size = btrfs_super_sys_array_size(super_copy);
2902 ptr = super_copy->sys_chunk_array;
2903 cur = 0;
2905 while (cur < array_size) {
2906 disk_key = (struct btrfs_disk_key *)ptr;
2907 btrfs_disk_key_to_cpu(&key, disk_key);
2909 len = sizeof(*disk_key);
2911 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2912 chunk = (struct btrfs_chunk *)(ptr + len);
2913 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2914 len += btrfs_chunk_item_size(num_stripes);
2915 } else {
2916 ret = -EIO;
2917 break;
2919 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2920 key.offset == chunk_offset) {
2921 memmove(ptr, ptr + len, array_size - (cur + len));
2922 array_size -= len;
2923 btrfs_set_super_sys_array_size(super_copy, array_size);
2924 } else {
2925 ptr += len;
2926 cur += len;
2929 mutex_unlock(&fs_info->chunk_mutex);
2930 return ret;
2934 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2935 * @logical: Logical block offset in bytes.
2936 * @length: Length of extent in bytes.
2938 * Return: Chunk mapping or ERR_PTR.
2940 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2941 u64 logical, u64 length)
2943 struct extent_map_tree *em_tree;
2944 struct extent_map *em;
2946 em_tree = &fs_info->mapping_tree;
2947 read_lock(&em_tree->lock);
2948 em = lookup_extent_mapping(em_tree, logical, length);
2949 read_unlock(&em_tree->lock);
2951 if (!em) {
2952 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2953 logical, length);
2954 return ERR_PTR(-EINVAL);
2957 if (em->start > logical || em->start + em->len < logical) {
2958 btrfs_crit(fs_info,
2959 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2960 logical, length, em->start, em->start + em->len);
2961 free_extent_map(em);
2962 return ERR_PTR(-EINVAL);
2965 /* callers are responsible for dropping em's ref. */
2966 return em;
2969 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2971 struct btrfs_fs_info *fs_info = trans->fs_info;
2972 struct extent_map *em;
2973 struct map_lookup *map;
2974 u64 dev_extent_len = 0;
2975 int i, ret = 0;
2976 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2978 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
2979 if (IS_ERR(em)) {
2981 * This is a logic error, but we don't want to just rely on the
2982 * user having built with ASSERT enabled, so if ASSERT doesn't
2983 * do anything we still error out.
2985 ASSERT(0);
2986 return PTR_ERR(em);
2988 map = em->map_lookup;
2989 mutex_lock(&fs_info->chunk_mutex);
2990 check_system_chunk(trans, map->type);
2991 mutex_unlock(&fs_info->chunk_mutex);
2994 * Take the device list mutex to prevent races with the final phase of
2995 * a device replace operation that replaces the device object associated
2996 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2998 mutex_lock(&fs_devices->device_list_mutex);
2999 for (i = 0; i < map->num_stripes; i++) {
3000 struct btrfs_device *device = map->stripes[i].dev;
3001 ret = btrfs_free_dev_extent(trans, device,
3002 map->stripes[i].physical,
3003 &dev_extent_len);
3004 if (ret) {
3005 mutex_unlock(&fs_devices->device_list_mutex);
3006 btrfs_abort_transaction(trans, ret);
3007 goto out;
3010 if (device->bytes_used > 0) {
3011 mutex_lock(&fs_info->chunk_mutex);
3012 btrfs_device_set_bytes_used(device,
3013 device->bytes_used - dev_extent_len);
3014 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3015 btrfs_clear_space_info_full(fs_info);
3016 mutex_unlock(&fs_info->chunk_mutex);
3019 ret = btrfs_update_device(trans, device);
3020 if (ret) {
3021 mutex_unlock(&fs_devices->device_list_mutex);
3022 btrfs_abort_transaction(trans, ret);
3023 goto out;
3026 mutex_unlock(&fs_devices->device_list_mutex);
3028 ret = btrfs_free_chunk(trans, chunk_offset);
3029 if (ret) {
3030 btrfs_abort_transaction(trans, ret);
3031 goto out;
3034 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
3036 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3037 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3038 if (ret) {
3039 btrfs_abort_transaction(trans, ret);
3040 goto out;
3044 ret = btrfs_remove_block_group(trans, chunk_offset, em);
3045 if (ret) {
3046 btrfs_abort_transaction(trans, ret);
3047 goto out;
3050 out:
3051 /* once for us */
3052 free_extent_map(em);
3053 return ret;
3056 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3058 struct btrfs_root *root = fs_info->chunk_root;
3059 struct btrfs_trans_handle *trans;
3060 int ret;
3063 * Prevent races with automatic removal of unused block groups.
3064 * After we relocate and before we remove the chunk with offset
3065 * chunk_offset, automatic removal of the block group can kick in,
3066 * resulting in a failure when calling btrfs_remove_chunk() below.
3068 * Make sure to acquire this mutex before doing a tree search (dev
3069 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3070 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3071 * we release the path used to search the chunk/dev tree and before
3072 * the current task acquires this mutex and calls us.
3074 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3076 ret = btrfs_can_relocate(fs_info, chunk_offset);
3077 if (ret)
3078 return -ENOSPC;
3080 /* step one, relocate all the extents inside this chunk */
3081 btrfs_scrub_pause(fs_info);
3082 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3083 btrfs_scrub_continue(fs_info);
3084 if (ret)
3085 return ret;
3088 * We add the kobjects here (and after forcing data chunk creation)
3089 * since relocation is the only place we'll create chunks of a new
3090 * type at runtime. The only place where we'll remove the last
3091 * chunk of a type is the call immediately below this one. Even
3092 * so, we're protected against races with the cleaner thread since
3093 * we're covered by the delete_unused_bgs_mutex.
3095 btrfs_add_raid_kobjects(fs_info);
3097 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3098 chunk_offset);
3099 if (IS_ERR(trans)) {
3100 ret = PTR_ERR(trans);
3101 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3102 return ret;
3106 * step two, delete the device extents and the
3107 * chunk tree entries
3109 ret = btrfs_remove_chunk(trans, chunk_offset);
3110 btrfs_end_transaction(trans);
3111 return ret;
3114 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3116 struct btrfs_root *chunk_root = fs_info->chunk_root;
3117 struct btrfs_path *path;
3118 struct extent_buffer *leaf;
3119 struct btrfs_chunk *chunk;
3120 struct btrfs_key key;
3121 struct btrfs_key found_key;
3122 u64 chunk_type;
3123 bool retried = false;
3124 int failed = 0;
3125 int ret;
3127 path = btrfs_alloc_path();
3128 if (!path)
3129 return -ENOMEM;
3131 again:
3132 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3133 key.offset = (u64)-1;
3134 key.type = BTRFS_CHUNK_ITEM_KEY;
3136 while (1) {
3137 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3138 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3139 if (ret < 0) {
3140 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3141 goto error;
3143 BUG_ON(ret == 0); /* Corruption */
3145 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3146 key.type);
3147 if (ret)
3148 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3149 if (ret < 0)
3150 goto error;
3151 if (ret > 0)
3152 break;
3154 leaf = path->nodes[0];
3155 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3157 chunk = btrfs_item_ptr(leaf, path->slots[0],
3158 struct btrfs_chunk);
3159 chunk_type = btrfs_chunk_type(leaf, chunk);
3160 btrfs_release_path(path);
3162 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3163 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3164 if (ret == -ENOSPC)
3165 failed++;
3166 else
3167 BUG_ON(ret);
3169 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3171 if (found_key.offset == 0)
3172 break;
3173 key.offset = found_key.offset - 1;
3175 ret = 0;
3176 if (failed && !retried) {
3177 failed = 0;
3178 retried = true;
3179 goto again;
3180 } else if (WARN_ON(failed && retried)) {
3181 ret = -ENOSPC;
3183 error:
3184 btrfs_free_path(path);
3185 return ret;
3189 * return 1 : allocate a data chunk successfully,
3190 * return <0: errors during allocating a data chunk,
3191 * return 0 : no need to allocate a data chunk.
3193 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3194 u64 chunk_offset)
3196 struct btrfs_block_group_cache *cache;
3197 u64 bytes_used;
3198 u64 chunk_type;
3200 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3201 ASSERT(cache);
3202 chunk_type = cache->flags;
3203 btrfs_put_block_group(cache);
3205 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3206 spin_lock(&fs_info->data_sinfo->lock);
3207 bytes_used = fs_info->data_sinfo->bytes_used;
3208 spin_unlock(&fs_info->data_sinfo->lock);
3210 if (!bytes_used) {
3211 struct btrfs_trans_handle *trans;
3212 int ret;
3214 trans = btrfs_join_transaction(fs_info->tree_root);
3215 if (IS_ERR(trans))
3216 return PTR_ERR(trans);
3218 ret = btrfs_force_chunk_alloc(trans,
3219 BTRFS_BLOCK_GROUP_DATA);
3220 btrfs_end_transaction(trans);
3221 if (ret < 0)
3222 return ret;
3224 btrfs_add_raid_kobjects(fs_info);
3226 return 1;
3229 return 0;
3232 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3233 struct btrfs_balance_control *bctl)
3235 struct btrfs_root *root = fs_info->tree_root;
3236 struct btrfs_trans_handle *trans;
3237 struct btrfs_balance_item *item;
3238 struct btrfs_disk_balance_args disk_bargs;
3239 struct btrfs_path *path;
3240 struct extent_buffer *leaf;
3241 struct btrfs_key key;
3242 int ret, err;
3244 path = btrfs_alloc_path();
3245 if (!path)
3246 return -ENOMEM;
3248 trans = btrfs_start_transaction(root, 0);
3249 if (IS_ERR(trans)) {
3250 btrfs_free_path(path);
3251 return PTR_ERR(trans);
3254 key.objectid = BTRFS_BALANCE_OBJECTID;
3255 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3256 key.offset = 0;
3258 ret = btrfs_insert_empty_item(trans, root, path, &key,
3259 sizeof(*item));
3260 if (ret)
3261 goto out;
3263 leaf = path->nodes[0];
3264 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3266 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3268 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3269 btrfs_set_balance_data(leaf, item, &disk_bargs);
3270 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3271 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3272 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3273 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3275 btrfs_set_balance_flags(leaf, item, bctl->flags);
3277 btrfs_mark_buffer_dirty(leaf);
3278 out:
3279 btrfs_free_path(path);
3280 err = btrfs_commit_transaction(trans);
3281 if (err && !ret)
3282 ret = err;
3283 return ret;
3286 static int del_balance_item(struct btrfs_fs_info *fs_info)
3288 struct btrfs_root *root = fs_info->tree_root;
3289 struct btrfs_trans_handle *trans;
3290 struct btrfs_path *path;
3291 struct btrfs_key key;
3292 int ret, err;
3294 path = btrfs_alloc_path();
3295 if (!path)
3296 return -ENOMEM;
3298 trans = btrfs_start_transaction(root, 0);
3299 if (IS_ERR(trans)) {
3300 btrfs_free_path(path);
3301 return PTR_ERR(trans);
3304 key.objectid = BTRFS_BALANCE_OBJECTID;
3305 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3306 key.offset = 0;
3308 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3309 if (ret < 0)
3310 goto out;
3311 if (ret > 0) {
3312 ret = -ENOENT;
3313 goto out;
3316 ret = btrfs_del_item(trans, root, path);
3317 out:
3318 btrfs_free_path(path);
3319 err = btrfs_commit_transaction(trans);
3320 if (err && !ret)
3321 ret = err;
3322 return ret;
3326 * This is a heuristic used to reduce the number of chunks balanced on
3327 * resume after balance was interrupted.
3329 static void update_balance_args(struct btrfs_balance_control *bctl)
3332 * Turn on soft mode for chunk types that were being converted.
3334 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3335 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3336 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3337 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3338 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3339 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3342 * Turn on usage filter if is not already used. The idea is
3343 * that chunks that we have already balanced should be
3344 * reasonably full. Don't do it for chunks that are being
3345 * converted - that will keep us from relocating unconverted
3346 * (albeit full) chunks.
3348 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3349 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3350 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3351 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3352 bctl->data.usage = 90;
3354 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3355 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3356 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3357 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3358 bctl->sys.usage = 90;
3360 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3361 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3362 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3363 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3364 bctl->meta.usage = 90;
3369 * Clear the balance status in fs_info and delete the balance item from disk.
3371 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3373 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3374 int ret;
3376 BUG_ON(!fs_info->balance_ctl);
3378 spin_lock(&fs_info->balance_lock);
3379 fs_info->balance_ctl = NULL;
3380 spin_unlock(&fs_info->balance_lock);
3382 kfree(bctl);
3383 ret = del_balance_item(fs_info);
3384 if (ret)
3385 btrfs_handle_fs_error(fs_info, ret, NULL);
3389 * Balance filters. Return 1 if chunk should be filtered out
3390 * (should not be balanced).
3392 static int chunk_profiles_filter(u64 chunk_type,
3393 struct btrfs_balance_args *bargs)
3395 chunk_type = chunk_to_extended(chunk_type) &
3396 BTRFS_EXTENDED_PROFILE_MASK;
3398 if (bargs->profiles & chunk_type)
3399 return 0;
3401 return 1;
3404 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3405 struct btrfs_balance_args *bargs)
3407 struct btrfs_block_group_cache *cache;
3408 u64 chunk_used;
3409 u64 user_thresh_min;
3410 u64 user_thresh_max;
3411 int ret = 1;
3413 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3414 chunk_used = btrfs_block_group_used(&cache->item);
3416 if (bargs->usage_min == 0)
3417 user_thresh_min = 0;
3418 else
3419 user_thresh_min = div_factor_fine(cache->key.offset,
3420 bargs->usage_min);
3422 if (bargs->usage_max == 0)
3423 user_thresh_max = 1;
3424 else if (bargs->usage_max > 100)
3425 user_thresh_max = cache->key.offset;
3426 else
3427 user_thresh_max = div_factor_fine(cache->key.offset,
3428 bargs->usage_max);
3430 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3431 ret = 0;
3433 btrfs_put_block_group(cache);
3434 return ret;
3437 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3438 u64 chunk_offset, struct btrfs_balance_args *bargs)
3440 struct btrfs_block_group_cache *cache;
3441 u64 chunk_used, user_thresh;
3442 int ret = 1;
3444 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3445 chunk_used = btrfs_block_group_used(&cache->item);
3447 if (bargs->usage_min == 0)
3448 user_thresh = 1;
3449 else if (bargs->usage > 100)
3450 user_thresh = cache->key.offset;
3451 else
3452 user_thresh = div_factor_fine(cache->key.offset,
3453 bargs->usage);
3455 if (chunk_used < user_thresh)
3456 ret = 0;
3458 btrfs_put_block_group(cache);
3459 return ret;
3462 static int chunk_devid_filter(struct extent_buffer *leaf,
3463 struct btrfs_chunk *chunk,
3464 struct btrfs_balance_args *bargs)
3466 struct btrfs_stripe *stripe;
3467 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3468 int i;
3470 for (i = 0; i < num_stripes; i++) {
3471 stripe = btrfs_stripe_nr(chunk, i);
3472 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3473 return 0;
3476 return 1;
3479 static u64 calc_data_stripes(u64 type, int num_stripes)
3481 const int index = btrfs_bg_flags_to_raid_index(type);
3482 const int ncopies = btrfs_raid_array[index].ncopies;
3483 const int nparity = btrfs_raid_array[index].nparity;
3485 if (nparity)
3486 return num_stripes - nparity;
3487 else
3488 return num_stripes / ncopies;
3491 /* [pstart, pend) */
3492 static int chunk_drange_filter(struct extent_buffer *leaf,
3493 struct btrfs_chunk *chunk,
3494 struct btrfs_balance_args *bargs)
3496 struct btrfs_stripe *stripe;
3497 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3498 u64 stripe_offset;
3499 u64 stripe_length;
3500 u64 type;
3501 int factor;
3502 int i;
3504 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3505 return 0;
3507 type = btrfs_chunk_type(leaf, chunk);
3508 factor = calc_data_stripes(type, num_stripes);
3510 for (i = 0; i < num_stripes; i++) {
3511 stripe = btrfs_stripe_nr(chunk, i);
3512 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3513 continue;
3515 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3516 stripe_length = btrfs_chunk_length(leaf, chunk);
3517 stripe_length = div_u64(stripe_length, factor);
3519 if (stripe_offset < bargs->pend &&
3520 stripe_offset + stripe_length > bargs->pstart)
3521 return 0;
3524 return 1;
3527 /* [vstart, vend) */
3528 static int chunk_vrange_filter(struct extent_buffer *leaf,
3529 struct btrfs_chunk *chunk,
3530 u64 chunk_offset,
3531 struct btrfs_balance_args *bargs)
3533 if (chunk_offset < bargs->vend &&
3534 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3535 /* at least part of the chunk is inside this vrange */
3536 return 0;
3538 return 1;
3541 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3542 struct btrfs_chunk *chunk,
3543 struct btrfs_balance_args *bargs)
3545 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3547 if (bargs->stripes_min <= num_stripes
3548 && num_stripes <= bargs->stripes_max)
3549 return 0;
3551 return 1;
3554 static int chunk_soft_convert_filter(u64 chunk_type,
3555 struct btrfs_balance_args *bargs)
3557 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3558 return 0;
3560 chunk_type = chunk_to_extended(chunk_type) &
3561 BTRFS_EXTENDED_PROFILE_MASK;
3563 if (bargs->target == chunk_type)
3564 return 1;
3566 return 0;
3569 static int should_balance_chunk(struct extent_buffer *leaf,
3570 struct btrfs_chunk *chunk, u64 chunk_offset)
3572 struct btrfs_fs_info *fs_info = leaf->fs_info;
3573 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3574 struct btrfs_balance_args *bargs = NULL;
3575 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3577 /* type filter */
3578 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3579 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3580 return 0;
3583 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3584 bargs = &bctl->data;
3585 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3586 bargs = &bctl->sys;
3587 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3588 bargs = &bctl->meta;
3590 /* profiles filter */
3591 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3592 chunk_profiles_filter(chunk_type, bargs)) {
3593 return 0;
3596 /* usage filter */
3597 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3598 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3599 return 0;
3600 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3601 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3602 return 0;
3605 /* devid filter */
3606 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3607 chunk_devid_filter(leaf, chunk, bargs)) {
3608 return 0;
3611 /* drange filter, makes sense only with devid filter */
3612 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3613 chunk_drange_filter(leaf, chunk, bargs)) {
3614 return 0;
3617 /* vrange filter */
3618 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3619 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3620 return 0;
3623 /* stripes filter */
3624 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3625 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3626 return 0;
3629 /* soft profile changing mode */
3630 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3631 chunk_soft_convert_filter(chunk_type, bargs)) {
3632 return 0;
3636 * limited by count, must be the last filter
3638 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3639 if (bargs->limit == 0)
3640 return 0;
3641 else
3642 bargs->limit--;
3643 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3645 * Same logic as the 'limit' filter; the minimum cannot be
3646 * determined here because we do not have the global information
3647 * about the count of all chunks that satisfy the filters.
3649 if (bargs->limit_max == 0)
3650 return 0;
3651 else
3652 bargs->limit_max--;
3655 return 1;
3658 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3660 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3661 struct btrfs_root *chunk_root = fs_info->chunk_root;
3662 u64 chunk_type;
3663 struct btrfs_chunk *chunk;
3664 struct btrfs_path *path = NULL;
3665 struct btrfs_key key;
3666 struct btrfs_key found_key;
3667 struct extent_buffer *leaf;
3668 int slot;
3669 int ret;
3670 int enospc_errors = 0;
3671 bool counting = true;
3672 /* The single value limit and min/max limits use the same bytes in the */
3673 u64 limit_data = bctl->data.limit;
3674 u64 limit_meta = bctl->meta.limit;
3675 u64 limit_sys = bctl->sys.limit;
3676 u32 count_data = 0;
3677 u32 count_meta = 0;
3678 u32 count_sys = 0;
3679 int chunk_reserved = 0;
3681 path = btrfs_alloc_path();
3682 if (!path) {
3683 ret = -ENOMEM;
3684 goto error;
3687 /* zero out stat counters */
3688 spin_lock(&fs_info->balance_lock);
3689 memset(&bctl->stat, 0, sizeof(bctl->stat));
3690 spin_unlock(&fs_info->balance_lock);
3691 again:
3692 if (!counting) {
3694 * The single value limit and min/max limits use the same bytes
3695 * in the
3697 bctl->data.limit = limit_data;
3698 bctl->meta.limit = limit_meta;
3699 bctl->sys.limit = limit_sys;
3701 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3702 key.offset = (u64)-1;
3703 key.type = BTRFS_CHUNK_ITEM_KEY;
3705 while (1) {
3706 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3707 atomic_read(&fs_info->balance_cancel_req)) {
3708 ret = -ECANCELED;
3709 goto error;
3712 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3713 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3714 if (ret < 0) {
3715 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3716 goto error;
3720 * this shouldn't happen, it means the last relocate
3721 * failed
3723 if (ret == 0)
3724 BUG(); /* FIXME break ? */
3726 ret = btrfs_previous_item(chunk_root, path, 0,
3727 BTRFS_CHUNK_ITEM_KEY);
3728 if (ret) {
3729 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3730 ret = 0;
3731 break;
3734 leaf = path->nodes[0];
3735 slot = path->slots[0];
3736 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3738 if (found_key.objectid != key.objectid) {
3739 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3740 break;
3743 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3744 chunk_type = btrfs_chunk_type(leaf, chunk);
3746 if (!counting) {
3747 spin_lock(&fs_info->balance_lock);
3748 bctl->stat.considered++;
3749 spin_unlock(&fs_info->balance_lock);
3752 ret = should_balance_chunk(leaf, chunk, found_key.offset);
3754 btrfs_release_path(path);
3755 if (!ret) {
3756 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3757 goto loop;
3760 if (counting) {
3761 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3762 spin_lock(&fs_info->balance_lock);
3763 bctl->stat.expected++;
3764 spin_unlock(&fs_info->balance_lock);
3766 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3767 count_data++;
3768 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3769 count_sys++;
3770 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3771 count_meta++;
3773 goto loop;
3777 * Apply limit_min filter, no need to check if the LIMITS
3778 * filter is used, limit_min is 0 by default
3780 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3781 count_data < bctl->data.limit_min)
3782 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3783 count_meta < bctl->meta.limit_min)
3784 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3785 count_sys < bctl->sys.limit_min)) {
3786 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3787 goto loop;
3790 if (!chunk_reserved) {
3792 * We may be relocating the only data chunk we have,
3793 * which could potentially end up with losing data's
3794 * raid profile, so lets allocate an empty one in
3795 * advance.
3797 ret = btrfs_may_alloc_data_chunk(fs_info,
3798 found_key.offset);
3799 if (ret < 0) {
3800 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3801 goto error;
3802 } else if (ret == 1) {
3803 chunk_reserved = 1;
3807 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3808 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3809 if (ret == -ENOSPC) {
3810 enospc_errors++;
3811 } else if (ret == -ETXTBSY) {
3812 btrfs_info(fs_info,
3813 "skipping relocation of block group %llu due to active swapfile",
3814 found_key.offset);
3815 ret = 0;
3816 } else if (ret) {
3817 goto error;
3818 } else {
3819 spin_lock(&fs_info->balance_lock);
3820 bctl->stat.completed++;
3821 spin_unlock(&fs_info->balance_lock);
3823 loop:
3824 if (found_key.offset == 0)
3825 break;
3826 key.offset = found_key.offset - 1;
3829 if (counting) {
3830 btrfs_release_path(path);
3831 counting = false;
3832 goto again;
3834 error:
3835 btrfs_free_path(path);
3836 if (enospc_errors) {
3837 btrfs_info(fs_info, "%d enospc errors during balance",
3838 enospc_errors);
3839 if (!ret)
3840 ret = -ENOSPC;
3843 return ret;
3847 * alloc_profile_is_valid - see if a given profile is valid and reduced
3848 * @flags: profile to validate
3849 * @extended: if true @flags is treated as an extended profile
3851 static int alloc_profile_is_valid(u64 flags, int extended)
3853 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3854 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3856 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3858 /* 1) check that all other bits are zeroed */
3859 if (flags & ~mask)
3860 return 0;
3862 /* 2) see if profile is reduced */
3863 if (flags == 0)
3864 return !extended; /* "0" is valid for usual profiles */
3866 /* true if exactly one bit set */
3867 return is_power_of_2(flags);
3870 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3872 /* cancel requested || normal exit path */
3873 return atomic_read(&fs_info->balance_cancel_req) ||
3874 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3875 atomic_read(&fs_info->balance_cancel_req) == 0);
3878 /* Non-zero return value signifies invalidity */
3879 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3880 u64 allowed)
3882 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3883 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3884 (bctl_arg->target & ~allowed)));
3888 * Fill @buf with textual description of balance filter flags @bargs, up to
3889 * @size_buf including the terminating null. The output may be trimmed if it
3890 * does not fit into the provided buffer.
3892 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
3893 u32 size_buf)
3895 int ret;
3896 u32 size_bp = size_buf;
3897 char *bp = buf;
3898 u64 flags = bargs->flags;
3899 char tmp_buf[128] = {'\0'};
3901 if (!flags)
3902 return;
3904 #define CHECK_APPEND_NOARG(a) \
3905 do { \
3906 ret = snprintf(bp, size_bp, (a)); \
3907 if (ret < 0 || ret >= size_bp) \
3908 goto out_overflow; \
3909 size_bp -= ret; \
3910 bp += ret; \
3911 } while (0)
3913 #define CHECK_APPEND_1ARG(a, v1) \
3914 do { \
3915 ret = snprintf(bp, size_bp, (a), (v1)); \
3916 if (ret < 0 || ret >= size_bp) \
3917 goto out_overflow; \
3918 size_bp -= ret; \
3919 bp += ret; \
3920 } while (0)
3922 #define CHECK_APPEND_2ARG(a, v1, v2) \
3923 do { \
3924 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \
3925 if (ret < 0 || ret >= size_bp) \
3926 goto out_overflow; \
3927 size_bp -= ret; \
3928 bp += ret; \
3929 } while (0)
3931 if (flags & BTRFS_BALANCE_ARGS_CONVERT)
3932 CHECK_APPEND_1ARG("convert=%s,",
3933 btrfs_bg_type_to_raid_name(bargs->target));
3935 if (flags & BTRFS_BALANCE_ARGS_SOFT)
3936 CHECK_APPEND_NOARG("soft,");
3938 if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
3939 btrfs_describe_block_groups(bargs->profiles, tmp_buf,
3940 sizeof(tmp_buf));
3941 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
3944 if (flags & BTRFS_BALANCE_ARGS_USAGE)
3945 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
3947 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
3948 CHECK_APPEND_2ARG("usage=%u..%u,",
3949 bargs->usage_min, bargs->usage_max);
3951 if (flags & BTRFS_BALANCE_ARGS_DEVID)
3952 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
3954 if (flags & BTRFS_BALANCE_ARGS_DRANGE)
3955 CHECK_APPEND_2ARG("drange=%llu..%llu,",
3956 bargs->pstart, bargs->pend);
3958 if (flags & BTRFS_BALANCE_ARGS_VRANGE)
3959 CHECK_APPEND_2ARG("vrange=%llu..%llu,",
3960 bargs->vstart, bargs->vend);
3962 if (flags & BTRFS_BALANCE_ARGS_LIMIT)
3963 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
3965 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
3966 CHECK_APPEND_2ARG("limit=%u..%u,",
3967 bargs->limit_min, bargs->limit_max);
3969 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
3970 CHECK_APPEND_2ARG("stripes=%u..%u,",
3971 bargs->stripes_min, bargs->stripes_max);
3973 #undef CHECK_APPEND_2ARG
3974 #undef CHECK_APPEND_1ARG
3975 #undef CHECK_APPEND_NOARG
3977 out_overflow:
3979 if (size_bp < size_buf)
3980 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
3981 else
3982 buf[0] = '\0';
3985 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
3987 u32 size_buf = 1024;
3988 char tmp_buf[192] = {'\0'};
3989 char *buf;
3990 char *bp;
3991 u32 size_bp = size_buf;
3992 int ret;
3993 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3995 buf = kzalloc(size_buf, GFP_KERNEL);
3996 if (!buf)
3997 return;
3999 bp = buf;
4001 #define CHECK_APPEND_1ARG(a, v1) \
4002 do { \
4003 ret = snprintf(bp, size_bp, (a), (v1)); \
4004 if (ret < 0 || ret >= size_bp) \
4005 goto out_overflow; \
4006 size_bp -= ret; \
4007 bp += ret; \
4008 } while (0)
4010 if (bctl->flags & BTRFS_BALANCE_FORCE)
4011 CHECK_APPEND_1ARG("%s", "-f ");
4013 if (bctl->flags & BTRFS_BALANCE_DATA) {
4014 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4015 CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4018 if (bctl->flags & BTRFS_BALANCE_METADATA) {
4019 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4020 CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4023 if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4024 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4025 CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4028 #undef CHECK_APPEND_1ARG
4030 out_overflow:
4032 if (size_bp < size_buf)
4033 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4034 btrfs_info(fs_info, "balance: %s %s",
4035 (bctl->flags & BTRFS_BALANCE_RESUME) ?
4036 "resume" : "start", buf);
4038 kfree(buf);
4042 * Should be called with balance mutexe held
4044 int btrfs_balance(struct btrfs_fs_info *fs_info,
4045 struct btrfs_balance_control *bctl,
4046 struct btrfs_ioctl_balance_args *bargs)
4048 u64 meta_target, data_target;
4049 u64 allowed;
4050 int mixed = 0;
4051 int ret;
4052 u64 num_devices;
4053 unsigned seq;
4054 bool reducing_integrity;
4055 int i;
4057 if (btrfs_fs_closing(fs_info) ||
4058 atomic_read(&fs_info->balance_pause_req) ||
4059 atomic_read(&fs_info->balance_cancel_req)) {
4060 ret = -EINVAL;
4061 goto out;
4064 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4065 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4066 mixed = 1;
4069 * In case of mixed groups both data and meta should be picked,
4070 * and identical options should be given for both of them.
4072 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4073 if (mixed && (bctl->flags & allowed)) {
4074 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4075 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4076 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4077 btrfs_err(fs_info,
4078 "balance: mixed groups data and metadata options must be the same");
4079 ret = -EINVAL;
4080 goto out;
4084 num_devices = btrfs_num_devices(fs_info);
4085 allowed = 0;
4086 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4087 if (num_devices >= btrfs_raid_array[i].devs_min)
4088 allowed |= btrfs_raid_array[i].bg_flag;
4090 if (validate_convert_profile(&bctl->data, allowed)) {
4091 btrfs_err(fs_info,
4092 "balance: invalid convert data profile %s",
4093 btrfs_bg_type_to_raid_name(bctl->data.target));
4094 ret = -EINVAL;
4095 goto out;
4097 if (validate_convert_profile(&bctl->meta, allowed)) {
4098 btrfs_err(fs_info,
4099 "balance: invalid convert metadata profile %s",
4100 btrfs_bg_type_to_raid_name(bctl->meta.target));
4101 ret = -EINVAL;
4102 goto out;
4104 if (validate_convert_profile(&bctl->sys, allowed)) {
4105 btrfs_err(fs_info,
4106 "balance: invalid convert system profile %s",
4107 btrfs_bg_type_to_raid_name(bctl->sys.target));
4108 ret = -EINVAL;
4109 goto out;
4113 * Allow to reduce metadata or system integrity only if force set for
4114 * profiles with redundancy (copies, parity)
4116 allowed = 0;
4117 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4118 if (btrfs_raid_array[i].ncopies >= 2 ||
4119 btrfs_raid_array[i].tolerated_failures >= 1)
4120 allowed |= btrfs_raid_array[i].bg_flag;
4122 do {
4123 seq = read_seqbegin(&fs_info->profiles_lock);
4125 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4126 (fs_info->avail_system_alloc_bits & allowed) &&
4127 !(bctl->sys.target & allowed)) ||
4128 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4129 (fs_info->avail_metadata_alloc_bits & allowed) &&
4130 !(bctl->meta.target & allowed)))
4131 reducing_integrity = true;
4132 else
4133 reducing_integrity = false;
4135 /* if we're not converting, the target field is uninitialized */
4136 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4137 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4138 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4139 bctl->data.target : fs_info->avail_data_alloc_bits;
4140 } while (read_seqretry(&fs_info->profiles_lock, seq));
4142 if (reducing_integrity) {
4143 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4144 btrfs_info(fs_info,
4145 "balance: force reducing metadata integrity");
4146 } else {
4147 btrfs_err(fs_info,
4148 "balance: reduces metadata integrity, use --force if you want this");
4149 ret = -EINVAL;
4150 goto out;
4154 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4155 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4156 btrfs_warn(fs_info,
4157 "balance: metadata profile %s has lower redundancy than data profile %s",
4158 btrfs_bg_type_to_raid_name(meta_target),
4159 btrfs_bg_type_to_raid_name(data_target));
4162 ret = insert_balance_item(fs_info, bctl);
4163 if (ret && ret != -EEXIST)
4164 goto out;
4166 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4167 BUG_ON(ret == -EEXIST);
4168 BUG_ON(fs_info->balance_ctl);
4169 spin_lock(&fs_info->balance_lock);
4170 fs_info->balance_ctl = bctl;
4171 spin_unlock(&fs_info->balance_lock);
4172 } else {
4173 BUG_ON(ret != -EEXIST);
4174 spin_lock(&fs_info->balance_lock);
4175 update_balance_args(bctl);
4176 spin_unlock(&fs_info->balance_lock);
4179 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4180 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4181 describe_balance_start_or_resume(fs_info);
4182 mutex_unlock(&fs_info->balance_mutex);
4184 ret = __btrfs_balance(fs_info);
4186 mutex_lock(&fs_info->balance_mutex);
4187 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req))
4188 btrfs_info(fs_info, "balance: paused");
4189 else if (ret == -ECANCELED && atomic_read(&fs_info->balance_cancel_req))
4190 btrfs_info(fs_info, "balance: canceled");
4191 else
4192 btrfs_info(fs_info, "balance: ended with status: %d", ret);
4194 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4196 if (bargs) {
4197 memset(bargs, 0, sizeof(*bargs));
4198 btrfs_update_ioctl_balance_args(fs_info, bargs);
4201 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4202 balance_need_close(fs_info)) {
4203 reset_balance_state(fs_info);
4204 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4207 wake_up(&fs_info->balance_wait_q);
4209 return ret;
4210 out:
4211 if (bctl->flags & BTRFS_BALANCE_RESUME)
4212 reset_balance_state(fs_info);
4213 else
4214 kfree(bctl);
4215 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4217 return ret;
4220 static int balance_kthread(void *data)
4222 struct btrfs_fs_info *fs_info = data;
4223 int ret = 0;
4225 mutex_lock(&fs_info->balance_mutex);
4226 if (fs_info->balance_ctl)
4227 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4228 mutex_unlock(&fs_info->balance_mutex);
4230 return ret;
4233 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4235 struct task_struct *tsk;
4237 mutex_lock(&fs_info->balance_mutex);
4238 if (!fs_info->balance_ctl) {
4239 mutex_unlock(&fs_info->balance_mutex);
4240 return 0;
4242 mutex_unlock(&fs_info->balance_mutex);
4244 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4245 btrfs_info(fs_info, "balance: resume skipped");
4246 return 0;
4250 * A ro->rw remount sequence should continue with the paused balance
4251 * regardless of who pauses it, system or the user as of now, so set
4252 * the resume flag.
4254 spin_lock(&fs_info->balance_lock);
4255 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4256 spin_unlock(&fs_info->balance_lock);
4258 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4259 return PTR_ERR_OR_ZERO(tsk);
4262 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4264 struct btrfs_balance_control *bctl;
4265 struct btrfs_balance_item *item;
4266 struct btrfs_disk_balance_args disk_bargs;
4267 struct btrfs_path *path;
4268 struct extent_buffer *leaf;
4269 struct btrfs_key key;
4270 int ret;
4272 path = btrfs_alloc_path();
4273 if (!path)
4274 return -ENOMEM;
4276 key.objectid = BTRFS_BALANCE_OBJECTID;
4277 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4278 key.offset = 0;
4280 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4281 if (ret < 0)
4282 goto out;
4283 if (ret > 0) { /* ret = -ENOENT; */
4284 ret = 0;
4285 goto out;
4288 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4289 if (!bctl) {
4290 ret = -ENOMEM;
4291 goto out;
4294 leaf = path->nodes[0];
4295 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4297 bctl->flags = btrfs_balance_flags(leaf, item);
4298 bctl->flags |= BTRFS_BALANCE_RESUME;
4300 btrfs_balance_data(leaf, item, &disk_bargs);
4301 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4302 btrfs_balance_meta(leaf, item, &disk_bargs);
4303 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4304 btrfs_balance_sys(leaf, item, &disk_bargs);
4305 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4308 * This should never happen, as the paused balance state is recovered
4309 * during mount without any chance of other exclusive ops to collide.
4311 * This gives the exclusive op status to balance and keeps in paused
4312 * state until user intervention (cancel or umount). If the ownership
4313 * cannot be assigned, show a message but do not fail. The balance
4314 * is in a paused state and must have fs_info::balance_ctl properly
4315 * set up.
4317 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
4318 btrfs_warn(fs_info,
4319 "balance: cannot set exclusive op status, resume manually");
4321 mutex_lock(&fs_info->balance_mutex);
4322 BUG_ON(fs_info->balance_ctl);
4323 spin_lock(&fs_info->balance_lock);
4324 fs_info->balance_ctl = bctl;
4325 spin_unlock(&fs_info->balance_lock);
4326 mutex_unlock(&fs_info->balance_mutex);
4327 out:
4328 btrfs_free_path(path);
4329 return ret;
4332 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4334 int ret = 0;
4336 mutex_lock(&fs_info->balance_mutex);
4337 if (!fs_info->balance_ctl) {
4338 mutex_unlock(&fs_info->balance_mutex);
4339 return -ENOTCONN;
4342 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4343 atomic_inc(&fs_info->balance_pause_req);
4344 mutex_unlock(&fs_info->balance_mutex);
4346 wait_event(fs_info->balance_wait_q,
4347 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4349 mutex_lock(&fs_info->balance_mutex);
4350 /* we are good with balance_ctl ripped off from under us */
4351 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4352 atomic_dec(&fs_info->balance_pause_req);
4353 } else {
4354 ret = -ENOTCONN;
4357 mutex_unlock(&fs_info->balance_mutex);
4358 return ret;
4361 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4363 mutex_lock(&fs_info->balance_mutex);
4364 if (!fs_info->balance_ctl) {
4365 mutex_unlock(&fs_info->balance_mutex);
4366 return -ENOTCONN;
4370 * A paused balance with the item stored on disk can be resumed at
4371 * mount time if the mount is read-write. Otherwise it's still paused
4372 * and we must not allow cancelling as it deletes the item.
4374 if (sb_rdonly(fs_info->sb)) {
4375 mutex_unlock(&fs_info->balance_mutex);
4376 return -EROFS;
4379 atomic_inc(&fs_info->balance_cancel_req);
4381 * if we are running just wait and return, balance item is
4382 * deleted in btrfs_balance in this case
4384 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4385 mutex_unlock(&fs_info->balance_mutex);
4386 wait_event(fs_info->balance_wait_q,
4387 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4388 mutex_lock(&fs_info->balance_mutex);
4389 } else {
4390 mutex_unlock(&fs_info->balance_mutex);
4392 * Lock released to allow other waiters to continue, we'll
4393 * reexamine the status again.
4395 mutex_lock(&fs_info->balance_mutex);
4397 if (fs_info->balance_ctl) {
4398 reset_balance_state(fs_info);
4399 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4400 btrfs_info(fs_info, "balance: canceled");
4404 BUG_ON(fs_info->balance_ctl ||
4405 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4406 atomic_dec(&fs_info->balance_cancel_req);
4407 mutex_unlock(&fs_info->balance_mutex);
4408 return 0;
4411 static int btrfs_uuid_scan_kthread(void *data)
4413 struct btrfs_fs_info *fs_info = data;
4414 struct btrfs_root *root = fs_info->tree_root;
4415 struct btrfs_key key;
4416 struct btrfs_path *path = NULL;
4417 int ret = 0;
4418 struct extent_buffer *eb;
4419 int slot;
4420 struct btrfs_root_item root_item;
4421 u32 item_size;
4422 struct btrfs_trans_handle *trans = NULL;
4424 path = btrfs_alloc_path();
4425 if (!path) {
4426 ret = -ENOMEM;
4427 goto out;
4430 key.objectid = 0;
4431 key.type = BTRFS_ROOT_ITEM_KEY;
4432 key.offset = 0;
4434 while (1) {
4435 ret = btrfs_search_forward(root, &key, path,
4436 BTRFS_OLDEST_GENERATION);
4437 if (ret) {
4438 if (ret > 0)
4439 ret = 0;
4440 break;
4443 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4444 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4445 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4446 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4447 goto skip;
4449 eb = path->nodes[0];
4450 slot = path->slots[0];
4451 item_size = btrfs_item_size_nr(eb, slot);
4452 if (item_size < sizeof(root_item))
4453 goto skip;
4455 read_extent_buffer(eb, &root_item,
4456 btrfs_item_ptr_offset(eb, slot),
4457 (int)sizeof(root_item));
4458 if (btrfs_root_refs(&root_item) == 0)
4459 goto skip;
4461 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4462 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4463 if (trans)
4464 goto update_tree;
4466 btrfs_release_path(path);
4468 * 1 - subvol uuid item
4469 * 1 - received_subvol uuid item
4471 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4472 if (IS_ERR(trans)) {
4473 ret = PTR_ERR(trans);
4474 break;
4476 continue;
4477 } else {
4478 goto skip;
4480 update_tree:
4481 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4482 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4483 BTRFS_UUID_KEY_SUBVOL,
4484 key.objectid);
4485 if (ret < 0) {
4486 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4487 ret);
4488 break;
4492 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4493 ret = btrfs_uuid_tree_add(trans,
4494 root_item.received_uuid,
4495 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4496 key.objectid);
4497 if (ret < 0) {
4498 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4499 ret);
4500 break;
4504 skip:
4505 if (trans) {
4506 ret = btrfs_end_transaction(trans);
4507 trans = NULL;
4508 if (ret)
4509 break;
4512 btrfs_release_path(path);
4513 if (key.offset < (u64)-1) {
4514 key.offset++;
4515 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4516 key.offset = 0;
4517 key.type = BTRFS_ROOT_ITEM_KEY;
4518 } else if (key.objectid < (u64)-1) {
4519 key.offset = 0;
4520 key.type = BTRFS_ROOT_ITEM_KEY;
4521 key.objectid++;
4522 } else {
4523 break;
4525 cond_resched();
4528 out:
4529 btrfs_free_path(path);
4530 if (trans && !IS_ERR(trans))
4531 btrfs_end_transaction(trans);
4532 if (ret)
4533 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4534 else
4535 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4536 up(&fs_info->uuid_tree_rescan_sem);
4537 return 0;
4541 * Callback for btrfs_uuid_tree_iterate().
4542 * returns:
4543 * 0 check succeeded, the entry is not outdated.
4544 * < 0 if an error occurred.
4545 * > 0 if the check failed, which means the caller shall remove the entry.
4547 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4548 u8 *uuid, u8 type, u64 subid)
4550 struct btrfs_key key;
4551 int ret = 0;
4552 struct btrfs_root *subvol_root;
4554 if (type != BTRFS_UUID_KEY_SUBVOL &&
4555 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4556 goto out;
4558 key.objectid = subid;
4559 key.type = BTRFS_ROOT_ITEM_KEY;
4560 key.offset = (u64)-1;
4561 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4562 if (IS_ERR(subvol_root)) {
4563 ret = PTR_ERR(subvol_root);
4564 if (ret == -ENOENT)
4565 ret = 1;
4566 goto out;
4569 switch (type) {
4570 case BTRFS_UUID_KEY_SUBVOL:
4571 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4572 ret = 1;
4573 break;
4574 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4575 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4576 BTRFS_UUID_SIZE))
4577 ret = 1;
4578 break;
4581 out:
4582 return ret;
4585 static int btrfs_uuid_rescan_kthread(void *data)
4587 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4588 int ret;
4591 * 1st step is to iterate through the existing UUID tree and
4592 * to delete all entries that contain outdated data.
4593 * 2nd step is to add all missing entries to the UUID tree.
4595 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4596 if (ret < 0) {
4597 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4598 up(&fs_info->uuid_tree_rescan_sem);
4599 return ret;
4601 return btrfs_uuid_scan_kthread(data);
4604 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4606 struct btrfs_trans_handle *trans;
4607 struct btrfs_root *tree_root = fs_info->tree_root;
4608 struct btrfs_root *uuid_root;
4609 struct task_struct *task;
4610 int ret;
4613 * 1 - root node
4614 * 1 - root item
4616 trans = btrfs_start_transaction(tree_root, 2);
4617 if (IS_ERR(trans))
4618 return PTR_ERR(trans);
4620 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID);
4621 if (IS_ERR(uuid_root)) {
4622 ret = PTR_ERR(uuid_root);
4623 btrfs_abort_transaction(trans, ret);
4624 btrfs_end_transaction(trans);
4625 return ret;
4628 fs_info->uuid_root = uuid_root;
4630 ret = btrfs_commit_transaction(trans);
4631 if (ret)
4632 return ret;
4634 down(&fs_info->uuid_tree_rescan_sem);
4635 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4636 if (IS_ERR(task)) {
4637 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4638 btrfs_warn(fs_info, "failed to start uuid_scan task");
4639 up(&fs_info->uuid_tree_rescan_sem);
4640 return PTR_ERR(task);
4643 return 0;
4646 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4648 struct task_struct *task;
4650 down(&fs_info->uuid_tree_rescan_sem);
4651 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4652 if (IS_ERR(task)) {
4653 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4654 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4655 up(&fs_info->uuid_tree_rescan_sem);
4656 return PTR_ERR(task);
4659 return 0;
4663 * shrinking a device means finding all of the device extents past
4664 * the new size, and then following the back refs to the chunks.
4665 * The chunk relocation code actually frees the device extent
4667 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4669 struct btrfs_fs_info *fs_info = device->fs_info;
4670 struct btrfs_root *root = fs_info->dev_root;
4671 struct btrfs_trans_handle *trans;
4672 struct btrfs_dev_extent *dev_extent = NULL;
4673 struct btrfs_path *path;
4674 u64 length;
4675 u64 chunk_offset;
4676 int ret;
4677 int slot;
4678 int failed = 0;
4679 bool retried = false;
4680 struct extent_buffer *l;
4681 struct btrfs_key key;
4682 struct btrfs_super_block *super_copy = fs_info->super_copy;
4683 u64 old_total = btrfs_super_total_bytes(super_copy);
4684 u64 old_size = btrfs_device_get_total_bytes(device);
4685 u64 diff;
4686 u64 start;
4688 new_size = round_down(new_size, fs_info->sectorsize);
4689 start = new_size;
4690 diff = round_down(old_size - new_size, fs_info->sectorsize);
4692 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4693 return -EINVAL;
4695 path = btrfs_alloc_path();
4696 if (!path)
4697 return -ENOMEM;
4699 path->reada = READA_BACK;
4701 trans = btrfs_start_transaction(root, 0);
4702 if (IS_ERR(trans)) {
4703 btrfs_free_path(path);
4704 return PTR_ERR(trans);
4707 mutex_lock(&fs_info->chunk_mutex);
4709 btrfs_device_set_total_bytes(device, new_size);
4710 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4711 device->fs_devices->total_rw_bytes -= diff;
4712 atomic64_sub(diff, &fs_info->free_chunk_space);
4716 * Once the device's size has been set to the new size, ensure all
4717 * in-memory chunks are synced to disk so that the loop below sees them
4718 * and relocates them accordingly.
4720 if (contains_pending_extent(device, &start, diff)) {
4721 mutex_unlock(&fs_info->chunk_mutex);
4722 ret = btrfs_commit_transaction(trans);
4723 if (ret)
4724 goto done;
4725 } else {
4726 mutex_unlock(&fs_info->chunk_mutex);
4727 btrfs_end_transaction(trans);
4730 again:
4731 key.objectid = device->devid;
4732 key.offset = (u64)-1;
4733 key.type = BTRFS_DEV_EXTENT_KEY;
4735 do {
4736 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4737 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4738 if (ret < 0) {
4739 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4740 goto done;
4743 ret = btrfs_previous_item(root, path, 0, key.type);
4744 if (ret)
4745 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4746 if (ret < 0)
4747 goto done;
4748 if (ret) {
4749 ret = 0;
4750 btrfs_release_path(path);
4751 break;
4754 l = path->nodes[0];
4755 slot = path->slots[0];
4756 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4758 if (key.objectid != device->devid) {
4759 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4760 btrfs_release_path(path);
4761 break;
4764 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4765 length = btrfs_dev_extent_length(l, dev_extent);
4767 if (key.offset + length <= new_size) {
4768 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4769 btrfs_release_path(path);
4770 break;
4773 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4774 btrfs_release_path(path);
4777 * We may be relocating the only data chunk we have,
4778 * which could potentially end up with losing data's
4779 * raid profile, so lets allocate an empty one in
4780 * advance.
4782 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4783 if (ret < 0) {
4784 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4785 goto done;
4788 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4789 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4790 if (ret == -ENOSPC) {
4791 failed++;
4792 } else if (ret) {
4793 if (ret == -ETXTBSY) {
4794 btrfs_warn(fs_info,
4795 "could not shrink block group %llu due to active swapfile",
4796 chunk_offset);
4798 goto done;
4800 } while (key.offset-- > 0);
4802 if (failed && !retried) {
4803 failed = 0;
4804 retried = true;
4805 goto again;
4806 } else if (failed && retried) {
4807 ret = -ENOSPC;
4808 goto done;
4811 /* Shrinking succeeded, else we would be at "done". */
4812 trans = btrfs_start_transaction(root, 0);
4813 if (IS_ERR(trans)) {
4814 ret = PTR_ERR(trans);
4815 goto done;
4818 mutex_lock(&fs_info->chunk_mutex);
4819 btrfs_device_set_disk_total_bytes(device, new_size);
4820 if (list_empty(&device->post_commit_list))
4821 list_add_tail(&device->post_commit_list,
4822 &trans->transaction->dev_update_list);
4824 WARN_ON(diff > old_total);
4825 btrfs_set_super_total_bytes(super_copy,
4826 round_down(old_total - diff, fs_info->sectorsize));
4827 mutex_unlock(&fs_info->chunk_mutex);
4829 /* Now btrfs_update_device() will change the on-disk size. */
4830 ret = btrfs_update_device(trans, device);
4831 if (ret < 0) {
4832 btrfs_abort_transaction(trans, ret);
4833 btrfs_end_transaction(trans);
4834 } else {
4835 ret = btrfs_commit_transaction(trans);
4837 done:
4838 btrfs_free_path(path);
4839 if (ret) {
4840 mutex_lock(&fs_info->chunk_mutex);
4841 btrfs_device_set_total_bytes(device, old_size);
4842 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4843 device->fs_devices->total_rw_bytes += diff;
4844 atomic64_add(diff, &fs_info->free_chunk_space);
4845 mutex_unlock(&fs_info->chunk_mutex);
4847 return ret;
4850 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4851 struct btrfs_key *key,
4852 struct btrfs_chunk *chunk, int item_size)
4854 struct btrfs_super_block *super_copy = fs_info->super_copy;
4855 struct btrfs_disk_key disk_key;
4856 u32 array_size;
4857 u8 *ptr;
4859 mutex_lock(&fs_info->chunk_mutex);
4860 array_size = btrfs_super_sys_array_size(super_copy);
4861 if (array_size + item_size + sizeof(disk_key)
4862 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4863 mutex_unlock(&fs_info->chunk_mutex);
4864 return -EFBIG;
4867 ptr = super_copy->sys_chunk_array + array_size;
4868 btrfs_cpu_key_to_disk(&disk_key, key);
4869 memcpy(ptr, &disk_key, sizeof(disk_key));
4870 ptr += sizeof(disk_key);
4871 memcpy(ptr, chunk, item_size);
4872 item_size += sizeof(disk_key);
4873 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4874 mutex_unlock(&fs_info->chunk_mutex);
4876 return 0;
4880 * sort the devices in descending order by max_avail, total_avail
4882 static int btrfs_cmp_device_info(const void *a, const void *b)
4884 const struct btrfs_device_info *di_a = a;
4885 const struct btrfs_device_info *di_b = b;
4887 if (di_a->max_avail > di_b->max_avail)
4888 return -1;
4889 if (di_a->max_avail < di_b->max_avail)
4890 return 1;
4891 if (di_a->total_avail > di_b->total_avail)
4892 return -1;
4893 if (di_a->total_avail < di_b->total_avail)
4894 return 1;
4895 return 0;
4898 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4900 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4901 return;
4903 btrfs_set_fs_incompat(info, RAID56);
4906 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4907 u64 start, u64 type)
4909 struct btrfs_fs_info *info = trans->fs_info;
4910 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4911 struct btrfs_device *device;
4912 struct map_lookup *map = NULL;
4913 struct extent_map_tree *em_tree;
4914 struct extent_map *em;
4915 struct btrfs_device_info *devices_info = NULL;
4916 u64 total_avail;
4917 int num_stripes; /* total number of stripes to allocate */
4918 int data_stripes; /* number of stripes that count for
4919 block group size */
4920 int sub_stripes; /* sub_stripes info for map */
4921 int dev_stripes; /* stripes per dev */
4922 int devs_max; /* max devs to use */
4923 int devs_min; /* min devs needed */
4924 int devs_increment; /* ndevs has to be a multiple of this */
4925 int ncopies; /* how many copies to data has */
4926 int nparity; /* number of stripes worth of bytes to
4927 store parity information */
4928 int ret;
4929 u64 max_stripe_size;
4930 u64 max_chunk_size;
4931 u64 stripe_size;
4932 u64 chunk_size;
4933 int ndevs;
4934 int i;
4935 int j;
4936 int index;
4938 BUG_ON(!alloc_profile_is_valid(type, 0));
4940 if (list_empty(&fs_devices->alloc_list)) {
4941 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4942 btrfs_debug(info, "%s: no writable device", __func__);
4943 return -ENOSPC;
4946 index = btrfs_bg_flags_to_raid_index(type);
4948 sub_stripes = btrfs_raid_array[index].sub_stripes;
4949 dev_stripes = btrfs_raid_array[index].dev_stripes;
4950 devs_max = btrfs_raid_array[index].devs_max;
4951 if (!devs_max)
4952 devs_max = BTRFS_MAX_DEVS(info);
4953 devs_min = btrfs_raid_array[index].devs_min;
4954 devs_increment = btrfs_raid_array[index].devs_increment;
4955 ncopies = btrfs_raid_array[index].ncopies;
4956 nparity = btrfs_raid_array[index].nparity;
4958 if (type & BTRFS_BLOCK_GROUP_DATA) {
4959 max_stripe_size = SZ_1G;
4960 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4961 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4962 /* for larger filesystems, use larger metadata chunks */
4963 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4964 max_stripe_size = SZ_1G;
4965 else
4966 max_stripe_size = SZ_256M;
4967 max_chunk_size = max_stripe_size;
4968 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4969 max_stripe_size = SZ_32M;
4970 max_chunk_size = 2 * max_stripe_size;
4971 } else {
4972 btrfs_err(info, "invalid chunk type 0x%llx requested",
4973 type);
4974 BUG();
4977 /* We don't want a chunk larger than 10% of writable space */
4978 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4979 max_chunk_size);
4981 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4982 GFP_NOFS);
4983 if (!devices_info)
4984 return -ENOMEM;
4987 * in the first pass through the devices list, we gather information
4988 * about the available holes on each device.
4990 ndevs = 0;
4991 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4992 u64 max_avail;
4993 u64 dev_offset;
4995 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4996 WARN(1, KERN_ERR
4997 "BTRFS: read-only device in alloc_list\n");
4998 continue;
5001 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5002 &device->dev_state) ||
5003 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5004 continue;
5006 if (device->total_bytes > device->bytes_used)
5007 total_avail = device->total_bytes - device->bytes_used;
5008 else
5009 total_avail = 0;
5011 /* If there is no space on this device, skip it. */
5012 if (total_avail == 0)
5013 continue;
5015 ret = find_free_dev_extent(device,
5016 max_stripe_size * dev_stripes,
5017 &dev_offset, &max_avail);
5018 if (ret && ret != -ENOSPC)
5019 goto error;
5021 if (ret == 0)
5022 max_avail = max_stripe_size * dev_stripes;
5024 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
5025 if (btrfs_test_opt(info, ENOSPC_DEBUG))
5026 btrfs_debug(info,
5027 "%s: devid %llu has no free space, have=%llu want=%u",
5028 __func__, device->devid, max_avail,
5029 BTRFS_STRIPE_LEN * dev_stripes);
5030 continue;
5033 if (ndevs == fs_devices->rw_devices) {
5034 WARN(1, "%s: found more than %llu devices\n",
5035 __func__, fs_devices->rw_devices);
5036 break;
5038 devices_info[ndevs].dev_offset = dev_offset;
5039 devices_info[ndevs].max_avail = max_avail;
5040 devices_info[ndevs].total_avail = total_avail;
5041 devices_info[ndevs].dev = device;
5042 ++ndevs;
5046 * now sort the devices by hole size / available space
5048 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5049 btrfs_cmp_device_info, NULL);
5051 /* round down to number of usable stripes */
5052 ndevs = round_down(ndevs, devs_increment);
5054 if (ndevs < devs_min) {
5055 ret = -ENOSPC;
5056 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5057 btrfs_debug(info,
5058 "%s: not enough devices with free space: have=%d minimum required=%d",
5059 __func__, ndevs, devs_min);
5061 goto error;
5064 ndevs = min(ndevs, devs_max);
5067 * The primary goal is to maximize the number of stripes, so use as
5068 * many devices as possible, even if the stripes are not maximum sized.
5070 * The DUP profile stores more than one stripe per device, the
5071 * max_avail is the total size so we have to adjust.
5073 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
5074 num_stripes = ndevs * dev_stripes;
5077 * this will have to be fixed for RAID1 and RAID10 over
5078 * more drives
5080 data_stripes = (num_stripes - nparity) / ncopies;
5083 * Use the number of data stripes to figure out how big this chunk
5084 * is really going to be in terms of logical address space,
5085 * and compare that answer with the max chunk size. If it's higher,
5086 * we try to reduce stripe_size.
5088 if (stripe_size * data_stripes > max_chunk_size) {
5090 * Reduce stripe_size, round it up to a 16MB boundary again and
5091 * then use it, unless it ends up being even bigger than the
5092 * previous value we had already.
5094 stripe_size = min(round_up(div_u64(max_chunk_size,
5095 data_stripes), SZ_16M),
5096 stripe_size);
5099 /* align to BTRFS_STRIPE_LEN */
5100 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
5102 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
5103 if (!map) {
5104 ret = -ENOMEM;
5105 goto error;
5107 map->num_stripes = num_stripes;
5109 for (i = 0; i < ndevs; ++i) {
5110 for (j = 0; j < dev_stripes; ++j) {
5111 int s = i * dev_stripes + j;
5112 map->stripes[s].dev = devices_info[i].dev;
5113 map->stripes[s].physical = devices_info[i].dev_offset +
5114 j * stripe_size;
5117 map->stripe_len = BTRFS_STRIPE_LEN;
5118 map->io_align = BTRFS_STRIPE_LEN;
5119 map->io_width = BTRFS_STRIPE_LEN;
5120 map->type = type;
5121 map->sub_stripes = sub_stripes;
5123 chunk_size = stripe_size * data_stripes;
5125 trace_btrfs_chunk_alloc(info, map, start, chunk_size);
5127 em = alloc_extent_map();
5128 if (!em) {
5129 kfree(map);
5130 ret = -ENOMEM;
5131 goto error;
5133 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5134 em->map_lookup = map;
5135 em->start = start;
5136 em->len = chunk_size;
5137 em->block_start = 0;
5138 em->block_len = em->len;
5139 em->orig_block_len = stripe_size;
5141 em_tree = &info->mapping_tree;
5142 write_lock(&em_tree->lock);
5143 ret = add_extent_mapping(em_tree, em, 0);
5144 if (ret) {
5145 write_unlock(&em_tree->lock);
5146 free_extent_map(em);
5147 goto error;
5149 write_unlock(&em_tree->lock);
5151 ret = btrfs_make_block_group(trans, 0, type, start, chunk_size);
5152 if (ret)
5153 goto error_del_extent;
5155 for (i = 0; i < map->num_stripes; i++) {
5156 struct btrfs_device *dev = map->stripes[i].dev;
5158 btrfs_device_set_bytes_used(dev, dev->bytes_used + stripe_size);
5159 if (list_empty(&dev->post_commit_list))
5160 list_add_tail(&dev->post_commit_list,
5161 &trans->transaction->dev_update_list);
5164 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
5166 free_extent_map(em);
5167 check_raid56_incompat_flag(info, type);
5169 kfree(devices_info);
5170 return 0;
5172 error_del_extent:
5173 write_lock(&em_tree->lock);
5174 remove_extent_mapping(em_tree, em);
5175 write_unlock(&em_tree->lock);
5177 /* One for our allocation */
5178 free_extent_map(em);
5179 /* One for the tree reference */
5180 free_extent_map(em);
5181 error:
5182 kfree(devices_info);
5183 return ret;
5186 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
5187 u64 chunk_offset, u64 chunk_size)
5189 struct btrfs_fs_info *fs_info = trans->fs_info;
5190 struct btrfs_root *extent_root = fs_info->extent_root;
5191 struct btrfs_root *chunk_root = fs_info->chunk_root;
5192 struct btrfs_key key;
5193 struct btrfs_device *device;
5194 struct btrfs_chunk *chunk;
5195 struct btrfs_stripe *stripe;
5196 struct extent_map *em;
5197 struct map_lookup *map;
5198 size_t item_size;
5199 u64 dev_offset;
5200 u64 stripe_size;
5201 int i = 0;
5202 int ret = 0;
5204 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
5205 if (IS_ERR(em))
5206 return PTR_ERR(em);
5208 map = em->map_lookup;
5209 item_size = btrfs_chunk_item_size(map->num_stripes);
5210 stripe_size = em->orig_block_len;
5212 chunk = kzalloc(item_size, GFP_NOFS);
5213 if (!chunk) {
5214 ret = -ENOMEM;
5215 goto out;
5219 * Take the device list mutex to prevent races with the final phase of
5220 * a device replace operation that replaces the device object associated
5221 * with the map's stripes, because the device object's id can change
5222 * at any time during that final phase of the device replace operation
5223 * (dev-replace.c:btrfs_dev_replace_finishing()).
5225 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5226 for (i = 0; i < map->num_stripes; i++) {
5227 device = map->stripes[i].dev;
5228 dev_offset = map->stripes[i].physical;
5230 ret = btrfs_update_device(trans, device);
5231 if (ret)
5232 break;
5233 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5234 dev_offset, stripe_size);
5235 if (ret)
5236 break;
5238 if (ret) {
5239 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5240 goto out;
5243 stripe = &chunk->stripe;
5244 for (i = 0; i < map->num_stripes; i++) {
5245 device = map->stripes[i].dev;
5246 dev_offset = map->stripes[i].physical;
5248 btrfs_set_stack_stripe_devid(stripe, device->devid);
5249 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5250 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5251 stripe++;
5253 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5255 btrfs_set_stack_chunk_length(chunk, chunk_size);
5256 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5257 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5258 btrfs_set_stack_chunk_type(chunk, map->type);
5259 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5260 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5261 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5262 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5263 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5265 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5266 key.type = BTRFS_CHUNK_ITEM_KEY;
5267 key.offset = chunk_offset;
5269 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5270 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5272 * TODO: Cleanup of inserted chunk root in case of
5273 * failure.
5275 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5278 out:
5279 kfree(chunk);
5280 free_extent_map(em);
5281 return ret;
5285 * Chunk allocation falls into two parts. The first part does work
5286 * that makes the new allocated chunk usable, but does not do any operation
5287 * that modifies the chunk tree. The second part does the work that
5288 * requires modifying the chunk tree. This division is important for the
5289 * bootstrap process of adding storage to a seed btrfs.
5291 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5293 u64 chunk_offset;
5295 lockdep_assert_held(&trans->fs_info->chunk_mutex);
5296 chunk_offset = find_next_chunk(trans->fs_info);
5297 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5300 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5302 struct btrfs_fs_info *fs_info = trans->fs_info;
5303 u64 chunk_offset;
5304 u64 sys_chunk_offset;
5305 u64 alloc_profile;
5306 int ret;
5308 chunk_offset = find_next_chunk(fs_info);
5309 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5310 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5311 if (ret)
5312 return ret;
5314 sys_chunk_offset = find_next_chunk(fs_info);
5315 alloc_profile = btrfs_system_alloc_profile(fs_info);
5316 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5317 return ret;
5320 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5322 const int index = btrfs_bg_flags_to_raid_index(map->type);
5324 return btrfs_raid_array[index].tolerated_failures;
5327 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5329 struct extent_map *em;
5330 struct map_lookup *map;
5331 int readonly = 0;
5332 int miss_ndevs = 0;
5333 int i;
5335 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5336 if (IS_ERR(em))
5337 return 1;
5339 map = em->map_lookup;
5340 for (i = 0; i < map->num_stripes; i++) {
5341 if (test_bit(BTRFS_DEV_STATE_MISSING,
5342 &map->stripes[i].dev->dev_state)) {
5343 miss_ndevs++;
5344 continue;
5346 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5347 &map->stripes[i].dev->dev_state)) {
5348 readonly = 1;
5349 goto end;
5354 * If the number of missing devices is larger than max errors,
5355 * we can not write the data into that chunk successfully, so
5356 * set it readonly.
5358 if (miss_ndevs > btrfs_chunk_max_errors(map))
5359 readonly = 1;
5360 end:
5361 free_extent_map(em);
5362 return readonly;
5365 void btrfs_mapping_tree_free(struct extent_map_tree *tree)
5367 struct extent_map *em;
5369 while (1) {
5370 write_lock(&tree->lock);
5371 em = lookup_extent_mapping(tree, 0, (u64)-1);
5372 if (em)
5373 remove_extent_mapping(tree, em);
5374 write_unlock(&tree->lock);
5375 if (!em)
5376 break;
5377 /* once for us */
5378 free_extent_map(em);
5379 /* once for the tree */
5380 free_extent_map(em);
5384 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5386 struct extent_map *em;
5387 struct map_lookup *map;
5388 int ret;
5390 em = btrfs_get_chunk_map(fs_info, logical, len);
5391 if (IS_ERR(em))
5393 * We could return errors for these cases, but that could get
5394 * ugly and we'd probably do the same thing which is just not do
5395 * anything else and exit, so return 1 so the callers don't try
5396 * to use other copies.
5398 return 1;
5400 map = em->map_lookup;
5401 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5402 ret = map->num_stripes;
5403 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5404 ret = map->sub_stripes;
5405 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5406 ret = 2;
5407 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5409 * There could be two corrupted data stripes, we need
5410 * to loop retry in order to rebuild the correct data.
5412 * Fail a stripe at a time on every retry except the
5413 * stripe under reconstruction.
5415 ret = map->num_stripes;
5416 else
5417 ret = 1;
5418 free_extent_map(em);
5420 down_read(&fs_info->dev_replace.rwsem);
5421 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5422 fs_info->dev_replace.tgtdev)
5423 ret++;
5424 up_read(&fs_info->dev_replace.rwsem);
5426 return ret;
5429 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5430 u64 logical)
5432 struct extent_map *em;
5433 struct map_lookup *map;
5434 unsigned long len = fs_info->sectorsize;
5436 em = btrfs_get_chunk_map(fs_info, logical, len);
5438 if (!WARN_ON(IS_ERR(em))) {
5439 map = em->map_lookup;
5440 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5441 len = map->stripe_len * nr_data_stripes(map);
5442 free_extent_map(em);
5444 return len;
5447 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5449 struct extent_map *em;
5450 struct map_lookup *map;
5451 int ret = 0;
5453 em = btrfs_get_chunk_map(fs_info, logical, len);
5455 if(!WARN_ON(IS_ERR(em))) {
5456 map = em->map_lookup;
5457 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5458 ret = 1;
5459 free_extent_map(em);
5461 return ret;
5464 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5465 struct map_lookup *map, int first,
5466 int dev_replace_is_ongoing)
5468 int i;
5469 int num_stripes;
5470 int preferred_mirror;
5471 int tolerance;
5472 struct btrfs_device *srcdev;
5474 ASSERT((map->type &
5475 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)));
5477 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5478 num_stripes = map->sub_stripes;
5479 else
5480 num_stripes = map->num_stripes;
5482 preferred_mirror = first + current->pid % num_stripes;
5484 if (dev_replace_is_ongoing &&
5485 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5486 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5487 srcdev = fs_info->dev_replace.srcdev;
5488 else
5489 srcdev = NULL;
5492 * try to avoid the drive that is the source drive for a
5493 * dev-replace procedure, only choose it if no other non-missing
5494 * mirror is available
5496 for (tolerance = 0; tolerance < 2; tolerance++) {
5497 if (map->stripes[preferred_mirror].dev->bdev &&
5498 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5499 return preferred_mirror;
5500 for (i = first; i < first + num_stripes; i++) {
5501 if (map->stripes[i].dev->bdev &&
5502 (tolerance || map->stripes[i].dev != srcdev))
5503 return i;
5507 /* we couldn't find one that doesn't fail. Just return something
5508 * and the io error handling code will clean up eventually
5510 return preferred_mirror;
5513 static inline int parity_smaller(u64 a, u64 b)
5515 return a > b;
5518 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5519 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5521 struct btrfs_bio_stripe s;
5522 int i;
5523 u64 l;
5524 int again = 1;
5526 while (again) {
5527 again = 0;
5528 for (i = 0; i < num_stripes - 1; i++) {
5529 if (parity_smaller(bbio->raid_map[i],
5530 bbio->raid_map[i+1])) {
5531 s = bbio->stripes[i];
5532 l = bbio->raid_map[i];
5533 bbio->stripes[i] = bbio->stripes[i+1];
5534 bbio->raid_map[i] = bbio->raid_map[i+1];
5535 bbio->stripes[i+1] = s;
5536 bbio->raid_map[i+1] = l;
5538 again = 1;
5544 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5546 struct btrfs_bio *bbio = kzalloc(
5547 /* the size of the btrfs_bio */
5548 sizeof(struct btrfs_bio) +
5549 /* plus the variable array for the stripes */
5550 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5551 /* plus the variable array for the tgt dev */
5552 sizeof(int) * (real_stripes) +
5554 * plus the raid_map, which includes both the tgt dev
5555 * and the stripes
5557 sizeof(u64) * (total_stripes),
5558 GFP_NOFS|__GFP_NOFAIL);
5560 atomic_set(&bbio->error, 0);
5561 refcount_set(&bbio->refs, 1);
5563 return bbio;
5566 void btrfs_get_bbio(struct btrfs_bio *bbio)
5568 WARN_ON(!refcount_read(&bbio->refs));
5569 refcount_inc(&bbio->refs);
5572 void btrfs_put_bbio(struct btrfs_bio *bbio)
5574 if (!bbio)
5575 return;
5576 if (refcount_dec_and_test(&bbio->refs))
5577 kfree(bbio);
5580 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5582 * Please note that, discard won't be sent to target device of device
5583 * replace.
5585 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5586 u64 logical, u64 length,
5587 struct btrfs_bio **bbio_ret)
5589 struct extent_map *em;
5590 struct map_lookup *map;
5591 struct btrfs_bio *bbio;
5592 u64 offset;
5593 u64 stripe_nr;
5594 u64 stripe_nr_end;
5595 u64 stripe_end_offset;
5596 u64 stripe_cnt;
5597 u64 stripe_len;
5598 u64 stripe_offset;
5599 u64 num_stripes;
5600 u32 stripe_index;
5601 u32 factor = 0;
5602 u32 sub_stripes = 0;
5603 u64 stripes_per_dev = 0;
5604 u32 remaining_stripes = 0;
5605 u32 last_stripe = 0;
5606 int ret = 0;
5607 int i;
5609 /* discard always return a bbio */
5610 ASSERT(bbio_ret);
5612 em = btrfs_get_chunk_map(fs_info, logical, length);
5613 if (IS_ERR(em))
5614 return PTR_ERR(em);
5616 map = em->map_lookup;
5617 /* we don't discard raid56 yet */
5618 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5619 ret = -EOPNOTSUPP;
5620 goto out;
5623 offset = logical - em->start;
5624 length = min_t(u64, em->len - offset, length);
5626 stripe_len = map->stripe_len;
5628 * stripe_nr counts the total number of stripes we have to stride
5629 * to get to this block
5631 stripe_nr = div64_u64(offset, stripe_len);
5633 /* stripe_offset is the offset of this block in its stripe */
5634 stripe_offset = offset - stripe_nr * stripe_len;
5636 stripe_nr_end = round_up(offset + length, map->stripe_len);
5637 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5638 stripe_cnt = stripe_nr_end - stripe_nr;
5639 stripe_end_offset = stripe_nr_end * map->stripe_len -
5640 (offset + length);
5642 * after this, stripe_nr is the number of stripes on this
5643 * device we have to walk to find the data, and stripe_index is
5644 * the number of our device in the stripe array
5646 num_stripes = 1;
5647 stripe_index = 0;
5648 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5649 BTRFS_BLOCK_GROUP_RAID10)) {
5650 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5651 sub_stripes = 1;
5652 else
5653 sub_stripes = map->sub_stripes;
5655 factor = map->num_stripes / sub_stripes;
5656 num_stripes = min_t(u64, map->num_stripes,
5657 sub_stripes * stripe_cnt);
5658 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5659 stripe_index *= sub_stripes;
5660 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5661 &remaining_stripes);
5662 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5663 last_stripe *= sub_stripes;
5664 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5665 BTRFS_BLOCK_GROUP_DUP)) {
5666 num_stripes = map->num_stripes;
5667 } else {
5668 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5669 &stripe_index);
5672 bbio = alloc_btrfs_bio(num_stripes, 0);
5673 if (!bbio) {
5674 ret = -ENOMEM;
5675 goto out;
5678 for (i = 0; i < num_stripes; i++) {
5679 bbio->stripes[i].physical =
5680 map->stripes[stripe_index].physical +
5681 stripe_offset + stripe_nr * map->stripe_len;
5682 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5684 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5685 BTRFS_BLOCK_GROUP_RAID10)) {
5686 bbio->stripes[i].length = stripes_per_dev *
5687 map->stripe_len;
5689 if (i / sub_stripes < remaining_stripes)
5690 bbio->stripes[i].length +=
5691 map->stripe_len;
5694 * Special for the first stripe and
5695 * the last stripe:
5697 * |-------|...|-------|
5698 * |----------|
5699 * off end_off
5701 if (i < sub_stripes)
5702 bbio->stripes[i].length -=
5703 stripe_offset;
5705 if (stripe_index >= last_stripe &&
5706 stripe_index <= (last_stripe +
5707 sub_stripes - 1))
5708 bbio->stripes[i].length -=
5709 stripe_end_offset;
5711 if (i == sub_stripes - 1)
5712 stripe_offset = 0;
5713 } else {
5714 bbio->stripes[i].length = length;
5717 stripe_index++;
5718 if (stripe_index == map->num_stripes) {
5719 stripe_index = 0;
5720 stripe_nr++;
5724 *bbio_ret = bbio;
5725 bbio->map_type = map->type;
5726 bbio->num_stripes = num_stripes;
5727 out:
5728 free_extent_map(em);
5729 return ret;
5733 * In dev-replace case, for repair case (that's the only case where the mirror
5734 * is selected explicitly when calling btrfs_map_block), blocks left of the
5735 * left cursor can also be read from the target drive.
5737 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5738 * array of stripes.
5739 * For READ, it also needs to be supported using the same mirror number.
5741 * If the requested block is not left of the left cursor, EIO is returned. This
5742 * can happen because btrfs_num_copies() returns one more in the dev-replace
5743 * case.
5745 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5746 u64 logical, u64 length,
5747 u64 srcdev_devid, int *mirror_num,
5748 u64 *physical)
5750 struct btrfs_bio *bbio = NULL;
5751 int num_stripes;
5752 int index_srcdev = 0;
5753 int found = 0;
5754 u64 physical_of_found = 0;
5755 int i;
5756 int ret = 0;
5758 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5759 logical, &length, &bbio, 0, 0);
5760 if (ret) {
5761 ASSERT(bbio == NULL);
5762 return ret;
5765 num_stripes = bbio->num_stripes;
5766 if (*mirror_num > num_stripes) {
5768 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5769 * that means that the requested area is not left of the left
5770 * cursor
5772 btrfs_put_bbio(bbio);
5773 return -EIO;
5777 * process the rest of the function using the mirror_num of the source
5778 * drive. Therefore look it up first. At the end, patch the device
5779 * pointer to the one of the target drive.
5781 for (i = 0; i < num_stripes; i++) {
5782 if (bbio->stripes[i].dev->devid != srcdev_devid)
5783 continue;
5786 * In case of DUP, in order to keep it simple, only add the
5787 * mirror with the lowest physical address
5789 if (found &&
5790 physical_of_found <= bbio->stripes[i].physical)
5791 continue;
5793 index_srcdev = i;
5794 found = 1;
5795 physical_of_found = bbio->stripes[i].physical;
5798 btrfs_put_bbio(bbio);
5800 ASSERT(found);
5801 if (!found)
5802 return -EIO;
5804 *mirror_num = index_srcdev + 1;
5805 *physical = physical_of_found;
5806 return ret;
5809 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5810 struct btrfs_bio **bbio_ret,
5811 struct btrfs_dev_replace *dev_replace,
5812 int *num_stripes_ret, int *max_errors_ret)
5814 struct btrfs_bio *bbio = *bbio_ret;
5815 u64 srcdev_devid = dev_replace->srcdev->devid;
5816 int tgtdev_indexes = 0;
5817 int num_stripes = *num_stripes_ret;
5818 int max_errors = *max_errors_ret;
5819 int i;
5821 if (op == BTRFS_MAP_WRITE) {
5822 int index_where_to_add;
5825 * duplicate the write operations while the dev replace
5826 * procedure is running. Since the copying of the old disk to
5827 * the new disk takes place at run time while the filesystem is
5828 * mounted writable, the regular write operations to the old
5829 * disk have to be duplicated to go to the new disk as well.
5831 * Note that device->missing is handled by the caller, and that
5832 * the write to the old disk is already set up in the stripes
5833 * array.
5835 index_where_to_add = num_stripes;
5836 for (i = 0; i < num_stripes; i++) {
5837 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5838 /* write to new disk, too */
5839 struct btrfs_bio_stripe *new =
5840 bbio->stripes + index_where_to_add;
5841 struct btrfs_bio_stripe *old =
5842 bbio->stripes + i;
5844 new->physical = old->physical;
5845 new->length = old->length;
5846 new->dev = dev_replace->tgtdev;
5847 bbio->tgtdev_map[i] = index_where_to_add;
5848 index_where_to_add++;
5849 max_errors++;
5850 tgtdev_indexes++;
5853 num_stripes = index_where_to_add;
5854 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5855 int index_srcdev = 0;
5856 int found = 0;
5857 u64 physical_of_found = 0;
5860 * During the dev-replace procedure, the target drive can also
5861 * be used to read data in case it is needed to repair a corrupt
5862 * block elsewhere. This is possible if the requested area is
5863 * left of the left cursor. In this area, the target drive is a
5864 * full copy of the source drive.
5866 for (i = 0; i < num_stripes; i++) {
5867 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5869 * In case of DUP, in order to keep it simple,
5870 * only add the mirror with the lowest physical
5871 * address
5873 if (found &&
5874 physical_of_found <=
5875 bbio->stripes[i].physical)
5876 continue;
5877 index_srcdev = i;
5878 found = 1;
5879 physical_of_found = bbio->stripes[i].physical;
5882 if (found) {
5883 struct btrfs_bio_stripe *tgtdev_stripe =
5884 bbio->stripes + num_stripes;
5886 tgtdev_stripe->physical = physical_of_found;
5887 tgtdev_stripe->length =
5888 bbio->stripes[index_srcdev].length;
5889 tgtdev_stripe->dev = dev_replace->tgtdev;
5890 bbio->tgtdev_map[index_srcdev] = num_stripes;
5892 tgtdev_indexes++;
5893 num_stripes++;
5897 *num_stripes_ret = num_stripes;
5898 *max_errors_ret = max_errors;
5899 bbio->num_tgtdevs = tgtdev_indexes;
5900 *bbio_ret = bbio;
5903 static bool need_full_stripe(enum btrfs_map_op op)
5905 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5908 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5909 enum btrfs_map_op op,
5910 u64 logical, u64 *length,
5911 struct btrfs_bio **bbio_ret,
5912 int mirror_num, int need_raid_map)
5914 struct extent_map *em;
5915 struct map_lookup *map;
5916 u64 offset;
5917 u64 stripe_offset;
5918 u64 stripe_nr;
5919 u64 stripe_len;
5920 u32 stripe_index;
5921 int i;
5922 int ret = 0;
5923 int num_stripes;
5924 int max_errors = 0;
5925 int tgtdev_indexes = 0;
5926 struct btrfs_bio *bbio = NULL;
5927 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5928 int dev_replace_is_ongoing = 0;
5929 int num_alloc_stripes;
5930 int patch_the_first_stripe_for_dev_replace = 0;
5931 u64 physical_to_patch_in_first_stripe = 0;
5932 u64 raid56_full_stripe_start = (u64)-1;
5934 if (op == BTRFS_MAP_DISCARD)
5935 return __btrfs_map_block_for_discard(fs_info, logical,
5936 *length, bbio_ret);
5938 em = btrfs_get_chunk_map(fs_info, logical, *length);
5939 if (IS_ERR(em))
5940 return PTR_ERR(em);
5942 map = em->map_lookup;
5943 offset = logical - em->start;
5945 stripe_len = map->stripe_len;
5946 stripe_nr = offset;
5948 * stripe_nr counts the total number of stripes we have to stride
5949 * to get to this block
5951 stripe_nr = div64_u64(stripe_nr, stripe_len);
5953 stripe_offset = stripe_nr * stripe_len;
5954 if (offset < stripe_offset) {
5955 btrfs_crit(fs_info,
5956 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
5957 stripe_offset, offset, em->start, logical,
5958 stripe_len);
5959 free_extent_map(em);
5960 return -EINVAL;
5963 /* stripe_offset is the offset of this block in its stripe*/
5964 stripe_offset = offset - stripe_offset;
5966 /* if we're here for raid56, we need to know the stripe aligned start */
5967 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5968 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5969 raid56_full_stripe_start = offset;
5971 /* allow a write of a full stripe, but make sure we don't
5972 * allow straddling of stripes
5974 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5975 full_stripe_len);
5976 raid56_full_stripe_start *= full_stripe_len;
5979 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5980 u64 max_len;
5981 /* For writes to RAID[56], allow a full stripeset across all disks.
5982 For other RAID types and for RAID[56] reads, just allow a single
5983 stripe (on a single disk). */
5984 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5985 (op == BTRFS_MAP_WRITE)) {
5986 max_len = stripe_len * nr_data_stripes(map) -
5987 (offset - raid56_full_stripe_start);
5988 } else {
5989 /* we limit the length of each bio to what fits in a stripe */
5990 max_len = stripe_len - stripe_offset;
5992 *length = min_t(u64, em->len - offset, max_len);
5993 } else {
5994 *length = em->len - offset;
5998 * This is for when we're called from btrfs_bio_fits_in_stripe and all
5999 * it cares about is the length
6001 if (!bbio_ret)
6002 goto out;
6004 down_read(&dev_replace->rwsem);
6005 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6007 * Hold the semaphore for read during the whole operation, write is
6008 * requested at commit time but must wait.
6010 if (!dev_replace_is_ongoing)
6011 up_read(&dev_replace->rwsem);
6013 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6014 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6015 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6016 dev_replace->srcdev->devid,
6017 &mirror_num,
6018 &physical_to_patch_in_first_stripe);
6019 if (ret)
6020 goto out;
6021 else
6022 patch_the_first_stripe_for_dev_replace = 1;
6023 } else if (mirror_num > map->num_stripes) {
6024 mirror_num = 0;
6027 num_stripes = 1;
6028 stripe_index = 0;
6029 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6030 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6031 &stripe_index);
6032 if (!need_full_stripe(op))
6033 mirror_num = 1;
6034 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
6035 if (need_full_stripe(op))
6036 num_stripes = map->num_stripes;
6037 else if (mirror_num)
6038 stripe_index = mirror_num - 1;
6039 else {
6040 stripe_index = find_live_mirror(fs_info, map, 0,
6041 dev_replace_is_ongoing);
6042 mirror_num = stripe_index + 1;
6045 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6046 if (need_full_stripe(op)) {
6047 num_stripes = map->num_stripes;
6048 } else if (mirror_num) {
6049 stripe_index = mirror_num - 1;
6050 } else {
6051 mirror_num = 1;
6054 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6055 u32 factor = map->num_stripes / map->sub_stripes;
6057 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6058 stripe_index *= map->sub_stripes;
6060 if (need_full_stripe(op))
6061 num_stripes = map->sub_stripes;
6062 else if (mirror_num)
6063 stripe_index += mirror_num - 1;
6064 else {
6065 int old_stripe_index = stripe_index;
6066 stripe_index = find_live_mirror(fs_info, map,
6067 stripe_index,
6068 dev_replace_is_ongoing);
6069 mirror_num = stripe_index - old_stripe_index + 1;
6072 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6073 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6074 /* push stripe_nr back to the start of the full stripe */
6075 stripe_nr = div64_u64(raid56_full_stripe_start,
6076 stripe_len * nr_data_stripes(map));
6078 /* RAID[56] write or recovery. Return all stripes */
6079 num_stripes = map->num_stripes;
6080 max_errors = nr_parity_stripes(map);
6082 *length = map->stripe_len;
6083 stripe_index = 0;
6084 stripe_offset = 0;
6085 } else {
6087 * Mirror #0 or #1 means the original data block.
6088 * Mirror #2 is RAID5 parity block.
6089 * Mirror #3 is RAID6 Q block.
6091 stripe_nr = div_u64_rem(stripe_nr,
6092 nr_data_stripes(map), &stripe_index);
6093 if (mirror_num > 1)
6094 stripe_index = nr_data_stripes(map) +
6095 mirror_num - 2;
6097 /* We distribute the parity blocks across stripes */
6098 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6099 &stripe_index);
6100 if (!need_full_stripe(op) && mirror_num <= 1)
6101 mirror_num = 1;
6103 } else {
6105 * after this, stripe_nr is the number of stripes on this
6106 * device we have to walk to find the data, and stripe_index is
6107 * the number of our device in the stripe array
6109 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6110 &stripe_index);
6111 mirror_num = stripe_index + 1;
6113 if (stripe_index >= map->num_stripes) {
6114 btrfs_crit(fs_info,
6115 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6116 stripe_index, map->num_stripes);
6117 ret = -EINVAL;
6118 goto out;
6121 num_alloc_stripes = num_stripes;
6122 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6123 if (op == BTRFS_MAP_WRITE)
6124 num_alloc_stripes <<= 1;
6125 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6126 num_alloc_stripes++;
6127 tgtdev_indexes = num_stripes;
6130 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6131 if (!bbio) {
6132 ret = -ENOMEM;
6133 goto out;
6135 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
6136 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
6138 /* build raid_map */
6139 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6140 (need_full_stripe(op) || mirror_num > 1)) {
6141 u64 tmp;
6142 unsigned rot;
6144 bbio->raid_map = (u64 *)((void *)bbio->stripes +
6145 sizeof(struct btrfs_bio_stripe) *
6146 num_alloc_stripes +
6147 sizeof(int) * tgtdev_indexes);
6149 /* Work out the disk rotation on this stripe-set */
6150 div_u64_rem(stripe_nr, num_stripes, &rot);
6152 /* Fill in the logical address of each stripe */
6153 tmp = stripe_nr * nr_data_stripes(map);
6154 for (i = 0; i < nr_data_stripes(map); i++)
6155 bbio->raid_map[(i+rot) % num_stripes] =
6156 em->start + (tmp + i) * map->stripe_len;
6158 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6159 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6160 bbio->raid_map[(i+rot+1) % num_stripes] =
6161 RAID6_Q_STRIPE;
6165 for (i = 0; i < num_stripes; i++) {
6166 bbio->stripes[i].physical =
6167 map->stripes[stripe_index].physical +
6168 stripe_offset +
6169 stripe_nr * map->stripe_len;
6170 bbio->stripes[i].dev =
6171 map->stripes[stripe_index].dev;
6172 stripe_index++;
6175 if (need_full_stripe(op))
6176 max_errors = btrfs_chunk_max_errors(map);
6178 if (bbio->raid_map)
6179 sort_parity_stripes(bbio, num_stripes);
6181 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6182 need_full_stripe(op)) {
6183 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
6184 &max_errors);
6187 *bbio_ret = bbio;
6188 bbio->map_type = map->type;
6189 bbio->num_stripes = num_stripes;
6190 bbio->max_errors = max_errors;
6191 bbio->mirror_num = mirror_num;
6194 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6195 * mirror_num == num_stripes + 1 && dev_replace target drive is
6196 * available as a mirror
6198 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6199 WARN_ON(num_stripes > 1);
6200 bbio->stripes[0].dev = dev_replace->tgtdev;
6201 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6202 bbio->mirror_num = map->num_stripes + 1;
6204 out:
6205 if (dev_replace_is_ongoing) {
6206 lockdep_assert_held(&dev_replace->rwsem);
6207 /* Unlock and let waiting writers proceed */
6208 up_read(&dev_replace->rwsem);
6210 free_extent_map(em);
6211 return ret;
6214 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6215 u64 logical, u64 *length,
6216 struct btrfs_bio **bbio_ret, int mirror_num)
6218 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6219 mirror_num, 0);
6222 /* For Scrub/replace */
6223 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6224 u64 logical, u64 *length,
6225 struct btrfs_bio **bbio_ret)
6227 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6230 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
6231 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
6233 struct extent_map *em;
6234 struct map_lookup *map;
6235 u64 *buf;
6236 u64 bytenr;
6237 u64 length;
6238 u64 stripe_nr;
6239 u64 rmap_len;
6240 int i, j, nr = 0;
6242 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
6243 if (IS_ERR(em))
6244 return -EIO;
6246 map = em->map_lookup;
6247 length = em->len;
6248 rmap_len = map->stripe_len;
6250 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6251 length = div_u64(length, map->num_stripes / map->sub_stripes);
6252 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6253 length = div_u64(length, map->num_stripes);
6254 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6255 length = div_u64(length, nr_data_stripes(map));
6256 rmap_len = map->stripe_len * nr_data_stripes(map);
6259 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
6260 BUG_ON(!buf); /* -ENOMEM */
6262 for (i = 0; i < map->num_stripes; i++) {
6263 if (map->stripes[i].physical > physical ||
6264 map->stripes[i].physical + length <= physical)
6265 continue;
6267 stripe_nr = physical - map->stripes[i].physical;
6268 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
6270 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6271 stripe_nr = stripe_nr * map->num_stripes + i;
6272 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
6273 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6274 stripe_nr = stripe_nr * map->num_stripes + i;
6275 } /* else if RAID[56], multiply by nr_data_stripes().
6276 * Alternatively, just use rmap_len below instead of
6277 * map->stripe_len */
6279 bytenr = chunk_start + stripe_nr * rmap_len;
6280 WARN_ON(nr >= map->num_stripes);
6281 for (j = 0; j < nr; j++) {
6282 if (buf[j] == bytenr)
6283 break;
6285 if (j == nr) {
6286 WARN_ON(nr >= map->num_stripes);
6287 buf[nr++] = bytenr;
6291 *logical = buf;
6292 *naddrs = nr;
6293 *stripe_len = rmap_len;
6295 free_extent_map(em);
6296 return 0;
6299 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6301 bio->bi_private = bbio->private;
6302 bio->bi_end_io = bbio->end_io;
6303 bio_endio(bio);
6305 btrfs_put_bbio(bbio);
6308 static void btrfs_end_bio(struct bio *bio)
6310 struct btrfs_bio *bbio = bio->bi_private;
6311 int is_orig_bio = 0;
6313 if (bio->bi_status) {
6314 atomic_inc(&bbio->error);
6315 if (bio->bi_status == BLK_STS_IOERR ||
6316 bio->bi_status == BLK_STS_TARGET) {
6317 unsigned int stripe_index =
6318 btrfs_io_bio(bio)->stripe_index;
6319 struct btrfs_device *dev;
6321 BUG_ON(stripe_index >= bbio->num_stripes);
6322 dev = bbio->stripes[stripe_index].dev;
6323 if (dev->bdev) {
6324 if (bio_op(bio) == REQ_OP_WRITE)
6325 btrfs_dev_stat_inc_and_print(dev,
6326 BTRFS_DEV_STAT_WRITE_ERRS);
6327 else if (!(bio->bi_opf & REQ_RAHEAD))
6328 btrfs_dev_stat_inc_and_print(dev,
6329 BTRFS_DEV_STAT_READ_ERRS);
6330 if (bio->bi_opf & REQ_PREFLUSH)
6331 btrfs_dev_stat_inc_and_print(dev,
6332 BTRFS_DEV_STAT_FLUSH_ERRS);
6337 if (bio == bbio->orig_bio)
6338 is_orig_bio = 1;
6340 btrfs_bio_counter_dec(bbio->fs_info);
6342 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6343 if (!is_orig_bio) {
6344 bio_put(bio);
6345 bio = bbio->orig_bio;
6348 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6349 /* only send an error to the higher layers if it is
6350 * beyond the tolerance of the btrfs bio
6352 if (atomic_read(&bbio->error) > bbio->max_errors) {
6353 bio->bi_status = BLK_STS_IOERR;
6354 } else {
6356 * this bio is actually up to date, we didn't
6357 * go over the max number of errors
6359 bio->bi_status = BLK_STS_OK;
6362 btrfs_end_bbio(bbio, bio);
6363 } else if (!is_orig_bio) {
6364 bio_put(bio);
6369 * see run_scheduled_bios for a description of why bios are collected for
6370 * async submit.
6372 * This will add one bio to the pending list for a device and make sure
6373 * the work struct is scheduled.
6375 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6376 struct bio *bio)
6378 struct btrfs_fs_info *fs_info = device->fs_info;
6379 int should_queue = 1;
6380 struct btrfs_pending_bios *pending_bios;
6382 /* don't bother with additional async steps for reads, right now */
6383 if (bio_op(bio) == REQ_OP_READ) {
6384 btrfsic_submit_bio(bio);
6385 return;
6388 WARN_ON(bio->bi_next);
6389 bio->bi_next = NULL;
6391 spin_lock(&device->io_lock);
6392 if (op_is_sync(bio->bi_opf))
6393 pending_bios = &device->pending_sync_bios;
6394 else
6395 pending_bios = &device->pending_bios;
6397 if (pending_bios->tail)
6398 pending_bios->tail->bi_next = bio;
6400 pending_bios->tail = bio;
6401 if (!pending_bios->head)
6402 pending_bios->head = bio;
6403 if (device->running_pending)
6404 should_queue = 0;
6406 spin_unlock(&device->io_lock);
6408 if (should_queue)
6409 btrfs_queue_work(fs_info->submit_workers, &device->work);
6412 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6413 u64 physical, int dev_nr, int async)
6415 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6416 struct btrfs_fs_info *fs_info = bbio->fs_info;
6418 bio->bi_private = bbio;
6419 btrfs_io_bio(bio)->stripe_index = dev_nr;
6420 bio->bi_end_io = btrfs_end_bio;
6421 bio->bi_iter.bi_sector = physical >> 9;
6422 btrfs_debug_in_rcu(fs_info,
6423 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6424 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6425 (u_long)dev->bdev->bd_dev, rcu_str_deref(dev->name), dev->devid,
6426 bio->bi_iter.bi_size);
6427 bio_set_dev(bio, dev->bdev);
6429 btrfs_bio_counter_inc_noblocked(fs_info);
6431 if (async)
6432 btrfs_schedule_bio(dev, bio);
6433 else
6434 btrfsic_submit_bio(bio);
6437 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6439 atomic_inc(&bbio->error);
6440 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6441 /* Should be the original bio. */
6442 WARN_ON(bio != bbio->orig_bio);
6444 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6445 bio->bi_iter.bi_sector = logical >> 9;
6446 if (atomic_read(&bbio->error) > bbio->max_errors)
6447 bio->bi_status = BLK_STS_IOERR;
6448 else
6449 bio->bi_status = BLK_STS_OK;
6450 btrfs_end_bbio(bbio, bio);
6454 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6455 int mirror_num, int async_submit)
6457 struct btrfs_device *dev;
6458 struct bio *first_bio = bio;
6459 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6460 u64 length = 0;
6461 u64 map_length;
6462 int ret;
6463 int dev_nr;
6464 int total_devs;
6465 struct btrfs_bio *bbio = NULL;
6467 length = bio->bi_iter.bi_size;
6468 map_length = length;
6470 btrfs_bio_counter_inc_blocked(fs_info);
6471 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6472 &map_length, &bbio, mirror_num, 1);
6473 if (ret) {
6474 btrfs_bio_counter_dec(fs_info);
6475 return errno_to_blk_status(ret);
6478 total_devs = bbio->num_stripes;
6479 bbio->orig_bio = first_bio;
6480 bbio->private = first_bio->bi_private;
6481 bbio->end_io = first_bio->bi_end_io;
6482 bbio->fs_info = fs_info;
6483 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6485 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6486 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6487 /* In this case, map_length has been set to the length of
6488 a single stripe; not the whole write */
6489 if (bio_op(bio) == REQ_OP_WRITE) {
6490 ret = raid56_parity_write(fs_info, bio, bbio,
6491 map_length);
6492 } else {
6493 ret = raid56_parity_recover(fs_info, bio, bbio,
6494 map_length, mirror_num, 1);
6497 btrfs_bio_counter_dec(fs_info);
6498 return errno_to_blk_status(ret);
6501 if (map_length < length) {
6502 btrfs_crit(fs_info,
6503 "mapping failed logical %llu bio len %llu len %llu",
6504 logical, length, map_length);
6505 BUG();
6508 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6509 dev = bbio->stripes[dev_nr].dev;
6510 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6511 &dev->dev_state) ||
6512 (bio_op(first_bio) == REQ_OP_WRITE &&
6513 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6514 bbio_error(bbio, first_bio, logical);
6515 continue;
6518 if (dev_nr < total_devs - 1)
6519 bio = btrfs_bio_clone(first_bio);
6520 else
6521 bio = first_bio;
6523 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6524 dev_nr, async_submit);
6526 btrfs_bio_counter_dec(fs_info);
6527 return BLK_STS_OK;
6531 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6532 * return NULL.
6534 * If devid and uuid are both specified, the match must be exact, otherwise
6535 * only devid is used.
6537 * If @seed is true, traverse through the seed devices.
6539 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6540 u64 devid, u8 *uuid, u8 *fsid,
6541 bool seed)
6543 struct btrfs_device *device;
6545 while (fs_devices) {
6546 if (!fsid ||
6547 !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6548 list_for_each_entry(device, &fs_devices->devices,
6549 dev_list) {
6550 if (device->devid == devid &&
6551 (!uuid || memcmp(device->uuid, uuid,
6552 BTRFS_UUID_SIZE) == 0))
6553 return device;
6556 if (seed)
6557 fs_devices = fs_devices->seed;
6558 else
6559 return NULL;
6561 return NULL;
6564 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6565 u64 devid, u8 *dev_uuid)
6567 struct btrfs_device *device;
6569 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6570 if (IS_ERR(device))
6571 return device;
6573 list_add(&device->dev_list, &fs_devices->devices);
6574 device->fs_devices = fs_devices;
6575 fs_devices->num_devices++;
6577 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6578 fs_devices->missing_devices++;
6580 return device;
6584 * btrfs_alloc_device - allocate struct btrfs_device
6585 * @fs_info: used only for generating a new devid, can be NULL if
6586 * devid is provided (i.e. @devid != NULL).
6587 * @devid: a pointer to devid for this device. If NULL a new devid
6588 * is generated.
6589 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6590 * is generated.
6592 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6593 * on error. Returned struct is not linked onto any lists and must be
6594 * destroyed with btrfs_free_device.
6596 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6597 const u64 *devid,
6598 const u8 *uuid)
6600 struct btrfs_device *dev;
6601 u64 tmp;
6603 if (WARN_ON(!devid && !fs_info))
6604 return ERR_PTR(-EINVAL);
6606 dev = __alloc_device();
6607 if (IS_ERR(dev))
6608 return dev;
6610 if (devid)
6611 tmp = *devid;
6612 else {
6613 int ret;
6615 ret = find_next_devid(fs_info, &tmp);
6616 if (ret) {
6617 btrfs_free_device(dev);
6618 return ERR_PTR(ret);
6621 dev->devid = tmp;
6623 if (uuid)
6624 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6625 else
6626 generate_random_uuid(dev->uuid);
6628 btrfs_init_work(&dev->work, btrfs_submit_helper,
6629 pending_bios_fn, NULL, NULL);
6631 return dev;
6634 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6635 u64 devid, u8 *uuid, bool error)
6637 if (error)
6638 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6639 devid, uuid);
6640 else
6641 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6642 devid, uuid);
6645 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
6647 int index = btrfs_bg_flags_to_raid_index(type);
6648 int ncopies = btrfs_raid_array[index].ncopies;
6649 int data_stripes;
6651 switch (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6652 case BTRFS_BLOCK_GROUP_RAID5:
6653 data_stripes = num_stripes - 1;
6654 break;
6655 case BTRFS_BLOCK_GROUP_RAID6:
6656 data_stripes = num_stripes - 2;
6657 break;
6658 default:
6659 data_stripes = num_stripes / ncopies;
6660 break;
6662 return div_u64(chunk_len, data_stripes);
6665 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
6666 struct btrfs_chunk *chunk)
6668 struct btrfs_fs_info *fs_info = leaf->fs_info;
6669 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
6670 struct map_lookup *map;
6671 struct extent_map *em;
6672 u64 logical;
6673 u64 length;
6674 u64 devid;
6675 u8 uuid[BTRFS_UUID_SIZE];
6676 int num_stripes;
6677 int ret;
6678 int i;
6680 logical = key->offset;
6681 length = btrfs_chunk_length(leaf, chunk);
6682 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6685 * Only need to verify chunk item if we're reading from sys chunk array,
6686 * as chunk item in tree block is already verified by tree-checker.
6688 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6689 ret = btrfs_check_chunk_valid(leaf, chunk, logical);
6690 if (ret)
6691 return ret;
6694 read_lock(&map_tree->lock);
6695 em = lookup_extent_mapping(map_tree, logical, 1);
6696 read_unlock(&map_tree->lock);
6698 /* already mapped? */
6699 if (em && em->start <= logical && em->start + em->len > logical) {
6700 free_extent_map(em);
6701 return 0;
6702 } else if (em) {
6703 free_extent_map(em);
6706 em = alloc_extent_map();
6707 if (!em)
6708 return -ENOMEM;
6709 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6710 if (!map) {
6711 free_extent_map(em);
6712 return -ENOMEM;
6715 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6716 em->map_lookup = map;
6717 em->start = logical;
6718 em->len = length;
6719 em->orig_start = 0;
6720 em->block_start = 0;
6721 em->block_len = em->len;
6723 map->num_stripes = num_stripes;
6724 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6725 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6726 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6727 map->type = btrfs_chunk_type(leaf, chunk);
6728 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6729 map->verified_stripes = 0;
6730 em->orig_block_len = calc_stripe_length(map->type, em->len,
6731 map->num_stripes);
6732 for (i = 0; i < num_stripes; i++) {
6733 map->stripes[i].physical =
6734 btrfs_stripe_offset_nr(leaf, chunk, i);
6735 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6736 read_extent_buffer(leaf, uuid, (unsigned long)
6737 btrfs_stripe_dev_uuid_nr(chunk, i),
6738 BTRFS_UUID_SIZE);
6739 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
6740 devid, uuid, NULL, true);
6741 if (!map->stripes[i].dev &&
6742 !btrfs_test_opt(fs_info, DEGRADED)) {
6743 free_extent_map(em);
6744 btrfs_report_missing_device(fs_info, devid, uuid, true);
6745 return -ENOENT;
6747 if (!map->stripes[i].dev) {
6748 map->stripes[i].dev =
6749 add_missing_dev(fs_info->fs_devices, devid,
6750 uuid);
6751 if (IS_ERR(map->stripes[i].dev)) {
6752 free_extent_map(em);
6753 btrfs_err(fs_info,
6754 "failed to init missing dev %llu: %ld",
6755 devid, PTR_ERR(map->stripes[i].dev));
6756 return PTR_ERR(map->stripes[i].dev);
6758 btrfs_report_missing_device(fs_info, devid, uuid, false);
6760 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6761 &(map->stripes[i].dev->dev_state));
6765 write_lock(&map_tree->lock);
6766 ret = add_extent_mapping(map_tree, em, 0);
6767 write_unlock(&map_tree->lock);
6768 if (ret < 0) {
6769 btrfs_err(fs_info,
6770 "failed to add chunk map, start=%llu len=%llu: %d",
6771 em->start, em->len, ret);
6773 free_extent_map(em);
6775 return ret;
6778 static void fill_device_from_item(struct extent_buffer *leaf,
6779 struct btrfs_dev_item *dev_item,
6780 struct btrfs_device *device)
6782 unsigned long ptr;
6784 device->devid = btrfs_device_id(leaf, dev_item);
6785 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6786 device->total_bytes = device->disk_total_bytes;
6787 device->commit_total_bytes = device->disk_total_bytes;
6788 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6789 device->commit_bytes_used = device->bytes_used;
6790 device->type = btrfs_device_type(leaf, dev_item);
6791 device->io_align = btrfs_device_io_align(leaf, dev_item);
6792 device->io_width = btrfs_device_io_width(leaf, dev_item);
6793 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6794 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6795 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6797 ptr = btrfs_device_uuid(dev_item);
6798 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6801 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6802 u8 *fsid)
6804 struct btrfs_fs_devices *fs_devices;
6805 int ret;
6807 lockdep_assert_held(&uuid_mutex);
6808 ASSERT(fsid);
6810 fs_devices = fs_info->fs_devices->seed;
6811 while (fs_devices) {
6812 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6813 return fs_devices;
6815 fs_devices = fs_devices->seed;
6818 fs_devices = find_fsid(fsid, NULL);
6819 if (!fs_devices) {
6820 if (!btrfs_test_opt(fs_info, DEGRADED))
6821 return ERR_PTR(-ENOENT);
6823 fs_devices = alloc_fs_devices(fsid, NULL);
6824 if (IS_ERR(fs_devices))
6825 return fs_devices;
6827 fs_devices->seeding = 1;
6828 fs_devices->opened = 1;
6829 return fs_devices;
6832 fs_devices = clone_fs_devices(fs_devices);
6833 if (IS_ERR(fs_devices))
6834 return fs_devices;
6836 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6837 if (ret) {
6838 free_fs_devices(fs_devices);
6839 fs_devices = ERR_PTR(ret);
6840 goto out;
6843 if (!fs_devices->seeding) {
6844 close_fs_devices(fs_devices);
6845 free_fs_devices(fs_devices);
6846 fs_devices = ERR_PTR(-EINVAL);
6847 goto out;
6850 fs_devices->seed = fs_info->fs_devices->seed;
6851 fs_info->fs_devices->seed = fs_devices;
6852 out:
6853 return fs_devices;
6856 static int read_one_dev(struct extent_buffer *leaf,
6857 struct btrfs_dev_item *dev_item)
6859 struct btrfs_fs_info *fs_info = leaf->fs_info;
6860 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6861 struct btrfs_device *device;
6862 u64 devid;
6863 int ret;
6864 u8 fs_uuid[BTRFS_FSID_SIZE];
6865 u8 dev_uuid[BTRFS_UUID_SIZE];
6867 devid = btrfs_device_id(leaf, dev_item);
6868 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6869 BTRFS_UUID_SIZE);
6870 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6871 BTRFS_FSID_SIZE);
6873 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
6874 fs_devices = open_seed_devices(fs_info, fs_uuid);
6875 if (IS_ERR(fs_devices))
6876 return PTR_ERR(fs_devices);
6879 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
6880 fs_uuid, true);
6881 if (!device) {
6882 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6883 btrfs_report_missing_device(fs_info, devid,
6884 dev_uuid, true);
6885 return -ENOENT;
6888 device = add_missing_dev(fs_devices, devid, dev_uuid);
6889 if (IS_ERR(device)) {
6890 btrfs_err(fs_info,
6891 "failed to add missing dev %llu: %ld",
6892 devid, PTR_ERR(device));
6893 return PTR_ERR(device);
6895 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6896 } else {
6897 if (!device->bdev) {
6898 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6899 btrfs_report_missing_device(fs_info,
6900 devid, dev_uuid, true);
6901 return -ENOENT;
6903 btrfs_report_missing_device(fs_info, devid,
6904 dev_uuid, false);
6907 if (!device->bdev &&
6908 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6910 * this happens when a device that was properly setup
6911 * in the device info lists suddenly goes bad.
6912 * device->bdev is NULL, and so we have to set
6913 * device->missing to one here
6915 device->fs_devices->missing_devices++;
6916 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6919 /* Move the device to its own fs_devices */
6920 if (device->fs_devices != fs_devices) {
6921 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6922 &device->dev_state));
6924 list_move(&device->dev_list, &fs_devices->devices);
6925 device->fs_devices->num_devices--;
6926 fs_devices->num_devices++;
6928 device->fs_devices->missing_devices--;
6929 fs_devices->missing_devices++;
6931 device->fs_devices = fs_devices;
6935 if (device->fs_devices != fs_info->fs_devices) {
6936 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6937 if (device->generation !=
6938 btrfs_device_generation(leaf, dev_item))
6939 return -EINVAL;
6942 fill_device_from_item(leaf, dev_item, device);
6943 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6944 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6945 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6946 device->fs_devices->total_rw_bytes += device->total_bytes;
6947 atomic64_add(device->total_bytes - device->bytes_used,
6948 &fs_info->free_chunk_space);
6950 ret = 0;
6951 return ret;
6954 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6956 struct btrfs_root *root = fs_info->tree_root;
6957 struct btrfs_super_block *super_copy = fs_info->super_copy;
6958 struct extent_buffer *sb;
6959 struct btrfs_disk_key *disk_key;
6960 struct btrfs_chunk *chunk;
6961 u8 *array_ptr;
6962 unsigned long sb_array_offset;
6963 int ret = 0;
6964 u32 num_stripes;
6965 u32 array_size;
6966 u32 len = 0;
6967 u32 cur_offset;
6968 u64 type;
6969 struct btrfs_key key;
6971 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6973 * This will create extent buffer of nodesize, superblock size is
6974 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6975 * overallocate but we can keep it as-is, only the first page is used.
6977 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6978 if (IS_ERR(sb))
6979 return PTR_ERR(sb);
6980 set_extent_buffer_uptodate(sb);
6981 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6983 * The sb extent buffer is artificial and just used to read the system array.
6984 * set_extent_buffer_uptodate() call does not properly mark all it's
6985 * pages up-to-date when the page is larger: extent does not cover the
6986 * whole page and consequently check_page_uptodate does not find all
6987 * the page's extents up-to-date (the hole beyond sb),
6988 * write_extent_buffer then triggers a WARN_ON.
6990 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6991 * but sb spans only this function. Add an explicit SetPageUptodate call
6992 * to silence the warning eg. on PowerPC 64.
6994 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6995 SetPageUptodate(sb->pages[0]);
6997 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6998 array_size = btrfs_super_sys_array_size(super_copy);
7000 array_ptr = super_copy->sys_chunk_array;
7001 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7002 cur_offset = 0;
7004 while (cur_offset < array_size) {
7005 disk_key = (struct btrfs_disk_key *)array_ptr;
7006 len = sizeof(*disk_key);
7007 if (cur_offset + len > array_size)
7008 goto out_short_read;
7010 btrfs_disk_key_to_cpu(&key, disk_key);
7012 array_ptr += len;
7013 sb_array_offset += len;
7014 cur_offset += len;
7016 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
7017 chunk = (struct btrfs_chunk *)sb_array_offset;
7019 * At least one btrfs_chunk with one stripe must be
7020 * present, exact stripe count check comes afterwards
7022 len = btrfs_chunk_item_size(1);
7023 if (cur_offset + len > array_size)
7024 goto out_short_read;
7026 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7027 if (!num_stripes) {
7028 btrfs_err(fs_info,
7029 "invalid number of stripes %u in sys_array at offset %u",
7030 num_stripes, cur_offset);
7031 ret = -EIO;
7032 break;
7035 type = btrfs_chunk_type(sb, chunk);
7036 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7037 btrfs_err(fs_info,
7038 "invalid chunk type %llu in sys_array at offset %u",
7039 type, cur_offset);
7040 ret = -EIO;
7041 break;
7044 len = btrfs_chunk_item_size(num_stripes);
7045 if (cur_offset + len > array_size)
7046 goto out_short_read;
7048 ret = read_one_chunk(&key, sb, chunk);
7049 if (ret)
7050 break;
7051 } else {
7052 btrfs_err(fs_info,
7053 "unexpected item type %u in sys_array at offset %u",
7054 (u32)key.type, cur_offset);
7055 ret = -EIO;
7056 break;
7058 array_ptr += len;
7059 sb_array_offset += len;
7060 cur_offset += len;
7062 clear_extent_buffer_uptodate(sb);
7063 free_extent_buffer_stale(sb);
7064 return ret;
7066 out_short_read:
7067 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7068 len, cur_offset);
7069 clear_extent_buffer_uptodate(sb);
7070 free_extent_buffer_stale(sb);
7071 return -EIO;
7075 * Check if all chunks in the fs are OK for read-write degraded mount
7077 * If the @failing_dev is specified, it's accounted as missing.
7079 * Return true if all chunks meet the minimal RW mount requirements.
7080 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7082 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7083 struct btrfs_device *failing_dev)
7085 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
7086 struct extent_map *em;
7087 u64 next_start = 0;
7088 bool ret = true;
7090 read_lock(&map_tree->lock);
7091 em = lookup_extent_mapping(map_tree, 0, (u64)-1);
7092 read_unlock(&map_tree->lock);
7093 /* No chunk at all? Return false anyway */
7094 if (!em) {
7095 ret = false;
7096 goto out;
7098 while (em) {
7099 struct map_lookup *map;
7100 int missing = 0;
7101 int max_tolerated;
7102 int i;
7104 map = em->map_lookup;
7105 max_tolerated =
7106 btrfs_get_num_tolerated_disk_barrier_failures(
7107 map->type);
7108 for (i = 0; i < map->num_stripes; i++) {
7109 struct btrfs_device *dev = map->stripes[i].dev;
7111 if (!dev || !dev->bdev ||
7112 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7113 dev->last_flush_error)
7114 missing++;
7115 else if (failing_dev && failing_dev == dev)
7116 missing++;
7118 if (missing > max_tolerated) {
7119 if (!failing_dev)
7120 btrfs_warn(fs_info,
7121 "chunk %llu missing %d devices, max tolerance is %d for writable mount",
7122 em->start, missing, max_tolerated);
7123 free_extent_map(em);
7124 ret = false;
7125 goto out;
7127 next_start = extent_map_end(em);
7128 free_extent_map(em);
7130 read_lock(&map_tree->lock);
7131 em = lookup_extent_mapping(map_tree, next_start,
7132 (u64)(-1) - next_start);
7133 read_unlock(&map_tree->lock);
7135 out:
7136 return ret;
7139 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7141 struct btrfs_root *root = fs_info->chunk_root;
7142 struct btrfs_path *path;
7143 struct extent_buffer *leaf;
7144 struct btrfs_key key;
7145 struct btrfs_key found_key;
7146 int ret;
7147 int slot;
7148 u64 total_dev = 0;
7150 path = btrfs_alloc_path();
7151 if (!path)
7152 return -ENOMEM;
7155 * uuid_mutex is needed only if we are mounting a sprout FS
7156 * otherwise we don't need it.
7158 mutex_lock(&uuid_mutex);
7159 mutex_lock(&fs_info->chunk_mutex);
7162 * Read all device items, and then all the chunk items. All
7163 * device items are found before any chunk item (their object id
7164 * is smaller than the lowest possible object id for a chunk
7165 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7167 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7168 key.offset = 0;
7169 key.type = 0;
7170 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7171 if (ret < 0)
7172 goto error;
7173 while (1) {
7174 leaf = path->nodes[0];
7175 slot = path->slots[0];
7176 if (slot >= btrfs_header_nritems(leaf)) {
7177 ret = btrfs_next_leaf(root, path);
7178 if (ret == 0)
7179 continue;
7180 if (ret < 0)
7181 goto error;
7182 break;
7184 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7185 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7186 struct btrfs_dev_item *dev_item;
7187 dev_item = btrfs_item_ptr(leaf, slot,
7188 struct btrfs_dev_item);
7189 ret = read_one_dev(leaf, dev_item);
7190 if (ret)
7191 goto error;
7192 total_dev++;
7193 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7194 struct btrfs_chunk *chunk;
7195 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7196 ret = read_one_chunk(&found_key, leaf, chunk);
7197 if (ret)
7198 goto error;
7200 path->slots[0]++;
7204 * After loading chunk tree, we've got all device information,
7205 * do another round of validation checks.
7207 if (total_dev != fs_info->fs_devices->total_devices) {
7208 btrfs_err(fs_info,
7209 "super_num_devices %llu mismatch with num_devices %llu found here",
7210 btrfs_super_num_devices(fs_info->super_copy),
7211 total_dev);
7212 ret = -EINVAL;
7213 goto error;
7215 if (btrfs_super_total_bytes(fs_info->super_copy) <
7216 fs_info->fs_devices->total_rw_bytes) {
7217 btrfs_err(fs_info,
7218 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7219 btrfs_super_total_bytes(fs_info->super_copy),
7220 fs_info->fs_devices->total_rw_bytes);
7221 ret = -EINVAL;
7222 goto error;
7224 ret = 0;
7225 error:
7226 mutex_unlock(&fs_info->chunk_mutex);
7227 mutex_unlock(&uuid_mutex);
7229 btrfs_free_path(path);
7230 return ret;
7233 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7235 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7236 struct btrfs_device *device;
7238 while (fs_devices) {
7239 mutex_lock(&fs_devices->device_list_mutex);
7240 list_for_each_entry(device, &fs_devices->devices, dev_list)
7241 device->fs_info = fs_info;
7242 mutex_unlock(&fs_devices->device_list_mutex);
7244 fs_devices = fs_devices->seed;
7248 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
7250 int i;
7252 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7253 btrfs_dev_stat_reset(dev, i);
7256 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7258 struct btrfs_key key;
7259 struct btrfs_key found_key;
7260 struct btrfs_root *dev_root = fs_info->dev_root;
7261 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7262 struct extent_buffer *eb;
7263 int slot;
7264 int ret = 0;
7265 struct btrfs_device *device;
7266 struct btrfs_path *path = NULL;
7267 int i;
7269 path = btrfs_alloc_path();
7270 if (!path) {
7271 ret = -ENOMEM;
7272 goto out;
7275 mutex_lock(&fs_devices->device_list_mutex);
7276 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7277 int item_size;
7278 struct btrfs_dev_stats_item *ptr;
7280 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7281 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7282 key.offset = device->devid;
7283 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7284 if (ret) {
7285 __btrfs_reset_dev_stats(device);
7286 device->dev_stats_valid = 1;
7287 btrfs_release_path(path);
7288 continue;
7290 slot = path->slots[0];
7291 eb = path->nodes[0];
7292 btrfs_item_key_to_cpu(eb, &found_key, slot);
7293 item_size = btrfs_item_size_nr(eb, slot);
7295 ptr = btrfs_item_ptr(eb, slot,
7296 struct btrfs_dev_stats_item);
7298 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7299 if (item_size >= (1 + i) * sizeof(__le64))
7300 btrfs_dev_stat_set(device, i,
7301 btrfs_dev_stats_value(eb, ptr, i));
7302 else
7303 btrfs_dev_stat_reset(device, i);
7306 device->dev_stats_valid = 1;
7307 btrfs_dev_stat_print_on_load(device);
7308 btrfs_release_path(path);
7310 mutex_unlock(&fs_devices->device_list_mutex);
7312 out:
7313 btrfs_free_path(path);
7314 return ret < 0 ? ret : 0;
7317 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7318 struct btrfs_device *device)
7320 struct btrfs_fs_info *fs_info = trans->fs_info;
7321 struct btrfs_root *dev_root = fs_info->dev_root;
7322 struct btrfs_path *path;
7323 struct btrfs_key key;
7324 struct extent_buffer *eb;
7325 struct btrfs_dev_stats_item *ptr;
7326 int ret;
7327 int i;
7329 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7330 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7331 key.offset = device->devid;
7333 path = btrfs_alloc_path();
7334 if (!path)
7335 return -ENOMEM;
7336 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7337 if (ret < 0) {
7338 btrfs_warn_in_rcu(fs_info,
7339 "error %d while searching for dev_stats item for device %s",
7340 ret, rcu_str_deref(device->name));
7341 goto out;
7344 if (ret == 0 &&
7345 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7346 /* need to delete old one and insert a new one */
7347 ret = btrfs_del_item(trans, dev_root, path);
7348 if (ret != 0) {
7349 btrfs_warn_in_rcu(fs_info,
7350 "delete too small dev_stats item for device %s failed %d",
7351 rcu_str_deref(device->name), ret);
7352 goto out;
7354 ret = 1;
7357 if (ret == 1) {
7358 /* need to insert a new item */
7359 btrfs_release_path(path);
7360 ret = btrfs_insert_empty_item(trans, dev_root, path,
7361 &key, sizeof(*ptr));
7362 if (ret < 0) {
7363 btrfs_warn_in_rcu(fs_info,
7364 "insert dev_stats item for device %s failed %d",
7365 rcu_str_deref(device->name), ret);
7366 goto out;
7370 eb = path->nodes[0];
7371 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7372 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7373 btrfs_set_dev_stats_value(eb, ptr, i,
7374 btrfs_dev_stat_read(device, i));
7375 btrfs_mark_buffer_dirty(eb);
7377 out:
7378 btrfs_free_path(path);
7379 return ret;
7383 * called from commit_transaction. Writes all changed device stats to disk.
7385 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7387 struct btrfs_fs_info *fs_info = trans->fs_info;
7388 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7389 struct btrfs_device *device;
7390 int stats_cnt;
7391 int ret = 0;
7393 mutex_lock(&fs_devices->device_list_mutex);
7394 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7395 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7396 if (!device->dev_stats_valid || stats_cnt == 0)
7397 continue;
7401 * There is a LOAD-LOAD control dependency between the value of
7402 * dev_stats_ccnt and updating the on-disk values which requires
7403 * reading the in-memory counters. Such control dependencies
7404 * require explicit read memory barriers.
7406 * This memory barriers pairs with smp_mb__before_atomic in
7407 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7408 * barrier implied by atomic_xchg in
7409 * btrfs_dev_stats_read_and_reset
7411 smp_rmb();
7413 ret = update_dev_stat_item(trans, device);
7414 if (!ret)
7415 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7417 mutex_unlock(&fs_devices->device_list_mutex);
7419 return ret;
7422 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7424 btrfs_dev_stat_inc(dev, index);
7425 btrfs_dev_stat_print_on_error(dev);
7428 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7430 if (!dev->dev_stats_valid)
7431 return;
7432 btrfs_err_rl_in_rcu(dev->fs_info,
7433 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7434 rcu_str_deref(dev->name),
7435 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7436 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7437 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7438 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7439 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7442 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7444 int i;
7446 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7447 if (btrfs_dev_stat_read(dev, i) != 0)
7448 break;
7449 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7450 return; /* all values == 0, suppress message */
7452 btrfs_info_in_rcu(dev->fs_info,
7453 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7454 rcu_str_deref(dev->name),
7455 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7456 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7457 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7458 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7459 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7462 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7463 struct btrfs_ioctl_get_dev_stats *stats)
7465 struct btrfs_device *dev;
7466 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7467 int i;
7469 mutex_lock(&fs_devices->device_list_mutex);
7470 dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL,
7471 true);
7472 mutex_unlock(&fs_devices->device_list_mutex);
7474 if (!dev) {
7475 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7476 return -ENODEV;
7477 } else if (!dev->dev_stats_valid) {
7478 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7479 return -ENODEV;
7480 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7481 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7482 if (stats->nr_items > i)
7483 stats->values[i] =
7484 btrfs_dev_stat_read_and_reset(dev, i);
7485 else
7486 btrfs_dev_stat_reset(dev, i);
7488 } else {
7489 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7490 if (stats->nr_items > i)
7491 stats->values[i] = btrfs_dev_stat_read(dev, i);
7493 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7494 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7495 return 0;
7498 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7500 struct buffer_head *bh;
7501 struct btrfs_super_block *disk_super;
7502 int copy_num;
7504 if (!bdev)
7505 return;
7507 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7508 copy_num++) {
7510 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7511 continue;
7513 disk_super = (struct btrfs_super_block *)bh->b_data;
7515 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7516 set_buffer_dirty(bh);
7517 sync_dirty_buffer(bh);
7518 brelse(bh);
7521 /* Notify udev that device has changed */
7522 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7524 /* Update ctime/mtime for device path for libblkid */
7525 update_dev_time(device_path);
7529 * Update the size and bytes used for each device where it changed. This is
7530 * delayed since we would otherwise get errors while writing out the
7531 * superblocks.
7533 * Must be invoked during transaction commit.
7535 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7537 struct btrfs_device *curr, *next;
7539 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7541 if (list_empty(&trans->dev_update_list))
7542 return;
7545 * We don't need the device_list_mutex here. This list is owned by the
7546 * transaction and the transaction must complete before the device is
7547 * released.
7549 mutex_lock(&trans->fs_info->chunk_mutex);
7550 list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7551 post_commit_list) {
7552 list_del_init(&curr->post_commit_list);
7553 curr->commit_total_bytes = curr->disk_total_bytes;
7554 curr->commit_bytes_used = curr->bytes_used;
7556 mutex_unlock(&trans->fs_info->chunk_mutex);
7559 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7561 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7562 while (fs_devices) {
7563 fs_devices->fs_info = fs_info;
7564 fs_devices = fs_devices->seed;
7568 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7570 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7571 while (fs_devices) {
7572 fs_devices->fs_info = NULL;
7573 fs_devices = fs_devices->seed;
7578 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7580 int btrfs_bg_type_to_factor(u64 flags)
7582 const int index = btrfs_bg_flags_to_raid_index(flags);
7584 return btrfs_raid_array[index].ncopies;
7589 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7590 u64 chunk_offset, u64 devid,
7591 u64 physical_offset, u64 physical_len)
7593 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7594 struct extent_map *em;
7595 struct map_lookup *map;
7596 struct btrfs_device *dev;
7597 u64 stripe_len;
7598 bool found = false;
7599 int ret = 0;
7600 int i;
7602 read_lock(&em_tree->lock);
7603 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7604 read_unlock(&em_tree->lock);
7606 if (!em) {
7607 btrfs_err(fs_info,
7608 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7609 physical_offset, devid);
7610 ret = -EUCLEAN;
7611 goto out;
7614 map = em->map_lookup;
7615 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7616 if (physical_len != stripe_len) {
7617 btrfs_err(fs_info,
7618 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7619 physical_offset, devid, em->start, physical_len,
7620 stripe_len);
7621 ret = -EUCLEAN;
7622 goto out;
7625 for (i = 0; i < map->num_stripes; i++) {
7626 if (map->stripes[i].dev->devid == devid &&
7627 map->stripes[i].physical == physical_offset) {
7628 found = true;
7629 if (map->verified_stripes >= map->num_stripes) {
7630 btrfs_err(fs_info,
7631 "too many dev extents for chunk %llu found",
7632 em->start);
7633 ret = -EUCLEAN;
7634 goto out;
7636 map->verified_stripes++;
7637 break;
7640 if (!found) {
7641 btrfs_err(fs_info,
7642 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7643 physical_offset, devid);
7644 ret = -EUCLEAN;
7647 /* Make sure no dev extent is beyond device bondary */
7648 dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
7649 if (!dev) {
7650 btrfs_err(fs_info, "failed to find devid %llu", devid);
7651 ret = -EUCLEAN;
7652 goto out;
7655 /* It's possible this device is a dummy for seed device */
7656 if (dev->disk_total_bytes == 0) {
7657 dev = btrfs_find_device(fs_info->fs_devices->seed, devid, NULL,
7658 NULL, false);
7659 if (!dev) {
7660 btrfs_err(fs_info, "failed to find seed devid %llu",
7661 devid);
7662 ret = -EUCLEAN;
7663 goto out;
7667 if (physical_offset + physical_len > dev->disk_total_bytes) {
7668 btrfs_err(fs_info,
7669 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7670 devid, physical_offset, physical_len,
7671 dev->disk_total_bytes);
7672 ret = -EUCLEAN;
7673 goto out;
7675 out:
7676 free_extent_map(em);
7677 return ret;
7680 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7682 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
7683 struct extent_map *em;
7684 struct rb_node *node;
7685 int ret = 0;
7687 read_lock(&em_tree->lock);
7688 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7689 em = rb_entry(node, struct extent_map, rb_node);
7690 if (em->map_lookup->num_stripes !=
7691 em->map_lookup->verified_stripes) {
7692 btrfs_err(fs_info,
7693 "chunk %llu has missing dev extent, have %d expect %d",
7694 em->start, em->map_lookup->verified_stripes,
7695 em->map_lookup->num_stripes);
7696 ret = -EUCLEAN;
7697 goto out;
7700 out:
7701 read_unlock(&em_tree->lock);
7702 return ret;
7706 * Ensure that all dev extents are mapped to correct chunk, otherwise
7707 * later chunk allocation/free would cause unexpected behavior.
7709 * NOTE: This will iterate through the whole device tree, which should be of
7710 * the same size level as the chunk tree. This slightly increases mount time.
7712 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7714 struct btrfs_path *path;
7715 struct btrfs_root *root = fs_info->dev_root;
7716 struct btrfs_key key;
7717 u64 prev_devid = 0;
7718 u64 prev_dev_ext_end = 0;
7719 int ret = 0;
7721 key.objectid = 1;
7722 key.type = BTRFS_DEV_EXTENT_KEY;
7723 key.offset = 0;
7725 path = btrfs_alloc_path();
7726 if (!path)
7727 return -ENOMEM;
7729 path->reada = READA_FORWARD;
7730 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7731 if (ret < 0)
7732 goto out;
7734 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7735 ret = btrfs_next_item(root, path);
7736 if (ret < 0)
7737 goto out;
7738 /* No dev extents at all? Not good */
7739 if (ret > 0) {
7740 ret = -EUCLEAN;
7741 goto out;
7744 while (1) {
7745 struct extent_buffer *leaf = path->nodes[0];
7746 struct btrfs_dev_extent *dext;
7747 int slot = path->slots[0];
7748 u64 chunk_offset;
7749 u64 physical_offset;
7750 u64 physical_len;
7751 u64 devid;
7753 btrfs_item_key_to_cpu(leaf, &key, slot);
7754 if (key.type != BTRFS_DEV_EXTENT_KEY)
7755 break;
7756 devid = key.objectid;
7757 physical_offset = key.offset;
7759 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7760 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7761 physical_len = btrfs_dev_extent_length(leaf, dext);
7763 /* Check if this dev extent overlaps with the previous one */
7764 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7765 btrfs_err(fs_info,
7766 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7767 devid, physical_offset, prev_dev_ext_end);
7768 ret = -EUCLEAN;
7769 goto out;
7772 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7773 physical_offset, physical_len);
7774 if (ret < 0)
7775 goto out;
7776 prev_devid = devid;
7777 prev_dev_ext_end = physical_offset + physical_len;
7779 ret = btrfs_next_item(root, path);
7780 if (ret < 0)
7781 goto out;
7782 if (ret > 0) {
7783 ret = 0;
7784 break;
7788 /* Ensure all chunks have corresponding dev extents */
7789 ret = verify_chunk_dev_extent_mapping(fs_info);
7790 out:
7791 btrfs_free_path(path);
7792 return ret;
7796 * Check whether the given block group or device is pinned by any inode being
7797 * used as a swapfile.
7799 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7801 struct btrfs_swapfile_pin *sp;
7802 struct rb_node *node;
7804 spin_lock(&fs_info->swapfile_pins_lock);
7805 node = fs_info->swapfile_pins.rb_node;
7806 while (node) {
7807 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7808 if (ptr < sp->ptr)
7809 node = node->rb_left;
7810 else if (ptr > sp->ptr)
7811 node = node->rb_right;
7812 else
7813 break;
7815 spin_unlock(&fs_info->swapfile_pins_lock);
7816 return node != NULL;