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 <linux/list_sort.h>
31 #include <asm/div64.h>
33 #include "extent_map.h"
35 #include "transaction.h"
36 #include "print-tree.h"
39 #include "async-thread.h"
40 #include "check-integrity.h"
41 #include "rcu-string.h"
43 #include "dev-replace.h"
46 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
47 [BTRFS_RAID_RAID10] = {
50 .devs_max = 0, /* 0 == as many as possible */
52 .tolerated_failures = 1,
56 [BTRFS_RAID_RAID1] = {
61 .tolerated_failures = 1,
70 .tolerated_failures = 0,
74 [BTRFS_RAID_RAID0] = {
79 .tolerated_failures = 0,
83 [BTRFS_RAID_SINGLE] = {
88 .tolerated_failures = 0,
92 [BTRFS_RAID_RAID5] = {
97 .tolerated_failures = 1,
101 [BTRFS_RAID_RAID6] = {
106 .tolerated_failures = 2,
112 const u64 btrfs_raid_group[BTRFS_NR_RAID_TYPES] = {
113 [BTRFS_RAID_RAID10] = BTRFS_BLOCK_GROUP_RAID10,
114 [BTRFS_RAID_RAID1] = BTRFS_BLOCK_GROUP_RAID1,
115 [BTRFS_RAID_DUP] = BTRFS_BLOCK_GROUP_DUP,
116 [BTRFS_RAID_RAID0] = BTRFS_BLOCK_GROUP_RAID0,
117 [BTRFS_RAID_SINGLE] = 0,
118 [BTRFS_RAID_RAID5] = BTRFS_BLOCK_GROUP_RAID5,
119 [BTRFS_RAID_RAID6] = BTRFS_BLOCK_GROUP_RAID6,
123 * Table to convert BTRFS_RAID_* to the error code if minimum number of devices
124 * condition is not met. Zero means there's no corresponding
125 * BTRFS_ERROR_DEV_*_NOT_MET value.
127 const int btrfs_raid_mindev_error[BTRFS_NR_RAID_TYPES] = {
128 [BTRFS_RAID_RAID10] = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
129 [BTRFS_RAID_RAID1] = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
130 [BTRFS_RAID_DUP] = 0,
131 [BTRFS_RAID_RAID0] = 0,
132 [BTRFS_RAID_SINGLE] = 0,
133 [BTRFS_RAID_RAID5] = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
134 [BTRFS_RAID_RAID6] = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
137 static int init_first_rw_device(struct btrfs_trans_handle *trans,
138 struct btrfs_fs_info *fs_info);
139 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
140 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
141 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
142 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
143 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
144 enum btrfs_map_op op,
145 u64 logical, u64 *length,
146 struct btrfs_bio **bbio_ret,
147 int mirror_num, int need_raid_map);
153 * There are several mutexes that protect manipulation of devices and low-level
154 * structures like chunks but not block groups, extents or files
156 * uuid_mutex (global lock)
157 * ------------------------
158 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
159 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
160 * device) or requested by the device= mount option
162 * the mutex can be very coarse and can cover long-running operations
164 * protects: updates to fs_devices counters like missing devices, rw devices,
165 * seeding, structure cloning, openning/closing devices at mount/umount time
167 * global::fs_devs - add, remove, updates to the global list
169 * does not protect: manipulation of the fs_devices::devices list!
171 * btrfs_device::name - renames (write side), read is RCU
173 * fs_devices::device_list_mutex (per-fs, with RCU)
174 * ------------------------------------------------
175 * protects updates to fs_devices::devices, ie. adding and deleting
177 * simple list traversal with read-only actions can be done with RCU protection
179 * may be used to exclude some operations from running concurrently without any
180 * modifications to the list (see write_all_supers)
184 * coarse lock owned by a mounted filesystem; used to exclude some operations
185 * that cannot run in parallel and affect the higher-level properties of the
186 * filesystem like: device add/deleting/resize/replace, or balance
190 * protects balance structures (status, state) and context accessed from
191 * several places (internally, ioctl)
195 * protects chunks, adding or removing during allocation, trim or when a new
196 * device is added/removed
200 * a big lock that is held by the cleaner thread and prevents running subvolume
201 * cleaning together with relocation or delayed iputs
214 DEFINE_MUTEX(uuid_mutex);
215 static LIST_HEAD(fs_uuids);
216 struct list_head *btrfs_get_fs_uuids(void)
222 * alloc_fs_devices - allocate struct btrfs_fs_devices
223 * @fsid: if not NULL, copy the uuid to fs_devices::fsid
225 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
226 * The returned struct is not linked onto any lists and can be destroyed with
227 * kfree() right away.
229 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
231 struct btrfs_fs_devices *fs_devs;
233 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
235 return ERR_PTR(-ENOMEM);
237 mutex_init(&fs_devs->device_list_mutex);
239 INIT_LIST_HEAD(&fs_devs->devices);
240 INIT_LIST_HEAD(&fs_devs->resized_devices);
241 INIT_LIST_HEAD(&fs_devs->alloc_list);
242 INIT_LIST_HEAD(&fs_devs->list);
244 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
249 static void free_device(struct btrfs_device *device)
251 rcu_string_free(device->name);
252 bio_put(device->flush_bio);
256 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
258 struct btrfs_device *device;
259 WARN_ON(fs_devices->opened);
260 while (!list_empty(&fs_devices->devices)) {
261 device = list_entry(fs_devices->devices.next,
262 struct btrfs_device, dev_list);
263 list_del(&device->dev_list);
269 static void btrfs_kobject_uevent(struct block_device *bdev,
270 enum kobject_action action)
274 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
276 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
278 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
279 &disk_to_dev(bdev->bd_disk)->kobj);
282 void __exit btrfs_cleanup_fs_uuids(void)
284 struct btrfs_fs_devices *fs_devices;
286 while (!list_empty(&fs_uuids)) {
287 fs_devices = list_entry(fs_uuids.next,
288 struct btrfs_fs_devices, list);
289 list_del(&fs_devices->list);
290 free_fs_devices(fs_devices);
295 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
296 * Returned struct is not linked onto any lists and must be destroyed using
299 static struct btrfs_device *__alloc_device(void)
301 struct btrfs_device *dev;
303 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
305 return ERR_PTR(-ENOMEM);
308 * Preallocate a bio that's always going to be used for flushing device
309 * barriers and matches the device lifespan
311 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
312 if (!dev->flush_bio) {
314 return ERR_PTR(-ENOMEM);
317 INIT_LIST_HEAD(&dev->dev_list);
318 INIT_LIST_HEAD(&dev->dev_alloc_list);
319 INIT_LIST_HEAD(&dev->resized_list);
321 spin_lock_init(&dev->io_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 * Search and remove all stale (devices which are not mounted) devices.
610 * When both inputs are NULL, it will search and release all stale devices.
611 * path: Optional. When provided will it release all unmounted devices
612 * matching this path only.
613 * skip_dev: Optional. Will skip this device when searching for the stale
616 static void btrfs_free_stale_devices(const char *path,
617 struct btrfs_device *skip_dev)
619 struct btrfs_fs_devices *fs_devs, *tmp_fs_devs;
620 struct btrfs_device *dev, *tmp_dev;
622 list_for_each_entry_safe(fs_devs, tmp_fs_devs, &fs_uuids, list) {
627 list_for_each_entry_safe(dev, tmp_dev,
628 &fs_devs->devices, dev_list) {
631 if (skip_dev && skip_dev == dev)
633 if (path && !dev->name)
638 not_found = strcmp(rcu_str_deref(dev->name),
644 /* delete the stale device */
645 if (fs_devs->num_devices == 1) {
646 btrfs_sysfs_remove_fsid(fs_devs);
647 list_del(&fs_devs->list);
648 free_fs_devices(fs_devs);
651 fs_devs->num_devices--;
652 list_del(&dev->dev_list);
659 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
660 struct btrfs_device *device, fmode_t flags,
663 struct request_queue *q;
664 struct block_device *bdev;
665 struct buffer_head *bh;
666 struct btrfs_super_block *disk_super;
675 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
680 disk_super = (struct btrfs_super_block *)bh->b_data;
681 devid = btrfs_stack_device_id(&disk_super->dev_item);
682 if (devid != device->devid)
685 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
688 device->generation = btrfs_super_generation(disk_super);
690 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
691 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
692 fs_devices->seeding = 1;
694 if (bdev_read_only(bdev))
695 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
697 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
700 q = bdev_get_queue(bdev);
701 if (!blk_queue_nonrot(q))
702 fs_devices->rotating = 1;
705 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
706 device->mode = flags;
708 fs_devices->open_devices++;
709 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
710 device->devid != BTRFS_DEV_REPLACE_DEVID) {
711 fs_devices->rw_devices++;
712 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
720 blkdev_put(bdev, flags);
726 * Add new device to list of registered devices
729 * device pointer which was just added or updated when successful
730 * error pointer when failed
732 static noinline struct btrfs_device *device_list_add(const char *path,
733 struct btrfs_super_block *disk_super)
735 struct btrfs_device *device;
736 struct btrfs_fs_devices *fs_devices;
737 struct rcu_string *name;
738 u64 found_transid = btrfs_super_generation(disk_super);
739 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
741 fs_devices = find_fsid(disk_super->fsid);
743 fs_devices = alloc_fs_devices(disk_super->fsid);
744 if (IS_ERR(fs_devices))
745 return ERR_CAST(fs_devices);
747 list_add(&fs_devices->list, &fs_uuids);
751 device = find_device(fs_devices, devid,
752 disk_super->dev_item.uuid);
756 if (fs_devices->opened)
757 return ERR_PTR(-EBUSY);
759 device = btrfs_alloc_device(NULL, &devid,
760 disk_super->dev_item.uuid);
761 if (IS_ERR(device)) {
762 /* we can safely leave the fs_devices entry around */
766 name = rcu_string_strdup(path, GFP_NOFS);
769 return ERR_PTR(-ENOMEM);
771 rcu_assign_pointer(device->name, name);
773 mutex_lock(&fs_devices->device_list_mutex);
774 list_add_rcu(&device->dev_list, &fs_devices->devices);
775 fs_devices->num_devices++;
776 mutex_unlock(&fs_devices->device_list_mutex);
778 device->fs_devices = fs_devices;
779 btrfs_free_stale_devices(path, device);
781 if (disk_super->label[0])
782 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
783 disk_super->label, devid, found_transid, path);
785 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
786 disk_super->fsid, devid, found_transid, path);
788 } else if (!device->name || strcmp(device->name->str, path)) {
790 * When FS is already mounted.
791 * 1. If you are here and if the device->name is NULL that
792 * means this device was missing at time of FS mount.
793 * 2. If you are here and if the device->name is different
794 * from 'path' that means either
795 * a. The same device disappeared and reappeared with
797 * b. The missing-disk-which-was-replaced, has
800 * We must allow 1 and 2a above. But 2b would be a spurious
803 * Further in case of 1 and 2a above, the disk at 'path'
804 * would have missed some transaction when it was away and
805 * in case of 2a the stale bdev has to be updated as well.
806 * 2b must not be allowed at all time.
810 * For now, we do allow update to btrfs_fs_device through the
811 * btrfs dev scan cli after FS has been mounted. We're still
812 * tracking a problem where systems fail mount by subvolume id
813 * when we reject replacement on a mounted FS.
815 if (!fs_devices->opened && found_transid < device->generation) {
817 * That is if the FS is _not_ mounted and if you
818 * are here, that means there is more than one
819 * disk with same uuid and devid.We keep the one
820 * with larger generation number or the last-in if
821 * generation are equal.
823 return ERR_PTR(-EEXIST);
826 name = rcu_string_strdup(path, GFP_NOFS);
828 return ERR_PTR(-ENOMEM);
829 rcu_string_free(device->name);
830 rcu_assign_pointer(device->name, name);
831 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
832 fs_devices->missing_devices--;
833 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
838 * Unmount does not free the btrfs_device struct but would zero
839 * generation along with most of the other members. So just update
840 * it back. We need it to pick the disk with largest generation
843 if (!fs_devices->opened)
844 device->generation = found_transid;
846 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
851 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
853 struct btrfs_fs_devices *fs_devices;
854 struct btrfs_device *device;
855 struct btrfs_device *orig_dev;
857 fs_devices = alloc_fs_devices(orig->fsid);
858 if (IS_ERR(fs_devices))
861 mutex_lock(&orig->device_list_mutex);
862 fs_devices->total_devices = orig->total_devices;
864 /* We have held the volume lock, it is safe to get the devices. */
865 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
866 struct rcu_string *name;
868 device = btrfs_alloc_device(NULL, &orig_dev->devid,
874 * This is ok to do without rcu read locked because we hold the
875 * uuid mutex so nothing we touch in here is going to disappear.
877 if (orig_dev->name) {
878 name = rcu_string_strdup(orig_dev->name->str,
884 rcu_assign_pointer(device->name, name);
887 list_add(&device->dev_list, &fs_devices->devices);
888 device->fs_devices = fs_devices;
889 fs_devices->num_devices++;
891 mutex_unlock(&orig->device_list_mutex);
894 mutex_unlock(&orig->device_list_mutex);
895 free_fs_devices(fs_devices);
896 return ERR_PTR(-ENOMEM);
899 void btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices, int step)
901 struct btrfs_device *device, *next;
902 struct btrfs_device *latest_dev = NULL;
904 mutex_lock(&uuid_mutex);
906 /* This is the initialized path, it is safe to release the devices. */
907 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
908 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
909 &device->dev_state)) {
910 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
911 &device->dev_state) &&
913 device->generation > latest_dev->generation)) {
919 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
921 * In the first step, keep the device which has
922 * the correct fsid and the devid that is used
923 * for the dev_replace procedure.
924 * In the second step, the dev_replace state is
925 * read from the device tree and it is known
926 * whether the procedure is really active or
927 * not, which means whether this device is
928 * used or whether it should be removed.
930 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
931 &device->dev_state)) {
936 blkdev_put(device->bdev, device->mode);
938 fs_devices->open_devices--;
940 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
941 list_del_init(&device->dev_alloc_list);
942 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
943 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
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--;
998 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
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 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1109 struct btrfs_device *dev1, *dev2;
1111 dev1 = list_entry(a, struct btrfs_device, dev_list);
1112 dev2 = list_entry(b, struct btrfs_device, dev_list);
1114 if (dev1->devid < dev2->devid)
1116 else if (dev1->devid > dev2->devid)
1121 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1122 fmode_t flags, void *holder)
1126 mutex_lock(&uuid_mutex);
1127 if (fs_devices->opened) {
1128 fs_devices->opened++;
1131 list_sort(NULL, &fs_devices->devices, devid_cmp);
1132 ret = __btrfs_open_devices(fs_devices, flags, holder);
1134 mutex_unlock(&uuid_mutex);
1138 static void btrfs_release_disk_super(struct page *page)
1144 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1146 struct btrfs_super_block **disk_super)
1151 /* make sure our super fits in the device */
1152 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1155 /* make sure our super fits in the page */
1156 if (sizeof(**disk_super) > PAGE_SIZE)
1159 /* make sure our super doesn't straddle pages on disk */
1160 index = bytenr >> PAGE_SHIFT;
1161 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1164 /* pull in the page with our super */
1165 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1168 if (IS_ERR_OR_NULL(*page))
1173 /* align our pointer to the offset of the super block */
1174 *disk_super = p + (bytenr & ~PAGE_MASK);
1176 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1177 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1178 btrfs_release_disk_super(*page);
1182 if ((*disk_super)->label[0] &&
1183 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1184 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1190 * Look for a btrfs signature on a device. This may be called out of the mount path
1191 * and we are not allowed to call set_blocksize during the scan. The superblock
1192 * is read via pagecache
1194 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
1195 struct btrfs_fs_devices **fs_devices_ret)
1197 struct btrfs_super_block *disk_super;
1198 struct btrfs_device *device;
1199 struct block_device *bdev;
1205 * we would like to check all the supers, but that would make
1206 * a btrfs mount succeed after a mkfs from a different FS.
1207 * So, we need to add a special mount option to scan for
1208 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1210 bytenr = btrfs_sb_offset(0);
1211 flags |= FMODE_EXCL;
1212 mutex_lock(&uuid_mutex);
1214 bdev = blkdev_get_by_path(path, flags, holder);
1216 ret = PTR_ERR(bdev);
1220 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1222 goto error_bdev_put;
1225 device = device_list_add(path, disk_super);
1227 ret = PTR_ERR(device);
1229 *fs_devices_ret = device->fs_devices;
1231 btrfs_release_disk_super(page);
1234 blkdev_put(bdev, flags);
1236 mutex_unlock(&uuid_mutex);
1240 /* helper to account the used device space in the range */
1241 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1242 u64 end, u64 *length)
1244 struct btrfs_key key;
1245 struct btrfs_root *root = device->fs_info->dev_root;
1246 struct btrfs_dev_extent *dev_extent;
1247 struct btrfs_path *path;
1251 struct extent_buffer *l;
1255 if (start >= device->total_bytes ||
1256 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
1259 path = btrfs_alloc_path();
1262 path->reada = READA_FORWARD;
1264 key.objectid = device->devid;
1266 key.type = BTRFS_DEV_EXTENT_KEY;
1268 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1272 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1279 slot = path->slots[0];
1280 if (slot >= btrfs_header_nritems(l)) {
1281 ret = btrfs_next_leaf(root, path);
1289 btrfs_item_key_to_cpu(l, &key, slot);
1291 if (key.objectid < device->devid)
1294 if (key.objectid > device->devid)
1297 if (key.type != BTRFS_DEV_EXTENT_KEY)
1300 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1301 extent_end = key.offset + btrfs_dev_extent_length(l,
1303 if (key.offset <= start && extent_end > end) {
1304 *length = end - start + 1;
1306 } else if (key.offset <= start && extent_end > start)
1307 *length += extent_end - start;
1308 else if (key.offset > start && extent_end <= end)
1309 *length += extent_end - key.offset;
1310 else if (key.offset > start && key.offset <= end) {
1311 *length += end - key.offset + 1;
1313 } else if (key.offset > end)
1321 btrfs_free_path(path);
1325 static int contains_pending_extent(struct btrfs_transaction *transaction,
1326 struct btrfs_device *device,
1327 u64 *start, u64 len)
1329 struct btrfs_fs_info *fs_info = device->fs_info;
1330 struct extent_map *em;
1331 struct list_head *search_list = &fs_info->pinned_chunks;
1333 u64 physical_start = *start;
1336 search_list = &transaction->pending_chunks;
1338 list_for_each_entry(em, search_list, list) {
1339 struct map_lookup *map;
1342 map = em->map_lookup;
1343 for (i = 0; i < map->num_stripes; i++) {
1346 if (map->stripes[i].dev != device)
1348 if (map->stripes[i].physical >= physical_start + len ||
1349 map->stripes[i].physical + em->orig_block_len <=
1353 * Make sure that while processing the pinned list we do
1354 * not override our *start with a lower value, because
1355 * we can have pinned chunks that fall within this
1356 * device hole and that have lower physical addresses
1357 * than the pending chunks we processed before. If we
1358 * do not take this special care we can end up getting
1359 * 2 pending chunks that start at the same physical
1360 * device offsets because the end offset of a pinned
1361 * chunk can be equal to the start offset of some
1364 end = map->stripes[i].physical + em->orig_block_len;
1371 if (search_list != &fs_info->pinned_chunks) {
1372 search_list = &fs_info->pinned_chunks;
1381 * find_free_dev_extent_start - find free space in the specified device
1382 * @device: the device which we search the free space in
1383 * @num_bytes: the size of the free space that we need
1384 * @search_start: the position from which to begin the search
1385 * @start: store the start of the free space.
1386 * @len: the size of the free space. that we find, or the size
1387 * of the max free space if we don't find suitable free space
1389 * this uses a pretty simple search, the expectation is that it is
1390 * called very infrequently and that a given device has a small number
1393 * @start is used to store the start of the free space if we find. But if we
1394 * don't find suitable free space, it will be used to store the start position
1395 * of the max free space.
1397 * @len is used to store the size of the free space that we find.
1398 * But if we don't find suitable free space, it is used to store the size of
1399 * the max free space.
1401 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1402 struct btrfs_device *device, u64 num_bytes,
1403 u64 search_start, u64 *start, u64 *len)
1405 struct btrfs_fs_info *fs_info = device->fs_info;
1406 struct btrfs_root *root = fs_info->dev_root;
1407 struct btrfs_key key;
1408 struct btrfs_dev_extent *dev_extent;
1409 struct btrfs_path *path;
1414 u64 search_end = device->total_bytes;
1417 struct extent_buffer *l;
1420 * We don't want to overwrite the superblock on the drive nor any area
1421 * used by the boot loader (grub for example), so we make sure to start
1422 * at an offset of at least 1MB.
1424 search_start = max_t(u64, search_start, SZ_1M);
1426 path = btrfs_alloc_path();
1430 max_hole_start = search_start;
1434 if (search_start >= search_end ||
1435 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1440 path->reada = READA_FORWARD;
1441 path->search_commit_root = 1;
1442 path->skip_locking = 1;
1444 key.objectid = device->devid;
1445 key.offset = search_start;
1446 key.type = BTRFS_DEV_EXTENT_KEY;
1448 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1452 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1459 slot = path->slots[0];
1460 if (slot >= btrfs_header_nritems(l)) {
1461 ret = btrfs_next_leaf(root, path);
1469 btrfs_item_key_to_cpu(l, &key, slot);
1471 if (key.objectid < device->devid)
1474 if (key.objectid > device->devid)
1477 if (key.type != BTRFS_DEV_EXTENT_KEY)
1480 if (key.offset > search_start) {
1481 hole_size = key.offset - search_start;
1484 * Have to check before we set max_hole_start, otherwise
1485 * we could end up sending back this offset anyway.
1487 if (contains_pending_extent(transaction, device,
1490 if (key.offset >= search_start) {
1491 hole_size = key.offset - search_start;
1498 if (hole_size > max_hole_size) {
1499 max_hole_start = search_start;
1500 max_hole_size = hole_size;
1504 * If this free space is greater than which we need,
1505 * it must be the max free space that we have found
1506 * until now, so max_hole_start must point to the start
1507 * of this free space and the length of this free space
1508 * is stored in max_hole_size. Thus, we return
1509 * max_hole_start and max_hole_size and go back to the
1512 if (hole_size >= num_bytes) {
1518 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1519 extent_end = key.offset + btrfs_dev_extent_length(l,
1521 if (extent_end > search_start)
1522 search_start = extent_end;
1529 * At this point, search_start should be the end of
1530 * allocated dev extents, and when shrinking the device,
1531 * search_end may be smaller than search_start.
1533 if (search_end > search_start) {
1534 hole_size = search_end - search_start;
1536 if (contains_pending_extent(transaction, device, &search_start,
1538 btrfs_release_path(path);
1542 if (hole_size > max_hole_size) {
1543 max_hole_start = search_start;
1544 max_hole_size = hole_size;
1549 if (max_hole_size < num_bytes)
1555 btrfs_free_path(path);
1556 *start = max_hole_start;
1558 *len = max_hole_size;
1562 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1563 struct btrfs_device *device, u64 num_bytes,
1564 u64 *start, u64 *len)
1566 /* FIXME use last free of some kind */
1567 return find_free_dev_extent_start(trans->transaction, device,
1568 num_bytes, 0, start, len);
1571 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1572 struct btrfs_device *device,
1573 u64 start, u64 *dev_extent_len)
1575 struct btrfs_fs_info *fs_info = device->fs_info;
1576 struct btrfs_root *root = fs_info->dev_root;
1578 struct btrfs_path *path;
1579 struct btrfs_key key;
1580 struct btrfs_key found_key;
1581 struct extent_buffer *leaf = NULL;
1582 struct btrfs_dev_extent *extent = NULL;
1584 path = btrfs_alloc_path();
1588 key.objectid = device->devid;
1590 key.type = BTRFS_DEV_EXTENT_KEY;
1592 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1594 ret = btrfs_previous_item(root, path, key.objectid,
1595 BTRFS_DEV_EXTENT_KEY);
1598 leaf = path->nodes[0];
1599 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1600 extent = btrfs_item_ptr(leaf, path->slots[0],
1601 struct btrfs_dev_extent);
1602 BUG_ON(found_key.offset > start || found_key.offset +
1603 btrfs_dev_extent_length(leaf, extent) < start);
1605 btrfs_release_path(path);
1607 } else if (ret == 0) {
1608 leaf = path->nodes[0];
1609 extent = btrfs_item_ptr(leaf, path->slots[0],
1610 struct btrfs_dev_extent);
1612 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1616 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1618 ret = btrfs_del_item(trans, root, path);
1620 btrfs_handle_fs_error(fs_info, ret,
1621 "Failed to remove dev extent item");
1623 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1626 btrfs_free_path(path);
1630 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1631 struct btrfs_device *device,
1632 u64 chunk_offset, u64 start, u64 num_bytes)
1635 struct btrfs_path *path;
1636 struct btrfs_fs_info *fs_info = device->fs_info;
1637 struct btrfs_root *root = fs_info->dev_root;
1638 struct btrfs_dev_extent *extent;
1639 struct extent_buffer *leaf;
1640 struct btrfs_key key;
1642 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1643 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1644 path = btrfs_alloc_path();
1648 key.objectid = device->devid;
1650 key.type = BTRFS_DEV_EXTENT_KEY;
1651 ret = btrfs_insert_empty_item(trans, root, path, &key,
1656 leaf = path->nodes[0];
1657 extent = btrfs_item_ptr(leaf, path->slots[0],
1658 struct btrfs_dev_extent);
1659 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1660 BTRFS_CHUNK_TREE_OBJECTID);
1661 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1662 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1663 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1665 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1666 btrfs_mark_buffer_dirty(leaf);
1668 btrfs_free_path(path);
1672 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1674 struct extent_map_tree *em_tree;
1675 struct extent_map *em;
1679 em_tree = &fs_info->mapping_tree.map_tree;
1680 read_lock(&em_tree->lock);
1681 n = rb_last(&em_tree->map);
1683 em = rb_entry(n, struct extent_map, rb_node);
1684 ret = em->start + em->len;
1686 read_unlock(&em_tree->lock);
1691 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1695 struct btrfs_key key;
1696 struct btrfs_key found_key;
1697 struct btrfs_path *path;
1699 path = btrfs_alloc_path();
1703 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1704 key.type = BTRFS_DEV_ITEM_KEY;
1705 key.offset = (u64)-1;
1707 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1711 BUG_ON(ret == 0); /* Corruption */
1713 ret = btrfs_previous_item(fs_info->chunk_root, path,
1714 BTRFS_DEV_ITEMS_OBJECTID,
1715 BTRFS_DEV_ITEM_KEY);
1719 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1721 *devid_ret = found_key.offset + 1;
1725 btrfs_free_path(path);
1730 * the device information is stored in the chunk root
1731 * the btrfs_device struct should be fully filled in
1733 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1734 struct btrfs_fs_info *fs_info,
1735 struct btrfs_device *device)
1737 struct btrfs_root *root = fs_info->chunk_root;
1739 struct btrfs_path *path;
1740 struct btrfs_dev_item *dev_item;
1741 struct extent_buffer *leaf;
1742 struct btrfs_key key;
1745 path = btrfs_alloc_path();
1749 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1750 key.type = BTRFS_DEV_ITEM_KEY;
1751 key.offset = device->devid;
1753 ret = btrfs_insert_empty_item(trans, root, path, &key,
1758 leaf = path->nodes[0];
1759 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1761 btrfs_set_device_id(leaf, dev_item, device->devid);
1762 btrfs_set_device_generation(leaf, dev_item, 0);
1763 btrfs_set_device_type(leaf, dev_item, device->type);
1764 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1765 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1766 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1767 btrfs_set_device_total_bytes(leaf, dev_item,
1768 btrfs_device_get_disk_total_bytes(device));
1769 btrfs_set_device_bytes_used(leaf, dev_item,
1770 btrfs_device_get_bytes_used(device));
1771 btrfs_set_device_group(leaf, dev_item, 0);
1772 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1773 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1774 btrfs_set_device_start_offset(leaf, dev_item, 0);
1776 ptr = btrfs_device_uuid(dev_item);
1777 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1778 ptr = btrfs_device_fsid(dev_item);
1779 write_extent_buffer(leaf, fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1780 btrfs_mark_buffer_dirty(leaf);
1784 btrfs_free_path(path);
1789 * Function to update ctime/mtime for a given device path.
1790 * Mainly used for ctime/mtime based probe like libblkid.
1792 static void update_dev_time(const char *path_name)
1796 filp = filp_open(path_name, O_RDWR, 0);
1799 file_update_time(filp);
1800 filp_close(filp, NULL);
1803 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1804 struct btrfs_device *device)
1806 struct btrfs_root *root = fs_info->chunk_root;
1808 struct btrfs_path *path;
1809 struct btrfs_key key;
1810 struct btrfs_trans_handle *trans;
1812 path = btrfs_alloc_path();
1816 trans = btrfs_start_transaction(root, 0);
1817 if (IS_ERR(trans)) {
1818 btrfs_free_path(path);
1819 return PTR_ERR(trans);
1821 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1822 key.type = BTRFS_DEV_ITEM_KEY;
1823 key.offset = device->devid;
1825 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1829 btrfs_abort_transaction(trans, ret);
1830 btrfs_end_transaction(trans);
1834 ret = btrfs_del_item(trans, root, path);
1836 btrfs_abort_transaction(trans, ret);
1837 btrfs_end_transaction(trans);
1841 btrfs_free_path(path);
1843 ret = btrfs_commit_transaction(trans);
1848 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1849 * filesystem. It's up to the caller to adjust that number regarding eg. device
1852 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1860 seq = read_seqbegin(&fs_info->profiles_lock);
1862 all_avail = fs_info->avail_data_alloc_bits |
1863 fs_info->avail_system_alloc_bits |
1864 fs_info->avail_metadata_alloc_bits;
1865 } while (read_seqretry(&fs_info->profiles_lock, seq));
1867 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1868 if (!(all_avail & btrfs_raid_group[i]))
1871 if (num_devices < btrfs_raid_array[i].devs_min) {
1872 int ret = btrfs_raid_mindev_error[i];
1882 static struct btrfs_device * btrfs_find_next_active_device(
1883 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1885 struct btrfs_device *next_device;
1887 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1888 if (next_device != device &&
1889 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1890 && next_device->bdev)
1898 * Helper function to check if the given device is part of s_bdev / latest_bdev
1899 * and replace it with the provided or the next active device, in the context
1900 * where this function called, there should be always be another device (or
1901 * this_dev) which is active.
1903 void btrfs_assign_next_active_device(struct btrfs_fs_info *fs_info,
1904 struct btrfs_device *device, struct btrfs_device *this_dev)
1906 struct btrfs_device *next_device;
1909 next_device = this_dev;
1911 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1913 ASSERT(next_device);
1915 if (fs_info->sb->s_bdev &&
1916 (fs_info->sb->s_bdev == device->bdev))
1917 fs_info->sb->s_bdev = next_device->bdev;
1919 if (fs_info->fs_devices->latest_bdev == device->bdev)
1920 fs_info->fs_devices->latest_bdev = next_device->bdev;
1923 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1926 struct btrfs_device *device;
1927 struct btrfs_fs_devices *cur_devices;
1931 mutex_lock(&fs_info->volume_mutex);
1932 mutex_lock(&uuid_mutex);
1934 num_devices = fs_info->fs_devices->num_devices;
1935 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
1936 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1937 WARN_ON(num_devices < 1);
1940 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
1942 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1946 ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1951 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1952 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1956 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1957 fs_info->fs_devices->rw_devices == 1) {
1958 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1962 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1963 mutex_lock(&fs_info->chunk_mutex);
1964 list_del_init(&device->dev_alloc_list);
1965 device->fs_devices->rw_devices--;
1966 mutex_unlock(&fs_info->chunk_mutex);
1969 mutex_unlock(&uuid_mutex);
1970 ret = btrfs_shrink_device(device, 0);
1971 mutex_lock(&uuid_mutex);
1976 * TODO: the superblock still includes this device in its num_devices
1977 * counter although write_all_supers() is not locked out. This
1978 * could give a filesystem state which requires a degraded mount.
1980 ret = btrfs_rm_dev_item(fs_info, device);
1984 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
1985 btrfs_scrub_cancel_dev(fs_info, device);
1988 * the device list mutex makes sure that we don't change
1989 * the device list while someone else is writing out all
1990 * the device supers. Whoever is writing all supers, should
1991 * lock the device list mutex before getting the number of
1992 * devices in the super block (super_copy). Conversely,
1993 * whoever updates the number of devices in the super block
1994 * (super_copy) should hold the device list mutex.
1997 cur_devices = device->fs_devices;
1998 mutex_lock(&fs_info->fs_devices->device_list_mutex);
1999 list_del_rcu(&device->dev_list);
2001 device->fs_devices->num_devices--;
2002 device->fs_devices->total_devices--;
2004 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2005 device->fs_devices->missing_devices--;
2007 btrfs_assign_next_active_device(fs_info, device, NULL);
2010 device->fs_devices->open_devices--;
2011 /* remove sysfs entry */
2012 btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
2015 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2016 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2017 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2020 * at this point, the device is zero sized and detached from
2021 * the devices list. All that's left is to zero out the old
2022 * supers and free the device.
2024 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2025 btrfs_scratch_superblocks(device->bdev, device->name->str);
2027 btrfs_close_bdev(device);
2028 call_rcu(&device->rcu, free_device_rcu);
2030 if (cur_devices->open_devices == 0) {
2031 struct btrfs_fs_devices *fs_devices;
2032 fs_devices = fs_info->fs_devices;
2033 while (fs_devices) {
2034 if (fs_devices->seed == cur_devices) {
2035 fs_devices->seed = cur_devices->seed;
2038 fs_devices = fs_devices->seed;
2040 cur_devices->seed = NULL;
2041 __btrfs_close_devices(cur_devices);
2042 free_fs_devices(cur_devices);
2046 mutex_unlock(&uuid_mutex);
2047 mutex_unlock(&fs_info->volume_mutex);
2051 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2052 mutex_lock(&fs_info->chunk_mutex);
2053 list_add(&device->dev_alloc_list,
2054 &fs_info->fs_devices->alloc_list);
2055 device->fs_devices->rw_devices++;
2056 mutex_unlock(&fs_info->chunk_mutex);
2061 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
2062 struct btrfs_device *srcdev)
2064 struct btrfs_fs_devices *fs_devices;
2066 WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
2069 * in case of fs with no seed, srcdev->fs_devices will point
2070 * to fs_devices of fs_info. However when the dev being replaced is
2071 * a seed dev it will point to the seed's local fs_devices. In short
2072 * srcdev will have its correct fs_devices in both the cases.
2074 fs_devices = srcdev->fs_devices;
2076 list_del_rcu(&srcdev->dev_list);
2077 list_del(&srcdev->dev_alloc_list);
2078 fs_devices->num_devices--;
2079 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2080 fs_devices->missing_devices--;
2082 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2083 fs_devices->rw_devices--;
2086 fs_devices->open_devices--;
2089 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2090 struct btrfs_device *srcdev)
2092 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2094 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2095 /* zero out the old super if it is writable */
2096 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2099 btrfs_close_bdev(srcdev);
2100 call_rcu(&srcdev->rcu, free_device_rcu);
2102 /* if this is no devs we rather delete the fs_devices */
2103 if (!fs_devices->num_devices) {
2104 struct btrfs_fs_devices *tmp_fs_devices;
2107 * On a mounted FS, num_devices can't be zero unless it's a
2108 * seed. In case of a seed device being replaced, the replace
2109 * target added to the sprout FS, so there will be no more
2110 * device left under the seed FS.
2112 ASSERT(fs_devices->seeding);
2114 tmp_fs_devices = fs_info->fs_devices;
2115 while (tmp_fs_devices) {
2116 if (tmp_fs_devices->seed == fs_devices) {
2117 tmp_fs_devices->seed = fs_devices->seed;
2120 tmp_fs_devices = tmp_fs_devices->seed;
2122 fs_devices->seed = NULL;
2123 __btrfs_close_devices(fs_devices);
2124 free_fs_devices(fs_devices);
2128 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2129 struct btrfs_device *tgtdev)
2131 mutex_lock(&uuid_mutex);
2133 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2135 btrfs_sysfs_rm_device_link(fs_info->fs_devices, tgtdev);
2138 fs_info->fs_devices->open_devices--;
2140 fs_info->fs_devices->num_devices--;
2142 btrfs_assign_next_active_device(fs_info, tgtdev, NULL);
2144 list_del_rcu(&tgtdev->dev_list);
2146 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2147 mutex_unlock(&uuid_mutex);
2150 * The update_dev_time() with in btrfs_scratch_superblocks()
2151 * may lead to a call to btrfs_show_devname() which will try
2152 * to hold device_list_mutex. And here this device
2153 * is already out of device list, so we don't have to hold
2154 * the device_list_mutex lock.
2156 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2158 btrfs_close_bdev(tgtdev);
2159 call_rcu(&tgtdev->rcu, free_device_rcu);
2162 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2163 const char *device_path,
2164 struct btrfs_device **device)
2167 struct btrfs_super_block *disk_super;
2170 struct block_device *bdev;
2171 struct buffer_head *bh;
2174 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2175 fs_info->bdev_holder, 0, &bdev, &bh);
2178 disk_super = (struct btrfs_super_block *)bh->b_data;
2179 devid = btrfs_stack_device_id(&disk_super->dev_item);
2180 dev_uuid = disk_super->dev_item.uuid;
2181 *device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2185 blkdev_put(bdev, FMODE_READ);
2189 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2190 const char *device_path,
2191 struct btrfs_device **device)
2194 if (strcmp(device_path, "missing") == 0) {
2195 struct list_head *devices;
2196 struct btrfs_device *tmp;
2198 devices = &fs_info->fs_devices->devices;
2200 * It is safe to read the devices since the volume_mutex
2201 * is held by the caller.
2203 list_for_each_entry(tmp, devices, dev_list) {
2204 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2205 &tmp->dev_state) && !tmp->bdev) {
2212 return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2216 return btrfs_find_device_by_path(fs_info, device_path, device);
2221 * Lookup a device given by device id, or the path if the id is 0.
2223 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2224 const char *devpath,
2225 struct btrfs_device **device)
2231 *device = btrfs_find_device(fs_info, devid, NULL, NULL);
2235 if (!devpath || !devpath[0])
2238 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2245 * does all the dirty work required for changing file system's UUID.
2247 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2249 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2250 struct btrfs_fs_devices *old_devices;
2251 struct btrfs_fs_devices *seed_devices;
2252 struct btrfs_super_block *disk_super = fs_info->super_copy;
2253 struct btrfs_device *device;
2256 BUG_ON(!mutex_is_locked(&uuid_mutex));
2257 if (!fs_devices->seeding)
2260 seed_devices = alloc_fs_devices(NULL);
2261 if (IS_ERR(seed_devices))
2262 return PTR_ERR(seed_devices);
2264 old_devices = clone_fs_devices(fs_devices);
2265 if (IS_ERR(old_devices)) {
2266 kfree(seed_devices);
2267 return PTR_ERR(old_devices);
2270 list_add(&old_devices->list, &fs_uuids);
2272 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2273 seed_devices->opened = 1;
2274 INIT_LIST_HEAD(&seed_devices->devices);
2275 INIT_LIST_HEAD(&seed_devices->alloc_list);
2276 mutex_init(&seed_devices->device_list_mutex);
2278 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2279 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2281 list_for_each_entry(device, &seed_devices->devices, dev_list)
2282 device->fs_devices = seed_devices;
2284 mutex_lock(&fs_info->chunk_mutex);
2285 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2286 mutex_unlock(&fs_info->chunk_mutex);
2288 fs_devices->seeding = 0;
2289 fs_devices->num_devices = 0;
2290 fs_devices->open_devices = 0;
2291 fs_devices->missing_devices = 0;
2292 fs_devices->rotating = 0;
2293 fs_devices->seed = seed_devices;
2295 generate_random_uuid(fs_devices->fsid);
2296 memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2297 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2298 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2300 super_flags = btrfs_super_flags(disk_super) &
2301 ~BTRFS_SUPER_FLAG_SEEDING;
2302 btrfs_set_super_flags(disk_super, super_flags);
2308 * Store the expected generation for seed devices in device items.
2310 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2311 struct btrfs_fs_info *fs_info)
2313 struct btrfs_root *root = fs_info->chunk_root;
2314 struct btrfs_path *path;
2315 struct extent_buffer *leaf;
2316 struct btrfs_dev_item *dev_item;
2317 struct btrfs_device *device;
2318 struct btrfs_key key;
2319 u8 fs_uuid[BTRFS_FSID_SIZE];
2320 u8 dev_uuid[BTRFS_UUID_SIZE];
2324 path = btrfs_alloc_path();
2328 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2330 key.type = BTRFS_DEV_ITEM_KEY;
2333 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2337 leaf = path->nodes[0];
2339 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2340 ret = btrfs_next_leaf(root, path);
2345 leaf = path->nodes[0];
2346 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2347 btrfs_release_path(path);
2351 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2352 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2353 key.type != BTRFS_DEV_ITEM_KEY)
2356 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2357 struct btrfs_dev_item);
2358 devid = btrfs_device_id(leaf, dev_item);
2359 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2361 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2363 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2364 BUG_ON(!device); /* Logic error */
2366 if (device->fs_devices->seeding) {
2367 btrfs_set_device_generation(leaf, dev_item,
2368 device->generation);
2369 btrfs_mark_buffer_dirty(leaf);
2377 btrfs_free_path(path);
2381 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2383 struct btrfs_root *root = fs_info->dev_root;
2384 struct request_queue *q;
2385 struct btrfs_trans_handle *trans;
2386 struct btrfs_device *device;
2387 struct block_device *bdev;
2388 struct list_head *devices;
2389 struct super_block *sb = fs_info->sb;
2390 struct rcu_string *name;
2392 int seeding_dev = 0;
2394 bool unlocked = false;
2396 if (sb_rdonly(sb) && !fs_info->fs_devices->seeding)
2399 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2400 fs_info->bdev_holder);
2402 return PTR_ERR(bdev);
2404 if (fs_info->fs_devices->seeding) {
2406 down_write(&sb->s_umount);
2407 mutex_lock(&uuid_mutex);
2410 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2412 devices = &fs_info->fs_devices->devices;
2414 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2415 list_for_each_entry(device, devices, dev_list) {
2416 if (device->bdev == bdev) {
2419 &fs_info->fs_devices->device_list_mutex);
2423 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2425 device = btrfs_alloc_device(fs_info, NULL, NULL);
2426 if (IS_ERR(device)) {
2427 /* we can safely leave the fs_devices entry around */
2428 ret = PTR_ERR(device);
2432 name = rcu_string_strdup(device_path, GFP_KERNEL);
2435 goto error_free_device;
2437 rcu_assign_pointer(device->name, name);
2439 trans = btrfs_start_transaction(root, 0);
2440 if (IS_ERR(trans)) {
2441 ret = PTR_ERR(trans);
2442 goto error_free_device;
2445 q = bdev_get_queue(bdev);
2446 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2447 device->generation = trans->transid;
2448 device->io_width = fs_info->sectorsize;
2449 device->io_align = fs_info->sectorsize;
2450 device->sector_size = fs_info->sectorsize;
2451 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2452 fs_info->sectorsize);
2453 device->disk_total_bytes = device->total_bytes;
2454 device->commit_total_bytes = device->total_bytes;
2455 device->fs_info = fs_info;
2456 device->bdev = bdev;
2457 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2458 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2459 device->mode = FMODE_EXCL;
2460 device->dev_stats_valid = 1;
2461 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2464 sb->s_flags &= ~SB_RDONLY;
2465 ret = btrfs_prepare_sprout(fs_info);
2467 btrfs_abort_transaction(trans, ret);
2472 device->fs_devices = fs_info->fs_devices;
2474 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2475 mutex_lock(&fs_info->chunk_mutex);
2476 list_add_rcu(&device->dev_list, &fs_info->fs_devices->devices);
2477 list_add(&device->dev_alloc_list,
2478 &fs_info->fs_devices->alloc_list);
2479 fs_info->fs_devices->num_devices++;
2480 fs_info->fs_devices->open_devices++;
2481 fs_info->fs_devices->rw_devices++;
2482 fs_info->fs_devices->total_devices++;
2483 fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2485 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2487 if (!blk_queue_nonrot(q))
2488 fs_info->fs_devices->rotating = 1;
2490 tmp = btrfs_super_total_bytes(fs_info->super_copy);
2491 btrfs_set_super_total_bytes(fs_info->super_copy,
2492 round_down(tmp + device->total_bytes, fs_info->sectorsize));
2494 tmp = btrfs_super_num_devices(fs_info->super_copy);
2495 btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
2497 /* add sysfs device entry */
2498 btrfs_sysfs_add_device_link(fs_info->fs_devices, device);
2501 * we've got more storage, clear any full flags on the space
2504 btrfs_clear_space_info_full(fs_info);
2506 mutex_unlock(&fs_info->chunk_mutex);
2507 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2510 mutex_lock(&fs_info->chunk_mutex);
2511 ret = init_first_rw_device(trans, fs_info);
2512 mutex_unlock(&fs_info->chunk_mutex);
2514 btrfs_abort_transaction(trans, ret);
2519 ret = btrfs_add_dev_item(trans, fs_info, device);
2521 btrfs_abort_transaction(trans, ret);
2526 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2528 ret = btrfs_finish_sprout(trans, fs_info);
2530 btrfs_abort_transaction(trans, ret);
2534 /* Sprouting would change fsid of the mounted root,
2535 * so rename the fsid on the sysfs
2537 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2539 if (kobject_rename(&fs_info->fs_devices->fsid_kobj, fsid_buf))
2541 "sysfs: failed to create fsid for sprout");
2544 ret = btrfs_commit_transaction(trans);
2547 mutex_unlock(&uuid_mutex);
2548 up_write(&sb->s_umount);
2551 if (ret) /* transaction commit */
2554 ret = btrfs_relocate_sys_chunks(fs_info);
2556 btrfs_handle_fs_error(fs_info, ret,
2557 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2558 trans = btrfs_attach_transaction(root);
2559 if (IS_ERR(trans)) {
2560 if (PTR_ERR(trans) == -ENOENT)
2562 ret = PTR_ERR(trans);
2566 ret = btrfs_commit_transaction(trans);
2569 /* Update ctime/mtime for libblkid */
2570 update_dev_time(device_path);
2574 btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
2577 sb->s_flags |= SB_RDONLY;
2579 btrfs_end_transaction(trans);
2581 free_device(device);
2583 blkdev_put(bdev, FMODE_EXCL);
2584 if (seeding_dev && !unlocked) {
2585 mutex_unlock(&uuid_mutex);
2586 up_write(&sb->s_umount);
2591 int btrfs_init_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2592 const char *device_path,
2593 struct btrfs_device *srcdev,
2594 struct btrfs_device **device_out)
2596 struct btrfs_device *device;
2597 struct block_device *bdev;
2598 struct list_head *devices;
2599 struct rcu_string *name;
2600 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2604 if (fs_info->fs_devices->seeding) {
2605 btrfs_err(fs_info, "the filesystem is a seed filesystem!");
2609 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2610 fs_info->bdev_holder);
2612 btrfs_err(fs_info, "target device %s is invalid!", device_path);
2613 return PTR_ERR(bdev);
2616 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2618 devices = &fs_info->fs_devices->devices;
2619 list_for_each_entry(device, devices, dev_list) {
2620 if (device->bdev == bdev) {
2622 "target device is in the filesystem!");
2629 if (i_size_read(bdev->bd_inode) <
2630 btrfs_device_get_total_bytes(srcdev)) {
2632 "target device is smaller than source device!");
2638 device = btrfs_alloc_device(NULL, &devid, NULL);
2639 if (IS_ERR(device)) {
2640 ret = PTR_ERR(device);
2644 name = rcu_string_strdup(device_path, GFP_KERNEL);
2646 free_device(device);
2650 rcu_assign_pointer(device->name, name);
2652 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2653 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2654 device->generation = 0;
2655 device->io_width = fs_info->sectorsize;
2656 device->io_align = fs_info->sectorsize;
2657 device->sector_size = fs_info->sectorsize;
2658 device->total_bytes = btrfs_device_get_total_bytes(srcdev);
2659 device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
2660 device->bytes_used = btrfs_device_get_bytes_used(srcdev);
2661 ASSERT(list_empty(&srcdev->resized_list));
2662 device->commit_total_bytes = srcdev->commit_total_bytes;
2663 device->commit_bytes_used = device->bytes_used;
2664 device->fs_info = fs_info;
2665 device->bdev = bdev;
2666 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2667 set_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2668 device->mode = FMODE_EXCL;
2669 device->dev_stats_valid = 1;
2670 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2671 device->fs_devices = fs_info->fs_devices;
2672 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2673 fs_info->fs_devices->num_devices++;
2674 fs_info->fs_devices->open_devices++;
2675 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2677 *device_out = device;
2681 blkdev_put(bdev, FMODE_EXCL);
2685 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2686 struct btrfs_device *device)
2689 struct btrfs_path *path;
2690 struct btrfs_root *root = device->fs_info->chunk_root;
2691 struct btrfs_dev_item *dev_item;
2692 struct extent_buffer *leaf;
2693 struct btrfs_key key;
2695 path = btrfs_alloc_path();
2699 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2700 key.type = BTRFS_DEV_ITEM_KEY;
2701 key.offset = device->devid;
2703 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2712 leaf = path->nodes[0];
2713 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2715 btrfs_set_device_id(leaf, dev_item, device->devid);
2716 btrfs_set_device_type(leaf, dev_item, device->type);
2717 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2718 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2719 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2720 btrfs_set_device_total_bytes(leaf, dev_item,
2721 btrfs_device_get_disk_total_bytes(device));
2722 btrfs_set_device_bytes_used(leaf, dev_item,
2723 btrfs_device_get_bytes_used(device));
2724 btrfs_mark_buffer_dirty(leaf);
2727 btrfs_free_path(path);
2731 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2732 struct btrfs_device *device, u64 new_size)
2734 struct btrfs_fs_info *fs_info = device->fs_info;
2735 struct btrfs_super_block *super_copy = fs_info->super_copy;
2736 struct btrfs_fs_devices *fs_devices;
2740 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2743 new_size = round_down(new_size, fs_info->sectorsize);
2745 mutex_lock(&fs_info->chunk_mutex);
2746 old_total = btrfs_super_total_bytes(super_copy);
2747 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2749 if (new_size <= device->total_bytes ||
2750 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2751 mutex_unlock(&fs_info->chunk_mutex);
2755 fs_devices = fs_info->fs_devices;
2757 btrfs_set_super_total_bytes(super_copy,
2758 round_down(old_total + diff, fs_info->sectorsize));
2759 device->fs_devices->total_rw_bytes += diff;
2761 btrfs_device_set_total_bytes(device, new_size);
2762 btrfs_device_set_disk_total_bytes(device, new_size);
2763 btrfs_clear_space_info_full(device->fs_info);
2764 if (list_empty(&device->resized_list))
2765 list_add_tail(&device->resized_list,
2766 &fs_devices->resized_devices);
2767 mutex_unlock(&fs_info->chunk_mutex);
2769 return btrfs_update_device(trans, device);
2772 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2773 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2775 struct btrfs_root *root = fs_info->chunk_root;
2777 struct btrfs_path *path;
2778 struct btrfs_key key;
2780 path = btrfs_alloc_path();
2784 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2785 key.offset = chunk_offset;
2786 key.type = BTRFS_CHUNK_ITEM_KEY;
2788 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2791 else if (ret > 0) { /* Logic error or corruption */
2792 btrfs_handle_fs_error(fs_info, -ENOENT,
2793 "Failed lookup while freeing chunk.");
2798 ret = btrfs_del_item(trans, root, path);
2800 btrfs_handle_fs_error(fs_info, ret,
2801 "Failed to delete chunk item.");
2803 btrfs_free_path(path);
2807 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2809 struct btrfs_super_block *super_copy = fs_info->super_copy;
2810 struct btrfs_disk_key *disk_key;
2811 struct btrfs_chunk *chunk;
2818 struct btrfs_key key;
2820 mutex_lock(&fs_info->chunk_mutex);
2821 array_size = btrfs_super_sys_array_size(super_copy);
2823 ptr = super_copy->sys_chunk_array;
2826 while (cur < array_size) {
2827 disk_key = (struct btrfs_disk_key *)ptr;
2828 btrfs_disk_key_to_cpu(&key, disk_key);
2830 len = sizeof(*disk_key);
2832 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2833 chunk = (struct btrfs_chunk *)(ptr + len);
2834 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2835 len += btrfs_chunk_item_size(num_stripes);
2840 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2841 key.offset == chunk_offset) {
2842 memmove(ptr, ptr + len, array_size - (cur + len));
2844 btrfs_set_super_sys_array_size(super_copy, array_size);
2850 mutex_unlock(&fs_info->chunk_mutex);
2854 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2855 u64 logical, u64 length)
2857 struct extent_map_tree *em_tree;
2858 struct extent_map *em;
2860 em_tree = &fs_info->mapping_tree.map_tree;
2861 read_lock(&em_tree->lock);
2862 em = lookup_extent_mapping(em_tree, logical, length);
2863 read_unlock(&em_tree->lock);
2866 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2868 return ERR_PTR(-EINVAL);
2871 if (em->start > logical || em->start + em->len < logical) {
2873 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2874 logical, length, em->start, em->start + em->len);
2875 free_extent_map(em);
2876 return ERR_PTR(-EINVAL);
2879 /* callers are responsible for dropping em's ref. */
2883 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2884 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2886 struct extent_map *em;
2887 struct map_lookup *map;
2888 u64 dev_extent_len = 0;
2890 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2892 em = get_chunk_map(fs_info, chunk_offset, 1);
2895 * This is a logic error, but we don't want to just rely on the
2896 * user having built with ASSERT enabled, so if ASSERT doesn't
2897 * do anything we still error out.
2902 map = em->map_lookup;
2903 mutex_lock(&fs_info->chunk_mutex);
2904 check_system_chunk(trans, fs_info, map->type);
2905 mutex_unlock(&fs_info->chunk_mutex);
2908 * Take the device list mutex to prevent races with the final phase of
2909 * a device replace operation that replaces the device object associated
2910 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2912 mutex_lock(&fs_devices->device_list_mutex);
2913 for (i = 0; i < map->num_stripes; i++) {
2914 struct btrfs_device *device = map->stripes[i].dev;
2915 ret = btrfs_free_dev_extent(trans, device,
2916 map->stripes[i].physical,
2919 mutex_unlock(&fs_devices->device_list_mutex);
2920 btrfs_abort_transaction(trans, ret);
2924 if (device->bytes_used > 0) {
2925 mutex_lock(&fs_info->chunk_mutex);
2926 btrfs_device_set_bytes_used(device,
2927 device->bytes_used - dev_extent_len);
2928 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2929 btrfs_clear_space_info_full(fs_info);
2930 mutex_unlock(&fs_info->chunk_mutex);
2933 if (map->stripes[i].dev) {
2934 ret = btrfs_update_device(trans, map->stripes[i].dev);
2936 mutex_unlock(&fs_devices->device_list_mutex);
2937 btrfs_abort_transaction(trans, ret);
2942 mutex_unlock(&fs_devices->device_list_mutex);
2944 ret = btrfs_free_chunk(trans, fs_info, chunk_offset);
2946 btrfs_abort_transaction(trans, ret);
2950 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2952 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2953 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2955 btrfs_abort_transaction(trans, ret);
2960 ret = btrfs_remove_block_group(trans, fs_info, chunk_offset, em);
2962 btrfs_abort_transaction(trans, ret);
2968 free_extent_map(em);
2972 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2974 struct btrfs_root *root = fs_info->chunk_root;
2975 struct btrfs_trans_handle *trans;
2979 * Prevent races with automatic removal of unused block groups.
2980 * After we relocate and before we remove the chunk with offset
2981 * chunk_offset, automatic removal of the block group can kick in,
2982 * resulting in a failure when calling btrfs_remove_chunk() below.
2984 * Make sure to acquire this mutex before doing a tree search (dev
2985 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2986 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2987 * we release the path used to search the chunk/dev tree and before
2988 * the current task acquires this mutex and calls us.
2990 ASSERT(mutex_is_locked(&fs_info->delete_unused_bgs_mutex));
2992 ret = btrfs_can_relocate(fs_info, chunk_offset);
2996 /* step one, relocate all the extents inside this chunk */
2997 btrfs_scrub_pause(fs_info);
2998 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2999 btrfs_scrub_continue(fs_info);
3003 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3005 if (IS_ERR(trans)) {
3006 ret = PTR_ERR(trans);
3007 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3012 * step two, delete the device extents and the
3013 * chunk tree entries
3015 ret = btrfs_remove_chunk(trans, fs_info, chunk_offset);
3016 btrfs_end_transaction(trans);
3020 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3022 struct btrfs_root *chunk_root = fs_info->chunk_root;
3023 struct btrfs_path *path;
3024 struct extent_buffer *leaf;
3025 struct btrfs_chunk *chunk;
3026 struct btrfs_key key;
3027 struct btrfs_key found_key;
3029 bool retried = false;
3033 path = btrfs_alloc_path();
3038 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3039 key.offset = (u64)-1;
3040 key.type = BTRFS_CHUNK_ITEM_KEY;
3043 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3044 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3046 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3049 BUG_ON(ret == 0); /* Corruption */
3051 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3054 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3060 leaf = path->nodes[0];
3061 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3063 chunk = btrfs_item_ptr(leaf, path->slots[0],
3064 struct btrfs_chunk);
3065 chunk_type = btrfs_chunk_type(leaf, chunk);
3066 btrfs_release_path(path);
3068 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3069 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3075 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3077 if (found_key.offset == 0)
3079 key.offset = found_key.offset - 1;
3082 if (failed && !retried) {
3086 } else if (WARN_ON(failed && retried)) {
3090 btrfs_free_path(path);
3095 * return 1 : allocate a data chunk successfully,
3096 * return <0: errors during allocating a data chunk,
3097 * return 0 : no need to allocate a data chunk.
3099 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3102 struct btrfs_block_group_cache *cache;
3106 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3108 chunk_type = cache->flags;
3109 btrfs_put_block_group(cache);
3111 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3112 spin_lock(&fs_info->data_sinfo->lock);
3113 bytes_used = fs_info->data_sinfo->bytes_used;
3114 spin_unlock(&fs_info->data_sinfo->lock);
3117 struct btrfs_trans_handle *trans;
3120 trans = btrfs_join_transaction(fs_info->tree_root);
3122 return PTR_ERR(trans);
3124 ret = btrfs_force_chunk_alloc(trans, fs_info,
3125 BTRFS_BLOCK_GROUP_DATA);
3126 btrfs_end_transaction(trans);
3136 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3137 struct btrfs_balance_control *bctl)
3139 struct btrfs_root *root = fs_info->tree_root;
3140 struct btrfs_trans_handle *trans;
3141 struct btrfs_balance_item *item;
3142 struct btrfs_disk_balance_args disk_bargs;
3143 struct btrfs_path *path;
3144 struct extent_buffer *leaf;
3145 struct btrfs_key key;
3148 path = btrfs_alloc_path();
3152 trans = btrfs_start_transaction(root, 0);
3153 if (IS_ERR(trans)) {
3154 btrfs_free_path(path);
3155 return PTR_ERR(trans);
3158 key.objectid = BTRFS_BALANCE_OBJECTID;
3159 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3162 ret = btrfs_insert_empty_item(trans, root, path, &key,
3167 leaf = path->nodes[0];
3168 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3170 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3172 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3173 btrfs_set_balance_data(leaf, item, &disk_bargs);
3174 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3175 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3176 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3177 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3179 btrfs_set_balance_flags(leaf, item, bctl->flags);
3181 btrfs_mark_buffer_dirty(leaf);
3183 btrfs_free_path(path);
3184 err = btrfs_commit_transaction(trans);
3190 static int del_balance_item(struct btrfs_fs_info *fs_info)
3192 struct btrfs_root *root = fs_info->tree_root;
3193 struct btrfs_trans_handle *trans;
3194 struct btrfs_path *path;
3195 struct btrfs_key key;
3198 path = btrfs_alloc_path();
3202 trans = btrfs_start_transaction(root, 0);
3203 if (IS_ERR(trans)) {
3204 btrfs_free_path(path);
3205 return PTR_ERR(trans);
3208 key.objectid = BTRFS_BALANCE_OBJECTID;
3209 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3212 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3220 ret = btrfs_del_item(trans, root, path);
3222 btrfs_free_path(path);
3223 err = btrfs_commit_transaction(trans);
3230 * This is a heuristic used to reduce the number of chunks balanced on
3231 * resume after balance was interrupted.
3233 static void update_balance_args(struct btrfs_balance_control *bctl)
3236 * Turn on soft mode for chunk types that were being converted.
3238 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3239 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3240 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3241 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3242 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3243 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3246 * Turn on usage filter if is not already used. The idea is
3247 * that chunks that we have already balanced should be
3248 * reasonably full. Don't do it for chunks that are being
3249 * converted - that will keep us from relocating unconverted
3250 * (albeit full) chunks.
3252 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3253 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3254 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3255 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3256 bctl->data.usage = 90;
3258 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3259 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3260 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3261 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3262 bctl->sys.usage = 90;
3264 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3265 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3266 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3267 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3268 bctl->meta.usage = 90;
3273 * Should be called with both balance and volume mutexes held to
3274 * serialize other volume operations (add_dev/rm_dev/resize) with
3275 * restriper. Same goes for unset_balance_control.
3277 static void set_balance_control(struct btrfs_balance_control *bctl)
3279 struct btrfs_fs_info *fs_info = bctl->fs_info;
3281 BUG_ON(fs_info->balance_ctl);
3283 spin_lock(&fs_info->balance_lock);
3284 fs_info->balance_ctl = bctl;
3285 spin_unlock(&fs_info->balance_lock);
3288 static void unset_balance_control(struct btrfs_fs_info *fs_info)
3290 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3292 BUG_ON(!fs_info->balance_ctl);
3294 spin_lock(&fs_info->balance_lock);
3295 fs_info->balance_ctl = NULL;
3296 spin_unlock(&fs_info->balance_lock);
3302 * Balance filters. Return 1 if chunk should be filtered out
3303 * (should not be balanced).
3305 static int chunk_profiles_filter(u64 chunk_type,
3306 struct btrfs_balance_args *bargs)
3308 chunk_type = chunk_to_extended(chunk_type) &
3309 BTRFS_EXTENDED_PROFILE_MASK;
3311 if (bargs->profiles & chunk_type)
3317 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3318 struct btrfs_balance_args *bargs)
3320 struct btrfs_block_group_cache *cache;
3322 u64 user_thresh_min;
3323 u64 user_thresh_max;
3326 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3327 chunk_used = btrfs_block_group_used(&cache->item);
3329 if (bargs->usage_min == 0)
3330 user_thresh_min = 0;
3332 user_thresh_min = div_factor_fine(cache->key.offset,
3335 if (bargs->usage_max == 0)
3336 user_thresh_max = 1;
3337 else if (bargs->usage_max > 100)
3338 user_thresh_max = cache->key.offset;
3340 user_thresh_max = div_factor_fine(cache->key.offset,
3343 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3346 btrfs_put_block_group(cache);
3350 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3351 u64 chunk_offset, struct btrfs_balance_args *bargs)
3353 struct btrfs_block_group_cache *cache;
3354 u64 chunk_used, user_thresh;
3357 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3358 chunk_used = btrfs_block_group_used(&cache->item);
3360 if (bargs->usage_min == 0)
3362 else if (bargs->usage > 100)
3363 user_thresh = cache->key.offset;
3365 user_thresh = div_factor_fine(cache->key.offset,
3368 if (chunk_used < user_thresh)
3371 btrfs_put_block_group(cache);
3375 static int chunk_devid_filter(struct extent_buffer *leaf,
3376 struct btrfs_chunk *chunk,
3377 struct btrfs_balance_args *bargs)
3379 struct btrfs_stripe *stripe;
3380 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3383 for (i = 0; i < num_stripes; i++) {
3384 stripe = btrfs_stripe_nr(chunk, i);
3385 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3392 /* [pstart, pend) */
3393 static int chunk_drange_filter(struct extent_buffer *leaf,
3394 struct btrfs_chunk *chunk,
3395 struct btrfs_balance_args *bargs)
3397 struct btrfs_stripe *stripe;
3398 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3404 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3407 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3408 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3409 factor = num_stripes / 2;
3410 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3411 factor = num_stripes - 1;
3412 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3413 factor = num_stripes - 2;
3415 factor = num_stripes;
3418 for (i = 0; i < num_stripes; i++) {
3419 stripe = btrfs_stripe_nr(chunk, i);
3420 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3423 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3424 stripe_length = btrfs_chunk_length(leaf, chunk);
3425 stripe_length = div_u64(stripe_length, factor);
3427 if (stripe_offset < bargs->pend &&
3428 stripe_offset + stripe_length > bargs->pstart)
3435 /* [vstart, vend) */
3436 static int chunk_vrange_filter(struct extent_buffer *leaf,
3437 struct btrfs_chunk *chunk,
3439 struct btrfs_balance_args *bargs)
3441 if (chunk_offset < bargs->vend &&
3442 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3443 /* at least part of the chunk is inside this vrange */
3449 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3450 struct btrfs_chunk *chunk,
3451 struct btrfs_balance_args *bargs)
3453 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3455 if (bargs->stripes_min <= num_stripes
3456 && num_stripes <= bargs->stripes_max)
3462 static int chunk_soft_convert_filter(u64 chunk_type,
3463 struct btrfs_balance_args *bargs)
3465 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3468 chunk_type = chunk_to_extended(chunk_type) &
3469 BTRFS_EXTENDED_PROFILE_MASK;
3471 if (bargs->target == chunk_type)
3477 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3478 struct extent_buffer *leaf,
3479 struct btrfs_chunk *chunk, u64 chunk_offset)
3481 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3482 struct btrfs_balance_args *bargs = NULL;
3483 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3486 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3487 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3491 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3492 bargs = &bctl->data;
3493 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3495 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3496 bargs = &bctl->meta;
3498 /* profiles filter */
3499 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3500 chunk_profiles_filter(chunk_type, bargs)) {
3505 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3506 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3508 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3509 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3514 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3515 chunk_devid_filter(leaf, chunk, bargs)) {
3519 /* drange filter, makes sense only with devid filter */
3520 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3521 chunk_drange_filter(leaf, chunk, bargs)) {
3526 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3527 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3531 /* stripes filter */
3532 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3533 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3537 /* soft profile changing mode */
3538 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3539 chunk_soft_convert_filter(chunk_type, bargs)) {
3544 * limited by count, must be the last filter
3546 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3547 if (bargs->limit == 0)
3551 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3553 * Same logic as the 'limit' filter; the minimum cannot be
3554 * determined here because we do not have the global information
3555 * about the count of all chunks that satisfy the filters.
3557 if (bargs->limit_max == 0)
3566 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3568 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3569 struct btrfs_root *chunk_root = fs_info->chunk_root;
3570 struct btrfs_root *dev_root = fs_info->dev_root;
3571 struct list_head *devices;
3572 struct btrfs_device *device;
3576 struct btrfs_chunk *chunk;
3577 struct btrfs_path *path = NULL;
3578 struct btrfs_key key;
3579 struct btrfs_key found_key;
3580 struct btrfs_trans_handle *trans;
3581 struct extent_buffer *leaf;
3584 int enospc_errors = 0;
3585 bool counting = true;
3586 /* The single value limit and min/max limits use the same bytes in the */
3587 u64 limit_data = bctl->data.limit;
3588 u64 limit_meta = bctl->meta.limit;
3589 u64 limit_sys = bctl->sys.limit;
3593 int chunk_reserved = 0;
3595 /* step one make some room on all the devices */
3596 devices = &fs_info->fs_devices->devices;
3597 list_for_each_entry(device, devices, dev_list) {
3598 old_size = btrfs_device_get_total_bytes(device);
3599 size_to_free = div_factor(old_size, 1);
3600 size_to_free = min_t(u64, size_to_free, SZ_1M);
3601 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
3602 btrfs_device_get_total_bytes(device) -
3603 btrfs_device_get_bytes_used(device) > size_to_free ||
3604 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
3607 ret = btrfs_shrink_device(device, old_size - size_to_free);
3611 /* btrfs_shrink_device never returns ret > 0 */
3616 trans = btrfs_start_transaction(dev_root, 0);
3617 if (IS_ERR(trans)) {
3618 ret = PTR_ERR(trans);
3619 btrfs_info_in_rcu(fs_info,
3620 "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3621 rcu_str_deref(device->name), ret,
3622 old_size, old_size - size_to_free);
3626 ret = btrfs_grow_device(trans, device, old_size);
3628 btrfs_end_transaction(trans);
3629 /* btrfs_grow_device never returns ret > 0 */
3631 btrfs_info_in_rcu(fs_info,
3632 "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3633 rcu_str_deref(device->name), ret,
3634 old_size, old_size - size_to_free);
3638 btrfs_end_transaction(trans);
3641 /* step two, relocate all the chunks */
3642 path = btrfs_alloc_path();
3648 /* zero out stat counters */
3649 spin_lock(&fs_info->balance_lock);
3650 memset(&bctl->stat, 0, sizeof(bctl->stat));
3651 spin_unlock(&fs_info->balance_lock);
3655 * The single value limit and min/max limits use the same bytes
3658 bctl->data.limit = limit_data;
3659 bctl->meta.limit = limit_meta;
3660 bctl->sys.limit = limit_sys;
3662 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3663 key.offset = (u64)-1;
3664 key.type = BTRFS_CHUNK_ITEM_KEY;
3667 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3668 atomic_read(&fs_info->balance_cancel_req)) {
3673 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3674 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3676 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3681 * this shouldn't happen, it means the last relocate
3685 BUG(); /* FIXME break ? */
3687 ret = btrfs_previous_item(chunk_root, path, 0,
3688 BTRFS_CHUNK_ITEM_KEY);
3690 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3695 leaf = path->nodes[0];
3696 slot = path->slots[0];
3697 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3699 if (found_key.objectid != key.objectid) {
3700 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3704 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3705 chunk_type = btrfs_chunk_type(leaf, chunk);
3708 spin_lock(&fs_info->balance_lock);
3709 bctl->stat.considered++;
3710 spin_unlock(&fs_info->balance_lock);
3713 ret = should_balance_chunk(fs_info, leaf, chunk,
3716 btrfs_release_path(path);
3718 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3723 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3724 spin_lock(&fs_info->balance_lock);
3725 bctl->stat.expected++;
3726 spin_unlock(&fs_info->balance_lock);
3728 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3730 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3732 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3739 * Apply limit_min filter, no need to check if the LIMITS
3740 * filter is used, limit_min is 0 by default
3742 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3743 count_data < bctl->data.limit_min)
3744 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3745 count_meta < bctl->meta.limit_min)
3746 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3747 count_sys < bctl->sys.limit_min)) {
3748 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3752 if (!chunk_reserved) {
3754 * We may be relocating the only data chunk we have,
3755 * which could potentially end up with losing data's
3756 * raid profile, so lets allocate an empty one in
3759 ret = btrfs_may_alloc_data_chunk(fs_info,
3762 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3764 } else if (ret == 1) {
3769 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3770 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3771 if (ret && ret != -ENOSPC)
3773 if (ret == -ENOSPC) {
3776 spin_lock(&fs_info->balance_lock);
3777 bctl->stat.completed++;
3778 spin_unlock(&fs_info->balance_lock);
3781 if (found_key.offset == 0)
3783 key.offset = found_key.offset - 1;
3787 btrfs_release_path(path);
3792 btrfs_free_path(path);
3793 if (enospc_errors) {
3794 btrfs_info(fs_info, "%d enospc errors during balance",
3804 * alloc_profile_is_valid - see if a given profile is valid and reduced
3805 * @flags: profile to validate
3806 * @extended: if true @flags is treated as an extended profile
3808 static int alloc_profile_is_valid(u64 flags, int extended)
3810 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3811 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3813 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3815 /* 1) check that all other bits are zeroed */
3819 /* 2) see if profile is reduced */
3821 return !extended; /* "0" is valid for usual profiles */
3823 /* true if exactly one bit set */
3824 return (flags & (flags - 1)) == 0;
3827 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3829 /* cancel requested || normal exit path */
3830 return atomic_read(&fs_info->balance_cancel_req) ||
3831 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3832 atomic_read(&fs_info->balance_cancel_req) == 0);
3835 static void __cancel_balance(struct btrfs_fs_info *fs_info)
3839 unset_balance_control(fs_info);
3840 ret = del_balance_item(fs_info);
3842 btrfs_handle_fs_error(fs_info, ret, NULL);
3844 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3847 /* Non-zero return value signifies invalidity */
3848 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3851 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3852 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3853 (bctl_arg->target & ~allowed)));
3857 * Should be called with both balance and volume mutexes held
3859 int btrfs_balance(struct btrfs_balance_control *bctl,
3860 struct btrfs_ioctl_balance_args *bargs)
3862 struct btrfs_fs_info *fs_info = bctl->fs_info;
3863 u64 meta_target, data_target;
3870 if (btrfs_fs_closing(fs_info) ||
3871 atomic_read(&fs_info->balance_pause_req) ||
3872 atomic_read(&fs_info->balance_cancel_req)) {
3877 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3878 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3882 * In case of mixed groups both data and meta should be picked,
3883 * and identical options should be given for both of them.
3885 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3886 if (mixed && (bctl->flags & allowed)) {
3887 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3888 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3889 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3891 "with mixed groups data and metadata balance options must be the same");
3897 num_devices = fs_info->fs_devices->num_devices;
3898 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
3899 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3900 BUG_ON(num_devices < 1);
3903 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
3904 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3905 if (num_devices > 1)
3906 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3907 if (num_devices > 2)
3908 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3909 if (num_devices > 3)
3910 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3911 BTRFS_BLOCK_GROUP_RAID6);
3912 if (validate_convert_profile(&bctl->data, allowed)) {
3914 "unable to start balance with target data profile %llu",
3919 if (validate_convert_profile(&bctl->meta, allowed)) {
3921 "unable to start balance with target metadata profile %llu",
3926 if (validate_convert_profile(&bctl->sys, allowed)) {
3928 "unable to start balance with target system profile %llu",
3934 /* allow to reduce meta or sys integrity only if force set */
3935 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3936 BTRFS_BLOCK_GROUP_RAID10 |
3937 BTRFS_BLOCK_GROUP_RAID5 |
3938 BTRFS_BLOCK_GROUP_RAID6;
3940 seq = read_seqbegin(&fs_info->profiles_lock);
3942 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3943 (fs_info->avail_system_alloc_bits & allowed) &&
3944 !(bctl->sys.target & allowed)) ||
3945 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3946 (fs_info->avail_metadata_alloc_bits & allowed) &&
3947 !(bctl->meta.target & allowed))) {
3948 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3950 "force reducing metadata integrity");
3953 "balance will reduce metadata integrity, use force if you want this");
3958 } while (read_seqretry(&fs_info->profiles_lock, seq));
3960 /* if we're not converting, the target field is uninitialized */
3961 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3962 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
3963 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3964 bctl->data.target : fs_info->avail_data_alloc_bits;
3965 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
3966 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
3968 "metadata profile 0x%llx has lower redundancy than data profile 0x%llx",
3969 meta_target, data_target);
3972 ret = insert_balance_item(fs_info, bctl);
3973 if (ret && ret != -EEXIST)
3976 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3977 BUG_ON(ret == -EEXIST);
3978 set_balance_control(bctl);
3980 BUG_ON(ret != -EEXIST);
3981 spin_lock(&fs_info->balance_lock);
3982 update_balance_args(bctl);
3983 spin_unlock(&fs_info->balance_lock);
3986 atomic_inc(&fs_info->balance_running);
3987 mutex_unlock(&fs_info->balance_mutex);
3989 ret = __btrfs_balance(fs_info);
3991 mutex_lock(&fs_info->balance_mutex);
3992 atomic_dec(&fs_info->balance_running);
3995 memset(bargs, 0, sizeof(*bargs));
3996 update_ioctl_balance_args(fs_info, 0, bargs);
3999 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4000 balance_need_close(fs_info)) {
4001 __cancel_balance(fs_info);
4004 wake_up(&fs_info->balance_wait_q);
4008 if (bctl->flags & BTRFS_BALANCE_RESUME)
4009 __cancel_balance(fs_info);
4012 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4017 static int balance_kthread(void *data)
4019 struct btrfs_fs_info *fs_info = data;
4022 mutex_lock(&fs_info->volume_mutex);
4023 mutex_lock(&fs_info->balance_mutex);
4025 if (fs_info->balance_ctl) {
4026 btrfs_info(fs_info, "continuing balance");
4027 ret = btrfs_balance(fs_info->balance_ctl, NULL);
4030 mutex_unlock(&fs_info->balance_mutex);
4031 mutex_unlock(&fs_info->volume_mutex);
4036 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4038 struct task_struct *tsk;
4040 spin_lock(&fs_info->balance_lock);
4041 if (!fs_info->balance_ctl) {
4042 spin_unlock(&fs_info->balance_lock);
4045 spin_unlock(&fs_info->balance_lock);
4047 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4048 btrfs_info(fs_info, "force skipping balance");
4052 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4053 return PTR_ERR_OR_ZERO(tsk);
4056 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4058 struct btrfs_balance_control *bctl;
4059 struct btrfs_balance_item *item;
4060 struct btrfs_disk_balance_args disk_bargs;
4061 struct btrfs_path *path;
4062 struct extent_buffer *leaf;
4063 struct btrfs_key key;
4066 path = btrfs_alloc_path();
4070 key.objectid = BTRFS_BALANCE_OBJECTID;
4071 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4074 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4077 if (ret > 0) { /* ret = -ENOENT; */
4082 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4088 leaf = path->nodes[0];
4089 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4091 bctl->fs_info = fs_info;
4092 bctl->flags = btrfs_balance_flags(leaf, item);
4093 bctl->flags |= BTRFS_BALANCE_RESUME;
4095 btrfs_balance_data(leaf, item, &disk_bargs);
4096 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4097 btrfs_balance_meta(leaf, item, &disk_bargs);
4098 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4099 btrfs_balance_sys(leaf, item, &disk_bargs);
4100 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4102 WARN_ON(test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4104 mutex_lock(&fs_info->volume_mutex);
4105 mutex_lock(&fs_info->balance_mutex);
4107 set_balance_control(bctl);
4109 mutex_unlock(&fs_info->balance_mutex);
4110 mutex_unlock(&fs_info->volume_mutex);
4112 btrfs_free_path(path);
4116 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4120 mutex_lock(&fs_info->balance_mutex);
4121 if (!fs_info->balance_ctl) {
4122 mutex_unlock(&fs_info->balance_mutex);
4126 if (atomic_read(&fs_info->balance_running)) {
4127 atomic_inc(&fs_info->balance_pause_req);
4128 mutex_unlock(&fs_info->balance_mutex);
4130 wait_event(fs_info->balance_wait_q,
4131 atomic_read(&fs_info->balance_running) == 0);
4133 mutex_lock(&fs_info->balance_mutex);
4134 /* we are good with balance_ctl ripped off from under us */
4135 BUG_ON(atomic_read(&fs_info->balance_running));
4136 atomic_dec(&fs_info->balance_pause_req);
4141 mutex_unlock(&fs_info->balance_mutex);
4145 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4147 if (sb_rdonly(fs_info->sb))
4150 mutex_lock(&fs_info->balance_mutex);
4151 if (!fs_info->balance_ctl) {
4152 mutex_unlock(&fs_info->balance_mutex);
4156 atomic_inc(&fs_info->balance_cancel_req);
4158 * if we are running just wait and return, balance item is
4159 * deleted in btrfs_balance in this case
4161 if (atomic_read(&fs_info->balance_running)) {
4162 mutex_unlock(&fs_info->balance_mutex);
4163 wait_event(fs_info->balance_wait_q,
4164 atomic_read(&fs_info->balance_running) == 0);
4165 mutex_lock(&fs_info->balance_mutex);
4167 /* __cancel_balance needs volume_mutex */
4168 mutex_unlock(&fs_info->balance_mutex);
4169 mutex_lock(&fs_info->volume_mutex);
4170 mutex_lock(&fs_info->balance_mutex);
4172 if (fs_info->balance_ctl)
4173 __cancel_balance(fs_info);
4175 mutex_unlock(&fs_info->volume_mutex);
4178 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
4179 atomic_dec(&fs_info->balance_cancel_req);
4180 mutex_unlock(&fs_info->balance_mutex);
4184 static int btrfs_uuid_scan_kthread(void *data)
4186 struct btrfs_fs_info *fs_info = data;
4187 struct btrfs_root *root = fs_info->tree_root;
4188 struct btrfs_key key;
4189 struct btrfs_path *path = NULL;
4191 struct extent_buffer *eb;
4193 struct btrfs_root_item root_item;
4195 struct btrfs_trans_handle *trans = NULL;
4197 path = btrfs_alloc_path();
4204 key.type = BTRFS_ROOT_ITEM_KEY;
4208 ret = btrfs_search_forward(root, &key, path, 0);
4215 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4216 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4217 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4218 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4221 eb = path->nodes[0];
4222 slot = path->slots[0];
4223 item_size = btrfs_item_size_nr(eb, slot);
4224 if (item_size < sizeof(root_item))
4227 read_extent_buffer(eb, &root_item,
4228 btrfs_item_ptr_offset(eb, slot),
4229 (int)sizeof(root_item));
4230 if (btrfs_root_refs(&root_item) == 0)
4233 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4234 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4238 btrfs_release_path(path);
4240 * 1 - subvol uuid item
4241 * 1 - received_subvol uuid item
4243 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4244 if (IS_ERR(trans)) {
4245 ret = PTR_ERR(trans);
4253 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4254 ret = btrfs_uuid_tree_add(trans, fs_info,
4256 BTRFS_UUID_KEY_SUBVOL,
4259 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4265 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4266 ret = btrfs_uuid_tree_add(trans, fs_info,
4267 root_item.received_uuid,
4268 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4271 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4279 ret = btrfs_end_transaction(trans);
4285 btrfs_release_path(path);
4286 if (key.offset < (u64)-1) {
4288 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4290 key.type = BTRFS_ROOT_ITEM_KEY;
4291 } else if (key.objectid < (u64)-1) {
4293 key.type = BTRFS_ROOT_ITEM_KEY;
4302 btrfs_free_path(path);
4303 if (trans && !IS_ERR(trans))
4304 btrfs_end_transaction(trans);
4306 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4308 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4309 up(&fs_info->uuid_tree_rescan_sem);
4314 * Callback for btrfs_uuid_tree_iterate().
4316 * 0 check succeeded, the entry is not outdated.
4317 * < 0 if an error occurred.
4318 * > 0 if the check failed, which means the caller shall remove the entry.
4320 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4321 u8 *uuid, u8 type, u64 subid)
4323 struct btrfs_key key;
4325 struct btrfs_root *subvol_root;
4327 if (type != BTRFS_UUID_KEY_SUBVOL &&
4328 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4331 key.objectid = subid;
4332 key.type = BTRFS_ROOT_ITEM_KEY;
4333 key.offset = (u64)-1;
4334 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4335 if (IS_ERR(subvol_root)) {
4336 ret = PTR_ERR(subvol_root);
4343 case BTRFS_UUID_KEY_SUBVOL:
4344 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4347 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4348 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4358 static int btrfs_uuid_rescan_kthread(void *data)
4360 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4364 * 1st step is to iterate through the existing UUID tree and
4365 * to delete all entries that contain outdated data.
4366 * 2nd step is to add all missing entries to the UUID tree.
4368 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4370 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4371 up(&fs_info->uuid_tree_rescan_sem);
4374 return btrfs_uuid_scan_kthread(data);
4377 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4379 struct btrfs_trans_handle *trans;
4380 struct btrfs_root *tree_root = fs_info->tree_root;
4381 struct btrfs_root *uuid_root;
4382 struct task_struct *task;
4389 trans = btrfs_start_transaction(tree_root, 2);
4391 return PTR_ERR(trans);
4393 uuid_root = btrfs_create_tree(trans, fs_info,
4394 BTRFS_UUID_TREE_OBJECTID);
4395 if (IS_ERR(uuid_root)) {
4396 ret = PTR_ERR(uuid_root);
4397 btrfs_abort_transaction(trans, ret);
4398 btrfs_end_transaction(trans);
4402 fs_info->uuid_root = uuid_root;
4404 ret = btrfs_commit_transaction(trans);
4408 down(&fs_info->uuid_tree_rescan_sem);
4409 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4411 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4412 btrfs_warn(fs_info, "failed to start uuid_scan task");
4413 up(&fs_info->uuid_tree_rescan_sem);
4414 return PTR_ERR(task);
4420 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4422 struct task_struct *task;
4424 down(&fs_info->uuid_tree_rescan_sem);
4425 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4427 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4428 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4429 up(&fs_info->uuid_tree_rescan_sem);
4430 return PTR_ERR(task);
4437 * shrinking a device means finding all of the device extents past
4438 * the new size, and then following the back refs to the chunks.
4439 * The chunk relocation code actually frees the device extent
4441 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4443 struct btrfs_fs_info *fs_info = device->fs_info;
4444 struct btrfs_root *root = fs_info->dev_root;
4445 struct btrfs_trans_handle *trans;
4446 struct btrfs_dev_extent *dev_extent = NULL;
4447 struct btrfs_path *path;
4453 bool retried = false;
4454 bool checked_pending_chunks = false;
4455 struct extent_buffer *l;
4456 struct btrfs_key key;
4457 struct btrfs_super_block *super_copy = fs_info->super_copy;
4458 u64 old_total = btrfs_super_total_bytes(super_copy);
4459 u64 old_size = btrfs_device_get_total_bytes(device);
4462 new_size = round_down(new_size, fs_info->sectorsize);
4463 diff = round_down(old_size - new_size, fs_info->sectorsize);
4465 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4468 path = btrfs_alloc_path();
4472 path->reada = READA_FORWARD;
4474 mutex_lock(&fs_info->chunk_mutex);
4476 btrfs_device_set_total_bytes(device, new_size);
4477 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4478 device->fs_devices->total_rw_bytes -= diff;
4479 atomic64_sub(diff, &fs_info->free_chunk_space);
4481 mutex_unlock(&fs_info->chunk_mutex);
4484 key.objectid = device->devid;
4485 key.offset = (u64)-1;
4486 key.type = BTRFS_DEV_EXTENT_KEY;
4489 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4490 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4492 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4496 ret = btrfs_previous_item(root, path, 0, key.type);
4498 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4503 btrfs_release_path(path);
4508 slot = path->slots[0];
4509 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4511 if (key.objectid != device->devid) {
4512 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4513 btrfs_release_path(path);
4517 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4518 length = btrfs_dev_extent_length(l, dev_extent);
4520 if (key.offset + length <= new_size) {
4521 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4522 btrfs_release_path(path);
4526 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4527 btrfs_release_path(path);
4530 * We may be relocating the only data chunk we have,
4531 * which could potentially end up with losing data's
4532 * raid profile, so lets allocate an empty one in
4535 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4537 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4541 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4542 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4543 if (ret && ret != -ENOSPC)
4547 } while (key.offset-- > 0);
4549 if (failed && !retried) {
4553 } else if (failed && retried) {
4558 /* Shrinking succeeded, else we would be at "done". */
4559 trans = btrfs_start_transaction(root, 0);
4560 if (IS_ERR(trans)) {
4561 ret = PTR_ERR(trans);
4565 mutex_lock(&fs_info->chunk_mutex);
4568 * We checked in the above loop all device extents that were already in
4569 * the device tree. However before we have updated the device's
4570 * total_bytes to the new size, we might have had chunk allocations that
4571 * have not complete yet (new block groups attached to transaction
4572 * handles), and therefore their device extents were not yet in the
4573 * device tree and we missed them in the loop above. So if we have any
4574 * pending chunk using a device extent that overlaps the device range
4575 * that we can not use anymore, commit the current transaction and
4576 * repeat the search on the device tree - this way we guarantee we will
4577 * not have chunks using device extents that end beyond 'new_size'.
4579 if (!checked_pending_chunks) {
4580 u64 start = new_size;
4581 u64 len = old_size - new_size;
4583 if (contains_pending_extent(trans->transaction, device,
4585 mutex_unlock(&fs_info->chunk_mutex);
4586 checked_pending_chunks = true;
4589 ret = btrfs_commit_transaction(trans);
4596 btrfs_device_set_disk_total_bytes(device, new_size);
4597 if (list_empty(&device->resized_list))
4598 list_add_tail(&device->resized_list,
4599 &fs_info->fs_devices->resized_devices);
4601 WARN_ON(diff > old_total);
4602 btrfs_set_super_total_bytes(super_copy,
4603 round_down(old_total - diff, fs_info->sectorsize));
4604 mutex_unlock(&fs_info->chunk_mutex);
4606 /* Now btrfs_update_device() will change the on-disk size. */
4607 ret = btrfs_update_device(trans, device);
4608 btrfs_end_transaction(trans);
4610 btrfs_free_path(path);
4612 mutex_lock(&fs_info->chunk_mutex);
4613 btrfs_device_set_total_bytes(device, old_size);
4614 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4615 device->fs_devices->total_rw_bytes += diff;
4616 atomic64_add(diff, &fs_info->free_chunk_space);
4617 mutex_unlock(&fs_info->chunk_mutex);
4622 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4623 struct btrfs_key *key,
4624 struct btrfs_chunk *chunk, int item_size)
4626 struct btrfs_super_block *super_copy = fs_info->super_copy;
4627 struct btrfs_disk_key disk_key;
4631 mutex_lock(&fs_info->chunk_mutex);
4632 array_size = btrfs_super_sys_array_size(super_copy);
4633 if (array_size + item_size + sizeof(disk_key)
4634 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4635 mutex_unlock(&fs_info->chunk_mutex);
4639 ptr = super_copy->sys_chunk_array + array_size;
4640 btrfs_cpu_key_to_disk(&disk_key, key);
4641 memcpy(ptr, &disk_key, sizeof(disk_key));
4642 ptr += sizeof(disk_key);
4643 memcpy(ptr, chunk, item_size);
4644 item_size += sizeof(disk_key);
4645 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4646 mutex_unlock(&fs_info->chunk_mutex);
4652 * sort the devices in descending order by max_avail, total_avail
4654 static int btrfs_cmp_device_info(const void *a, const void *b)
4656 const struct btrfs_device_info *di_a = a;
4657 const struct btrfs_device_info *di_b = b;
4659 if (di_a->max_avail > di_b->max_avail)
4661 if (di_a->max_avail < di_b->max_avail)
4663 if (di_a->total_avail > di_b->total_avail)
4665 if (di_a->total_avail < di_b->total_avail)
4670 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4672 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4675 btrfs_set_fs_incompat(info, RAID56);
4678 #define BTRFS_MAX_DEVS(info) ((BTRFS_MAX_ITEM_SIZE(info) \
4679 - sizeof(struct btrfs_chunk)) \
4680 / sizeof(struct btrfs_stripe) + 1)
4682 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4683 - 2 * sizeof(struct btrfs_disk_key) \
4684 - 2 * sizeof(struct btrfs_chunk)) \
4685 / sizeof(struct btrfs_stripe) + 1)
4687 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4688 u64 start, u64 type)
4690 struct btrfs_fs_info *info = trans->fs_info;
4691 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4692 struct btrfs_device *device;
4693 struct map_lookup *map = NULL;
4694 struct extent_map_tree *em_tree;
4695 struct extent_map *em;
4696 struct btrfs_device_info *devices_info = NULL;
4698 int num_stripes; /* total number of stripes to allocate */
4699 int data_stripes; /* number of stripes that count for
4701 int sub_stripes; /* sub_stripes info for map */
4702 int dev_stripes; /* stripes per dev */
4703 int devs_max; /* max devs to use */
4704 int devs_min; /* min devs needed */
4705 int devs_increment; /* ndevs has to be a multiple of this */
4706 int ncopies; /* how many copies to data has */
4708 u64 max_stripe_size;
4717 BUG_ON(!alloc_profile_is_valid(type, 0));
4719 if (list_empty(&fs_devices->alloc_list)) {
4720 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4721 btrfs_debug(info, "%s: no writable device", __func__);
4725 index = btrfs_bg_flags_to_raid_index(type);
4727 sub_stripes = btrfs_raid_array[index].sub_stripes;
4728 dev_stripes = btrfs_raid_array[index].dev_stripes;
4729 devs_max = btrfs_raid_array[index].devs_max;
4730 devs_min = btrfs_raid_array[index].devs_min;
4731 devs_increment = btrfs_raid_array[index].devs_increment;
4732 ncopies = btrfs_raid_array[index].ncopies;
4734 if (type & BTRFS_BLOCK_GROUP_DATA) {
4735 max_stripe_size = SZ_1G;
4736 max_chunk_size = 10 * max_stripe_size;
4738 devs_max = BTRFS_MAX_DEVS(info);
4739 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4740 /* for larger filesystems, use larger metadata chunks */
4741 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4742 max_stripe_size = SZ_1G;
4744 max_stripe_size = SZ_256M;
4745 max_chunk_size = max_stripe_size;
4747 devs_max = BTRFS_MAX_DEVS(info);
4748 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4749 max_stripe_size = SZ_32M;
4750 max_chunk_size = 2 * max_stripe_size;
4752 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4754 btrfs_err(info, "invalid chunk type 0x%llx requested",
4759 /* we don't want a chunk larger than 10% of writeable space */
4760 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4763 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4769 * in the first pass through the devices list, we gather information
4770 * about the available holes on each device.
4773 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4777 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4779 "BTRFS: read-only device in alloc_list\n");
4783 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4784 &device->dev_state) ||
4785 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4788 if (device->total_bytes > device->bytes_used)
4789 total_avail = device->total_bytes - device->bytes_used;
4793 /* If there is no space on this device, skip it. */
4794 if (total_avail == 0)
4797 ret = find_free_dev_extent(trans, device,
4798 max_stripe_size * dev_stripes,
4799 &dev_offset, &max_avail);
4800 if (ret && ret != -ENOSPC)
4804 max_avail = max_stripe_size * dev_stripes;
4806 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
4807 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4809 "%s: devid %llu has no free space, have=%llu want=%u",
4810 __func__, device->devid, max_avail,
4811 BTRFS_STRIPE_LEN * dev_stripes);
4815 if (ndevs == fs_devices->rw_devices) {
4816 WARN(1, "%s: found more than %llu devices\n",
4817 __func__, fs_devices->rw_devices);
4820 devices_info[ndevs].dev_offset = dev_offset;
4821 devices_info[ndevs].max_avail = max_avail;
4822 devices_info[ndevs].total_avail = total_avail;
4823 devices_info[ndevs].dev = device;
4828 * now sort the devices by hole size / available space
4830 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4831 btrfs_cmp_device_info, NULL);
4833 /* round down to number of usable stripes */
4834 ndevs = round_down(ndevs, devs_increment);
4836 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
4838 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
4840 "%s: not enough devices with free space: have=%d minimum required=%d",
4841 __func__, ndevs, min(devs_min,
4842 devs_increment * sub_stripes));
4847 ndevs = min(ndevs, devs_max);
4850 * The primary goal is to maximize the number of stripes, so use as
4851 * many devices as possible, even if the stripes are not maximum sized.
4853 * The DUP profile stores more than one stripe per device, the
4854 * max_avail is the total size so we have to adjust.
4856 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
4857 num_stripes = ndevs * dev_stripes;
4860 * this will have to be fixed for RAID1 and RAID10 over
4863 data_stripes = num_stripes / ncopies;
4865 if (type & BTRFS_BLOCK_GROUP_RAID5)
4866 data_stripes = num_stripes - 1;
4868 if (type & BTRFS_BLOCK_GROUP_RAID6)
4869 data_stripes = num_stripes - 2;
4872 * Use the number of data stripes to figure out how big this chunk
4873 * is really going to be in terms of logical address space,
4874 * and compare that answer with the max chunk size
4876 if (stripe_size * data_stripes > max_chunk_size) {
4877 stripe_size = div_u64(max_chunk_size, data_stripes);
4879 /* bump the answer up to a 16MB boundary */
4880 stripe_size = round_up(stripe_size, SZ_16M);
4883 * But don't go higher than the limits we found while searching
4886 stripe_size = min(devices_info[ndevs - 1].max_avail,
4890 /* align to BTRFS_STRIPE_LEN */
4891 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
4893 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4898 map->num_stripes = num_stripes;
4900 for (i = 0; i < ndevs; ++i) {
4901 for (j = 0; j < dev_stripes; ++j) {
4902 int s = i * dev_stripes + j;
4903 map->stripes[s].dev = devices_info[i].dev;
4904 map->stripes[s].physical = devices_info[i].dev_offset +
4908 map->stripe_len = BTRFS_STRIPE_LEN;
4909 map->io_align = BTRFS_STRIPE_LEN;
4910 map->io_width = BTRFS_STRIPE_LEN;
4912 map->sub_stripes = sub_stripes;
4914 num_bytes = stripe_size * data_stripes;
4916 trace_btrfs_chunk_alloc(info, map, start, num_bytes);
4918 em = alloc_extent_map();
4924 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4925 em->map_lookup = map;
4927 em->len = num_bytes;
4928 em->block_start = 0;
4929 em->block_len = em->len;
4930 em->orig_block_len = stripe_size;
4932 em_tree = &info->mapping_tree.map_tree;
4933 write_lock(&em_tree->lock);
4934 ret = add_extent_mapping(em_tree, em, 0);
4936 write_unlock(&em_tree->lock);
4937 free_extent_map(em);
4941 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4942 refcount_inc(&em->refs);
4943 write_unlock(&em_tree->lock);
4945 ret = btrfs_make_block_group(trans, info, 0, type, start, num_bytes);
4947 goto error_del_extent;
4949 for (i = 0; i < map->num_stripes; i++) {
4950 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4951 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4954 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
4956 free_extent_map(em);
4957 check_raid56_incompat_flag(info, type);
4959 kfree(devices_info);
4963 write_lock(&em_tree->lock);
4964 remove_extent_mapping(em_tree, em);
4965 write_unlock(&em_tree->lock);
4967 /* One for our allocation */
4968 free_extent_map(em);
4969 /* One for the tree reference */
4970 free_extent_map(em);
4971 /* One for the pending_chunks list reference */
4972 free_extent_map(em);
4974 kfree(devices_info);
4978 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4979 struct btrfs_fs_info *fs_info,
4980 u64 chunk_offset, u64 chunk_size)
4982 struct btrfs_root *extent_root = fs_info->extent_root;
4983 struct btrfs_root *chunk_root = fs_info->chunk_root;
4984 struct btrfs_key key;
4985 struct btrfs_device *device;
4986 struct btrfs_chunk *chunk;
4987 struct btrfs_stripe *stripe;
4988 struct extent_map *em;
4989 struct map_lookup *map;
4996 em = get_chunk_map(fs_info, chunk_offset, chunk_size);
5000 map = em->map_lookup;
5001 item_size = btrfs_chunk_item_size(map->num_stripes);
5002 stripe_size = em->orig_block_len;
5004 chunk = kzalloc(item_size, GFP_NOFS);
5011 * Take the device list mutex to prevent races with the final phase of
5012 * a device replace operation that replaces the device object associated
5013 * with the map's stripes, because the device object's id can change
5014 * at any time during that final phase of the device replace operation
5015 * (dev-replace.c:btrfs_dev_replace_finishing()).
5017 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5018 for (i = 0; i < map->num_stripes; i++) {
5019 device = map->stripes[i].dev;
5020 dev_offset = map->stripes[i].physical;
5022 ret = btrfs_update_device(trans, device);
5025 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5026 dev_offset, stripe_size);
5031 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5035 stripe = &chunk->stripe;
5036 for (i = 0; i < map->num_stripes; i++) {
5037 device = map->stripes[i].dev;
5038 dev_offset = map->stripes[i].physical;
5040 btrfs_set_stack_stripe_devid(stripe, device->devid);
5041 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5042 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5045 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5047 btrfs_set_stack_chunk_length(chunk, chunk_size);
5048 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5049 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5050 btrfs_set_stack_chunk_type(chunk, map->type);
5051 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5052 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5053 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5054 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5055 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5057 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5058 key.type = BTRFS_CHUNK_ITEM_KEY;
5059 key.offset = chunk_offset;
5061 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5062 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5064 * TODO: Cleanup of inserted chunk root in case of
5067 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5072 free_extent_map(em);
5077 * Chunk allocation falls into two parts. The first part does works
5078 * that make the new allocated chunk useable, but not do any operation
5079 * that modifies the chunk tree. The second part does the works that
5080 * require modifying the chunk tree. This division is important for the
5081 * bootstrap process of adding storage to a seed btrfs.
5083 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
5084 struct btrfs_fs_info *fs_info, u64 type)
5088 ASSERT(mutex_is_locked(&fs_info->chunk_mutex));
5089 chunk_offset = find_next_chunk(fs_info);
5090 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5093 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5094 struct btrfs_fs_info *fs_info)
5097 u64 sys_chunk_offset;
5101 chunk_offset = find_next_chunk(fs_info);
5102 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5103 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5107 sys_chunk_offset = find_next_chunk(fs_info);
5108 alloc_profile = btrfs_system_alloc_profile(fs_info);
5109 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5113 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5117 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5118 BTRFS_BLOCK_GROUP_RAID10 |
5119 BTRFS_BLOCK_GROUP_RAID5 |
5120 BTRFS_BLOCK_GROUP_DUP)) {
5122 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5131 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5133 struct extent_map *em;
5134 struct map_lookup *map;
5139 em = get_chunk_map(fs_info, chunk_offset, 1);
5143 map = em->map_lookup;
5144 for (i = 0; i < map->num_stripes; i++) {
5145 if (test_bit(BTRFS_DEV_STATE_MISSING,
5146 &map->stripes[i].dev->dev_state)) {
5150 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5151 &map->stripes[i].dev->dev_state)) {
5158 * If the number of missing devices is larger than max errors,
5159 * we can not write the data into that chunk successfully, so
5162 if (miss_ndevs > btrfs_chunk_max_errors(map))
5165 free_extent_map(em);
5169 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5171 extent_map_tree_init(&tree->map_tree);
5174 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5176 struct extent_map *em;
5179 write_lock(&tree->map_tree.lock);
5180 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5182 remove_extent_mapping(&tree->map_tree, em);
5183 write_unlock(&tree->map_tree.lock);
5187 free_extent_map(em);
5188 /* once for the tree */
5189 free_extent_map(em);
5193 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5195 struct extent_map *em;
5196 struct map_lookup *map;
5199 em = get_chunk_map(fs_info, logical, len);
5202 * We could return errors for these cases, but that could get
5203 * ugly and we'd probably do the same thing which is just not do
5204 * anything else and exit, so return 1 so the callers don't try
5205 * to use other copies.
5209 map = em->map_lookup;
5210 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5211 ret = map->num_stripes;
5212 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5213 ret = map->sub_stripes;
5214 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5216 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5218 * There could be two corrupted data stripes, we need
5219 * to loop retry in order to rebuild the correct data.
5221 * Fail a stripe at a time on every retry except the
5222 * stripe under reconstruction.
5224 ret = map->num_stripes;
5227 free_extent_map(em);
5229 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
5230 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5231 fs_info->dev_replace.tgtdev)
5233 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
5238 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5241 struct extent_map *em;
5242 struct map_lookup *map;
5243 unsigned long len = fs_info->sectorsize;
5245 em = get_chunk_map(fs_info, logical, len);
5247 if (!WARN_ON(IS_ERR(em))) {
5248 map = em->map_lookup;
5249 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5250 len = map->stripe_len * nr_data_stripes(map);
5251 free_extent_map(em);
5256 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5258 struct extent_map *em;
5259 struct map_lookup *map;
5262 em = get_chunk_map(fs_info, logical, len);
5264 if(!WARN_ON(IS_ERR(em))) {
5265 map = em->map_lookup;
5266 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5268 free_extent_map(em);
5273 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5274 struct map_lookup *map, int first, int num,
5275 int optimal, int dev_replace_is_ongoing)
5279 struct btrfs_device *srcdev;
5281 if (dev_replace_is_ongoing &&
5282 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5283 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5284 srcdev = fs_info->dev_replace.srcdev;
5289 * try to avoid the drive that is the source drive for a
5290 * dev-replace procedure, only choose it if no other non-missing
5291 * mirror is available
5293 for (tolerance = 0; tolerance < 2; tolerance++) {
5294 if (map->stripes[optimal].dev->bdev &&
5295 (tolerance || map->stripes[optimal].dev != srcdev))
5297 for (i = first; i < first + num; i++) {
5298 if (map->stripes[i].dev->bdev &&
5299 (tolerance || map->stripes[i].dev != srcdev))
5304 /* we couldn't find one that doesn't fail. Just return something
5305 * and the io error handling code will clean up eventually
5310 static inline int parity_smaller(u64 a, u64 b)
5315 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5316 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5318 struct btrfs_bio_stripe s;
5325 for (i = 0; i < num_stripes - 1; i++) {
5326 if (parity_smaller(bbio->raid_map[i],
5327 bbio->raid_map[i+1])) {
5328 s = bbio->stripes[i];
5329 l = bbio->raid_map[i];
5330 bbio->stripes[i] = bbio->stripes[i+1];
5331 bbio->raid_map[i] = bbio->raid_map[i+1];
5332 bbio->stripes[i+1] = s;
5333 bbio->raid_map[i+1] = l;
5341 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5343 struct btrfs_bio *bbio = kzalloc(
5344 /* the size of the btrfs_bio */
5345 sizeof(struct btrfs_bio) +
5346 /* plus the variable array for the stripes */
5347 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5348 /* plus the variable array for the tgt dev */
5349 sizeof(int) * (real_stripes) +
5351 * plus the raid_map, which includes both the tgt dev
5354 sizeof(u64) * (total_stripes),
5355 GFP_NOFS|__GFP_NOFAIL);
5357 atomic_set(&bbio->error, 0);
5358 refcount_set(&bbio->refs, 1);
5363 void btrfs_get_bbio(struct btrfs_bio *bbio)
5365 WARN_ON(!refcount_read(&bbio->refs));
5366 refcount_inc(&bbio->refs);
5369 void btrfs_put_bbio(struct btrfs_bio *bbio)
5373 if (refcount_dec_and_test(&bbio->refs))
5377 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5379 * Please note that, discard won't be sent to target device of device
5382 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5383 u64 logical, u64 length,
5384 struct btrfs_bio **bbio_ret)
5386 struct extent_map *em;
5387 struct map_lookup *map;
5388 struct btrfs_bio *bbio;
5392 u64 stripe_end_offset;
5399 u32 sub_stripes = 0;
5400 u64 stripes_per_dev = 0;
5401 u32 remaining_stripes = 0;
5402 u32 last_stripe = 0;
5406 /* discard always return a bbio */
5409 em = get_chunk_map(fs_info, logical, length);
5413 map = em->map_lookup;
5414 /* we don't discard raid56 yet */
5415 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5420 offset = logical - em->start;
5421 length = min_t(u64, em->len - offset, length);
5423 stripe_len = map->stripe_len;
5425 * stripe_nr counts the total number of stripes we have to stride
5426 * to get to this block
5428 stripe_nr = div64_u64(offset, stripe_len);
5430 /* stripe_offset is the offset of this block in its stripe */
5431 stripe_offset = offset - stripe_nr * stripe_len;
5433 stripe_nr_end = round_up(offset + length, map->stripe_len);
5434 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5435 stripe_cnt = stripe_nr_end - stripe_nr;
5436 stripe_end_offset = stripe_nr_end * map->stripe_len -
5439 * after this, stripe_nr is the number of stripes on this
5440 * device we have to walk to find the data, and stripe_index is
5441 * the number of our device in the stripe array
5445 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5446 BTRFS_BLOCK_GROUP_RAID10)) {
5447 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5450 sub_stripes = map->sub_stripes;
5452 factor = map->num_stripes / sub_stripes;
5453 num_stripes = min_t(u64, map->num_stripes,
5454 sub_stripes * stripe_cnt);
5455 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5456 stripe_index *= sub_stripes;
5457 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5458 &remaining_stripes);
5459 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5460 last_stripe *= sub_stripes;
5461 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5462 BTRFS_BLOCK_GROUP_DUP)) {
5463 num_stripes = map->num_stripes;
5465 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5469 bbio = alloc_btrfs_bio(num_stripes, 0);
5475 for (i = 0; i < num_stripes; i++) {
5476 bbio->stripes[i].physical =
5477 map->stripes[stripe_index].physical +
5478 stripe_offset + stripe_nr * map->stripe_len;
5479 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5481 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5482 BTRFS_BLOCK_GROUP_RAID10)) {
5483 bbio->stripes[i].length = stripes_per_dev *
5486 if (i / sub_stripes < remaining_stripes)
5487 bbio->stripes[i].length +=
5491 * Special for the first stripe and
5494 * |-------|...|-------|
5498 if (i < sub_stripes)
5499 bbio->stripes[i].length -=
5502 if (stripe_index >= last_stripe &&
5503 stripe_index <= (last_stripe +
5505 bbio->stripes[i].length -=
5508 if (i == sub_stripes - 1)
5511 bbio->stripes[i].length = length;
5515 if (stripe_index == map->num_stripes) {
5522 bbio->map_type = map->type;
5523 bbio->num_stripes = num_stripes;
5525 free_extent_map(em);
5530 * In dev-replace case, for repair case (that's the only case where the mirror
5531 * is selected explicitly when calling btrfs_map_block), blocks left of the
5532 * left cursor can also be read from the target drive.
5534 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5536 * For READ, it also needs to be supported using the same mirror number.
5538 * If the requested block is not left of the left cursor, EIO is returned. This
5539 * can happen because btrfs_num_copies() returns one more in the dev-replace
5542 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5543 u64 logical, u64 length,
5544 u64 srcdev_devid, int *mirror_num,
5547 struct btrfs_bio *bbio = NULL;
5549 int index_srcdev = 0;
5551 u64 physical_of_found = 0;
5555 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5556 logical, &length, &bbio, 0, 0);
5558 ASSERT(bbio == NULL);
5562 num_stripes = bbio->num_stripes;
5563 if (*mirror_num > num_stripes) {
5565 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5566 * that means that the requested area is not left of the left
5569 btrfs_put_bbio(bbio);
5574 * process the rest of the function using the mirror_num of the source
5575 * drive. Therefore look it up first. At the end, patch the device
5576 * pointer to the one of the target drive.
5578 for (i = 0; i < num_stripes; i++) {
5579 if (bbio->stripes[i].dev->devid != srcdev_devid)
5583 * In case of DUP, in order to keep it simple, only add the
5584 * mirror with the lowest physical address
5587 physical_of_found <= bbio->stripes[i].physical)
5592 physical_of_found = bbio->stripes[i].physical;
5595 btrfs_put_bbio(bbio);
5601 *mirror_num = index_srcdev + 1;
5602 *physical = physical_of_found;
5606 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5607 struct btrfs_bio **bbio_ret,
5608 struct btrfs_dev_replace *dev_replace,
5609 int *num_stripes_ret, int *max_errors_ret)
5611 struct btrfs_bio *bbio = *bbio_ret;
5612 u64 srcdev_devid = dev_replace->srcdev->devid;
5613 int tgtdev_indexes = 0;
5614 int num_stripes = *num_stripes_ret;
5615 int max_errors = *max_errors_ret;
5618 if (op == BTRFS_MAP_WRITE) {
5619 int index_where_to_add;
5622 * duplicate the write operations while the dev replace
5623 * procedure is running. Since the copying of the old disk to
5624 * the new disk takes place at run time while the filesystem is
5625 * mounted writable, the regular write operations to the old
5626 * disk have to be duplicated to go to the new disk as well.
5628 * Note that device->missing is handled by the caller, and that
5629 * the write to the old disk is already set up in the stripes
5632 index_where_to_add = num_stripes;
5633 for (i = 0; i < num_stripes; i++) {
5634 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5635 /* write to new disk, too */
5636 struct btrfs_bio_stripe *new =
5637 bbio->stripes + index_where_to_add;
5638 struct btrfs_bio_stripe *old =
5641 new->physical = old->physical;
5642 new->length = old->length;
5643 new->dev = dev_replace->tgtdev;
5644 bbio->tgtdev_map[i] = index_where_to_add;
5645 index_where_to_add++;
5650 num_stripes = index_where_to_add;
5651 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5652 int index_srcdev = 0;
5654 u64 physical_of_found = 0;
5657 * During the dev-replace procedure, the target drive can also
5658 * be used to read data in case it is needed to repair a corrupt
5659 * block elsewhere. This is possible if the requested area is
5660 * left of the left cursor. In this area, the target drive is a
5661 * full copy of the source drive.
5663 for (i = 0; i < num_stripes; i++) {
5664 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5666 * In case of DUP, in order to keep it simple,
5667 * only add the mirror with the lowest physical
5671 physical_of_found <=
5672 bbio->stripes[i].physical)
5676 physical_of_found = bbio->stripes[i].physical;
5680 struct btrfs_bio_stripe *tgtdev_stripe =
5681 bbio->stripes + num_stripes;
5683 tgtdev_stripe->physical = physical_of_found;
5684 tgtdev_stripe->length =
5685 bbio->stripes[index_srcdev].length;
5686 tgtdev_stripe->dev = dev_replace->tgtdev;
5687 bbio->tgtdev_map[index_srcdev] = num_stripes;
5694 *num_stripes_ret = num_stripes;
5695 *max_errors_ret = max_errors;
5696 bbio->num_tgtdevs = tgtdev_indexes;
5700 static bool need_full_stripe(enum btrfs_map_op op)
5702 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5705 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5706 enum btrfs_map_op op,
5707 u64 logical, u64 *length,
5708 struct btrfs_bio **bbio_ret,
5709 int mirror_num, int need_raid_map)
5711 struct extent_map *em;
5712 struct map_lookup *map;
5722 int tgtdev_indexes = 0;
5723 struct btrfs_bio *bbio = NULL;
5724 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5725 int dev_replace_is_ongoing = 0;
5726 int num_alloc_stripes;
5727 int patch_the_first_stripe_for_dev_replace = 0;
5728 u64 physical_to_patch_in_first_stripe = 0;
5729 u64 raid56_full_stripe_start = (u64)-1;
5731 if (op == BTRFS_MAP_DISCARD)
5732 return __btrfs_map_block_for_discard(fs_info, logical,
5735 em = get_chunk_map(fs_info, logical, *length);
5739 map = em->map_lookup;
5740 offset = logical - em->start;
5742 stripe_len = map->stripe_len;
5745 * stripe_nr counts the total number of stripes we have to stride
5746 * to get to this block
5748 stripe_nr = div64_u64(stripe_nr, stripe_len);
5750 stripe_offset = stripe_nr * stripe_len;
5751 if (offset < stripe_offset) {
5753 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
5754 stripe_offset, offset, em->start, logical,
5756 free_extent_map(em);
5760 /* stripe_offset is the offset of this block in its stripe*/
5761 stripe_offset = offset - stripe_offset;
5763 /* if we're here for raid56, we need to know the stripe aligned start */
5764 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5765 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5766 raid56_full_stripe_start = offset;
5768 /* allow a write of a full stripe, but make sure we don't
5769 * allow straddling of stripes
5771 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5773 raid56_full_stripe_start *= full_stripe_len;
5776 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5778 /* For writes to RAID[56], allow a full stripeset across all disks.
5779 For other RAID types and for RAID[56] reads, just allow a single
5780 stripe (on a single disk). */
5781 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5782 (op == BTRFS_MAP_WRITE)) {
5783 max_len = stripe_len * nr_data_stripes(map) -
5784 (offset - raid56_full_stripe_start);
5786 /* we limit the length of each bio to what fits in a stripe */
5787 max_len = stripe_len - stripe_offset;
5789 *length = min_t(u64, em->len - offset, max_len);
5791 *length = em->len - offset;
5794 /* This is for when we're called from btrfs_merge_bio_hook() and all
5795 it cares about is the length */
5799 btrfs_dev_replace_lock(dev_replace, 0);
5800 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5801 if (!dev_replace_is_ongoing)
5802 btrfs_dev_replace_unlock(dev_replace, 0);
5804 btrfs_dev_replace_set_lock_blocking(dev_replace);
5806 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5807 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
5808 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
5809 dev_replace->srcdev->devid,
5811 &physical_to_patch_in_first_stripe);
5815 patch_the_first_stripe_for_dev_replace = 1;
5816 } else if (mirror_num > map->num_stripes) {
5822 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5823 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5825 if (!need_full_stripe(op))
5827 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5828 if (need_full_stripe(op))
5829 num_stripes = map->num_stripes;
5830 else if (mirror_num)
5831 stripe_index = mirror_num - 1;
5833 stripe_index = find_live_mirror(fs_info, map, 0,
5835 current->pid % map->num_stripes,
5836 dev_replace_is_ongoing);
5837 mirror_num = stripe_index + 1;
5840 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5841 if (need_full_stripe(op)) {
5842 num_stripes = map->num_stripes;
5843 } else if (mirror_num) {
5844 stripe_index = mirror_num - 1;
5849 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5850 u32 factor = map->num_stripes / map->sub_stripes;
5852 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5853 stripe_index *= map->sub_stripes;
5855 if (need_full_stripe(op))
5856 num_stripes = map->sub_stripes;
5857 else if (mirror_num)
5858 stripe_index += mirror_num - 1;
5860 int old_stripe_index = stripe_index;
5861 stripe_index = find_live_mirror(fs_info, map,
5863 map->sub_stripes, stripe_index +
5864 current->pid % map->sub_stripes,
5865 dev_replace_is_ongoing);
5866 mirror_num = stripe_index - old_stripe_index + 1;
5869 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5870 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
5871 /* push stripe_nr back to the start of the full stripe */
5872 stripe_nr = div64_u64(raid56_full_stripe_start,
5873 stripe_len * nr_data_stripes(map));
5875 /* RAID[56] write or recovery. Return all stripes */
5876 num_stripes = map->num_stripes;
5877 max_errors = nr_parity_stripes(map);
5879 *length = map->stripe_len;
5884 * Mirror #0 or #1 means the original data block.
5885 * Mirror #2 is RAID5 parity block.
5886 * Mirror #3 is RAID6 Q block.
5888 stripe_nr = div_u64_rem(stripe_nr,
5889 nr_data_stripes(map), &stripe_index);
5891 stripe_index = nr_data_stripes(map) +
5894 /* We distribute the parity blocks across stripes */
5895 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5897 if (!need_full_stripe(op) && mirror_num <= 1)
5902 * after this, stripe_nr is the number of stripes on this
5903 * device we have to walk to find the data, and stripe_index is
5904 * the number of our device in the stripe array
5906 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5908 mirror_num = stripe_index + 1;
5910 if (stripe_index >= map->num_stripes) {
5912 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
5913 stripe_index, map->num_stripes);
5918 num_alloc_stripes = num_stripes;
5919 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
5920 if (op == BTRFS_MAP_WRITE)
5921 num_alloc_stripes <<= 1;
5922 if (op == BTRFS_MAP_GET_READ_MIRRORS)
5923 num_alloc_stripes++;
5924 tgtdev_indexes = num_stripes;
5927 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5932 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
5933 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5935 /* build raid_map */
5936 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
5937 (need_full_stripe(op) || mirror_num > 1)) {
5941 bbio->raid_map = (u64 *)((void *)bbio->stripes +
5942 sizeof(struct btrfs_bio_stripe) *
5944 sizeof(int) * tgtdev_indexes);
5946 /* Work out the disk rotation on this stripe-set */
5947 div_u64_rem(stripe_nr, num_stripes, &rot);
5949 /* Fill in the logical address of each stripe */
5950 tmp = stripe_nr * nr_data_stripes(map);
5951 for (i = 0; i < nr_data_stripes(map); i++)
5952 bbio->raid_map[(i+rot) % num_stripes] =
5953 em->start + (tmp + i) * map->stripe_len;
5955 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5956 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5957 bbio->raid_map[(i+rot+1) % num_stripes] =
5962 for (i = 0; i < num_stripes; i++) {
5963 bbio->stripes[i].physical =
5964 map->stripes[stripe_index].physical +
5966 stripe_nr * map->stripe_len;
5967 bbio->stripes[i].dev =
5968 map->stripes[stripe_index].dev;
5972 if (need_full_stripe(op))
5973 max_errors = btrfs_chunk_max_errors(map);
5976 sort_parity_stripes(bbio, num_stripes);
5978 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
5979 need_full_stripe(op)) {
5980 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
5985 bbio->map_type = map->type;
5986 bbio->num_stripes = num_stripes;
5987 bbio->max_errors = max_errors;
5988 bbio->mirror_num = mirror_num;
5991 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5992 * mirror_num == num_stripes + 1 && dev_replace target drive is
5993 * available as a mirror
5995 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5996 WARN_ON(num_stripes > 1);
5997 bbio->stripes[0].dev = dev_replace->tgtdev;
5998 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5999 bbio->mirror_num = map->num_stripes + 1;
6002 if (dev_replace_is_ongoing) {
6003 btrfs_dev_replace_clear_lock_blocking(dev_replace);
6004 btrfs_dev_replace_unlock(dev_replace, 0);
6006 free_extent_map(em);
6010 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6011 u64 logical, u64 *length,
6012 struct btrfs_bio **bbio_ret, int mirror_num)
6014 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6018 /* For Scrub/replace */
6019 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6020 u64 logical, u64 *length,
6021 struct btrfs_bio **bbio_ret)
6023 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6026 int btrfs_rmap_block(struct btrfs_fs_info *fs_info,
6027 u64 chunk_start, u64 physical, u64 devid,
6028 u64 **logical, int *naddrs, int *stripe_len)
6030 struct extent_map *em;
6031 struct map_lookup *map;
6039 em = get_chunk_map(fs_info, chunk_start, 1);
6043 map = em->map_lookup;
6045 rmap_len = map->stripe_len;
6047 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6048 length = div_u64(length, map->num_stripes / map->sub_stripes);
6049 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6050 length = div_u64(length, map->num_stripes);
6051 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6052 length = div_u64(length, nr_data_stripes(map));
6053 rmap_len = map->stripe_len * nr_data_stripes(map);
6056 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
6057 BUG_ON(!buf); /* -ENOMEM */
6059 for (i = 0; i < map->num_stripes; i++) {
6060 if (devid && map->stripes[i].dev->devid != devid)
6062 if (map->stripes[i].physical > physical ||
6063 map->stripes[i].physical + length <= physical)
6066 stripe_nr = physical - map->stripes[i].physical;
6067 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
6069 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6070 stripe_nr = stripe_nr * map->num_stripes + i;
6071 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
6072 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6073 stripe_nr = stripe_nr * map->num_stripes + i;
6074 } /* else if RAID[56], multiply by nr_data_stripes().
6075 * Alternatively, just use rmap_len below instead of
6076 * map->stripe_len */
6078 bytenr = chunk_start + stripe_nr * rmap_len;
6079 WARN_ON(nr >= map->num_stripes);
6080 for (j = 0; j < nr; j++) {
6081 if (buf[j] == bytenr)
6085 WARN_ON(nr >= map->num_stripes);
6092 *stripe_len = rmap_len;
6094 free_extent_map(em);
6098 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6100 bio->bi_private = bbio->private;
6101 bio->bi_end_io = bbio->end_io;
6104 btrfs_put_bbio(bbio);
6107 static void btrfs_end_bio(struct bio *bio)
6109 struct btrfs_bio *bbio = bio->bi_private;
6110 int is_orig_bio = 0;
6112 if (bio->bi_status) {
6113 atomic_inc(&bbio->error);
6114 if (bio->bi_status == BLK_STS_IOERR ||
6115 bio->bi_status == BLK_STS_TARGET) {
6116 unsigned int stripe_index =
6117 btrfs_io_bio(bio)->stripe_index;
6118 struct btrfs_device *dev;
6120 BUG_ON(stripe_index >= bbio->num_stripes);
6121 dev = bbio->stripes[stripe_index].dev;
6123 if (bio_op(bio) == REQ_OP_WRITE)
6124 btrfs_dev_stat_inc_and_print(dev,
6125 BTRFS_DEV_STAT_WRITE_ERRS);
6127 btrfs_dev_stat_inc_and_print(dev,
6128 BTRFS_DEV_STAT_READ_ERRS);
6129 if (bio->bi_opf & REQ_PREFLUSH)
6130 btrfs_dev_stat_inc_and_print(dev,
6131 BTRFS_DEV_STAT_FLUSH_ERRS);
6136 if (bio == bbio->orig_bio)
6139 btrfs_bio_counter_dec(bbio->fs_info);
6141 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6144 bio = bbio->orig_bio;
6147 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6148 /* only send an error to the higher layers if it is
6149 * beyond the tolerance of the btrfs bio
6151 if (atomic_read(&bbio->error) > bbio->max_errors) {
6152 bio->bi_status = BLK_STS_IOERR;
6155 * this bio is actually up to date, we didn't
6156 * go over the max number of errors
6158 bio->bi_status = BLK_STS_OK;
6161 btrfs_end_bbio(bbio, bio);
6162 } else if (!is_orig_bio) {
6168 * see run_scheduled_bios for a description of why bios are collected for
6171 * This will add one bio to the pending list for a device and make sure
6172 * the work struct is scheduled.
6174 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6177 struct btrfs_fs_info *fs_info = device->fs_info;
6178 int should_queue = 1;
6179 struct btrfs_pending_bios *pending_bios;
6181 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state) ||
6187 /* don't bother with additional async steps for reads, right now */
6188 if (bio_op(bio) == REQ_OP_READ) {
6189 btrfsic_submit_bio(bio);
6193 WARN_ON(bio->bi_next);
6194 bio->bi_next = NULL;
6196 spin_lock(&device->io_lock);
6197 if (op_is_sync(bio->bi_opf))
6198 pending_bios = &device->pending_sync_bios;
6200 pending_bios = &device->pending_bios;
6202 if (pending_bios->tail)
6203 pending_bios->tail->bi_next = bio;
6205 pending_bios->tail = bio;
6206 if (!pending_bios->head)
6207 pending_bios->head = bio;
6208 if (device->running_pending)
6211 spin_unlock(&device->io_lock);
6214 btrfs_queue_work(fs_info->submit_workers, &device->work);
6217 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6218 u64 physical, int dev_nr, int async)
6220 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6221 struct btrfs_fs_info *fs_info = bbio->fs_info;
6223 bio->bi_private = bbio;
6224 btrfs_io_bio(bio)->stripe_index = dev_nr;
6225 bio->bi_end_io = btrfs_end_bio;
6226 bio->bi_iter.bi_sector = physical >> 9;
6229 struct rcu_string *name;
6232 name = rcu_dereference(dev->name);
6233 btrfs_debug(fs_info,
6234 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6235 bio_op(bio), bio->bi_opf,
6236 (u64)bio->bi_iter.bi_sector,
6237 (u_long)dev->bdev->bd_dev, name->str, dev->devid,
6238 bio->bi_iter.bi_size);
6242 bio_set_dev(bio, dev->bdev);
6244 btrfs_bio_counter_inc_noblocked(fs_info);
6247 btrfs_schedule_bio(dev, bio);
6249 btrfsic_submit_bio(bio);
6252 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6254 atomic_inc(&bbio->error);
6255 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6256 /* Should be the original bio. */
6257 WARN_ON(bio != bbio->orig_bio);
6259 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6260 bio->bi_iter.bi_sector = logical >> 9;
6261 if (atomic_read(&bbio->error) > bbio->max_errors)
6262 bio->bi_status = BLK_STS_IOERR;
6264 bio->bi_status = BLK_STS_OK;
6265 btrfs_end_bbio(bbio, bio);
6269 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6270 int mirror_num, int async_submit)
6272 struct btrfs_device *dev;
6273 struct bio *first_bio = bio;
6274 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6280 struct btrfs_bio *bbio = NULL;
6282 length = bio->bi_iter.bi_size;
6283 map_length = length;
6285 btrfs_bio_counter_inc_blocked(fs_info);
6286 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6287 &map_length, &bbio, mirror_num, 1);
6289 btrfs_bio_counter_dec(fs_info);
6290 return errno_to_blk_status(ret);
6293 total_devs = bbio->num_stripes;
6294 bbio->orig_bio = first_bio;
6295 bbio->private = first_bio->bi_private;
6296 bbio->end_io = first_bio->bi_end_io;
6297 bbio->fs_info = fs_info;
6298 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6300 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6301 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6302 /* In this case, map_length has been set to the length of
6303 a single stripe; not the whole write */
6304 if (bio_op(bio) == REQ_OP_WRITE) {
6305 ret = raid56_parity_write(fs_info, bio, bbio,
6308 ret = raid56_parity_recover(fs_info, bio, bbio,
6309 map_length, mirror_num, 1);
6312 btrfs_bio_counter_dec(fs_info);
6313 return errno_to_blk_status(ret);
6316 if (map_length < length) {
6318 "mapping failed logical %llu bio len %llu len %llu",
6319 logical, length, map_length);
6323 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6324 dev = bbio->stripes[dev_nr].dev;
6325 if (!dev || !dev->bdev ||
6326 (bio_op(first_bio) == REQ_OP_WRITE &&
6327 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6328 bbio_error(bbio, first_bio, logical);
6332 if (dev_nr < total_devs - 1)
6333 bio = btrfs_bio_clone(first_bio);
6337 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6338 dev_nr, async_submit);
6340 btrfs_bio_counter_dec(fs_info);
6344 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
6347 struct btrfs_device *device;
6348 struct btrfs_fs_devices *cur_devices;
6350 cur_devices = fs_info->fs_devices;
6351 while (cur_devices) {
6353 !memcmp(cur_devices->fsid, fsid, BTRFS_FSID_SIZE)) {
6354 device = find_device(cur_devices, devid, uuid);
6358 cur_devices = cur_devices->seed;
6363 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6364 u64 devid, u8 *dev_uuid)
6366 struct btrfs_device *device;
6368 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6372 list_add(&device->dev_list, &fs_devices->devices);
6373 device->fs_devices = fs_devices;
6374 fs_devices->num_devices++;
6376 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6377 fs_devices->missing_devices++;
6383 * btrfs_alloc_device - allocate struct btrfs_device
6384 * @fs_info: used only for generating a new devid, can be NULL if
6385 * devid is provided (i.e. @devid != NULL).
6386 * @devid: a pointer to devid for this device. If NULL a new devid
6388 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6391 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6392 * on error. Returned struct is not linked onto any lists and must be
6393 * destroyed with free_device.
6395 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6399 struct btrfs_device *dev;
6402 if (WARN_ON(!devid && !fs_info))
6403 return ERR_PTR(-EINVAL);
6405 dev = __alloc_device();
6414 ret = find_next_devid(fs_info, &tmp);
6417 return ERR_PTR(ret);
6423 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6425 generate_random_uuid(dev->uuid);
6427 btrfs_init_work(&dev->work, btrfs_submit_helper,
6428 pending_bios_fn, NULL, NULL);
6433 /* Return -EIO if any error, otherwise return 0. */
6434 static int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info,
6435 struct extent_buffer *leaf,
6436 struct btrfs_chunk *chunk, u64 logical)
6444 length = btrfs_chunk_length(leaf, chunk);
6445 stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6446 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6447 sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6448 type = btrfs_chunk_type(leaf, chunk);
6451 btrfs_err(fs_info, "invalid chunk num_stripes: %u",
6455 if (!IS_ALIGNED(logical, fs_info->sectorsize)) {
6456 btrfs_err(fs_info, "invalid chunk logical %llu", logical);
6459 if (btrfs_chunk_sector_size(leaf, chunk) != fs_info->sectorsize) {
6460 btrfs_err(fs_info, "invalid chunk sectorsize %u",
6461 btrfs_chunk_sector_size(leaf, chunk));
6464 if (!length || !IS_ALIGNED(length, fs_info->sectorsize)) {
6465 btrfs_err(fs_info, "invalid chunk length %llu", length);
6468 if (!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN) {
6469 btrfs_err(fs_info, "invalid chunk stripe length: %llu",
6473 if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6475 btrfs_err(fs_info, "unrecognized chunk type: %llu",
6476 ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
6477 BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6478 btrfs_chunk_type(leaf, chunk));
6481 if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes != 2) ||
6482 (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes < 1) ||
6483 (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
6484 (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
6485 (type & BTRFS_BLOCK_GROUP_DUP && num_stripes > 2) ||
6486 ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
6487 num_stripes != 1)) {
6489 "invalid num_stripes:sub_stripes %u:%u for profile %llu",
6490 num_stripes, sub_stripes,
6491 type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
6498 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6499 u64 devid, u8 *uuid, bool error)
6502 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6505 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6509 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6510 struct extent_buffer *leaf,
6511 struct btrfs_chunk *chunk)
6513 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6514 struct map_lookup *map;
6515 struct extent_map *em;
6519 u8 uuid[BTRFS_UUID_SIZE];
6524 logical = key->offset;
6525 length = btrfs_chunk_length(leaf, chunk);
6526 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6528 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6532 read_lock(&map_tree->map_tree.lock);
6533 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6534 read_unlock(&map_tree->map_tree.lock);
6536 /* already mapped? */
6537 if (em && em->start <= logical && em->start + em->len > logical) {
6538 free_extent_map(em);
6541 free_extent_map(em);
6544 em = alloc_extent_map();
6547 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6549 free_extent_map(em);
6553 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6554 em->map_lookup = map;
6555 em->start = logical;
6558 em->block_start = 0;
6559 em->block_len = em->len;
6561 map->num_stripes = num_stripes;
6562 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6563 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6564 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6565 map->type = btrfs_chunk_type(leaf, chunk);
6566 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6567 for (i = 0; i < num_stripes; i++) {
6568 map->stripes[i].physical =
6569 btrfs_stripe_offset_nr(leaf, chunk, i);
6570 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6571 read_extent_buffer(leaf, uuid, (unsigned long)
6572 btrfs_stripe_dev_uuid_nr(chunk, i),
6574 map->stripes[i].dev = btrfs_find_device(fs_info, devid,
6576 if (!map->stripes[i].dev &&
6577 !btrfs_test_opt(fs_info, DEGRADED)) {
6578 free_extent_map(em);
6579 btrfs_report_missing_device(fs_info, devid, uuid, true);
6582 if (!map->stripes[i].dev) {
6583 map->stripes[i].dev =
6584 add_missing_dev(fs_info->fs_devices, devid,
6586 if (IS_ERR(map->stripes[i].dev)) {
6587 free_extent_map(em);
6589 "failed to init missing dev %llu: %ld",
6590 devid, PTR_ERR(map->stripes[i].dev));
6591 return PTR_ERR(map->stripes[i].dev);
6593 btrfs_report_missing_device(fs_info, devid, uuid, false);
6595 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6596 &(map->stripes[i].dev->dev_state));
6600 write_lock(&map_tree->map_tree.lock);
6601 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6602 write_unlock(&map_tree->map_tree.lock);
6603 BUG_ON(ret); /* Tree corruption */
6604 free_extent_map(em);
6609 static void fill_device_from_item(struct extent_buffer *leaf,
6610 struct btrfs_dev_item *dev_item,
6611 struct btrfs_device *device)
6615 device->devid = btrfs_device_id(leaf, dev_item);
6616 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6617 device->total_bytes = device->disk_total_bytes;
6618 device->commit_total_bytes = device->disk_total_bytes;
6619 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6620 device->commit_bytes_used = device->bytes_used;
6621 device->type = btrfs_device_type(leaf, dev_item);
6622 device->io_align = btrfs_device_io_align(leaf, dev_item);
6623 device->io_width = btrfs_device_io_width(leaf, dev_item);
6624 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6625 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6626 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6628 ptr = btrfs_device_uuid(dev_item);
6629 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6632 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6635 struct btrfs_fs_devices *fs_devices;
6638 BUG_ON(!mutex_is_locked(&uuid_mutex));
6641 fs_devices = fs_info->fs_devices->seed;
6642 while (fs_devices) {
6643 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6646 fs_devices = fs_devices->seed;
6649 fs_devices = find_fsid(fsid);
6651 if (!btrfs_test_opt(fs_info, DEGRADED))
6652 return ERR_PTR(-ENOENT);
6654 fs_devices = alloc_fs_devices(fsid);
6655 if (IS_ERR(fs_devices))
6658 fs_devices->seeding = 1;
6659 fs_devices->opened = 1;
6663 fs_devices = clone_fs_devices(fs_devices);
6664 if (IS_ERR(fs_devices))
6667 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
6668 fs_info->bdev_holder);
6670 free_fs_devices(fs_devices);
6671 fs_devices = ERR_PTR(ret);
6675 if (!fs_devices->seeding) {
6676 __btrfs_close_devices(fs_devices);
6677 free_fs_devices(fs_devices);
6678 fs_devices = ERR_PTR(-EINVAL);
6682 fs_devices->seed = fs_info->fs_devices->seed;
6683 fs_info->fs_devices->seed = fs_devices;
6688 static int read_one_dev(struct btrfs_fs_info *fs_info,
6689 struct extent_buffer *leaf,
6690 struct btrfs_dev_item *dev_item)
6692 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6693 struct btrfs_device *device;
6696 u8 fs_uuid[BTRFS_FSID_SIZE];
6697 u8 dev_uuid[BTRFS_UUID_SIZE];
6699 devid = btrfs_device_id(leaf, dev_item);
6700 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6702 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6705 if (memcmp(fs_uuid, fs_info->fsid, BTRFS_FSID_SIZE)) {
6706 fs_devices = open_seed_devices(fs_info, fs_uuid);
6707 if (IS_ERR(fs_devices))
6708 return PTR_ERR(fs_devices);
6711 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
6713 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6714 btrfs_report_missing_device(fs_info, devid,
6719 device = add_missing_dev(fs_devices, devid, dev_uuid);
6720 if (IS_ERR(device)) {
6722 "failed to add missing dev %llu: %ld",
6723 devid, PTR_ERR(device));
6724 return PTR_ERR(device);
6726 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6728 if (!device->bdev) {
6729 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6730 btrfs_report_missing_device(fs_info,
6731 devid, dev_uuid, true);
6734 btrfs_report_missing_device(fs_info, devid,
6738 if (!device->bdev &&
6739 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6741 * this happens when a device that was properly setup
6742 * in the device info lists suddenly goes bad.
6743 * device->bdev is NULL, and so we have to set
6744 * device->missing to one here
6746 device->fs_devices->missing_devices++;
6747 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6750 /* Move the device to its own fs_devices */
6751 if (device->fs_devices != fs_devices) {
6752 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6753 &device->dev_state));
6755 list_move(&device->dev_list, &fs_devices->devices);
6756 device->fs_devices->num_devices--;
6757 fs_devices->num_devices++;
6759 device->fs_devices->missing_devices--;
6760 fs_devices->missing_devices++;
6762 device->fs_devices = fs_devices;
6766 if (device->fs_devices != fs_info->fs_devices) {
6767 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6768 if (device->generation !=
6769 btrfs_device_generation(leaf, dev_item))
6773 fill_device_from_item(leaf, dev_item, device);
6774 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6775 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6776 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6777 device->fs_devices->total_rw_bytes += device->total_bytes;
6778 atomic64_add(device->total_bytes - device->bytes_used,
6779 &fs_info->free_chunk_space);
6785 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6787 struct btrfs_root *root = fs_info->tree_root;
6788 struct btrfs_super_block *super_copy = fs_info->super_copy;
6789 struct extent_buffer *sb;
6790 struct btrfs_disk_key *disk_key;
6791 struct btrfs_chunk *chunk;
6793 unsigned long sb_array_offset;
6800 struct btrfs_key key;
6802 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6804 * This will create extent buffer of nodesize, superblock size is
6805 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6806 * overallocate but we can keep it as-is, only the first page is used.
6808 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6811 set_extent_buffer_uptodate(sb);
6812 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6814 * The sb extent buffer is artificial and just used to read the system array.
6815 * set_extent_buffer_uptodate() call does not properly mark all it's
6816 * pages up-to-date when the page is larger: extent does not cover the
6817 * whole page and consequently check_page_uptodate does not find all
6818 * the page's extents up-to-date (the hole beyond sb),
6819 * write_extent_buffer then triggers a WARN_ON.
6821 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6822 * but sb spans only this function. Add an explicit SetPageUptodate call
6823 * to silence the warning eg. on PowerPC 64.
6825 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6826 SetPageUptodate(sb->pages[0]);
6828 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6829 array_size = btrfs_super_sys_array_size(super_copy);
6831 array_ptr = super_copy->sys_chunk_array;
6832 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6835 while (cur_offset < array_size) {
6836 disk_key = (struct btrfs_disk_key *)array_ptr;
6837 len = sizeof(*disk_key);
6838 if (cur_offset + len > array_size)
6839 goto out_short_read;
6841 btrfs_disk_key_to_cpu(&key, disk_key);
6844 sb_array_offset += len;
6847 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6848 chunk = (struct btrfs_chunk *)sb_array_offset;
6850 * At least one btrfs_chunk with one stripe must be
6851 * present, exact stripe count check comes afterwards
6853 len = btrfs_chunk_item_size(1);
6854 if (cur_offset + len > array_size)
6855 goto out_short_read;
6857 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6860 "invalid number of stripes %u in sys_array at offset %u",
6861 num_stripes, cur_offset);
6866 type = btrfs_chunk_type(sb, chunk);
6867 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6869 "invalid chunk type %llu in sys_array at offset %u",
6875 len = btrfs_chunk_item_size(num_stripes);
6876 if (cur_offset + len > array_size)
6877 goto out_short_read;
6879 ret = read_one_chunk(fs_info, &key, sb, chunk);
6884 "unexpected item type %u in sys_array at offset %u",
6885 (u32)key.type, cur_offset);
6890 sb_array_offset += len;
6893 clear_extent_buffer_uptodate(sb);
6894 free_extent_buffer_stale(sb);
6898 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6900 clear_extent_buffer_uptodate(sb);
6901 free_extent_buffer_stale(sb);
6906 * Check if all chunks in the fs are OK for read-write degraded mount
6908 * If the @failing_dev is specified, it's accounted as missing.
6910 * Return true if all chunks meet the minimal RW mount requirements.
6911 * Return false if any chunk doesn't meet the minimal RW mount requirements.
6913 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
6914 struct btrfs_device *failing_dev)
6916 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6917 struct extent_map *em;
6921 read_lock(&map_tree->map_tree.lock);
6922 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
6923 read_unlock(&map_tree->map_tree.lock);
6924 /* No chunk at all? Return false anyway */
6930 struct map_lookup *map;
6935 map = em->map_lookup;
6937 btrfs_get_num_tolerated_disk_barrier_failures(
6939 for (i = 0; i < map->num_stripes; i++) {
6940 struct btrfs_device *dev = map->stripes[i].dev;
6942 if (!dev || !dev->bdev ||
6943 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
6944 dev->last_flush_error)
6946 else if (failing_dev && failing_dev == dev)
6949 if (missing > max_tolerated) {
6952 "chunk %llu missing %d devices, max tolerance is %d for writeable mount",
6953 em->start, missing, max_tolerated);
6954 free_extent_map(em);
6958 next_start = extent_map_end(em);
6959 free_extent_map(em);
6961 read_lock(&map_tree->map_tree.lock);
6962 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
6963 (u64)(-1) - next_start);
6964 read_unlock(&map_tree->map_tree.lock);
6970 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
6972 struct btrfs_root *root = fs_info->chunk_root;
6973 struct btrfs_path *path;
6974 struct extent_buffer *leaf;
6975 struct btrfs_key key;
6976 struct btrfs_key found_key;
6981 path = btrfs_alloc_path();
6985 mutex_lock(&uuid_mutex);
6986 mutex_lock(&fs_info->chunk_mutex);
6989 * Read all device items, and then all the chunk items. All
6990 * device items are found before any chunk item (their object id
6991 * is smaller than the lowest possible object id for a chunk
6992 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6994 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6997 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7001 leaf = path->nodes[0];
7002 slot = path->slots[0];
7003 if (slot >= btrfs_header_nritems(leaf)) {
7004 ret = btrfs_next_leaf(root, path);
7011 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7012 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7013 struct btrfs_dev_item *dev_item;
7014 dev_item = btrfs_item_ptr(leaf, slot,
7015 struct btrfs_dev_item);
7016 ret = read_one_dev(fs_info, leaf, dev_item);
7020 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7021 struct btrfs_chunk *chunk;
7022 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7023 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
7031 * After loading chunk tree, we've got all device information,
7032 * do another round of validation checks.
7034 if (total_dev != fs_info->fs_devices->total_devices) {
7036 "super_num_devices %llu mismatch with num_devices %llu found here",
7037 btrfs_super_num_devices(fs_info->super_copy),
7042 if (btrfs_super_total_bytes(fs_info->super_copy) <
7043 fs_info->fs_devices->total_rw_bytes) {
7045 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7046 btrfs_super_total_bytes(fs_info->super_copy),
7047 fs_info->fs_devices->total_rw_bytes);
7053 mutex_unlock(&fs_info->chunk_mutex);
7054 mutex_unlock(&uuid_mutex);
7056 btrfs_free_path(path);
7060 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7062 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7063 struct btrfs_device *device;
7065 while (fs_devices) {
7066 mutex_lock(&fs_devices->device_list_mutex);
7067 list_for_each_entry(device, &fs_devices->devices, dev_list)
7068 device->fs_info = fs_info;
7069 mutex_unlock(&fs_devices->device_list_mutex);
7071 fs_devices = fs_devices->seed;
7075 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
7079 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7080 btrfs_dev_stat_reset(dev, i);
7083 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7085 struct btrfs_key key;
7086 struct btrfs_key found_key;
7087 struct btrfs_root *dev_root = fs_info->dev_root;
7088 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7089 struct extent_buffer *eb;
7092 struct btrfs_device *device;
7093 struct btrfs_path *path = NULL;
7096 path = btrfs_alloc_path();
7102 mutex_lock(&fs_devices->device_list_mutex);
7103 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7105 struct btrfs_dev_stats_item *ptr;
7107 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7108 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7109 key.offset = device->devid;
7110 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7112 __btrfs_reset_dev_stats(device);
7113 device->dev_stats_valid = 1;
7114 btrfs_release_path(path);
7117 slot = path->slots[0];
7118 eb = path->nodes[0];
7119 btrfs_item_key_to_cpu(eb, &found_key, slot);
7120 item_size = btrfs_item_size_nr(eb, slot);
7122 ptr = btrfs_item_ptr(eb, slot,
7123 struct btrfs_dev_stats_item);
7125 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7126 if (item_size >= (1 + i) * sizeof(__le64))
7127 btrfs_dev_stat_set(device, i,
7128 btrfs_dev_stats_value(eb, ptr, i));
7130 btrfs_dev_stat_reset(device, i);
7133 device->dev_stats_valid = 1;
7134 btrfs_dev_stat_print_on_load(device);
7135 btrfs_release_path(path);
7137 mutex_unlock(&fs_devices->device_list_mutex);
7140 btrfs_free_path(path);
7141 return ret < 0 ? ret : 0;
7144 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7145 struct btrfs_fs_info *fs_info,
7146 struct btrfs_device *device)
7148 struct btrfs_root *dev_root = fs_info->dev_root;
7149 struct btrfs_path *path;
7150 struct btrfs_key key;
7151 struct extent_buffer *eb;
7152 struct btrfs_dev_stats_item *ptr;
7156 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7157 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7158 key.offset = device->devid;
7160 path = btrfs_alloc_path();
7163 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7165 btrfs_warn_in_rcu(fs_info,
7166 "error %d while searching for dev_stats item for device %s",
7167 ret, rcu_str_deref(device->name));
7172 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7173 /* need to delete old one and insert a new one */
7174 ret = btrfs_del_item(trans, dev_root, path);
7176 btrfs_warn_in_rcu(fs_info,
7177 "delete too small dev_stats item for device %s failed %d",
7178 rcu_str_deref(device->name), ret);
7185 /* need to insert a new item */
7186 btrfs_release_path(path);
7187 ret = btrfs_insert_empty_item(trans, dev_root, path,
7188 &key, sizeof(*ptr));
7190 btrfs_warn_in_rcu(fs_info,
7191 "insert dev_stats item for device %s failed %d",
7192 rcu_str_deref(device->name), ret);
7197 eb = path->nodes[0];
7198 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7199 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7200 btrfs_set_dev_stats_value(eb, ptr, i,
7201 btrfs_dev_stat_read(device, i));
7202 btrfs_mark_buffer_dirty(eb);
7205 btrfs_free_path(path);
7210 * called from commit_transaction. Writes all changed device stats to disk.
7212 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7213 struct btrfs_fs_info *fs_info)
7215 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7216 struct btrfs_device *device;
7220 mutex_lock(&fs_devices->device_list_mutex);
7221 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7222 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7223 if (!device->dev_stats_valid || stats_cnt == 0)
7228 * There is a LOAD-LOAD control dependency between the value of
7229 * dev_stats_ccnt and updating the on-disk values which requires
7230 * reading the in-memory counters. Such control dependencies
7231 * require explicit read memory barriers.
7233 * This memory barriers pairs with smp_mb__before_atomic in
7234 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7235 * barrier implied by atomic_xchg in
7236 * btrfs_dev_stats_read_and_reset
7240 ret = update_dev_stat_item(trans, fs_info, device);
7242 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7244 mutex_unlock(&fs_devices->device_list_mutex);
7249 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7251 btrfs_dev_stat_inc(dev, index);
7252 btrfs_dev_stat_print_on_error(dev);
7255 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7257 if (!dev->dev_stats_valid)
7259 btrfs_err_rl_in_rcu(dev->fs_info,
7260 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7261 rcu_str_deref(dev->name),
7262 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7263 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7264 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7265 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7266 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7269 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7273 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7274 if (btrfs_dev_stat_read(dev, i) != 0)
7276 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7277 return; /* all values == 0, suppress message */
7279 btrfs_info_in_rcu(dev->fs_info,
7280 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7281 rcu_str_deref(dev->name),
7282 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7283 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7284 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7285 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7286 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7289 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7290 struct btrfs_ioctl_get_dev_stats *stats)
7292 struct btrfs_device *dev;
7293 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7296 mutex_lock(&fs_devices->device_list_mutex);
7297 dev = btrfs_find_device(fs_info, stats->devid, NULL, NULL);
7298 mutex_unlock(&fs_devices->device_list_mutex);
7301 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7303 } else if (!dev->dev_stats_valid) {
7304 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7306 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7307 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7308 if (stats->nr_items > i)
7310 btrfs_dev_stat_read_and_reset(dev, i);
7312 btrfs_dev_stat_reset(dev, i);
7315 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7316 if (stats->nr_items > i)
7317 stats->values[i] = btrfs_dev_stat_read(dev, i);
7319 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7320 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7324 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7326 struct buffer_head *bh;
7327 struct btrfs_super_block *disk_super;
7333 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7336 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7339 disk_super = (struct btrfs_super_block *)bh->b_data;
7341 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7342 set_buffer_dirty(bh);
7343 sync_dirty_buffer(bh);
7347 /* Notify udev that device has changed */
7348 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7350 /* Update ctime/mtime for device path for libblkid */
7351 update_dev_time(device_path);
7355 * Update the size of all devices, which is used for writing out the
7358 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7360 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7361 struct btrfs_device *curr, *next;
7363 if (list_empty(&fs_devices->resized_devices))
7366 mutex_lock(&fs_devices->device_list_mutex);
7367 mutex_lock(&fs_info->chunk_mutex);
7368 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7370 list_del_init(&curr->resized_list);
7371 curr->commit_total_bytes = curr->disk_total_bytes;
7373 mutex_unlock(&fs_info->chunk_mutex);
7374 mutex_unlock(&fs_devices->device_list_mutex);
7377 /* Must be invoked during the transaction commit */
7378 void btrfs_update_commit_device_bytes_used(struct btrfs_transaction *trans)
7380 struct btrfs_fs_info *fs_info = trans->fs_info;
7381 struct extent_map *em;
7382 struct map_lookup *map;
7383 struct btrfs_device *dev;
7386 if (list_empty(&trans->pending_chunks))
7389 /* In order to kick the device replace finish process */
7390 mutex_lock(&fs_info->chunk_mutex);
7391 list_for_each_entry(em, &trans->pending_chunks, list) {
7392 map = em->map_lookup;
7394 for (i = 0; i < map->num_stripes; i++) {
7395 dev = map->stripes[i].dev;
7396 dev->commit_bytes_used = dev->bytes_used;
7399 mutex_unlock(&fs_info->chunk_mutex);
7402 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7404 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7405 while (fs_devices) {
7406 fs_devices->fs_info = fs_info;
7407 fs_devices = fs_devices->seed;
7411 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7413 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7414 while (fs_devices) {
7415 fs_devices->fs_info = NULL;
7416 fs_devices = fs_devices->seed;