2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
18 #include <linux/sched.h>
19 #include <linux/bio.h>
20 #include <linux/slab.h>
21 #include <linux/buffer_head.h>
22 #include <linux/blkdev.h>
23 #include <linux/iocontext.h>
24 #include <linux/capability.h>
25 #include <linux/ratelimit.h>
26 #include <linux/kthread.h>
27 #include <linux/raid/pq.h>
28 #include <linux/semaphore.h>
29 #include <linux/uuid.h>
30 #include <asm/div64.h>
32 #include "extent_map.h"
34 #include "transaction.h"
35 #include "print-tree.h"
38 #include "async-thread.h"
39 #include "check-integrity.h"
40 #include "rcu-string.h"
42 #include "dev-replace.h"
45 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
46 [BTRFS_RAID_RAID10] = {
49 .devs_max = 0, /* 0 == as many as possible */
51 .tolerated_failures = 1,
55 [BTRFS_RAID_RAID1] = {
60 .tolerated_failures = 1,
69 .tolerated_failures = 0,
73 [BTRFS_RAID_RAID0] = {
78 .tolerated_failures = 0,
82 [BTRFS_RAID_SINGLE] = {
87 .tolerated_failures = 0,
91 [BTRFS_RAID_RAID5] = {
96 .tolerated_failures = 1,
100 [BTRFS_RAID_RAID6] = {
105 .tolerated_failures = 2,
111 const u64 btrfs_raid_group[BTRFS_NR_RAID_TYPES] = {
112 [BTRFS_RAID_RAID10] = BTRFS_BLOCK_GROUP_RAID10,
113 [BTRFS_RAID_RAID1] = BTRFS_BLOCK_GROUP_RAID1,
114 [BTRFS_RAID_DUP] = BTRFS_BLOCK_GROUP_DUP,
115 [BTRFS_RAID_RAID0] = BTRFS_BLOCK_GROUP_RAID0,
116 [BTRFS_RAID_SINGLE] = 0,
117 [BTRFS_RAID_RAID5] = BTRFS_BLOCK_GROUP_RAID5,
118 [BTRFS_RAID_RAID6] = BTRFS_BLOCK_GROUP_RAID6,
122 * Table to convert BTRFS_RAID_* to the error code if minimum number of devices
123 * condition is not met. Zero means there's no corresponding
124 * BTRFS_ERROR_DEV_*_NOT_MET value.
126 const int btrfs_raid_mindev_error[BTRFS_NR_RAID_TYPES] = {
127 [BTRFS_RAID_RAID10] = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
128 [BTRFS_RAID_RAID1] = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
129 [BTRFS_RAID_DUP] = 0,
130 [BTRFS_RAID_RAID0] = 0,
131 [BTRFS_RAID_SINGLE] = 0,
132 [BTRFS_RAID_RAID5] = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
133 [BTRFS_RAID_RAID6] = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
136 static int init_first_rw_device(struct btrfs_trans_handle *trans,
137 struct btrfs_fs_info *fs_info);
138 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
139 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
140 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
141 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
142 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
143 enum btrfs_map_op op,
144 u64 logical, u64 *length,
145 struct btrfs_bio **bbio_ret,
146 int mirror_num, int need_raid_map);
152 * There are several mutexes that protect manipulation of devices and low-level
153 * structures like chunks but not block groups, extents or files
155 * uuid_mutex (global lock)
156 * ------------------------
157 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
158 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
159 * device) or requested by the device= mount option
161 * the mutex can be very coarse and can cover long-running operations
163 * protects: updates to fs_devices counters like missing devices, rw devices,
164 * seeding, structure cloning, openning/closing devices at mount/umount time
166 * global::fs_devs - add, remove, updates to the global list
168 * does not protect: manipulation of the fs_devices::devices list!
170 * btrfs_device::name - renames (write side), read is RCU
172 * fs_devices::device_list_mutex (per-fs, with RCU)
173 * ------------------------------------------------
174 * protects updates to fs_devices::devices, ie. adding and deleting
176 * simple list traversal with read-only actions can be done with RCU protection
178 * may be used to exclude some operations from running concurrently without any
179 * modifications to the list (see write_all_supers)
183 * coarse lock owned by a mounted filesystem; used to exclude some operations
184 * that cannot run in parallel and affect the higher-level properties of the
185 * filesystem like: device add/deleting/resize/replace, or balance
189 * protects balance structures (status, state) and context accessed from
190 * several places (internally, ioctl)
194 * protects chunks, adding or removing during allocation, trim or when a new
195 * device is added/removed
199 * a big lock that is held by the cleaner thread and prevents running subvolume
200 * cleaning together with relocation or delayed iputs
213 DEFINE_MUTEX(uuid_mutex);
214 static LIST_HEAD(fs_uuids);
215 struct list_head *btrfs_get_fs_uuids(void)
221 * alloc_fs_devices - allocate struct btrfs_fs_devices
222 * @fsid: if not NULL, copy the uuid to fs_devices::fsid
224 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
225 * The returned struct is not linked onto any lists and can be destroyed with
226 * kfree() right away.
228 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
230 struct btrfs_fs_devices *fs_devs;
232 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
234 return ERR_PTR(-ENOMEM);
236 mutex_init(&fs_devs->device_list_mutex);
238 INIT_LIST_HEAD(&fs_devs->devices);
239 INIT_LIST_HEAD(&fs_devs->resized_devices);
240 INIT_LIST_HEAD(&fs_devs->alloc_list);
241 INIT_LIST_HEAD(&fs_devs->list);
243 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
248 static void free_device(struct btrfs_device *device)
250 rcu_string_free(device->name);
251 bio_put(device->flush_bio);
255 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
257 struct btrfs_device *device;
258 WARN_ON(fs_devices->opened);
259 while (!list_empty(&fs_devices->devices)) {
260 device = list_entry(fs_devices->devices.next,
261 struct btrfs_device, dev_list);
262 list_del(&device->dev_list);
268 static void btrfs_kobject_uevent(struct block_device *bdev,
269 enum kobject_action action)
273 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
275 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
277 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
278 &disk_to_dev(bdev->bd_disk)->kobj);
281 void btrfs_cleanup_fs_uuids(void)
283 struct btrfs_fs_devices *fs_devices;
285 while (!list_empty(&fs_uuids)) {
286 fs_devices = list_entry(fs_uuids.next,
287 struct btrfs_fs_devices, list);
288 list_del(&fs_devices->list);
289 free_fs_devices(fs_devices);
294 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
295 * Returned struct is not linked onto any lists and must be destroyed using
298 static struct btrfs_device *__alloc_device(void)
300 struct btrfs_device *dev;
302 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
304 return ERR_PTR(-ENOMEM);
307 * Preallocate a bio that's always going to be used for flushing device
308 * barriers and matches the device lifespan
310 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
311 if (!dev->flush_bio) {
313 return ERR_PTR(-ENOMEM);
316 INIT_LIST_HEAD(&dev->dev_list);
317 INIT_LIST_HEAD(&dev->dev_alloc_list);
318 INIT_LIST_HEAD(&dev->resized_list);
320 spin_lock_init(&dev->io_lock);
322 spin_lock_init(&dev->reada_lock);
323 atomic_set(&dev->reada_in_flight, 0);
324 atomic_set(&dev->dev_stats_ccnt, 0);
325 btrfs_device_data_ordered_init(dev);
326 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
327 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
333 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
336 * If devid and uuid are both specified, the match must be exact, otherwise
337 * only devid is used.
339 static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,
340 u64 devid, const u8 *uuid)
342 struct list_head *head = &fs_devices->devices;
343 struct btrfs_device *dev;
345 list_for_each_entry(dev, head, dev_list) {
346 if (dev->devid == devid &&
347 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
354 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
356 struct btrfs_fs_devices *fs_devices;
358 list_for_each_entry(fs_devices, &fs_uuids, list) {
359 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
366 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
367 int flush, struct block_device **bdev,
368 struct buffer_head **bh)
372 *bdev = blkdev_get_by_path(device_path, flags, holder);
375 ret = PTR_ERR(*bdev);
380 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
381 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
383 blkdev_put(*bdev, flags);
386 invalidate_bdev(*bdev);
387 *bh = btrfs_read_dev_super(*bdev);
390 blkdev_put(*bdev, flags);
402 static void requeue_list(struct btrfs_pending_bios *pending_bios,
403 struct bio *head, struct bio *tail)
406 struct bio *old_head;
408 old_head = pending_bios->head;
409 pending_bios->head = head;
410 if (pending_bios->tail)
411 tail->bi_next = old_head;
413 pending_bios->tail = tail;
417 * we try to collect pending bios for a device so we don't get a large
418 * number of procs sending bios down to the same device. This greatly
419 * improves the schedulers ability to collect and merge the bios.
421 * But, it also turns into a long list of bios to process and that is sure
422 * to eventually make the worker thread block. The solution here is to
423 * make some progress and then put this work struct back at the end of
424 * the list if the block device is congested. This way, multiple devices
425 * can make progress from a single worker thread.
427 static noinline void run_scheduled_bios(struct btrfs_device *device)
429 struct btrfs_fs_info *fs_info = device->fs_info;
431 struct backing_dev_info *bdi;
432 struct btrfs_pending_bios *pending_bios;
436 unsigned long num_run;
437 unsigned long batch_run = 0;
438 unsigned long last_waited = 0;
440 int sync_pending = 0;
441 struct blk_plug plug;
444 * this function runs all the bios we've collected for
445 * a particular device. We don't want to wander off to
446 * another device without first sending all of these down.
447 * So, setup a plug here and finish it off before we return
449 blk_start_plug(&plug);
451 bdi = device->bdev->bd_bdi;
454 spin_lock(&device->io_lock);
459 /* take all the bios off the list at once and process them
460 * later on (without the lock held). But, remember the
461 * tail and other pointers so the bios can be properly reinserted
462 * into the list if we hit congestion
464 if (!force_reg && device->pending_sync_bios.head) {
465 pending_bios = &device->pending_sync_bios;
468 pending_bios = &device->pending_bios;
472 pending = pending_bios->head;
473 tail = pending_bios->tail;
474 WARN_ON(pending && !tail);
477 * if pending was null this time around, no bios need processing
478 * at all and we can stop. Otherwise it'll loop back up again
479 * and do an additional check so no bios are missed.
481 * device->running_pending is used to synchronize with the
484 if (device->pending_sync_bios.head == NULL &&
485 device->pending_bios.head == NULL) {
487 device->running_pending = 0;
490 device->running_pending = 1;
493 pending_bios->head = NULL;
494 pending_bios->tail = NULL;
496 spin_unlock(&device->io_lock);
501 /* we want to work on both lists, but do more bios on the
502 * sync list than the regular list
505 pending_bios != &device->pending_sync_bios &&
506 device->pending_sync_bios.head) ||
507 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
508 device->pending_bios.head)) {
509 spin_lock(&device->io_lock);
510 requeue_list(pending_bios, pending, tail);
515 pending = pending->bi_next;
518 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
521 * if we're doing the sync list, record that our
522 * plug has some sync requests on it
524 * If we're doing the regular list and there are
525 * sync requests sitting around, unplug before
528 if (pending_bios == &device->pending_sync_bios) {
530 } else if (sync_pending) {
531 blk_finish_plug(&plug);
532 blk_start_plug(&plug);
536 btrfsic_submit_bio(cur);
543 * we made progress, there is more work to do and the bdi
544 * is now congested. Back off and let other work structs
547 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
548 fs_info->fs_devices->open_devices > 1) {
549 struct io_context *ioc;
551 ioc = current->io_context;
554 * the main goal here is that we don't want to
555 * block if we're going to be able to submit
556 * more requests without blocking.
558 * This code does two great things, it pokes into
559 * the elevator code from a filesystem _and_
560 * it makes assumptions about how batching works.
562 if (ioc && ioc->nr_batch_requests > 0 &&
563 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
565 ioc->last_waited == last_waited)) {
567 * we want to go through our batch of
568 * requests and stop. So, we copy out
569 * the ioc->last_waited time and test
570 * against it before looping
572 last_waited = ioc->last_waited;
576 spin_lock(&device->io_lock);
577 requeue_list(pending_bios, pending, tail);
578 device->running_pending = 1;
580 spin_unlock(&device->io_lock);
581 btrfs_queue_work(fs_info->submit_workers,
591 spin_lock(&device->io_lock);
592 if (device->pending_bios.head || device->pending_sync_bios.head)
594 spin_unlock(&device->io_lock);
597 blk_finish_plug(&plug);
600 static void pending_bios_fn(struct btrfs_work *work)
602 struct btrfs_device *device;
604 device = container_of(work, struct btrfs_device, work);
605 run_scheduled_bios(device);
609 static void btrfs_free_stale_device(struct btrfs_device *cur_dev)
611 struct btrfs_fs_devices *fs_devs;
612 struct btrfs_device *dev;
617 list_for_each_entry(fs_devs, &fs_uuids, list) {
622 if (fs_devs->seeding)
625 list_for_each_entry(dev, &fs_devs->devices, dev_list) {
633 * Todo: This won't be enough. What if the same device
634 * comes back (with new uuid and) with its mapper path?
635 * But for now, this does help as mostly an admin will
636 * either use mapper or non mapper path throughout.
639 del = strcmp(rcu_str_deref(dev->name),
640 rcu_str_deref(cur_dev->name));
647 /* delete the stale device */
648 if (fs_devs->num_devices == 1) {
649 btrfs_sysfs_remove_fsid(fs_devs);
650 list_del(&fs_devs->list);
651 free_fs_devices(fs_devs);
653 fs_devs->num_devices--;
654 list_del(&dev->dev_list);
662 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
663 struct btrfs_device *device, fmode_t flags,
666 struct request_queue *q;
667 struct block_device *bdev;
668 struct buffer_head *bh;
669 struct btrfs_super_block *disk_super;
678 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
683 disk_super = (struct btrfs_super_block *)bh->b_data;
684 devid = btrfs_stack_device_id(&disk_super->dev_item);
685 if (devid != device->devid)
688 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
691 device->generation = btrfs_super_generation(disk_super);
693 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
694 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
695 fs_devices->seeding = 1;
697 if (bdev_read_only(bdev))
698 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
700 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
703 q = bdev_get_queue(bdev);
704 if (!blk_queue_nonrot(q))
705 fs_devices->rotating = 1;
708 device->in_fs_metadata = 0;
709 device->mode = flags;
711 fs_devices->open_devices++;
712 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
713 device->devid != BTRFS_DEV_REPLACE_DEVID) {
714 fs_devices->rw_devices++;
715 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
723 blkdev_put(bdev, flags);
729 * Add new device to list of registered devices
732 * 1 - first time device is seen
733 * 0 - device already known
736 static noinline int device_list_add(const char *path,
737 struct btrfs_super_block *disk_super,
738 u64 devid, struct btrfs_fs_devices **fs_devices_ret)
740 struct btrfs_device *device;
741 struct btrfs_fs_devices *fs_devices;
742 struct rcu_string *name;
744 u64 found_transid = btrfs_super_generation(disk_super);
746 fs_devices = find_fsid(disk_super->fsid);
748 fs_devices = alloc_fs_devices(disk_super->fsid);
749 if (IS_ERR(fs_devices))
750 return PTR_ERR(fs_devices);
752 list_add(&fs_devices->list, &fs_uuids);
756 device = find_device(fs_devices, devid,
757 disk_super->dev_item.uuid);
761 if (fs_devices->opened)
764 device = btrfs_alloc_device(NULL, &devid,
765 disk_super->dev_item.uuid);
766 if (IS_ERR(device)) {
767 /* we can safely leave the fs_devices entry around */
768 return PTR_ERR(device);
771 name = rcu_string_strdup(path, GFP_NOFS);
776 rcu_assign_pointer(device->name, name);
778 mutex_lock(&fs_devices->device_list_mutex);
779 list_add_rcu(&device->dev_list, &fs_devices->devices);
780 fs_devices->num_devices++;
781 mutex_unlock(&fs_devices->device_list_mutex);
784 device->fs_devices = fs_devices;
785 } else if (!device->name || strcmp(device->name->str, path)) {
787 * When FS is already mounted.
788 * 1. If you are here and if the device->name is NULL that
789 * means this device was missing at time of FS mount.
790 * 2. If you are here and if the device->name is different
791 * from 'path' that means either
792 * a. The same device disappeared and reappeared with
794 * b. The missing-disk-which-was-replaced, has
797 * We must allow 1 and 2a above. But 2b would be a spurious
800 * Further in case of 1 and 2a above, the disk at 'path'
801 * would have missed some transaction when it was away and
802 * in case of 2a the stale bdev has to be updated as well.
803 * 2b must not be allowed at all time.
807 * For now, we do allow update to btrfs_fs_device through the
808 * btrfs dev scan cli after FS has been mounted. We're still
809 * tracking a problem where systems fail mount by subvolume id
810 * when we reject replacement on a mounted FS.
812 if (!fs_devices->opened && found_transid < device->generation) {
814 * That is if the FS is _not_ mounted and if you
815 * are here, that means there is more than one
816 * disk with same uuid and devid.We keep the one
817 * with larger generation number or the last-in if
818 * generation are equal.
823 name = rcu_string_strdup(path, GFP_NOFS);
826 rcu_string_free(device->name);
827 rcu_assign_pointer(device->name, name);
828 if (device->missing) {
829 fs_devices->missing_devices--;
835 * Unmount does not free the btrfs_device struct but would zero
836 * generation along with most of the other members. So just update
837 * it back. We need it to pick the disk with largest generation
840 if (!fs_devices->opened)
841 device->generation = found_transid;
844 * if there is new btrfs on an already registered device,
845 * then remove the stale device entry.
848 btrfs_free_stale_device(device);
850 *fs_devices_ret = fs_devices;
855 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
857 struct btrfs_fs_devices *fs_devices;
858 struct btrfs_device *device;
859 struct btrfs_device *orig_dev;
861 fs_devices = alloc_fs_devices(orig->fsid);
862 if (IS_ERR(fs_devices))
865 mutex_lock(&orig->device_list_mutex);
866 fs_devices->total_devices = orig->total_devices;
868 /* We have held the volume lock, it is safe to get the devices. */
869 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
870 struct rcu_string *name;
872 device = btrfs_alloc_device(NULL, &orig_dev->devid,
878 * This is ok to do without rcu read locked because we hold the
879 * uuid mutex so nothing we touch in here is going to disappear.
881 if (orig_dev->name) {
882 name = rcu_string_strdup(orig_dev->name->str,
888 rcu_assign_pointer(device->name, name);
891 list_add(&device->dev_list, &fs_devices->devices);
892 device->fs_devices = fs_devices;
893 fs_devices->num_devices++;
895 mutex_unlock(&orig->device_list_mutex);
898 mutex_unlock(&orig->device_list_mutex);
899 free_fs_devices(fs_devices);
900 return ERR_PTR(-ENOMEM);
903 void btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices, int step)
905 struct btrfs_device *device, *next;
906 struct btrfs_device *latest_dev = NULL;
908 mutex_lock(&uuid_mutex);
910 /* This is the initialized path, it is safe to release the devices. */
911 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
912 if (device->in_fs_metadata) {
913 if (!device->is_tgtdev_for_dev_replace &&
915 device->generation > latest_dev->generation)) {
921 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
923 * In the first step, keep the device which has
924 * the correct fsid and the devid that is used
925 * for the dev_replace procedure.
926 * In the second step, the dev_replace state is
927 * read from the device tree and it is known
928 * whether the procedure is really active or
929 * not, which means whether this device is
930 * used or whether it should be removed.
932 if (step == 0 || device->is_tgtdev_for_dev_replace) {
937 blkdev_put(device->bdev, device->mode);
939 fs_devices->open_devices--;
941 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
942 list_del_init(&device->dev_alloc_list);
943 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
944 if (!device->is_tgtdev_for_dev_replace)
945 fs_devices->rw_devices--;
947 list_del_init(&device->dev_list);
948 fs_devices->num_devices--;
952 if (fs_devices->seed) {
953 fs_devices = fs_devices->seed;
957 fs_devices->latest_bdev = latest_dev->bdev;
959 mutex_unlock(&uuid_mutex);
962 static void free_device_rcu(struct rcu_head *head)
964 struct btrfs_device *device;
966 device = container_of(head, struct btrfs_device, rcu);
970 static void btrfs_close_bdev(struct btrfs_device *device)
975 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
976 sync_blockdev(device->bdev);
977 invalidate_bdev(device->bdev);
980 blkdev_put(device->bdev, device->mode);
983 static void btrfs_prepare_close_one_device(struct btrfs_device *device)
985 struct btrfs_fs_devices *fs_devices = device->fs_devices;
986 struct btrfs_device *new_device;
987 struct rcu_string *name;
990 fs_devices->open_devices--;
992 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
993 device->devid != BTRFS_DEV_REPLACE_DEVID) {
994 list_del_init(&device->dev_alloc_list);
995 fs_devices->rw_devices--;
999 fs_devices->missing_devices--;
1001 new_device = btrfs_alloc_device(NULL, &device->devid,
1003 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1005 /* Safe because we are under uuid_mutex */
1007 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1008 BUG_ON(!name); /* -ENOMEM */
1009 rcu_assign_pointer(new_device->name, name);
1012 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1013 new_device->fs_devices = device->fs_devices;
1016 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1018 struct btrfs_device *device, *tmp;
1019 struct list_head pending_put;
1021 INIT_LIST_HEAD(&pending_put);
1023 if (--fs_devices->opened > 0)
1026 mutex_lock(&fs_devices->device_list_mutex);
1027 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1028 btrfs_prepare_close_one_device(device);
1029 list_add(&device->dev_list, &pending_put);
1031 mutex_unlock(&fs_devices->device_list_mutex);
1034 * btrfs_show_devname() is using the device_list_mutex,
1035 * sometimes call to blkdev_put() leads vfs calling
1036 * into this func. So do put outside of device_list_mutex,
1039 while (!list_empty(&pending_put)) {
1040 device = list_first_entry(&pending_put,
1041 struct btrfs_device, dev_list);
1042 list_del(&device->dev_list);
1043 btrfs_close_bdev(device);
1044 call_rcu(&device->rcu, free_device_rcu);
1047 WARN_ON(fs_devices->open_devices);
1048 WARN_ON(fs_devices->rw_devices);
1049 fs_devices->opened = 0;
1050 fs_devices->seeding = 0;
1055 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1057 struct btrfs_fs_devices *seed_devices = NULL;
1060 mutex_lock(&uuid_mutex);
1061 ret = __btrfs_close_devices(fs_devices);
1062 if (!fs_devices->opened) {
1063 seed_devices = fs_devices->seed;
1064 fs_devices->seed = NULL;
1066 mutex_unlock(&uuid_mutex);
1068 while (seed_devices) {
1069 fs_devices = seed_devices;
1070 seed_devices = fs_devices->seed;
1071 __btrfs_close_devices(fs_devices);
1072 free_fs_devices(fs_devices);
1077 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1078 fmode_t flags, void *holder)
1080 struct list_head *head = &fs_devices->devices;
1081 struct btrfs_device *device;
1082 struct btrfs_device *latest_dev = NULL;
1085 flags |= FMODE_EXCL;
1087 list_for_each_entry(device, head, dev_list) {
1088 /* Just open everything we can; ignore failures here */
1089 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1093 device->generation > latest_dev->generation)
1094 latest_dev = device;
1096 if (fs_devices->open_devices == 0) {
1100 fs_devices->opened = 1;
1101 fs_devices->latest_bdev = latest_dev->bdev;
1102 fs_devices->total_rw_bytes = 0;
1107 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1108 fmode_t flags, void *holder)
1112 mutex_lock(&uuid_mutex);
1113 if (fs_devices->opened) {
1114 fs_devices->opened++;
1117 ret = __btrfs_open_devices(fs_devices, flags, holder);
1119 mutex_unlock(&uuid_mutex);
1123 static void btrfs_release_disk_super(struct page *page)
1129 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1131 struct btrfs_super_block **disk_super)
1136 /* make sure our super fits in the device */
1137 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1140 /* make sure our super fits in the page */
1141 if (sizeof(**disk_super) > PAGE_SIZE)
1144 /* make sure our super doesn't straddle pages on disk */
1145 index = bytenr >> PAGE_SHIFT;
1146 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1149 /* pull in the page with our super */
1150 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1153 if (IS_ERR_OR_NULL(*page))
1158 /* align our pointer to the offset of the super block */
1159 *disk_super = p + (bytenr & ~PAGE_MASK);
1161 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1162 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1163 btrfs_release_disk_super(*page);
1167 if ((*disk_super)->label[0] &&
1168 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1169 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1175 * Look for a btrfs signature on a device. This may be called out of the mount path
1176 * and we are not allowed to call set_blocksize during the scan. The superblock
1177 * is read via pagecache
1179 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
1180 struct btrfs_fs_devices **fs_devices_ret)
1182 struct btrfs_super_block *disk_super;
1183 struct block_device *bdev;
1192 * we would like to check all the supers, but that would make
1193 * a btrfs mount succeed after a mkfs from a different FS.
1194 * So, we need to add a special mount option to scan for
1195 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1197 bytenr = btrfs_sb_offset(0);
1198 flags |= FMODE_EXCL;
1199 mutex_lock(&uuid_mutex);
1201 bdev = blkdev_get_by_path(path, flags, holder);
1203 ret = PTR_ERR(bdev);
1207 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super))
1208 goto error_bdev_put;
1210 devid = btrfs_stack_device_id(&disk_super->dev_item);
1211 transid = btrfs_super_generation(disk_super);
1212 total_devices = btrfs_super_num_devices(disk_super);
1214 ret = device_list_add(path, disk_super, devid, fs_devices_ret);
1216 if (disk_super->label[0]) {
1217 pr_info("BTRFS: device label %s ", disk_super->label);
1219 pr_info("BTRFS: device fsid %pU ", disk_super->fsid);
1222 pr_cont("devid %llu transid %llu %s\n", devid, transid, path);
1225 if (!ret && fs_devices_ret)
1226 (*fs_devices_ret)->total_devices = total_devices;
1228 btrfs_release_disk_super(page);
1231 blkdev_put(bdev, flags);
1233 mutex_unlock(&uuid_mutex);
1237 /* helper to account the used device space in the range */
1238 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1239 u64 end, u64 *length)
1241 struct btrfs_key key;
1242 struct btrfs_root *root = device->fs_info->dev_root;
1243 struct btrfs_dev_extent *dev_extent;
1244 struct btrfs_path *path;
1248 struct extent_buffer *l;
1252 if (start >= device->total_bytes || device->is_tgtdev_for_dev_replace)
1255 path = btrfs_alloc_path();
1258 path->reada = READA_FORWARD;
1260 key.objectid = device->devid;
1262 key.type = BTRFS_DEV_EXTENT_KEY;
1264 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1268 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1275 slot = path->slots[0];
1276 if (slot >= btrfs_header_nritems(l)) {
1277 ret = btrfs_next_leaf(root, path);
1285 btrfs_item_key_to_cpu(l, &key, slot);
1287 if (key.objectid < device->devid)
1290 if (key.objectid > device->devid)
1293 if (key.type != BTRFS_DEV_EXTENT_KEY)
1296 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1297 extent_end = key.offset + btrfs_dev_extent_length(l,
1299 if (key.offset <= start && extent_end > end) {
1300 *length = end - start + 1;
1302 } else if (key.offset <= start && extent_end > start)
1303 *length += extent_end - start;
1304 else if (key.offset > start && extent_end <= end)
1305 *length += extent_end - key.offset;
1306 else if (key.offset > start && key.offset <= end) {
1307 *length += end - key.offset + 1;
1309 } else if (key.offset > end)
1317 btrfs_free_path(path);
1321 static int contains_pending_extent(struct btrfs_transaction *transaction,
1322 struct btrfs_device *device,
1323 u64 *start, u64 len)
1325 struct btrfs_fs_info *fs_info = device->fs_info;
1326 struct extent_map *em;
1327 struct list_head *search_list = &fs_info->pinned_chunks;
1329 u64 physical_start = *start;
1332 search_list = &transaction->pending_chunks;
1334 list_for_each_entry(em, search_list, list) {
1335 struct map_lookup *map;
1338 map = em->map_lookup;
1339 for (i = 0; i < map->num_stripes; i++) {
1342 if (map->stripes[i].dev != device)
1344 if (map->stripes[i].physical >= physical_start + len ||
1345 map->stripes[i].physical + em->orig_block_len <=
1349 * Make sure that while processing the pinned list we do
1350 * not override our *start with a lower value, because
1351 * we can have pinned chunks that fall within this
1352 * device hole and that have lower physical addresses
1353 * than the pending chunks we processed before. If we
1354 * do not take this special care we can end up getting
1355 * 2 pending chunks that start at the same physical
1356 * device offsets because the end offset of a pinned
1357 * chunk can be equal to the start offset of some
1360 end = map->stripes[i].physical + em->orig_block_len;
1367 if (search_list != &fs_info->pinned_chunks) {
1368 search_list = &fs_info->pinned_chunks;
1377 * find_free_dev_extent_start - find free space in the specified device
1378 * @device: the device which we search the free space in
1379 * @num_bytes: the size of the free space that we need
1380 * @search_start: the position from which to begin the search
1381 * @start: store the start of the free space.
1382 * @len: the size of the free space. that we find, or the size
1383 * of the max free space if we don't find suitable free space
1385 * this uses a pretty simple search, the expectation is that it is
1386 * called very infrequently and that a given device has a small number
1389 * @start is used to store the start of the free space if we find. But if we
1390 * don't find suitable free space, it will be used to store the start position
1391 * of the max free space.
1393 * @len is used to store the size of the free space that we find.
1394 * But if we don't find suitable free space, it is used to store the size of
1395 * the max free space.
1397 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1398 struct btrfs_device *device, u64 num_bytes,
1399 u64 search_start, u64 *start, u64 *len)
1401 struct btrfs_fs_info *fs_info = device->fs_info;
1402 struct btrfs_root *root = fs_info->dev_root;
1403 struct btrfs_key key;
1404 struct btrfs_dev_extent *dev_extent;
1405 struct btrfs_path *path;
1410 u64 search_end = device->total_bytes;
1413 struct extent_buffer *l;
1416 * We don't want to overwrite the superblock on the drive nor any area
1417 * used by the boot loader (grub for example), so we make sure to start
1418 * at an offset of at least 1MB.
1420 search_start = max_t(u64, search_start, SZ_1M);
1422 path = btrfs_alloc_path();
1426 max_hole_start = search_start;
1430 if (search_start >= search_end || device->is_tgtdev_for_dev_replace) {
1435 path->reada = READA_FORWARD;
1436 path->search_commit_root = 1;
1437 path->skip_locking = 1;
1439 key.objectid = device->devid;
1440 key.offset = search_start;
1441 key.type = BTRFS_DEV_EXTENT_KEY;
1443 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1447 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1454 slot = path->slots[0];
1455 if (slot >= btrfs_header_nritems(l)) {
1456 ret = btrfs_next_leaf(root, path);
1464 btrfs_item_key_to_cpu(l, &key, slot);
1466 if (key.objectid < device->devid)
1469 if (key.objectid > device->devid)
1472 if (key.type != BTRFS_DEV_EXTENT_KEY)
1475 if (key.offset > search_start) {
1476 hole_size = key.offset - search_start;
1479 * Have to check before we set max_hole_start, otherwise
1480 * we could end up sending back this offset anyway.
1482 if (contains_pending_extent(transaction, device,
1485 if (key.offset >= search_start) {
1486 hole_size = key.offset - search_start;
1493 if (hole_size > max_hole_size) {
1494 max_hole_start = search_start;
1495 max_hole_size = hole_size;
1499 * If this free space is greater than which we need,
1500 * it must be the max free space that we have found
1501 * until now, so max_hole_start must point to the start
1502 * of this free space and the length of this free space
1503 * is stored in max_hole_size. Thus, we return
1504 * max_hole_start and max_hole_size and go back to the
1507 if (hole_size >= num_bytes) {
1513 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1514 extent_end = key.offset + btrfs_dev_extent_length(l,
1516 if (extent_end > search_start)
1517 search_start = extent_end;
1524 * At this point, search_start should be the end of
1525 * allocated dev extents, and when shrinking the device,
1526 * search_end may be smaller than search_start.
1528 if (search_end > search_start) {
1529 hole_size = search_end - search_start;
1531 if (contains_pending_extent(transaction, device, &search_start,
1533 btrfs_release_path(path);
1537 if (hole_size > max_hole_size) {
1538 max_hole_start = search_start;
1539 max_hole_size = hole_size;
1544 if (max_hole_size < num_bytes)
1550 btrfs_free_path(path);
1551 *start = max_hole_start;
1553 *len = max_hole_size;
1557 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1558 struct btrfs_device *device, u64 num_bytes,
1559 u64 *start, u64 *len)
1561 /* FIXME use last free of some kind */
1562 return find_free_dev_extent_start(trans->transaction, device,
1563 num_bytes, 0, start, len);
1566 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1567 struct btrfs_device *device,
1568 u64 start, u64 *dev_extent_len)
1570 struct btrfs_fs_info *fs_info = device->fs_info;
1571 struct btrfs_root *root = fs_info->dev_root;
1573 struct btrfs_path *path;
1574 struct btrfs_key key;
1575 struct btrfs_key found_key;
1576 struct extent_buffer *leaf = NULL;
1577 struct btrfs_dev_extent *extent = NULL;
1579 path = btrfs_alloc_path();
1583 key.objectid = device->devid;
1585 key.type = BTRFS_DEV_EXTENT_KEY;
1587 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1589 ret = btrfs_previous_item(root, path, key.objectid,
1590 BTRFS_DEV_EXTENT_KEY);
1593 leaf = path->nodes[0];
1594 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1595 extent = btrfs_item_ptr(leaf, path->slots[0],
1596 struct btrfs_dev_extent);
1597 BUG_ON(found_key.offset > start || found_key.offset +
1598 btrfs_dev_extent_length(leaf, extent) < start);
1600 btrfs_release_path(path);
1602 } else if (ret == 0) {
1603 leaf = path->nodes[0];
1604 extent = btrfs_item_ptr(leaf, path->slots[0],
1605 struct btrfs_dev_extent);
1607 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1611 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1613 ret = btrfs_del_item(trans, root, path);
1615 btrfs_handle_fs_error(fs_info, ret,
1616 "Failed to remove dev extent item");
1618 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1621 btrfs_free_path(path);
1625 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1626 struct btrfs_device *device,
1627 u64 chunk_offset, u64 start, u64 num_bytes)
1630 struct btrfs_path *path;
1631 struct btrfs_fs_info *fs_info = device->fs_info;
1632 struct btrfs_root *root = fs_info->dev_root;
1633 struct btrfs_dev_extent *extent;
1634 struct extent_buffer *leaf;
1635 struct btrfs_key key;
1637 WARN_ON(!device->in_fs_metadata);
1638 WARN_ON(device->is_tgtdev_for_dev_replace);
1639 path = btrfs_alloc_path();
1643 key.objectid = device->devid;
1645 key.type = BTRFS_DEV_EXTENT_KEY;
1646 ret = btrfs_insert_empty_item(trans, root, path, &key,
1651 leaf = path->nodes[0];
1652 extent = btrfs_item_ptr(leaf, path->slots[0],
1653 struct btrfs_dev_extent);
1654 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1655 BTRFS_CHUNK_TREE_OBJECTID);
1656 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1657 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1658 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1660 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1661 btrfs_mark_buffer_dirty(leaf);
1663 btrfs_free_path(path);
1667 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1669 struct extent_map_tree *em_tree;
1670 struct extent_map *em;
1674 em_tree = &fs_info->mapping_tree.map_tree;
1675 read_lock(&em_tree->lock);
1676 n = rb_last(&em_tree->map);
1678 em = rb_entry(n, struct extent_map, rb_node);
1679 ret = em->start + em->len;
1681 read_unlock(&em_tree->lock);
1686 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1690 struct btrfs_key key;
1691 struct btrfs_key found_key;
1692 struct btrfs_path *path;
1694 path = btrfs_alloc_path();
1698 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1699 key.type = BTRFS_DEV_ITEM_KEY;
1700 key.offset = (u64)-1;
1702 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1706 BUG_ON(ret == 0); /* Corruption */
1708 ret = btrfs_previous_item(fs_info->chunk_root, path,
1709 BTRFS_DEV_ITEMS_OBJECTID,
1710 BTRFS_DEV_ITEM_KEY);
1714 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1716 *devid_ret = found_key.offset + 1;
1720 btrfs_free_path(path);
1725 * the device information is stored in the chunk root
1726 * the btrfs_device struct should be fully filled in
1728 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1729 struct btrfs_fs_info *fs_info,
1730 struct btrfs_device *device)
1732 struct btrfs_root *root = fs_info->chunk_root;
1734 struct btrfs_path *path;
1735 struct btrfs_dev_item *dev_item;
1736 struct extent_buffer *leaf;
1737 struct btrfs_key key;
1740 path = btrfs_alloc_path();
1744 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1745 key.type = BTRFS_DEV_ITEM_KEY;
1746 key.offset = device->devid;
1748 ret = btrfs_insert_empty_item(trans, root, path, &key,
1753 leaf = path->nodes[0];
1754 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1756 btrfs_set_device_id(leaf, dev_item, device->devid);
1757 btrfs_set_device_generation(leaf, dev_item, 0);
1758 btrfs_set_device_type(leaf, dev_item, device->type);
1759 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1760 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1761 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1762 btrfs_set_device_total_bytes(leaf, dev_item,
1763 btrfs_device_get_disk_total_bytes(device));
1764 btrfs_set_device_bytes_used(leaf, dev_item,
1765 btrfs_device_get_bytes_used(device));
1766 btrfs_set_device_group(leaf, dev_item, 0);
1767 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1768 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1769 btrfs_set_device_start_offset(leaf, dev_item, 0);
1771 ptr = btrfs_device_uuid(dev_item);
1772 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1773 ptr = btrfs_device_fsid(dev_item);
1774 write_extent_buffer(leaf, fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1775 btrfs_mark_buffer_dirty(leaf);
1779 btrfs_free_path(path);
1784 * Function to update ctime/mtime for a given device path.
1785 * Mainly used for ctime/mtime based probe like libblkid.
1787 static void update_dev_time(const char *path_name)
1791 filp = filp_open(path_name, O_RDWR, 0);
1794 file_update_time(filp);
1795 filp_close(filp, NULL);
1798 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1799 struct btrfs_device *device)
1801 struct btrfs_root *root = fs_info->chunk_root;
1803 struct btrfs_path *path;
1804 struct btrfs_key key;
1805 struct btrfs_trans_handle *trans;
1807 path = btrfs_alloc_path();
1811 trans = btrfs_start_transaction(root, 0);
1812 if (IS_ERR(trans)) {
1813 btrfs_free_path(path);
1814 return PTR_ERR(trans);
1816 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1817 key.type = BTRFS_DEV_ITEM_KEY;
1818 key.offset = device->devid;
1820 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1824 btrfs_abort_transaction(trans, ret);
1825 btrfs_end_transaction(trans);
1829 ret = btrfs_del_item(trans, root, path);
1831 btrfs_abort_transaction(trans, ret);
1832 btrfs_end_transaction(trans);
1836 btrfs_free_path(path);
1838 ret = btrfs_commit_transaction(trans);
1843 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1844 * filesystem. It's up to the caller to adjust that number regarding eg. device
1847 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1855 seq = read_seqbegin(&fs_info->profiles_lock);
1857 all_avail = fs_info->avail_data_alloc_bits |
1858 fs_info->avail_system_alloc_bits |
1859 fs_info->avail_metadata_alloc_bits;
1860 } while (read_seqretry(&fs_info->profiles_lock, seq));
1862 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1863 if (!(all_avail & btrfs_raid_group[i]))
1866 if (num_devices < btrfs_raid_array[i].devs_min) {
1867 int ret = btrfs_raid_mindev_error[i];
1877 static struct btrfs_device * btrfs_find_next_active_device(
1878 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1880 struct btrfs_device *next_device;
1882 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1883 if (next_device != device &&
1884 !next_device->missing && next_device->bdev)
1892 * Helper function to check if the given device is part of s_bdev / latest_bdev
1893 * and replace it with the provided or the next active device, in the context
1894 * where this function called, there should be always be another device (or
1895 * this_dev) which is active.
1897 void btrfs_assign_next_active_device(struct btrfs_fs_info *fs_info,
1898 struct btrfs_device *device, struct btrfs_device *this_dev)
1900 struct btrfs_device *next_device;
1903 next_device = this_dev;
1905 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1907 ASSERT(next_device);
1909 if (fs_info->sb->s_bdev &&
1910 (fs_info->sb->s_bdev == device->bdev))
1911 fs_info->sb->s_bdev = next_device->bdev;
1913 if (fs_info->fs_devices->latest_bdev == device->bdev)
1914 fs_info->fs_devices->latest_bdev = next_device->bdev;
1917 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1920 struct btrfs_device *device;
1921 struct btrfs_fs_devices *cur_devices;
1925 mutex_lock(&fs_info->volume_mutex);
1926 mutex_lock(&uuid_mutex);
1928 num_devices = fs_info->fs_devices->num_devices;
1929 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
1930 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1931 WARN_ON(num_devices < 1);
1934 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
1936 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1940 ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1945 if (device->is_tgtdev_for_dev_replace) {
1946 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1950 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1951 fs_info->fs_devices->rw_devices == 1) {
1952 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1956 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1957 mutex_lock(&fs_info->chunk_mutex);
1958 list_del_init(&device->dev_alloc_list);
1959 device->fs_devices->rw_devices--;
1960 mutex_unlock(&fs_info->chunk_mutex);
1963 mutex_unlock(&uuid_mutex);
1964 ret = btrfs_shrink_device(device, 0);
1965 mutex_lock(&uuid_mutex);
1970 * TODO: the superblock still includes this device in its num_devices
1971 * counter although write_all_supers() is not locked out. This
1972 * could give a filesystem state which requires a degraded mount.
1974 ret = btrfs_rm_dev_item(fs_info, device);
1978 device->in_fs_metadata = 0;
1979 btrfs_scrub_cancel_dev(fs_info, device);
1982 * the device list mutex makes sure that we don't change
1983 * the device list while someone else is writing out all
1984 * the device supers. Whoever is writing all supers, should
1985 * lock the device list mutex before getting the number of
1986 * devices in the super block (super_copy). Conversely,
1987 * whoever updates the number of devices in the super block
1988 * (super_copy) should hold the device list mutex.
1991 cur_devices = device->fs_devices;
1992 mutex_lock(&fs_info->fs_devices->device_list_mutex);
1993 list_del_rcu(&device->dev_list);
1995 device->fs_devices->num_devices--;
1996 device->fs_devices->total_devices--;
1998 if (device->missing)
1999 device->fs_devices->missing_devices--;
2001 btrfs_assign_next_active_device(fs_info, device, NULL);
2004 device->fs_devices->open_devices--;
2005 /* remove sysfs entry */
2006 btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
2009 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2010 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2011 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2014 * at this point, the device is zero sized and detached from
2015 * the devices list. All that's left is to zero out the old
2016 * supers and free the device.
2018 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2019 btrfs_scratch_superblocks(device->bdev, device->name->str);
2021 btrfs_close_bdev(device);
2022 call_rcu(&device->rcu, free_device_rcu);
2024 if (cur_devices->open_devices == 0) {
2025 struct btrfs_fs_devices *fs_devices;
2026 fs_devices = fs_info->fs_devices;
2027 while (fs_devices) {
2028 if (fs_devices->seed == cur_devices) {
2029 fs_devices->seed = cur_devices->seed;
2032 fs_devices = fs_devices->seed;
2034 cur_devices->seed = NULL;
2035 __btrfs_close_devices(cur_devices);
2036 free_fs_devices(cur_devices);
2040 mutex_unlock(&uuid_mutex);
2041 mutex_unlock(&fs_info->volume_mutex);
2045 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2046 mutex_lock(&fs_info->chunk_mutex);
2047 list_add(&device->dev_alloc_list,
2048 &fs_info->fs_devices->alloc_list);
2049 device->fs_devices->rw_devices++;
2050 mutex_unlock(&fs_info->chunk_mutex);
2055 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
2056 struct btrfs_device *srcdev)
2058 struct btrfs_fs_devices *fs_devices;
2060 WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
2063 * in case of fs with no seed, srcdev->fs_devices will point
2064 * to fs_devices of fs_info. However when the dev being replaced is
2065 * a seed dev it will point to the seed's local fs_devices. In short
2066 * srcdev will have its correct fs_devices in both the cases.
2068 fs_devices = srcdev->fs_devices;
2070 list_del_rcu(&srcdev->dev_list);
2071 list_del(&srcdev->dev_alloc_list);
2072 fs_devices->num_devices--;
2073 if (srcdev->missing)
2074 fs_devices->missing_devices--;
2076 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2077 fs_devices->rw_devices--;
2080 fs_devices->open_devices--;
2083 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2084 struct btrfs_device *srcdev)
2086 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2088 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2089 /* zero out the old super if it is writable */
2090 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2093 btrfs_close_bdev(srcdev);
2094 call_rcu(&srcdev->rcu, free_device_rcu);
2096 /* if this is no devs we rather delete the fs_devices */
2097 if (!fs_devices->num_devices) {
2098 struct btrfs_fs_devices *tmp_fs_devices;
2101 * On a mounted FS, num_devices can't be zero unless it's a
2102 * seed. In case of a seed device being replaced, the replace
2103 * target added to the sprout FS, so there will be no more
2104 * device left under the seed FS.
2106 ASSERT(fs_devices->seeding);
2108 tmp_fs_devices = fs_info->fs_devices;
2109 while (tmp_fs_devices) {
2110 if (tmp_fs_devices->seed == fs_devices) {
2111 tmp_fs_devices->seed = fs_devices->seed;
2114 tmp_fs_devices = tmp_fs_devices->seed;
2116 fs_devices->seed = NULL;
2117 __btrfs_close_devices(fs_devices);
2118 free_fs_devices(fs_devices);
2122 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2123 struct btrfs_device *tgtdev)
2125 mutex_lock(&uuid_mutex);
2127 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2129 btrfs_sysfs_rm_device_link(fs_info->fs_devices, tgtdev);
2132 fs_info->fs_devices->open_devices--;
2134 fs_info->fs_devices->num_devices--;
2136 btrfs_assign_next_active_device(fs_info, tgtdev, NULL);
2138 list_del_rcu(&tgtdev->dev_list);
2140 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2141 mutex_unlock(&uuid_mutex);
2144 * The update_dev_time() with in btrfs_scratch_superblocks()
2145 * may lead to a call to btrfs_show_devname() which will try
2146 * to hold device_list_mutex. And here this device
2147 * is already out of device list, so we don't have to hold
2148 * the device_list_mutex lock.
2150 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2152 btrfs_close_bdev(tgtdev);
2153 call_rcu(&tgtdev->rcu, free_device_rcu);
2156 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2157 const char *device_path,
2158 struct btrfs_device **device)
2161 struct btrfs_super_block *disk_super;
2164 struct block_device *bdev;
2165 struct buffer_head *bh;
2168 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2169 fs_info->bdev_holder, 0, &bdev, &bh);
2172 disk_super = (struct btrfs_super_block *)bh->b_data;
2173 devid = btrfs_stack_device_id(&disk_super->dev_item);
2174 dev_uuid = disk_super->dev_item.uuid;
2175 *device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2179 blkdev_put(bdev, FMODE_READ);
2183 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2184 const char *device_path,
2185 struct btrfs_device **device)
2188 if (strcmp(device_path, "missing") == 0) {
2189 struct list_head *devices;
2190 struct btrfs_device *tmp;
2192 devices = &fs_info->fs_devices->devices;
2194 * It is safe to read the devices since the volume_mutex
2195 * is held by the caller.
2197 list_for_each_entry(tmp, devices, dev_list) {
2198 if (tmp->in_fs_metadata && !tmp->bdev) {
2205 return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2209 return btrfs_find_device_by_path(fs_info, device_path, device);
2214 * Lookup a device given by device id, or the path if the id is 0.
2216 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2217 const char *devpath,
2218 struct btrfs_device **device)
2224 *device = btrfs_find_device(fs_info, devid, NULL, NULL);
2228 if (!devpath || !devpath[0])
2231 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2238 * does all the dirty work required for changing file system's UUID.
2240 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2242 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2243 struct btrfs_fs_devices *old_devices;
2244 struct btrfs_fs_devices *seed_devices;
2245 struct btrfs_super_block *disk_super = fs_info->super_copy;
2246 struct btrfs_device *device;
2249 BUG_ON(!mutex_is_locked(&uuid_mutex));
2250 if (!fs_devices->seeding)
2253 seed_devices = alloc_fs_devices(NULL);
2254 if (IS_ERR(seed_devices))
2255 return PTR_ERR(seed_devices);
2257 old_devices = clone_fs_devices(fs_devices);
2258 if (IS_ERR(old_devices)) {
2259 kfree(seed_devices);
2260 return PTR_ERR(old_devices);
2263 list_add(&old_devices->list, &fs_uuids);
2265 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2266 seed_devices->opened = 1;
2267 INIT_LIST_HEAD(&seed_devices->devices);
2268 INIT_LIST_HEAD(&seed_devices->alloc_list);
2269 mutex_init(&seed_devices->device_list_mutex);
2271 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2272 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2274 list_for_each_entry(device, &seed_devices->devices, dev_list)
2275 device->fs_devices = seed_devices;
2277 mutex_lock(&fs_info->chunk_mutex);
2278 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2279 mutex_unlock(&fs_info->chunk_mutex);
2281 fs_devices->seeding = 0;
2282 fs_devices->num_devices = 0;
2283 fs_devices->open_devices = 0;
2284 fs_devices->missing_devices = 0;
2285 fs_devices->rotating = 0;
2286 fs_devices->seed = seed_devices;
2288 generate_random_uuid(fs_devices->fsid);
2289 memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2290 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2291 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2293 super_flags = btrfs_super_flags(disk_super) &
2294 ~BTRFS_SUPER_FLAG_SEEDING;
2295 btrfs_set_super_flags(disk_super, super_flags);
2301 * Store the expected generation for seed devices in device items.
2303 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2304 struct btrfs_fs_info *fs_info)
2306 struct btrfs_root *root = fs_info->chunk_root;
2307 struct btrfs_path *path;
2308 struct extent_buffer *leaf;
2309 struct btrfs_dev_item *dev_item;
2310 struct btrfs_device *device;
2311 struct btrfs_key key;
2312 u8 fs_uuid[BTRFS_FSID_SIZE];
2313 u8 dev_uuid[BTRFS_UUID_SIZE];
2317 path = btrfs_alloc_path();
2321 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2323 key.type = BTRFS_DEV_ITEM_KEY;
2326 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2330 leaf = path->nodes[0];
2332 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2333 ret = btrfs_next_leaf(root, path);
2338 leaf = path->nodes[0];
2339 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2340 btrfs_release_path(path);
2344 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2345 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2346 key.type != BTRFS_DEV_ITEM_KEY)
2349 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2350 struct btrfs_dev_item);
2351 devid = btrfs_device_id(leaf, dev_item);
2352 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2354 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2356 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2357 BUG_ON(!device); /* Logic error */
2359 if (device->fs_devices->seeding) {
2360 btrfs_set_device_generation(leaf, dev_item,
2361 device->generation);
2362 btrfs_mark_buffer_dirty(leaf);
2370 btrfs_free_path(path);
2374 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2376 struct btrfs_root *root = fs_info->dev_root;
2377 struct request_queue *q;
2378 struct btrfs_trans_handle *trans;
2379 struct btrfs_device *device;
2380 struct block_device *bdev;
2381 struct list_head *devices;
2382 struct super_block *sb = fs_info->sb;
2383 struct rcu_string *name;
2385 int seeding_dev = 0;
2387 bool unlocked = false;
2389 if (sb_rdonly(sb) && !fs_info->fs_devices->seeding)
2392 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2393 fs_info->bdev_holder);
2395 return PTR_ERR(bdev);
2397 if (fs_info->fs_devices->seeding) {
2399 down_write(&sb->s_umount);
2400 mutex_lock(&uuid_mutex);
2403 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2405 devices = &fs_info->fs_devices->devices;
2407 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2408 list_for_each_entry(device, devices, dev_list) {
2409 if (device->bdev == bdev) {
2412 &fs_info->fs_devices->device_list_mutex);
2416 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2418 device = btrfs_alloc_device(fs_info, NULL, NULL);
2419 if (IS_ERR(device)) {
2420 /* we can safely leave the fs_devices entry around */
2421 ret = PTR_ERR(device);
2425 name = rcu_string_strdup(device_path, GFP_KERNEL);
2428 goto error_free_device;
2430 rcu_assign_pointer(device->name, name);
2432 trans = btrfs_start_transaction(root, 0);
2433 if (IS_ERR(trans)) {
2434 ret = PTR_ERR(trans);
2435 goto error_free_device;
2438 q = bdev_get_queue(bdev);
2439 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2440 device->generation = trans->transid;
2441 device->io_width = fs_info->sectorsize;
2442 device->io_align = fs_info->sectorsize;
2443 device->sector_size = fs_info->sectorsize;
2444 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2445 fs_info->sectorsize);
2446 device->disk_total_bytes = device->total_bytes;
2447 device->commit_total_bytes = device->total_bytes;
2448 device->fs_info = fs_info;
2449 device->bdev = bdev;
2450 device->in_fs_metadata = 1;
2451 device->is_tgtdev_for_dev_replace = 0;
2452 device->mode = FMODE_EXCL;
2453 device->dev_stats_valid = 1;
2454 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2457 sb->s_flags &= ~SB_RDONLY;
2458 ret = btrfs_prepare_sprout(fs_info);
2460 btrfs_abort_transaction(trans, ret);
2465 device->fs_devices = fs_info->fs_devices;
2467 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2468 mutex_lock(&fs_info->chunk_mutex);
2469 list_add_rcu(&device->dev_list, &fs_info->fs_devices->devices);
2470 list_add(&device->dev_alloc_list,
2471 &fs_info->fs_devices->alloc_list);
2472 fs_info->fs_devices->num_devices++;
2473 fs_info->fs_devices->open_devices++;
2474 fs_info->fs_devices->rw_devices++;
2475 fs_info->fs_devices->total_devices++;
2476 fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2478 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2480 if (!blk_queue_nonrot(q))
2481 fs_info->fs_devices->rotating = 1;
2483 tmp = btrfs_super_total_bytes(fs_info->super_copy);
2484 btrfs_set_super_total_bytes(fs_info->super_copy,
2485 round_down(tmp + device->total_bytes, fs_info->sectorsize));
2487 tmp = btrfs_super_num_devices(fs_info->super_copy);
2488 btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
2490 /* add sysfs device entry */
2491 btrfs_sysfs_add_device_link(fs_info->fs_devices, device);
2494 * we've got more storage, clear any full flags on the space
2497 btrfs_clear_space_info_full(fs_info);
2499 mutex_unlock(&fs_info->chunk_mutex);
2500 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2503 mutex_lock(&fs_info->chunk_mutex);
2504 ret = init_first_rw_device(trans, fs_info);
2505 mutex_unlock(&fs_info->chunk_mutex);
2507 btrfs_abort_transaction(trans, ret);
2512 ret = btrfs_add_dev_item(trans, fs_info, device);
2514 btrfs_abort_transaction(trans, ret);
2519 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2521 ret = btrfs_finish_sprout(trans, fs_info);
2523 btrfs_abort_transaction(trans, ret);
2527 /* Sprouting would change fsid of the mounted root,
2528 * so rename the fsid on the sysfs
2530 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2532 if (kobject_rename(&fs_info->fs_devices->fsid_kobj, fsid_buf))
2534 "sysfs: failed to create fsid for sprout");
2537 ret = btrfs_commit_transaction(trans);
2540 mutex_unlock(&uuid_mutex);
2541 up_write(&sb->s_umount);
2544 if (ret) /* transaction commit */
2547 ret = btrfs_relocate_sys_chunks(fs_info);
2549 btrfs_handle_fs_error(fs_info, ret,
2550 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2551 trans = btrfs_attach_transaction(root);
2552 if (IS_ERR(trans)) {
2553 if (PTR_ERR(trans) == -ENOENT)
2555 ret = PTR_ERR(trans);
2559 ret = btrfs_commit_transaction(trans);
2562 /* Update ctime/mtime for libblkid */
2563 update_dev_time(device_path);
2567 btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
2570 sb->s_flags |= SB_RDONLY;
2572 btrfs_end_transaction(trans);
2574 free_device(device);
2576 blkdev_put(bdev, FMODE_EXCL);
2577 if (seeding_dev && !unlocked) {
2578 mutex_unlock(&uuid_mutex);
2579 up_write(&sb->s_umount);
2584 int btrfs_init_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2585 const char *device_path,
2586 struct btrfs_device *srcdev,
2587 struct btrfs_device **device_out)
2589 struct btrfs_device *device;
2590 struct block_device *bdev;
2591 struct list_head *devices;
2592 struct rcu_string *name;
2593 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2597 if (fs_info->fs_devices->seeding) {
2598 btrfs_err(fs_info, "the filesystem is a seed filesystem!");
2602 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2603 fs_info->bdev_holder);
2605 btrfs_err(fs_info, "target device %s is invalid!", device_path);
2606 return PTR_ERR(bdev);
2609 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2611 devices = &fs_info->fs_devices->devices;
2612 list_for_each_entry(device, devices, dev_list) {
2613 if (device->bdev == bdev) {
2615 "target device is in the filesystem!");
2622 if (i_size_read(bdev->bd_inode) <
2623 btrfs_device_get_total_bytes(srcdev)) {
2625 "target device is smaller than source device!");
2631 device = btrfs_alloc_device(NULL, &devid, NULL);
2632 if (IS_ERR(device)) {
2633 ret = PTR_ERR(device);
2637 name = rcu_string_strdup(device_path, GFP_KERNEL);
2639 free_device(device);
2643 rcu_assign_pointer(device->name, name);
2645 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2646 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2647 device->generation = 0;
2648 device->io_width = fs_info->sectorsize;
2649 device->io_align = fs_info->sectorsize;
2650 device->sector_size = fs_info->sectorsize;
2651 device->total_bytes = btrfs_device_get_total_bytes(srcdev);
2652 device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
2653 device->bytes_used = btrfs_device_get_bytes_used(srcdev);
2654 ASSERT(list_empty(&srcdev->resized_list));
2655 device->commit_total_bytes = srcdev->commit_total_bytes;
2656 device->commit_bytes_used = device->bytes_used;
2657 device->fs_info = fs_info;
2658 device->bdev = bdev;
2659 device->in_fs_metadata = 1;
2660 device->is_tgtdev_for_dev_replace = 1;
2661 device->mode = FMODE_EXCL;
2662 device->dev_stats_valid = 1;
2663 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2664 device->fs_devices = fs_info->fs_devices;
2665 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2666 fs_info->fs_devices->num_devices++;
2667 fs_info->fs_devices->open_devices++;
2668 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2670 *device_out = device;
2674 blkdev_put(bdev, FMODE_EXCL);
2678 void btrfs_init_dev_replace_tgtdev_for_resume(struct btrfs_fs_info *fs_info,
2679 struct btrfs_device *tgtdev)
2681 u32 sectorsize = fs_info->sectorsize;
2683 WARN_ON(fs_info->fs_devices->rw_devices == 0);
2684 tgtdev->io_width = sectorsize;
2685 tgtdev->io_align = sectorsize;
2686 tgtdev->sector_size = sectorsize;
2687 tgtdev->fs_info = fs_info;
2688 tgtdev->in_fs_metadata = 1;
2691 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2692 struct btrfs_device *device)
2695 struct btrfs_path *path;
2696 struct btrfs_root *root = device->fs_info->chunk_root;
2697 struct btrfs_dev_item *dev_item;
2698 struct extent_buffer *leaf;
2699 struct btrfs_key key;
2701 path = btrfs_alloc_path();
2705 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2706 key.type = BTRFS_DEV_ITEM_KEY;
2707 key.offset = device->devid;
2709 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2718 leaf = path->nodes[0];
2719 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2721 btrfs_set_device_id(leaf, dev_item, device->devid);
2722 btrfs_set_device_type(leaf, dev_item, device->type);
2723 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2724 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2725 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2726 btrfs_set_device_total_bytes(leaf, dev_item,
2727 btrfs_device_get_disk_total_bytes(device));
2728 btrfs_set_device_bytes_used(leaf, dev_item,
2729 btrfs_device_get_bytes_used(device));
2730 btrfs_mark_buffer_dirty(leaf);
2733 btrfs_free_path(path);
2737 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2738 struct btrfs_device *device, u64 new_size)
2740 struct btrfs_fs_info *fs_info = device->fs_info;
2741 struct btrfs_super_block *super_copy = fs_info->super_copy;
2742 struct btrfs_fs_devices *fs_devices;
2746 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2749 new_size = round_down(new_size, fs_info->sectorsize);
2751 mutex_lock(&fs_info->chunk_mutex);
2752 old_total = btrfs_super_total_bytes(super_copy);
2753 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2755 if (new_size <= device->total_bytes ||
2756 device->is_tgtdev_for_dev_replace) {
2757 mutex_unlock(&fs_info->chunk_mutex);
2761 fs_devices = fs_info->fs_devices;
2763 btrfs_set_super_total_bytes(super_copy,
2764 round_down(old_total + diff, fs_info->sectorsize));
2765 device->fs_devices->total_rw_bytes += diff;
2767 btrfs_device_set_total_bytes(device, new_size);
2768 btrfs_device_set_disk_total_bytes(device, new_size);
2769 btrfs_clear_space_info_full(device->fs_info);
2770 if (list_empty(&device->resized_list))
2771 list_add_tail(&device->resized_list,
2772 &fs_devices->resized_devices);
2773 mutex_unlock(&fs_info->chunk_mutex);
2775 return btrfs_update_device(trans, device);
2778 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2779 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2781 struct btrfs_root *root = fs_info->chunk_root;
2783 struct btrfs_path *path;
2784 struct btrfs_key key;
2786 path = btrfs_alloc_path();
2790 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2791 key.offset = chunk_offset;
2792 key.type = BTRFS_CHUNK_ITEM_KEY;
2794 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2797 else if (ret > 0) { /* Logic error or corruption */
2798 btrfs_handle_fs_error(fs_info, -ENOENT,
2799 "Failed lookup while freeing chunk.");
2804 ret = btrfs_del_item(trans, root, path);
2806 btrfs_handle_fs_error(fs_info, ret,
2807 "Failed to delete chunk item.");
2809 btrfs_free_path(path);
2813 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2815 struct btrfs_super_block *super_copy = fs_info->super_copy;
2816 struct btrfs_disk_key *disk_key;
2817 struct btrfs_chunk *chunk;
2824 struct btrfs_key key;
2826 mutex_lock(&fs_info->chunk_mutex);
2827 array_size = btrfs_super_sys_array_size(super_copy);
2829 ptr = super_copy->sys_chunk_array;
2832 while (cur < array_size) {
2833 disk_key = (struct btrfs_disk_key *)ptr;
2834 btrfs_disk_key_to_cpu(&key, disk_key);
2836 len = sizeof(*disk_key);
2838 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2839 chunk = (struct btrfs_chunk *)(ptr + len);
2840 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2841 len += btrfs_chunk_item_size(num_stripes);
2846 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2847 key.offset == chunk_offset) {
2848 memmove(ptr, ptr + len, array_size - (cur + len));
2850 btrfs_set_super_sys_array_size(super_copy, array_size);
2856 mutex_unlock(&fs_info->chunk_mutex);
2860 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2861 u64 logical, u64 length)
2863 struct extent_map_tree *em_tree;
2864 struct extent_map *em;
2866 em_tree = &fs_info->mapping_tree.map_tree;
2867 read_lock(&em_tree->lock);
2868 em = lookup_extent_mapping(em_tree, logical, length);
2869 read_unlock(&em_tree->lock);
2872 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2874 return ERR_PTR(-EINVAL);
2877 if (em->start > logical || em->start + em->len < logical) {
2879 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2880 logical, length, em->start, em->start + em->len);
2881 free_extent_map(em);
2882 return ERR_PTR(-EINVAL);
2885 /* callers are responsible for dropping em's ref. */
2889 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2890 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2892 struct extent_map *em;
2893 struct map_lookup *map;
2894 u64 dev_extent_len = 0;
2896 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2898 em = get_chunk_map(fs_info, chunk_offset, 1);
2901 * This is a logic error, but we don't want to just rely on the
2902 * user having built with ASSERT enabled, so if ASSERT doesn't
2903 * do anything we still error out.
2908 map = em->map_lookup;
2909 mutex_lock(&fs_info->chunk_mutex);
2910 check_system_chunk(trans, fs_info, map->type);
2911 mutex_unlock(&fs_info->chunk_mutex);
2914 * Take the device list mutex to prevent races with the final phase of
2915 * a device replace operation that replaces the device object associated
2916 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2918 mutex_lock(&fs_devices->device_list_mutex);
2919 for (i = 0; i < map->num_stripes; i++) {
2920 struct btrfs_device *device = map->stripes[i].dev;
2921 ret = btrfs_free_dev_extent(trans, device,
2922 map->stripes[i].physical,
2925 mutex_unlock(&fs_devices->device_list_mutex);
2926 btrfs_abort_transaction(trans, ret);
2930 if (device->bytes_used > 0) {
2931 mutex_lock(&fs_info->chunk_mutex);
2932 btrfs_device_set_bytes_used(device,
2933 device->bytes_used - dev_extent_len);
2934 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2935 btrfs_clear_space_info_full(fs_info);
2936 mutex_unlock(&fs_info->chunk_mutex);
2939 if (map->stripes[i].dev) {
2940 ret = btrfs_update_device(trans, map->stripes[i].dev);
2942 mutex_unlock(&fs_devices->device_list_mutex);
2943 btrfs_abort_transaction(trans, ret);
2948 mutex_unlock(&fs_devices->device_list_mutex);
2950 ret = btrfs_free_chunk(trans, fs_info, chunk_offset);
2952 btrfs_abort_transaction(trans, ret);
2956 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2958 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2959 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2961 btrfs_abort_transaction(trans, ret);
2966 ret = btrfs_remove_block_group(trans, fs_info, chunk_offset, em);
2968 btrfs_abort_transaction(trans, ret);
2974 free_extent_map(em);
2978 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2980 struct btrfs_root *root = fs_info->chunk_root;
2981 struct btrfs_trans_handle *trans;
2985 * Prevent races with automatic removal of unused block groups.
2986 * After we relocate and before we remove the chunk with offset
2987 * chunk_offset, automatic removal of the block group can kick in,
2988 * resulting in a failure when calling btrfs_remove_chunk() below.
2990 * Make sure to acquire this mutex before doing a tree search (dev
2991 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2992 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2993 * we release the path used to search the chunk/dev tree and before
2994 * the current task acquires this mutex and calls us.
2996 ASSERT(mutex_is_locked(&fs_info->delete_unused_bgs_mutex));
2998 ret = btrfs_can_relocate(fs_info, chunk_offset);
3002 /* step one, relocate all the extents inside this chunk */
3003 btrfs_scrub_pause(fs_info);
3004 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3005 btrfs_scrub_continue(fs_info);
3009 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3011 if (IS_ERR(trans)) {
3012 ret = PTR_ERR(trans);
3013 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3018 * step two, delete the device extents and the
3019 * chunk tree entries
3021 ret = btrfs_remove_chunk(trans, fs_info, chunk_offset);
3022 btrfs_end_transaction(trans);
3026 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3028 struct btrfs_root *chunk_root = fs_info->chunk_root;
3029 struct btrfs_path *path;
3030 struct extent_buffer *leaf;
3031 struct btrfs_chunk *chunk;
3032 struct btrfs_key key;
3033 struct btrfs_key found_key;
3035 bool retried = false;
3039 path = btrfs_alloc_path();
3044 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3045 key.offset = (u64)-1;
3046 key.type = BTRFS_CHUNK_ITEM_KEY;
3049 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3050 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3052 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3055 BUG_ON(ret == 0); /* Corruption */
3057 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3060 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3066 leaf = path->nodes[0];
3067 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3069 chunk = btrfs_item_ptr(leaf, path->slots[0],
3070 struct btrfs_chunk);
3071 chunk_type = btrfs_chunk_type(leaf, chunk);
3072 btrfs_release_path(path);
3074 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3075 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3081 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3083 if (found_key.offset == 0)
3085 key.offset = found_key.offset - 1;
3088 if (failed && !retried) {
3092 } else if (WARN_ON(failed && retried)) {
3096 btrfs_free_path(path);
3100 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3101 struct btrfs_balance_control *bctl)
3103 struct btrfs_root *root = fs_info->tree_root;
3104 struct btrfs_trans_handle *trans;
3105 struct btrfs_balance_item *item;
3106 struct btrfs_disk_balance_args disk_bargs;
3107 struct btrfs_path *path;
3108 struct extent_buffer *leaf;
3109 struct btrfs_key key;
3112 path = btrfs_alloc_path();
3116 trans = btrfs_start_transaction(root, 0);
3117 if (IS_ERR(trans)) {
3118 btrfs_free_path(path);
3119 return PTR_ERR(trans);
3122 key.objectid = BTRFS_BALANCE_OBJECTID;
3123 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3126 ret = btrfs_insert_empty_item(trans, root, path, &key,
3131 leaf = path->nodes[0];
3132 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3134 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3136 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3137 btrfs_set_balance_data(leaf, item, &disk_bargs);
3138 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3139 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3140 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3141 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3143 btrfs_set_balance_flags(leaf, item, bctl->flags);
3145 btrfs_mark_buffer_dirty(leaf);
3147 btrfs_free_path(path);
3148 err = btrfs_commit_transaction(trans);
3154 static int del_balance_item(struct btrfs_fs_info *fs_info)
3156 struct btrfs_root *root = fs_info->tree_root;
3157 struct btrfs_trans_handle *trans;
3158 struct btrfs_path *path;
3159 struct btrfs_key key;
3162 path = btrfs_alloc_path();
3166 trans = btrfs_start_transaction(root, 0);
3167 if (IS_ERR(trans)) {
3168 btrfs_free_path(path);
3169 return PTR_ERR(trans);
3172 key.objectid = BTRFS_BALANCE_OBJECTID;
3173 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3176 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3184 ret = btrfs_del_item(trans, root, path);
3186 btrfs_free_path(path);
3187 err = btrfs_commit_transaction(trans);
3194 * This is a heuristic used to reduce the number of chunks balanced on
3195 * resume after balance was interrupted.
3197 static void update_balance_args(struct btrfs_balance_control *bctl)
3200 * Turn on soft mode for chunk types that were being converted.
3202 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3203 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3204 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3205 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3206 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3207 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3210 * Turn on usage filter if is not already used. The idea is
3211 * that chunks that we have already balanced should be
3212 * reasonably full. Don't do it for chunks that are being
3213 * converted - that will keep us from relocating unconverted
3214 * (albeit full) chunks.
3216 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3217 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3218 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3219 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3220 bctl->data.usage = 90;
3222 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3223 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3224 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3225 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3226 bctl->sys.usage = 90;
3228 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3229 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3230 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3231 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3232 bctl->meta.usage = 90;
3237 * Should be called with both balance and volume mutexes held to
3238 * serialize other volume operations (add_dev/rm_dev/resize) with
3239 * restriper. Same goes for unset_balance_control.
3241 static void set_balance_control(struct btrfs_balance_control *bctl)
3243 struct btrfs_fs_info *fs_info = bctl->fs_info;
3245 BUG_ON(fs_info->balance_ctl);
3247 spin_lock(&fs_info->balance_lock);
3248 fs_info->balance_ctl = bctl;
3249 spin_unlock(&fs_info->balance_lock);
3252 static void unset_balance_control(struct btrfs_fs_info *fs_info)
3254 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3256 BUG_ON(!fs_info->balance_ctl);
3258 spin_lock(&fs_info->balance_lock);
3259 fs_info->balance_ctl = NULL;
3260 spin_unlock(&fs_info->balance_lock);
3266 * Balance filters. Return 1 if chunk should be filtered out
3267 * (should not be balanced).
3269 static int chunk_profiles_filter(u64 chunk_type,
3270 struct btrfs_balance_args *bargs)
3272 chunk_type = chunk_to_extended(chunk_type) &
3273 BTRFS_EXTENDED_PROFILE_MASK;
3275 if (bargs->profiles & chunk_type)
3281 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3282 struct btrfs_balance_args *bargs)
3284 struct btrfs_block_group_cache *cache;
3286 u64 user_thresh_min;
3287 u64 user_thresh_max;
3290 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3291 chunk_used = btrfs_block_group_used(&cache->item);
3293 if (bargs->usage_min == 0)
3294 user_thresh_min = 0;
3296 user_thresh_min = div_factor_fine(cache->key.offset,
3299 if (bargs->usage_max == 0)
3300 user_thresh_max = 1;
3301 else if (bargs->usage_max > 100)
3302 user_thresh_max = cache->key.offset;
3304 user_thresh_max = div_factor_fine(cache->key.offset,
3307 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3310 btrfs_put_block_group(cache);
3314 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3315 u64 chunk_offset, struct btrfs_balance_args *bargs)
3317 struct btrfs_block_group_cache *cache;
3318 u64 chunk_used, user_thresh;
3321 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3322 chunk_used = btrfs_block_group_used(&cache->item);
3324 if (bargs->usage_min == 0)
3326 else if (bargs->usage > 100)
3327 user_thresh = cache->key.offset;
3329 user_thresh = div_factor_fine(cache->key.offset,
3332 if (chunk_used < user_thresh)
3335 btrfs_put_block_group(cache);
3339 static int chunk_devid_filter(struct extent_buffer *leaf,
3340 struct btrfs_chunk *chunk,
3341 struct btrfs_balance_args *bargs)
3343 struct btrfs_stripe *stripe;
3344 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3347 for (i = 0; i < num_stripes; i++) {
3348 stripe = btrfs_stripe_nr(chunk, i);
3349 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3356 /* [pstart, pend) */
3357 static int chunk_drange_filter(struct extent_buffer *leaf,
3358 struct btrfs_chunk *chunk,
3359 struct btrfs_balance_args *bargs)
3361 struct btrfs_stripe *stripe;
3362 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3368 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3371 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3372 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3373 factor = num_stripes / 2;
3374 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3375 factor = num_stripes - 1;
3376 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3377 factor = num_stripes - 2;
3379 factor = num_stripes;
3382 for (i = 0; i < num_stripes; i++) {
3383 stripe = btrfs_stripe_nr(chunk, i);
3384 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3387 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3388 stripe_length = btrfs_chunk_length(leaf, chunk);
3389 stripe_length = div_u64(stripe_length, factor);
3391 if (stripe_offset < bargs->pend &&
3392 stripe_offset + stripe_length > bargs->pstart)
3399 /* [vstart, vend) */
3400 static int chunk_vrange_filter(struct extent_buffer *leaf,
3401 struct btrfs_chunk *chunk,
3403 struct btrfs_balance_args *bargs)
3405 if (chunk_offset < bargs->vend &&
3406 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3407 /* at least part of the chunk is inside this vrange */
3413 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3414 struct btrfs_chunk *chunk,
3415 struct btrfs_balance_args *bargs)
3417 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3419 if (bargs->stripes_min <= num_stripes
3420 && num_stripes <= bargs->stripes_max)
3426 static int chunk_soft_convert_filter(u64 chunk_type,
3427 struct btrfs_balance_args *bargs)
3429 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3432 chunk_type = chunk_to_extended(chunk_type) &
3433 BTRFS_EXTENDED_PROFILE_MASK;
3435 if (bargs->target == chunk_type)
3441 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3442 struct extent_buffer *leaf,
3443 struct btrfs_chunk *chunk, u64 chunk_offset)
3445 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3446 struct btrfs_balance_args *bargs = NULL;
3447 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3450 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3451 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3455 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3456 bargs = &bctl->data;
3457 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3459 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3460 bargs = &bctl->meta;
3462 /* profiles filter */
3463 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3464 chunk_profiles_filter(chunk_type, bargs)) {
3469 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3470 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3472 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3473 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3478 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3479 chunk_devid_filter(leaf, chunk, bargs)) {
3483 /* drange filter, makes sense only with devid filter */
3484 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3485 chunk_drange_filter(leaf, chunk, bargs)) {
3490 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3491 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3495 /* stripes filter */
3496 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3497 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3501 /* soft profile changing mode */
3502 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3503 chunk_soft_convert_filter(chunk_type, bargs)) {
3508 * limited by count, must be the last filter
3510 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3511 if (bargs->limit == 0)
3515 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3517 * Same logic as the 'limit' filter; the minimum cannot be
3518 * determined here because we do not have the global information
3519 * about the count of all chunks that satisfy the filters.
3521 if (bargs->limit_max == 0)
3530 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3532 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3533 struct btrfs_root *chunk_root = fs_info->chunk_root;
3534 struct btrfs_root *dev_root = fs_info->dev_root;
3535 struct list_head *devices;
3536 struct btrfs_device *device;
3540 struct btrfs_chunk *chunk;
3541 struct btrfs_path *path = NULL;
3542 struct btrfs_key key;
3543 struct btrfs_key found_key;
3544 struct btrfs_trans_handle *trans;
3545 struct extent_buffer *leaf;
3548 int enospc_errors = 0;
3549 bool counting = true;
3550 /* The single value limit and min/max limits use the same bytes in the */
3551 u64 limit_data = bctl->data.limit;
3552 u64 limit_meta = bctl->meta.limit;
3553 u64 limit_sys = bctl->sys.limit;
3557 int chunk_reserved = 0;
3560 /* step one make some room on all the devices */
3561 devices = &fs_info->fs_devices->devices;
3562 list_for_each_entry(device, devices, dev_list) {
3563 old_size = btrfs_device_get_total_bytes(device);
3564 size_to_free = div_factor(old_size, 1);
3565 size_to_free = min_t(u64, size_to_free, SZ_1M);
3566 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
3567 btrfs_device_get_total_bytes(device) -
3568 btrfs_device_get_bytes_used(device) > size_to_free ||
3569 device->is_tgtdev_for_dev_replace)
3572 ret = btrfs_shrink_device(device, old_size - size_to_free);
3576 /* btrfs_shrink_device never returns ret > 0 */
3581 trans = btrfs_start_transaction(dev_root, 0);
3582 if (IS_ERR(trans)) {
3583 ret = PTR_ERR(trans);
3584 btrfs_info_in_rcu(fs_info,
3585 "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3586 rcu_str_deref(device->name), ret,
3587 old_size, old_size - size_to_free);
3591 ret = btrfs_grow_device(trans, device, old_size);
3593 btrfs_end_transaction(trans);
3594 /* btrfs_grow_device never returns ret > 0 */
3596 btrfs_info_in_rcu(fs_info,
3597 "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3598 rcu_str_deref(device->name), ret,
3599 old_size, old_size - size_to_free);
3603 btrfs_end_transaction(trans);
3606 /* step two, relocate all the chunks */
3607 path = btrfs_alloc_path();
3613 /* zero out stat counters */
3614 spin_lock(&fs_info->balance_lock);
3615 memset(&bctl->stat, 0, sizeof(bctl->stat));
3616 spin_unlock(&fs_info->balance_lock);
3620 * The single value limit and min/max limits use the same bytes
3623 bctl->data.limit = limit_data;
3624 bctl->meta.limit = limit_meta;
3625 bctl->sys.limit = limit_sys;
3627 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3628 key.offset = (u64)-1;
3629 key.type = BTRFS_CHUNK_ITEM_KEY;
3632 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3633 atomic_read(&fs_info->balance_cancel_req)) {
3638 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3639 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3641 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3646 * this shouldn't happen, it means the last relocate
3650 BUG(); /* FIXME break ? */
3652 ret = btrfs_previous_item(chunk_root, path, 0,
3653 BTRFS_CHUNK_ITEM_KEY);
3655 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3660 leaf = path->nodes[0];
3661 slot = path->slots[0];
3662 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3664 if (found_key.objectid != key.objectid) {
3665 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3669 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3670 chunk_type = btrfs_chunk_type(leaf, chunk);
3673 spin_lock(&fs_info->balance_lock);
3674 bctl->stat.considered++;
3675 spin_unlock(&fs_info->balance_lock);
3678 ret = should_balance_chunk(fs_info, leaf, chunk,
3681 btrfs_release_path(path);
3683 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3688 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3689 spin_lock(&fs_info->balance_lock);
3690 bctl->stat.expected++;
3691 spin_unlock(&fs_info->balance_lock);
3693 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3695 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3697 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3704 * Apply limit_min filter, no need to check if the LIMITS
3705 * filter is used, limit_min is 0 by default
3707 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3708 count_data < bctl->data.limit_min)
3709 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3710 count_meta < bctl->meta.limit_min)
3711 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3712 count_sys < bctl->sys.limit_min)) {
3713 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3717 ASSERT(fs_info->data_sinfo);
3718 spin_lock(&fs_info->data_sinfo->lock);
3719 bytes_used = fs_info->data_sinfo->bytes_used;
3720 spin_unlock(&fs_info->data_sinfo->lock);
3722 if ((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3723 !chunk_reserved && !bytes_used) {
3724 trans = btrfs_start_transaction(chunk_root, 0);
3725 if (IS_ERR(trans)) {
3726 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3727 ret = PTR_ERR(trans);
3731 ret = btrfs_force_chunk_alloc(trans, fs_info,
3732 BTRFS_BLOCK_GROUP_DATA);
3733 btrfs_end_transaction(trans);
3735 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3741 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3742 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3743 if (ret && ret != -ENOSPC)
3745 if (ret == -ENOSPC) {
3748 spin_lock(&fs_info->balance_lock);
3749 bctl->stat.completed++;
3750 spin_unlock(&fs_info->balance_lock);
3753 if (found_key.offset == 0)
3755 key.offset = found_key.offset - 1;
3759 btrfs_release_path(path);
3764 btrfs_free_path(path);
3765 if (enospc_errors) {
3766 btrfs_info(fs_info, "%d enospc errors during balance",
3776 * alloc_profile_is_valid - see if a given profile is valid and reduced
3777 * @flags: profile to validate
3778 * @extended: if true @flags is treated as an extended profile
3780 static int alloc_profile_is_valid(u64 flags, int extended)
3782 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3783 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3785 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3787 /* 1) check that all other bits are zeroed */
3791 /* 2) see if profile is reduced */
3793 return !extended; /* "0" is valid for usual profiles */
3795 /* true if exactly one bit set */
3796 return (flags & (flags - 1)) == 0;
3799 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3801 /* cancel requested || normal exit path */
3802 return atomic_read(&fs_info->balance_cancel_req) ||
3803 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3804 atomic_read(&fs_info->balance_cancel_req) == 0);
3807 static void __cancel_balance(struct btrfs_fs_info *fs_info)
3811 unset_balance_control(fs_info);
3812 ret = del_balance_item(fs_info);
3814 btrfs_handle_fs_error(fs_info, ret, NULL);
3816 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3819 /* Non-zero return value signifies invalidity */
3820 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3823 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3824 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3825 (bctl_arg->target & ~allowed)));
3829 * Should be called with both balance and volume mutexes held
3831 int btrfs_balance(struct btrfs_balance_control *bctl,
3832 struct btrfs_ioctl_balance_args *bargs)
3834 struct btrfs_fs_info *fs_info = bctl->fs_info;
3835 u64 meta_target, data_target;
3842 if (btrfs_fs_closing(fs_info) ||
3843 atomic_read(&fs_info->balance_pause_req) ||
3844 atomic_read(&fs_info->balance_cancel_req)) {
3849 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3850 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3854 * In case of mixed groups both data and meta should be picked,
3855 * and identical options should be given for both of them.
3857 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3858 if (mixed && (bctl->flags & allowed)) {
3859 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3860 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3861 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3863 "with mixed groups data and metadata balance options must be the same");
3869 num_devices = fs_info->fs_devices->num_devices;
3870 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
3871 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3872 BUG_ON(num_devices < 1);
3875 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
3876 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3877 if (num_devices > 1)
3878 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3879 if (num_devices > 2)
3880 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3881 if (num_devices > 3)
3882 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3883 BTRFS_BLOCK_GROUP_RAID6);
3884 if (validate_convert_profile(&bctl->data, allowed)) {
3886 "unable to start balance with target data profile %llu",
3891 if (validate_convert_profile(&bctl->meta, allowed)) {
3893 "unable to start balance with target metadata profile %llu",
3898 if (validate_convert_profile(&bctl->sys, allowed)) {
3900 "unable to start balance with target system profile %llu",
3906 /* allow to reduce meta or sys integrity only if force set */
3907 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3908 BTRFS_BLOCK_GROUP_RAID10 |
3909 BTRFS_BLOCK_GROUP_RAID5 |
3910 BTRFS_BLOCK_GROUP_RAID6;
3912 seq = read_seqbegin(&fs_info->profiles_lock);
3914 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3915 (fs_info->avail_system_alloc_bits & allowed) &&
3916 !(bctl->sys.target & allowed)) ||
3917 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3918 (fs_info->avail_metadata_alloc_bits & allowed) &&
3919 !(bctl->meta.target & allowed))) {
3920 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3922 "force reducing metadata integrity");
3925 "balance will reduce metadata integrity, use force if you want this");
3930 } while (read_seqretry(&fs_info->profiles_lock, seq));
3932 /* if we're not converting, the target field is uninitialized */
3933 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3934 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
3935 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3936 bctl->data.target : fs_info->avail_data_alloc_bits;
3937 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
3938 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
3940 "metadata profile 0x%llx has lower redundancy than data profile 0x%llx",
3941 meta_target, data_target);
3944 ret = insert_balance_item(fs_info, bctl);
3945 if (ret && ret != -EEXIST)
3948 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3949 BUG_ON(ret == -EEXIST);
3950 set_balance_control(bctl);
3952 BUG_ON(ret != -EEXIST);
3953 spin_lock(&fs_info->balance_lock);
3954 update_balance_args(bctl);
3955 spin_unlock(&fs_info->balance_lock);
3958 atomic_inc(&fs_info->balance_running);
3959 mutex_unlock(&fs_info->balance_mutex);
3961 ret = __btrfs_balance(fs_info);
3963 mutex_lock(&fs_info->balance_mutex);
3964 atomic_dec(&fs_info->balance_running);
3967 memset(bargs, 0, sizeof(*bargs));
3968 update_ioctl_balance_args(fs_info, 0, bargs);
3971 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3972 balance_need_close(fs_info)) {
3973 __cancel_balance(fs_info);
3976 wake_up(&fs_info->balance_wait_q);
3980 if (bctl->flags & BTRFS_BALANCE_RESUME)
3981 __cancel_balance(fs_info);
3984 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3989 static int balance_kthread(void *data)
3991 struct btrfs_fs_info *fs_info = data;
3994 mutex_lock(&fs_info->volume_mutex);
3995 mutex_lock(&fs_info->balance_mutex);
3997 if (fs_info->balance_ctl) {
3998 btrfs_info(fs_info, "continuing balance");
3999 ret = btrfs_balance(fs_info->balance_ctl, NULL);
4002 mutex_unlock(&fs_info->balance_mutex);
4003 mutex_unlock(&fs_info->volume_mutex);
4008 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4010 struct task_struct *tsk;
4012 spin_lock(&fs_info->balance_lock);
4013 if (!fs_info->balance_ctl) {
4014 spin_unlock(&fs_info->balance_lock);
4017 spin_unlock(&fs_info->balance_lock);
4019 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4020 btrfs_info(fs_info, "force skipping balance");
4024 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4025 return PTR_ERR_OR_ZERO(tsk);
4028 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4030 struct btrfs_balance_control *bctl;
4031 struct btrfs_balance_item *item;
4032 struct btrfs_disk_balance_args disk_bargs;
4033 struct btrfs_path *path;
4034 struct extent_buffer *leaf;
4035 struct btrfs_key key;
4038 path = btrfs_alloc_path();
4042 key.objectid = BTRFS_BALANCE_OBJECTID;
4043 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4046 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4049 if (ret > 0) { /* ret = -ENOENT; */
4054 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4060 leaf = path->nodes[0];
4061 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4063 bctl->fs_info = fs_info;
4064 bctl->flags = btrfs_balance_flags(leaf, item);
4065 bctl->flags |= BTRFS_BALANCE_RESUME;
4067 btrfs_balance_data(leaf, item, &disk_bargs);
4068 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4069 btrfs_balance_meta(leaf, item, &disk_bargs);
4070 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4071 btrfs_balance_sys(leaf, item, &disk_bargs);
4072 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4074 WARN_ON(test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4076 mutex_lock(&fs_info->volume_mutex);
4077 mutex_lock(&fs_info->balance_mutex);
4079 set_balance_control(bctl);
4081 mutex_unlock(&fs_info->balance_mutex);
4082 mutex_unlock(&fs_info->volume_mutex);
4084 btrfs_free_path(path);
4088 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4092 mutex_lock(&fs_info->balance_mutex);
4093 if (!fs_info->balance_ctl) {
4094 mutex_unlock(&fs_info->balance_mutex);
4098 if (atomic_read(&fs_info->balance_running)) {
4099 atomic_inc(&fs_info->balance_pause_req);
4100 mutex_unlock(&fs_info->balance_mutex);
4102 wait_event(fs_info->balance_wait_q,
4103 atomic_read(&fs_info->balance_running) == 0);
4105 mutex_lock(&fs_info->balance_mutex);
4106 /* we are good with balance_ctl ripped off from under us */
4107 BUG_ON(atomic_read(&fs_info->balance_running));
4108 atomic_dec(&fs_info->balance_pause_req);
4113 mutex_unlock(&fs_info->balance_mutex);
4117 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4119 if (sb_rdonly(fs_info->sb))
4122 mutex_lock(&fs_info->balance_mutex);
4123 if (!fs_info->balance_ctl) {
4124 mutex_unlock(&fs_info->balance_mutex);
4128 atomic_inc(&fs_info->balance_cancel_req);
4130 * if we are running just wait and return, balance item is
4131 * deleted in btrfs_balance in this case
4133 if (atomic_read(&fs_info->balance_running)) {
4134 mutex_unlock(&fs_info->balance_mutex);
4135 wait_event(fs_info->balance_wait_q,
4136 atomic_read(&fs_info->balance_running) == 0);
4137 mutex_lock(&fs_info->balance_mutex);
4139 /* __cancel_balance needs volume_mutex */
4140 mutex_unlock(&fs_info->balance_mutex);
4141 mutex_lock(&fs_info->volume_mutex);
4142 mutex_lock(&fs_info->balance_mutex);
4144 if (fs_info->balance_ctl)
4145 __cancel_balance(fs_info);
4147 mutex_unlock(&fs_info->volume_mutex);
4150 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
4151 atomic_dec(&fs_info->balance_cancel_req);
4152 mutex_unlock(&fs_info->balance_mutex);
4156 static int btrfs_uuid_scan_kthread(void *data)
4158 struct btrfs_fs_info *fs_info = data;
4159 struct btrfs_root *root = fs_info->tree_root;
4160 struct btrfs_key key;
4161 struct btrfs_path *path = NULL;
4163 struct extent_buffer *eb;
4165 struct btrfs_root_item root_item;
4167 struct btrfs_trans_handle *trans = NULL;
4169 path = btrfs_alloc_path();
4176 key.type = BTRFS_ROOT_ITEM_KEY;
4180 ret = btrfs_search_forward(root, &key, path, 0);
4187 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4188 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4189 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4190 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4193 eb = path->nodes[0];
4194 slot = path->slots[0];
4195 item_size = btrfs_item_size_nr(eb, slot);
4196 if (item_size < sizeof(root_item))
4199 read_extent_buffer(eb, &root_item,
4200 btrfs_item_ptr_offset(eb, slot),
4201 (int)sizeof(root_item));
4202 if (btrfs_root_refs(&root_item) == 0)
4205 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4206 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4210 btrfs_release_path(path);
4212 * 1 - subvol uuid item
4213 * 1 - received_subvol uuid item
4215 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4216 if (IS_ERR(trans)) {
4217 ret = PTR_ERR(trans);
4225 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4226 ret = btrfs_uuid_tree_add(trans, fs_info,
4228 BTRFS_UUID_KEY_SUBVOL,
4231 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4237 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4238 ret = btrfs_uuid_tree_add(trans, fs_info,
4239 root_item.received_uuid,
4240 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4243 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4251 ret = btrfs_end_transaction(trans);
4257 btrfs_release_path(path);
4258 if (key.offset < (u64)-1) {
4260 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4262 key.type = BTRFS_ROOT_ITEM_KEY;
4263 } else if (key.objectid < (u64)-1) {
4265 key.type = BTRFS_ROOT_ITEM_KEY;
4274 btrfs_free_path(path);
4275 if (trans && !IS_ERR(trans))
4276 btrfs_end_transaction(trans);
4278 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4280 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4281 up(&fs_info->uuid_tree_rescan_sem);
4286 * Callback for btrfs_uuid_tree_iterate().
4288 * 0 check succeeded, the entry is not outdated.
4289 * < 0 if an error occurred.
4290 * > 0 if the check failed, which means the caller shall remove the entry.
4292 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4293 u8 *uuid, u8 type, u64 subid)
4295 struct btrfs_key key;
4297 struct btrfs_root *subvol_root;
4299 if (type != BTRFS_UUID_KEY_SUBVOL &&
4300 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4303 key.objectid = subid;
4304 key.type = BTRFS_ROOT_ITEM_KEY;
4305 key.offset = (u64)-1;
4306 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4307 if (IS_ERR(subvol_root)) {
4308 ret = PTR_ERR(subvol_root);
4315 case BTRFS_UUID_KEY_SUBVOL:
4316 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4319 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4320 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4330 static int btrfs_uuid_rescan_kthread(void *data)
4332 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4336 * 1st step is to iterate through the existing UUID tree and
4337 * to delete all entries that contain outdated data.
4338 * 2nd step is to add all missing entries to the UUID tree.
4340 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4342 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4343 up(&fs_info->uuid_tree_rescan_sem);
4346 return btrfs_uuid_scan_kthread(data);
4349 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4351 struct btrfs_trans_handle *trans;
4352 struct btrfs_root *tree_root = fs_info->tree_root;
4353 struct btrfs_root *uuid_root;
4354 struct task_struct *task;
4361 trans = btrfs_start_transaction(tree_root, 2);
4363 return PTR_ERR(trans);
4365 uuid_root = btrfs_create_tree(trans, fs_info,
4366 BTRFS_UUID_TREE_OBJECTID);
4367 if (IS_ERR(uuid_root)) {
4368 ret = PTR_ERR(uuid_root);
4369 btrfs_abort_transaction(trans, ret);
4370 btrfs_end_transaction(trans);
4374 fs_info->uuid_root = uuid_root;
4376 ret = btrfs_commit_transaction(trans);
4380 down(&fs_info->uuid_tree_rescan_sem);
4381 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4383 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4384 btrfs_warn(fs_info, "failed to start uuid_scan task");
4385 up(&fs_info->uuid_tree_rescan_sem);
4386 return PTR_ERR(task);
4392 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4394 struct task_struct *task;
4396 down(&fs_info->uuid_tree_rescan_sem);
4397 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4399 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4400 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4401 up(&fs_info->uuid_tree_rescan_sem);
4402 return PTR_ERR(task);
4409 * shrinking a device means finding all of the device extents past
4410 * the new size, and then following the back refs to the chunks.
4411 * The chunk relocation code actually frees the device extent
4413 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4415 struct btrfs_fs_info *fs_info = device->fs_info;
4416 struct btrfs_root *root = fs_info->dev_root;
4417 struct btrfs_trans_handle *trans;
4418 struct btrfs_dev_extent *dev_extent = NULL;
4419 struct btrfs_path *path;
4425 bool retried = false;
4426 bool checked_pending_chunks = false;
4427 struct extent_buffer *l;
4428 struct btrfs_key key;
4429 struct btrfs_super_block *super_copy = fs_info->super_copy;
4430 u64 old_total = btrfs_super_total_bytes(super_copy);
4431 u64 old_size = btrfs_device_get_total_bytes(device);
4434 new_size = round_down(new_size, fs_info->sectorsize);
4435 diff = round_down(old_size - new_size, fs_info->sectorsize);
4437 if (device->is_tgtdev_for_dev_replace)
4440 path = btrfs_alloc_path();
4444 path->reada = READA_FORWARD;
4446 mutex_lock(&fs_info->chunk_mutex);
4448 btrfs_device_set_total_bytes(device, new_size);
4449 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4450 device->fs_devices->total_rw_bytes -= diff;
4451 atomic64_sub(diff, &fs_info->free_chunk_space);
4453 mutex_unlock(&fs_info->chunk_mutex);
4456 key.objectid = device->devid;
4457 key.offset = (u64)-1;
4458 key.type = BTRFS_DEV_EXTENT_KEY;
4461 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4462 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4464 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4468 ret = btrfs_previous_item(root, path, 0, key.type);
4470 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4475 btrfs_release_path(path);
4480 slot = path->slots[0];
4481 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4483 if (key.objectid != device->devid) {
4484 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4485 btrfs_release_path(path);
4489 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4490 length = btrfs_dev_extent_length(l, dev_extent);
4492 if (key.offset + length <= new_size) {
4493 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4494 btrfs_release_path(path);
4498 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4499 btrfs_release_path(path);
4501 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4502 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4503 if (ret && ret != -ENOSPC)
4507 } while (key.offset-- > 0);
4509 if (failed && !retried) {
4513 } else if (failed && retried) {
4518 /* Shrinking succeeded, else we would be at "done". */
4519 trans = btrfs_start_transaction(root, 0);
4520 if (IS_ERR(trans)) {
4521 ret = PTR_ERR(trans);
4525 mutex_lock(&fs_info->chunk_mutex);
4528 * We checked in the above loop all device extents that were already in
4529 * the device tree. However before we have updated the device's
4530 * total_bytes to the new size, we might have had chunk allocations that
4531 * have not complete yet (new block groups attached to transaction
4532 * handles), and therefore their device extents were not yet in the
4533 * device tree and we missed them in the loop above. So if we have any
4534 * pending chunk using a device extent that overlaps the device range
4535 * that we can not use anymore, commit the current transaction and
4536 * repeat the search on the device tree - this way we guarantee we will
4537 * not have chunks using device extents that end beyond 'new_size'.
4539 if (!checked_pending_chunks) {
4540 u64 start = new_size;
4541 u64 len = old_size - new_size;
4543 if (contains_pending_extent(trans->transaction, device,
4545 mutex_unlock(&fs_info->chunk_mutex);
4546 checked_pending_chunks = true;
4549 ret = btrfs_commit_transaction(trans);
4556 btrfs_device_set_disk_total_bytes(device, new_size);
4557 if (list_empty(&device->resized_list))
4558 list_add_tail(&device->resized_list,
4559 &fs_info->fs_devices->resized_devices);
4561 WARN_ON(diff > old_total);
4562 btrfs_set_super_total_bytes(super_copy,
4563 round_down(old_total - diff, fs_info->sectorsize));
4564 mutex_unlock(&fs_info->chunk_mutex);
4566 /* Now btrfs_update_device() will change the on-disk size. */
4567 ret = btrfs_update_device(trans, device);
4568 btrfs_end_transaction(trans);
4570 btrfs_free_path(path);
4572 mutex_lock(&fs_info->chunk_mutex);
4573 btrfs_device_set_total_bytes(device, old_size);
4574 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4575 device->fs_devices->total_rw_bytes += diff;
4576 atomic64_add(diff, &fs_info->free_chunk_space);
4577 mutex_unlock(&fs_info->chunk_mutex);
4582 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4583 struct btrfs_key *key,
4584 struct btrfs_chunk *chunk, int item_size)
4586 struct btrfs_super_block *super_copy = fs_info->super_copy;
4587 struct btrfs_disk_key disk_key;
4591 mutex_lock(&fs_info->chunk_mutex);
4592 array_size = btrfs_super_sys_array_size(super_copy);
4593 if (array_size + item_size + sizeof(disk_key)
4594 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4595 mutex_unlock(&fs_info->chunk_mutex);
4599 ptr = super_copy->sys_chunk_array + array_size;
4600 btrfs_cpu_key_to_disk(&disk_key, key);
4601 memcpy(ptr, &disk_key, sizeof(disk_key));
4602 ptr += sizeof(disk_key);
4603 memcpy(ptr, chunk, item_size);
4604 item_size += sizeof(disk_key);
4605 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4606 mutex_unlock(&fs_info->chunk_mutex);
4612 * sort the devices in descending order by max_avail, total_avail
4614 static int btrfs_cmp_device_info(const void *a, const void *b)
4616 const struct btrfs_device_info *di_a = a;
4617 const struct btrfs_device_info *di_b = b;
4619 if (di_a->max_avail > di_b->max_avail)
4621 if (di_a->max_avail < di_b->max_avail)
4623 if (di_a->total_avail > di_b->total_avail)
4625 if (di_a->total_avail < di_b->total_avail)
4630 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4632 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4635 btrfs_set_fs_incompat(info, RAID56);
4638 #define BTRFS_MAX_DEVS(r) ((BTRFS_MAX_ITEM_SIZE(r->fs_info) \
4639 - sizeof(struct btrfs_chunk)) \
4640 / sizeof(struct btrfs_stripe) + 1)
4642 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4643 - 2 * sizeof(struct btrfs_disk_key) \
4644 - 2 * sizeof(struct btrfs_chunk)) \
4645 / sizeof(struct btrfs_stripe) + 1)
4647 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4648 u64 start, u64 type)
4650 struct btrfs_fs_info *info = trans->fs_info;
4651 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4652 struct btrfs_device *device;
4653 struct map_lookup *map = NULL;
4654 struct extent_map_tree *em_tree;
4655 struct extent_map *em;
4656 struct btrfs_device_info *devices_info = NULL;
4658 int num_stripes; /* total number of stripes to allocate */
4659 int data_stripes; /* number of stripes that count for
4661 int sub_stripes; /* sub_stripes info for map */
4662 int dev_stripes; /* stripes per dev */
4663 int devs_max; /* max devs to use */
4664 int devs_min; /* min devs needed */
4665 int devs_increment; /* ndevs has to be a multiple of this */
4666 int ncopies; /* how many copies to data has */
4668 u64 max_stripe_size;
4677 BUG_ON(!alloc_profile_is_valid(type, 0));
4679 if (list_empty(&fs_devices->alloc_list))
4682 index = __get_raid_index(type);
4684 sub_stripes = btrfs_raid_array[index].sub_stripes;
4685 dev_stripes = btrfs_raid_array[index].dev_stripes;
4686 devs_max = btrfs_raid_array[index].devs_max;
4687 devs_min = btrfs_raid_array[index].devs_min;
4688 devs_increment = btrfs_raid_array[index].devs_increment;
4689 ncopies = btrfs_raid_array[index].ncopies;
4691 if (type & BTRFS_BLOCK_GROUP_DATA) {
4692 max_stripe_size = SZ_1G;
4693 max_chunk_size = 10 * max_stripe_size;
4695 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4696 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4697 /* for larger filesystems, use larger metadata chunks */
4698 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4699 max_stripe_size = SZ_1G;
4701 max_stripe_size = SZ_256M;
4702 max_chunk_size = max_stripe_size;
4704 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4705 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4706 max_stripe_size = SZ_32M;
4707 max_chunk_size = 2 * max_stripe_size;
4709 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4711 btrfs_err(info, "invalid chunk type 0x%llx requested",
4716 /* we don't want a chunk larger than 10% of writeable space */
4717 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4720 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4726 * in the first pass through the devices list, we gather information
4727 * about the available holes on each device.
4730 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4734 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4736 "BTRFS: read-only device in alloc_list\n");
4740 if (!device->in_fs_metadata ||
4741 device->is_tgtdev_for_dev_replace)
4744 if (device->total_bytes > device->bytes_used)
4745 total_avail = device->total_bytes - device->bytes_used;
4749 /* If there is no space on this device, skip it. */
4750 if (total_avail == 0)
4753 ret = find_free_dev_extent(trans, device,
4754 max_stripe_size * dev_stripes,
4755 &dev_offset, &max_avail);
4756 if (ret && ret != -ENOSPC)
4760 max_avail = max_stripe_size * dev_stripes;
4762 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
4765 if (ndevs == fs_devices->rw_devices) {
4766 WARN(1, "%s: found more than %llu devices\n",
4767 __func__, fs_devices->rw_devices);
4770 devices_info[ndevs].dev_offset = dev_offset;
4771 devices_info[ndevs].max_avail = max_avail;
4772 devices_info[ndevs].total_avail = total_avail;
4773 devices_info[ndevs].dev = device;
4778 * now sort the devices by hole size / available space
4780 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4781 btrfs_cmp_device_info, NULL);
4783 /* round down to number of usable stripes */
4784 ndevs = round_down(ndevs, devs_increment);
4786 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
4791 ndevs = min(ndevs, devs_max);
4794 * the primary goal is to maximize the number of stripes, so use as many
4795 * devices as possible, even if the stripes are not maximum sized.
4797 stripe_size = devices_info[ndevs-1].max_avail;
4798 num_stripes = ndevs * dev_stripes;
4801 * this will have to be fixed for RAID1 and RAID10 over
4804 data_stripes = num_stripes / ncopies;
4806 if (type & BTRFS_BLOCK_GROUP_RAID5)
4807 data_stripes = num_stripes - 1;
4809 if (type & BTRFS_BLOCK_GROUP_RAID6)
4810 data_stripes = num_stripes - 2;
4813 * Use the number of data stripes to figure out how big this chunk
4814 * is really going to be in terms of logical address space,
4815 * and compare that answer with the max chunk size
4817 if (stripe_size * data_stripes > max_chunk_size) {
4818 u64 mask = (1ULL << 24) - 1;
4820 stripe_size = div_u64(max_chunk_size, data_stripes);
4822 /* bump the answer up to a 16MB boundary */
4823 stripe_size = (stripe_size + mask) & ~mask;
4825 /* but don't go higher than the limits we found
4826 * while searching for free extents
4828 if (stripe_size > devices_info[ndevs-1].max_avail)
4829 stripe_size = devices_info[ndevs-1].max_avail;
4832 stripe_size = div_u64(stripe_size, dev_stripes);
4834 /* align to BTRFS_STRIPE_LEN */
4835 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
4837 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4842 map->num_stripes = num_stripes;
4844 for (i = 0; i < ndevs; ++i) {
4845 for (j = 0; j < dev_stripes; ++j) {
4846 int s = i * dev_stripes + j;
4847 map->stripes[s].dev = devices_info[i].dev;
4848 map->stripes[s].physical = devices_info[i].dev_offset +
4852 map->stripe_len = BTRFS_STRIPE_LEN;
4853 map->io_align = BTRFS_STRIPE_LEN;
4854 map->io_width = BTRFS_STRIPE_LEN;
4856 map->sub_stripes = sub_stripes;
4858 num_bytes = stripe_size * data_stripes;
4860 trace_btrfs_chunk_alloc(info, map, start, num_bytes);
4862 em = alloc_extent_map();
4868 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4869 em->map_lookup = map;
4871 em->len = num_bytes;
4872 em->block_start = 0;
4873 em->block_len = em->len;
4874 em->orig_block_len = stripe_size;
4876 em_tree = &info->mapping_tree.map_tree;
4877 write_lock(&em_tree->lock);
4878 ret = add_extent_mapping(em_tree, em, 0);
4880 write_unlock(&em_tree->lock);
4881 free_extent_map(em);
4885 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4886 refcount_inc(&em->refs);
4887 write_unlock(&em_tree->lock);
4889 ret = btrfs_make_block_group(trans, info, 0, type, start, num_bytes);
4891 goto error_del_extent;
4893 for (i = 0; i < map->num_stripes; i++) {
4894 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4895 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4898 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
4900 free_extent_map(em);
4901 check_raid56_incompat_flag(info, type);
4903 kfree(devices_info);
4907 write_lock(&em_tree->lock);
4908 remove_extent_mapping(em_tree, em);
4909 write_unlock(&em_tree->lock);
4911 /* One for our allocation */
4912 free_extent_map(em);
4913 /* One for the tree reference */
4914 free_extent_map(em);
4915 /* One for the pending_chunks list reference */
4916 free_extent_map(em);
4918 kfree(devices_info);
4922 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4923 struct btrfs_fs_info *fs_info,
4924 u64 chunk_offset, u64 chunk_size)
4926 struct btrfs_root *extent_root = fs_info->extent_root;
4927 struct btrfs_root *chunk_root = fs_info->chunk_root;
4928 struct btrfs_key key;
4929 struct btrfs_device *device;
4930 struct btrfs_chunk *chunk;
4931 struct btrfs_stripe *stripe;
4932 struct extent_map *em;
4933 struct map_lookup *map;
4940 em = get_chunk_map(fs_info, chunk_offset, chunk_size);
4944 map = em->map_lookup;
4945 item_size = btrfs_chunk_item_size(map->num_stripes);
4946 stripe_size = em->orig_block_len;
4948 chunk = kzalloc(item_size, GFP_NOFS);
4955 * Take the device list mutex to prevent races with the final phase of
4956 * a device replace operation that replaces the device object associated
4957 * with the map's stripes, because the device object's id can change
4958 * at any time during that final phase of the device replace operation
4959 * (dev-replace.c:btrfs_dev_replace_finishing()).
4961 mutex_lock(&fs_info->fs_devices->device_list_mutex);
4962 for (i = 0; i < map->num_stripes; i++) {
4963 device = map->stripes[i].dev;
4964 dev_offset = map->stripes[i].physical;
4966 ret = btrfs_update_device(trans, device);
4969 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
4970 dev_offset, stripe_size);
4975 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4979 stripe = &chunk->stripe;
4980 for (i = 0; i < map->num_stripes; i++) {
4981 device = map->stripes[i].dev;
4982 dev_offset = map->stripes[i].physical;
4984 btrfs_set_stack_stripe_devid(stripe, device->devid);
4985 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4986 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4989 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4991 btrfs_set_stack_chunk_length(chunk, chunk_size);
4992 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4993 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4994 btrfs_set_stack_chunk_type(chunk, map->type);
4995 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4996 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4997 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4998 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
4999 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5001 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5002 key.type = BTRFS_CHUNK_ITEM_KEY;
5003 key.offset = chunk_offset;
5005 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5006 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5008 * TODO: Cleanup of inserted chunk root in case of
5011 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5016 free_extent_map(em);
5021 * Chunk allocation falls into two parts. The first part does works
5022 * that make the new allocated chunk useable, but not do any operation
5023 * that modifies the chunk tree. The second part does the works that
5024 * require modifying the chunk tree. This division is important for the
5025 * bootstrap process of adding storage to a seed btrfs.
5027 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
5028 struct btrfs_fs_info *fs_info, u64 type)
5032 ASSERT(mutex_is_locked(&fs_info->chunk_mutex));
5033 chunk_offset = find_next_chunk(fs_info);
5034 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5037 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5038 struct btrfs_fs_info *fs_info)
5041 u64 sys_chunk_offset;
5045 chunk_offset = find_next_chunk(fs_info);
5046 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5047 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5051 sys_chunk_offset = find_next_chunk(fs_info);
5052 alloc_profile = btrfs_system_alloc_profile(fs_info);
5053 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5057 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5061 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5062 BTRFS_BLOCK_GROUP_RAID10 |
5063 BTRFS_BLOCK_GROUP_RAID5 |
5064 BTRFS_BLOCK_GROUP_DUP)) {
5066 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5075 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5077 struct extent_map *em;
5078 struct map_lookup *map;
5083 em = get_chunk_map(fs_info, chunk_offset, 1);
5087 map = em->map_lookup;
5088 for (i = 0; i < map->num_stripes; i++) {
5089 if (map->stripes[i].dev->missing) {
5093 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5094 &map->stripes[i].dev->dev_state)) {
5101 * If the number of missing devices is larger than max errors,
5102 * we can not write the data into that chunk successfully, so
5105 if (miss_ndevs > btrfs_chunk_max_errors(map))
5108 free_extent_map(em);
5112 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5114 extent_map_tree_init(&tree->map_tree);
5117 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5119 struct extent_map *em;
5122 write_lock(&tree->map_tree.lock);
5123 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5125 remove_extent_mapping(&tree->map_tree, em);
5126 write_unlock(&tree->map_tree.lock);
5130 free_extent_map(em);
5131 /* once for the tree */
5132 free_extent_map(em);
5136 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5138 struct extent_map *em;
5139 struct map_lookup *map;
5142 em = get_chunk_map(fs_info, logical, len);
5145 * We could return errors for these cases, but that could get
5146 * ugly and we'd probably do the same thing which is just not do
5147 * anything else and exit, so return 1 so the callers don't try
5148 * to use other copies.
5152 map = em->map_lookup;
5153 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5154 ret = map->num_stripes;
5155 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5156 ret = map->sub_stripes;
5157 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5159 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5163 free_extent_map(em);
5165 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
5166 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5167 fs_info->dev_replace.tgtdev)
5169 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
5174 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5177 struct extent_map *em;
5178 struct map_lookup *map;
5179 unsigned long len = fs_info->sectorsize;
5181 em = get_chunk_map(fs_info, logical, len);
5183 if (!WARN_ON(IS_ERR(em))) {
5184 map = em->map_lookup;
5185 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5186 len = map->stripe_len * nr_data_stripes(map);
5187 free_extent_map(em);
5192 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5194 struct extent_map *em;
5195 struct map_lookup *map;
5198 em = get_chunk_map(fs_info, logical, len);
5200 if(!WARN_ON(IS_ERR(em))) {
5201 map = em->map_lookup;
5202 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5204 free_extent_map(em);
5209 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5210 struct map_lookup *map, int first, int num,
5211 int optimal, int dev_replace_is_ongoing)
5215 struct btrfs_device *srcdev;
5217 if (dev_replace_is_ongoing &&
5218 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5219 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5220 srcdev = fs_info->dev_replace.srcdev;
5225 * try to avoid the drive that is the source drive for a
5226 * dev-replace procedure, only choose it if no other non-missing
5227 * mirror is available
5229 for (tolerance = 0; tolerance < 2; tolerance++) {
5230 if (map->stripes[optimal].dev->bdev &&
5231 (tolerance || map->stripes[optimal].dev != srcdev))
5233 for (i = first; i < first + num; i++) {
5234 if (map->stripes[i].dev->bdev &&
5235 (tolerance || map->stripes[i].dev != srcdev))
5240 /* we couldn't find one that doesn't fail. Just return something
5241 * and the io error handling code will clean up eventually
5246 static inline int parity_smaller(u64 a, u64 b)
5251 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5252 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5254 struct btrfs_bio_stripe s;
5261 for (i = 0; i < num_stripes - 1; i++) {
5262 if (parity_smaller(bbio->raid_map[i],
5263 bbio->raid_map[i+1])) {
5264 s = bbio->stripes[i];
5265 l = bbio->raid_map[i];
5266 bbio->stripes[i] = bbio->stripes[i+1];
5267 bbio->raid_map[i] = bbio->raid_map[i+1];
5268 bbio->stripes[i+1] = s;
5269 bbio->raid_map[i+1] = l;
5277 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5279 struct btrfs_bio *bbio = kzalloc(
5280 /* the size of the btrfs_bio */
5281 sizeof(struct btrfs_bio) +
5282 /* plus the variable array for the stripes */
5283 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5284 /* plus the variable array for the tgt dev */
5285 sizeof(int) * (real_stripes) +
5287 * plus the raid_map, which includes both the tgt dev
5290 sizeof(u64) * (total_stripes),
5291 GFP_NOFS|__GFP_NOFAIL);
5293 atomic_set(&bbio->error, 0);
5294 refcount_set(&bbio->refs, 1);
5299 void btrfs_get_bbio(struct btrfs_bio *bbio)
5301 WARN_ON(!refcount_read(&bbio->refs));
5302 refcount_inc(&bbio->refs);
5305 void btrfs_put_bbio(struct btrfs_bio *bbio)
5309 if (refcount_dec_and_test(&bbio->refs))
5313 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5315 * Please note that, discard won't be sent to target device of device
5318 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5319 u64 logical, u64 length,
5320 struct btrfs_bio **bbio_ret)
5322 struct extent_map *em;
5323 struct map_lookup *map;
5324 struct btrfs_bio *bbio;
5328 u64 stripe_end_offset;
5335 u32 sub_stripes = 0;
5336 u64 stripes_per_dev = 0;
5337 u32 remaining_stripes = 0;
5338 u32 last_stripe = 0;
5342 /* discard always return a bbio */
5345 em = get_chunk_map(fs_info, logical, length);
5349 map = em->map_lookup;
5350 /* we don't discard raid56 yet */
5351 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5356 offset = logical - em->start;
5357 length = min_t(u64, em->len - offset, length);
5359 stripe_len = map->stripe_len;
5361 * stripe_nr counts the total number of stripes we have to stride
5362 * to get to this block
5364 stripe_nr = div64_u64(offset, stripe_len);
5366 /* stripe_offset is the offset of this block in its stripe */
5367 stripe_offset = offset - stripe_nr * stripe_len;
5369 stripe_nr_end = round_up(offset + length, map->stripe_len);
5370 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5371 stripe_cnt = stripe_nr_end - stripe_nr;
5372 stripe_end_offset = stripe_nr_end * map->stripe_len -
5375 * after this, stripe_nr is the number of stripes on this
5376 * device we have to walk to find the data, and stripe_index is
5377 * the number of our device in the stripe array
5381 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5382 BTRFS_BLOCK_GROUP_RAID10)) {
5383 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5386 sub_stripes = map->sub_stripes;
5388 factor = map->num_stripes / sub_stripes;
5389 num_stripes = min_t(u64, map->num_stripes,
5390 sub_stripes * stripe_cnt);
5391 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5392 stripe_index *= sub_stripes;
5393 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5394 &remaining_stripes);
5395 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5396 last_stripe *= sub_stripes;
5397 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5398 BTRFS_BLOCK_GROUP_DUP)) {
5399 num_stripes = map->num_stripes;
5401 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5405 bbio = alloc_btrfs_bio(num_stripes, 0);
5411 for (i = 0; i < num_stripes; i++) {
5412 bbio->stripes[i].physical =
5413 map->stripes[stripe_index].physical +
5414 stripe_offset + stripe_nr * map->stripe_len;
5415 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5417 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5418 BTRFS_BLOCK_GROUP_RAID10)) {
5419 bbio->stripes[i].length = stripes_per_dev *
5422 if (i / sub_stripes < remaining_stripes)
5423 bbio->stripes[i].length +=
5427 * Special for the first stripe and
5430 * |-------|...|-------|
5434 if (i < sub_stripes)
5435 bbio->stripes[i].length -=
5438 if (stripe_index >= last_stripe &&
5439 stripe_index <= (last_stripe +
5441 bbio->stripes[i].length -=
5444 if (i == sub_stripes - 1)
5447 bbio->stripes[i].length = length;
5451 if (stripe_index == map->num_stripes) {
5458 bbio->map_type = map->type;
5459 bbio->num_stripes = num_stripes;
5461 free_extent_map(em);
5466 * In dev-replace case, for repair case (that's the only case where the mirror
5467 * is selected explicitly when calling btrfs_map_block), blocks left of the
5468 * left cursor can also be read from the target drive.
5470 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5472 * For READ, it also needs to be supported using the same mirror number.
5474 * If the requested block is not left of the left cursor, EIO is returned. This
5475 * can happen because btrfs_num_copies() returns one more in the dev-replace
5478 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5479 u64 logical, u64 length,
5480 u64 srcdev_devid, int *mirror_num,
5483 struct btrfs_bio *bbio = NULL;
5485 int index_srcdev = 0;
5487 u64 physical_of_found = 0;
5491 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5492 logical, &length, &bbio, 0, 0);
5494 ASSERT(bbio == NULL);
5498 num_stripes = bbio->num_stripes;
5499 if (*mirror_num > num_stripes) {
5501 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5502 * that means that the requested area is not left of the left
5505 btrfs_put_bbio(bbio);
5510 * process the rest of the function using the mirror_num of the source
5511 * drive. Therefore look it up first. At the end, patch the device
5512 * pointer to the one of the target drive.
5514 for (i = 0; i < num_stripes; i++) {
5515 if (bbio->stripes[i].dev->devid != srcdev_devid)
5519 * In case of DUP, in order to keep it simple, only add the
5520 * mirror with the lowest physical address
5523 physical_of_found <= bbio->stripes[i].physical)
5528 physical_of_found = bbio->stripes[i].physical;
5531 btrfs_put_bbio(bbio);
5537 *mirror_num = index_srcdev + 1;
5538 *physical = physical_of_found;
5542 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5543 struct btrfs_bio **bbio_ret,
5544 struct btrfs_dev_replace *dev_replace,
5545 int *num_stripes_ret, int *max_errors_ret)
5547 struct btrfs_bio *bbio = *bbio_ret;
5548 u64 srcdev_devid = dev_replace->srcdev->devid;
5549 int tgtdev_indexes = 0;
5550 int num_stripes = *num_stripes_ret;
5551 int max_errors = *max_errors_ret;
5554 if (op == BTRFS_MAP_WRITE) {
5555 int index_where_to_add;
5558 * duplicate the write operations while the dev replace
5559 * procedure is running. Since the copying of the old disk to
5560 * the new disk takes place at run time while the filesystem is
5561 * mounted writable, the regular write operations to the old
5562 * disk have to be duplicated to go to the new disk as well.
5564 * Note that device->missing is handled by the caller, and that
5565 * the write to the old disk is already set up in the stripes
5568 index_where_to_add = num_stripes;
5569 for (i = 0; i < num_stripes; i++) {
5570 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5571 /* write to new disk, too */
5572 struct btrfs_bio_stripe *new =
5573 bbio->stripes + index_where_to_add;
5574 struct btrfs_bio_stripe *old =
5577 new->physical = old->physical;
5578 new->length = old->length;
5579 new->dev = dev_replace->tgtdev;
5580 bbio->tgtdev_map[i] = index_where_to_add;
5581 index_where_to_add++;
5586 num_stripes = index_where_to_add;
5587 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5588 int index_srcdev = 0;
5590 u64 physical_of_found = 0;
5593 * During the dev-replace procedure, the target drive can also
5594 * be used to read data in case it is needed to repair a corrupt
5595 * block elsewhere. This is possible if the requested area is
5596 * left of the left cursor. In this area, the target drive is a
5597 * full copy of the source drive.
5599 for (i = 0; i < num_stripes; i++) {
5600 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5602 * In case of DUP, in order to keep it simple,
5603 * only add the mirror with the lowest physical
5607 physical_of_found <=
5608 bbio->stripes[i].physical)
5612 physical_of_found = bbio->stripes[i].physical;
5616 struct btrfs_bio_stripe *tgtdev_stripe =
5617 bbio->stripes + num_stripes;
5619 tgtdev_stripe->physical = physical_of_found;
5620 tgtdev_stripe->length =
5621 bbio->stripes[index_srcdev].length;
5622 tgtdev_stripe->dev = dev_replace->tgtdev;
5623 bbio->tgtdev_map[index_srcdev] = num_stripes;
5630 *num_stripes_ret = num_stripes;
5631 *max_errors_ret = max_errors;
5632 bbio->num_tgtdevs = tgtdev_indexes;
5636 static bool need_full_stripe(enum btrfs_map_op op)
5638 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5641 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5642 enum btrfs_map_op op,
5643 u64 logical, u64 *length,
5644 struct btrfs_bio **bbio_ret,
5645 int mirror_num, int need_raid_map)
5647 struct extent_map *em;
5648 struct map_lookup *map;
5658 int tgtdev_indexes = 0;
5659 struct btrfs_bio *bbio = NULL;
5660 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5661 int dev_replace_is_ongoing = 0;
5662 int num_alloc_stripes;
5663 int patch_the_first_stripe_for_dev_replace = 0;
5664 u64 physical_to_patch_in_first_stripe = 0;
5665 u64 raid56_full_stripe_start = (u64)-1;
5667 if (op == BTRFS_MAP_DISCARD)
5668 return __btrfs_map_block_for_discard(fs_info, logical,
5671 em = get_chunk_map(fs_info, logical, *length);
5675 map = em->map_lookup;
5676 offset = logical - em->start;
5678 stripe_len = map->stripe_len;
5681 * stripe_nr counts the total number of stripes we have to stride
5682 * to get to this block
5684 stripe_nr = div64_u64(stripe_nr, stripe_len);
5686 stripe_offset = stripe_nr * stripe_len;
5687 if (offset < stripe_offset) {
5689 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
5690 stripe_offset, offset, em->start, logical,
5692 free_extent_map(em);
5696 /* stripe_offset is the offset of this block in its stripe*/
5697 stripe_offset = offset - stripe_offset;
5699 /* if we're here for raid56, we need to know the stripe aligned start */
5700 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5701 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5702 raid56_full_stripe_start = offset;
5704 /* allow a write of a full stripe, but make sure we don't
5705 * allow straddling of stripes
5707 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5709 raid56_full_stripe_start *= full_stripe_len;
5712 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5714 /* For writes to RAID[56], allow a full stripeset across all disks.
5715 For other RAID types and for RAID[56] reads, just allow a single
5716 stripe (on a single disk). */
5717 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5718 (op == BTRFS_MAP_WRITE)) {
5719 max_len = stripe_len * nr_data_stripes(map) -
5720 (offset - raid56_full_stripe_start);
5722 /* we limit the length of each bio to what fits in a stripe */
5723 max_len = stripe_len - stripe_offset;
5725 *length = min_t(u64, em->len - offset, max_len);
5727 *length = em->len - offset;
5730 /* This is for when we're called from btrfs_merge_bio_hook() and all
5731 it cares about is the length */
5735 btrfs_dev_replace_lock(dev_replace, 0);
5736 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5737 if (!dev_replace_is_ongoing)
5738 btrfs_dev_replace_unlock(dev_replace, 0);
5740 btrfs_dev_replace_set_lock_blocking(dev_replace);
5742 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5743 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
5744 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
5745 dev_replace->srcdev->devid,
5747 &physical_to_patch_in_first_stripe);
5751 patch_the_first_stripe_for_dev_replace = 1;
5752 } else if (mirror_num > map->num_stripes) {
5758 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5759 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5761 if (!need_full_stripe(op))
5763 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5764 if (need_full_stripe(op))
5765 num_stripes = map->num_stripes;
5766 else if (mirror_num)
5767 stripe_index = mirror_num - 1;
5769 stripe_index = find_live_mirror(fs_info, map, 0,
5771 current->pid % map->num_stripes,
5772 dev_replace_is_ongoing);
5773 mirror_num = stripe_index + 1;
5776 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5777 if (need_full_stripe(op)) {
5778 num_stripes = map->num_stripes;
5779 } else if (mirror_num) {
5780 stripe_index = mirror_num - 1;
5785 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5786 u32 factor = map->num_stripes / map->sub_stripes;
5788 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5789 stripe_index *= map->sub_stripes;
5791 if (need_full_stripe(op))
5792 num_stripes = map->sub_stripes;
5793 else if (mirror_num)
5794 stripe_index += mirror_num - 1;
5796 int old_stripe_index = stripe_index;
5797 stripe_index = find_live_mirror(fs_info, map,
5799 map->sub_stripes, stripe_index +
5800 current->pid % map->sub_stripes,
5801 dev_replace_is_ongoing);
5802 mirror_num = stripe_index - old_stripe_index + 1;
5805 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5806 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
5807 /* push stripe_nr back to the start of the full stripe */
5808 stripe_nr = div64_u64(raid56_full_stripe_start,
5809 stripe_len * nr_data_stripes(map));
5811 /* RAID[56] write or recovery. Return all stripes */
5812 num_stripes = map->num_stripes;
5813 max_errors = nr_parity_stripes(map);
5815 *length = map->stripe_len;
5820 * Mirror #0 or #1 means the original data block.
5821 * Mirror #2 is RAID5 parity block.
5822 * Mirror #3 is RAID6 Q block.
5824 stripe_nr = div_u64_rem(stripe_nr,
5825 nr_data_stripes(map), &stripe_index);
5827 stripe_index = nr_data_stripes(map) +
5830 /* We distribute the parity blocks across stripes */
5831 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5833 if (!need_full_stripe(op) && mirror_num <= 1)
5838 * after this, stripe_nr is the number of stripes on this
5839 * device we have to walk to find the data, and stripe_index is
5840 * the number of our device in the stripe array
5842 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5844 mirror_num = stripe_index + 1;
5846 if (stripe_index >= map->num_stripes) {
5848 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
5849 stripe_index, map->num_stripes);
5854 num_alloc_stripes = num_stripes;
5855 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
5856 if (op == BTRFS_MAP_WRITE)
5857 num_alloc_stripes <<= 1;
5858 if (op == BTRFS_MAP_GET_READ_MIRRORS)
5859 num_alloc_stripes++;
5860 tgtdev_indexes = num_stripes;
5863 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5868 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
5869 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5871 /* build raid_map */
5872 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
5873 (need_full_stripe(op) || mirror_num > 1)) {
5877 bbio->raid_map = (u64 *)((void *)bbio->stripes +
5878 sizeof(struct btrfs_bio_stripe) *
5880 sizeof(int) * tgtdev_indexes);
5882 /* Work out the disk rotation on this stripe-set */
5883 div_u64_rem(stripe_nr, num_stripes, &rot);
5885 /* Fill in the logical address of each stripe */
5886 tmp = stripe_nr * nr_data_stripes(map);
5887 for (i = 0; i < nr_data_stripes(map); i++)
5888 bbio->raid_map[(i+rot) % num_stripes] =
5889 em->start + (tmp + i) * map->stripe_len;
5891 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5892 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5893 bbio->raid_map[(i+rot+1) % num_stripes] =
5898 for (i = 0; i < num_stripes; i++) {
5899 bbio->stripes[i].physical =
5900 map->stripes[stripe_index].physical +
5902 stripe_nr * map->stripe_len;
5903 bbio->stripes[i].dev =
5904 map->stripes[stripe_index].dev;
5908 if (need_full_stripe(op))
5909 max_errors = btrfs_chunk_max_errors(map);
5912 sort_parity_stripes(bbio, num_stripes);
5914 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
5915 need_full_stripe(op)) {
5916 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
5921 bbio->map_type = map->type;
5922 bbio->num_stripes = num_stripes;
5923 bbio->max_errors = max_errors;
5924 bbio->mirror_num = mirror_num;
5927 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5928 * mirror_num == num_stripes + 1 && dev_replace target drive is
5929 * available as a mirror
5931 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5932 WARN_ON(num_stripes > 1);
5933 bbio->stripes[0].dev = dev_replace->tgtdev;
5934 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5935 bbio->mirror_num = map->num_stripes + 1;
5938 if (dev_replace_is_ongoing) {
5939 btrfs_dev_replace_clear_lock_blocking(dev_replace);
5940 btrfs_dev_replace_unlock(dev_replace, 0);
5942 free_extent_map(em);
5946 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5947 u64 logical, u64 *length,
5948 struct btrfs_bio **bbio_ret, int mirror_num)
5950 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
5954 /* For Scrub/replace */
5955 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5956 u64 logical, u64 *length,
5957 struct btrfs_bio **bbio_ret)
5959 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
5962 int btrfs_rmap_block(struct btrfs_fs_info *fs_info,
5963 u64 chunk_start, u64 physical, u64 devid,
5964 u64 **logical, int *naddrs, int *stripe_len)
5966 struct extent_map *em;
5967 struct map_lookup *map;
5975 em = get_chunk_map(fs_info, chunk_start, 1);
5979 map = em->map_lookup;
5981 rmap_len = map->stripe_len;
5983 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5984 length = div_u64(length, map->num_stripes / map->sub_stripes);
5985 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5986 length = div_u64(length, map->num_stripes);
5987 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5988 length = div_u64(length, nr_data_stripes(map));
5989 rmap_len = map->stripe_len * nr_data_stripes(map);
5992 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
5993 BUG_ON(!buf); /* -ENOMEM */
5995 for (i = 0; i < map->num_stripes; i++) {
5996 if (devid && map->stripes[i].dev->devid != devid)
5998 if (map->stripes[i].physical > physical ||
5999 map->stripes[i].physical + length <= physical)
6002 stripe_nr = physical - map->stripes[i].physical;
6003 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
6005 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6006 stripe_nr = stripe_nr * map->num_stripes + i;
6007 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
6008 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6009 stripe_nr = stripe_nr * map->num_stripes + i;
6010 } /* else if RAID[56], multiply by nr_data_stripes().
6011 * Alternatively, just use rmap_len below instead of
6012 * map->stripe_len */
6014 bytenr = chunk_start + stripe_nr * rmap_len;
6015 WARN_ON(nr >= map->num_stripes);
6016 for (j = 0; j < nr; j++) {
6017 if (buf[j] == bytenr)
6021 WARN_ON(nr >= map->num_stripes);
6028 *stripe_len = rmap_len;
6030 free_extent_map(em);
6034 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6036 bio->bi_private = bbio->private;
6037 bio->bi_end_io = bbio->end_io;
6040 btrfs_put_bbio(bbio);
6043 static void btrfs_end_bio(struct bio *bio)
6045 struct btrfs_bio *bbio = bio->bi_private;
6046 int is_orig_bio = 0;
6048 if (bio->bi_status) {
6049 atomic_inc(&bbio->error);
6050 if (bio->bi_status == BLK_STS_IOERR ||
6051 bio->bi_status == BLK_STS_TARGET) {
6052 unsigned int stripe_index =
6053 btrfs_io_bio(bio)->stripe_index;
6054 struct btrfs_device *dev;
6056 BUG_ON(stripe_index >= bbio->num_stripes);
6057 dev = bbio->stripes[stripe_index].dev;
6059 if (bio_op(bio) == REQ_OP_WRITE)
6060 btrfs_dev_stat_inc_and_print(dev,
6061 BTRFS_DEV_STAT_WRITE_ERRS);
6063 btrfs_dev_stat_inc_and_print(dev,
6064 BTRFS_DEV_STAT_READ_ERRS);
6065 if (bio->bi_opf & REQ_PREFLUSH)
6066 btrfs_dev_stat_inc_and_print(dev,
6067 BTRFS_DEV_STAT_FLUSH_ERRS);
6072 if (bio == bbio->orig_bio)
6075 btrfs_bio_counter_dec(bbio->fs_info);
6077 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6080 bio = bbio->orig_bio;
6083 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6084 /* only send an error to the higher layers if it is
6085 * beyond the tolerance of the btrfs bio
6087 if (atomic_read(&bbio->error) > bbio->max_errors) {
6088 bio->bi_status = BLK_STS_IOERR;
6091 * this bio is actually up to date, we didn't
6092 * go over the max number of errors
6094 bio->bi_status = BLK_STS_OK;
6097 btrfs_end_bbio(bbio, bio);
6098 } else if (!is_orig_bio) {
6104 * see run_scheduled_bios for a description of why bios are collected for
6107 * This will add one bio to the pending list for a device and make sure
6108 * the work struct is scheduled.
6110 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6113 struct btrfs_fs_info *fs_info = device->fs_info;
6114 int should_queue = 1;
6115 struct btrfs_pending_bios *pending_bios;
6117 if (device->missing || !device->bdev) {
6122 /* don't bother with additional async steps for reads, right now */
6123 if (bio_op(bio) == REQ_OP_READ) {
6125 btrfsic_submit_bio(bio);
6130 WARN_ON(bio->bi_next);
6131 bio->bi_next = NULL;
6133 spin_lock(&device->io_lock);
6134 if (op_is_sync(bio->bi_opf))
6135 pending_bios = &device->pending_sync_bios;
6137 pending_bios = &device->pending_bios;
6139 if (pending_bios->tail)
6140 pending_bios->tail->bi_next = bio;
6142 pending_bios->tail = bio;
6143 if (!pending_bios->head)
6144 pending_bios->head = bio;
6145 if (device->running_pending)
6148 spin_unlock(&device->io_lock);
6151 btrfs_queue_work(fs_info->submit_workers, &device->work);
6154 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6155 u64 physical, int dev_nr, int async)
6157 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6158 struct btrfs_fs_info *fs_info = bbio->fs_info;
6160 bio->bi_private = bbio;
6161 btrfs_io_bio(bio)->stripe_index = dev_nr;
6162 bio->bi_end_io = btrfs_end_bio;
6163 bio->bi_iter.bi_sector = physical >> 9;
6166 struct rcu_string *name;
6169 name = rcu_dereference(dev->name);
6170 btrfs_debug(fs_info,
6171 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6172 bio_op(bio), bio->bi_opf,
6173 (u64)bio->bi_iter.bi_sector,
6174 (u_long)dev->bdev->bd_dev, name->str, dev->devid,
6175 bio->bi_iter.bi_size);
6179 bio_set_dev(bio, dev->bdev);
6181 btrfs_bio_counter_inc_noblocked(fs_info);
6184 btrfs_schedule_bio(dev, bio);
6186 btrfsic_submit_bio(bio);
6189 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6191 atomic_inc(&bbio->error);
6192 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6193 /* Should be the original bio. */
6194 WARN_ON(bio != bbio->orig_bio);
6196 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6197 bio->bi_iter.bi_sector = logical >> 9;
6198 if (atomic_read(&bbio->error) > bbio->max_errors)
6199 bio->bi_status = BLK_STS_IOERR;
6201 bio->bi_status = BLK_STS_OK;
6202 btrfs_end_bbio(bbio, bio);
6206 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6207 int mirror_num, int async_submit)
6209 struct btrfs_device *dev;
6210 struct bio *first_bio = bio;
6211 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6217 struct btrfs_bio *bbio = NULL;
6219 length = bio->bi_iter.bi_size;
6220 map_length = length;
6222 btrfs_bio_counter_inc_blocked(fs_info);
6223 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6224 &map_length, &bbio, mirror_num, 1);
6226 btrfs_bio_counter_dec(fs_info);
6227 return errno_to_blk_status(ret);
6230 total_devs = bbio->num_stripes;
6231 bbio->orig_bio = first_bio;
6232 bbio->private = first_bio->bi_private;
6233 bbio->end_io = first_bio->bi_end_io;
6234 bbio->fs_info = fs_info;
6235 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6237 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6238 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6239 /* In this case, map_length has been set to the length of
6240 a single stripe; not the whole write */
6241 if (bio_op(bio) == REQ_OP_WRITE) {
6242 ret = raid56_parity_write(fs_info, bio, bbio,
6245 ret = raid56_parity_recover(fs_info, bio, bbio,
6246 map_length, mirror_num, 1);
6249 btrfs_bio_counter_dec(fs_info);
6250 return errno_to_blk_status(ret);
6253 if (map_length < length) {
6255 "mapping failed logical %llu bio len %llu len %llu",
6256 logical, length, map_length);
6260 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6261 dev = bbio->stripes[dev_nr].dev;
6262 if (!dev || !dev->bdev ||
6263 (bio_op(first_bio) == REQ_OP_WRITE &&
6264 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6265 bbio_error(bbio, first_bio, logical);
6269 if (dev_nr < total_devs - 1)
6270 bio = btrfs_bio_clone(first_bio);
6274 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6275 dev_nr, async_submit);
6277 btrfs_bio_counter_dec(fs_info);
6281 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
6284 struct btrfs_device *device;
6285 struct btrfs_fs_devices *cur_devices;
6287 cur_devices = fs_info->fs_devices;
6288 while (cur_devices) {
6290 !memcmp(cur_devices->fsid, fsid, BTRFS_FSID_SIZE)) {
6291 device = find_device(cur_devices, devid, uuid);
6295 cur_devices = cur_devices->seed;
6300 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6301 u64 devid, u8 *dev_uuid)
6303 struct btrfs_device *device;
6305 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6309 list_add(&device->dev_list, &fs_devices->devices);
6310 device->fs_devices = fs_devices;
6311 fs_devices->num_devices++;
6313 device->missing = 1;
6314 fs_devices->missing_devices++;
6320 * btrfs_alloc_device - allocate struct btrfs_device
6321 * @fs_info: used only for generating a new devid, can be NULL if
6322 * devid is provided (i.e. @devid != NULL).
6323 * @devid: a pointer to devid for this device. If NULL a new devid
6325 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6328 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6329 * on error. Returned struct is not linked onto any lists and must be
6330 * destroyed with free_device.
6332 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6336 struct btrfs_device *dev;
6339 if (WARN_ON(!devid && !fs_info))
6340 return ERR_PTR(-EINVAL);
6342 dev = __alloc_device();
6351 ret = find_next_devid(fs_info, &tmp);
6354 return ERR_PTR(ret);
6360 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6362 generate_random_uuid(dev->uuid);
6364 btrfs_init_work(&dev->work, btrfs_submit_helper,
6365 pending_bios_fn, NULL, NULL);
6370 /* Return -EIO if any error, otherwise return 0. */
6371 static int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info,
6372 struct extent_buffer *leaf,
6373 struct btrfs_chunk *chunk, u64 logical)
6381 length = btrfs_chunk_length(leaf, chunk);
6382 stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6383 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6384 sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6385 type = btrfs_chunk_type(leaf, chunk);
6388 btrfs_err(fs_info, "invalid chunk num_stripes: %u",
6392 if (!IS_ALIGNED(logical, fs_info->sectorsize)) {
6393 btrfs_err(fs_info, "invalid chunk logical %llu", logical);
6396 if (btrfs_chunk_sector_size(leaf, chunk) != fs_info->sectorsize) {
6397 btrfs_err(fs_info, "invalid chunk sectorsize %u",
6398 btrfs_chunk_sector_size(leaf, chunk));
6401 if (!length || !IS_ALIGNED(length, fs_info->sectorsize)) {
6402 btrfs_err(fs_info, "invalid chunk length %llu", length);
6405 if (!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN) {
6406 btrfs_err(fs_info, "invalid chunk stripe length: %llu",
6410 if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6412 btrfs_err(fs_info, "unrecognized chunk type: %llu",
6413 ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
6414 BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6415 btrfs_chunk_type(leaf, chunk));
6418 if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes != 2) ||
6419 (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes < 1) ||
6420 (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
6421 (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
6422 (type & BTRFS_BLOCK_GROUP_DUP && num_stripes > 2) ||
6423 ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
6424 num_stripes != 1)) {
6426 "invalid num_stripes:sub_stripes %u:%u for profile %llu",
6427 num_stripes, sub_stripes,
6428 type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
6435 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6436 u64 devid, u8 *uuid, bool error)
6439 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6442 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6446 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6447 struct extent_buffer *leaf,
6448 struct btrfs_chunk *chunk)
6450 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6451 struct map_lookup *map;
6452 struct extent_map *em;
6456 u8 uuid[BTRFS_UUID_SIZE];
6461 logical = key->offset;
6462 length = btrfs_chunk_length(leaf, chunk);
6463 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6465 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6469 read_lock(&map_tree->map_tree.lock);
6470 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6471 read_unlock(&map_tree->map_tree.lock);
6473 /* already mapped? */
6474 if (em && em->start <= logical && em->start + em->len > logical) {
6475 free_extent_map(em);
6478 free_extent_map(em);
6481 em = alloc_extent_map();
6484 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6486 free_extent_map(em);
6490 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6491 em->map_lookup = map;
6492 em->start = logical;
6495 em->block_start = 0;
6496 em->block_len = em->len;
6498 map->num_stripes = num_stripes;
6499 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6500 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6501 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6502 map->type = btrfs_chunk_type(leaf, chunk);
6503 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6504 for (i = 0; i < num_stripes; i++) {
6505 map->stripes[i].physical =
6506 btrfs_stripe_offset_nr(leaf, chunk, i);
6507 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6508 read_extent_buffer(leaf, uuid, (unsigned long)
6509 btrfs_stripe_dev_uuid_nr(chunk, i),
6511 map->stripes[i].dev = btrfs_find_device(fs_info, devid,
6513 if (!map->stripes[i].dev &&
6514 !btrfs_test_opt(fs_info, DEGRADED)) {
6515 free_extent_map(em);
6516 btrfs_report_missing_device(fs_info, devid, uuid, true);
6519 if (!map->stripes[i].dev) {
6520 map->stripes[i].dev =
6521 add_missing_dev(fs_info->fs_devices, devid,
6523 if (IS_ERR(map->stripes[i].dev)) {
6524 free_extent_map(em);
6526 "failed to init missing dev %llu: %ld",
6527 devid, PTR_ERR(map->stripes[i].dev));
6528 return PTR_ERR(map->stripes[i].dev);
6530 btrfs_report_missing_device(fs_info, devid, uuid, false);
6532 map->stripes[i].dev->in_fs_metadata = 1;
6535 write_lock(&map_tree->map_tree.lock);
6536 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6537 write_unlock(&map_tree->map_tree.lock);
6538 BUG_ON(ret); /* Tree corruption */
6539 free_extent_map(em);
6544 static void fill_device_from_item(struct extent_buffer *leaf,
6545 struct btrfs_dev_item *dev_item,
6546 struct btrfs_device *device)
6550 device->devid = btrfs_device_id(leaf, dev_item);
6551 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6552 device->total_bytes = device->disk_total_bytes;
6553 device->commit_total_bytes = device->disk_total_bytes;
6554 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6555 device->commit_bytes_used = device->bytes_used;
6556 device->type = btrfs_device_type(leaf, dev_item);
6557 device->io_align = btrfs_device_io_align(leaf, dev_item);
6558 device->io_width = btrfs_device_io_width(leaf, dev_item);
6559 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6560 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6561 device->is_tgtdev_for_dev_replace = 0;
6563 ptr = btrfs_device_uuid(dev_item);
6564 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6567 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6570 struct btrfs_fs_devices *fs_devices;
6573 BUG_ON(!mutex_is_locked(&uuid_mutex));
6576 fs_devices = fs_info->fs_devices->seed;
6577 while (fs_devices) {
6578 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6581 fs_devices = fs_devices->seed;
6584 fs_devices = find_fsid(fsid);
6586 if (!btrfs_test_opt(fs_info, DEGRADED))
6587 return ERR_PTR(-ENOENT);
6589 fs_devices = alloc_fs_devices(fsid);
6590 if (IS_ERR(fs_devices))
6593 fs_devices->seeding = 1;
6594 fs_devices->opened = 1;
6598 fs_devices = clone_fs_devices(fs_devices);
6599 if (IS_ERR(fs_devices))
6602 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
6603 fs_info->bdev_holder);
6605 free_fs_devices(fs_devices);
6606 fs_devices = ERR_PTR(ret);
6610 if (!fs_devices->seeding) {
6611 __btrfs_close_devices(fs_devices);
6612 free_fs_devices(fs_devices);
6613 fs_devices = ERR_PTR(-EINVAL);
6617 fs_devices->seed = fs_info->fs_devices->seed;
6618 fs_info->fs_devices->seed = fs_devices;
6623 static int read_one_dev(struct btrfs_fs_info *fs_info,
6624 struct extent_buffer *leaf,
6625 struct btrfs_dev_item *dev_item)
6627 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6628 struct btrfs_device *device;
6631 u8 fs_uuid[BTRFS_FSID_SIZE];
6632 u8 dev_uuid[BTRFS_UUID_SIZE];
6634 devid = btrfs_device_id(leaf, dev_item);
6635 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6637 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6640 if (memcmp(fs_uuid, fs_info->fsid, BTRFS_FSID_SIZE)) {
6641 fs_devices = open_seed_devices(fs_info, fs_uuid);
6642 if (IS_ERR(fs_devices))
6643 return PTR_ERR(fs_devices);
6646 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
6648 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6649 btrfs_report_missing_device(fs_info, devid,
6654 device = add_missing_dev(fs_devices, devid, dev_uuid);
6655 if (IS_ERR(device)) {
6657 "failed to add missing dev %llu: %ld",
6658 devid, PTR_ERR(device));
6659 return PTR_ERR(device);
6661 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6663 if (!device->bdev) {
6664 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6665 btrfs_report_missing_device(fs_info,
6666 devid, dev_uuid, true);
6669 btrfs_report_missing_device(fs_info, devid,
6673 if(!device->bdev && !device->missing) {
6675 * this happens when a device that was properly setup
6676 * in the device info lists suddenly goes bad.
6677 * device->bdev is NULL, and so we have to set
6678 * device->missing to one here
6680 device->fs_devices->missing_devices++;
6681 device->missing = 1;
6684 /* Move the device to its own fs_devices */
6685 if (device->fs_devices != fs_devices) {
6686 ASSERT(device->missing);
6688 list_move(&device->dev_list, &fs_devices->devices);
6689 device->fs_devices->num_devices--;
6690 fs_devices->num_devices++;
6692 device->fs_devices->missing_devices--;
6693 fs_devices->missing_devices++;
6695 device->fs_devices = fs_devices;
6699 if (device->fs_devices != fs_info->fs_devices) {
6700 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6701 if (device->generation !=
6702 btrfs_device_generation(leaf, dev_item))
6706 fill_device_from_item(leaf, dev_item, device);
6707 device->in_fs_metadata = 1;
6708 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6709 !device->is_tgtdev_for_dev_replace) {
6710 device->fs_devices->total_rw_bytes += device->total_bytes;
6711 atomic64_add(device->total_bytes - device->bytes_used,
6712 &fs_info->free_chunk_space);
6718 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6720 struct btrfs_root *root = fs_info->tree_root;
6721 struct btrfs_super_block *super_copy = fs_info->super_copy;
6722 struct extent_buffer *sb;
6723 struct btrfs_disk_key *disk_key;
6724 struct btrfs_chunk *chunk;
6726 unsigned long sb_array_offset;
6733 struct btrfs_key key;
6735 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6737 * This will create extent buffer of nodesize, superblock size is
6738 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6739 * overallocate but we can keep it as-is, only the first page is used.
6741 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6744 set_extent_buffer_uptodate(sb);
6745 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6747 * The sb extent buffer is artificial and just used to read the system array.
6748 * set_extent_buffer_uptodate() call does not properly mark all it's
6749 * pages up-to-date when the page is larger: extent does not cover the
6750 * whole page and consequently check_page_uptodate does not find all
6751 * the page's extents up-to-date (the hole beyond sb),
6752 * write_extent_buffer then triggers a WARN_ON.
6754 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6755 * but sb spans only this function. Add an explicit SetPageUptodate call
6756 * to silence the warning eg. on PowerPC 64.
6758 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6759 SetPageUptodate(sb->pages[0]);
6761 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6762 array_size = btrfs_super_sys_array_size(super_copy);
6764 array_ptr = super_copy->sys_chunk_array;
6765 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6768 while (cur_offset < array_size) {
6769 disk_key = (struct btrfs_disk_key *)array_ptr;
6770 len = sizeof(*disk_key);
6771 if (cur_offset + len > array_size)
6772 goto out_short_read;
6774 btrfs_disk_key_to_cpu(&key, disk_key);
6777 sb_array_offset += len;
6780 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6781 chunk = (struct btrfs_chunk *)sb_array_offset;
6783 * At least one btrfs_chunk with one stripe must be
6784 * present, exact stripe count check comes afterwards
6786 len = btrfs_chunk_item_size(1);
6787 if (cur_offset + len > array_size)
6788 goto out_short_read;
6790 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6793 "invalid number of stripes %u in sys_array at offset %u",
6794 num_stripes, cur_offset);
6799 type = btrfs_chunk_type(sb, chunk);
6800 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6802 "invalid chunk type %llu in sys_array at offset %u",
6808 len = btrfs_chunk_item_size(num_stripes);
6809 if (cur_offset + len > array_size)
6810 goto out_short_read;
6812 ret = read_one_chunk(fs_info, &key, sb, chunk);
6817 "unexpected item type %u in sys_array at offset %u",
6818 (u32)key.type, cur_offset);
6823 sb_array_offset += len;
6826 clear_extent_buffer_uptodate(sb);
6827 free_extent_buffer_stale(sb);
6831 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6833 clear_extent_buffer_uptodate(sb);
6834 free_extent_buffer_stale(sb);
6839 * Check if all chunks in the fs are OK for read-write degraded mount
6841 * Return true if all chunks meet the minimal RW mount requirements.
6842 * Return false if any chunk doesn't meet the minimal RW mount requirements.
6844 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info)
6846 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6847 struct extent_map *em;
6851 read_lock(&map_tree->map_tree.lock);
6852 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
6853 read_unlock(&map_tree->map_tree.lock);
6854 /* No chunk at all? Return false anyway */
6860 struct map_lookup *map;
6865 map = em->map_lookup;
6867 btrfs_get_num_tolerated_disk_barrier_failures(
6869 for (i = 0; i < map->num_stripes; i++) {
6870 struct btrfs_device *dev = map->stripes[i].dev;
6872 if (!dev || !dev->bdev || dev->missing ||
6873 dev->last_flush_error)
6876 if (missing > max_tolerated) {
6878 "chunk %llu missing %d devices, max tolerance is %d for writeable mount",
6879 em->start, missing, max_tolerated);
6880 free_extent_map(em);
6884 next_start = extent_map_end(em);
6885 free_extent_map(em);
6887 read_lock(&map_tree->map_tree.lock);
6888 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
6889 (u64)(-1) - next_start);
6890 read_unlock(&map_tree->map_tree.lock);
6896 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
6898 struct btrfs_root *root = fs_info->chunk_root;
6899 struct btrfs_path *path;
6900 struct extent_buffer *leaf;
6901 struct btrfs_key key;
6902 struct btrfs_key found_key;
6907 path = btrfs_alloc_path();
6911 mutex_lock(&uuid_mutex);
6912 mutex_lock(&fs_info->chunk_mutex);
6915 * Read all device items, and then all the chunk items. All
6916 * device items are found before any chunk item (their object id
6917 * is smaller than the lowest possible object id for a chunk
6918 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6920 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6923 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6927 leaf = path->nodes[0];
6928 slot = path->slots[0];
6929 if (slot >= btrfs_header_nritems(leaf)) {
6930 ret = btrfs_next_leaf(root, path);
6937 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6938 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6939 struct btrfs_dev_item *dev_item;
6940 dev_item = btrfs_item_ptr(leaf, slot,
6941 struct btrfs_dev_item);
6942 ret = read_one_dev(fs_info, leaf, dev_item);
6946 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6947 struct btrfs_chunk *chunk;
6948 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6949 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
6957 * After loading chunk tree, we've got all device information,
6958 * do another round of validation checks.
6960 if (total_dev != fs_info->fs_devices->total_devices) {
6962 "super_num_devices %llu mismatch with num_devices %llu found here",
6963 btrfs_super_num_devices(fs_info->super_copy),
6968 if (btrfs_super_total_bytes(fs_info->super_copy) <
6969 fs_info->fs_devices->total_rw_bytes) {
6971 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
6972 btrfs_super_total_bytes(fs_info->super_copy),
6973 fs_info->fs_devices->total_rw_bytes);
6979 mutex_unlock(&fs_info->chunk_mutex);
6980 mutex_unlock(&uuid_mutex);
6982 btrfs_free_path(path);
6986 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6988 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6989 struct btrfs_device *device;
6991 while (fs_devices) {
6992 mutex_lock(&fs_devices->device_list_mutex);
6993 list_for_each_entry(device, &fs_devices->devices, dev_list)
6994 device->fs_info = fs_info;
6995 mutex_unlock(&fs_devices->device_list_mutex);
6997 fs_devices = fs_devices->seed;
7001 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
7005 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7006 btrfs_dev_stat_reset(dev, i);
7009 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7011 struct btrfs_key key;
7012 struct btrfs_key found_key;
7013 struct btrfs_root *dev_root = fs_info->dev_root;
7014 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7015 struct extent_buffer *eb;
7018 struct btrfs_device *device;
7019 struct btrfs_path *path = NULL;
7022 path = btrfs_alloc_path();
7028 mutex_lock(&fs_devices->device_list_mutex);
7029 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7031 struct btrfs_dev_stats_item *ptr;
7033 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7034 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7035 key.offset = device->devid;
7036 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7038 __btrfs_reset_dev_stats(device);
7039 device->dev_stats_valid = 1;
7040 btrfs_release_path(path);
7043 slot = path->slots[0];
7044 eb = path->nodes[0];
7045 btrfs_item_key_to_cpu(eb, &found_key, slot);
7046 item_size = btrfs_item_size_nr(eb, slot);
7048 ptr = btrfs_item_ptr(eb, slot,
7049 struct btrfs_dev_stats_item);
7051 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7052 if (item_size >= (1 + i) * sizeof(__le64))
7053 btrfs_dev_stat_set(device, i,
7054 btrfs_dev_stats_value(eb, ptr, i));
7056 btrfs_dev_stat_reset(device, i);
7059 device->dev_stats_valid = 1;
7060 btrfs_dev_stat_print_on_load(device);
7061 btrfs_release_path(path);
7063 mutex_unlock(&fs_devices->device_list_mutex);
7066 btrfs_free_path(path);
7067 return ret < 0 ? ret : 0;
7070 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7071 struct btrfs_fs_info *fs_info,
7072 struct btrfs_device *device)
7074 struct btrfs_root *dev_root = fs_info->dev_root;
7075 struct btrfs_path *path;
7076 struct btrfs_key key;
7077 struct extent_buffer *eb;
7078 struct btrfs_dev_stats_item *ptr;
7082 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7083 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7084 key.offset = device->devid;
7086 path = btrfs_alloc_path();
7089 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7091 btrfs_warn_in_rcu(fs_info,
7092 "error %d while searching for dev_stats item for device %s",
7093 ret, rcu_str_deref(device->name));
7098 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7099 /* need to delete old one and insert a new one */
7100 ret = btrfs_del_item(trans, dev_root, path);
7102 btrfs_warn_in_rcu(fs_info,
7103 "delete too small dev_stats item for device %s failed %d",
7104 rcu_str_deref(device->name), ret);
7111 /* need to insert a new item */
7112 btrfs_release_path(path);
7113 ret = btrfs_insert_empty_item(trans, dev_root, path,
7114 &key, sizeof(*ptr));
7116 btrfs_warn_in_rcu(fs_info,
7117 "insert dev_stats item for device %s failed %d",
7118 rcu_str_deref(device->name), ret);
7123 eb = path->nodes[0];
7124 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7125 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7126 btrfs_set_dev_stats_value(eb, ptr, i,
7127 btrfs_dev_stat_read(device, i));
7128 btrfs_mark_buffer_dirty(eb);
7131 btrfs_free_path(path);
7136 * called from commit_transaction. Writes all changed device stats to disk.
7138 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7139 struct btrfs_fs_info *fs_info)
7141 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7142 struct btrfs_device *device;
7146 mutex_lock(&fs_devices->device_list_mutex);
7147 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7148 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7149 if (!device->dev_stats_valid || stats_cnt == 0)
7154 * There is a LOAD-LOAD control dependency between the value of
7155 * dev_stats_ccnt and updating the on-disk values which requires
7156 * reading the in-memory counters. Such control dependencies
7157 * require explicit read memory barriers.
7159 * This memory barriers pairs with smp_mb__before_atomic in
7160 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7161 * barrier implied by atomic_xchg in
7162 * btrfs_dev_stats_read_and_reset
7166 ret = update_dev_stat_item(trans, fs_info, device);
7168 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7170 mutex_unlock(&fs_devices->device_list_mutex);
7175 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7177 btrfs_dev_stat_inc(dev, index);
7178 btrfs_dev_stat_print_on_error(dev);
7181 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7183 if (!dev->dev_stats_valid)
7185 btrfs_err_rl_in_rcu(dev->fs_info,
7186 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7187 rcu_str_deref(dev->name),
7188 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7189 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7190 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7191 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7192 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7195 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7199 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7200 if (btrfs_dev_stat_read(dev, i) != 0)
7202 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7203 return; /* all values == 0, suppress message */
7205 btrfs_info_in_rcu(dev->fs_info,
7206 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7207 rcu_str_deref(dev->name),
7208 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7209 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7210 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7211 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7212 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7215 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7216 struct btrfs_ioctl_get_dev_stats *stats)
7218 struct btrfs_device *dev;
7219 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7222 mutex_lock(&fs_devices->device_list_mutex);
7223 dev = btrfs_find_device(fs_info, stats->devid, NULL, NULL);
7224 mutex_unlock(&fs_devices->device_list_mutex);
7227 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7229 } else if (!dev->dev_stats_valid) {
7230 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7232 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7233 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7234 if (stats->nr_items > i)
7236 btrfs_dev_stat_read_and_reset(dev, i);
7238 btrfs_dev_stat_reset(dev, i);
7241 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7242 if (stats->nr_items > i)
7243 stats->values[i] = btrfs_dev_stat_read(dev, i);
7245 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7246 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7250 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7252 struct buffer_head *bh;
7253 struct btrfs_super_block *disk_super;
7259 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7262 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7265 disk_super = (struct btrfs_super_block *)bh->b_data;
7267 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7268 set_buffer_dirty(bh);
7269 sync_dirty_buffer(bh);
7273 /* Notify udev that device has changed */
7274 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7276 /* Update ctime/mtime for device path for libblkid */
7277 update_dev_time(device_path);
7281 * Update the size of all devices, which is used for writing out the
7284 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7286 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7287 struct btrfs_device *curr, *next;
7289 if (list_empty(&fs_devices->resized_devices))
7292 mutex_lock(&fs_devices->device_list_mutex);
7293 mutex_lock(&fs_info->chunk_mutex);
7294 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7296 list_del_init(&curr->resized_list);
7297 curr->commit_total_bytes = curr->disk_total_bytes;
7299 mutex_unlock(&fs_info->chunk_mutex);
7300 mutex_unlock(&fs_devices->device_list_mutex);
7303 /* Must be invoked during the transaction commit */
7304 void btrfs_update_commit_device_bytes_used(struct btrfs_fs_info *fs_info,
7305 struct btrfs_transaction *transaction)
7307 struct extent_map *em;
7308 struct map_lookup *map;
7309 struct btrfs_device *dev;
7312 if (list_empty(&transaction->pending_chunks))
7315 /* In order to kick the device replace finish process */
7316 mutex_lock(&fs_info->chunk_mutex);
7317 list_for_each_entry(em, &transaction->pending_chunks, list) {
7318 map = em->map_lookup;
7320 for (i = 0; i < map->num_stripes; i++) {
7321 dev = map->stripes[i].dev;
7322 dev->commit_bytes_used = dev->bytes_used;
7325 mutex_unlock(&fs_info->chunk_mutex);
7328 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7330 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7331 while (fs_devices) {
7332 fs_devices->fs_info = fs_info;
7333 fs_devices = fs_devices->seed;
7337 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7339 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7340 while (fs_devices) {
7341 fs_devices->fs_info = NULL;
7342 fs_devices = fs_devices->seed;