Linux 4.18.10
[linux/fpc-iii.git] / fs / btrfs / volumes.c
blob5304b8d6ceb8fd43bd9bc5410766ac6d42e98b02
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/iocontext.h>
12 #include <linux/capability.h>
13 #include <linux/ratelimit.h>
14 #include <linux/kthread.h>
15 #include <linux/raid/pq.h>
16 #include <linux/semaphore.h>
17 #include <linux/uuid.h>
18 #include <linux/list_sort.h>
19 #include <asm/div64.h>
20 #include "ctree.h"
21 #include "extent_map.h"
22 #include "disk-io.h"
23 #include "transaction.h"
24 #include "print-tree.h"
25 #include "volumes.h"
26 #include "raid56.h"
27 #include "async-thread.h"
28 #include "check-integrity.h"
29 #include "rcu-string.h"
30 #include "math.h"
31 #include "dev-replace.h"
32 #include "sysfs.h"
34 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
35 [BTRFS_RAID_RAID10] = {
36 .sub_stripes = 2,
37 .dev_stripes = 1,
38 .devs_max = 0, /* 0 == as many as possible */
39 .devs_min = 4,
40 .tolerated_failures = 1,
41 .devs_increment = 2,
42 .ncopies = 2,
43 .raid_name = "raid10",
44 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
45 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
47 [BTRFS_RAID_RAID1] = {
48 .sub_stripes = 1,
49 .dev_stripes = 1,
50 .devs_max = 2,
51 .devs_min = 2,
52 .tolerated_failures = 1,
53 .devs_increment = 2,
54 .ncopies = 2,
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 .raid_name = "dup",
68 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
69 .mindev_error = 0,
71 [BTRFS_RAID_RAID0] = {
72 .sub_stripes = 1,
73 .dev_stripes = 1,
74 .devs_max = 0,
75 .devs_min = 2,
76 .tolerated_failures = 0,
77 .devs_increment = 1,
78 .ncopies = 1,
79 .raid_name = "raid0",
80 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
81 .mindev_error = 0,
83 [BTRFS_RAID_SINGLE] = {
84 .sub_stripes = 1,
85 .dev_stripes = 1,
86 .devs_max = 1,
87 .devs_min = 1,
88 .tolerated_failures = 0,
89 .devs_increment = 1,
90 .ncopies = 1,
91 .raid_name = "single",
92 .bg_flag = 0,
93 .mindev_error = 0,
95 [BTRFS_RAID_RAID5] = {
96 .sub_stripes = 1,
97 .dev_stripes = 1,
98 .devs_max = 0,
99 .devs_min = 2,
100 .tolerated_failures = 1,
101 .devs_increment = 1,
102 .ncopies = 2,
103 .raid_name = "raid5",
104 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
105 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
107 [BTRFS_RAID_RAID6] = {
108 .sub_stripes = 1,
109 .dev_stripes = 1,
110 .devs_max = 0,
111 .devs_min = 3,
112 .tolerated_failures = 2,
113 .devs_increment = 1,
114 .ncopies = 3,
115 .raid_name = "raid6",
116 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
117 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
121 const char *get_raid_name(enum btrfs_raid_types type)
123 if (type >= BTRFS_NR_RAID_TYPES)
124 return NULL;
126 return btrfs_raid_array[type].raid_name;
129 static int init_first_rw_device(struct btrfs_trans_handle *trans,
130 struct btrfs_fs_info *fs_info);
131 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
132 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
133 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
134 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
135 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
136 enum btrfs_map_op op,
137 u64 logical, u64 *length,
138 struct btrfs_bio **bbio_ret,
139 int mirror_num, int need_raid_map);
142 * Device locking
143 * ==============
145 * There are several mutexes that protect manipulation of devices and low-level
146 * structures like chunks but not block groups, extents or files
148 * uuid_mutex (global lock)
149 * ------------------------
150 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
151 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
152 * device) or requested by the device= mount option
154 * the mutex can be very coarse and can cover long-running operations
156 * protects: updates to fs_devices counters like missing devices, rw devices,
157 * seeding, structure cloning, openning/closing devices at mount/umount time
159 * global::fs_devs - add, remove, updates to the global list
161 * does not protect: manipulation of the fs_devices::devices list!
163 * btrfs_device::name - renames (write side), read is RCU
165 * fs_devices::device_list_mutex (per-fs, with RCU)
166 * ------------------------------------------------
167 * protects updates to fs_devices::devices, ie. adding and deleting
169 * simple list traversal with read-only actions can be done with RCU protection
171 * may be used to exclude some operations from running concurrently without any
172 * modifications to the list (see write_all_supers)
174 * balance_mutex
175 * -------------
176 * protects balance structures (status, state) and context accessed from
177 * several places (internally, ioctl)
179 * chunk_mutex
180 * -----------
181 * protects chunks, adding or removing during allocation, trim or when a new
182 * device is added/removed
184 * cleaner_mutex
185 * -------------
186 * a big lock that is held by the cleaner thread and prevents running subvolume
187 * cleaning together with relocation or delayed iputs
190 * Lock nesting
191 * ============
193 * uuid_mutex
194 * volume_mutex
195 * device_list_mutex
196 * chunk_mutex
197 * balance_mutex
200 * Exclusive operations, BTRFS_FS_EXCL_OP
201 * ======================================
203 * Maintains the exclusivity of the following operations that apply to the
204 * whole filesystem and cannot run in parallel.
206 * - Balance (*)
207 * - Device add
208 * - Device remove
209 * - Device replace (*)
210 * - Resize
212 * The device operations (as above) can be in one of the following states:
214 * - Running state
215 * - Paused state
216 * - Completed state
218 * Only device operations marked with (*) can go into the Paused state for the
219 * following reasons:
221 * - ioctl (only Balance can be Paused through ioctl)
222 * - filesystem remounted as read-only
223 * - filesystem unmounted and mounted as read-only
224 * - system power-cycle and filesystem mounted as read-only
225 * - filesystem or device errors leading to forced read-only
227 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
228 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
229 * A device operation in Paused or Running state can be canceled or resumed
230 * either by ioctl (Balance only) or when remounted as read-write.
231 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
232 * completed.
235 DEFINE_MUTEX(uuid_mutex);
236 static LIST_HEAD(fs_uuids);
237 struct list_head *btrfs_get_fs_uuids(void)
239 return &fs_uuids;
243 * alloc_fs_devices - allocate struct btrfs_fs_devices
244 * @fsid: if not NULL, copy the uuid to fs_devices::fsid
246 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
247 * The returned struct is not linked onto any lists and can be destroyed with
248 * kfree() right away.
250 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
252 struct btrfs_fs_devices *fs_devs;
254 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
255 if (!fs_devs)
256 return ERR_PTR(-ENOMEM);
258 mutex_init(&fs_devs->device_list_mutex);
260 INIT_LIST_HEAD(&fs_devs->devices);
261 INIT_LIST_HEAD(&fs_devs->resized_devices);
262 INIT_LIST_HEAD(&fs_devs->alloc_list);
263 INIT_LIST_HEAD(&fs_devs->fs_list);
264 if (fsid)
265 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
267 return fs_devs;
270 void btrfs_free_device(struct btrfs_device *device)
272 rcu_string_free(device->name);
273 bio_put(device->flush_bio);
274 kfree(device);
277 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
279 struct btrfs_device *device;
280 WARN_ON(fs_devices->opened);
281 while (!list_empty(&fs_devices->devices)) {
282 device = list_entry(fs_devices->devices.next,
283 struct btrfs_device, dev_list);
284 list_del(&device->dev_list);
285 btrfs_free_device(device);
287 kfree(fs_devices);
290 static void btrfs_kobject_uevent(struct block_device *bdev,
291 enum kobject_action action)
293 int ret;
295 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
296 if (ret)
297 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
298 action,
299 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
300 &disk_to_dev(bdev->bd_disk)->kobj);
303 void __exit btrfs_cleanup_fs_uuids(void)
305 struct btrfs_fs_devices *fs_devices;
307 while (!list_empty(&fs_uuids)) {
308 fs_devices = list_entry(fs_uuids.next,
309 struct btrfs_fs_devices, fs_list);
310 list_del(&fs_devices->fs_list);
311 free_fs_devices(fs_devices);
316 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
317 * Returned struct is not linked onto any lists and must be destroyed using
318 * btrfs_free_device.
320 static struct btrfs_device *__alloc_device(void)
322 struct btrfs_device *dev;
324 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
325 if (!dev)
326 return ERR_PTR(-ENOMEM);
329 * Preallocate a bio that's always going to be used for flushing device
330 * barriers and matches the device lifespan
332 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
333 if (!dev->flush_bio) {
334 kfree(dev);
335 return ERR_PTR(-ENOMEM);
338 INIT_LIST_HEAD(&dev->dev_list);
339 INIT_LIST_HEAD(&dev->dev_alloc_list);
340 INIT_LIST_HEAD(&dev->resized_list);
342 spin_lock_init(&dev->io_lock);
344 atomic_set(&dev->reada_in_flight, 0);
345 atomic_set(&dev->dev_stats_ccnt, 0);
346 btrfs_device_data_ordered_init(dev);
347 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
348 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
350 return dev;
354 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
355 * return NULL.
357 * If devid and uuid are both specified, the match must be exact, otherwise
358 * only devid is used.
360 static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,
361 u64 devid, const u8 *uuid)
363 struct btrfs_device *dev;
365 list_for_each_entry(dev, &fs_devices->devices, dev_list) {
366 if (dev->devid == devid &&
367 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
368 return dev;
371 return NULL;
374 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
376 struct btrfs_fs_devices *fs_devices;
378 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
379 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
380 return fs_devices;
382 return NULL;
385 static int
386 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
387 int flush, struct block_device **bdev,
388 struct buffer_head **bh)
390 int ret;
392 *bdev = blkdev_get_by_path(device_path, flags, holder);
394 if (IS_ERR(*bdev)) {
395 ret = PTR_ERR(*bdev);
396 goto error;
399 if (flush)
400 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
401 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
402 if (ret) {
403 blkdev_put(*bdev, flags);
404 goto error;
406 invalidate_bdev(*bdev);
407 *bh = btrfs_read_dev_super(*bdev);
408 if (IS_ERR(*bh)) {
409 ret = PTR_ERR(*bh);
410 blkdev_put(*bdev, flags);
411 goto error;
414 return 0;
416 error:
417 *bdev = NULL;
418 *bh = NULL;
419 return ret;
422 static void requeue_list(struct btrfs_pending_bios *pending_bios,
423 struct bio *head, struct bio *tail)
426 struct bio *old_head;
428 old_head = pending_bios->head;
429 pending_bios->head = head;
430 if (pending_bios->tail)
431 tail->bi_next = old_head;
432 else
433 pending_bios->tail = tail;
437 * we try to collect pending bios for a device so we don't get a large
438 * number of procs sending bios down to the same device. This greatly
439 * improves the schedulers ability to collect and merge the bios.
441 * But, it also turns into a long list of bios to process and that is sure
442 * to eventually make the worker thread block. The solution here is to
443 * make some progress and then put this work struct back at the end of
444 * the list if the block device is congested. This way, multiple devices
445 * can make progress from a single worker thread.
447 static noinline void run_scheduled_bios(struct btrfs_device *device)
449 struct btrfs_fs_info *fs_info = device->fs_info;
450 struct bio *pending;
451 struct backing_dev_info *bdi;
452 struct btrfs_pending_bios *pending_bios;
453 struct bio *tail;
454 struct bio *cur;
455 int again = 0;
456 unsigned long num_run;
457 unsigned long batch_run = 0;
458 unsigned long last_waited = 0;
459 int force_reg = 0;
460 int sync_pending = 0;
461 struct blk_plug plug;
464 * this function runs all the bios we've collected for
465 * a particular device. We don't want to wander off to
466 * another device without first sending all of these down.
467 * So, setup a plug here and finish it off before we return
469 blk_start_plug(&plug);
471 bdi = device->bdev->bd_bdi;
473 loop:
474 spin_lock(&device->io_lock);
476 loop_lock:
477 num_run = 0;
479 /* take all the bios off the list at once and process them
480 * later on (without the lock held). But, remember the
481 * tail and other pointers so the bios can be properly reinserted
482 * into the list if we hit congestion
484 if (!force_reg && device->pending_sync_bios.head) {
485 pending_bios = &device->pending_sync_bios;
486 force_reg = 1;
487 } else {
488 pending_bios = &device->pending_bios;
489 force_reg = 0;
492 pending = pending_bios->head;
493 tail = pending_bios->tail;
494 WARN_ON(pending && !tail);
497 * if pending was null this time around, no bios need processing
498 * at all and we can stop. Otherwise it'll loop back up again
499 * and do an additional check so no bios are missed.
501 * device->running_pending is used to synchronize with the
502 * schedule_bio code.
504 if (device->pending_sync_bios.head == NULL &&
505 device->pending_bios.head == NULL) {
506 again = 0;
507 device->running_pending = 0;
508 } else {
509 again = 1;
510 device->running_pending = 1;
513 pending_bios->head = NULL;
514 pending_bios->tail = NULL;
516 spin_unlock(&device->io_lock);
518 while (pending) {
520 rmb();
521 /* we want to work on both lists, but do more bios on the
522 * sync list than the regular list
524 if ((num_run > 32 &&
525 pending_bios != &device->pending_sync_bios &&
526 device->pending_sync_bios.head) ||
527 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
528 device->pending_bios.head)) {
529 spin_lock(&device->io_lock);
530 requeue_list(pending_bios, pending, tail);
531 goto loop_lock;
534 cur = pending;
535 pending = pending->bi_next;
536 cur->bi_next = NULL;
538 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
541 * if we're doing the sync list, record that our
542 * plug has some sync requests on it
544 * If we're doing the regular list and there are
545 * sync requests sitting around, unplug before
546 * we add more
548 if (pending_bios == &device->pending_sync_bios) {
549 sync_pending = 1;
550 } else if (sync_pending) {
551 blk_finish_plug(&plug);
552 blk_start_plug(&plug);
553 sync_pending = 0;
556 btrfsic_submit_bio(cur);
557 num_run++;
558 batch_run++;
560 cond_resched();
563 * we made progress, there is more work to do and the bdi
564 * is now congested. Back off and let other work structs
565 * run instead
567 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
568 fs_info->fs_devices->open_devices > 1) {
569 struct io_context *ioc;
571 ioc = current->io_context;
574 * the main goal here is that we don't want to
575 * block if we're going to be able to submit
576 * more requests without blocking.
578 * This code does two great things, it pokes into
579 * the elevator code from a filesystem _and_
580 * it makes assumptions about how batching works.
582 if (ioc && ioc->nr_batch_requests > 0 &&
583 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
584 (last_waited == 0 ||
585 ioc->last_waited == last_waited)) {
587 * we want to go through our batch of
588 * requests and stop. So, we copy out
589 * the ioc->last_waited time and test
590 * against it before looping
592 last_waited = ioc->last_waited;
593 cond_resched();
594 continue;
596 spin_lock(&device->io_lock);
597 requeue_list(pending_bios, pending, tail);
598 device->running_pending = 1;
600 spin_unlock(&device->io_lock);
601 btrfs_queue_work(fs_info->submit_workers,
602 &device->work);
603 goto done;
607 cond_resched();
608 if (again)
609 goto loop;
611 spin_lock(&device->io_lock);
612 if (device->pending_bios.head || device->pending_sync_bios.head)
613 goto loop_lock;
614 spin_unlock(&device->io_lock);
616 done:
617 blk_finish_plug(&plug);
620 static void pending_bios_fn(struct btrfs_work *work)
622 struct btrfs_device *device;
624 device = container_of(work, struct btrfs_device, work);
625 run_scheduled_bios(device);
629 * Search and remove all stale (devices which are not mounted) devices.
630 * When both inputs are NULL, it will search and release all stale devices.
631 * path: Optional. When provided will it release all unmounted devices
632 * matching this path only.
633 * skip_dev: Optional. Will skip this device when searching for the stale
634 * devices.
636 static void btrfs_free_stale_devices(const char *path,
637 struct btrfs_device *skip_device)
639 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
640 struct btrfs_device *device, *tmp_device;
642 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
643 mutex_lock(&fs_devices->device_list_mutex);
644 if (fs_devices->opened) {
645 mutex_unlock(&fs_devices->device_list_mutex);
646 continue;
649 list_for_each_entry_safe(device, tmp_device,
650 &fs_devices->devices, dev_list) {
651 int not_found = 0;
653 if (skip_device && skip_device == device)
654 continue;
655 if (path && !device->name)
656 continue;
658 rcu_read_lock();
659 if (path)
660 not_found = strcmp(rcu_str_deref(device->name),
661 path);
662 rcu_read_unlock();
663 if (not_found)
664 continue;
666 /* delete the stale device */
667 fs_devices->num_devices--;
668 list_del(&device->dev_list);
669 btrfs_free_device(device);
671 if (fs_devices->num_devices == 0)
672 break;
674 mutex_unlock(&fs_devices->device_list_mutex);
675 if (fs_devices->num_devices == 0) {
676 btrfs_sysfs_remove_fsid(fs_devices);
677 list_del(&fs_devices->fs_list);
678 free_fs_devices(fs_devices);
683 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
684 struct btrfs_device *device, fmode_t flags,
685 void *holder)
687 struct request_queue *q;
688 struct block_device *bdev;
689 struct buffer_head *bh;
690 struct btrfs_super_block *disk_super;
691 u64 devid;
692 int ret;
694 if (device->bdev)
695 return -EINVAL;
696 if (!device->name)
697 return -EINVAL;
699 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
700 &bdev, &bh);
701 if (ret)
702 return ret;
704 disk_super = (struct btrfs_super_block *)bh->b_data;
705 devid = btrfs_stack_device_id(&disk_super->dev_item);
706 if (devid != device->devid)
707 goto error_brelse;
709 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
710 goto error_brelse;
712 device->generation = btrfs_super_generation(disk_super);
714 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
715 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
716 fs_devices->seeding = 1;
717 } else {
718 if (bdev_read_only(bdev))
719 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
720 else
721 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
724 q = bdev_get_queue(bdev);
725 if (!blk_queue_nonrot(q))
726 fs_devices->rotating = 1;
728 device->bdev = bdev;
729 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
730 device->mode = flags;
732 fs_devices->open_devices++;
733 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
734 device->devid != BTRFS_DEV_REPLACE_DEVID) {
735 fs_devices->rw_devices++;
736 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
738 brelse(bh);
740 return 0;
742 error_brelse:
743 brelse(bh);
744 blkdev_put(bdev, flags);
746 return -EINVAL;
750 * Add new device to list of registered devices
752 * Returns:
753 * device pointer which was just added or updated when successful
754 * error pointer when failed
756 static noinline struct btrfs_device *device_list_add(const char *path,
757 struct btrfs_super_block *disk_super,
758 bool *new_device_added)
760 struct btrfs_device *device;
761 struct btrfs_fs_devices *fs_devices;
762 struct rcu_string *name;
763 u64 found_transid = btrfs_super_generation(disk_super);
764 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
766 fs_devices = find_fsid(disk_super->fsid);
767 if (!fs_devices) {
768 fs_devices = alloc_fs_devices(disk_super->fsid);
769 if (IS_ERR(fs_devices))
770 return ERR_CAST(fs_devices);
772 mutex_lock(&fs_devices->device_list_mutex);
773 list_add(&fs_devices->fs_list, &fs_uuids);
775 device = NULL;
776 } else {
777 mutex_lock(&fs_devices->device_list_mutex);
778 device = find_device(fs_devices, devid,
779 disk_super->dev_item.uuid);
782 if (!device) {
783 if (fs_devices->opened) {
784 mutex_unlock(&fs_devices->device_list_mutex);
785 return ERR_PTR(-EBUSY);
788 device = btrfs_alloc_device(NULL, &devid,
789 disk_super->dev_item.uuid);
790 if (IS_ERR(device)) {
791 mutex_unlock(&fs_devices->device_list_mutex);
792 /* we can safely leave the fs_devices entry around */
793 return device;
796 name = rcu_string_strdup(path, GFP_NOFS);
797 if (!name) {
798 btrfs_free_device(device);
799 mutex_unlock(&fs_devices->device_list_mutex);
800 return ERR_PTR(-ENOMEM);
802 rcu_assign_pointer(device->name, name);
804 list_add_rcu(&device->dev_list, &fs_devices->devices);
805 fs_devices->num_devices++;
807 device->fs_devices = fs_devices;
808 *new_device_added = true;
810 if (disk_super->label[0])
811 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
812 disk_super->label, devid, found_transid, path);
813 else
814 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
815 disk_super->fsid, devid, found_transid, path);
817 } else if (!device->name || strcmp(device->name->str, path)) {
819 * When FS is already mounted.
820 * 1. If you are here and if the device->name is NULL that
821 * means this device was missing at time of FS mount.
822 * 2. If you are here and if the device->name is different
823 * from 'path' that means either
824 * a. The same device disappeared and reappeared with
825 * different name. or
826 * b. The missing-disk-which-was-replaced, has
827 * reappeared now.
829 * We must allow 1 and 2a above. But 2b would be a spurious
830 * and unintentional.
832 * Further in case of 1 and 2a above, the disk at 'path'
833 * would have missed some transaction when it was away and
834 * in case of 2a the stale bdev has to be updated as well.
835 * 2b must not be allowed at all time.
839 * For now, we do allow update to btrfs_fs_device through the
840 * btrfs dev scan cli after FS has been mounted. We're still
841 * tracking a problem where systems fail mount by subvolume id
842 * when we reject replacement on a mounted FS.
844 if (!fs_devices->opened && found_transid < device->generation) {
846 * That is if the FS is _not_ mounted and if you
847 * are here, that means there is more than one
848 * disk with same uuid and devid.We keep the one
849 * with larger generation number or the last-in if
850 * generation are equal.
852 mutex_unlock(&fs_devices->device_list_mutex);
853 return ERR_PTR(-EEXIST);
856 name = rcu_string_strdup(path, GFP_NOFS);
857 if (!name) {
858 mutex_unlock(&fs_devices->device_list_mutex);
859 return ERR_PTR(-ENOMEM);
861 rcu_string_free(device->name);
862 rcu_assign_pointer(device->name, name);
863 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
864 fs_devices->missing_devices--;
865 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
870 * Unmount does not free the btrfs_device struct but would zero
871 * generation along with most of the other members. So just update
872 * it back. We need it to pick the disk with largest generation
873 * (as above).
875 if (!fs_devices->opened)
876 device->generation = found_transid;
878 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
880 mutex_unlock(&fs_devices->device_list_mutex);
881 return device;
884 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
886 struct btrfs_fs_devices *fs_devices;
887 struct btrfs_device *device;
888 struct btrfs_device *orig_dev;
890 fs_devices = alloc_fs_devices(orig->fsid);
891 if (IS_ERR(fs_devices))
892 return fs_devices;
894 mutex_lock(&orig->device_list_mutex);
895 fs_devices->total_devices = orig->total_devices;
897 /* We have held the volume lock, it is safe to get the devices. */
898 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
899 struct rcu_string *name;
901 device = btrfs_alloc_device(NULL, &orig_dev->devid,
902 orig_dev->uuid);
903 if (IS_ERR(device))
904 goto error;
907 * This is ok to do without rcu read locked because we hold the
908 * uuid mutex so nothing we touch in here is going to disappear.
910 if (orig_dev->name) {
911 name = rcu_string_strdup(orig_dev->name->str,
912 GFP_KERNEL);
913 if (!name) {
914 btrfs_free_device(device);
915 goto error;
917 rcu_assign_pointer(device->name, name);
920 list_add(&device->dev_list, &fs_devices->devices);
921 device->fs_devices = fs_devices;
922 fs_devices->num_devices++;
924 mutex_unlock(&orig->device_list_mutex);
925 return fs_devices;
926 error:
927 mutex_unlock(&orig->device_list_mutex);
928 free_fs_devices(fs_devices);
929 return ERR_PTR(-ENOMEM);
933 * After we have read the system tree and know devids belonging to
934 * this filesystem, remove the device which does not belong there.
936 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
938 struct btrfs_device *device, *next;
939 struct btrfs_device *latest_dev = NULL;
941 mutex_lock(&uuid_mutex);
942 again:
943 /* This is the initialized path, it is safe to release the devices. */
944 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
945 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
946 &device->dev_state)) {
947 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
948 &device->dev_state) &&
949 (!latest_dev ||
950 device->generation > latest_dev->generation)) {
951 latest_dev = device;
953 continue;
956 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
958 * In the first step, keep the device which has
959 * the correct fsid and the devid that is used
960 * for the dev_replace procedure.
961 * In the second step, the dev_replace state is
962 * read from the device tree and it is known
963 * whether the procedure is really active or
964 * not, which means whether this device is
965 * used or whether it should be removed.
967 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
968 &device->dev_state)) {
969 continue;
972 if (device->bdev) {
973 blkdev_put(device->bdev, device->mode);
974 device->bdev = NULL;
975 fs_devices->open_devices--;
977 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
978 list_del_init(&device->dev_alloc_list);
979 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
980 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
981 &device->dev_state))
982 fs_devices->rw_devices--;
984 list_del_init(&device->dev_list);
985 fs_devices->num_devices--;
986 btrfs_free_device(device);
989 if (fs_devices->seed) {
990 fs_devices = fs_devices->seed;
991 goto again;
994 fs_devices->latest_bdev = latest_dev->bdev;
996 mutex_unlock(&uuid_mutex);
999 static void free_device_rcu(struct rcu_head *head)
1001 struct btrfs_device *device;
1003 device = container_of(head, struct btrfs_device, rcu);
1004 btrfs_free_device(device);
1007 static void btrfs_close_bdev(struct btrfs_device *device)
1009 if (!device->bdev)
1010 return;
1012 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1013 sync_blockdev(device->bdev);
1014 invalidate_bdev(device->bdev);
1017 blkdev_put(device->bdev, device->mode);
1020 static void btrfs_prepare_close_one_device(struct btrfs_device *device)
1022 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1023 struct btrfs_device *new_device;
1024 struct rcu_string *name;
1026 if (device->bdev)
1027 fs_devices->open_devices--;
1029 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1030 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1031 list_del_init(&device->dev_alloc_list);
1032 fs_devices->rw_devices--;
1035 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1036 fs_devices->missing_devices--;
1038 new_device = btrfs_alloc_device(NULL, &device->devid,
1039 device->uuid);
1040 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1042 /* Safe because we are under uuid_mutex */
1043 if (device->name) {
1044 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1045 BUG_ON(!name); /* -ENOMEM */
1046 rcu_assign_pointer(new_device->name, name);
1049 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1050 new_device->fs_devices = device->fs_devices;
1053 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1055 struct btrfs_device *device, *tmp;
1056 struct list_head pending_put;
1058 INIT_LIST_HEAD(&pending_put);
1060 if (--fs_devices->opened > 0)
1061 return 0;
1063 mutex_lock(&fs_devices->device_list_mutex);
1064 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1065 btrfs_prepare_close_one_device(device);
1066 list_add(&device->dev_list, &pending_put);
1068 mutex_unlock(&fs_devices->device_list_mutex);
1071 * btrfs_show_devname() is using the device_list_mutex,
1072 * sometimes call to blkdev_put() leads vfs calling
1073 * into this func. So do put outside of device_list_mutex,
1074 * as of now.
1076 while (!list_empty(&pending_put)) {
1077 device = list_first_entry(&pending_put,
1078 struct btrfs_device, dev_list);
1079 list_del(&device->dev_list);
1080 btrfs_close_bdev(device);
1081 call_rcu(&device->rcu, free_device_rcu);
1084 WARN_ON(fs_devices->open_devices);
1085 WARN_ON(fs_devices->rw_devices);
1086 fs_devices->opened = 0;
1087 fs_devices->seeding = 0;
1089 return 0;
1092 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1094 struct btrfs_fs_devices *seed_devices = NULL;
1095 int ret;
1097 mutex_lock(&uuid_mutex);
1098 ret = close_fs_devices(fs_devices);
1099 if (!fs_devices->opened) {
1100 seed_devices = fs_devices->seed;
1101 fs_devices->seed = NULL;
1103 mutex_unlock(&uuid_mutex);
1105 while (seed_devices) {
1106 fs_devices = seed_devices;
1107 seed_devices = fs_devices->seed;
1108 close_fs_devices(fs_devices);
1109 free_fs_devices(fs_devices);
1111 return ret;
1114 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1115 fmode_t flags, void *holder)
1117 struct btrfs_device *device;
1118 struct btrfs_device *latest_dev = NULL;
1119 int ret = 0;
1121 flags |= FMODE_EXCL;
1123 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1124 /* Just open everything we can; ignore failures here */
1125 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1126 continue;
1128 if (!latest_dev ||
1129 device->generation > latest_dev->generation)
1130 latest_dev = device;
1132 if (fs_devices->open_devices == 0) {
1133 ret = -EINVAL;
1134 goto out;
1136 fs_devices->opened = 1;
1137 fs_devices->latest_bdev = latest_dev->bdev;
1138 fs_devices->total_rw_bytes = 0;
1139 out:
1140 return ret;
1143 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1145 struct btrfs_device *dev1, *dev2;
1147 dev1 = list_entry(a, struct btrfs_device, dev_list);
1148 dev2 = list_entry(b, struct btrfs_device, dev_list);
1150 if (dev1->devid < dev2->devid)
1151 return -1;
1152 else if (dev1->devid > dev2->devid)
1153 return 1;
1154 return 0;
1157 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1158 fmode_t flags, void *holder)
1160 int ret;
1162 lockdep_assert_held(&uuid_mutex);
1164 mutex_lock(&fs_devices->device_list_mutex);
1165 if (fs_devices->opened) {
1166 fs_devices->opened++;
1167 ret = 0;
1168 } else {
1169 list_sort(NULL, &fs_devices->devices, devid_cmp);
1170 ret = open_fs_devices(fs_devices, flags, holder);
1172 mutex_unlock(&fs_devices->device_list_mutex);
1174 return ret;
1177 static void btrfs_release_disk_super(struct page *page)
1179 kunmap(page);
1180 put_page(page);
1183 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1184 struct page **page,
1185 struct btrfs_super_block **disk_super)
1187 void *p;
1188 pgoff_t index;
1190 /* make sure our super fits in the device */
1191 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1192 return 1;
1194 /* make sure our super fits in the page */
1195 if (sizeof(**disk_super) > PAGE_SIZE)
1196 return 1;
1198 /* make sure our super doesn't straddle pages on disk */
1199 index = bytenr >> PAGE_SHIFT;
1200 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1201 return 1;
1203 /* pull in the page with our super */
1204 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1205 index, GFP_KERNEL);
1207 if (IS_ERR_OR_NULL(*page))
1208 return 1;
1210 p = kmap(*page);
1212 /* align our pointer to the offset of the super block */
1213 *disk_super = p + (bytenr & ~PAGE_MASK);
1215 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1216 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1217 btrfs_release_disk_super(*page);
1218 return 1;
1221 if ((*disk_super)->label[0] &&
1222 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1223 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1225 return 0;
1229 * Look for a btrfs signature on a device. This may be called out of the mount path
1230 * and we are not allowed to call set_blocksize during the scan. The superblock
1231 * is read via pagecache
1233 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
1234 struct btrfs_fs_devices **fs_devices_ret)
1236 struct btrfs_super_block *disk_super;
1237 bool new_device_added = false;
1238 struct btrfs_device *device;
1239 struct block_device *bdev;
1240 struct page *page;
1241 int ret = 0;
1242 u64 bytenr;
1244 lockdep_assert_held(&uuid_mutex);
1247 * we would like to check all the supers, but that would make
1248 * a btrfs mount succeed after a mkfs from a different FS.
1249 * So, we need to add a special mount option to scan for
1250 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1252 bytenr = btrfs_sb_offset(0);
1253 flags |= FMODE_EXCL;
1255 bdev = blkdev_get_by_path(path, flags, holder);
1256 if (IS_ERR(bdev))
1257 return PTR_ERR(bdev);
1259 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1260 ret = -EINVAL;
1261 goto error_bdev_put;
1264 device = device_list_add(path, disk_super, &new_device_added);
1265 if (IS_ERR(device)) {
1266 ret = PTR_ERR(device);
1267 } else {
1268 *fs_devices_ret = device->fs_devices;
1269 if (new_device_added)
1270 btrfs_free_stale_devices(path, device);
1273 btrfs_release_disk_super(page);
1275 error_bdev_put:
1276 blkdev_put(bdev, flags);
1278 return ret;
1281 /* helper to account the used device space in the range */
1282 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1283 u64 end, u64 *length)
1285 struct btrfs_key key;
1286 struct btrfs_root *root = device->fs_info->dev_root;
1287 struct btrfs_dev_extent *dev_extent;
1288 struct btrfs_path *path;
1289 u64 extent_end;
1290 int ret;
1291 int slot;
1292 struct extent_buffer *l;
1294 *length = 0;
1296 if (start >= device->total_bytes ||
1297 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
1298 return 0;
1300 path = btrfs_alloc_path();
1301 if (!path)
1302 return -ENOMEM;
1303 path->reada = READA_FORWARD;
1305 key.objectid = device->devid;
1306 key.offset = start;
1307 key.type = BTRFS_DEV_EXTENT_KEY;
1309 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1310 if (ret < 0)
1311 goto out;
1312 if (ret > 0) {
1313 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1314 if (ret < 0)
1315 goto out;
1318 while (1) {
1319 l = path->nodes[0];
1320 slot = path->slots[0];
1321 if (slot >= btrfs_header_nritems(l)) {
1322 ret = btrfs_next_leaf(root, path);
1323 if (ret == 0)
1324 continue;
1325 if (ret < 0)
1326 goto out;
1328 break;
1330 btrfs_item_key_to_cpu(l, &key, slot);
1332 if (key.objectid < device->devid)
1333 goto next;
1335 if (key.objectid > device->devid)
1336 break;
1338 if (key.type != BTRFS_DEV_EXTENT_KEY)
1339 goto next;
1341 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1342 extent_end = key.offset + btrfs_dev_extent_length(l,
1343 dev_extent);
1344 if (key.offset <= start && extent_end > end) {
1345 *length = end - start + 1;
1346 break;
1347 } else if (key.offset <= start && extent_end > start)
1348 *length += extent_end - start;
1349 else if (key.offset > start && extent_end <= end)
1350 *length += extent_end - key.offset;
1351 else if (key.offset > start && key.offset <= end) {
1352 *length += end - key.offset + 1;
1353 break;
1354 } else if (key.offset > end)
1355 break;
1357 next:
1358 path->slots[0]++;
1360 ret = 0;
1361 out:
1362 btrfs_free_path(path);
1363 return ret;
1366 static int contains_pending_extent(struct btrfs_transaction *transaction,
1367 struct btrfs_device *device,
1368 u64 *start, u64 len)
1370 struct btrfs_fs_info *fs_info = device->fs_info;
1371 struct extent_map *em;
1372 struct list_head *search_list = &fs_info->pinned_chunks;
1373 int ret = 0;
1374 u64 physical_start = *start;
1376 if (transaction)
1377 search_list = &transaction->pending_chunks;
1378 again:
1379 list_for_each_entry(em, search_list, list) {
1380 struct map_lookup *map;
1381 int i;
1383 map = em->map_lookup;
1384 for (i = 0; i < map->num_stripes; i++) {
1385 u64 end;
1387 if (map->stripes[i].dev != device)
1388 continue;
1389 if (map->stripes[i].physical >= physical_start + len ||
1390 map->stripes[i].physical + em->orig_block_len <=
1391 physical_start)
1392 continue;
1394 * Make sure that while processing the pinned list we do
1395 * not override our *start with a lower value, because
1396 * we can have pinned chunks that fall within this
1397 * device hole and that have lower physical addresses
1398 * than the pending chunks we processed before. If we
1399 * do not take this special care we can end up getting
1400 * 2 pending chunks that start at the same physical
1401 * device offsets because the end offset of a pinned
1402 * chunk can be equal to the start offset of some
1403 * pending chunk.
1405 end = map->stripes[i].physical + em->orig_block_len;
1406 if (end > *start) {
1407 *start = end;
1408 ret = 1;
1412 if (search_list != &fs_info->pinned_chunks) {
1413 search_list = &fs_info->pinned_chunks;
1414 goto again;
1417 return ret;
1422 * find_free_dev_extent_start - find free space in the specified device
1423 * @device: the device which we search the free space in
1424 * @num_bytes: the size of the free space that we need
1425 * @search_start: the position from which to begin the search
1426 * @start: store the start of the free space.
1427 * @len: the size of the free space. that we find, or the size
1428 * of the max free space if we don't find suitable free space
1430 * this uses a pretty simple search, the expectation is that it is
1431 * called very infrequently and that a given device has a small number
1432 * of extents
1434 * @start is used to store the start of the free space if we find. But if we
1435 * don't find suitable free space, it will be used to store the start position
1436 * of the max free space.
1438 * @len is used to store the size of the free space that we find.
1439 * But if we don't find suitable free space, it is used to store the size of
1440 * the max free space.
1442 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1443 struct btrfs_device *device, u64 num_bytes,
1444 u64 search_start, u64 *start, u64 *len)
1446 struct btrfs_fs_info *fs_info = device->fs_info;
1447 struct btrfs_root *root = fs_info->dev_root;
1448 struct btrfs_key key;
1449 struct btrfs_dev_extent *dev_extent;
1450 struct btrfs_path *path;
1451 u64 hole_size;
1452 u64 max_hole_start;
1453 u64 max_hole_size;
1454 u64 extent_end;
1455 u64 search_end = device->total_bytes;
1456 int ret;
1457 int slot;
1458 struct extent_buffer *l;
1461 * We don't want to overwrite the superblock on the drive nor any area
1462 * used by the boot loader (grub for example), so we make sure to start
1463 * at an offset of at least 1MB.
1465 search_start = max_t(u64, search_start, SZ_1M);
1467 path = btrfs_alloc_path();
1468 if (!path)
1469 return -ENOMEM;
1471 max_hole_start = search_start;
1472 max_hole_size = 0;
1474 again:
1475 if (search_start >= search_end ||
1476 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1477 ret = -ENOSPC;
1478 goto out;
1481 path->reada = READA_FORWARD;
1482 path->search_commit_root = 1;
1483 path->skip_locking = 1;
1485 key.objectid = device->devid;
1486 key.offset = search_start;
1487 key.type = BTRFS_DEV_EXTENT_KEY;
1489 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1490 if (ret < 0)
1491 goto out;
1492 if (ret > 0) {
1493 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1494 if (ret < 0)
1495 goto out;
1498 while (1) {
1499 l = path->nodes[0];
1500 slot = path->slots[0];
1501 if (slot >= btrfs_header_nritems(l)) {
1502 ret = btrfs_next_leaf(root, path);
1503 if (ret == 0)
1504 continue;
1505 if (ret < 0)
1506 goto out;
1508 break;
1510 btrfs_item_key_to_cpu(l, &key, slot);
1512 if (key.objectid < device->devid)
1513 goto next;
1515 if (key.objectid > device->devid)
1516 break;
1518 if (key.type != BTRFS_DEV_EXTENT_KEY)
1519 goto next;
1521 if (key.offset > search_start) {
1522 hole_size = key.offset - search_start;
1525 * Have to check before we set max_hole_start, otherwise
1526 * we could end up sending back this offset anyway.
1528 if (contains_pending_extent(transaction, device,
1529 &search_start,
1530 hole_size)) {
1531 if (key.offset >= search_start) {
1532 hole_size = key.offset - search_start;
1533 } else {
1534 WARN_ON_ONCE(1);
1535 hole_size = 0;
1539 if (hole_size > max_hole_size) {
1540 max_hole_start = search_start;
1541 max_hole_size = hole_size;
1545 * If this free space is greater than which we need,
1546 * it must be the max free space that we have found
1547 * until now, so max_hole_start must point to the start
1548 * of this free space and the length of this free space
1549 * is stored in max_hole_size. Thus, we return
1550 * max_hole_start and max_hole_size and go back to the
1551 * caller.
1553 if (hole_size >= num_bytes) {
1554 ret = 0;
1555 goto out;
1559 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1560 extent_end = key.offset + btrfs_dev_extent_length(l,
1561 dev_extent);
1562 if (extent_end > search_start)
1563 search_start = extent_end;
1564 next:
1565 path->slots[0]++;
1566 cond_resched();
1570 * At this point, search_start should be the end of
1571 * allocated dev extents, and when shrinking the device,
1572 * search_end may be smaller than search_start.
1574 if (search_end > search_start) {
1575 hole_size = search_end - search_start;
1577 if (contains_pending_extent(transaction, device, &search_start,
1578 hole_size)) {
1579 btrfs_release_path(path);
1580 goto again;
1583 if (hole_size > max_hole_size) {
1584 max_hole_start = search_start;
1585 max_hole_size = hole_size;
1589 /* See above. */
1590 if (max_hole_size < num_bytes)
1591 ret = -ENOSPC;
1592 else
1593 ret = 0;
1595 out:
1596 btrfs_free_path(path);
1597 *start = max_hole_start;
1598 if (len)
1599 *len = max_hole_size;
1600 return ret;
1603 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1604 struct btrfs_device *device, u64 num_bytes,
1605 u64 *start, u64 *len)
1607 /* FIXME use last free of some kind */
1608 return find_free_dev_extent_start(trans->transaction, device,
1609 num_bytes, 0, start, len);
1612 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1613 struct btrfs_device *device,
1614 u64 start, u64 *dev_extent_len)
1616 struct btrfs_fs_info *fs_info = device->fs_info;
1617 struct btrfs_root *root = fs_info->dev_root;
1618 int ret;
1619 struct btrfs_path *path;
1620 struct btrfs_key key;
1621 struct btrfs_key found_key;
1622 struct extent_buffer *leaf = NULL;
1623 struct btrfs_dev_extent *extent = NULL;
1625 path = btrfs_alloc_path();
1626 if (!path)
1627 return -ENOMEM;
1629 key.objectid = device->devid;
1630 key.offset = start;
1631 key.type = BTRFS_DEV_EXTENT_KEY;
1632 again:
1633 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1634 if (ret > 0) {
1635 ret = btrfs_previous_item(root, path, key.objectid,
1636 BTRFS_DEV_EXTENT_KEY);
1637 if (ret)
1638 goto out;
1639 leaf = path->nodes[0];
1640 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1641 extent = btrfs_item_ptr(leaf, path->slots[0],
1642 struct btrfs_dev_extent);
1643 BUG_ON(found_key.offset > start || found_key.offset +
1644 btrfs_dev_extent_length(leaf, extent) < start);
1645 key = found_key;
1646 btrfs_release_path(path);
1647 goto again;
1648 } else if (ret == 0) {
1649 leaf = path->nodes[0];
1650 extent = btrfs_item_ptr(leaf, path->slots[0],
1651 struct btrfs_dev_extent);
1652 } else {
1653 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1654 goto out;
1657 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1659 ret = btrfs_del_item(trans, root, path);
1660 if (ret) {
1661 btrfs_handle_fs_error(fs_info, ret,
1662 "Failed to remove dev extent item");
1663 } else {
1664 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1666 out:
1667 btrfs_free_path(path);
1668 return ret;
1671 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1672 struct btrfs_device *device,
1673 u64 chunk_offset, u64 start, u64 num_bytes)
1675 int ret;
1676 struct btrfs_path *path;
1677 struct btrfs_fs_info *fs_info = device->fs_info;
1678 struct btrfs_root *root = fs_info->dev_root;
1679 struct btrfs_dev_extent *extent;
1680 struct extent_buffer *leaf;
1681 struct btrfs_key key;
1683 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1684 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1685 path = btrfs_alloc_path();
1686 if (!path)
1687 return -ENOMEM;
1689 key.objectid = device->devid;
1690 key.offset = start;
1691 key.type = BTRFS_DEV_EXTENT_KEY;
1692 ret = btrfs_insert_empty_item(trans, root, path, &key,
1693 sizeof(*extent));
1694 if (ret)
1695 goto out;
1697 leaf = path->nodes[0];
1698 extent = btrfs_item_ptr(leaf, path->slots[0],
1699 struct btrfs_dev_extent);
1700 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1701 BTRFS_CHUNK_TREE_OBJECTID);
1702 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1703 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1704 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1706 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1707 btrfs_mark_buffer_dirty(leaf);
1708 out:
1709 btrfs_free_path(path);
1710 return ret;
1713 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1715 struct extent_map_tree *em_tree;
1716 struct extent_map *em;
1717 struct rb_node *n;
1718 u64 ret = 0;
1720 em_tree = &fs_info->mapping_tree.map_tree;
1721 read_lock(&em_tree->lock);
1722 n = rb_last(&em_tree->map);
1723 if (n) {
1724 em = rb_entry(n, struct extent_map, rb_node);
1725 ret = em->start + em->len;
1727 read_unlock(&em_tree->lock);
1729 return ret;
1732 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1733 u64 *devid_ret)
1735 int ret;
1736 struct btrfs_key key;
1737 struct btrfs_key found_key;
1738 struct btrfs_path *path;
1740 path = btrfs_alloc_path();
1741 if (!path)
1742 return -ENOMEM;
1744 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1745 key.type = BTRFS_DEV_ITEM_KEY;
1746 key.offset = (u64)-1;
1748 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1749 if (ret < 0)
1750 goto error;
1752 BUG_ON(ret == 0); /* Corruption */
1754 ret = btrfs_previous_item(fs_info->chunk_root, path,
1755 BTRFS_DEV_ITEMS_OBJECTID,
1756 BTRFS_DEV_ITEM_KEY);
1757 if (ret) {
1758 *devid_ret = 1;
1759 } else {
1760 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1761 path->slots[0]);
1762 *devid_ret = found_key.offset + 1;
1764 ret = 0;
1765 error:
1766 btrfs_free_path(path);
1767 return ret;
1771 * the device information is stored in the chunk root
1772 * the btrfs_device struct should be fully filled in
1774 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1775 struct btrfs_fs_info *fs_info,
1776 struct btrfs_device *device)
1778 struct btrfs_root *root = fs_info->chunk_root;
1779 int ret;
1780 struct btrfs_path *path;
1781 struct btrfs_dev_item *dev_item;
1782 struct extent_buffer *leaf;
1783 struct btrfs_key key;
1784 unsigned long ptr;
1786 path = btrfs_alloc_path();
1787 if (!path)
1788 return -ENOMEM;
1790 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1791 key.type = BTRFS_DEV_ITEM_KEY;
1792 key.offset = device->devid;
1794 ret = btrfs_insert_empty_item(trans, root, path, &key,
1795 sizeof(*dev_item));
1796 if (ret)
1797 goto out;
1799 leaf = path->nodes[0];
1800 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1802 btrfs_set_device_id(leaf, dev_item, device->devid);
1803 btrfs_set_device_generation(leaf, dev_item, 0);
1804 btrfs_set_device_type(leaf, dev_item, device->type);
1805 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1806 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1807 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1808 btrfs_set_device_total_bytes(leaf, dev_item,
1809 btrfs_device_get_disk_total_bytes(device));
1810 btrfs_set_device_bytes_used(leaf, dev_item,
1811 btrfs_device_get_bytes_used(device));
1812 btrfs_set_device_group(leaf, dev_item, 0);
1813 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1814 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1815 btrfs_set_device_start_offset(leaf, dev_item, 0);
1817 ptr = btrfs_device_uuid(dev_item);
1818 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1819 ptr = btrfs_device_fsid(dev_item);
1820 write_extent_buffer(leaf, fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1821 btrfs_mark_buffer_dirty(leaf);
1823 ret = 0;
1824 out:
1825 btrfs_free_path(path);
1826 return ret;
1830 * Function to update ctime/mtime for a given device path.
1831 * Mainly used for ctime/mtime based probe like libblkid.
1833 static void update_dev_time(const char *path_name)
1835 struct file *filp;
1837 filp = filp_open(path_name, O_RDWR, 0);
1838 if (IS_ERR(filp))
1839 return;
1840 file_update_time(filp);
1841 filp_close(filp, NULL);
1844 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1845 struct btrfs_device *device)
1847 struct btrfs_root *root = fs_info->chunk_root;
1848 int ret;
1849 struct btrfs_path *path;
1850 struct btrfs_key key;
1851 struct btrfs_trans_handle *trans;
1853 path = btrfs_alloc_path();
1854 if (!path)
1855 return -ENOMEM;
1857 trans = btrfs_start_transaction(root, 0);
1858 if (IS_ERR(trans)) {
1859 btrfs_free_path(path);
1860 return PTR_ERR(trans);
1862 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1863 key.type = BTRFS_DEV_ITEM_KEY;
1864 key.offset = device->devid;
1866 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1867 if (ret) {
1868 if (ret > 0)
1869 ret = -ENOENT;
1870 btrfs_abort_transaction(trans, ret);
1871 btrfs_end_transaction(trans);
1872 goto out;
1875 ret = btrfs_del_item(trans, root, path);
1876 if (ret) {
1877 btrfs_abort_transaction(trans, ret);
1878 btrfs_end_transaction(trans);
1881 out:
1882 btrfs_free_path(path);
1883 if (!ret)
1884 ret = btrfs_commit_transaction(trans);
1885 return ret;
1889 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1890 * filesystem. It's up to the caller to adjust that number regarding eg. device
1891 * replace.
1893 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1894 u64 num_devices)
1896 u64 all_avail;
1897 unsigned seq;
1898 int i;
1900 do {
1901 seq = read_seqbegin(&fs_info->profiles_lock);
1903 all_avail = fs_info->avail_data_alloc_bits |
1904 fs_info->avail_system_alloc_bits |
1905 fs_info->avail_metadata_alloc_bits;
1906 } while (read_seqretry(&fs_info->profiles_lock, seq));
1908 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1909 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1910 continue;
1912 if (num_devices < btrfs_raid_array[i].devs_min) {
1913 int ret = btrfs_raid_array[i].mindev_error;
1915 if (ret)
1916 return ret;
1920 return 0;
1923 static struct btrfs_device * btrfs_find_next_active_device(
1924 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1926 struct btrfs_device *next_device;
1928 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1929 if (next_device != device &&
1930 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1931 && next_device->bdev)
1932 return next_device;
1935 return NULL;
1939 * Helper function to check if the given device is part of s_bdev / latest_bdev
1940 * and replace it with the provided or the next active device, in the context
1941 * where this function called, there should be always be another device (or
1942 * this_dev) which is active.
1944 void btrfs_assign_next_active_device(struct btrfs_fs_info *fs_info,
1945 struct btrfs_device *device, struct btrfs_device *this_dev)
1947 struct btrfs_device *next_device;
1949 if (this_dev)
1950 next_device = this_dev;
1951 else
1952 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1953 device);
1954 ASSERT(next_device);
1956 if (fs_info->sb->s_bdev &&
1957 (fs_info->sb->s_bdev == device->bdev))
1958 fs_info->sb->s_bdev = next_device->bdev;
1960 if (fs_info->fs_devices->latest_bdev == device->bdev)
1961 fs_info->fs_devices->latest_bdev = next_device->bdev;
1964 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1965 u64 devid)
1967 struct btrfs_device *device;
1968 struct btrfs_fs_devices *cur_devices;
1969 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1970 u64 num_devices;
1971 int ret = 0;
1973 mutex_lock(&uuid_mutex);
1975 num_devices = fs_devices->num_devices;
1976 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
1977 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1978 WARN_ON(num_devices < 1);
1979 num_devices--;
1981 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
1983 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1984 if (ret)
1985 goto out;
1987 ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1988 &device);
1989 if (ret)
1990 goto out;
1992 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1993 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1994 goto out;
1997 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1998 fs_info->fs_devices->rw_devices == 1) {
1999 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
2000 goto out;
2003 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2004 mutex_lock(&fs_info->chunk_mutex);
2005 list_del_init(&device->dev_alloc_list);
2006 device->fs_devices->rw_devices--;
2007 mutex_unlock(&fs_info->chunk_mutex);
2010 mutex_unlock(&uuid_mutex);
2011 ret = btrfs_shrink_device(device, 0);
2012 mutex_lock(&uuid_mutex);
2013 if (ret)
2014 goto error_undo;
2017 * TODO: the superblock still includes this device in its num_devices
2018 * counter although write_all_supers() is not locked out. This
2019 * could give a filesystem state which requires a degraded mount.
2021 ret = btrfs_rm_dev_item(fs_info, device);
2022 if (ret)
2023 goto error_undo;
2025 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2026 btrfs_scrub_cancel_dev(fs_info, device);
2029 * the device list mutex makes sure that we don't change
2030 * the device list while someone else is writing out all
2031 * the device supers. Whoever is writing all supers, should
2032 * lock the device list mutex before getting the number of
2033 * devices in the super block (super_copy). Conversely,
2034 * whoever updates the number of devices in the super block
2035 * (super_copy) should hold the device list mutex.
2039 * In normal cases the cur_devices == fs_devices. But in case
2040 * of deleting a seed device, the cur_devices should point to
2041 * its own fs_devices listed under the fs_devices->seed.
2043 cur_devices = device->fs_devices;
2044 mutex_lock(&fs_devices->device_list_mutex);
2045 list_del_rcu(&device->dev_list);
2047 cur_devices->num_devices--;
2048 cur_devices->total_devices--;
2049 /* Update total_devices of the parent fs_devices if it's seed */
2050 if (cur_devices != fs_devices)
2051 fs_devices->total_devices--;
2053 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2054 cur_devices->missing_devices--;
2056 btrfs_assign_next_active_device(fs_info, device, NULL);
2058 if (device->bdev) {
2059 cur_devices->open_devices--;
2060 /* remove sysfs entry */
2061 btrfs_sysfs_rm_device_link(fs_devices, device);
2064 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2065 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2066 mutex_unlock(&fs_devices->device_list_mutex);
2069 * at this point, the device is zero sized and detached from
2070 * the devices list. All that's left is to zero out the old
2071 * supers and free the device.
2073 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2074 btrfs_scratch_superblocks(device->bdev, device->name->str);
2076 btrfs_close_bdev(device);
2077 call_rcu(&device->rcu, free_device_rcu);
2079 if (cur_devices->open_devices == 0) {
2080 while (fs_devices) {
2081 if (fs_devices->seed == cur_devices) {
2082 fs_devices->seed = cur_devices->seed;
2083 break;
2085 fs_devices = fs_devices->seed;
2087 cur_devices->seed = NULL;
2088 close_fs_devices(cur_devices);
2089 free_fs_devices(cur_devices);
2092 out:
2093 mutex_unlock(&uuid_mutex);
2094 return ret;
2096 error_undo:
2097 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2098 mutex_lock(&fs_info->chunk_mutex);
2099 list_add(&device->dev_alloc_list,
2100 &fs_devices->alloc_list);
2101 device->fs_devices->rw_devices++;
2102 mutex_unlock(&fs_info->chunk_mutex);
2104 goto out;
2107 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
2108 struct btrfs_device *srcdev)
2110 struct btrfs_fs_devices *fs_devices;
2112 lockdep_assert_held(&fs_info->fs_devices->device_list_mutex);
2115 * in case of fs with no seed, srcdev->fs_devices will point
2116 * to fs_devices of fs_info. However when the dev being replaced is
2117 * a seed dev it will point to the seed's local fs_devices. In short
2118 * srcdev will have its correct fs_devices in both the cases.
2120 fs_devices = srcdev->fs_devices;
2122 list_del_rcu(&srcdev->dev_list);
2123 list_del(&srcdev->dev_alloc_list);
2124 fs_devices->num_devices--;
2125 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2126 fs_devices->missing_devices--;
2128 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2129 fs_devices->rw_devices--;
2131 if (srcdev->bdev)
2132 fs_devices->open_devices--;
2135 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2136 struct btrfs_device *srcdev)
2138 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2140 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2141 /* zero out the old super if it is writable */
2142 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2145 btrfs_close_bdev(srcdev);
2146 call_rcu(&srcdev->rcu, free_device_rcu);
2148 /* if this is no devs we rather delete the fs_devices */
2149 if (!fs_devices->num_devices) {
2150 struct btrfs_fs_devices *tmp_fs_devices;
2153 * On a mounted FS, num_devices can't be zero unless it's a
2154 * seed. In case of a seed device being replaced, the replace
2155 * target added to the sprout FS, so there will be no more
2156 * device left under the seed FS.
2158 ASSERT(fs_devices->seeding);
2160 tmp_fs_devices = fs_info->fs_devices;
2161 while (tmp_fs_devices) {
2162 if (tmp_fs_devices->seed == fs_devices) {
2163 tmp_fs_devices->seed = fs_devices->seed;
2164 break;
2166 tmp_fs_devices = tmp_fs_devices->seed;
2168 fs_devices->seed = NULL;
2169 close_fs_devices(fs_devices);
2170 free_fs_devices(fs_devices);
2174 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2175 struct btrfs_device *tgtdev)
2177 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2179 WARN_ON(!tgtdev);
2180 mutex_lock(&fs_devices->device_list_mutex);
2182 btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2184 if (tgtdev->bdev)
2185 fs_devices->open_devices--;
2187 fs_devices->num_devices--;
2189 btrfs_assign_next_active_device(fs_info, tgtdev, NULL);
2191 list_del_rcu(&tgtdev->dev_list);
2193 mutex_unlock(&fs_devices->device_list_mutex);
2196 * The update_dev_time() with in btrfs_scratch_superblocks()
2197 * may lead to a call to btrfs_show_devname() which will try
2198 * to hold device_list_mutex. And here this device
2199 * is already out of device list, so we don't have to hold
2200 * the device_list_mutex lock.
2202 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2204 btrfs_close_bdev(tgtdev);
2205 call_rcu(&tgtdev->rcu, free_device_rcu);
2208 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2209 const char *device_path,
2210 struct btrfs_device **device)
2212 int ret = 0;
2213 struct btrfs_super_block *disk_super;
2214 u64 devid;
2215 u8 *dev_uuid;
2216 struct block_device *bdev;
2217 struct buffer_head *bh;
2219 *device = NULL;
2220 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2221 fs_info->bdev_holder, 0, &bdev, &bh);
2222 if (ret)
2223 return ret;
2224 disk_super = (struct btrfs_super_block *)bh->b_data;
2225 devid = btrfs_stack_device_id(&disk_super->dev_item);
2226 dev_uuid = disk_super->dev_item.uuid;
2227 *device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2228 brelse(bh);
2229 if (!*device)
2230 ret = -ENOENT;
2231 blkdev_put(bdev, FMODE_READ);
2232 return ret;
2235 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2236 const char *device_path,
2237 struct btrfs_device **device)
2239 *device = NULL;
2240 if (strcmp(device_path, "missing") == 0) {
2241 struct list_head *devices;
2242 struct btrfs_device *tmp;
2244 devices = &fs_info->fs_devices->devices;
2245 list_for_each_entry(tmp, devices, dev_list) {
2246 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2247 &tmp->dev_state) && !tmp->bdev) {
2248 *device = tmp;
2249 break;
2253 if (!*device)
2254 return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2256 return 0;
2257 } else {
2258 return btrfs_find_device_by_path(fs_info, device_path, device);
2263 * Lookup a device given by device id, or the path if the id is 0.
2265 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2266 const char *devpath,
2267 struct btrfs_device **device)
2269 int ret;
2271 if (devid) {
2272 ret = 0;
2273 *device = btrfs_find_device(fs_info, devid, NULL, NULL);
2274 if (!*device)
2275 ret = -ENOENT;
2276 } else {
2277 if (!devpath || !devpath[0])
2278 return -EINVAL;
2280 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2281 device);
2283 return ret;
2287 * does all the dirty work required for changing file system's UUID.
2289 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2291 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2292 struct btrfs_fs_devices *old_devices;
2293 struct btrfs_fs_devices *seed_devices;
2294 struct btrfs_super_block *disk_super = fs_info->super_copy;
2295 struct btrfs_device *device;
2296 u64 super_flags;
2298 lockdep_assert_held(&uuid_mutex);
2299 if (!fs_devices->seeding)
2300 return -EINVAL;
2302 seed_devices = alloc_fs_devices(NULL);
2303 if (IS_ERR(seed_devices))
2304 return PTR_ERR(seed_devices);
2306 old_devices = clone_fs_devices(fs_devices);
2307 if (IS_ERR(old_devices)) {
2308 kfree(seed_devices);
2309 return PTR_ERR(old_devices);
2312 list_add(&old_devices->fs_list, &fs_uuids);
2314 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2315 seed_devices->opened = 1;
2316 INIT_LIST_HEAD(&seed_devices->devices);
2317 INIT_LIST_HEAD(&seed_devices->alloc_list);
2318 mutex_init(&seed_devices->device_list_mutex);
2320 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2321 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2322 synchronize_rcu);
2323 list_for_each_entry(device, &seed_devices->devices, dev_list)
2324 device->fs_devices = seed_devices;
2326 mutex_lock(&fs_info->chunk_mutex);
2327 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2328 mutex_unlock(&fs_info->chunk_mutex);
2330 fs_devices->seeding = 0;
2331 fs_devices->num_devices = 0;
2332 fs_devices->open_devices = 0;
2333 fs_devices->missing_devices = 0;
2334 fs_devices->rotating = 0;
2335 fs_devices->seed = seed_devices;
2337 generate_random_uuid(fs_devices->fsid);
2338 memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2339 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2340 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2342 super_flags = btrfs_super_flags(disk_super) &
2343 ~BTRFS_SUPER_FLAG_SEEDING;
2344 btrfs_set_super_flags(disk_super, super_flags);
2346 return 0;
2350 * Store the expected generation for seed devices in device items.
2352 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2353 struct btrfs_fs_info *fs_info)
2355 struct btrfs_root *root = fs_info->chunk_root;
2356 struct btrfs_path *path;
2357 struct extent_buffer *leaf;
2358 struct btrfs_dev_item *dev_item;
2359 struct btrfs_device *device;
2360 struct btrfs_key key;
2361 u8 fs_uuid[BTRFS_FSID_SIZE];
2362 u8 dev_uuid[BTRFS_UUID_SIZE];
2363 u64 devid;
2364 int ret;
2366 path = btrfs_alloc_path();
2367 if (!path)
2368 return -ENOMEM;
2370 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2371 key.offset = 0;
2372 key.type = BTRFS_DEV_ITEM_KEY;
2374 while (1) {
2375 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2376 if (ret < 0)
2377 goto error;
2379 leaf = path->nodes[0];
2380 next_slot:
2381 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2382 ret = btrfs_next_leaf(root, path);
2383 if (ret > 0)
2384 break;
2385 if (ret < 0)
2386 goto error;
2387 leaf = path->nodes[0];
2388 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2389 btrfs_release_path(path);
2390 continue;
2393 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2394 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2395 key.type != BTRFS_DEV_ITEM_KEY)
2396 break;
2398 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2399 struct btrfs_dev_item);
2400 devid = btrfs_device_id(leaf, dev_item);
2401 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2402 BTRFS_UUID_SIZE);
2403 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2404 BTRFS_FSID_SIZE);
2405 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2406 BUG_ON(!device); /* Logic error */
2408 if (device->fs_devices->seeding) {
2409 btrfs_set_device_generation(leaf, dev_item,
2410 device->generation);
2411 btrfs_mark_buffer_dirty(leaf);
2414 path->slots[0]++;
2415 goto next_slot;
2417 ret = 0;
2418 error:
2419 btrfs_free_path(path);
2420 return ret;
2423 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2425 struct btrfs_root *root = fs_info->dev_root;
2426 struct request_queue *q;
2427 struct btrfs_trans_handle *trans;
2428 struct btrfs_device *device;
2429 struct block_device *bdev;
2430 struct list_head *devices;
2431 struct super_block *sb = fs_info->sb;
2432 struct rcu_string *name;
2433 u64 tmp;
2434 int seeding_dev = 0;
2435 int ret = 0;
2436 bool unlocked = false;
2438 if (sb_rdonly(sb) && !fs_info->fs_devices->seeding)
2439 return -EROFS;
2441 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2442 fs_info->bdev_holder);
2443 if (IS_ERR(bdev))
2444 return PTR_ERR(bdev);
2446 if (fs_info->fs_devices->seeding) {
2447 seeding_dev = 1;
2448 down_write(&sb->s_umount);
2449 mutex_lock(&uuid_mutex);
2452 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2454 devices = &fs_info->fs_devices->devices;
2456 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2457 list_for_each_entry(device, devices, dev_list) {
2458 if (device->bdev == bdev) {
2459 ret = -EEXIST;
2460 mutex_unlock(
2461 &fs_info->fs_devices->device_list_mutex);
2462 goto error;
2465 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2467 device = btrfs_alloc_device(fs_info, NULL, NULL);
2468 if (IS_ERR(device)) {
2469 /* we can safely leave the fs_devices entry around */
2470 ret = PTR_ERR(device);
2471 goto error;
2474 name = rcu_string_strdup(device_path, GFP_KERNEL);
2475 if (!name) {
2476 ret = -ENOMEM;
2477 goto error_free_device;
2479 rcu_assign_pointer(device->name, name);
2481 trans = btrfs_start_transaction(root, 0);
2482 if (IS_ERR(trans)) {
2483 ret = PTR_ERR(trans);
2484 goto error_free_device;
2487 q = bdev_get_queue(bdev);
2488 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2489 device->generation = trans->transid;
2490 device->io_width = fs_info->sectorsize;
2491 device->io_align = fs_info->sectorsize;
2492 device->sector_size = fs_info->sectorsize;
2493 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2494 fs_info->sectorsize);
2495 device->disk_total_bytes = device->total_bytes;
2496 device->commit_total_bytes = device->total_bytes;
2497 device->fs_info = fs_info;
2498 device->bdev = bdev;
2499 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2500 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2501 device->mode = FMODE_EXCL;
2502 device->dev_stats_valid = 1;
2503 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2505 if (seeding_dev) {
2506 sb->s_flags &= ~SB_RDONLY;
2507 ret = btrfs_prepare_sprout(fs_info);
2508 if (ret) {
2509 btrfs_abort_transaction(trans, ret);
2510 goto error_trans;
2514 device->fs_devices = fs_info->fs_devices;
2516 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2517 mutex_lock(&fs_info->chunk_mutex);
2518 list_add_rcu(&device->dev_list, &fs_info->fs_devices->devices);
2519 list_add(&device->dev_alloc_list,
2520 &fs_info->fs_devices->alloc_list);
2521 fs_info->fs_devices->num_devices++;
2522 fs_info->fs_devices->open_devices++;
2523 fs_info->fs_devices->rw_devices++;
2524 fs_info->fs_devices->total_devices++;
2525 fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2527 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2529 if (!blk_queue_nonrot(q))
2530 fs_info->fs_devices->rotating = 1;
2532 tmp = btrfs_super_total_bytes(fs_info->super_copy);
2533 btrfs_set_super_total_bytes(fs_info->super_copy,
2534 round_down(tmp + device->total_bytes, fs_info->sectorsize));
2536 tmp = btrfs_super_num_devices(fs_info->super_copy);
2537 btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
2539 /* add sysfs device entry */
2540 btrfs_sysfs_add_device_link(fs_info->fs_devices, device);
2543 * we've got more storage, clear any full flags on the space
2544 * infos
2546 btrfs_clear_space_info_full(fs_info);
2548 mutex_unlock(&fs_info->chunk_mutex);
2549 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2551 if (seeding_dev) {
2552 mutex_lock(&fs_info->chunk_mutex);
2553 ret = init_first_rw_device(trans, fs_info);
2554 mutex_unlock(&fs_info->chunk_mutex);
2555 if (ret) {
2556 btrfs_abort_transaction(trans, ret);
2557 goto error_sysfs;
2561 ret = btrfs_add_dev_item(trans, fs_info, device);
2562 if (ret) {
2563 btrfs_abort_transaction(trans, ret);
2564 goto error_sysfs;
2567 if (seeding_dev) {
2568 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2570 ret = btrfs_finish_sprout(trans, fs_info);
2571 if (ret) {
2572 btrfs_abort_transaction(trans, ret);
2573 goto error_sysfs;
2576 /* Sprouting would change fsid of the mounted root,
2577 * so rename the fsid on the sysfs
2579 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2580 fs_info->fsid);
2581 if (kobject_rename(&fs_info->fs_devices->fsid_kobj, fsid_buf))
2582 btrfs_warn(fs_info,
2583 "sysfs: failed to create fsid for sprout");
2586 ret = btrfs_commit_transaction(trans);
2588 if (seeding_dev) {
2589 mutex_unlock(&uuid_mutex);
2590 up_write(&sb->s_umount);
2591 unlocked = true;
2593 if (ret) /* transaction commit */
2594 return ret;
2596 ret = btrfs_relocate_sys_chunks(fs_info);
2597 if (ret < 0)
2598 btrfs_handle_fs_error(fs_info, ret,
2599 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2600 trans = btrfs_attach_transaction(root);
2601 if (IS_ERR(trans)) {
2602 if (PTR_ERR(trans) == -ENOENT)
2603 return 0;
2604 ret = PTR_ERR(trans);
2605 trans = NULL;
2606 goto error_sysfs;
2608 ret = btrfs_commit_transaction(trans);
2611 /* Update ctime/mtime for libblkid */
2612 update_dev_time(device_path);
2613 return ret;
2615 error_sysfs:
2616 btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
2617 error_trans:
2618 if (seeding_dev)
2619 sb->s_flags |= SB_RDONLY;
2620 if (trans)
2621 btrfs_end_transaction(trans);
2622 error_free_device:
2623 btrfs_free_device(device);
2624 error:
2625 blkdev_put(bdev, FMODE_EXCL);
2626 if (seeding_dev && !unlocked) {
2627 mutex_unlock(&uuid_mutex);
2628 up_write(&sb->s_umount);
2630 return ret;
2633 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2634 struct btrfs_device *device)
2636 int ret;
2637 struct btrfs_path *path;
2638 struct btrfs_root *root = device->fs_info->chunk_root;
2639 struct btrfs_dev_item *dev_item;
2640 struct extent_buffer *leaf;
2641 struct btrfs_key key;
2643 path = btrfs_alloc_path();
2644 if (!path)
2645 return -ENOMEM;
2647 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2648 key.type = BTRFS_DEV_ITEM_KEY;
2649 key.offset = device->devid;
2651 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2652 if (ret < 0)
2653 goto out;
2655 if (ret > 0) {
2656 ret = -ENOENT;
2657 goto out;
2660 leaf = path->nodes[0];
2661 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2663 btrfs_set_device_id(leaf, dev_item, device->devid);
2664 btrfs_set_device_type(leaf, dev_item, device->type);
2665 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2666 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2667 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2668 btrfs_set_device_total_bytes(leaf, dev_item,
2669 btrfs_device_get_disk_total_bytes(device));
2670 btrfs_set_device_bytes_used(leaf, dev_item,
2671 btrfs_device_get_bytes_used(device));
2672 btrfs_mark_buffer_dirty(leaf);
2674 out:
2675 btrfs_free_path(path);
2676 return ret;
2679 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2680 struct btrfs_device *device, u64 new_size)
2682 struct btrfs_fs_info *fs_info = device->fs_info;
2683 struct btrfs_super_block *super_copy = fs_info->super_copy;
2684 struct btrfs_fs_devices *fs_devices;
2685 u64 old_total;
2686 u64 diff;
2688 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2689 return -EACCES;
2691 new_size = round_down(new_size, fs_info->sectorsize);
2693 mutex_lock(&fs_info->chunk_mutex);
2694 old_total = btrfs_super_total_bytes(super_copy);
2695 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2697 if (new_size <= device->total_bytes ||
2698 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2699 mutex_unlock(&fs_info->chunk_mutex);
2700 return -EINVAL;
2703 fs_devices = fs_info->fs_devices;
2705 btrfs_set_super_total_bytes(super_copy,
2706 round_down(old_total + diff, fs_info->sectorsize));
2707 device->fs_devices->total_rw_bytes += diff;
2709 btrfs_device_set_total_bytes(device, new_size);
2710 btrfs_device_set_disk_total_bytes(device, new_size);
2711 btrfs_clear_space_info_full(device->fs_info);
2712 if (list_empty(&device->resized_list))
2713 list_add_tail(&device->resized_list,
2714 &fs_devices->resized_devices);
2715 mutex_unlock(&fs_info->chunk_mutex);
2717 return btrfs_update_device(trans, device);
2720 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2721 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2723 struct btrfs_root *root = fs_info->chunk_root;
2724 int ret;
2725 struct btrfs_path *path;
2726 struct btrfs_key key;
2728 path = btrfs_alloc_path();
2729 if (!path)
2730 return -ENOMEM;
2732 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2733 key.offset = chunk_offset;
2734 key.type = BTRFS_CHUNK_ITEM_KEY;
2736 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2737 if (ret < 0)
2738 goto out;
2739 else if (ret > 0) { /* Logic error or corruption */
2740 btrfs_handle_fs_error(fs_info, -ENOENT,
2741 "Failed lookup while freeing chunk.");
2742 ret = -ENOENT;
2743 goto out;
2746 ret = btrfs_del_item(trans, root, path);
2747 if (ret < 0)
2748 btrfs_handle_fs_error(fs_info, ret,
2749 "Failed to delete chunk item.");
2750 out:
2751 btrfs_free_path(path);
2752 return ret;
2755 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2757 struct btrfs_super_block *super_copy = fs_info->super_copy;
2758 struct btrfs_disk_key *disk_key;
2759 struct btrfs_chunk *chunk;
2760 u8 *ptr;
2761 int ret = 0;
2762 u32 num_stripes;
2763 u32 array_size;
2764 u32 len = 0;
2765 u32 cur;
2766 struct btrfs_key key;
2768 mutex_lock(&fs_info->chunk_mutex);
2769 array_size = btrfs_super_sys_array_size(super_copy);
2771 ptr = super_copy->sys_chunk_array;
2772 cur = 0;
2774 while (cur < array_size) {
2775 disk_key = (struct btrfs_disk_key *)ptr;
2776 btrfs_disk_key_to_cpu(&key, disk_key);
2778 len = sizeof(*disk_key);
2780 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2781 chunk = (struct btrfs_chunk *)(ptr + len);
2782 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2783 len += btrfs_chunk_item_size(num_stripes);
2784 } else {
2785 ret = -EIO;
2786 break;
2788 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2789 key.offset == chunk_offset) {
2790 memmove(ptr, ptr + len, array_size - (cur + len));
2791 array_size -= len;
2792 btrfs_set_super_sys_array_size(super_copy, array_size);
2793 } else {
2794 ptr += len;
2795 cur += len;
2798 mutex_unlock(&fs_info->chunk_mutex);
2799 return ret;
2802 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2803 u64 logical, u64 length)
2805 struct extent_map_tree *em_tree;
2806 struct extent_map *em;
2808 em_tree = &fs_info->mapping_tree.map_tree;
2809 read_lock(&em_tree->lock);
2810 em = lookup_extent_mapping(em_tree, logical, length);
2811 read_unlock(&em_tree->lock);
2813 if (!em) {
2814 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2815 logical, length);
2816 return ERR_PTR(-EINVAL);
2819 if (em->start > logical || em->start + em->len < logical) {
2820 btrfs_crit(fs_info,
2821 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2822 logical, length, em->start, em->start + em->len);
2823 free_extent_map(em);
2824 return ERR_PTR(-EINVAL);
2827 /* callers are responsible for dropping em's ref. */
2828 return em;
2831 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2832 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2834 struct extent_map *em;
2835 struct map_lookup *map;
2836 u64 dev_extent_len = 0;
2837 int i, ret = 0;
2838 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2840 em = get_chunk_map(fs_info, chunk_offset, 1);
2841 if (IS_ERR(em)) {
2843 * This is a logic error, but we don't want to just rely on the
2844 * user having built with ASSERT enabled, so if ASSERT doesn't
2845 * do anything we still error out.
2847 ASSERT(0);
2848 return PTR_ERR(em);
2850 map = em->map_lookup;
2851 mutex_lock(&fs_info->chunk_mutex);
2852 check_system_chunk(trans, fs_info, map->type);
2853 mutex_unlock(&fs_info->chunk_mutex);
2856 * Take the device list mutex to prevent races with the final phase of
2857 * a device replace operation that replaces the device object associated
2858 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2860 mutex_lock(&fs_devices->device_list_mutex);
2861 for (i = 0; i < map->num_stripes; i++) {
2862 struct btrfs_device *device = map->stripes[i].dev;
2863 ret = btrfs_free_dev_extent(trans, device,
2864 map->stripes[i].physical,
2865 &dev_extent_len);
2866 if (ret) {
2867 mutex_unlock(&fs_devices->device_list_mutex);
2868 btrfs_abort_transaction(trans, ret);
2869 goto out;
2872 if (device->bytes_used > 0) {
2873 mutex_lock(&fs_info->chunk_mutex);
2874 btrfs_device_set_bytes_used(device,
2875 device->bytes_used - dev_extent_len);
2876 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2877 btrfs_clear_space_info_full(fs_info);
2878 mutex_unlock(&fs_info->chunk_mutex);
2881 if (map->stripes[i].dev) {
2882 ret = btrfs_update_device(trans, map->stripes[i].dev);
2883 if (ret) {
2884 mutex_unlock(&fs_devices->device_list_mutex);
2885 btrfs_abort_transaction(trans, ret);
2886 goto out;
2890 mutex_unlock(&fs_devices->device_list_mutex);
2892 ret = btrfs_free_chunk(trans, fs_info, chunk_offset);
2893 if (ret) {
2894 btrfs_abort_transaction(trans, ret);
2895 goto out;
2898 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2900 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2901 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2902 if (ret) {
2903 btrfs_abort_transaction(trans, ret);
2904 goto out;
2908 ret = btrfs_remove_block_group(trans, fs_info, chunk_offset, em);
2909 if (ret) {
2910 btrfs_abort_transaction(trans, ret);
2911 goto out;
2914 out:
2915 /* once for us */
2916 free_extent_map(em);
2917 return ret;
2920 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2922 struct btrfs_root *root = fs_info->chunk_root;
2923 struct btrfs_trans_handle *trans;
2924 int ret;
2927 * Prevent races with automatic removal of unused block groups.
2928 * After we relocate and before we remove the chunk with offset
2929 * chunk_offset, automatic removal of the block group can kick in,
2930 * resulting in a failure when calling btrfs_remove_chunk() below.
2932 * Make sure to acquire this mutex before doing a tree search (dev
2933 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2934 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2935 * we release the path used to search the chunk/dev tree and before
2936 * the current task acquires this mutex and calls us.
2938 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
2940 ret = btrfs_can_relocate(fs_info, chunk_offset);
2941 if (ret)
2942 return -ENOSPC;
2944 /* step one, relocate all the extents inside this chunk */
2945 btrfs_scrub_pause(fs_info);
2946 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2947 btrfs_scrub_continue(fs_info);
2948 if (ret)
2949 return ret;
2952 * We add the kobjects here (and after forcing data chunk creation)
2953 * since relocation is the only place we'll create chunks of a new
2954 * type at runtime. The only place where we'll remove the last
2955 * chunk of a type is the call immediately below this one. Even
2956 * so, we're protected against races with the cleaner thread since
2957 * we're covered by the delete_unused_bgs_mutex.
2959 btrfs_add_raid_kobjects(fs_info);
2961 trans = btrfs_start_trans_remove_block_group(root->fs_info,
2962 chunk_offset);
2963 if (IS_ERR(trans)) {
2964 ret = PTR_ERR(trans);
2965 btrfs_handle_fs_error(root->fs_info, ret, NULL);
2966 return ret;
2970 * step two, delete the device extents and the
2971 * chunk tree entries
2973 ret = btrfs_remove_chunk(trans, fs_info, chunk_offset);
2974 btrfs_end_transaction(trans);
2975 return ret;
2978 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
2980 struct btrfs_root *chunk_root = fs_info->chunk_root;
2981 struct btrfs_path *path;
2982 struct extent_buffer *leaf;
2983 struct btrfs_chunk *chunk;
2984 struct btrfs_key key;
2985 struct btrfs_key found_key;
2986 u64 chunk_type;
2987 bool retried = false;
2988 int failed = 0;
2989 int ret;
2991 path = btrfs_alloc_path();
2992 if (!path)
2993 return -ENOMEM;
2995 again:
2996 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2997 key.offset = (u64)-1;
2998 key.type = BTRFS_CHUNK_ITEM_KEY;
3000 while (1) {
3001 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3002 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3003 if (ret < 0) {
3004 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3005 goto error;
3007 BUG_ON(ret == 0); /* Corruption */
3009 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3010 key.type);
3011 if (ret)
3012 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3013 if (ret < 0)
3014 goto error;
3015 if (ret > 0)
3016 break;
3018 leaf = path->nodes[0];
3019 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3021 chunk = btrfs_item_ptr(leaf, path->slots[0],
3022 struct btrfs_chunk);
3023 chunk_type = btrfs_chunk_type(leaf, chunk);
3024 btrfs_release_path(path);
3026 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3027 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3028 if (ret == -ENOSPC)
3029 failed++;
3030 else
3031 BUG_ON(ret);
3033 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3035 if (found_key.offset == 0)
3036 break;
3037 key.offset = found_key.offset - 1;
3039 ret = 0;
3040 if (failed && !retried) {
3041 failed = 0;
3042 retried = true;
3043 goto again;
3044 } else if (WARN_ON(failed && retried)) {
3045 ret = -ENOSPC;
3047 error:
3048 btrfs_free_path(path);
3049 return ret;
3053 * return 1 : allocate a data chunk successfully,
3054 * return <0: errors during allocating a data chunk,
3055 * return 0 : no need to allocate a data chunk.
3057 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3058 u64 chunk_offset)
3060 struct btrfs_block_group_cache *cache;
3061 u64 bytes_used;
3062 u64 chunk_type;
3064 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3065 ASSERT(cache);
3066 chunk_type = cache->flags;
3067 btrfs_put_block_group(cache);
3069 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3070 spin_lock(&fs_info->data_sinfo->lock);
3071 bytes_used = fs_info->data_sinfo->bytes_used;
3072 spin_unlock(&fs_info->data_sinfo->lock);
3074 if (!bytes_used) {
3075 struct btrfs_trans_handle *trans;
3076 int ret;
3078 trans = btrfs_join_transaction(fs_info->tree_root);
3079 if (IS_ERR(trans))
3080 return PTR_ERR(trans);
3082 ret = btrfs_force_chunk_alloc(trans, fs_info,
3083 BTRFS_BLOCK_GROUP_DATA);
3084 btrfs_end_transaction(trans);
3085 if (ret < 0)
3086 return ret;
3088 btrfs_add_raid_kobjects(fs_info);
3090 return 1;
3093 return 0;
3096 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3097 struct btrfs_balance_control *bctl)
3099 struct btrfs_root *root = fs_info->tree_root;
3100 struct btrfs_trans_handle *trans;
3101 struct btrfs_balance_item *item;
3102 struct btrfs_disk_balance_args disk_bargs;
3103 struct btrfs_path *path;
3104 struct extent_buffer *leaf;
3105 struct btrfs_key key;
3106 int ret, err;
3108 path = btrfs_alloc_path();
3109 if (!path)
3110 return -ENOMEM;
3112 trans = btrfs_start_transaction(root, 0);
3113 if (IS_ERR(trans)) {
3114 btrfs_free_path(path);
3115 return PTR_ERR(trans);
3118 key.objectid = BTRFS_BALANCE_OBJECTID;
3119 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3120 key.offset = 0;
3122 ret = btrfs_insert_empty_item(trans, root, path, &key,
3123 sizeof(*item));
3124 if (ret)
3125 goto out;
3127 leaf = path->nodes[0];
3128 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3130 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3132 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3133 btrfs_set_balance_data(leaf, item, &disk_bargs);
3134 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3135 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3136 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3137 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3139 btrfs_set_balance_flags(leaf, item, bctl->flags);
3141 btrfs_mark_buffer_dirty(leaf);
3142 out:
3143 btrfs_free_path(path);
3144 err = btrfs_commit_transaction(trans);
3145 if (err && !ret)
3146 ret = err;
3147 return ret;
3150 static int del_balance_item(struct btrfs_fs_info *fs_info)
3152 struct btrfs_root *root = fs_info->tree_root;
3153 struct btrfs_trans_handle *trans;
3154 struct btrfs_path *path;
3155 struct btrfs_key key;
3156 int ret, err;
3158 path = btrfs_alloc_path();
3159 if (!path)
3160 return -ENOMEM;
3162 trans = btrfs_start_transaction(root, 0);
3163 if (IS_ERR(trans)) {
3164 btrfs_free_path(path);
3165 return PTR_ERR(trans);
3168 key.objectid = BTRFS_BALANCE_OBJECTID;
3169 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3170 key.offset = 0;
3172 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3173 if (ret < 0)
3174 goto out;
3175 if (ret > 0) {
3176 ret = -ENOENT;
3177 goto out;
3180 ret = btrfs_del_item(trans, root, path);
3181 out:
3182 btrfs_free_path(path);
3183 err = btrfs_commit_transaction(trans);
3184 if (err && !ret)
3185 ret = err;
3186 return ret;
3190 * This is a heuristic used to reduce the number of chunks balanced on
3191 * resume after balance was interrupted.
3193 static void update_balance_args(struct btrfs_balance_control *bctl)
3196 * Turn on soft mode for chunk types that were being converted.
3198 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3199 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3200 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3201 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3202 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3203 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3206 * Turn on usage filter if is not already used. The idea is
3207 * that chunks that we have already balanced should be
3208 * reasonably full. Don't do it for chunks that are being
3209 * converted - that will keep us from relocating unconverted
3210 * (albeit full) chunks.
3212 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3213 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3214 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3215 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3216 bctl->data.usage = 90;
3218 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3219 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3220 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3221 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3222 bctl->sys.usage = 90;
3224 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3225 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3226 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3227 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3228 bctl->meta.usage = 90;
3233 * Clear the balance status in fs_info and delete the balance item from disk.
3235 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3237 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3238 int ret;
3240 BUG_ON(!fs_info->balance_ctl);
3242 spin_lock(&fs_info->balance_lock);
3243 fs_info->balance_ctl = NULL;
3244 spin_unlock(&fs_info->balance_lock);
3246 kfree(bctl);
3247 ret = del_balance_item(fs_info);
3248 if (ret)
3249 btrfs_handle_fs_error(fs_info, ret, NULL);
3253 * Balance filters. Return 1 if chunk should be filtered out
3254 * (should not be balanced).
3256 static int chunk_profiles_filter(u64 chunk_type,
3257 struct btrfs_balance_args *bargs)
3259 chunk_type = chunk_to_extended(chunk_type) &
3260 BTRFS_EXTENDED_PROFILE_MASK;
3262 if (bargs->profiles & chunk_type)
3263 return 0;
3265 return 1;
3268 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3269 struct btrfs_balance_args *bargs)
3271 struct btrfs_block_group_cache *cache;
3272 u64 chunk_used;
3273 u64 user_thresh_min;
3274 u64 user_thresh_max;
3275 int ret = 1;
3277 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3278 chunk_used = btrfs_block_group_used(&cache->item);
3280 if (bargs->usage_min == 0)
3281 user_thresh_min = 0;
3282 else
3283 user_thresh_min = div_factor_fine(cache->key.offset,
3284 bargs->usage_min);
3286 if (bargs->usage_max == 0)
3287 user_thresh_max = 1;
3288 else if (bargs->usage_max > 100)
3289 user_thresh_max = cache->key.offset;
3290 else
3291 user_thresh_max = div_factor_fine(cache->key.offset,
3292 bargs->usage_max);
3294 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3295 ret = 0;
3297 btrfs_put_block_group(cache);
3298 return ret;
3301 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3302 u64 chunk_offset, struct btrfs_balance_args *bargs)
3304 struct btrfs_block_group_cache *cache;
3305 u64 chunk_used, user_thresh;
3306 int ret = 1;
3308 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3309 chunk_used = btrfs_block_group_used(&cache->item);
3311 if (bargs->usage_min == 0)
3312 user_thresh = 1;
3313 else if (bargs->usage > 100)
3314 user_thresh = cache->key.offset;
3315 else
3316 user_thresh = div_factor_fine(cache->key.offset,
3317 bargs->usage);
3319 if (chunk_used < user_thresh)
3320 ret = 0;
3322 btrfs_put_block_group(cache);
3323 return ret;
3326 static int chunk_devid_filter(struct extent_buffer *leaf,
3327 struct btrfs_chunk *chunk,
3328 struct btrfs_balance_args *bargs)
3330 struct btrfs_stripe *stripe;
3331 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3332 int i;
3334 for (i = 0; i < num_stripes; i++) {
3335 stripe = btrfs_stripe_nr(chunk, i);
3336 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3337 return 0;
3340 return 1;
3343 /* [pstart, pend) */
3344 static int chunk_drange_filter(struct extent_buffer *leaf,
3345 struct btrfs_chunk *chunk,
3346 struct btrfs_balance_args *bargs)
3348 struct btrfs_stripe *stripe;
3349 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3350 u64 stripe_offset;
3351 u64 stripe_length;
3352 int factor;
3353 int i;
3355 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3356 return 0;
3358 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3359 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3360 factor = num_stripes / 2;
3361 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3362 factor = num_stripes - 1;
3363 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3364 factor = num_stripes - 2;
3365 } else {
3366 factor = num_stripes;
3369 for (i = 0; i < num_stripes; i++) {
3370 stripe = btrfs_stripe_nr(chunk, i);
3371 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3372 continue;
3374 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3375 stripe_length = btrfs_chunk_length(leaf, chunk);
3376 stripe_length = div_u64(stripe_length, factor);
3378 if (stripe_offset < bargs->pend &&
3379 stripe_offset + stripe_length > bargs->pstart)
3380 return 0;
3383 return 1;
3386 /* [vstart, vend) */
3387 static int chunk_vrange_filter(struct extent_buffer *leaf,
3388 struct btrfs_chunk *chunk,
3389 u64 chunk_offset,
3390 struct btrfs_balance_args *bargs)
3392 if (chunk_offset < bargs->vend &&
3393 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3394 /* at least part of the chunk is inside this vrange */
3395 return 0;
3397 return 1;
3400 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3401 struct btrfs_chunk *chunk,
3402 struct btrfs_balance_args *bargs)
3404 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3406 if (bargs->stripes_min <= num_stripes
3407 && num_stripes <= bargs->stripes_max)
3408 return 0;
3410 return 1;
3413 static int chunk_soft_convert_filter(u64 chunk_type,
3414 struct btrfs_balance_args *bargs)
3416 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3417 return 0;
3419 chunk_type = chunk_to_extended(chunk_type) &
3420 BTRFS_EXTENDED_PROFILE_MASK;
3422 if (bargs->target == chunk_type)
3423 return 1;
3425 return 0;
3428 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3429 struct extent_buffer *leaf,
3430 struct btrfs_chunk *chunk, u64 chunk_offset)
3432 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3433 struct btrfs_balance_args *bargs = NULL;
3434 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3436 /* type filter */
3437 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3438 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3439 return 0;
3442 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3443 bargs = &bctl->data;
3444 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3445 bargs = &bctl->sys;
3446 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3447 bargs = &bctl->meta;
3449 /* profiles filter */
3450 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3451 chunk_profiles_filter(chunk_type, bargs)) {
3452 return 0;
3455 /* usage filter */
3456 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3457 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3458 return 0;
3459 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3460 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3461 return 0;
3464 /* devid filter */
3465 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3466 chunk_devid_filter(leaf, chunk, bargs)) {
3467 return 0;
3470 /* drange filter, makes sense only with devid filter */
3471 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3472 chunk_drange_filter(leaf, chunk, bargs)) {
3473 return 0;
3476 /* vrange filter */
3477 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3478 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3479 return 0;
3482 /* stripes filter */
3483 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3484 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3485 return 0;
3488 /* soft profile changing mode */
3489 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3490 chunk_soft_convert_filter(chunk_type, bargs)) {
3491 return 0;
3495 * limited by count, must be the last filter
3497 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3498 if (bargs->limit == 0)
3499 return 0;
3500 else
3501 bargs->limit--;
3502 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3504 * Same logic as the 'limit' filter; the minimum cannot be
3505 * determined here because we do not have the global information
3506 * about the count of all chunks that satisfy the filters.
3508 if (bargs->limit_max == 0)
3509 return 0;
3510 else
3511 bargs->limit_max--;
3514 return 1;
3517 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3519 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3520 struct btrfs_root *chunk_root = fs_info->chunk_root;
3521 struct btrfs_root *dev_root = fs_info->dev_root;
3522 struct list_head *devices;
3523 struct btrfs_device *device;
3524 u64 old_size;
3525 u64 size_to_free;
3526 u64 chunk_type;
3527 struct btrfs_chunk *chunk;
3528 struct btrfs_path *path = NULL;
3529 struct btrfs_key key;
3530 struct btrfs_key found_key;
3531 struct btrfs_trans_handle *trans;
3532 struct extent_buffer *leaf;
3533 int slot;
3534 int ret;
3535 int enospc_errors = 0;
3536 bool counting = true;
3537 /* The single value limit and min/max limits use the same bytes in the */
3538 u64 limit_data = bctl->data.limit;
3539 u64 limit_meta = bctl->meta.limit;
3540 u64 limit_sys = bctl->sys.limit;
3541 u32 count_data = 0;
3542 u32 count_meta = 0;
3543 u32 count_sys = 0;
3544 int chunk_reserved = 0;
3546 /* step one make some room on all the devices */
3547 devices = &fs_info->fs_devices->devices;
3548 list_for_each_entry(device, devices, dev_list) {
3549 old_size = btrfs_device_get_total_bytes(device);
3550 size_to_free = div_factor(old_size, 1);
3551 size_to_free = min_t(u64, size_to_free, SZ_1M);
3552 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
3553 btrfs_device_get_total_bytes(device) -
3554 btrfs_device_get_bytes_used(device) > size_to_free ||
3555 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
3556 continue;
3558 ret = btrfs_shrink_device(device, old_size - size_to_free);
3559 if (ret == -ENOSPC)
3560 break;
3561 if (ret) {
3562 /* btrfs_shrink_device never returns ret > 0 */
3563 WARN_ON(ret > 0);
3564 goto error;
3567 trans = btrfs_start_transaction(dev_root, 0);
3568 if (IS_ERR(trans)) {
3569 ret = PTR_ERR(trans);
3570 btrfs_info_in_rcu(fs_info,
3571 "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3572 rcu_str_deref(device->name), ret,
3573 old_size, old_size - size_to_free);
3574 goto error;
3577 ret = btrfs_grow_device(trans, device, old_size);
3578 if (ret) {
3579 btrfs_end_transaction(trans);
3580 /* btrfs_grow_device never returns ret > 0 */
3581 WARN_ON(ret > 0);
3582 btrfs_info_in_rcu(fs_info,
3583 "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3584 rcu_str_deref(device->name), ret,
3585 old_size, old_size - size_to_free);
3586 goto error;
3589 btrfs_end_transaction(trans);
3592 /* step two, relocate all the chunks */
3593 path = btrfs_alloc_path();
3594 if (!path) {
3595 ret = -ENOMEM;
3596 goto error;
3599 /* zero out stat counters */
3600 spin_lock(&fs_info->balance_lock);
3601 memset(&bctl->stat, 0, sizeof(bctl->stat));
3602 spin_unlock(&fs_info->balance_lock);
3603 again:
3604 if (!counting) {
3606 * The single value limit and min/max limits use the same bytes
3607 * in the
3609 bctl->data.limit = limit_data;
3610 bctl->meta.limit = limit_meta;
3611 bctl->sys.limit = limit_sys;
3613 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3614 key.offset = (u64)-1;
3615 key.type = BTRFS_CHUNK_ITEM_KEY;
3617 while (1) {
3618 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3619 atomic_read(&fs_info->balance_cancel_req)) {
3620 ret = -ECANCELED;
3621 goto error;
3624 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3625 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3626 if (ret < 0) {
3627 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3628 goto error;
3632 * this shouldn't happen, it means the last relocate
3633 * failed
3635 if (ret == 0)
3636 BUG(); /* FIXME break ? */
3638 ret = btrfs_previous_item(chunk_root, path, 0,
3639 BTRFS_CHUNK_ITEM_KEY);
3640 if (ret) {
3641 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3642 ret = 0;
3643 break;
3646 leaf = path->nodes[0];
3647 slot = path->slots[0];
3648 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3650 if (found_key.objectid != key.objectid) {
3651 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3652 break;
3655 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3656 chunk_type = btrfs_chunk_type(leaf, chunk);
3658 if (!counting) {
3659 spin_lock(&fs_info->balance_lock);
3660 bctl->stat.considered++;
3661 spin_unlock(&fs_info->balance_lock);
3664 ret = should_balance_chunk(fs_info, leaf, chunk,
3665 found_key.offset);
3667 btrfs_release_path(path);
3668 if (!ret) {
3669 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3670 goto loop;
3673 if (counting) {
3674 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3675 spin_lock(&fs_info->balance_lock);
3676 bctl->stat.expected++;
3677 spin_unlock(&fs_info->balance_lock);
3679 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3680 count_data++;
3681 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3682 count_sys++;
3683 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3684 count_meta++;
3686 goto loop;
3690 * Apply limit_min filter, no need to check if the LIMITS
3691 * filter is used, limit_min is 0 by default
3693 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3694 count_data < bctl->data.limit_min)
3695 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3696 count_meta < bctl->meta.limit_min)
3697 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3698 count_sys < bctl->sys.limit_min)) {
3699 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3700 goto loop;
3703 if (!chunk_reserved) {
3705 * We may be relocating the only data chunk we have,
3706 * which could potentially end up with losing data's
3707 * raid profile, so lets allocate an empty one in
3708 * advance.
3710 ret = btrfs_may_alloc_data_chunk(fs_info,
3711 found_key.offset);
3712 if (ret < 0) {
3713 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3714 goto error;
3715 } else if (ret == 1) {
3716 chunk_reserved = 1;
3720 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3721 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3722 if (ret && ret != -ENOSPC)
3723 goto error;
3724 if (ret == -ENOSPC) {
3725 enospc_errors++;
3726 } else {
3727 spin_lock(&fs_info->balance_lock);
3728 bctl->stat.completed++;
3729 spin_unlock(&fs_info->balance_lock);
3731 loop:
3732 if (found_key.offset == 0)
3733 break;
3734 key.offset = found_key.offset - 1;
3737 if (counting) {
3738 btrfs_release_path(path);
3739 counting = false;
3740 goto again;
3742 error:
3743 btrfs_free_path(path);
3744 if (enospc_errors) {
3745 btrfs_info(fs_info, "%d enospc errors during balance",
3746 enospc_errors);
3747 if (!ret)
3748 ret = -ENOSPC;
3751 return ret;
3755 * alloc_profile_is_valid - see if a given profile is valid and reduced
3756 * @flags: profile to validate
3757 * @extended: if true @flags is treated as an extended profile
3759 static int alloc_profile_is_valid(u64 flags, int extended)
3761 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3762 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3764 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3766 /* 1) check that all other bits are zeroed */
3767 if (flags & ~mask)
3768 return 0;
3770 /* 2) see if profile is reduced */
3771 if (flags == 0)
3772 return !extended; /* "0" is valid for usual profiles */
3774 /* true if exactly one bit set */
3775 return (flags & (flags - 1)) == 0;
3778 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3780 /* cancel requested || normal exit path */
3781 return atomic_read(&fs_info->balance_cancel_req) ||
3782 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3783 atomic_read(&fs_info->balance_cancel_req) == 0);
3786 /* Non-zero return value signifies invalidity */
3787 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3788 u64 allowed)
3790 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3791 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3792 (bctl_arg->target & ~allowed)));
3796 * Should be called with balance mutexe held
3798 int btrfs_balance(struct btrfs_fs_info *fs_info,
3799 struct btrfs_balance_control *bctl,
3800 struct btrfs_ioctl_balance_args *bargs)
3802 u64 meta_target, data_target;
3803 u64 allowed;
3804 int mixed = 0;
3805 int ret;
3806 u64 num_devices;
3807 unsigned seq;
3809 if (btrfs_fs_closing(fs_info) ||
3810 atomic_read(&fs_info->balance_pause_req) ||
3811 atomic_read(&fs_info->balance_cancel_req)) {
3812 ret = -EINVAL;
3813 goto out;
3816 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3817 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3818 mixed = 1;
3821 * In case of mixed groups both data and meta should be picked,
3822 * and identical options should be given for both of them.
3824 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3825 if (mixed && (bctl->flags & allowed)) {
3826 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3827 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3828 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3829 btrfs_err(fs_info,
3830 "balance: mixed groups data and metadata options must be the same");
3831 ret = -EINVAL;
3832 goto out;
3836 num_devices = fs_info->fs_devices->num_devices;
3837 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
3838 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3839 BUG_ON(num_devices < 1);
3840 num_devices--;
3842 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
3843 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3844 if (num_devices > 1)
3845 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3846 if (num_devices > 2)
3847 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3848 if (num_devices > 3)
3849 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3850 BTRFS_BLOCK_GROUP_RAID6);
3851 if (validate_convert_profile(&bctl->data, allowed)) {
3852 int index = btrfs_bg_flags_to_raid_index(bctl->data.target);
3854 btrfs_err(fs_info,
3855 "balance: invalid convert data profile %s",
3856 get_raid_name(index));
3857 ret = -EINVAL;
3858 goto out;
3860 if (validate_convert_profile(&bctl->meta, allowed)) {
3861 int index = btrfs_bg_flags_to_raid_index(bctl->meta.target);
3863 btrfs_err(fs_info,
3864 "balance: invalid convert metadata profile %s",
3865 get_raid_name(index));
3866 ret = -EINVAL;
3867 goto out;
3869 if (validate_convert_profile(&bctl->sys, allowed)) {
3870 int index = btrfs_bg_flags_to_raid_index(bctl->sys.target);
3872 btrfs_err(fs_info,
3873 "balance: invalid convert system profile %s",
3874 get_raid_name(index));
3875 ret = -EINVAL;
3876 goto out;
3879 /* allow to reduce meta or sys integrity only if force set */
3880 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3881 BTRFS_BLOCK_GROUP_RAID10 |
3882 BTRFS_BLOCK_GROUP_RAID5 |
3883 BTRFS_BLOCK_GROUP_RAID6;
3884 do {
3885 seq = read_seqbegin(&fs_info->profiles_lock);
3887 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3888 (fs_info->avail_system_alloc_bits & allowed) &&
3889 !(bctl->sys.target & allowed)) ||
3890 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3891 (fs_info->avail_metadata_alloc_bits & allowed) &&
3892 !(bctl->meta.target & allowed))) {
3893 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3894 btrfs_info(fs_info,
3895 "balance: force reducing metadata integrity");
3896 } else {
3897 btrfs_err(fs_info,
3898 "balance: reduces metadata integrity, use --force if you want this");
3899 ret = -EINVAL;
3900 goto out;
3903 } while (read_seqretry(&fs_info->profiles_lock, seq));
3905 /* if we're not converting, the target field is uninitialized */
3906 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3907 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
3908 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3909 bctl->data.target : fs_info->avail_data_alloc_bits;
3910 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
3911 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
3912 int meta_index = btrfs_bg_flags_to_raid_index(meta_target);
3913 int data_index = btrfs_bg_flags_to_raid_index(data_target);
3915 btrfs_warn(fs_info,
3916 "balance: metadata profile %s has lower redundancy than data profile %s",
3917 get_raid_name(meta_index), get_raid_name(data_index));
3920 ret = insert_balance_item(fs_info, bctl);
3921 if (ret && ret != -EEXIST)
3922 goto out;
3924 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3925 BUG_ON(ret == -EEXIST);
3926 BUG_ON(fs_info->balance_ctl);
3927 spin_lock(&fs_info->balance_lock);
3928 fs_info->balance_ctl = bctl;
3929 spin_unlock(&fs_info->balance_lock);
3930 } else {
3931 BUG_ON(ret != -EEXIST);
3932 spin_lock(&fs_info->balance_lock);
3933 update_balance_args(bctl);
3934 spin_unlock(&fs_info->balance_lock);
3937 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
3938 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
3939 mutex_unlock(&fs_info->balance_mutex);
3941 ret = __btrfs_balance(fs_info);
3943 mutex_lock(&fs_info->balance_mutex);
3944 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
3946 if (bargs) {
3947 memset(bargs, 0, sizeof(*bargs));
3948 btrfs_update_ioctl_balance_args(fs_info, bargs);
3951 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3952 balance_need_close(fs_info)) {
3953 reset_balance_state(fs_info);
3954 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3957 wake_up(&fs_info->balance_wait_q);
3959 return ret;
3960 out:
3961 if (bctl->flags & BTRFS_BALANCE_RESUME)
3962 reset_balance_state(fs_info);
3963 else
3964 kfree(bctl);
3965 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3967 return ret;
3970 static int balance_kthread(void *data)
3972 struct btrfs_fs_info *fs_info = data;
3973 int ret = 0;
3975 mutex_lock(&fs_info->balance_mutex);
3976 if (fs_info->balance_ctl) {
3977 btrfs_info(fs_info, "balance: resuming");
3978 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
3980 mutex_unlock(&fs_info->balance_mutex);
3982 return ret;
3985 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3987 struct task_struct *tsk;
3989 mutex_lock(&fs_info->balance_mutex);
3990 if (!fs_info->balance_ctl) {
3991 mutex_unlock(&fs_info->balance_mutex);
3992 return 0;
3994 mutex_unlock(&fs_info->balance_mutex);
3996 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
3997 btrfs_info(fs_info, "balance: resume skipped");
3998 return 0;
4002 * A ro->rw remount sequence should continue with the paused balance
4003 * regardless of who pauses it, system or the user as of now, so set
4004 * the resume flag.
4006 spin_lock(&fs_info->balance_lock);
4007 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4008 spin_unlock(&fs_info->balance_lock);
4010 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4011 return PTR_ERR_OR_ZERO(tsk);
4014 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4016 struct btrfs_balance_control *bctl;
4017 struct btrfs_balance_item *item;
4018 struct btrfs_disk_balance_args disk_bargs;
4019 struct btrfs_path *path;
4020 struct extent_buffer *leaf;
4021 struct btrfs_key key;
4022 int ret;
4024 path = btrfs_alloc_path();
4025 if (!path)
4026 return -ENOMEM;
4028 key.objectid = BTRFS_BALANCE_OBJECTID;
4029 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4030 key.offset = 0;
4032 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4033 if (ret < 0)
4034 goto out;
4035 if (ret > 0) { /* ret = -ENOENT; */
4036 ret = 0;
4037 goto out;
4040 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4041 if (!bctl) {
4042 ret = -ENOMEM;
4043 goto out;
4046 leaf = path->nodes[0];
4047 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4049 bctl->flags = btrfs_balance_flags(leaf, item);
4050 bctl->flags |= BTRFS_BALANCE_RESUME;
4052 btrfs_balance_data(leaf, item, &disk_bargs);
4053 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4054 btrfs_balance_meta(leaf, item, &disk_bargs);
4055 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4056 btrfs_balance_sys(leaf, item, &disk_bargs);
4057 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4060 * This should never happen, as the paused balance state is recovered
4061 * during mount without any chance of other exclusive ops to collide.
4063 * This gives the exclusive op status to balance and keeps in paused
4064 * state until user intervention (cancel or umount). If the ownership
4065 * cannot be assigned, show a message but do not fail. The balance
4066 * is in a paused state and must have fs_info::balance_ctl properly
4067 * set up.
4069 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
4070 btrfs_warn(fs_info,
4071 "balance: cannot set exclusive op status, resume manually");
4073 mutex_lock(&fs_info->balance_mutex);
4074 BUG_ON(fs_info->balance_ctl);
4075 spin_lock(&fs_info->balance_lock);
4076 fs_info->balance_ctl = bctl;
4077 spin_unlock(&fs_info->balance_lock);
4078 mutex_unlock(&fs_info->balance_mutex);
4079 out:
4080 btrfs_free_path(path);
4081 return ret;
4084 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4086 int ret = 0;
4088 mutex_lock(&fs_info->balance_mutex);
4089 if (!fs_info->balance_ctl) {
4090 mutex_unlock(&fs_info->balance_mutex);
4091 return -ENOTCONN;
4094 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4095 atomic_inc(&fs_info->balance_pause_req);
4096 mutex_unlock(&fs_info->balance_mutex);
4098 wait_event(fs_info->balance_wait_q,
4099 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4101 mutex_lock(&fs_info->balance_mutex);
4102 /* we are good with balance_ctl ripped off from under us */
4103 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4104 atomic_dec(&fs_info->balance_pause_req);
4105 } else {
4106 ret = -ENOTCONN;
4109 mutex_unlock(&fs_info->balance_mutex);
4110 return ret;
4113 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4115 mutex_lock(&fs_info->balance_mutex);
4116 if (!fs_info->balance_ctl) {
4117 mutex_unlock(&fs_info->balance_mutex);
4118 return -ENOTCONN;
4122 * A paused balance with the item stored on disk can be resumed at
4123 * mount time if the mount is read-write. Otherwise it's still paused
4124 * and we must not allow cancelling as it deletes the item.
4126 if (sb_rdonly(fs_info->sb)) {
4127 mutex_unlock(&fs_info->balance_mutex);
4128 return -EROFS;
4131 atomic_inc(&fs_info->balance_cancel_req);
4133 * if we are running just wait and return, balance item is
4134 * deleted in btrfs_balance in this case
4136 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4137 mutex_unlock(&fs_info->balance_mutex);
4138 wait_event(fs_info->balance_wait_q,
4139 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4140 mutex_lock(&fs_info->balance_mutex);
4141 } else {
4142 mutex_unlock(&fs_info->balance_mutex);
4144 * Lock released to allow other waiters to continue, we'll
4145 * reexamine the status again.
4147 mutex_lock(&fs_info->balance_mutex);
4149 if (fs_info->balance_ctl) {
4150 reset_balance_state(fs_info);
4151 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4152 btrfs_info(fs_info, "balance: canceled");
4156 BUG_ON(fs_info->balance_ctl ||
4157 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4158 atomic_dec(&fs_info->balance_cancel_req);
4159 mutex_unlock(&fs_info->balance_mutex);
4160 return 0;
4163 static int btrfs_uuid_scan_kthread(void *data)
4165 struct btrfs_fs_info *fs_info = data;
4166 struct btrfs_root *root = fs_info->tree_root;
4167 struct btrfs_key key;
4168 struct btrfs_path *path = NULL;
4169 int ret = 0;
4170 struct extent_buffer *eb;
4171 int slot;
4172 struct btrfs_root_item root_item;
4173 u32 item_size;
4174 struct btrfs_trans_handle *trans = NULL;
4176 path = btrfs_alloc_path();
4177 if (!path) {
4178 ret = -ENOMEM;
4179 goto out;
4182 key.objectid = 0;
4183 key.type = BTRFS_ROOT_ITEM_KEY;
4184 key.offset = 0;
4186 while (1) {
4187 ret = btrfs_search_forward(root, &key, path,
4188 BTRFS_OLDEST_GENERATION);
4189 if (ret) {
4190 if (ret > 0)
4191 ret = 0;
4192 break;
4195 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4196 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4197 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4198 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4199 goto skip;
4201 eb = path->nodes[0];
4202 slot = path->slots[0];
4203 item_size = btrfs_item_size_nr(eb, slot);
4204 if (item_size < sizeof(root_item))
4205 goto skip;
4207 read_extent_buffer(eb, &root_item,
4208 btrfs_item_ptr_offset(eb, slot),
4209 (int)sizeof(root_item));
4210 if (btrfs_root_refs(&root_item) == 0)
4211 goto skip;
4213 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4214 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4215 if (trans)
4216 goto update_tree;
4218 btrfs_release_path(path);
4220 * 1 - subvol uuid item
4221 * 1 - received_subvol uuid item
4223 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4224 if (IS_ERR(trans)) {
4225 ret = PTR_ERR(trans);
4226 break;
4228 continue;
4229 } else {
4230 goto skip;
4232 update_tree:
4233 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4234 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4235 BTRFS_UUID_KEY_SUBVOL,
4236 key.objectid);
4237 if (ret < 0) {
4238 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4239 ret);
4240 break;
4244 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4245 ret = btrfs_uuid_tree_add(trans,
4246 root_item.received_uuid,
4247 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4248 key.objectid);
4249 if (ret < 0) {
4250 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4251 ret);
4252 break;
4256 skip:
4257 if (trans) {
4258 ret = btrfs_end_transaction(trans);
4259 trans = NULL;
4260 if (ret)
4261 break;
4264 btrfs_release_path(path);
4265 if (key.offset < (u64)-1) {
4266 key.offset++;
4267 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4268 key.offset = 0;
4269 key.type = BTRFS_ROOT_ITEM_KEY;
4270 } else if (key.objectid < (u64)-1) {
4271 key.offset = 0;
4272 key.type = BTRFS_ROOT_ITEM_KEY;
4273 key.objectid++;
4274 } else {
4275 break;
4277 cond_resched();
4280 out:
4281 btrfs_free_path(path);
4282 if (trans && !IS_ERR(trans))
4283 btrfs_end_transaction(trans);
4284 if (ret)
4285 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4286 else
4287 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4288 up(&fs_info->uuid_tree_rescan_sem);
4289 return 0;
4293 * Callback for btrfs_uuid_tree_iterate().
4294 * returns:
4295 * 0 check succeeded, the entry is not outdated.
4296 * < 0 if an error occurred.
4297 * > 0 if the check failed, which means the caller shall remove the entry.
4299 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4300 u8 *uuid, u8 type, u64 subid)
4302 struct btrfs_key key;
4303 int ret = 0;
4304 struct btrfs_root *subvol_root;
4306 if (type != BTRFS_UUID_KEY_SUBVOL &&
4307 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4308 goto out;
4310 key.objectid = subid;
4311 key.type = BTRFS_ROOT_ITEM_KEY;
4312 key.offset = (u64)-1;
4313 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4314 if (IS_ERR(subvol_root)) {
4315 ret = PTR_ERR(subvol_root);
4316 if (ret == -ENOENT)
4317 ret = 1;
4318 goto out;
4321 switch (type) {
4322 case BTRFS_UUID_KEY_SUBVOL:
4323 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4324 ret = 1;
4325 break;
4326 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4327 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4328 BTRFS_UUID_SIZE))
4329 ret = 1;
4330 break;
4333 out:
4334 return ret;
4337 static int btrfs_uuid_rescan_kthread(void *data)
4339 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4340 int ret;
4343 * 1st step is to iterate through the existing UUID tree and
4344 * to delete all entries that contain outdated data.
4345 * 2nd step is to add all missing entries to the UUID tree.
4347 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4348 if (ret < 0) {
4349 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4350 up(&fs_info->uuid_tree_rescan_sem);
4351 return ret;
4353 return btrfs_uuid_scan_kthread(data);
4356 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4358 struct btrfs_trans_handle *trans;
4359 struct btrfs_root *tree_root = fs_info->tree_root;
4360 struct btrfs_root *uuid_root;
4361 struct task_struct *task;
4362 int ret;
4365 * 1 - root node
4366 * 1 - root item
4368 trans = btrfs_start_transaction(tree_root, 2);
4369 if (IS_ERR(trans))
4370 return PTR_ERR(trans);
4372 uuid_root = btrfs_create_tree(trans, fs_info,
4373 BTRFS_UUID_TREE_OBJECTID);
4374 if (IS_ERR(uuid_root)) {
4375 ret = PTR_ERR(uuid_root);
4376 btrfs_abort_transaction(trans, ret);
4377 btrfs_end_transaction(trans);
4378 return ret;
4381 fs_info->uuid_root = uuid_root;
4383 ret = btrfs_commit_transaction(trans);
4384 if (ret)
4385 return ret;
4387 down(&fs_info->uuid_tree_rescan_sem);
4388 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4389 if (IS_ERR(task)) {
4390 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4391 btrfs_warn(fs_info, "failed to start uuid_scan task");
4392 up(&fs_info->uuid_tree_rescan_sem);
4393 return PTR_ERR(task);
4396 return 0;
4399 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4401 struct task_struct *task;
4403 down(&fs_info->uuid_tree_rescan_sem);
4404 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4405 if (IS_ERR(task)) {
4406 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4407 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4408 up(&fs_info->uuid_tree_rescan_sem);
4409 return PTR_ERR(task);
4412 return 0;
4416 * shrinking a device means finding all of the device extents past
4417 * the new size, and then following the back refs to the chunks.
4418 * The chunk relocation code actually frees the device extent
4420 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4422 struct btrfs_fs_info *fs_info = device->fs_info;
4423 struct btrfs_root *root = fs_info->dev_root;
4424 struct btrfs_trans_handle *trans;
4425 struct btrfs_dev_extent *dev_extent = NULL;
4426 struct btrfs_path *path;
4427 u64 length;
4428 u64 chunk_offset;
4429 int ret;
4430 int slot;
4431 int failed = 0;
4432 bool retried = false;
4433 bool checked_pending_chunks = false;
4434 struct extent_buffer *l;
4435 struct btrfs_key key;
4436 struct btrfs_super_block *super_copy = fs_info->super_copy;
4437 u64 old_total = btrfs_super_total_bytes(super_copy);
4438 u64 old_size = btrfs_device_get_total_bytes(device);
4439 u64 diff;
4441 new_size = round_down(new_size, fs_info->sectorsize);
4442 diff = round_down(old_size - new_size, fs_info->sectorsize);
4444 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4445 return -EINVAL;
4447 path = btrfs_alloc_path();
4448 if (!path)
4449 return -ENOMEM;
4451 path->reada = READA_BACK;
4453 mutex_lock(&fs_info->chunk_mutex);
4455 btrfs_device_set_total_bytes(device, new_size);
4456 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4457 device->fs_devices->total_rw_bytes -= diff;
4458 atomic64_sub(diff, &fs_info->free_chunk_space);
4460 mutex_unlock(&fs_info->chunk_mutex);
4462 again:
4463 key.objectid = device->devid;
4464 key.offset = (u64)-1;
4465 key.type = BTRFS_DEV_EXTENT_KEY;
4467 do {
4468 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4469 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4470 if (ret < 0) {
4471 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4472 goto done;
4475 ret = btrfs_previous_item(root, path, 0, key.type);
4476 if (ret)
4477 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4478 if (ret < 0)
4479 goto done;
4480 if (ret) {
4481 ret = 0;
4482 btrfs_release_path(path);
4483 break;
4486 l = path->nodes[0];
4487 slot = path->slots[0];
4488 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4490 if (key.objectid != device->devid) {
4491 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4492 btrfs_release_path(path);
4493 break;
4496 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4497 length = btrfs_dev_extent_length(l, dev_extent);
4499 if (key.offset + length <= new_size) {
4500 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4501 btrfs_release_path(path);
4502 break;
4505 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4506 btrfs_release_path(path);
4509 * We may be relocating the only data chunk we have,
4510 * which could potentially end up with losing data's
4511 * raid profile, so lets allocate an empty one in
4512 * advance.
4514 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4515 if (ret < 0) {
4516 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4517 goto done;
4520 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4521 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4522 if (ret && ret != -ENOSPC)
4523 goto done;
4524 if (ret == -ENOSPC)
4525 failed++;
4526 } while (key.offset-- > 0);
4528 if (failed && !retried) {
4529 failed = 0;
4530 retried = true;
4531 goto again;
4532 } else if (failed && retried) {
4533 ret = -ENOSPC;
4534 goto done;
4537 /* Shrinking succeeded, else we would be at "done". */
4538 trans = btrfs_start_transaction(root, 0);
4539 if (IS_ERR(trans)) {
4540 ret = PTR_ERR(trans);
4541 goto done;
4544 mutex_lock(&fs_info->chunk_mutex);
4547 * We checked in the above loop all device extents that were already in
4548 * the device tree. However before we have updated the device's
4549 * total_bytes to the new size, we might have had chunk allocations that
4550 * have not complete yet (new block groups attached to transaction
4551 * handles), and therefore their device extents were not yet in the
4552 * device tree and we missed them in the loop above. So if we have any
4553 * pending chunk using a device extent that overlaps the device range
4554 * that we can not use anymore, commit the current transaction and
4555 * repeat the search on the device tree - this way we guarantee we will
4556 * not have chunks using device extents that end beyond 'new_size'.
4558 if (!checked_pending_chunks) {
4559 u64 start = new_size;
4560 u64 len = old_size - new_size;
4562 if (contains_pending_extent(trans->transaction, device,
4563 &start, len)) {
4564 mutex_unlock(&fs_info->chunk_mutex);
4565 checked_pending_chunks = true;
4566 failed = 0;
4567 retried = false;
4568 ret = btrfs_commit_transaction(trans);
4569 if (ret)
4570 goto done;
4571 goto again;
4575 btrfs_device_set_disk_total_bytes(device, new_size);
4576 if (list_empty(&device->resized_list))
4577 list_add_tail(&device->resized_list,
4578 &fs_info->fs_devices->resized_devices);
4580 WARN_ON(diff > old_total);
4581 btrfs_set_super_total_bytes(super_copy,
4582 round_down(old_total - diff, fs_info->sectorsize));
4583 mutex_unlock(&fs_info->chunk_mutex);
4585 /* Now btrfs_update_device() will change the on-disk size. */
4586 ret = btrfs_update_device(trans, device);
4587 btrfs_end_transaction(trans);
4588 done:
4589 btrfs_free_path(path);
4590 if (ret) {
4591 mutex_lock(&fs_info->chunk_mutex);
4592 btrfs_device_set_total_bytes(device, old_size);
4593 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4594 device->fs_devices->total_rw_bytes += diff;
4595 atomic64_add(diff, &fs_info->free_chunk_space);
4596 mutex_unlock(&fs_info->chunk_mutex);
4598 return ret;
4601 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4602 struct btrfs_key *key,
4603 struct btrfs_chunk *chunk, int item_size)
4605 struct btrfs_super_block *super_copy = fs_info->super_copy;
4606 struct btrfs_disk_key disk_key;
4607 u32 array_size;
4608 u8 *ptr;
4610 mutex_lock(&fs_info->chunk_mutex);
4611 array_size = btrfs_super_sys_array_size(super_copy);
4612 if (array_size + item_size + sizeof(disk_key)
4613 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4614 mutex_unlock(&fs_info->chunk_mutex);
4615 return -EFBIG;
4618 ptr = super_copy->sys_chunk_array + array_size;
4619 btrfs_cpu_key_to_disk(&disk_key, key);
4620 memcpy(ptr, &disk_key, sizeof(disk_key));
4621 ptr += sizeof(disk_key);
4622 memcpy(ptr, chunk, item_size);
4623 item_size += sizeof(disk_key);
4624 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4625 mutex_unlock(&fs_info->chunk_mutex);
4627 return 0;
4631 * sort the devices in descending order by max_avail, total_avail
4633 static int btrfs_cmp_device_info(const void *a, const void *b)
4635 const struct btrfs_device_info *di_a = a;
4636 const struct btrfs_device_info *di_b = b;
4638 if (di_a->max_avail > di_b->max_avail)
4639 return -1;
4640 if (di_a->max_avail < di_b->max_avail)
4641 return 1;
4642 if (di_a->total_avail > di_b->total_avail)
4643 return -1;
4644 if (di_a->total_avail < di_b->total_avail)
4645 return 1;
4646 return 0;
4649 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4651 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4652 return;
4654 btrfs_set_fs_incompat(info, RAID56);
4657 #define BTRFS_MAX_DEVS(info) ((BTRFS_MAX_ITEM_SIZE(info) \
4658 - sizeof(struct btrfs_chunk)) \
4659 / sizeof(struct btrfs_stripe) + 1)
4661 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4662 - 2 * sizeof(struct btrfs_disk_key) \
4663 - 2 * sizeof(struct btrfs_chunk)) \
4664 / sizeof(struct btrfs_stripe) + 1)
4666 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4667 u64 start, u64 type)
4669 struct btrfs_fs_info *info = trans->fs_info;
4670 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4671 struct btrfs_device *device;
4672 struct map_lookup *map = NULL;
4673 struct extent_map_tree *em_tree;
4674 struct extent_map *em;
4675 struct btrfs_device_info *devices_info = NULL;
4676 u64 total_avail;
4677 int num_stripes; /* total number of stripes to allocate */
4678 int data_stripes; /* number of stripes that count for
4679 block group size */
4680 int sub_stripes; /* sub_stripes info for map */
4681 int dev_stripes; /* stripes per dev */
4682 int devs_max; /* max devs to use */
4683 int devs_min; /* min devs needed */
4684 int devs_increment; /* ndevs has to be a multiple of this */
4685 int ncopies; /* how many copies to data has */
4686 int ret;
4687 u64 max_stripe_size;
4688 u64 max_chunk_size;
4689 u64 stripe_size;
4690 u64 num_bytes;
4691 int ndevs;
4692 int i;
4693 int j;
4694 int index;
4696 BUG_ON(!alloc_profile_is_valid(type, 0));
4698 if (list_empty(&fs_devices->alloc_list)) {
4699 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4700 btrfs_debug(info, "%s: no writable device", __func__);
4701 return -ENOSPC;
4704 index = btrfs_bg_flags_to_raid_index(type);
4706 sub_stripes = btrfs_raid_array[index].sub_stripes;
4707 dev_stripes = btrfs_raid_array[index].dev_stripes;
4708 devs_max = btrfs_raid_array[index].devs_max;
4709 devs_min = btrfs_raid_array[index].devs_min;
4710 devs_increment = btrfs_raid_array[index].devs_increment;
4711 ncopies = btrfs_raid_array[index].ncopies;
4713 if (type & BTRFS_BLOCK_GROUP_DATA) {
4714 max_stripe_size = SZ_1G;
4715 max_chunk_size = 10 * max_stripe_size;
4716 if (!devs_max)
4717 devs_max = BTRFS_MAX_DEVS(info);
4718 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4719 /* for larger filesystems, use larger metadata chunks */
4720 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4721 max_stripe_size = SZ_1G;
4722 else
4723 max_stripe_size = SZ_256M;
4724 max_chunk_size = max_stripe_size;
4725 if (!devs_max)
4726 devs_max = BTRFS_MAX_DEVS(info);
4727 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4728 max_stripe_size = SZ_32M;
4729 max_chunk_size = 2 * max_stripe_size;
4730 if (!devs_max)
4731 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4732 } else {
4733 btrfs_err(info, "invalid chunk type 0x%llx requested",
4734 type);
4735 BUG_ON(1);
4738 /* we don't want a chunk larger than 10% of writeable space */
4739 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4740 max_chunk_size);
4742 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4743 GFP_NOFS);
4744 if (!devices_info)
4745 return -ENOMEM;
4748 * in the first pass through the devices list, we gather information
4749 * about the available holes on each device.
4751 ndevs = 0;
4752 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4753 u64 max_avail;
4754 u64 dev_offset;
4756 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4757 WARN(1, KERN_ERR
4758 "BTRFS: read-only device in alloc_list\n");
4759 continue;
4762 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4763 &device->dev_state) ||
4764 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4765 continue;
4767 if (device->total_bytes > device->bytes_used)
4768 total_avail = device->total_bytes - device->bytes_used;
4769 else
4770 total_avail = 0;
4772 /* If there is no space on this device, skip it. */
4773 if (total_avail == 0)
4774 continue;
4776 ret = find_free_dev_extent(trans, device,
4777 max_stripe_size * dev_stripes,
4778 &dev_offset, &max_avail);
4779 if (ret && ret != -ENOSPC)
4780 goto error;
4782 if (ret == 0)
4783 max_avail = max_stripe_size * dev_stripes;
4785 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
4786 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4787 btrfs_debug(info,
4788 "%s: devid %llu has no free space, have=%llu want=%u",
4789 __func__, device->devid, max_avail,
4790 BTRFS_STRIPE_LEN * dev_stripes);
4791 continue;
4794 if (ndevs == fs_devices->rw_devices) {
4795 WARN(1, "%s: found more than %llu devices\n",
4796 __func__, fs_devices->rw_devices);
4797 break;
4799 devices_info[ndevs].dev_offset = dev_offset;
4800 devices_info[ndevs].max_avail = max_avail;
4801 devices_info[ndevs].total_avail = total_avail;
4802 devices_info[ndevs].dev = device;
4803 ++ndevs;
4807 * now sort the devices by hole size / available space
4809 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4810 btrfs_cmp_device_info, NULL);
4812 /* round down to number of usable stripes */
4813 ndevs = round_down(ndevs, devs_increment);
4815 if (ndevs < devs_min) {
4816 ret = -ENOSPC;
4817 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
4818 btrfs_debug(info,
4819 "%s: not enough devices with free space: have=%d minimum required=%d",
4820 __func__, ndevs, devs_min);
4822 goto error;
4825 ndevs = min(ndevs, devs_max);
4828 * The primary goal is to maximize the number of stripes, so use as
4829 * many devices as possible, even if the stripes are not maximum sized.
4831 * The DUP profile stores more than one stripe per device, the
4832 * max_avail is the total size so we have to adjust.
4834 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
4835 num_stripes = ndevs * dev_stripes;
4838 * this will have to be fixed for RAID1 and RAID10 over
4839 * more drives
4841 data_stripes = num_stripes / ncopies;
4843 if (type & BTRFS_BLOCK_GROUP_RAID5)
4844 data_stripes = num_stripes - 1;
4846 if (type & BTRFS_BLOCK_GROUP_RAID6)
4847 data_stripes = num_stripes - 2;
4850 * Use the number of data stripes to figure out how big this chunk
4851 * is really going to be in terms of logical address space,
4852 * and compare that answer with the max chunk size
4854 if (stripe_size * data_stripes > max_chunk_size) {
4855 stripe_size = div_u64(max_chunk_size, data_stripes);
4857 /* bump the answer up to a 16MB boundary */
4858 stripe_size = round_up(stripe_size, SZ_16M);
4861 * But don't go higher than the limits we found while searching
4862 * for free extents
4864 stripe_size = min(devices_info[ndevs - 1].max_avail,
4865 stripe_size);
4868 /* align to BTRFS_STRIPE_LEN */
4869 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
4871 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4872 if (!map) {
4873 ret = -ENOMEM;
4874 goto error;
4876 map->num_stripes = num_stripes;
4878 for (i = 0; i < ndevs; ++i) {
4879 for (j = 0; j < dev_stripes; ++j) {
4880 int s = i * dev_stripes + j;
4881 map->stripes[s].dev = devices_info[i].dev;
4882 map->stripes[s].physical = devices_info[i].dev_offset +
4883 j * stripe_size;
4886 map->stripe_len = BTRFS_STRIPE_LEN;
4887 map->io_align = BTRFS_STRIPE_LEN;
4888 map->io_width = BTRFS_STRIPE_LEN;
4889 map->type = type;
4890 map->sub_stripes = sub_stripes;
4892 num_bytes = stripe_size * data_stripes;
4894 trace_btrfs_chunk_alloc(info, map, start, num_bytes);
4896 em = alloc_extent_map();
4897 if (!em) {
4898 kfree(map);
4899 ret = -ENOMEM;
4900 goto error;
4902 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4903 em->map_lookup = map;
4904 em->start = start;
4905 em->len = num_bytes;
4906 em->block_start = 0;
4907 em->block_len = em->len;
4908 em->orig_block_len = stripe_size;
4910 em_tree = &info->mapping_tree.map_tree;
4911 write_lock(&em_tree->lock);
4912 ret = add_extent_mapping(em_tree, em, 0);
4913 if (ret) {
4914 write_unlock(&em_tree->lock);
4915 free_extent_map(em);
4916 goto error;
4919 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4920 refcount_inc(&em->refs);
4921 write_unlock(&em_tree->lock);
4923 ret = btrfs_make_block_group(trans, info, 0, type, start, num_bytes);
4924 if (ret)
4925 goto error_del_extent;
4927 for (i = 0; i < map->num_stripes; i++) {
4928 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4929 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4932 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
4934 free_extent_map(em);
4935 check_raid56_incompat_flag(info, type);
4937 kfree(devices_info);
4938 return 0;
4940 error_del_extent:
4941 write_lock(&em_tree->lock);
4942 remove_extent_mapping(em_tree, em);
4943 write_unlock(&em_tree->lock);
4945 /* One for our allocation */
4946 free_extent_map(em);
4947 /* One for the tree reference */
4948 free_extent_map(em);
4949 /* One for the pending_chunks list reference */
4950 free_extent_map(em);
4951 error:
4952 kfree(devices_info);
4953 return ret;
4956 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4957 struct btrfs_fs_info *fs_info,
4958 u64 chunk_offset, u64 chunk_size)
4960 struct btrfs_root *extent_root = fs_info->extent_root;
4961 struct btrfs_root *chunk_root = fs_info->chunk_root;
4962 struct btrfs_key key;
4963 struct btrfs_device *device;
4964 struct btrfs_chunk *chunk;
4965 struct btrfs_stripe *stripe;
4966 struct extent_map *em;
4967 struct map_lookup *map;
4968 size_t item_size;
4969 u64 dev_offset;
4970 u64 stripe_size;
4971 int i = 0;
4972 int ret = 0;
4974 em = get_chunk_map(fs_info, chunk_offset, chunk_size);
4975 if (IS_ERR(em))
4976 return PTR_ERR(em);
4978 map = em->map_lookup;
4979 item_size = btrfs_chunk_item_size(map->num_stripes);
4980 stripe_size = em->orig_block_len;
4982 chunk = kzalloc(item_size, GFP_NOFS);
4983 if (!chunk) {
4984 ret = -ENOMEM;
4985 goto out;
4989 * Take the device list mutex to prevent races with the final phase of
4990 * a device replace operation that replaces the device object associated
4991 * with the map's stripes, because the device object's id can change
4992 * at any time during that final phase of the device replace operation
4993 * (dev-replace.c:btrfs_dev_replace_finishing()).
4995 mutex_lock(&fs_info->fs_devices->device_list_mutex);
4996 for (i = 0; i < map->num_stripes; i++) {
4997 device = map->stripes[i].dev;
4998 dev_offset = map->stripes[i].physical;
5000 ret = btrfs_update_device(trans, device);
5001 if (ret)
5002 break;
5003 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5004 dev_offset, stripe_size);
5005 if (ret)
5006 break;
5008 if (ret) {
5009 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5010 goto out;
5013 stripe = &chunk->stripe;
5014 for (i = 0; i < map->num_stripes; i++) {
5015 device = map->stripes[i].dev;
5016 dev_offset = map->stripes[i].physical;
5018 btrfs_set_stack_stripe_devid(stripe, device->devid);
5019 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5020 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5021 stripe++;
5023 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5025 btrfs_set_stack_chunk_length(chunk, chunk_size);
5026 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5027 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5028 btrfs_set_stack_chunk_type(chunk, map->type);
5029 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5030 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5031 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5032 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5033 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5035 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5036 key.type = BTRFS_CHUNK_ITEM_KEY;
5037 key.offset = chunk_offset;
5039 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5040 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5042 * TODO: Cleanup of inserted chunk root in case of
5043 * failure.
5045 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5048 out:
5049 kfree(chunk);
5050 free_extent_map(em);
5051 return ret;
5055 * Chunk allocation falls into two parts. The first part does works
5056 * that make the new allocated chunk useable, but not do any operation
5057 * that modifies the chunk tree. The second part does the works that
5058 * require modifying the chunk tree. This division is important for the
5059 * bootstrap process of adding storage to a seed btrfs.
5061 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
5062 struct btrfs_fs_info *fs_info, u64 type)
5064 u64 chunk_offset;
5066 lockdep_assert_held(&fs_info->chunk_mutex);
5067 chunk_offset = find_next_chunk(fs_info);
5068 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5071 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5072 struct btrfs_fs_info *fs_info)
5074 u64 chunk_offset;
5075 u64 sys_chunk_offset;
5076 u64 alloc_profile;
5077 int ret;
5079 chunk_offset = find_next_chunk(fs_info);
5080 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5081 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5082 if (ret)
5083 return ret;
5085 sys_chunk_offset = find_next_chunk(fs_info);
5086 alloc_profile = btrfs_system_alloc_profile(fs_info);
5087 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5088 return ret;
5091 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5093 int max_errors;
5095 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5096 BTRFS_BLOCK_GROUP_RAID10 |
5097 BTRFS_BLOCK_GROUP_RAID5 |
5098 BTRFS_BLOCK_GROUP_DUP)) {
5099 max_errors = 1;
5100 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5101 max_errors = 2;
5102 } else {
5103 max_errors = 0;
5106 return max_errors;
5109 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5111 struct extent_map *em;
5112 struct map_lookup *map;
5113 int readonly = 0;
5114 int miss_ndevs = 0;
5115 int i;
5117 em = get_chunk_map(fs_info, chunk_offset, 1);
5118 if (IS_ERR(em))
5119 return 1;
5121 map = em->map_lookup;
5122 for (i = 0; i < map->num_stripes; i++) {
5123 if (test_bit(BTRFS_DEV_STATE_MISSING,
5124 &map->stripes[i].dev->dev_state)) {
5125 miss_ndevs++;
5126 continue;
5128 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5129 &map->stripes[i].dev->dev_state)) {
5130 readonly = 1;
5131 goto end;
5136 * If the number of missing devices is larger than max errors,
5137 * we can not write the data into that chunk successfully, so
5138 * set it readonly.
5140 if (miss_ndevs > btrfs_chunk_max_errors(map))
5141 readonly = 1;
5142 end:
5143 free_extent_map(em);
5144 return readonly;
5147 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5149 extent_map_tree_init(&tree->map_tree);
5152 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5154 struct extent_map *em;
5156 while (1) {
5157 write_lock(&tree->map_tree.lock);
5158 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5159 if (em)
5160 remove_extent_mapping(&tree->map_tree, em);
5161 write_unlock(&tree->map_tree.lock);
5162 if (!em)
5163 break;
5164 /* once for us */
5165 free_extent_map(em);
5166 /* once for the tree */
5167 free_extent_map(em);
5171 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5173 struct extent_map *em;
5174 struct map_lookup *map;
5175 int ret;
5177 em = get_chunk_map(fs_info, logical, len);
5178 if (IS_ERR(em))
5180 * We could return errors for these cases, but that could get
5181 * ugly and we'd probably do the same thing which is just not do
5182 * anything else and exit, so return 1 so the callers don't try
5183 * to use other copies.
5185 return 1;
5187 map = em->map_lookup;
5188 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5189 ret = map->num_stripes;
5190 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5191 ret = map->sub_stripes;
5192 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5193 ret = 2;
5194 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5196 * There could be two corrupted data stripes, we need
5197 * to loop retry in order to rebuild the correct data.
5199 * Fail a stripe at a time on every retry except the
5200 * stripe under reconstruction.
5202 ret = map->num_stripes;
5203 else
5204 ret = 1;
5205 free_extent_map(em);
5207 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
5208 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5209 fs_info->dev_replace.tgtdev)
5210 ret++;
5211 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
5213 return ret;
5216 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5217 u64 logical)
5219 struct extent_map *em;
5220 struct map_lookup *map;
5221 unsigned long len = fs_info->sectorsize;
5223 em = get_chunk_map(fs_info, logical, len);
5225 if (!WARN_ON(IS_ERR(em))) {
5226 map = em->map_lookup;
5227 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5228 len = map->stripe_len * nr_data_stripes(map);
5229 free_extent_map(em);
5231 return len;
5234 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5236 struct extent_map *em;
5237 struct map_lookup *map;
5238 int ret = 0;
5240 em = get_chunk_map(fs_info, logical, len);
5242 if(!WARN_ON(IS_ERR(em))) {
5243 map = em->map_lookup;
5244 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5245 ret = 1;
5246 free_extent_map(em);
5248 return ret;
5251 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5252 struct map_lookup *map, int first,
5253 int dev_replace_is_ongoing)
5255 int i;
5256 int num_stripes;
5257 int preferred_mirror;
5258 int tolerance;
5259 struct btrfs_device *srcdev;
5261 ASSERT((map->type &
5262 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)));
5264 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5265 num_stripes = map->sub_stripes;
5266 else
5267 num_stripes = map->num_stripes;
5269 preferred_mirror = first + current->pid % num_stripes;
5271 if (dev_replace_is_ongoing &&
5272 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5273 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5274 srcdev = fs_info->dev_replace.srcdev;
5275 else
5276 srcdev = NULL;
5279 * try to avoid the drive that is the source drive for a
5280 * dev-replace procedure, only choose it if no other non-missing
5281 * mirror is available
5283 for (tolerance = 0; tolerance < 2; tolerance++) {
5284 if (map->stripes[preferred_mirror].dev->bdev &&
5285 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5286 return preferred_mirror;
5287 for (i = first; i < first + num_stripes; i++) {
5288 if (map->stripes[i].dev->bdev &&
5289 (tolerance || map->stripes[i].dev != srcdev))
5290 return i;
5294 /* we couldn't find one that doesn't fail. Just return something
5295 * and the io error handling code will clean up eventually
5297 return preferred_mirror;
5300 static inline int parity_smaller(u64 a, u64 b)
5302 return a > b;
5305 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5306 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5308 struct btrfs_bio_stripe s;
5309 int i;
5310 u64 l;
5311 int again = 1;
5313 while (again) {
5314 again = 0;
5315 for (i = 0; i < num_stripes - 1; i++) {
5316 if (parity_smaller(bbio->raid_map[i],
5317 bbio->raid_map[i+1])) {
5318 s = bbio->stripes[i];
5319 l = bbio->raid_map[i];
5320 bbio->stripes[i] = bbio->stripes[i+1];
5321 bbio->raid_map[i] = bbio->raid_map[i+1];
5322 bbio->stripes[i+1] = s;
5323 bbio->raid_map[i+1] = l;
5325 again = 1;
5331 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5333 struct btrfs_bio *bbio = kzalloc(
5334 /* the size of the btrfs_bio */
5335 sizeof(struct btrfs_bio) +
5336 /* plus the variable array for the stripes */
5337 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5338 /* plus the variable array for the tgt dev */
5339 sizeof(int) * (real_stripes) +
5341 * plus the raid_map, which includes both the tgt dev
5342 * and the stripes
5344 sizeof(u64) * (total_stripes),
5345 GFP_NOFS|__GFP_NOFAIL);
5347 atomic_set(&bbio->error, 0);
5348 refcount_set(&bbio->refs, 1);
5350 return bbio;
5353 void btrfs_get_bbio(struct btrfs_bio *bbio)
5355 WARN_ON(!refcount_read(&bbio->refs));
5356 refcount_inc(&bbio->refs);
5359 void btrfs_put_bbio(struct btrfs_bio *bbio)
5361 if (!bbio)
5362 return;
5363 if (refcount_dec_and_test(&bbio->refs))
5364 kfree(bbio);
5367 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5369 * Please note that, discard won't be sent to target device of device
5370 * replace.
5372 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5373 u64 logical, u64 length,
5374 struct btrfs_bio **bbio_ret)
5376 struct extent_map *em;
5377 struct map_lookup *map;
5378 struct btrfs_bio *bbio;
5379 u64 offset;
5380 u64 stripe_nr;
5381 u64 stripe_nr_end;
5382 u64 stripe_end_offset;
5383 u64 stripe_cnt;
5384 u64 stripe_len;
5385 u64 stripe_offset;
5386 u64 num_stripes;
5387 u32 stripe_index;
5388 u32 factor = 0;
5389 u32 sub_stripes = 0;
5390 u64 stripes_per_dev = 0;
5391 u32 remaining_stripes = 0;
5392 u32 last_stripe = 0;
5393 int ret = 0;
5394 int i;
5396 /* discard always return a bbio */
5397 ASSERT(bbio_ret);
5399 em = get_chunk_map(fs_info, logical, length);
5400 if (IS_ERR(em))
5401 return PTR_ERR(em);
5403 map = em->map_lookup;
5404 /* we don't discard raid56 yet */
5405 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5406 ret = -EOPNOTSUPP;
5407 goto out;
5410 offset = logical - em->start;
5411 length = min_t(u64, em->len - offset, length);
5413 stripe_len = map->stripe_len;
5415 * stripe_nr counts the total number of stripes we have to stride
5416 * to get to this block
5418 stripe_nr = div64_u64(offset, stripe_len);
5420 /* stripe_offset is the offset of this block in its stripe */
5421 stripe_offset = offset - stripe_nr * stripe_len;
5423 stripe_nr_end = round_up(offset + length, map->stripe_len);
5424 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5425 stripe_cnt = stripe_nr_end - stripe_nr;
5426 stripe_end_offset = stripe_nr_end * map->stripe_len -
5427 (offset + length);
5429 * after this, stripe_nr is the number of stripes on this
5430 * device we have to walk to find the data, and stripe_index is
5431 * the number of our device in the stripe array
5433 num_stripes = 1;
5434 stripe_index = 0;
5435 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5436 BTRFS_BLOCK_GROUP_RAID10)) {
5437 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5438 sub_stripes = 1;
5439 else
5440 sub_stripes = map->sub_stripes;
5442 factor = map->num_stripes / sub_stripes;
5443 num_stripes = min_t(u64, map->num_stripes,
5444 sub_stripes * stripe_cnt);
5445 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5446 stripe_index *= sub_stripes;
5447 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5448 &remaining_stripes);
5449 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5450 last_stripe *= sub_stripes;
5451 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5452 BTRFS_BLOCK_GROUP_DUP)) {
5453 num_stripes = map->num_stripes;
5454 } else {
5455 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5456 &stripe_index);
5459 bbio = alloc_btrfs_bio(num_stripes, 0);
5460 if (!bbio) {
5461 ret = -ENOMEM;
5462 goto out;
5465 for (i = 0; i < num_stripes; i++) {
5466 bbio->stripes[i].physical =
5467 map->stripes[stripe_index].physical +
5468 stripe_offset + stripe_nr * map->stripe_len;
5469 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5471 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5472 BTRFS_BLOCK_GROUP_RAID10)) {
5473 bbio->stripes[i].length = stripes_per_dev *
5474 map->stripe_len;
5476 if (i / sub_stripes < remaining_stripes)
5477 bbio->stripes[i].length +=
5478 map->stripe_len;
5481 * Special for the first stripe and
5482 * the last stripe:
5484 * |-------|...|-------|
5485 * |----------|
5486 * off end_off
5488 if (i < sub_stripes)
5489 bbio->stripes[i].length -=
5490 stripe_offset;
5492 if (stripe_index >= last_stripe &&
5493 stripe_index <= (last_stripe +
5494 sub_stripes - 1))
5495 bbio->stripes[i].length -=
5496 stripe_end_offset;
5498 if (i == sub_stripes - 1)
5499 stripe_offset = 0;
5500 } else {
5501 bbio->stripes[i].length = length;
5504 stripe_index++;
5505 if (stripe_index == map->num_stripes) {
5506 stripe_index = 0;
5507 stripe_nr++;
5511 *bbio_ret = bbio;
5512 bbio->map_type = map->type;
5513 bbio->num_stripes = num_stripes;
5514 out:
5515 free_extent_map(em);
5516 return ret;
5520 * In dev-replace case, for repair case (that's the only case where the mirror
5521 * is selected explicitly when calling btrfs_map_block), blocks left of the
5522 * left cursor can also be read from the target drive.
5524 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5525 * array of stripes.
5526 * For READ, it also needs to be supported using the same mirror number.
5528 * If the requested block is not left of the left cursor, EIO is returned. This
5529 * can happen because btrfs_num_copies() returns one more in the dev-replace
5530 * case.
5532 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5533 u64 logical, u64 length,
5534 u64 srcdev_devid, int *mirror_num,
5535 u64 *physical)
5537 struct btrfs_bio *bbio = NULL;
5538 int num_stripes;
5539 int index_srcdev = 0;
5540 int found = 0;
5541 u64 physical_of_found = 0;
5542 int i;
5543 int ret = 0;
5545 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5546 logical, &length, &bbio, 0, 0);
5547 if (ret) {
5548 ASSERT(bbio == NULL);
5549 return ret;
5552 num_stripes = bbio->num_stripes;
5553 if (*mirror_num > num_stripes) {
5555 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5556 * that means that the requested area is not left of the left
5557 * cursor
5559 btrfs_put_bbio(bbio);
5560 return -EIO;
5564 * process the rest of the function using the mirror_num of the source
5565 * drive. Therefore look it up first. At the end, patch the device
5566 * pointer to the one of the target drive.
5568 for (i = 0; i < num_stripes; i++) {
5569 if (bbio->stripes[i].dev->devid != srcdev_devid)
5570 continue;
5573 * In case of DUP, in order to keep it simple, only add the
5574 * mirror with the lowest physical address
5576 if (found &&
5577 physical_of_found <= bbio->stripes[i].physical)
5578 continue;
5580 index_srcdev = i;
5581 found = 1;
5582 physical_of_found = bbio->stripes[i].physical;
5585 btrfs_put_bbio(bbio);
5587 ASSERT(found);
5588 if (!found)
5589 return -EIO;
5591 *mirror_num = index_srcdev + 1;
5592 *physical = physical_of_found;
5593 return ret;
5596 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5597 struct btrfs_bio **bbio_ret,
5598 struct btrfs_dev_replace *dev_replace,
5599 int *num_stripes_ret, int *max_errors_ret)
5601 struct btrfs_bio *bbio = *bbio_ret;
5602 u64 srcdev_devid = dev_replace->srcdev->devid;
5603 int tgtdev_indexes = 0;
5604 int num_stripes = *num_stripes_ret;
5605 int max_errors = *max_errors_ret;
5606 int i;
5608 if (op == BTRFS_MAP_WRITE) {
5609 int index_where_to_add;
5612 * duplicate the write operations while the dev replace
5613 * procedure is running. Since the copying of the old disk to
5614 * the new disk takes place at run time while the filesystem is
5615 * mounted writable, the regular write operations to the old
5616 * disk have to be duplicated to go to the new disk as well.
5618 * Note that device->missing is handled by the caller, and that
5619 * the write to the old disk is already set up in the stripes
5620 * array.
5622 index_where_to_add = num_stripes;
5623 for (i = 0; i < num_stripes; i++) {
5624 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5625 /* write to new disk, too */
5626 struct btrfs_bio_stripe *new =
5627 bbio->stripes + index_where_to_add;
5628 struct btrfs_bio_stripe *old =
5629 bbio->stripes + i;
5631 new->physical = old->physical;
5632 new->length = old->length;
5633 new->dev = dev_replace->tgtdev;
5634 bbio->tgtdev_map[i] = index_where_to_add;
5635 index_where_to_add++;
5636 max_errors++;
5637 tgtdev_indexes++;
5640 num_stripes = index_where_to_add;
5641 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5642 int index_srcdev = 0;
5643 int found = 0;
5644 u64 physical_of_found = 0;
5647 * During the dev-replace procedure, the target drive can also
5648 * be used to read data in case it is needed to repair a corrupt
5649 * block elsewhere. This is possible if the requested area is
5650 * left of the left cursor. In this area, the target drive is a
5651 * full copy of the source drive.
5653 for (i = 0; i < num_stripes; i++) {
5654 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5656 * In case of DUP, in order to keep it simple,
5657 * only add the mirror with the lowest physical
5658 * address
5660 if (found &&
5661 physical_of_found <=
5662 bbio->stripes[i].physical)
5663 continue;
5664 index_srcdev = i;
5665 found = 1;
5666 physical_of_found = bbio->stripes[i].physical;
5669 if (found) {
5670 struct btrfs_bio_stripe *tgtdev_stripe =
5671 bbio->stripes + num_stripes;
5673 tgtdev_stripe->physical = physical_of_found;
5674 tgtdev_stripe->length =
5675 bbio->stripes[index_srcdev].length;
5676 tgtdev_stripe->dev = dev_replace->tgtdev;
5677 bbio->tgtdev_map[index_srcdev] = num_stripes;
5679 tgtdev_indexes++;
5680 num_stripes++;
5684 *num_stripes_ret = num_stripes;
5685 *max_errors_ret = max_errors;
5686 bbio->num_tgtdevs = tgtdev_indexes;
5687 *bbio_ret = bbio;
5690 static bool need_full_stripe(enum btrfs_map_op op)
5692 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5695 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5696 enum btrfs_map_op op,
5697 u64 logical, u64 *length,
5698 struct btrfs_bio **bbio_ret,
5699 int mirror_num, int need_raid_map)
5701 struct extent_map *em;
5702 struct map_lookup *map;
5703 u64 offset;
5704 u64 stripe_offset;
5705 u64 stripe_nr;
5706 u64 stripe_len;
5707 u32 stripe_index;
5708 int i;
5709 int ret = 0;
5710 int num_stripes;
5711 int max_errors = 0;
5712 int tgtdev_indexes = 0;
5713 struct btrfs_bio *bbio = NULL;
5714 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5715 int dev_replace_is_ongoing = 0;
5716 int num_alloc_stripes;
5717 int patch_the_first_stripe_for_dev_replace = 0;
5718 u64 physical_to_patch_in_first_stripe = 0;
5719 u64 raid56_full_stripe_start = (u64)-1;
5721 if (op == BTRFS_MAP_DISCARD)
5722 return __btrfs_map_block_for_discard(fs_info, logical,
5723 *length, bbio_ret);
5725 em = get_chunk_map(fs_info, logical, *length);
5726 if (IS_ERR(em))
5727 return PTR_ERR(em);
5729 map = em->map_lookup;
5730 offset = logical - em->start;
5732 stripe_len = map->stripe_len;
5733 stripe_nr = offset;
5735 * stripe_nr counts the total number of stripes we have to stride
5736 * to get to this block
5738 stripe_nr = div64_u64(stripe_nr, stripe_len);
5740 stripe_offset = stripe_nr * stripe_len;
5741 if (offset < stripe_offset) {
5742 btrfs_crit(fs_info,
5743 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
5744 stripe_offset, offset, em->start, logical,
5745 stripe_len);
5746 free_extent_map(em);
5747 return -EINVAL;
5750 /* stripe_offset is the offset of this block in its stripe*/
5751 stripe_offset = offset - stripe_offset;
5753 /* if we're here for raid56, we need to know the stripe aligned start */
5754 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5755 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5756 raid56_full_stripe_start = offset;
5758 /* allow a write of a full stripe, but make sure we don't
5759 * allow straddling of stripes
5761 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5762 full_stripe_len);
5763 raid56_full_stripe_start *= full_stripe_len;
5766 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5767 u64 max_len;
5768 /* For writes to RAID[56], allow a full stripeset across all disks.
5769 For other RAID types and for RAID[56] reads, just allow a single
5770 stripe (on a single disk). */
5771 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5772 (op == BTRFS_MAP_WRITE)) {
5773 max_len = stripe_len * nr_data_stripes(map) -
5774 (offset - raid56_full_stripe_start);
5775 } else {
5776 /* we limit the length of each bio to what fits in a stripe */
5777 max_len = stripe_len - stripe_offset;
5779 *length = min_t(u64, em->len - offset, max_len);
5780 } else {
5781 *length = em->len - offset;
5784 /* This is for when we're called from btrfs_merge_bio_hook() and all
5785 it cares about is the length */
5786 if (!bbio_ret)
5787 goto out;
5789 btrfs_dev_replace_read_lock(dev_replace);
5790 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5791 if (!dev_replace_is_ongoing)
5792 btrfs_dev_replace_read_unlock(dev_replace);
5793 else
5794 btrfs_dev_replace_set_lock_blocking(dev_replace);
5796 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5797 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
5798 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
5799 dev_replace->srcdev->devid,
5800 &mirror_num,
5801 &physical_to_patch_in_first_stripe);
5802 if (ret)
5803 goto out;
5804 else
5805 patch_the_first_stripe_for_dev_replace = 1;
5806 } else if (mirror_num > map->num_stripes) {
5807 mirror_num = 0;
5810 num_stripes = 1;
5811 stripe_index = 0;
5812 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5813 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5814 &stripe_index);
5815 if (!need_full_stripe(op))
5816 mirror_num = 1;
5817 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5818 if (need_full_stripe(op))
5819 num_stripes = map->num_stripes;
5820 else if (mirror_num)
5821 stripe_index = mirror_num - 1;
5822 else {
5823 stripe_index = find_live_mirror(fs_info, map, 0,
5824 dev_replace_is_ongoing);
5825 mirror_num = stripe_index + 1;
5828 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5829 if (need_full_stripe(op)) {
5830 num_stripes = map->num_stripes;
5831 } else if (mirror_num) {
5832 stripe_index = mirror_num - 1;
5833 } else {
5834 mirror_num = 1;
5837 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5838 u32 factor = map->num_stripes / map->sub_stripes;
5840 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5841 stripe_index *= map->sub_stripes;
5843 if (need_full_stripe(op))
5844 num_stripes = map->sub_stripes;
5845 else if (mirror_num)
5846 stripe_index += mirror_num - 1;
5847 else {
5848 int old_stripe_index = stripe_index;
5849 stripe_index = find_live_mirror(fs_info, map,
5850 stripe_index,
5851 dev_replace_is_ongoing);
5852 mirror_num = stripe_index - old_stripe_index + 1;
5855 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5856 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
5857 /* push stripe_nr back to the start of the full stripe */
5858 stripe_nr = div64_u64(raid56_full_stripe_start,
5859 stripe_len * nr_data_stripes(map));
5861 /* RAID[56] write or recovery. Return all stripes */
5862 num_stripes = map->num_stripes;
5863 max_errors = nr_parity_stripes(map);
5865 *length = map->stripe_len;
5866 stripe_index = 0;
5867 stripe_offset = 0;
5868 } else {
5870 * Mirror #0 or #1 means the original data block.
5871 * Mirror #2 is RAID5 parity block.
5872 * Mirror #3 is RAID6 Q block.
5874 stripe_nr = div_u64_rem(stripe_nr,
5875 nr_data_stripes(map), &stripe_index);
5876 if (mirror_num > 1)
5877 stripe_index = nr_data_stripes(map) +
5878 mirror_num - 2;
5880 /* We distribute the parity blocks across stripes */
5881 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5882 &stripe_index);
5883 if (!need_full_stripe(op) && mirror_num <= 1)
5884 mirror_num = 1;
5886 } else {
5888 * after this, stripe_nr is the number of stripes on this
5889 * device we have to walk to find the data, and stripe_index is
5890 * the number of our device in the stripe array
5892 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5893 &stripe_index);
5894 mirror_num = stripe_index + 1;
5896 if (stripe_index >= map->num_stripes) {
5897 btrfs_crit(fs_info,
5898 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
5899 stripe_index, map->num_stripes);
5900 ret = -EINVAL;
5901 goto out;
5904 num_alloc_stripes = num_stripes;
5905 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
5906 if (op == BTRFS_MAP_WRITE)
5907 num_alloc_stripes <<= 1;
5908 if (op == BTRFS_MAP_GET_READ_MIRRORS)
5909 num_alloc_stripes++;
5910 tgtdev_indexes = num_stripes;
5913 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5914 if (!bbio) {
5915 ret = -ENOMEM;
5916 goto out;
5918 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
5919 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5921 /* build raid_map */
5922 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
5923 (need_full_stripe(op) || mirror_num > 1)) {
5924 u64 tmp;
5925 unsigned rot;
5927 bbio->raid_map = (u64 *)((void *)bbio->stripes +
5928 sizeof(struct btrfs_bio_stripe) *
5929 num_alloc_stripes +
5930 sizeof(int) * tgtdev_indexes);
5932 /* Work out the disk rotation on this stripe-set */
5933 div_u64_rem(stripe_nr, num_stripes, &rot);
5935 /* Fill in the logical address of each stripe */
5936 tmp = stripe_nr * nr_data_stripes(map);
5937 for (i = 0; i < nr_data_stripes(map); i++)
5938 bbio->raid_map[(i+rot) % num_stripes] =
5939 em->start + (tmp + i) * map->stripe_len;
5941 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5942 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5943 bbio->raid_map[(i+rot+1) % num_stripes] =
5944 RAID6_Q_STRIPE;
5948 for (i = 0; i < num_stripes; i++) {
5949 bbio->stripes[i].physical =
5950 map->stripes[stripe_index].physical +
5951 stripe_offset +
5952 stripe_nr * map->stripe_len;
5953 bbio->stripes[i].dev =
5954 map->stripes[stripe_index].dev;
5955 stripe_index++;
5958 if (need_full_stripe(op))
5959 max_errors = btrfs_chunk_max_errors(map);
5961 if (bbio->raid_map)
5962 sort_parity_stripes(bbio, num_stripes);
5964 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
5965 need_full_stripe(op)) {
5966 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
5967 &max_errors);
5970 *bbio_ret = bbio;
5971 bbio->map_type = map->type;
5972 bbio->num_stripes = num_stripes;
5973 bbio->max_errors = max_errors;
5974 bbio->mirror_num = mirror_num;
5977 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5978 * mirror_num == num_stripes + 1 && dev_replace target drive is
5979 * available as a mirror
5981 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5982 WARN_ON(num_stripes > 1);
5983 bbio->stripes[0].dev = dev_replace->tgtdev;
5984 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5985 bbio->mirror_num = map->num_stripes + 1;
5987 out:
5988 if (dev_replace_is_ongoing) {
5989 btrfs_dev_replace_clear_lock_blocking(dev_replace);
5990 btrfs_dev_replace_read_unlock(dev_replace);
5992 free_extent_map(em);
5993 return ret;
5996 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5997 u64 logical, u64 *length,
5998 struct btrfs_bio **bbio_ret, int mirror_num)
6000 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6001 mirror_num, 0);
6004 /* For Scrub/replace */
6005 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6006 u64 logical, u64 *length,
6007 struct btrfs_bio **bbio_ret)
6009 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6012 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
6013 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
6015 struct extent_map *em;
6016 struct map_lookup *map;
6017 u64 *buf;
6018 u64 bytenr;
6019 u64 length;
6020 u64 stripe_nr;
6021 u64 rmap_len;
6022 int i, j, nr = 0;
6024 em = get_chunk_map(fs_info, chunk_start, 1);
6025 if (IS_ERR(em))
6026 return -EIO;
6028 map = em->map_lookup;
6029 length = em->len;
6030 rmap_len = map->stripe_len;
6032 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6033 length = div_u64(length, map->num_stripes / map->sub_stripes);
6034 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6035 length = div_u64(length, map->num_stripes);
6036 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6037 length = div_u64(length, nr_data_stripes(map));
6038 rmap_len = map->stripe_len * nr_data_stripes(map);
6041 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
6042 BUG_ON(!buf); /* -ENOMEM */
6044 for (i = 0; i < map->num_stripes; i++) {
6045 if (map->stripes[i].physical > physical ||
6046 map->stripes[i].physical + length <= physical)
6047 continue;
6049 stripe_nr = physical - map->stripes[i].physical;
6050 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
6052 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6053 stripe_nr = stripe_nr * map->num_stripes + i;
6054 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
6055 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6056 stripe_nr = stripe_nr * map->num_stripes + i;
6057 } /* else if RAID[56], multiply by nr_data_stripes().
6058 * Alternatively, just use rmap_len below instead of
6059 * map->stripe_len */
6061 bytenr = chunk_start + stripe_nr * rmap_len;
6062 WARN_ON(nr >= map->num_stripes);
6063 for (j = 0; j < nr; j++) {
6064 if (buf[j] == bytenr)
6065 break;
6067 if (j == nr) {
6068 WARN_ON(nr >= map->num_stripes);
6069 buf[nr++] = bytenr;
6073 *logical = buf;
6074 *naddrs = nr;
6075 *stripe_len = rmap_len;
6077 free_extent_map(em);
6078 return 0;
6081 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6083 bio->bi_private = bbio->private;
6084 bio->bi_end_io = bbio->end_io;
6085 bio_endio(bio);
6087 btrfs_put_bbio(bbio);
6090 static void btrfs_end_bio(struct bio *bio)
6092 struct btrfs_bio *bbio = bio->bi_private;
6093 int is_orig_bio = 0;
6095 if (bio->bi_status) {
6096 atomic_inc(&bbio->error);
6097 if (bio->bi_status == BLK_STS_IOERR ||
6098 bio->bi_status == BLK_STS_TARGET) {
6099 unsigned int stripe_index =
6100 btrfs_io_bio(bio)->stripe_index;
6101 struct btrfs_device *dev;
6103 BUG_ON(stripe_index >= bbio->num_stripes);
6104 dev = bbio->stripes[stripe_index].dev;
6105 if (dev->bdev) {
6106 if (bio_op(bio) == REQ_OP_WRITE)
6107 btrfs_dev_stat_inc_and_print(dev,
6108 BTRFS_DEV_STAT_WRITE_ERRS);
6109 else
6110 btrfs_dev_stat_inc_and_print(dev,
6111 BTRFS_DEV_STAT_READ_ERRS);
6112 if (bio->bi_opf & REQ_PREFLUSH)
6113 btrfs_dev_stat_inc_and_print(dev,
6114 BTRFS_DEV_STAT_FLUSH_ERRS);
6119 if (bio == bbio->orig_bio)
6120 is_orig_bio = 1;
6122 btrfs_bio_counter_dec(bbio->fs_info);
6124 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6125 if (!is_orig_bio) {
6126 bio_put(bio);
6127 bio = bbio->orig_bio;
6130 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6131 /* only send an error to the higher layers if it is
6132 * beyond the tolerance of the btrfs bio
6134 if (atomic_read(&bbio->error) > bbio->max_errors) {
6135 bio->bi_status = BLK_STS_IOERR;
6136 } else {
6138 * this bio is actually up to date, we didn't
6139 * go over the max number of errors
6141 bio->bi_status = BLK_STS_OK;
6144 btrfs_end_bbio(bbio, bio);
6145 } else if (!is_orig_bio) {
6146 bio_put(bio);
6151 * see run_scheduled_bios for a description of why bios are collected for
6152 * async submit.
6154 * This will add one bio to the pending list for a device and make sure
6155 * the work struct is scheduled.
6157 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6158 struct bio *bio)
6160 struct btrfs_fs_info *fs_info = device->fs_info;
6161 int should_queue = 1;
6162 struct btrfs_pending_bios *pending_bios;
6164 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state) ||
6165 !device->bdev) {
6166 bio_io_error(bio);
6167 return;
6170 /* don't bother with additional async steps for reads, right now */
6171 if (bio_op(bio) == REQ_OP_READ) {
6172 btrfsic_submit_bio(bio);
6173 return;
6176 WARN_ON(bio->bi_next);
6177 bio->bi_next = NULL;
6179 spin_lock(&device->io_lock);
6180 if (op_is_sync(bio->bi_opf))
6181 pending_bios = &device->pending_sync_bios;
6182 else
6183 pending_bios = &device->pending_bios;
6185 if (pending_bios->tail)
6186 pending_bios->tail->bi_next = bio;
6188 pending_bios->tail = bio;
6189 if (!pending_bios->head)
6190 pending_bios->head = bio;
6191 if (device->running_pending)
6192 should_queue = 0;
6194 spin_unlock(&device->io_lock);
6196 if (should_queue)
6197 btrfs_queue_work(fs_info->submit_workers, &device->work);
6200 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6201 u64 physical, int dev_nr, int async)
6203 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6204 struct btrfs_fs_info *fs_info = bbio->fs_info;
6206 bio->bi_private = bbio;
6207 btrfs_io_bio(bio)->stripe_index = dev_nr;
6208 bio->bi_end_io = btrfs_end_bio;
6209 bio->bi_iter.bi_sector = physical >> 9;
6210 #ifdef DEBUG
6212 struct rcu_string *name;
6214 rcu_read_lock();
6215 name = rcu_dereference(dev->name);
6216 btrfs_debug(fs_info,
6217 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6218 bio_op(bio), bio->bi_opf,
6219 (u64)bio->bi_iter.bi_sector,
6220 (u_long)dev->bdev->bd_dev, name->str, dev->devid,
6221 bio->bi_iter.bi_size);
6222 rcu_read_unlock();
6224 #endif
6225 bio_set_dev(bio, dev->bdev);
6227 btrfs_bio_counter_inc_noblocked(fs_info);
6229 if (async)
6230 btrfs_schedule_bio(dev, bio);
6231 else
6232 btrfsic_submit_bio(bio);
6235 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6237 atomic_inc(&bbio->error);
6238 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6239 /* Should be the original bio. */
6240 WARN_ON(bio != bbio->orig_bio);
6242 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6243 bio->bi_iter.bi_sector = logical >> 9;
6244 if (atomic_read(&bbio->error) > bbio->max_errors)
6245 bio->bi_status = BLK_STS_IOERR;
6246 else
6247 bio->bi_status = BLK_STS_OK;
6248 btrfs_end_bbio(bbio, bio);
6252 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6253 int mirror_num, int async_submit)
6255 struct btrfs_device *dev;
6256 struct bio *first_bio = bio;
6257 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6258 u64 length = 0;
6259 u64 map_length;
6260 int ret;
6261 int dev_nr;
6262 int total_devs;
6263 struct btrfs_bio *bbio = NULL;
6265 length = bio->bi_iter.bi_size;
6266 map_length = length;
6268 btrfs_bio_counter_inc_blocked(fs_info);
6269 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6270 &map_length, &bbio, mirror_num, 1);
6271 if (ret) {
6272 btrfs_bio_counter_dec(fs_info);
6273 return errno_to_blk_status(ret);
6276 total_devs = bbio->num_stripes;
6277 bbio->orig_bio = first_bio;
6278 bbio->private = first_bio->bi_private;
6279 bbio->end_io = first_bio->bi_end_io;
6280 bbio->fs_info = fs_info;
6281 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6283 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6284 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6285 /* In this case, map_length has been set to the length of
6286 a single stripe; not the whole write */
6287 if (bio_op(bio) == REQ_OP_WRITE) {
6288 ret = raid56_parity_write(fs_info, bio, bbio,
6289 map_length);
6290 } else {
6291 ret = raid56_parity_recover(fs_info, bio, bbio,
6292 map_length, mirror_num, 1);
6295 btrfs_bio_counter_dec(fs_info);
6296 return errno_to_blk_status(ret);
6299 if (map_length < length) {
6300 btrfs_crit(fs_info,
6301 "mapping failed logical %llu bio len %llu len %llu",
6302 logical, length, map_length);
6303 BUG();
6306 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6307 dev = bbio->stripes[dev_nr].dev;
6308 if (!dev || !dev->bdev ||
6309 (bio_op(first_bio) == REQ_OP_WRITE &&
6310 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6311 bbio_error(bbio, first_bio, logical);
6312 continue;
6315 if (dev_nr < total_devs - 1)
6316 bio = btrfs_bio_clone(first_bio);
6317 else
6318 bio = first_bio;
6320 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6321 dev_nr, async_submit);
6323 btrfs_bio_counter_dec(fs_info);
6324 return BLK_STS_OK;
6327 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
6328 u8 *uuid, u8 *fsid)
6330 struct btrfs_device *device;
6331 struct btrfs_fs_devices *cur_devices;
6333 cur_devices = fs_info->fs_devices;
6334 while (cur_devices) {
6335 if (!fsid ||
6336 !memcmp(cur_devices->fsid, fsid, BTRFS_FSID_SIZE)) {
6337 device = find_device(cur_devices, devid, uuid);
6338 if (device)
6339 return device;
6341 cur_devices = cur_devices->seed;
6343 return NULL;
6346 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6347 u64 devid, u8 *dev_uuid)
6349 struct btrfs_device *device;
6351 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6352 if (IS_ERR(device))
6353 return device;
6355 list_add(&device->dev_list, &fs_devices->devices);
6356 device->fs_devices = fs_devices;
6357 fs_devices->num_devices++;
6359 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6360 fs_devices->missing_devices++;
6362 return device;
6366 * btrfs_alloc_device - allocate struct btrfs_device
6367 * @fs_info: used only for generating a new devid, can be NULL if
6368 * devid is provided (i.e. @devid != NULL).
6369 * @devid: a pointer to devid for this device. If NULL a new devid
6370 * is generated.
6371 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6372 * is generated.
6374 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6375 * on error. Returned struct is not linked onto any lists and must be
6376 * destroyed with btrfs_free_device.
6378 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6379 const u64 *devid,
6380 const u8 *uuid)
6382 struct btrfs_device *dev;
6383 u64 tmp;
6385 if (WARN_ON(!devid && !fs_info))
6386 return ERR_PTR(-EINVAL);
6388 dev = __alloc_device();
6389 if (IS_ERR(dev))
6390 return dev;
6392 if (devid)
6393 tmp = *devid;
6394 else {
6395 int ret;
6397 ret = find_next_devid(fs_info, &tmp);
6398 if (ret) {
6399 btrfs_free_device(dev);
6400 return ERR_PTR(ret);
6403 dev->devid = tmp;
6405 if (uuid)
6406 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6407 else
6408 generate_random_uuid(dev->uuid);
6410 btrfs_init_work(&dev->work, btrfs_submit_helper,
6411 pending_bios_fn, NULL, NULL);
6413 return dev;
6416 /* Return -EIO if any error, otherwise return 0. */
6417 static int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info,
6418 struct extent_buffer *leaf,
6419 struct btrfs_chunk *chunk, u64 logical)
6421 u64 length;
6422 u64 stripe_len;
6423 u16 num_stripes;
6424 u16 sub_stripes;
6425 u64 type;
6427 length = btrfs_chunk_length(leaf, chunk);
6428 stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6429 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6430 sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6431 type = btrfs_chunk_type(leaf, chunk);
6433 if (!num_stripes) {
6434 btrfs_err(fs_info, "invalid chunk num_stripes: %u",
6435 num_stripes);
6436 return -EIO;
6438 if (!IS_ALIGNED(logical, fs_info->sectorsize)) {
6439 btrfs_err(fs_info, "invalid chunk logical %llu", logical);
6440 return -EIO;
6442 if (btrfs_chunk_sector_size(leaf, chunk) != fs_info->sectorsize) {
6443 btrfs_err(fs_info, "invalid chunk sectorsize %u",
6444 btrfs_chunk_sector_size(leaf, chunk));
6445 return -EIO;
6447 if (!length || !IS_ALIGNED(length, fs_info->sectorsize)) {
6448 btrfs_err(fs_info, "invalid chunk length %llu", length);
6449 return -EIO;
6451 if (!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN) {
6452 btrfs_err(fs_info, "invalid chunk stripe length: %llu",
6453 stripe_len);
6454 return -EIO;
6456 if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6457 type) {
6458 btrfs_err(fs_info, "unrecognized chunk type: %llu",
6459 ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
6460 BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6461 btrfs_chunk_type(leaf, chunk));
6462 return -EIO;
6464 if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes != 2) ||
6465 (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes < 1) ||
6466 (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
6467 (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
6468 (type & BTRFS_BLOCK_GROUP_DUP && num_stripes > 2) ||
6469 ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
6470 num_stripes != 1)) {
6471 btrfs_err(fs_info,
6472 "invalid num_stripes:sub_stripes %u:%u for profile %llu",
6473 num_stripes, sub_stripes,
6474 type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
6475 return -EIO;
6478 return 0;
6481 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6482 u64 devid, u8 *uuid, bool error)
6484 if (error)
6485 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6486 devid, uuid);
6487 else
6488 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6489 devid, uuid);
6492 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6493 struct extent_buffer *leaf,
6494 struct btrfs_chunk *chunk)
6496 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6497 struct map_lookup *map;
6498 struct extent_map *em;
6499 u64 logical;
6500 u64 length;
6501 u64 devid;
6502 u8 uuid[BTRFS_UUID_SIZE];
6503 int num_stripes;
6504 int ret;
6505 int i;
6507 logical = key->offset;
6508 length = btrfs_chunk_length(leaf, chunk);
6509 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6511 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6512 if (ret)
6513 return ret;
6515 read_lock(&map_tree->map_tree.lock);
6516 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6517 read_unlock(&map_tree->map_tree.lock);
6519 /* already mapped? */
6520 if (em && em->start <= logical && em->start + em->len > logical) {
6521 free_extent_map(em);
6522 return 0;
6523 } else if (em) {
6524 free_extent_map(em);
6527 em = alloc_extent_map();
6528 if (!em)
6529 return -ENOMEM;
6530 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6531 if (!map) {
6532 free_extent_map(em);
6533 return -ENOMEM;
6536 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6537 em->map_lookup = map;
6538 em->start = logical;
6539 em->len = length;
6540 em->orig_start = 0;
6541 em->block_start = 0;
6542 em->block_len = em->len;
6544 map->num_stripes = num_stripes;
6545 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6546 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6547 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6548 map->type = btrfs_chunk_type(leaf, chunk);
6549 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6550 for (i = 0; i < num_stripes; i++) {
6551 map->stripes[i].physical =
6552 btrfs_stripe_offset_nr(leaf, chunk, i);
6553 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6554 read_extent_buffer(leaf, uuid, (unsigned long)
6555 btrfs_stripe_dev_uuid_nr(chunk, i),
6556 BTRFS_UUID_SIZE);
6557 map->stripes[i].dev = btrfs_find_device(fs_info, devid,
6558 uuid, NULL);
6559 if (!map->stripes[i].dev &&
6560 !btrfs_test_opt(fs_info, DEGRADED)) {
6561 free_extent_map(em);
6562 btrfs_report_missing_device(fs_info, devid, uuid, true);
6563 return -ENOENT;
6565 if (!map->stripes[i].dev) {
6566 map->stripes[i].dev =
6567 add_missing_dev(fs_info->fs_devices, devid,
6568 uuid);
6569 if (IS_ERR(map->stripes[i].dev)) {
6570 free_extent_map(em);
6571 btrfs_err(fs_info,
6572 "failed to init missing dev %llu: %ld",
6573 devid, PTR_ERR(map->stripes[i].dev));
6574 return PTR_ERR(map->stripes[i].dev);
6576 btrfs_report_missing_device(fs_info, devid, uuid, false);
6578 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6579 &(map->stripes[i].dev->dev_state));
6583 write_lock(&map_tree->map_tree.lock);
6584 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6585 write_unlock(&map_tree->map_tree.lock);
6586 if (ret < 0) {
6587 btrfs_err(fs_info,
6588 "failed to add chunk map, start=%llu len=%llu: %d",
6589 em->start, em->len, ret);
6591 free_extent_map(em);
6593 return ret;
6596 static void fill_device_from_item(struct extent_buffer *leaf,
6597 struct btrfs_dev_item *dev_item,
6598 struct btrfs_device *device)
6600 unsigned long ptr;
6602 device->devid = btrfs_device_id(leaf, dev_item);
6603 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6604 device->total_bytes = device->disk_total_bytes;
6605 device->commit_total_bytes = device->disk_total_bytes;
6606 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6607 device->commit_bytes_used = device->bytes_used;
6608 device->type = btrfs_device_type(leaf, dev_item);
6609 device->io_align = btrfs_device_io_align(leaf, dev_item);
6610 device->io_width = btrfs_device_io_width(leaf, dev_item);
6611 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6612 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6613 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6615 ptr = btrfs_device_uuid(dev_item);
6616 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6619 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6620 u8 *fsid)
6622 struct btrfs_fs_devices *fs_devices;
6623 int ret;
6625 lockdep_assert_held(&uuid_mutex);
6626 ASSERT(fsid);
6628 fs_devices = fs_info->fs_devices->seed;
6629 while (fs_devices) {
6630 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6631 return fs_devices;
6633 fs_devices = fs_devices->seed;
6636 fs_devices = find_fsid(fsid);
6637 if (!fs_devices) {
6638 if (!btrfs_test_opt(fs_info, DEGRADED))
6639 return ERR_PTR(-ENOENT);
6641 fs_devices = alloc_fs_devices(fsid);
6642 if (IS_ERR(fs_devices))
6643 return fs_devices;
6645 fs_devices->seeding = 1;
6646 fs_devices->opened = 1;
6647 return fs_devices;
6650 fs_devices = clone_fs_devices(fs_devices);
6651 if (IS_ERR(fs_devices))
6652 return fs_devices;
6654 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6655 if (ret) {
6656 free_fs_devices(fs_devices);
6657 fs_devices = ERR_PTR(ret);
6658 goto out;
6661 if (!fs_devices->seeding) {
6662 close_fs_devices(fs_devices);
6663 free_fs_devices(fs_devices);
6664 fs_devices = ERR_PTR(-EINVAL);
6665 goto out;
6668 fs_devices->seed = fs_info->fs_devices->seed;
6669 fs_info->fs_devices->seed = fs_devices;
6670 out:
6671 return fs_devices;
6674 static int read_one_dev(struct btrfs_fs_info *fs_info,
6675 struct extent_buffer *leaf,
6676 struct btrfs_dev_item *dev_item)
6678 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6679 struct btrfs_device *device;
6680 u64 devid;
6681 int ret;
6682 u8 fs_uuid[BTRFS_FSID_SIZE];
6683 u8 dev_uuid[BTRFS_UUID_SIZE];
6685 devid = btrfs_device_id(leaf, dev_item);
6686 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6687 BTRFS_UUID_SIZE);
6688 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6689 BTRFS_FSID_SIZE);
6691 if (memcmp(fs_uuid, fs_info->fsid, BTRFS_FSID_SIZE)) {
6692 fs_devices = open_seed_devices(fs_info, fs_uuid);
6693 if (IS_ERR(fs_devices))
6694 return PTR_ERR(fs_devices);
6697 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
6698 if (!device) {
6699 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6700 btrfs_report_missing_device(fs_info, devid,
6701 dev_uuid, true);
6702 return -ENOENT;
6705 device = add_missing_dev(fs_devices, devid, dev_uuid);
6706 if (IS_ERR(device)) {
6707 btrfs_err(fs_info,
6708 "failed to add missing dev %llu: %ld",
6709 devid, PTR_ERR(device));
6710 return PTR_ERR(device);
6712 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6713 } else {
6714 if (!device->bdev) {
6715 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6716 btrfs_report_missing_device(fs_info,
6717 devid, dev_uuid, true);
6718 return -ENOENT;
6720 btrfs_report_missing_device(fs_info, devid,
6721 dev_uuid, false);
6724 if (!device->bdev &&
6725 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6727 * this happens when a device that was properly setup
6728 * in the device info lists suddenly goes bad.
6729 * device->bdev is NULL, and so we have to set
6730 * device->missing to one here
6732 device->fs_devices->missing_devices++;
6733 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6736 /* Move the device to its own fs_devices */
6737 if (device->fs_devices != fs_devices) {
6738 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6739 &device->dev_state));
6741 list_move(&device->dev_list, &fs_devices->devices);
6742 device->fs_devices->num_devices--;
6743 fs_devices->num_devices++;
6745 device->fs_devices->missing_devices--;
6746 fs_devices->missing_devices++;
6748 device->fs_devices = fs_devices;
6752 if (device->fs_devices != fs_info->fs_devices) {
6753 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6754 if (device->generation !=
6755 btrfs_device_generation(leaf, dev_item))
6756 return -EINVAL;
6759 fill_device_from_item(leaf, dev_item, device);
6760 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6761 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6762 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6763 device->fs_devices->total_rw_bytes += device->total_bytes;
6764 atomic64_add(device->total_bytes - device->bytes_used,
6765 &fs_info->free_chunk_space);
6767 ret = 0;
6768 return ret;
6771 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6773 struct btrfs_root *root = fs_info->tree_root;
6774 struct btrfs_super_block *super_copy = fs_info->super_copy;
6775 struct extent_buffer *sb;
6776 struct btrfs_disk_key *disk_key;
6777 struct btrfs_chunk *chunk;
6778 u8 *array_ptr;
6779 unsigned long sb_array_offset;
6780 int ret = 0;
6781 u32 num_stripes;
6782 u32 array_size;
6783 u32 len = 0;
6784 u32 cur_offset;
6785 u64 type;
6786 struct btrfs_key key;
6788 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6790 * This will create extent buffer of nodesize, superblock size is
6791 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6792 * overallocate but we can keep it as-is, only the first page is used.
6794 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6795 if (IS_ERR(sb))
6796 return PTR_ERR(sb);
6797 set_extent_buffer_uptodate(sb);
6798 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6800 * The sb extent buffer is artificial and just used to read the system array.
6801 * set_extent_buffer_uptodate() call does not properly mark all it's
6802 * pages up-to-date when the page is larger: extent does not cover the
6803 * whole page and consequently check_page_uptodate does not find all
6804 * the page's extents up-to-date (the hole beyond sb),
6805 * write_extent_buffer then triggers a WARN_ON.
6807 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6808 * but sb spans only this function. Add an explicit SetPageUptodate call
6809 * to silence the warning eg. on PowerPC 64.
6811 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6812 SetPageUptodate(sb->pages[0]);
6814 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6815 array_size = btrfs_super_sys_array_size(super_copy);
6817 array_ptr = super_copy->sys_chunk_array;
6818 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6819 cur_offset = 0;
6821 while (cur_offset < array_size) {
6822 disk_key = (struct btrfs_disk_key *)array_ptr;
6823 len = sizeof(*disk_key);
6824 if (cur_offset + len > array_size)
6825 goto out_short_read;
6827 btrfs_disk_key_to_cpu(&key, disk_key);
6829 array_ptr += len;
6830 sb_array_offset += len;
6831 cur_offset += len;
6833 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6834 chunk = (struct btrfs_chunk *)sb_array_offset;
6836 * At least one btrfs_chunk with one stripe must be
6837 * present, exact stripe count check comes afterwards
6839 len = btrfs_chunk_item_size(1);
6840 if (cur_offset + len > array_size)
6841 goto out_short_read;
6843 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6844 if (!num_stripes) {
6845 btrfs_err(fs_info,
6846 "invalid number of stripes %u in sys_array at offset %u",
6847 num_stripes, cur_offset);
6848 ret = -EIO;
6849 break;
6852 type = btrfs_chunk_type(sb, chunk);
6853 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6854 btrfs_err(fs_info,
6855 "invalid chunk type %llu in sys_array at offset %u",
6856 type, cur_offset);
6857 ret = -EIO;
6858 break;
6861 len = btrfs_chunk_item_size(num_stripes);
6862 if (cur_offset + len > array_size)
6863 goto out_short_read;
6865 ret = read_one_chunk(fs_info, &key, sb, chunk);
6866 if (ret)
6867 break;
6868 } else {
6869 btrfs_err(fs_info,
6870 "unexpected item type %u in sys_array at offset %u",
6871 (u32)key.type, cur_offset);
6872 ret = -EIO;
6873 break;
6875 array_ptr += len;
6876 sb_array_offset += len;
6877 cur_offset += len;
6879 clear_extent_buffer_uptodate(sb);
6880 free_extent_buffer_stale(sb);
6881 return ret;
6883 out_short_read:
6884 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6885 len, cur_offset);
6886 clear_extent_buffer_uptodate(sb);
6887 free_extent_buffer_stale(sb);
6888 return -EIO;
6892 * Check if all chunks in the fs are OK for read-write degraded mount
6894 * If the @failing_dev is specified, it's accounted as missing.
6896 * Return true if all chunks meet the minimal RW mount requirements.
6897 * Return false if any chunk doesn't meet the minimal RW mount requirements.
6899 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
6900 struct btrfs_device *failing_dev)
6902 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6903 struct extent_map *em;
6904 u64 next_start = 0;
6905 bool ret = true;
6907 read_lock(&map_tree->map_tree.lock);
6908 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
6909 read_unlock(&map_tree->map_tree.lock);
6910 /* No chunk at all? Return false anyway */
6911 if (!em) {
6912 ret = false;
6913 goto out;
6915 while (em) {
6916 struct map_lookup *map;
6917 int missing = 0;
6918 int max_tolerated;
6919 int i;
6921 map = em->map_lookup;
6922 max_tolerated =
6923 btrfs_get_num_tolerated_disk_barrier_failures(
6924 map->type);
6925 for (i = 0; i < map->num_stripes; i++) {
6926 struct btrfs_device *dev = map->stripes[i].dev;
6928 if (!dev || !dev->bdev ||
6929 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
6930 dev->last_flush_error)
6931 missing++;
6932 else if (failing_dev && failing_dev == dev)
6933 missing++;
6935 if (missing > max_tolerated) {
6936 if (!failing_dev)
6937 btrfs_warn(fs_info,
6938 "chunk %llu missing %d devices, max tolerance is %d for writeable mount",
6939 em->start, missing, max_tolerated);
6940 free_extent_map(em);
6941 ret = false;
6942 goto out;
6944 next_start = extent_map_end(em);
6945 free_extent_map(em);
6947 read_lock(&map_tree->map_tree.lock);
6948 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
6949 (u64)(-1) - next_start);
6950 read_unlock(&map_tree->map_tree.lock);
6952 out:
6953 return ret;
6956 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
6958 struct btrfs_root *root = fs_info->chunk_root;
6959 struct btrfs_path *path;
6960 struct extent_buffer *leaf;
6961 struct btrfs_key key;
6962 struct btrfs_key found_key;
6963 int ret;
6964 int slot;
6965 u64 total_dev = 0;
6967 path = btrfs_alloc_path();
6968 if (!path)
6969 return -ENOMEM;
6972 * uuid_mutex is needed only if we are mounting a sprout FS
6973 * otherwise we don't need it.
6975 mutex_lock(&uuid_mutex);
6976 mutex_lock(&fs_info->chunk_mutex);
6979 * Read all device items, and then all the chunk items. All
6980 * device items are found before any chunk item (their object id
6981 * is smaller than the lowest possible object id for a chunk
6982 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6984 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6985 key.offset = 0;
6986 key.type = 0;
6987 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6988 if (ret < 0)
6989 goto error;
6990 while (1) {
6991 leaf = path->nodes[0];
6992 slot = path->slots[0];
6993 if (slot >= btrfs_header_nritems(leaf)) {
6994 ret = btrfs_next_leaf(root, path);
6995 if (ret == 0)
6996 continue;
6997 if (ret < 0)
6998 goto error;
6999 break;
7001 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7002 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7003 struct btrfs_dev_item *dev_item;
7004 dev_item = btrfs_item_ptr(leaf, slot,
7005 struct btrfs_dev_item);
7006 ret = read_one_dev(fs_info, leaf, dev_item);
7007 if (ret)
7008 goto error;
7009 total_dev++;
7010 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7011 struct btrfs_chunk *chunk;
7012 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7013 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
7014 if (ret)
7015 goto error;
7017 path->slots[0]++;
7021 * After loading chunk tree, we've got all device information,
7022 * do another round of validation checks.
7024 if (total_dev != fs_info->fs_devices->total_devices) {
7025 btrfs_err(fs_info,
7026 "super_num_devices %llu mismatch with num_devices %llu found here",
7027 btrfs_super_num_devices(fs_info->super_copy),
7028 total_dev);
7029 ret = -EINVAL;
7030 goto error;
7032 if (btrfs_super_total_bytes(fs_info->super_copy) <
7033 fs_info->fs_devices->total_rw_bytes) {
7034 btrfs_err(fs_info,
7035 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7036 btrfs_super_total_bytes(fs_info->super_copy),
7037 fs_info->fs_devices->total_rw_bytes);
7038 ret = -EINVAL;
7039 goto error;
7041 ret = 0;
7042 error:
7043 mutex_unlock(&fs_info->chunk_mutex);
7044 mutex_unlock(&uuid_mutex);
7046 btrfs_free_path(path);
7047 return ret;
7050 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7052 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7053 struct btrfs_device *device;
7055 while (fs_devices) {
7056 mutex_lock(&fs_devices->device_list_mutex);
7057 list_for_each_entry(device, &fs_devices->devices, dev_list)
7058 device->fs_info = fs_info;
7059 mutex_unlock(&fs_devices->device_list_mutex);
7061 fs_devices = fs_devices->seed;
7065 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
7067 int i;
7069 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7070 btrfs_dev_stat_reset(dev, i);
7073 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7075 struct btrfs_key key;
7076 struct btrfs_key found_key;
7077 struct btrfs_root *dev_root = fs_info->dev_root;
7078 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7079 struct extent_buffer *eb;
7080 int slot;
7081 int ret = 0;
7082 struct btrfs_device *device;
7083 struct btrfs_path *path = NULL;
7084 int i;
7086 path = btrfs_alloc_path();
7087 if (!path) {
7088 ret = -ENOMEM;
7089 goto out;
7092 mutex_lock(&fs_devices->device_list_mutex);
7093 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7094 int item_size;
7095 struct btrfs_dev_stats_item *ptr;
7097 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7098 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7099 key.offset = device->devid;
7100 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7101 if (ret) {
7102 __btrfs_reset_dev_stats(device);
7103 device->dev_stats_valid = 1;
7104 btrfs_release_path(path);
7105 continue;
7107 slot = path->slots[0];
7108 eb = path->nodes[0];
7109 btrfs_item_key_to_cpu(eb, &found_key, slot);
7110 item_size = btrfs_item_size_nr(eb, slot);
7112 ptr = btrfs_item_ptr(eb, slot,
7113 struct btrfs_dev_stats_item);
7115 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7116 if (item_size >= (1 + i) * sizeof(__le64))
7117 btrfs_dev_stat_set(device, i,
7118 btrfs_dev_stats_value(eb, ptr, i));
7119 else
7120 btrfs_dev_stat_reset(device, i);
7123 device->dev_stats_valid = 1;
7124 btrfs_dev_stat_print_on_load(device);
7125 btrfs_release_path(path);
7127 mutex_unlock(&fs_devices->device_list_mutex);
7129 out:
7130 btrfs_free_path(path);
7131 return ret < 0 ? ret : 0;
7134 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7135 struct btrfs_fs_info *fs_info,
7136 struct btrfs_device *device)
7138 struct btrfs_root *dev_root = fs_info->dev_root;
7139 struct btrfs_path *path;
7140 struct btrfs_key key;
7141 struct extent_buffer *eb;
7142 struct btrfs_dev_stats_item *ptr;
7143 int ret;
7144 int i;
7146 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7147 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7148 key.offset = device->devid;
7150 path = btrfs_alloc_path();
7151 if (!path)
7152 return -ENOMEM;
7153 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7154 if (ret < 0) {
7155 btrfs_warn_in_rcu(fs_info,
7156 "error %d while searching for dev_stats item for device %s",
7157 ret, rcu_str_deref(device->name));
7158 goto out;
7161 if (ret == 0 &&
7162 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7163 /* need to delete old one and insert a new one */
7164 ret = btrfs_del_item(trans, dev_root, path);
7165 if (ret != 0) {
7166 btrfs_warn_in_rcu(fs_info,
7167 "delete too small dev_stats item for device %s failed %d",
7168 rcu_str_deref(device->name), ret);
7169 goto out;
7171 ret = 1;
7174 if (ret == 1) {
7175 /* need to insert a new item */
7176 btrfs_release_path(path);
7177 ret = btrfs_insert_empty_item(trans, dev_root, path,
7178 &key, sizeof(*ptr));
7179 if (ret < 0) {
7180 btrfs_warn_in_rcu(fs_info,
7181 "insert dev_stats item for device %s failed %d",
7182 rcu_str_deref(device->name), ret);
7183 goto out;
7187 eb = path->nodes[0];
7188 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7189 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7190 btrfs_set_dev_stats_value(eb, ptr, i,
7191 btrfs_dev_stat_read(device, i));
7192 btrfs_mark_buffer_dirty(eb);
7194 out:
7195 btrfs_free_path(path);
7196 return ret;
7200 * called from commit_transaction. Writes all changed device stats to disk.
7202 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7203 struct btrfs_fs_info *fs_info)
7205 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7206 struct btrfs_device *device;
7207 int stats_cnt;
7208 int ret = 0;
7210 mutex_lock(&fs_devices->device_list_mutex);
7211 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7212 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7213 if (!device->dev_stats_valid || stats_cnt == 0)
7214 continue;
7218 * There is a LOAD-LOAD control dependency between the value of
7219 * dev_stats_ccnt and updating the on-disk values which requires
7220 * reading the in-memory counters. Such control dependencies
7221 * require explicit read memory barriers.
7223 * This memory barriers pairs with smp_mb__before_atomic in
7224 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7225 * barrier implied by atomic_xchg in
7226 * btrfs_dev_stats_read_and_reset
7228 smp_rmb();
7230 ret = update_dev_stat_item(trans, fs_info, device);
7231 if (!ret)
7232 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7234 mutex_unlock(&fs_devices->device_list_mutex);
7236 return ret;
7239 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7241 btrfs_dev_stat_inc(dev, index);
7242 btrfs_dev_stat_print_on_error(dev);
7245 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7247 if (!dev->dev_stats_valid)
7248 return;
7249 btrfs_err_rl_in_rcu(dev->fs_info,
7250 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7251 rcu_str_deref(dev->name),
7252 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7253 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7254 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7255 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7256 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7259 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7261 int i;
7263 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7264 if (btrfs_dev_stat_read(dev, i) != 0)
7265 break;
7266 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7267 return; /* all values == 0, suppress message */
7269 btrfs_info_in_rcu(dev->fs_info,
7270 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7271 rcu_str_deref(dev->name),
7272 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7273 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7274 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7275 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7276 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7279 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7280 struct btrfs_ioctl_get_dev_stats *stats)
7282 struct btrfs_device *dev;
7283 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7284 int i;
7286 mutex_lock(&fs_devices->device_list_mutex);
7287 dev = btrfs_find_device(fs_info, stats->devid, NULL, NULL);
7288 mutex_unlock(&fs_devices->device_list_mutex);
7290 if (!dev) {
7291 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7292 return -ENODEV;
7293 } else if (!dev->dev_stats_valid) {
7294 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7295 return -ENODEV;
7296 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7297 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7298 if (stats->nr_items > i)
7299 stats->values[i] =
7300 btrfs_dev_stat_read_and_reset(dev, i);
7301 else
7302 btrfs_dev_stat_reset(dev, i);
7304 } else {
7305 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7306 if (stats->nr_items > i)
7307 stats->values[i] = btrfs_dev_stat_read(dev, i);
7309 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7310 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7311 return 0;
7314 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7316 struct buffer_head *bh;
7317 struct btrfs_super_block *disk_super;
7318 int copy_num;
7320 if (!bdev)
7321 return;
7323 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7324 copy_num++) {
7326 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7327 continue;
7329 disk_super = (struct btrfs_super_block *)bh->b_data;
7331 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7332 set_buffer_dirty(bh);
7333 sync_dirty_buffer(bh);
7334 brelse(bh);
7337 /* Notify udev that device has changed */
7338 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7340 /* Update ctime/mtime for device path for libblkid */
7341 update_dev_time(device_path);
7345 * Update the size of all devices, which is used for writing out the
7346 * super blocks.
7348 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7350 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7351 struct btrfs_device *curr, *next;
7353 if (list_empty(&fs_devices->resized_devices))
7354 return;
7356 mutex_lock(&fs_devices->device_list_mutex);
7357 mutex_lock(&fs_info->chunk_mutex);
7358 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7359 resized_list) {
7360 list_del_init(&curr->resized_list);
7361 curr->commit_total_bytes = curr->disk_total_bytes;
7363 mutex_unlock(&fs_info->chunk_mutex);
7364 mutex_unlock(&fs_devices->device_list_mutex);
7367 /* Must be invoked during the transaction commit */
7368 void btrfs_update_commit_device_bytes_used(struct btrfs_transaction *trans)
7370 struct btrfs_fs_info *fs_info = trans->fs_info;
7371 struct extent_map *em;
7372 struct map_lookup *map;
7373 struct btrfs_device *dev;
7374 int i;
7376 if (list_empty(&trans->pending_chunks))
7377 return;
7379 /* In order to kick the device replace finish process */
7380 mutex_lock(&fs_info->chunk_mutex);
7381 list_for_each_entry(em, &trans->pending_chunks, list) {
7382 map = em->map_lookup;
7384 for (i = 0; i < map->num_stripes; i++) {
7385 dev = map->stripes[i].dev;
7386 dev->commit_bytes_used = dev->bytes_used;
7389 mutex_unlock(&fs_info->chunk_mutex);
7392 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7394 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7395 while (fs_devices) {
7396 fs_devices->fs_info = fs_info;
7397 fs_devices = fs_devices->seed;
7401 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7403 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7404 while (fs_devices) {
7405 fs_devices->fs_info = NULL;
7406 fs_devices = fs_devices->seed;