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/random.h>
24 #include <linux/iocontext.h>
25 #include <linux/capability.h>
26 #include <linux/ratelimit.h>
27 #include <linux/kthread.h>
28 #include <linux/raid/pq.h>
29 #include <linux/semaphore.h>
30 #include <asm/div64.h>
32 #include "extent_map.h"
34 #include "transaction.h"
35 #include "print-tree.h"
38 #include "async-thread.h"
39 #include "check-integrity.h"
40 #include "rcu-string.h"
42 #include "dev-replace.h"
45 static int init_first_rw_device(struct btrfs_trans_handle *trans,
46 struct btrfs_root *root,
47 struct btrfs_device *device);
48 static int btrfs_relocate_sys_chunks(struct btrfs_root *root);
49 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
50 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
51 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
53 DEFINE_MUTEX(uuid_mutex);
54 static LIST_HEAD(fs_uuids);
55 struct list_head *btrfs_get_fs_uuids(void)
60 static struct btrfs_fs_devices *__alloc_fs_devices(void)
62 struct btrfs_fs_devices *fs_devs;
64 fs_devs = kzalloc(sizeof(*fs_devs), GFP_NOFS);
66 return ERR_PTR(-ENOMEM);
68 mutex_init(&fs_devs->device_list_mutex);
70 INIT_LIST_HEAD(&fs_devs->devices);
71 INIT_LIST_HEAD(&fs_devs->resized_devices);
72 INIT_LIST_HEAD(&fs_devs->alloc_list);
73 INIT_LIST_HEAD(&fs_devs->list);
79 * alloc_fs_devices - allocate struct btrfs_fs_devices
80 * @fsid: a pointer to UUID for this FS. If NULL a new UUID is
83 * Return: a pointer to a new &struct btrfs_fs_devices on success;
84 * ERR_PTR() on error. Returned struct is not linked onto any lists and
85 * can be destroyed with kfree() right away.
87 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
89 struct btrfs_fs_devices *fs_devs;
91 fs_devs = __alloc_fs_devices();
96 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
98 generate_random_uuid(fs_devs->fsid);
103 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
105 struct btrfs_device *device;
106 WARN_ON(fs_devices->opened);
107 while (!list_empty(&fs_devices->devices)) {
108 device = list_entry(fs_devices->devices.next,
109 struct btrfs_device, dev_list);
110 list_del(&device->dev_list);
111 rcu_string_free(device->name);
117 static void btrfs_kobject_uevent(struct block_device *bdev,
118 enum kobject_action action)
122 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
124 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
126 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
127 &disk_to_dev(bdev->bd_disk)->kobj);
130 void btrfs_cleanup_fs_uuids(void)
132 struct btrfs_fs_devices *fs_devices;
134 while (!list_empty(&fs_uuids)) {
135 fs_devices = list_entry(fs_uuids.next,
136 struct btrfs_fs_devices, list);
137 list_del(&fs_devices->list);
138 free_fs_devices(fs_devices);
142 static struct btrfs_device *__alloc_device(void)
144 struct btrfs_device *dev;
146 dev = kzalloc(sizeof(*dev), GFP_NOFS);
148 return ERR_PTR(-ENOMEM);
150 INIT_LIST_HEAD(&dev->dev_list);
151 INIT_LIST_HEAD(&dev->dev_alloc_list);
152 INIT_LIST_HEAD(&dev->resized_list);
154 spin_lock_init(&dev->io_lock);
156 spin_lock_init(&dev->reada_lock);
157 atomic_set(&dev->reada_in_flight, 0);
158 atomic_set(&dev->dev_stats_ccnt, 0);
159 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_WAIT);
160 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_WAIT);
165 static noinline struct btrfs_device *__find_device(struct list_head *head,
168 struct btrfs_device *dev;
170 list_for_each_entry(dev, head, dev_list) {
171 if (dev->devid == devid &&
172 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
179 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
181 struct btrfs_fs_devices *fs_devices;
183 list_for_each_entry(fs_devices, &fs_uuids, list) {
184 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
191 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
192 int flush, struct block_device **bdev,
193 struct buffer_head **bh)
197 *bdev = blkdev_get_by_path(device_path, flags, holder);
200 ret = PTR_ERR(*bdev);
205 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
206 ret = set_blocksize(*bdev, 4096);
208 blkdev_put(*bdev, flags);
211 invalidate_bdev(*bdev);
212 *bh = btrfs_read_dev_super(*bdev);
215 blkdev_put(*bdev, flags);
227 static void requeue_list(struct btrfs_pending_bios *pending_bios,
228 struct bio *head, struct bio *tail)
231 struct bio *old_head;
233 old_head = pending_bios->head;
234 pending_bios->head = head;
235 if (pending_bios->tail)
236 tail->bi_next = old_head;
238 pending_bios->tail = tail;
242 * we try to collect pending bios for a device so we don't get a large
243 * number of procs sending bios down to the same device. This greatly
244 * improves the schedulers ability to collect and merge the bios.
246 * But, it also turns into a long list of bios to process and that is sure
247 * to eventually make the worker thread block. The solution here is to
248 * make some progress and then put this work struct back at the end of
249 * the list if the block device is congested. This way, multiple devices
250 * can make progress from a single worker thread.
252 static noinline void run_scheduled_bios(struct btrfs_device *device)
255 struct backing_dev_info *bdi;
256 struct btrfs_fs_info *fs_info;
257 struct btrfs_pending_bios *pending_bios;
261 unsigned long num_run;
262 unsigned long batch_run = 0;
264 unsigned long last_waited = 0;
266 int sync_pending = 0;
267 struct blk_plug plug;
270 * this function runs all the bios we've collected for
271 * a particular device. We don't want to wander off to
272 * another device without first sending all of these down.
273 * So, setup a plug here and finish it off before we return
275 blk_start_plug(&plug);
277 bdi = blk_get_backing_dev_info(device->bdev);
278 fs_info = device->dev_root->fs_info;
279 limit = btrfs_async_submit_limit(fs_info);
280 limit = limit * 2 / 3;
283 spin_lock(&device->io_lock);
288 /* take all the bios off the list at once and process them
289 * later on (without the lock held). But, remember the
290 * tail and other pointers so the bios can be properly reinserted
291 * into the list if we hit congestion
293 if (!force_reg && device->pending_sync_bios.head) {
294 pending_bios = &device->pending_sync_bios;
297 pending_bios = &device->pending_bios;
301 pending = pending_bios->head;
302 tail = pending_bios->tail;
303 WARN_ON(pending && !tail);
306 * if pending was null this time around, no bios need processing
307 * at all and we can stop. Otherwise it'll loop back up again
308 * and do an additional check so no bios are missed.
310 * device->running_pending is used to synchronize with the
313 if (device->pending_sync_bios.head == NULL &&
314 device->pending_bios.head == NULL) {
316 device->running_pending = 0;
319 device->running_pending = 1;
322 pending_bios->head = NULL;
323 pending_bios->tail = NULL;
325 spin_unlock(&device->io_lock);
330 /* we want to work on both lists, but do more bios on the
331 * sync list than the regular list
334 pending_bios != &device->pending_sync_bios &&
335 device->pending_sync_bios.head) ||
336 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
337 device->pending_bios.head)) {
338 spin_lock(&device->io_lock);
339 requeue_list(pending_bios, pending, tail);
344 pending = pending->bi_next;
347 if (atomic_dec_return(&fs_info->nr_async_bios) < limit &&
348 waitqueue_active(&fs_info->async_submit_wait))
349 wake_up(&fs_info->async_submit_wait);
351 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
354 * if we're doing the sync list, record that our
355 * plug has some sync requests on it
357 * If we're doing the regular list and there are
358 * sync requests sitting around, unplug before
361 if (pending_bios == &device->pending_sync_bios) {
363 } else if (sync_pending) {
364 blk_finish_plug(&plug);
365 blk_start_plug(&plug);
369 btrfsic_submit_bio(cur->bi_rw, cur);
376 * we made progress, there is more work to do and the bdi
377 * is now congested. Back off and let other work structs
380 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
381 fs_info->fs_devices->open_devices > 1) {
382 struct io_context *ioc;
384 ioc = current->io_context;
387 * the main goal here is that we don't want to
388 * block if we're going to be able to submit
389 * more requests without blocking.
391 * This code does two great things, it pokes into
392 * the elevator code from a filesystem _and_
393 * it makes assumptions about how batching works.
395 if (ioc && ioc->nr_batch_requests > 0 &&
396 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
398 ioc->last_waited == last_waited)) {
400 * we want to go through our batch of
401 * requests and stop. So, we copy out
402 * the ioc->last_waited time and test
403 * against it before looping
405 last_waited = ioc->last_waited;
409 spin_lock(&device->io_lock);
410 requeue_list(pending_bios, pending, tail);
411 device->running_pending = 1;
413 spin_unlock(&device->io_lock);
414 btrfs_queue_work(fs_info->submit_workers,
418 /* unplug every 64 requests just for good measure */
419 if (batch_run % 64 == 0) {
420 blk_finish_plug(&plug);
421 blk_start_plug(&plug);
430 spin_lock(&device->io_lock);
431 if (device->pending_bios.head || device->pending_sync_bios.head)
433 spin_unlock(&device->io_lock);
436 blk_finish_plug(&plug);
439 static void pending_bios_fn(struct btrfs_work *work)
441 struct btrfs_device *device;
443 device = container_of(work, struct btrfs_device, work);
444 run_scheduled_bios(device);
448 void btrfs_free_stale_device(struct btrfs_device *cur_dev)
450 struct btrfs_fs_devices *fs_devs;
451 struct btrfs_device *dev;
456 list_for_each_entry(fs_devs, &fs_uuids, list) {
461 if (fs_devs->seeding)
464 list_for_each_entry(dev, &fs_devs->devices, dev_list) {
472 * Todo: This won't be enough. What if the same device
473 * comes back (with new uuid and) with its mapper path?
474 * But for now, this does help as mostly an admin will
475 * either use mapper or non mapper path throughout.
478 del = strcmp(rcu_str_deref(dev->name),
479 rcu_str_deref(cur_dev->name));
486 /* delete the stale device */
487 if (fs_devs->num_devices == 1) {
488 btrfs_sysfs_remove_fsid(fs_devs);
489 list_del(&fs_devs->list);
490 free_fs_devices(fs_devs);
492 fs_devs->num_devices--;
493 list_del(&dev->dev_list);
494 rcu_string_free(dev->name);
503 * Add new device to list of registered devices
506 * 1 - first time device is seen
507 * 0 - device already known
510 static noinline int device_list_add(const char *path,
511 struct btrfs_super_block *disk_super,
512 u64 devid, struct btrfs_fs_devices **fs_devices_ret)
514 struct btrfs_device *device;
515 struct btrfs_fs_devices *fs_devices;
516 struct rcu_string *name;
518 u64 found_transid = btrfs_super_generation(disk_super);
520 fs_devices = find_fsid(disk_super->fsid);
522 fs_devices = alloc_fs_devices(disk_super->fsid);
523 if (IS_ERR(fs_devices))
524 return PTR_ERR(fs_devices);
526 list_add(&fs_devices->list, &fs_uuids);
530 device = __find_device(&fs_devices->devices, devid,
531 disk_super->dev_item.uuid);
535 if (fs_devices->opened)
538 device = btrfs_alloc_device(NULL, &devid,
539 disk_super->dev_item.uuid);
540 if (IS_ERR(device)) {
541 /* we can safely leave the fs_devices entry around */
542 return PTR_ERR(device);
545 name = rcu_string_strdup(path, GFP_NOFS);
550 rcu_assign_pointer(device->name, name);
552 mutex_lock(&fs_devices->device_list_mutex);
553 list_add_rcu(&device->dev_list, &fs_devices->devices);
554 fs_devices->num_devices++;
555 mutex_unlock(&fs_devices->device_list_mutex);
558 device->fs_devices = fs_devices;
559 } else if (!device->name || strcmp(device->name->str, path)) {
561 * When FS is already mounted.
562 * 1. If you are here and if the device->name is NULL that
563 * means this device was missing at time of FS mount.
564 * 2. If you are here and if the device->name is different
565 * from 'path' that means either
566 * a. The same device disappeared and reappeared with
568 * b. The missing-disk-which-was-replaced, has
571 * We must allow 1 and 2a above. But 2b would be a spurious
574 * Further in case of 1 and 2a above, the disk at 'path'
575 * would have missed some transaction when it was away and
576 * in case of 2a the stale bdev has to be updated as well.
577 * 2b must not be allowed at all time.
581 * For now, we do allow update to btrfs_fs_device through the
582 * btrfs dev scan cli after FS has been mounted. We're still
583 * tracking a problem where systems fail mount by subvolume id
584 * when we reject replacement on a mounted FS.
586 if (!fs_devices->opened && found_transid < device->generation) {
588 * That is if the FS is _not_ mounted and if you
589 * are here, that means there is more than one
590 * disk with same uuid and devid.We keep the one
591 * with larger generation number or the last-in if
592 * generation are equal.
597 name = rcu_string_strdup(path, GFP_NOFS);
600 rcu_string_free(device->name);
601 rcu_assign_pointer(device->name, name);
602 if (device->missing) {
603 fs_devices->missing_devices--;
609 * Unmount does not free the btrfs_device struct but would zero
610 * generation along with most of the other members. So just update
611 * it back. We need it to pick the disk with largest generation
614 if (!fs_devices->opened)
615 device->generation = found_transid;
618 * if there is new btrfs on an already registered device,
619 * then remove the stale device entry.
621 btrfs_free_stale_device(device);
623 *fs_devices_ret = fs_devices;
628 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
630 struct btrfs_fs_devices *fs_devices;
631 struct btrfs_device *device;
632 struct btrfs_device *orig_dev;
634 fs_devices = alloc_fs_devices(orig->fsid);
635 if (IS_ERR(fs_devices))
638 mutex_lock(&orig->device_list_mutex);
639 fs_devices->total_devices = orig->total_devices;
641 /* We have held the volume lock, it is safe to get the devices. */
642 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
643 struct rcu_string *name;
645 device = btrfs_alloc_device(NULL, &orig_dev->devid,
651 * This is ok to do without rcu read locked because we hold the
652 * uuid mutex so nothing we touch in here is going to disappear.
654 if (orig_dev->name) {
655 name = rcu_string_strdup(orig_dev->name->str, GFP_NOFS);
660 rcu_assign_pointer(device->name, name);
663 list_add(&device->dev_list, &fs_devices->devices);
664 device->fs_devices = fs_devices;
665 fs_devices->num_devices++;
667 mutex_unlock(&orig->device_list_mutex);
670 mutex_unlock(&orig->device_list_mutex);
671 free_fs_devices(fs_devices);
672 return ERR_PTR(-ENOMEM);
675 void btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices, int step)
677 struct btrfs_device *device, *next;
678 struct btrfs_device *latest_dev = NULL;
680 mutex_lock(&uuid_mutex);
682 /* This is the initialized path, it is safe to release the devices. */
683 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
684 if (device->in_fs_metadata) {
685 if (!device->is_tgtdev_for_dev_replace &&
687 device->generation > latest_dev->generation)) {
693 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
695 * In the first step, keep the device which has
696 * the correct fsid and the devid that is used
697 * for the dev_replace procedure.
698 * In the second step, the dev_replace state is
699 * read from the device tree and it is known
700 * whether the procedure is really active or
701 * not, which means whether this device is
702 * used or whether it should be removed.
704 if (step == 0 || device->is_tgtdev_for_dev_replace) {
709 blkdev_put(device->bdev, device->mode);
711 fs_devices->open_devices--;
713 if (device->writeable) {
714 list_del_init(&device->dev_alloc_list);
715 device->writeable = 0;
716 if (!device->is_tgtdev_for_dev_replace)
717 fs_devices->rw_devices--;
719 list_del_init(&device->dev_list);
720 fs_devices->num_devices--;
721 rcu_string_free(device->name);
725 if (fs_devices->seed) {
726 fs_devices = fs_devices->seed;
730 fs_devices->latest_bdev = latest_dev->bdev;
732 mutex_unlock(&uuid_mutex);
735 static void __free_device(struct work_struct *work)
737 struct btrfs_device *device;
739 device = container_of(work, struct btrfs_device, rcu_work);
742 blkdev_put(device->bdev, device->mode);
744 rcu_string_free(device->name);
748 static void free_device(struct rcu_head *head)
750 struct btrfs_device *device;
752 device = container_of(head, struct btrfs_device, rcu);
754 INIT_WORK(&device->rcu_work, __free_device);
755 schedule_work(&device->rcu_work);
758 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
760 struct btrfs_device *device, *tmp;
762 if (--fs_devices->opened > 0)
765 mutex_lock(&fs_devices->device_list_mutex);
766 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
767 btrfs_close_one_device(device);
769 mutex_unlock(&fs_devices->device_list_mutex);
771 WARN_ON(fs_devices->open_devices);
772 WARN_ON(fs_devices->rw_devices);
773 fs_devices->opened = 0;
774 fs_devices->seeding = 0;
779 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
781 struct btrfs_fs_devices *seed_devices = NULL;
784 mutex_lock(&uuid_mutex);
785 ret = __btrfs_close_devices(fs_devices);
786 if (!fs_devices->opened) {
787 seed_devices = fs_devices->seed;
788 fs_devices->seed = NULL;
790 mutex_unlock(&uuid_mutex);
792 while (seed_devices) {
793 fs_devices = seed_devices;
794 seed_devices = fs_devices->seed;
795 __btrfs_close_devices(fs_devices);
796 free_fs_devices(fs_devices);
799 * Wait for rcu kworkers under __btrfs_close_devices
800 * to finish all blkdev_puts so device is really
801 * free when umount is done.
807 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
808 fmode_t flags, void *holder)
810 struct request_queue *q;
811 struct block_device *bdev;
812 struct list_head *head = &fs_devices->devices;
813 struct btrfs_device *device;
814 struct btrfs_device *latest_dev = NULL;
815 struct buffer_head *bh;
816 struct btrfs_super_block *disk_super;
823 list_for_each_entry(device, head, dev_list) {
829 /* Just open everything we can; ignore failures here */
830 if (btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
834 disk_super = (struct btrfs_super_block *)bh->b_data;
835 devid = btrfs_stack_device_id(&disk_super->dev_item);
836 if (devid != device->devid)
839 if (memcmp(device->uuid, disk_super->dev_item.uuid,
843 device->generation = btrfs_super_generation(disk_super);
845 device->generation > latest_dev->generation)
848 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
849 device->writeable = 0;
851 device->writeable = !bdev_read_only(bdev);
855 q = bdev_get_queue(bdev);
856 if (blk_queue_discard(q))
857 device->can_discard = 1;
860 device->in_fs_metadata = 0;
861 device->mode = flags;
863 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
864 fs_devices->rotating = 1;
866 fs_devices->open_devices++;
867 if (device->writeable &&
868 device->devid != BTRFS_DEV_REPLACE_DEVID) {
869 fs_devices->rw_devices++;
870 list_add(&device->dev_alloc_list,
871 &fs_devices->alloc_list);
878 blkdev_put(bdev, flags);
881 if (fs_devices->open_devices == 0) {
885 fs_devices->seeding = seeding;
886 fs_devices->opened = 1;
887 fs_devices->latest_bdev = latest_dev->bdev;
888 fs_devices->total_rw_bytes = 0;
893 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
894 fmode_t flags, void *holder)
898 mutex_lock(&uuid_mutex);
899 if (fs_devices->opened) {
900 fs_devices->opened++;
903 ret = __btrfs_open_devices(fs_devices, flags, holder);
905 mutex_unlock(&uuid_mutex);
910 * Look for a btrfs signature on a device. This may be called out of the mount path
911 * and we are not allowed to call set_blocksize during the scan. The superblock
912 * is read via pagecache
914 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
915 struct btrfs_fs_devices **fs_devices_ret)
917 struct btrfs_super_block *disk_super;
918 struct block_device *bdev;
929 * we would like to check all the supers, but that would make
930 * a btrfs mount succeed after a mkfs from a different FS.
931 * So, we need to add a special mount option to scan for
932 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
934 bytenr = btrfs_sb_offset(0);
936 mutex_lock(&uuid_mutex);
938 bdev = blkdev_get_by_path(path, flags, holder);
945 /* make sure our super fits in the device */
946 if (bytenr + PAGE_CACHE_SIZE >= i_size_read(bdev->bd_inode))
949 /* make sure our super fits in the page */
950 if (sizeof(*disk_super) > PAGE_CACHE_SIZE)
953 /* make sure our super doesn't straddle pages on disk */
954 index = bytenr >> PAGE_CACHE_SHIFT;
955 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_CACHE_SHIFT != index)
958 /* pull in the page with our super */
959 page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
962 if (IS_ERR_OR_NULL(page))
967 /* align our pointer to the offset of the super block */
968 disk_super = p + (bytenr & ~PAGE_CACHE_MASK);
970 if (btrfs_super_bytenr(disk_super) != bytenr ||
971 btrfs_super_magic(disk_super) != BTRFS_MAGIC)
974 devid = btrfs_stack_device_id(&disk_super->dev_item);
975 transid = btrfs_super_generation(disk_super);
976 total_devices = btrfs_super_num_devices(disk_super);
978 ret = device_list_add(path, disk_super, devid, fs_devices_ret);
980 if (disk_super->label[0]) {
981 if (disk_super->label[BTRFS_LABEL_SIZE - 1])
982 disk_super->label[BTRFS_LABEL_SIZE - 1] = '\0';
983 printk(KERN_INFO "BTRFS: device label %s ", disk_super->label);
985 printk(KERN_INFO "BTRFS: device fsid %pU ", disk_super->fsid);
988 printk(KERN_CONT "devid %llu transid %llu %s\n", devid, transid, path);
991 if (!ret && fs_devices_ret)
992 (*fs_devices_ret)->total_devices = total_devices;
996 page_cache_release(page);
999 blkdev_put(bdev, flags);
1001 mutex_unlock(&uuid_mutex);
1005 /* helper to account the used device space in the range */
1006 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1007 u64 end, u64 *length)
1009 struct btrfs_key key;
1010 struct btrfs_root *root = device->dev_root;
1011 struct btrfs_dev_extent *dev_extent;
1012 struct btrfs_path *path;
1016 struct extent_buffer *l;
1020 if (start >= device->total_bytes || device->is_tgtdev_for_dev_replace)
1023 path = btrfs_alloc_path();
1028 key.objectid = device->devid;
1030 key.type = BTRFS_DEV_EXTENT_KEY;
1032 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1036 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1043 slot = path->slots[0];
1044 if (slot >= btrfs_header_nritems(l)) {
1045 ret = btrfs_next_leaf(root, path);
1053 btrfs_item_key_to_cpu(l, &key, slot);
1055 if (key.objectid < device->devid)
1058 if (key.objectid > device->devid)
1061 if (key.type != BTRFS_DEV_EXTENT_KEY)
1064 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1065 extent_end = key.offset + btrfs_dev_extent_length(l,
1067 if (key.offset <= start && extent_end > end) {
1068 *length = end - start + 1;
1070 } else if (key.offset <= start && extent_end > start)
1071 *length += extent_end - start;
1072 else if (key.offset > start && extent_end <= end)
1073 *length += extent_end - key.offset;
1074 else if (key.offset > start && key.offset <= end) {
1075 *length += end - key.offset + 1;
1077 } else if (key.offset > end)
1085 btrfs_free_path(path);
1089 static int contains_pending_extent(struct btrfs_transaction *transaction,
1090 struct btrfs_device *device,
1091 u64 *start, u64 len)
1093 struct btrfs_fs_info *fs_info = device->dev_root->fs_info;
1094 struct extent_map *em;
1095 struct list_head *search_list = &fs_info->pinned_chunks;
1097 u64 physical_start = *start;
1100 search_list = &transaction->pending_chunks;
1102 list_for_each_entry(em, search_list, list) {
1103 struct map_lookup *map;
1106 map = (struct map_lookup *)em->bdev;
1107 for (i = 0; i < map->num_stripes; i++) {
1110 if (map->stripes[i].dev != device)
1112 if (map->stripes[i].physical >= physical_start + len ||
1113 map->stripes[i].physical + em->orig_block_len <=
1117 * Make sure that while processing the pinned list we do
1118 * not override our *start with a lower value, because
1119 * we can have pinned chunks that fall within this
1120 * device hole and that have lower physical addresses
1121 * than the pending chunks we processed before. If we
1122 * do not take this special care we can end up getting
1123 * 2 pending chunks that start at the same physical
1124 * device offsets because the end offset of a pinned
1125 * chunk can be equal to the start offset of some
1128 end = map->stripes[i].physical + em->orig_block_len;
1135 if (search_list != &fs_info->pinned_chunks) {
1136 search_list = &fs_info->pinned_chunks;
1145 * find_free_dev_extent_start - find free space in the specified device
1146 * @device: the device which we search the free space in
1147 * @num_bytes: the size of the free space that we need
1148 * @search_start: the position from which to begin the search
1149 * @start: store the start of the free space.
1150 * @len: the size of the free space. that we find, or the size
1151 * of the max free space if we don't find suitable free space
1153 * this uses a pretty simple search, the expectation is that it is
1154 * called very infrequently and that a given device has a small number
1157 * @start is used to store the start of the free space if we find. But if we
1158 * don't find suitable free space, it will be used to store the start position
1159 * of the max free space.
1161 * @len is used to store the size of the free space that we find.
1162 * But if we don't find suitable free space, it is used to store the size of
1163 * the max free space.
1165 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1166 struct btrfs_device *device, u64 num_bytes,
1167 u64 search_start, u64 *start, u64 *len)
1169 struct btrfs_key key;
1170 struct btrfs_root *root = device->dev_root;
1171 struct btrfs_dev_extent *dev_extent;
1172 struct btrfs_path *path;
1177 u64 search_end = device->total_bytes;
1180 struct extent_buffer *l;
1182 path = btrfs_alloc_path();
1186 max_hole_start = search_start;
1190 if (search_start >= search_end || device->is_tgtdev_for_dev_replace) {
1196 path->search_commit_root = 1;
1197 path->skip_locking = 1;
1199 key.objectid = device->devid;
1200 key.offset = search_start;
1201 key.type = BTRFS_DEV_EXTENT_KEY;
1203 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1207 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1214 slot = path->slots[0];
1215 if (slot >= btrfs_header_nritems(l)) {
1216 ret = btrfs_next_leaf(root, path);
1224 btrfs_item_key_to_cpu(l, &key, slot);
1226 if (key.objectid < device->devid)
1229 if (key.objectid > device->devid)
1232 if (key.type != BTRFS_DEV_EXTENT_KEY)
1235 if (key.offset > search_start) {
1236 hole_size = key.offset - search_start;
1239 * Have to check before we set max_hole_start, otherwise
1240 * we could end up sending back this offset anyway.
1242 if (contains_pending_extent(transaction, device,
1245 if (key.offset >= search_start) {
1246 hole_size = key.offset - search_start;
1253 if (hole_size > max_hole_size) {
1254 max_hole_start = search_start;
1255 max_hole_size = hole_size;
1259 * If this free space is greater than which we need,
1260 * it must be the max free space that we have found
1261 * until now, so max_hole_start must point to the start
1262 * of this free space and the length of this free space
1263 * is stored in max_hole_size. Thus, we return
1264 * max_hole_start and max_hole_size and go back to the
1267 if (hole_size >= num_bytes) {
1273 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1274 extent_end = key.offset + btrfs_dev_extent_length(l,
1276 if (extent_end > search_start)
1277 search_start = extent_end;
1284 * At this point, search_start should be the end of
1285 * allocated dev extents, and when shrinking the device,
1286 * search_end may be smaller than search_start.
1288 if (search_end > search_start) {
1289 hole_size = search_end - search_start;
1291 if (contains_pending_extent(transaction, device, &search_start,
1293 btrfs_release_path(path);
1297 if (hole_size > max_hole_size) {
1298 max_hole_start = search_start;
1299 max_hole_size = hole_size;
1304 if (max_hole_size < num_bytes)
1310 btrfs_free_path(path);
1311 *start = max_hole_start;
1313 *len = max_hole_size;
1317 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1318 struct btrfs_device *device, u64 num_bytes,
1319 u64 *start, u64 *len)
1321 struct btrfs_root *root = device->dev_root;
1324 /* FIXME use last free of some kind */
1327 * we don't want to overwrite the superblock on the drive,
1328 * so we make sure to start at an offset of at least 1MB
1330 search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
1331 return find_free_dev_extent_start(trans->transaction, device,
1332 num_bytes, search_start, start, len);
1335 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1336 struct btrfs_device *device,
1337 u64 start, u64 *dev_extent_len)
1340 struct btrfs_path *path;
1341 struct btrfs_root *root = device->dev_root;
1342 struct btrfs_key key;
1343 struct btrfs_key found_key;
1344 struct extent_buffer *leaf = NULL;
1345 struct btrfs_dev_extent *extent = NULL;
1347 path = btrfs_alloc_path();
1351 key.objectid = device->devid;
1353 key.type = BTRFS_DEV_EXTENT_KEY;
1355 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1357 ret = btrfs_previous_item(root, path, key.objectid,
1358 BTRFS_DEV_EXTENT_KEY);
1361 leaf = path->nodes[0];
1362 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1363 extent = btrfs_item_ptr(leaf, path->slots[0],
1364 struct btrfs_dev_extent);
1365 BUG_ON(found_key.offset > start || found_key.offset +
1366 btrfs_dev_extent_length(leaf, extent) < start);
1368 btrfs_release_path(path);
1370 } else if (ret == 0) {
1371 leaf = path->nodes[0];
1372 extent = btrfs_item_ptr(leaf, path->slots[0],
1373 struct btrfs_dev_extent);
1375 btrfs_std_error(root->fs_info, ret, "Slot search failed");
1379 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1381 ret = btrfs_del_item(trans, root, path);
1383 btrfs_std_error(root->fs_info, ret,
1384 "Failed to remove dev extent item");
1386 trans->transaction->have_free_bgs = 1;
1389 btrfs_free_path(path);
1393 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1394 struct btrfs_device *device,
1395 u64 chunk_tree, u64 chunk_objectid,
1396 u64 chunk_offset, u64 start, u64 num_bytes)
1399 struct btrfs_path *path;
1400 struct btrfs_root *root = device->dev_root;
1401 struct btrfs_dev_extent *extent;
1402 struct extent_buffer *leaf;
1403 struct btrfs_key key;
1405 WARN_ON(!device->in_fs_metadata);
1406 WARN_ON(device->is_tgtdev_for_dev_replace);
1407 path = btrfs_alloc_path();
1411 key.objectid = device->devid;
1413 key.type = BTRFS_DEV_EXTENT_KEY;
1414 ret = btrfs_insert_empty_item(trans, root, path, &key,
1419 leaf = path->nodes[0];
1420 extent = btrfs_item_ptr(leaf, path->slots[0],
1421 struct btrfs_dev_extent);
1422 btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1423 btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1424 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1426 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1427 btrfs_dev_extent_chunk_tree_uuid(extent), BTRFS_UUID_SIZE);
1429 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1430 btrfs_mark_buffer_dirty(leaf);
1432 btrfs_free_path(path);
1436 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1438 struct extent_map_tree *em_tree;
1439 struct extent_map *em;
1443 em_tree = &fs_info->mapping_tree.map_tree;
1444 read_lock(&em_tree->lock);
1445 n = rb_last(&em_tree->map);
1447 em = rb_entry(n, struct extent_map, rb_node);
1448 ret = em->start + em->len;
1450 read_unlock(&em_tree->lock);
1455 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1459 struct btrfs_key key;
1460 struct btrfs_key found_key;
1461 struct btrfs_path *path;
1463 path = btrfs_alloc_path();
1467 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1468 key.type = BTRFS_DEV_ITEM_KEY;
1469 key.offset = (u64)-1;
1471 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1475 BUG_ON(ret == 0); /* Corruption */
1477 ret = btrfs_previous_item(fs_info->chunk_root, path,
1478 BTRFS_DEV_ITEMS_OBJECTID,
1479 BTRFS_DEV_ITEM_KEY);
1483 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1485 *devid_ret = found_key.offset + 1;
1489 btrfs_free_path(path);
1494 * the device information is stored in the chunk root
1495 * the btrfs_device struct should be fully filled in
1497 static int btrfs_add_device(struct btrfs_trans_handle *trans,
1498 struct btrfs_root *root,
1499 struct btrfs_device *device)
1502 struct btrfs_path *path;
1503 struct btrfs_dev_item *dev_item;
1504 struct extent_buffer *leaf;
1505 struct btrfs_key key;
1508 root = root->fs_info->chunk_root;
1510 path = btrfs_alloc_path();
1514 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1515 key.type = BTRFS_DEV_ITEM_KEY;
1516 key.offset = device->devid;
1518 ret = btrfs_insert_empty_item(trans, root, path, &key,
1523 leaf = path->nodes[0];
1524 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1526 btrfs_set_device_id(leaf, dev_item, device->devid);
1527 btrfs_set_device_generation(leaf, dev_item, 0);
1528 btrfs_set_device_type(leaf, dev_item, device->type);
1529 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1530 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1531 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1532 btrfs_set_device_total_bytes(leaf, dev_item,
1533 btrfs_device_get_disk_total_bytes(device));
1534 btrfs_set_device_bytes_used(leaf, dev_item,
1535 btrfs_device_get_bytes_used(device));
1536 btrfs_set_device_group(leaf, dev_item, 0);
1537 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1538 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1539 btrfs_set_device_start_offset(leaf, dev_item, 0);
1541 ptr = btrfs_device_uuid(dev_item);
1542 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1543 ptr = btrfs_device_fsid(dev_item);
1544 write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
1545 btrfs_mark_buffer_dirty(leaf);
1549 btrfs_free_path(path);
1554 * Function to update ctime/mtime for a given device path.
1555 * Mainly used for ctime/mtime based probe like libblkid.
1557 static void update_dev_time(char *path_name)
1561 filp = filp_open(path_name, O_RDWR, 0);
1564 file_update_time(filp);
1565 filp_close(filp, NULL);
1569 static int btrfs_rm_dev_item(struct btrfs_root *root,
1570 struct btrfs_device *device)
1573 struct btrfs_path *path;
1574 struct btrfs_key key;
1575 struct btrfs_trans_handle *trans;
1577 root = root->fs_info->chunk_root;
1579 path = btrfs_alloc_path();
1583 trans = btrfs_start_transaction(root, 0);
1584 if (IS_ERR(trans)) {
1585 btrfs_free_path(path);
1586 return PTR_ERR(trans);
1588 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1589 key.type = BTRFS_DEV_ITEM_KEY;
1590 key.offset = device->devid;
1592 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1601 ret = btrfs_del_item(trans, root, path);
1605 btrfs_free_path(path);
1606 btrfs_commit_transaction(trans, root);
1610 int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1612 struct btrfs_device *device;
1613 struct btrfs_device *next_device;
1614 struct block_device *bdev;
1615 struct buffer_head *bh = NULL;
1616 struct btrfs_super_block *disk_super;
1617 struct btrfs_fs_devices *cur_devices;
1624 bool clear_super = false;
1626 mutex_lock(&uuid_mutex);
1629 seq = read_seqbegin(&root->fs_info->profiles_lock);
1631 all_avail = root->fs_info->avail_data_alloc_bits |
1632 root->fs_info->avail_system_alloc_bits |
1633 root->fs_info->avail_metadata_alloc_bits;
1634 } while (read_seqretry(&root->fs_info->profiles_lock, seq));
1636 num_devices = root->fs_info->fs_devices->num_devices;
1637 btrfs_dev_replace_lock(&root->fs_info->dev_replace);
1638 if (btrfs_dev_replace_is_ongoing(&root->fs_info->dev_replace)) {
1639 WARN_ON(num_devices < 1);
1642 btrfs_dev_replace_unlock(&root->fs_info->dev_replace);
1644 if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) && num_devices <= 4) {
1645 ret = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET;
1649 if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) && num_devices <= 2) {
1650 ret = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET;
1654 if ((all_avail & BTRFS_BLOCK_GROUP_RAID5) &&
1655 root->fs_info->fs_devices->rw_devices <= 2) {
1656 ret = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET;
1659 if ((all_avail & BTRFS_BLOCK_GROUP_RAID6) &&
1660 root->fs_info->fs_devices->rw_devices <= 3) {
1661 ret = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET;
1665 if (strcmp(device_path, "missing") == 0) {
1666 struct list_head *devices;
1667 struct btrfs_device *tmp;
1670 devices = &root->fs_info->fs_devices->devices;
1672 * It is safe to read the devices since the volume_mutex
1675 list_for_each_entry(tmp, devices, dev_list) {
1676 if (tmp->in_fs_metadata &&
1677 !tmp->is_tgtdev_for_dev_replace &&
1687 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
1691 ret = btrfs_get_bdev_and_sb(device_path,
1692 FMODE_WRITE | FMODE_EXCL,
1693 root->fs_info->bdev_holder, 0,
1697 disk_super = (struct btrfs_super_block *)bh->b_data;
1698 devid = btrfs_stack_device_id(&disk_super->dev_item);
1699 dev_uuid = disk_super->dev_item.uuid;
1700 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1708 if (device->is_tgtdev_for_dev_replace) {
1709 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1713 if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
1714 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1718 if (device->writeable) {
1720 list_del_init(&device->dev_alloc_list);
1721 device->fs_devices->rw_devices--;
1722 unlock_chunks(root);
1726 mutex_unlock(&uuid_mutex);
1727 ret = btrfs_shrink_device(device, 0);
1728 mutex_lock(&uuid_mutex);
1733 * TODO: the superblock still includes this device in its num_devices
1734 * counter although write_all_supers() is not locked out. This
1735 * could give a filesystem state which requires a degraded mount.
1737 ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1741 device->in_fs_metadata = 0;
1742 btrfs_scrub_cancel_dev(root->fs_info, device);
1745 * the device list mutex makes sure that we don't change
1746 * the device list while someone else is writing out all
1747 * the device supers. Whoever is writing all supers, should
1748 * lock the device list mutex before getting the number of
1749 * devices in the super block (super_copy). Conversely,
1750 * whoever updates the number of devices in the super block
1751 * (super_copy) should hold the device list mutex.
1754 cur_devices = device->fs_devices;
1755 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1756 list_del_rcu(&device->dev_list);
1758 device->fs_devices->num_devices--;
1759 device->fs_devices->total_devices--;
1761 if (device->missing)
1762 device->fs_devices->missing_devices--;
1764 next_device = list_entry(root->fs_info->fs_devices->devices.next,
1765 struct btrfs_device, dev_list);
1766 if (device->bdev == root->fs_info->sb->s_bdev)
1767 root->fs_info->sb->s_bdev = next_device->bdev;
1768 if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1769 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1772 device->fs_devices->open_devices--;
1773 /* remove sysfs entry */
1774 btrfs_sysfs_rm_device_link(root->fs_info->fs_devices, device);
1777 call_rcu(&device->rcu, free_device);
1779 num_devices = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
1780 btrfs_set_super_num_devices(root->fs_info->super_copy, num_devices);
1781 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1783 if (cur_devices->open_devices == 0) {
1784 struct btrfs_fs_devices *fs_devices;
1785 fs_devices = root->fs_info->fs_devices;
1786 while (fs_devices) {
1787 if (fs_devices->seed == cur_devices) {
1788 fs_devices->seed = cur_devices->seed;
1791 fs_devices = fs_devices->seed;
1793 cur_devices->seed = NULL;
1794 __btrfs_close_devices(cur_devices);
1795 free_fs_devices(cur_devices);
1798 root->fs_info->num_tolerated_disk_barrier_failures =
1799 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
1802 * at this point, the device is zero sized. We want to
1803 * remove it from the devices list and zero out the old super
1805 if (clear_super && disk_super) {
1809 /* make sure this device isn't detected as part of
1812 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1813 set_buffer_dirty(bh);
1814 sync_dirty_buffer(bh);
1816 /* clear the mirror copies of super block on the disk
1817 * being removed, 0th copy is been taken care above and
1818 * the below would take of the rest
1820 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1821 bytenr = btrfs_sb_offset(i);
1822 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
1823 i_size_read(bdev->bd_inode))
1827 bh = __bread(bdev, bytenr / 4096,
1828 BTRFS_SUPER_INFO_SIZE);
1832 disk_super = (struct btrfs_super_block *)bh->b_data;
1834 if (btrfs_super_bytenr(disk_super) != bytenr ||
1835 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1838 memset(&disk_super->magic, 0,
1839 sizeof(disk_super->magic));
1840 set_buffer_dirty(bh);
1841 sync_dirty_buffer(bh);
1848 /* Notify udev that device has changed */
1849 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
1851 /* Update ctime/mtime for device path for libblkid */
1852 update_dev_time(device_path);
1858 blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
1860 mutex_unlock(&uuid_mutex);
1863 if (device->writeable) {
1865 list_add(&device->dev_alloc_list,
1866 &root->fs_info->fs_devices->alloc_list);
1867 device->fs_devices->rw_devices++;
1868 unlock_chunks(root);
1873 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
1874 struct btrfs_device *srcdev)
1876 struct btrfs_fs_devices *fs_devices;
1878 WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
1881 * in case of fs with no seed, srcdev->fs_devices will point
1882 * to fs_devices of fs_info. However when the dev being replaced is
1883 * a seed dev it will point to the seed's local fs_devices. In short
1884 * srcdev will have its correct fs_devices in both the cases.
1886 fs_devices = srcdev->fs_devices;
1888 list_del_rcu(&srcdev->dev_list);
1889 list_del_rcu(&srcdev->dev_alloc_list);
1890 fs_devices->num_devices--;
1891 if (srcdev->missing)
1892 fs_devices->missing_devices--;
1894 if (srcdev->writeable) {
1895 fs_devices->rw_devices--;
1896 /* zero out the old super if it is writable */
1897 btrfs_scratch_superblocks(srcdev->bdev,
1898 rcu_str_deref(srcdev->name));
1902 fs_devices->open_devices--;
1905 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
1906 struct btrfs_device *srcdev)
1908 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
1910 call_rcu(&srcdev->rcu, free_device);
1913 * unless fs_devices is seed fs, num_devices shouldn't go
1916 BUG_ON(!fs_devices->num_devices && !fs_devices->seeding);
1918 /* if this is no devs we rather delete the fs_devices */
1919 if (!fs_devices->num_devices) {
1920 struct btrfs_fs_devices *tmp_fs_devices;
1922 tmp_fs_devices = fs_info->fs_devices;
1923 while (tmp_fs_devices) {
1924 if (tmp_fs_devices->seed == fs_devices) {
1925 tmp_fs_devices->seed = fs_devices->seed;
1928 tmp_fs_devices = tmp_fs_devices->seed;
1930 fs_devices->seed = NULL;
1931 __btrfs_close_devices(fs_devices);
1932 free_fs_devices(fs_devices);
1936 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
1937 struct btrfs_device *tgtdev)
1939 struct btrfs_device *next_device;
1941 mutex_lock(&uuid_mutex);
1943 mutex_lock(&fs_info->fs_devices->device_list_mutex);
1945 btrfs_sysfs_rm_device_link(fs_info->fs_devices, tgtdev);
1948 btrfs_scratch_superblocks(tgtdev->bdev,
1949 rcu_str_deref(tgtdev->name));
1950 fs_info->fs_devices->open_devices--;
1952 fs_info->fs_devices->num_devices--;
1954 next_device = list_entry(fs_info->fs_devices->devices.next,
1955 struct btrfs_device, dev_list);
1956 if (tgtdev->bdev == fs_info->sb->s_bdev)
1957 fs_info->sb->s_bdev = next_device->bdev;
1958 if (tgtdev->bdev == fs_info->fs_devices->latest_bdev)
1959 fs_info->fs_devices->latest_bdev = next_device->bdev;
1960 list_del_rcu(&tgtdev->dev_list);
1962 call_rcu(&tgtdev->rcu, free_device);
1964 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1965 mutex_unlock(&uuid_mutex);
1968 static int btrfs_find_device_by_path(struct btrfs_root *root, char *device_path,
1969 struct btrfs_device **device)
1972 struct btrfs_super_block *disk_super;
1975 struct block_device *bdev;
1976 struct buffer_head *bh;
1979 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
1980 root->fs_info->bdev_holder, 0, &bdev, &bh);
1983 disk_super = (struct btrfs_super_block *)bh->b_data;
1984 devid = btrfs_stack_device_id(&disk_super->dev_item);
1985 dev_uuid = disk_super->dev_item.uuid;
1986 *device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1991 blkdev_put(bdev, FMODE_READ);
1995 int btrfs_find_device_missing_or_by_path(struct btrfs_root *root,
1997 struct btrfs_device **device)
2000 if (strcmp(device_path, "missing") == 0) {
2001 struct list_head *devices;
2002 struct btrfs_device *tmp;
2004 devices = &root->fs_info->fs_devices->devices;
2006 * It is safe to read the devices since the volume_mutex
2007 * is held by the caller.
2009 list_for_each_entry(tmp, devices, dev_list) {
2010 if (tmp->in_fs_metadata && !tmp->bdev) {
2017 return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2021 return btrfs_find_device_by_path(root, device_path, device);
2026 * does all the dirty work required for changing file system's UUID.
2028 static int btrfs_prepare_sprout(struct btrfs_root *root)
2030 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2031 struct btrfs_fs_devices *old_devices;
2032 struct btrfs_fs_devices *seed_devices;
2033 struct btrfs_super_block *disk_super = root->fs_info->super_copy;
2034 struct btrfs_device *device;
2037 BUG_ON(!mutex_is_locked(&uuid_mutex));
2038 if (!fs_devices->seeding)
2041 seed_devices = __alloc_fs_devices();
2042 if (IS_ERR(seed_devices))
2043 return PTR_ERR(seed_devices);
2045 old_devices = clone_fs_devices(fs_devices);
2046 if (IS_ERR(old_devices)) {
2047 kfree(seed_devices);
2048 return PTR_ERR(old_devices);
2051 list_add(&old_devices->list, &fs_uuids);
2053 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2054 seed_devices->opened = 1;
2055 INIT_LIST_HEAD(&seed_devices->devices);
2056 INIT_LIST_HEAD(&seed_devices->alloc_list);
2057 mutex_init(&seed_devices->device_list_mutex);
2059 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2060 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2062 list_for_each_entry(device, &seed_devices->devices, dev_list)
2063 device->fs_devices = seed_devices;
2066 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2067 unlock_chunks(root);
2069 fs_devices->seeding = 0;
2070 fs_devices->num_devices = 0;
2071 fs_devices->open_devices = 0;
2072 fs_devices->missing_devices = 0;
2073 fs_devices->rotating = 0;
2074 fs_devices->seed = seed_devices;
2076 generate_random_uuid(fs_devices->fsid);
2077 memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2078 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2079 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2081 super_flags = btrfs_super_flags(disk_super) &
2082 ~BTRFS_SUPER_FLAG_SEEDING;
2083 btrfs_set_super_flags(disk_super, super_flags);
2089 * strore the expected generation for seed devices in device items.
2091 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2092 struct btrfs_root *root)
2094 struct btrfs_path *path;
2095 struct extent_buffer *leaf;
2096 struct btrfs_dev_item *dev_item;
2097 struct btrfs_device *device;
2098 struct btrfs_key key;
2099 u8 fs_uuid[BTRFS_UUID_SIZE];
2100 u8 dev_uuid[BTRFS_UUID_SIZE];
2104 path = btrfs_alloc_path();
2108 root = root->fs_info->chunk_root;
2109 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2111 key.type = BTRFS_DEV_ITEM_KEY;
2114 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2118 leaf = path->nodes[0];
2120 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2121 ret = btrfs_next_leaf(root, path);
2126 leaf = path->nodes[0];
2127 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2128 btrfs_release_path(path);
2132 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2133 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2134 key.type != BTRFS_DEV_ITEM_KEY)
2137 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2138 struct btrfs_dev_item);
2139 devid = btrfs_device_id(leaf, dev_item);
2140 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2142 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2144 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
2146 BUG_ON(!device); /* Logic error */
2148 if (device->fs_devices->seeding) {
2149 btrfs_set_device_generation(leaf, dev_item,
2150 device->generation);
2151 btrfs_mark_buffer_dirty(leaf);
2159 btrfs_free_path(path);
2163 int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
2165 struct request_queue *q;
2166 struct btrfs_trans_handle *trans;
2167 struct btrfs_device *device;
2168 struct block_device *bdev;
2169 struct list_head *devices;
2170 struct super_block *sb = root->fs_info->sb;
2171 struct rcu_string *name;
2173 int seeding_dev = 0;
2176 if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
2179 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2180 root->fs_info->bdev_holder);
2182 return PTR_ERR(bdev);
2184 if (root->fs_info->fs_devices->seeding) {
2186 down_write(&sb->s_umount);
2187 mutex_lock(&uuid_mutex);
2190 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2192 devices = &root->fs_info->fs_devices->devices;
2194 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2195 list_for_each_entry(device, devices, dev_list) {
2196 if (device->bdev == bdev) {
2199 &root->fs_info->fs_devices->device_list_mutex);
2203 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2205 device = btrfs_alloc_device(root->fs_info, NULL, NULL);
2206 if (IS_ERR(device)) {
2207 /* we can safely leave the fs_devices entry around */
2208 ret = PTR_ERR(device);
2212 name = rcu_string_strdup(device_path, GFP_NOFS);
2218 rcu_assign_pointer(device->name, name);
2220 trans = btrfs_start_transaction(root, 0);
2221 if (IS_ERR(trans)) {
2222 rcu_string_free(device->name);
2224 ret = PTR_ERR(trans);
2228 q = bdev_get_queue(bdev);
2229 if (blk_queue_discard(q))
2230 device->can_discard = 1;
2231 device->writeable = 1;
2232 device->generation = trans->transid;
2233 device->io_width = root->sectorsize;
2234 device->io_align = root->sectorsize;
2235 device->sector_size = root->sectorsize;
2236 device->total_bytes = i_size_read(bdev->bd_inode);
2237 device->disk_total_bytes = device->total_bytes;
2238 device->commit_total_bytes = device->total_bytes;
2239 device->dev_root = root->fs_info->dev_root;
2240 device->bdev = bdev;
2241 device->in_fs_metadata = 1;
2242 device->is_tgtdev_for_dev_replace = 0;
2243 device->mode = FMODE_EXCL;
2244 device->dev_stats_valid = 1;
2245 set_blocksize(device->bdev, 4096);
2248 sb->s_flags &= ~MS_RDONLY;
2249 ret = btrfs_prepare_sprout(root);
2250 BUG_ON(ret); /* -ENOMEM */
2253 device->fs_devices = root->fs_info->fs_devices;
2255 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2257 list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
2258 list_add(&device->dev_alloc_list,
2259 &root->fs_info->fs_devices->alloc_list);
2260 root->fs_info->fs_devices->num_devices++;
2261 root->fs_info->fs_devices->open_devices++;
2262 root->fs_info->fs_devices->rw_devices++;
2263 root->fs_info->fs_devices->total_devices++;
2264 root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2266 spin_lock(&root->fs_info->free_chunk_lock);
2267 root->fs_info->free_chunk_space += device->total_bytes;
2268 spin_unlock(&root->fs_info->free_chunk_lock);
2270 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
2271 root->fs_info->fs_devices->rotating = 1;
2273 tmp = btrfs_super_total_bytes(root->fs_info->super_copy);
2274 btrfs_set_super_total_bytes(root->fs_info->super_copy,
2275 tmp + device->total_bytes);
2277 tmp = btrfs_super_num_devices(root->fs_info->super_copy);
2278 btrfs_set_super_num_devices(root->fs_info->super_copy,
2281 /* add sysfs device entry */
2282 btrfs_sysfs_add_device_link(root->fs_info->fs_devices, device);
2285 * we've got more storage, clear any full flags on the space
2288 btrfs_clear_space_info_full(root->fs_info);
2290 unlock_chunks(root);
2291 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2295 ret = init_first_rw_device(trans, root, device);
2296 unlock_chunks(root);
2298 btrfs_abort_transaction(trans, root, ret);
2303 ret = btrfs_add_device(trans, root, device);
2305 btrfs_abort_transaction(trans, root, ret);
2310 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2312 ret = btrfs_finish_sprout(trans, root);
2314 btrfs_abort_transaction(trans, root, ret);
2318 /* Sprouting would change fsid of the mounted root,
2319 * so rename the fsid on the sysfs
2321 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2322 root->fs_info->fsid);
2323 if (kobject_rename(&root->fs_info->fs_devices->fsid_kobj,
2325 pr_warn("BTRFS: sysfs: failed to create fsid for sprout\n");
2328 root->fs_info->num_tolerated_disk_barrier_failures =
2329 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
2330 ret = btrfs_commit_transaction(trans, root);
2333 mutex_unlock(&uuid_mutex);
2334 up_write(&sb->s_umount);
2336 if (ret) /* transaction commit */
2339 ret = btrfs_relocate_sys_chunks(root);
2341 btrfs_std_error(root->fs_info, ret,
2342 "Failed to relocate sys chunks after "
2343 "device initialization. This can be fixed "
2344 "using the \"btrfs balance\" command.");
2345 trans = btrfs_attach_transaction(root);
2346 if (IS_ERR(trans)) {
2347 if (PTR_ERR(trans) == -ENOENT)
2349 return PTR_ERR(trans);
2351 ret = btrfs_commit_transaction(trans, root);
2354 /* Update ctime/mtime for libblkid */
2355 update_dev_time(device_path);
2359 btrfs_end_transaction(trans, root);
2360 rcu_string_free(device->name);
2361 btrfs_sysfs_rm_device_link(root->fs_info->fs_devices, device);
2364 blkdev_put(bdev, FMODE_EXCL);
2366 mutex_unlock(&uuid_mutex);
2367 up_write(&sb->s_umount);
2372 int btrfs_init_dev_replace_tgtdev(struct btrfs_root *root, char *device_path,
2373 struct btrfs_device *srcdev,
2374 struct btrfs_device **device_out)
2376 struct request_queue *q;
2377 struct btrfs_device *device;
2378 struct block_device *bdev;
2379 struct btrfs_fs_info *fs_info = root->fs_info;
2380 struct list_head *devices;
2381 struct rcu_string *name;
2382 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2386 if (fs_info->fs_devices->seeding) {
2387 btrfs_err(fs_info, "the filesystem is a seed filesystem!");
2391 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2392 fs_info->bdev_holder);
2394 btrfs_err(fs_info, "target device %s is invalid!", device_path);
2395 return PTR_ERR(bdev);
2398 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2400 devices = &fs_info->fs_devices->devices;
2401 list_for_each_entry(device, devices, dev_list) {
2402 if (device->bdev == bdev) {
2403 btrfs_err(fs_info, "target device is in the filesystem!");
2410 if (i_size_read(bdev->bd_inode) <
2411 btrfs_device_get_total_bytes(srcdev)) {
2412 btrfs_err(fs_info, "target device is smaller than source device!");
2418 device = btrfs_alloc_device(NULL, &devid, NULL);
2419 if (IS_ERR(device)) {
2420 ret = PTR_ERR(device);
2424 name = rcu_string_strdup(device_path, GFP_NOFS);
2430 rcu_assign_pointer(device->name, name);
2432 q = bdev_get_queue(bdev);
2433 if (blk_queue_discard(q))
2434 device->can_discard = 1;
2435 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2436 device->writeable = 1;
2437 device->generation = 0;
2438 device->io_width = root->sectorsize;
2439 device->io_align = root->sectorsize;
2440 device->sector_size = root->sectorsize;
2441 device->total_bytes = btrfs_device_get_total_bytes(srcdev);
2442 device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
2443 device->bytes_used = btrfs_device_get_bytes_used(srcdev);
2444 ASSERT(list_empty(&srcdev->resized_list));
2445 device->commit_total_bytes = srcdev->commit_total_bytes;
2446 device->commit_bytes_used = device->bytes_used;
2447 device->dev_root = fs_info->dev_root;
2448 device->bdev = bdev;
2449 device->in_fs_metadata = 1;
2450 device->is_tgtdev_for_dev_replace = 1;
2451 device->mode = FMODE_EXCL;
2452 device->dev_stats_valid = 1;
2453 set_blocksize(device->bdev, 4096);
2454 device->fs_devices = fs_info->fs_devices;
2455 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2456 fs_info->fs_devices->num_devices++;
2457 fs_info->fs_devices->open_devices++;
2458 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2460 *device_out = device;
2464 blkdev_put(bdev, FMODE_EXCL);
2468 void btrfs_init_dev_replace_tgtdev_for_resume(struct btrfs_fs_info *fs_info,
2469 struct btrfs_device *tgtdev)
2471 WARN_ON(fs_info->fs_devices->rw_devices == 0);
2472 tgtdev->io_width = fs_info->dev_root->sectorsize;
2473 tgtdev->io_align = fs_info->dev_root->sectorsize;
2474 tgtdev->sector_size = fs_info->dev_root->sectorsize;
2475 tgtdev->dev_root = fs_info->dev_root;
2476 tgtdev->in_fs_metadata = 1;
2479 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2480 struct btrfs_device *device)
2483 struct btrfs_path *path;
2484 struct btrfs_root *root;
2485 struct btrfs_dev_item *dev_item;
2486 struct extent_buffer *leaf;
2487 struct btrfs_key key;
2489 root = device->dev_root->fs_info->chunk_root;
2491 path = btrfs_alloc_path();
2495 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2496 key.type = BTRFS_DEV_ITEM_KEY;
2497 key.offset = device->devid;
2499 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2508 leaf = path->nodes[0];
2509 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2511 btrfs_set_device_id(leaf, dev_item, device->devid);
2512 btrfs_set_device_type(leaf, dev_item, device->type);
2513 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2514 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2515 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2516 btrfs_set_device_total_bytes(leaf, dev_item,
2517 btrfs_device_get_disk_total_bytes(device));
2518 btrfs_set_device_bytes_used(leaf, dev_item,
2519 btrfs_device_get_bytes_used(device));
2520 btrfs_mark_buffer_dirty(leaf);
2523 btrfs_free_path(path);
2527 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2528 struct btrfs_device *device, u64 new_size)
2530 struct btrfs_super_block *super_copy =
2531 device->dev_root->fs_info->super_copy;
2532 struct btrfs_fs_devices *fs_devices;
2536 if (!device->writeable)
2539 lock_chunks(device->dev_root);
2540 old_total = btrfs_super_total_bytes(super_copy);
2541 diff = new_size - device->total_bytes;
2543 if (new_size <= device->total_bytes ||
2544 device->is_tgtdev_for_dev_replace) {
2545 unlock_chunks(device->dev_root);
2549 fs_devices = device->dev_root->fs_info->fs_devices;
2551 btrfs_set_super_total_bytes(super_copy, old_total + diff);
2552 device->fs_devices->total_rw_bytes += diff;
2554 btrfs_device_set_total_bytes(device, new_size);
2555 btrfs_device_set_disk_total_bytes(device, new_size);
2556 btrfs_clear_space_info_full(device->dev_root->fs_info);
2557 if (list_empty(&device->resized_list))
2558 list_add_tail(&device->resized_list,
2559 &fs_devices->resized_devices);
2560 unlock_chunks(device->dev_root);
2562 return btrfs_update_device(trans, device);
2565 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2566 struct btrfs_root *root, u64 chunk_objectid,
2570 struct btrfs_path *path;
2571 struct btrfs_key key;
2573 root = root->fs_info->chunk_root;
2574 path = btrfs_alloc_path();
2578 key.objectid = chunk_objectid;
2579 key.offset = chunk_offset;
2580 key.type = BTRFS_CHUNK_ITEM_KEY;
2582 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2585 else if (ret > 0) { /* Logic error or corruption */
2586 btrfs_std_error(root->fs_info, -ENOENT,
2587 "Failed lookup while freeing chunk.");
2592 ret = btrfs_del_item(trans, root, path);
2594 btrfs_std_error(root->fs_info, ret,
2595 "Failed to delete chunk item.");
2597 btrfs_free_path(path);
2601 static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
2604 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
2605 struct btrfs_disk_key *disk_key;
2606 struct btrfs_chunk *chunk;
2613 struct btrfs_key key;
2616 array_size = btrfs_super_sys_array_size(super_copy);
2618 ptr = super_copy->sys_chunk_array;
2621 while (cur < array_size) {
2622 disk_key = (struct btrfs_disk_key *)ptr;
2623 btrfs_disk_key_to_cpu(&key, disk_key);
2625 len = sizeof(*disk_key);
2627 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2628 chunk = (struct btrfs_chunk *)(ptr + len);
2629 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2630 len += btrfs_chunk_item_size(num_stripes);
2635 if (key.objectid == chunk_objectid &&
2636 key.offset == chunk_offset) {
2637 memmove(ptr, ptr + len, array_size - (cur + len));
2639 btrfs_set_super_sys_array_size(super_copy, array_size);
2645 unlock_chunks(root);
2649 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2650 struct btrfs_root *root, u64 chunk_offset)
2652 struct extent_map_tree *em_tree;
2653 struct extent_map *em;
2654 struct btrfs_root *extent_root = root->fs_info->extent_root;
2655 struct map_lookup *map;
2656 u64 dev_extent_len = 0;
2657 u64 chunk_objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2661 root = root->fs_info->chunk_root;
2662 em_tree = &root->fs_info->mapping_tree.map_tree;
2664 read_lock(&em_tree->lock);
2665 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
2666 read_unlock(&em_tree->lock);
2668 if (!em || em->start > chunk_offset ||
2669 em->start + em->len < chunk_offset) {
2671 * This is a logic error, but we don't want to just rely on the
2672 * user having built with ASSERT enabled, so if ASSERT doens't
2673 * do anything we still error out.
2677 free_extent_map(em);
2680 map = (struct map_lookup *)em->bdev;
2681 lock_chunks(root->fs_info->chunk_root);
2682 check_system_chunk(trans, extent_root, map->type);
2683 unlock_chunks(root->fs_info->chunk_root);
2685 for (i = 0; i < map->num_stripes; i++) {
2686 struct btrfs_device *device = map->stripes[i].dev;
2687 ret = btrfs_free_dev_extent(trans, device,
2688 map->stripes[i].physical,
2691 btrfs_abort_transaction(trans, root, ret);
2695 if (device->bytes_used > 0) {
2697 btrfs_device_set_bytes_used(device,
2698 device->bytes_used - dev_extent_len);
2699 spin_lock(&root->fs_info->free_chunk_lock);
2700 root->fs_info->free_chunk_space += dev_extent_len;
2701 spin_unlock(&root->fs_info->free_chunk_lock);
2702 btrfs_clear_space_info_full(root->fs_info);
2703 unlock_chunks(root);
2706 if (map->stripes[i].dev) {
2707 ret = btrfs_update_device(trans, map->stripes[i].dev);
2709 btrfs_abort_transaction(trans, root, ret);
2714 ret = btrfs_free_chunk(trans, root, chunk_objectid, chunk_offset);
2716 btrfs_abort_transaction(trans, root, ret);
2720 trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
2722 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2723 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
2725 btrfs_abort_transaction(trans, root, ret);
2730 ret = btrfs_remove_block_group(trans, extent_root, chunk_offset, em);
2732 btrfs_abort_transaction(trans, extent_root, ret);
2738 free_extent_map(em);
2742 static int btrfs_relocate_chunk(struct btrfs_root *root, u64 chunk_offset)
2744 struct btrfs_root *extent_root;
2745 struct btrfs_trans_handle *trans;
2748 root = root->fs_info->chunk_root;
2749 extent_root = root->fs_info->extent_root;
2752 * Prevent races with automatic removal of unused block groups.
2753 * After we relocate and before we remove the chunk with offset
2754 * chunk_offset, automatic removal of the block group can kick in,
2755 * resulting in a failure when calling btrfs_remove_chunk() below.
2757 * Make sure to acquire this mutex before doing a tree search (dev
2758 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2759 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2760 * we release the path used to search the chunk/dev tree and before
2761 * the current task acquires this mutex and calls us.
2763 ASSERT(mutex_is_locked(&root->fs_info->delete_unused_bgs_mutex));
2765 ret = btrfs_can_relocate(extent_root, chunk_offset);
2769 /* step one, relocate all the extents inside this chunk */
2770 btrfs_scrub_pause(root);
2771 ret = btrfs_relocate_block_group(extent_root, chunk_offset);
2772 btrfs_scrub_continue(root);
2776 trans = btrfs_start_transaction(root, 0);
2777 if (IS_ERR(trans)) {
2778 ret = PTR_ERR(trans);
2779 btrfs_std_error(root->fs_info, ret, NULL);
2784 * step two, delete the device extents and the
2785 * chunk tree entries
2787 ret = btrfs_remove_chunk(trans, root, chunk_offset);
2788 btrfs_end_transaction(trans, root);
2792 static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
2794 struct btrfs_root *chunk_root = root->fs_info->chunk_root;
2795 struct btrfs_path *path;
2796 struct extent_buffer *leaf;
2797 struct btrfs_chunk *chunk;
2798 struct btrfs_key key;
2799 struct btrfs_key found_key;
2801 bool retried = false;
2805 path = btrfs_alloc_path();
2810 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2811 key.offset = (u64)-1;
2812 key.type = BTRFS_CHUNK_ITEM_KEY;
2815 mutex_lock(&root->fs_info->delete_unused_bgs_mutex);
2816 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2818 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
2821 BUG_ON(ret == 0); /* Corruption */
2823 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2826 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
2832 leaf = path->nodes[0];
2833 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2835 chunk = btrfs_item_ptr(leaf, path->slots[0],
2836 struct btrfs_chunk);
2837 chunk_type = btrfs_chunk_type(leaf, chunk);
2838 btrfs_release_path(path);
2840 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2841 ret = btrfs_relocate_chunk(chunk_root,
2848 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
2850 if (found_key.offset == 0)
2852 key.offset = found_key.offset - 1;
2855 if (failed && !retried) {
2859 } else if (WARN_ON(failed && retried)) {
2863 btrfs_free_path(path);
2867 static int insert_balance_item(struct btrfs_root *root,
2868 struct btrfs_balance_control *bctl)
2870 struct btrfs_trans_handle *trans;
2871 struct btrfs_balance_item *item;
2872 struct btrfs_disk_balance_args disk_bargs;
2873 struct btrfs_path *path;
2874 struct extent_buffer *leaf;
2875 struct btrfs_key key;
2878 path = btrfs_alloc_path();
2882 trans = btrfs_start_transaction(root, 0);
2883 if (IS_ERR(trans)) {
2884 btrfs_free_path(path);
2885 return PTR_ERR(trans);
2888 key.objectid = BTRFS_BALANCE_OBJECTID;
2889 key.type = BTRFS_BALANCE_ITEM_KEY;
2892 ret = btrfs_insert_empty_item(trans, root, path, &key,
2897 leaf = path->nodes[0];
2898 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2900 memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
2902 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
2903 btrfs_set_balance_data(leaf, item, &disk_bargs);
2904 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
2905 btrfs_set_balance_meta(leaf, item, &disk_bargs);
2906 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
2907 btrfs_set_balance_sys(leaf, item, &disk_bargs);
2909 btrfs_set_balance_flags(leaf, item, bctl->flags);
2911 btrfs_mark_buffer_dirty(leaf);
2913 btrfs_free_path(path);
2914 err = btrfs_commit_transaction(trans, root);
2920 static int del_balance_item(struct btrfs_root *root)
2922 struct btrfs_trans_handle *trans;
2923 struct btrfs_path *path;
2924 struct btrfs_key key;
2927 path = btrfs_alloc_path();
2931 trans = btrfs_start_transaction(root, 0);
2932 if (IS_ERR(trans)) {
2933 btrfs_free_path(path);
2934 return PTR_ERR(trans);
2937 key.objectid = BTRFS_BALANCE_OBJECTID;
2938 key.type = BTRFS_BALANCE_ITEM_KEY;
2941 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2949 ret = btrfs_del_item(trans, root, path);
2951 btrfs_free_path(path);
2952 err = btrfs_commit_transaction(trans, root);
2959 * This is a heuristic used to reduce the number of chunks balanced on
2960 * resume after balance was interrupted.
2962 static void update_balance_args(struct btrfs_balance_control *bctl)
2965 * Turn on soft mode for chunk types that were being converted.
2967 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
2968 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
2969 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
2970 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
2971 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
2972 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
2975 * Turn on usage filter if is not already used. The idea is
2976 * that chunks that we have already balanced should be
2977 * reasonably full. Don't do it for chunks that are being
2978 * converted - that will keep us from relocating unconverted
2979 * (albeit full) chunks.
2981 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2982 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2983 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
2984 bctl->data.usage = 90;
2986 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2987 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2988 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
2989 bctl->sys.usage = 90;
2991 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2992 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2993 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
2994 bctl->meta.usage = 90;
2999 * Should be called with both balance and volume mutexes held to
3000 * serialize other volume operations (add_dev/rm_dev/resize) with
3001 * restriper. Same goes for unset_balance_control.
3003 static void set_balance_control(struct btrfs_balance_control *bctl)
3005 struct btrfs_fs_info *fs_info = bctl->fs_info;
3007 BUG_ON(fs_info->balance_ctl);
3009 spin_lock(&fs_info->balance_lock);
3010 fs_info->balance_ctl = bctl;
3011 spin_unlock(&fs_info->balance_lock);
3014 static void unset_balance_control(struct btrfs_fs_info *fs_info)
3016 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3018 BUG_ON(!fs_info->balance_ctl);
3020 spin_lock(&fs_info->balance_lock);
3021 fs_info->balance_ctl = NULL;
3022 spin_unlock(&fs_info->balance_lock);
3028 * Balance filters. Return 1 if chunk should be filtered out
3029 * (should not be balanced).
3031 static int chunk_profiles_filter(u64 chunk_type,
3032 struct btrfs_balance_args *bargs)
3034 chunk_type = chunk_to_extended(chunk_type) &
3035 BTRFS_EXTENDED_PROFILE_MASK;
3037 if (bargs->profiles & chunk_type)
3043 static int chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3044 struct btrfs_balance_args *bargs)
3046 struct btrfs_block_group_cache *cache;
3047 u64 chunk_used, user_thresh;
3050 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3051 chunk_used = btrfs_block_group_used(&cache->item);
3053 if (bargs->usage == 0)
3055 else if (bargs->usage > 100)
3056 user_thresh = cache->key.offset;
3058 user_thresh = div_factor_fine(cache->key.offset,
3061 if (chunk_used < user_thresh)
3064 btrfs_put_block_group(cache);
3068 static int chunk_devid_filter(struct extent_buffer *leaf,
3069 struct btrfs_chunk *chunk,
3070 struct btrfs_balance_args *bargs)
3072 struct btrfs_stripe *stripe;
3073 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3076 for (i = 0; i < num_stripes; i++) {
3077 stripe = btrfs_stripe_nr(chunk, i);
3078 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3085 /* [pstart, pend) */
3086 static int chunk_drange_filter(struct extent_buffer *leaf,
3087 struct btrfs_chunk *chunk,
3089 struct btrfs_balance_args *bargs)
3091 struct btrfs_stripe *stripe;
3092 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3098 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3101 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3102 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3103 factor = num_stripes / 2;
3104 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3105 factor = num_stripes - 1;
3106 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3107 factor = num_stripes - 2;
3109 factor = num_stripes;
3112 for (i = 0; i < num_stripes; i++) {
3113 stripe = btrfs_stripe_nr(chunk, i);
3114 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3117 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3118 stripe_length = btrfs_chunk_length(leaf, chunk);
3119 stripe_length = div_u64(stripe_length, factor);
3121 if (stripe_offset < bargs->pend &&
3122 stripe_offset + stripe_length > bargs->pstart)
3129 /* [vstart, vend) */
3130 static int chunk_vrange_filter(struct extent_buffer *leaf,
3131 struct btrfs_chunk *chunk,
3133 struct btrfs_balance_args *bargs)
3135 if (chunk_offset < bargs->vend &&
3136 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3137 /* at least part of the chunk is inside this vrange */
3143 static int chunk_soft_convert_filter(u64 chunk_type,
3144 struct btrfs_balance_args *bargs)
3146 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3149 chunk_type = chunk_to_extended(chunk_type) &
3150 BTRFS_EXTENDED_PROFILE_MASK;
3152 if (bargs->target == chunk_type)
3158 static int should_balance_chunk(struct btrfs_root *root,
3159 struct extent_buffer *leaf,
3160 struct btrfs_chunk *chunk, u64 chunk_offset)
3162 struct btrfs_balance_control *bctl = root->fs_info->balance_ctl;
3163 struct btrfs_balance_args *bargs = NULL;
3164 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3167 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3168 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3172 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3173 bargs = &bctl->data;
3174 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3176 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3177 bargs = &bctl->meta;
3179 /* profiles filter */
3180 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3181 chunk_profiles_filter(chunk_type, bargs)) {
3186 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3187 chunk_usage_filter(bctl->fs_info, chunk_offset, bargs)) {
3192 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3193 chunk_devid_filter(leaf, chunk, bargs)) {
3197 /* drange filter, makes sense only with devid filter */
3198 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3199 chunk_drange_filter(leaf, chunk, chunk_offset, bargs)) {
3204 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3205 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3209 /* soft profile changing mode */
3210 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3211 chunk_soft_convert_filter(chunk_type, bargs)) {
3216 * limited by count, must be the last filter
3218 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3219 if (bargs->limit == 0)
3228 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3230 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3231 struct btrfs_root *chunk_root = fs_info->chunk_root;
3232 struct btrfs_root *dev_root = fs_info->dev_root;
3233 struct list_head *devices;
3234 struct btrfs_device *device;
3237 struct btrfs_chunk *chunk;
3238 struct btrfs_path *path;
3239 struct btrfs_key key;
3240 struct btrfs_key found_key;
3241 struct btrfs_trans_handle *trans;
3242 struct extent_buffer *leaf;
3245 int enospc_errors = 0;
3246 bool counting = true;
3247 u64 limit_data = bctl->data.limit;
3248 u64 limit_meta = bctl->meta.limit;
3249 u64 limit_sys = bctl->sys.limit;
3251 /* step one make some room on all the devices */
3252 devices = &fs_info->fs_devices->devices;
3253 list_for_each_entry(device, devices, dev_list) {
3254 old_size = btrfs_device_get_total_bytes(device);
3255 size_to_free = div_factor(old_size, 1);
3256 size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
3257 if (!device->writeable ||
3258 btrfs_device_get_total_bytes(device) -
3259 btrfs_device_get_bytes_used(device) > size_to_free ||
3260 device->is_tgtdev_for_dev_replace)
3263 ret = btrfs_shrink_device(device, old_size - size_to_free);
3268 trans = btrfs_start_transaction(dev_root, 0);
3269 BUG_ON(IS_ERR(trans));
3271 ret = btrfs_grow_device(trans, device, old_size);
3274 btrfs_end_transaction(trans, dev_root);
3277 /* step two, relocate all the chunks */
3278 path = btrfs_alloc_path();
3284 /* zero out stat counters */
3285 spin_lock(&fs_info->balance_lock);
3286 memset(&bctl->stat, 0, sizeof(bctl->stat));
3287 spin_unlock(&fs_info->balance_lock);
3290 bctl->data.limit = limit_data;
3291 bctl->meta.limit = limit_meta;
3292 bctl->sys.limit = limit_sys;
3294 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3295 key.offset = (u64)-1;
3296 key.type = BTRFS_CHUNK_ITEM_KEY;
3299 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3300 atomic_read(&fs_info->balance_cancel_req)) {
3305 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3306 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3308 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3313 * this shouldn't happen, it means the last relocate
3317 BUG(); /* FIXME break ? */
3319 ret = btrfs_previous_item(chunk_root, path, 0,
3320 BTRFS_CHUNK_ITEM_KEY);
3322 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3327 leaf = path->nodes[0];
3328 slot = path->slots[0];
3329 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3331 if (found_key.objectid != key.objectid) {
3332 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3336 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3339 spin_lock(&fs_info->balance_lock);
3340 bctl->stat.considered++;
3341 spin_unlock(&fs_info->balance_lock);
3344 ret = should_balance_chunk(chunk_root, leaf, chunk,
3346 btrfs_release_path(path);
3348 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3353 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3354 spin_lock(&fs_info->balance_lock);
3355 bctl->stat.expected++;
3356 spin_unlock(&fs_info->balance_lock);
3360 ret = btrfs_relocate_chunk(chunk_root,
3362 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3363 if (ret && ret != -ENOSPC)
3365 if (ret == -ENOSPC) {
3368 spin_lock(&fs_info->balance_lock);
3369 bctl->stat.completed++;
3370 spin_unlock(&fs_info->balance_lock);
3373 if (found_key.offset == 0)
3375 key.offset = found_key.offset - 1;
3379 btrfs_release_path(path);
3384 btrfs_free_path(path);
3385 if (enospc_errors) {
3386 btrfs_info(fs_info, "%d enospc errors during balance",
3396 * alloc_profile_is_valid - see if a given profile is valid and reduced
3397 * @flags: profile to validate
3398 * @extended: if true @flags is treated as an extended profile
3400 static int alloc_profile_is_valid(u64 flags, int extended)
3402 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3403 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3405 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3407 /* 1) check that all other bits are zeroed */
3411 /* 2) see if profile is reduced */
3413 return !extended; /* "0" is valid for usual profiles */
3415 /* true if exactly one bit set */
3416 return (flags & (flags - 1)) == 0;
3419 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3421 /* cancel requested || normal exit path */
3422 return atomic_read(&fs_info->balance_cancel_req) ||
3423 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3424 atomic_read(&fs_info->balance_cancel_req) == 0);
3427 static void __cancel_balance(struct btrfs_fs_info *fs_info)
3431 unset_balance_control(fs_info);
3432 ret = del_balance_item(fs_info->tree_root);
3434 btrfs_std_error(fs_info, ret, NULL);
3436 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3440 * Should be called with both balance and volume mutexes held
3442 int btrfs_balance(struct btrfs_balance_control *bctl,
3443 struct btrfs_ioctl_balance_args *bargs)
3445 struct btrfs_fs_info *fs_info = bctl->fs_info;
3452 if (btrfs_fs_closing(fs_info) ||
3453 atomic_read(&fs_info->balance_pause_req) ||
3454 atomic_read(&fs_info->balance_cancel_req)) {
3459 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3460 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3464 * In case of mixed groups both data and meta should be picked,
3465 * and identical options should be given for both of them.
3467 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3468 if (mixed && (bctl->flags & allowed)) {
3469 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3470 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3471 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3472 btrfs_err(fs_info, "with mixed groups data and "
3473 "metadata balance options must be the same");
3479 num_devices = fs_info->fs_devices->num_devices;
3480 btrfs_dev_replace_lock(&fs_info->dev_replace);
3481 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3482 BUG_ON(num_devices < 1);
3485 btrfs_dev_replace_unlock(&fs_info->dev_replace);
3486 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
3487 if (num_devices == 1)
3488 allowed |= BTRFS_BLOCK_GROUP_DUP;
3489 else if (num_devices > 1)
3490 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3491 if (num_devices > 2)
3492 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3493 if (num_devices > 3)
3494 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3495 BTRFS_BLOCK_GROUP_RAID6);
3496 if ((bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3497 (!alloc_profile_is_valid(bctl->data.target, 1) ||
3498 (bctl->data.target & ~allowed))) {
3499 btrfs_err(fs_info, "unable to start balance with target "
3500 "data profile %llu",
3505 if ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3506 (!alloc_profile_is_valid(bctl->meta.target, 1) ||
3507 (bctl->meta.target & ~allowed))) {
3509 "unable to start balance with target metadata profile %llu",
3514 if ((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3515 (!alloc_profile_is_valid(bctl->sys.target, 1) ||
3516 (bctl->sys.target & ~allowed))) {
3518 "unable to start balance with target system profile %llu",
3524 /* allow dup'ed data chunks only in mixed mode */
3525 if (!mixed && (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3526 (bctl->data.target & BTRFS_BLOCK_GROUP_DUP)) {
3527 btrfs_err(fs_info, "dup for data is not allowed");
3532 /* allow to reduce meta or sys integrity only if force set */
3533 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3534 BTRFS_BLOCK_GROUP_RAID10 |
3535 BTRFS_BLOCK_GROUP_RAID5 |
3536 BTRFS_BLOCK_GROUP_RAID6;
3538 seq = read_seqbegin(&fs_info->profiles_lock);
3540 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3541 (fs_info->avail_system_alloc_bits & allowed) &&
3542 !(bctl->sys.target & allowed)) ||
3543 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3544 (fs_info->avail_metadata_alloc_bits & allowed) &&
3545 !(bctl->meta.target & allowed))) {
3546 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3547 btrfs_info(fs_info, "force reducing metadata integrity");
3549 btrfs_err(fs_info, "balance will reduce metadata "
3550 "integrity, use force if you want this");
3555 } while (read_seqretry(&fs_info->profiles_lock, seq));
3557 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3558 fs_info->num_tolerated_disk_barrier_failures = min(
3559 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info),
3560 btrfs_get_num_tolerated_disk_barrier_failures(
3564 ret = insert_balance_item(fs_info->tree_root, bctl);
3565 if (ret && ret != -EEXIST)
3568 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3569 BUG_ON(ret == -EEXIST);
3570 set_balance_control(bctl);
3572 BUG_ON(ret != -EEXIST);
3573 spin_lock(&fs_info->balance_lock);
3574 update_balance_args(bctl);
3575 spin_unlock(&fs_info->balance_lock);
3578 atomic_inc(&fs_info->balance_running);
3579 mutex_unlock(&fs_info->balance_mutex);
3581 ret = __btrfs_balance(fs_info);
3583 mutex_lock(&fs_info->balance_mutex);
3584 atomic_dec(&fs_info->balance_running);
3586 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3587 fs_info->num_tolerated_disk_barrier_failures =
3588 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3592 memset(bargs, 0, sizeof(*bargs));
3593 update_ioctl_balance_args(fs_info, 0, bargs);
3596 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3597 balance_need_close(fs_info)) {
3598 __cancel_balance(fs_info);
3601 wake_up(&fs_info->balance_wait_q);
3605 if (bctl->flags & BTRFS_BALANCE_RESUME)
3606 __cancel_balance(fs_info);
3609 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3614 static int balance_kthread(void *data)
3616 struct btrfs_fs_info *fs_info = data;
3619 mutex_lock(&fs_info->volume_mutex);
3620 mutex_lock(&fs_info->balance_mutex);
3622 if (fs_info->balance_ctl) {
3623 btrfs_info(fs_info, "continuing balance");
3624 ret = btrfs_balance(fs_info->balance_ctl, NULL);
3627 mutex_unlock(&fs_info->balance_mutex);
3628 mutex_unlock(&fs_info->volume_mutex);
3633 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3635 struct task_struct *tsk;
3637 spin_lock(&fs_info->balance_lock);
3638 if (!fs_info->balance_ctl) {
3639 spin_unlock(&fs_info->balance_lock);
3642 spin_unlock(&fs_info->balance_lock);
3644 if (btrfs_test_opt(fs_info->tree_root, SKIP_BALANCE)) {
3645 btrfs_info(fs_info, "force skipping balance");
3649 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3650 return PTR_ERR_OR_ZERO(tsk);
3653 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3655 struct btrfs_balance_control *bctl;
3656 struct btrfs_balance_item *item;
3657 struct btrfs_disk_balance_args disk_bargs;
3658 struct btrfs_path *path;
3659 struct extent_buffer *leaf;
3660 struct btrfs_key key;
3663 path = btrfs_alloc_path();
3667 key.objectid = BTRFS_BALANCE_OBJECTID;
3668 key.type = BTRFS_BALANCE_ITEM_KEY;
3671 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3674 if (ret > 0) { /* ret = -ENOENT; */
3679 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3685 leaf = path->nodes[0];
3686 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3688 bctl->fs_info = fs_info;
3689 bctl->flags = btrfs_balance_flags(leaf, item);
3690 bctl->flags |= BTRFS_BALANCE_RESUME;
3692 btrfs_balance_data(leaf, item, &disk_bargs);
3693 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
3694 btrfs_balance_meta(leaf, item, &disk_bargs);
3695 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
3696 btrfs_balance_sys(leaf, item, &disk_bargs);
3697 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
3699 WARN_ON(atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1));
3701 mutex_lock(&fs_info->volume_mutex);
3702 mutex_lock(&fs_info->balance_mutex);
3704 set_balance_control(bctl);
3706 mutex_unlock(&fs_info->balance_mutex);
3707 mutex_unlock(&fs_info->volume_mutex);
3709 btrfs_free_path(path);
3713 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
3717 mutex_lock(&fs_info->balance_mutex);
3718 if (!fs_info->balance_ctl) {
3719 mutex_unlock(&fs_info->balance_mutex);
3723 if (atomic_read(&fs_info->balance_running)) {
3724 atomic_inc(&fs_info->balance_pause_req);
3725 mutex_unlock(&fs_info->balance_mutex);
3727 wait_event(fs_info->balance_wait_q,
3728 atomic_read(&fs_info->balance_running) == 0);
3730 mutex_lock(&fs_info->balance_mutex);
3731 /* we are good with balance_ctl ripped off from under us */
3732 BUG_ON(atomic_read(&fs_info->balance_running));
3733 atomic_dec(&fs_info->balance_pause_req);
3738 mutex_unlock(&fs_info->balance_mutex);
3742 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
3744 if (fs_info->sb->s_flags & MS_RDONLY)
3747 mutex_lock(&fs_info->balance_mutex);
3748 if (!fs_info->balance_ctl) {
3749 mutex_unlock(&fs_info->balance_mutex);
3753 atomic_inc(&fs_info->balance_cancel_req);
3755 * if we are running just wait and return, balance item is
3756 * deleted in btrfs_balance in this case
3758 if (atomic_read(&fs_info->balance_running)) {
3759 mutex_unlock(&fs_info->balance_mutex);
3760 wait_event(fs_info->balance_wait_q,
3761 atomic_read(&fs_info->balance_running) == 0);
3762 mutex_lock(&fs_info->balance_mutex);
3764 /* __cancel_balance needs volume_mutex */
3765 mutex_unlock(&fs_info->balance_mutex);
3766 mutex_lock(&fs_info->volume_mutex);
3767 mutex_lock(&fs_info->balance_mutex);
3769 if (fs_info->balance_ctl)
3770 __cancel_balance(fs_info);
3772 mutex_unlock(&fs_info->volume_mutex);
3775 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
3776 atomic_dec(&fs_info->balance_cancel_req);
3777 mutex_unlock(&fs_info->balance_mutex);
3781 static int btrfs_uuid_scan_kthread(void *data)
3783 struct btrfs_fs_info *fs_info = data;
3784 struct btrfs_root *root = fs_info->tree_root;
3785 struct btrfs_key key;
3786 struct btrfs_key max_key;
3787 struct btrfs_path *path = NULL;
3789 struct extent_buffer *eb;
3791 struct btrfs_root_item root_item;
3793 struct btrfs_trans_handle *trans = NULL;
3795 path = btrfs_alloc_path();
3802 key.type = BTRFS_ROOT_ITEM_KEY;
3805 max_key.objectid = (u64)-1;
3806 max_key.type = BTRFS_ROOT_ITEM_KEY;
3807 max_key.offset = (u64)-1;
3810 ret = btrfs_search_forward(root, &key, path, 0);
3817 if (key.type != BTRFS_ROOT_ITEM_KEY ||
3818 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
3819 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
3820 key.objectid > BTRFS_LAST_FREE_OBJECTID)
3823 eb = path->nodes[0];
3824 slot = path->slots[0];
3825 item_size = btrfs_item_size_nr(eb, slot);
3826 if (item_size < sizeof(root_item))
3829 read_extent_buffer(eb, &root_item,
3830 btrfs_item_ptr_offset(eb, slot),
3831 (int)sizeof(root_item));
3832 if (btrfs_root_refs(&root_item) == 0)
3835 if (!btrfs_is_empty_uuid(root_item.uuid) ||
3836 !btrfs_is_empty_uuid(root_item.received_uuid)) {
3840 btrfs_release_path(path);
3842 * 1 - subvol uuid item
3843 * 1 - received_subvol uuid item
3845 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
3846 if (IS_ERR(trans)) {
3847 ret = PTR_ERR(trans);
3855 if (!btrfs_is_empty_uuid(root_item.uuid)) {
3856 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
3858 BTRFS_UUID_KEY_SUBVOL,
3861 btrfs_warn(fs_info, "uuid_tree_add failed %d",
3867 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
3868 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
3869 root_item.received_uuid,
3870 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
3873 btrfs_warn(fs_info, "uuid_tree_add failed %d",
3881 ret = btrfs_end_transaction(trans, fs_info->uuid_root);
3887 btrfs_release_path(path);
3888 if (key.offset < (u64)-1) {
3890 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
3892 key.type = BTRFS_ROOT_ITEM_KEY;
3893 } else if (key.objectid < (u64)-1) {
3895 key.type = BTRFS_ROOT_ITEM_KEY;
3904 btrfs_free_path(path);
3905 if (trans && !IS_ERR(trans))
3906 btrfs_end_transaction(trans, fs_info->uuid_root);
3908 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
3910 fs_info->update_uuid_tree_gen = 1;
3911 up(&fs_info->uuid_tree_rescan_sem);
3916 * Callback for btrfs_uuid_tree_iterate().
3918 * 0 check succeeded, the entry is not outdated.
3919 * < 0 if an error occured.
3920 * > 0 if the check failed, which means the caller shall remove the entry.
3922 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
3923 u8 *uuid, u8 type, u64 subid)
3925 struct btrfs_key key;
3927 struct btrfs_root *subvol_root;
3929 if (type != BTRFS_UUID_KEY_SUBVOL &&
3930 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
3933 key.objectid = subid;
3934 key.type = BTRFS_ROOT_ITEM_KEY;
3935 key.offset = (u64)-1;
3936 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
3937 if (IS_ERR(subvol_root)) {
3938 ret = PTR_ERR(subvol_root);
3945 case BTRFS_UUID_KEY_SUBVOL:
3946 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
3949 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
3950 if (memcmp(uuid, subvol_root->root_item.received_uuid,
3960 static int btrfs_uuid_rescan_kthread(void *data)
3962 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
3966 * 1st step is to iterate through the existing UUID tree and
3967 * to delete all entries that contain outdated data.
3968 * 2nd step is to add all missing entries to the UUID tree.
3970 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
3972 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
3973 up(&fs_info->uuid_tree_rescan_sem);
3976 return btrfs_uuid_scan_kthread(data);
3979 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
3981 struct btrfs_trans_handle *trans;
3982 struct btrfs_root *tree_root = fs_info->tree_root;
3983 struct btrfs_root *uuid_root;
3984 struct task_struct *task;
3991 trans = btrfs_start_transaction(tree_root, 2);
3993 return PTR_ERR(trans);
3995 uuid_root = btrfs_create_tree(trans, fs_info,
3996 BTRFS_UUID_TREE_OBJECTID);
3997 if (IS_ERR(uuid_root)) {
3998 ret = PTR_ERR(uuid_root);
3999 btrfs_abort_transaction(trans, tree_root, ret);
4003 fs_info->uuid_root = uuid_root;
4005 ret = btrfs_commit_transaction(trans, tree_root);
4009 down(&fs_info->uuid_tree_rescan_sem);
4010 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4012 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4013 btrfs_warn(fs_info, "failed to start uuid_scan task");
4014 up(&fs_info->uuid_tree_rescan_sem);
4015 return PTR_ERR(task);
4021 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4023 struct task_struct *task;
4025 down(&fs_info->uuid_tree_rescan_sem);
4026 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4028 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4029 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4030 up(&fs_info->uuid_tree_rescan_sem);
4031 return PTR_ERR(task);
4038 * shrinking a device means finding all of the device extents past
4039 * the new size, and then following the back refs to the chunks.
4040 * The chunk relocation code actually frees the device extent
4042 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4044 struct btrfs_trans_handle *trans;
4045 struct btrfs_root *root = device->dev_root;
4046 struct btrfs_dev_extent *dev_extent = NULL;
4047 struct btrfs_path *path;
4053 bool retried = false;
4054 bool checked_pending_chunks = false;
4055 struct extent_buffer *l;
4056 struct btrfs_key key;
4057 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
4058 u64 old_total = btrfs_super_total_bytes(super_copy);
4059 u64 old_size = btrfs_device_get_total_bytes(device);
4060 u64 diff = old_size - new_size;
4062 if (device->is_tgtdev_for_dev_replace)
4065 path = btrfs_alloc_path();
4073 btrfs_device_set_total_bytes(device, new_size);
4074 if (device->writeable) {
4075 device->fs_devices->total_rw_bytes -= diff;
4076 spin_lock(&root->fs_info->free_chunk_lock);
4077 root->fs_info->free_chunk_space -= diff;
4078 spin_unlock(&root->fs_info->free_chunk_lock);
4080 unlock_chunks(root);
4083 key.objectid = device->devid;
4084 key.offset = (u64)-1;
4085 key.type = BTRFS_DEV_EXTENT_KEY;
4088 mutex_lock(&root->fs_info->delete_unused_bgs_mutex);
4089 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4091 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4095 ret = btrfs_previous_item(root, path, 0, key.type);
4097 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4102 btrfs_release_path(path);
4107 slot = path->slots[0];
4108 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4110 if (key.objectid != device->devid) {
4111 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4112 btrfs_release_path(path);
4116 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4117 length = btrfs_dev_extent_length(l, dev_extent);
4119 if (key.offset + length <= new_size) {
4120 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4121 btrfs_release_path(path);
4125 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4126 btrfs_release_path(path);
4128 ret = btrfs_relocate_chunk(root, chunk_offset);
4129 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4130 if (ret && ret != -ENOSPC)
4134 } while (key.offset-- > 0);
4136 if (failed && !retried) {
4140 } else if (failed && retried) {
4145 /* Shrinking succeeded, else we would be at "done". */
4146 trans = btrfs_start_transaction(root, 0);
4147 if (IS_ERR(trans)) {
4148 ret = PTR_ERR(trans);
4155 * We checked in the above loop all device extents that were already in
4156 * the device tree. However before we have updated the device's
4157 * total_bytes to the new size, we might have had chunk allocations that
4158 * have not complete yet (new block groups attached to transaction
4159 * handles), and therefore their device extents were not yet in the
4160 * device tree and we missed them in the loop above. So if we have any
4161 * pending chunk using a device extent that overlaps the device range
4162 * that we can not use anymore, commit the current transaction and
4163 * repeat the search on the device tree - this way we guarantee we will
4164 * not have chunks using device extents that end beyond 'new_size'.
4166 if (!checked_pending_chunks) {
4167 u64 start = new_size;
4168 u64 len = old_size - new_size;
4170 if (contains_pending_extent(trans->transaction, device,
4172 unlock_chunks(root);
4173 checked_pending_chunks = true;
4176 ret = btrfs_commit_transaction(trans, root);
4183 btrfs_device_set_disk_total_bytes(device, new_size);
4184 if (list_empty(&device->resized_list))
4185 list_add_tail(&device->resized_list,
4186 &root->fs_info->fs_devices->resized_devices);
4188 WARN_ON(diff > old_total);
4189 btrfs_set_super_total_bytes(super_copy, old_total - diff);
4190 unlock_chunks(root);
4192 /* Now btrfs_update_device() will change the on-disk size. */
4193 ret = btrfs_update_device(trans, device);
4194 btrfs_end_transaction(trans, root);
4196 btrfs_free_path(path);
4199 btrfs_device_set_total_bytes(device, old_size);
4200 if (device->writeable)
4201 device->fs_devices->total_rw_bytes += diff;
4202 spin_lock(&root->fs_info->free_chunk_lock);
4203 root->fs_info->free_chunk_space += diff;
4204 spin_unlock(&root->fs_info->free_chunk_lock);
4205 unlock_chunks(root);
4210 static int btrfs_add_system_chunk(struct btrfs_root *root,
4211 struct btrfs_key *key,
4212 struct btrfs_chunk *chunk, int item_size)
4214 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
4215 struct btrfs_disk_key disk_key;
4220 array_size = btrfs_super_sys_array_size(super_copy);
4221 if (array_size + item_size + sizeof(disk_key)
4222 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4223 unlock_chunks(root);
4227 ptr = super_copy->sys_chunk_array + array_size;
4228 btrfs_cpu_key_to_disk(&disk_key, key);
4229 memcpy(ptr, &disk_key, sizeof(disk_key));
4230 ptr += sizeof(disk_key);
4231 memcpy(ptr, chunk, item_size);
4232 item_size += sizeof(disk_key);
4233 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4234 unlock_chunks(root);
4240 * sort the devices in descending order by max_avail, total_avail
4242 static int btrfs_cmp_device_info(const void *a, const void *b)
4244 const struct btrfs_device_info *di_a = a;
4245 const struct btrfs_device_info *di_b = b;
4247 if (di_a->max_avail > di_b->max_avail)
4249 if (di_a->max_avail < di_b->max_avail)
4251 if (di_a->total_avail > di_b->total_avail)
4253 if (di_a->total_avail < di_b->total_avail)
4258 static const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
4259 [BTRFS_RAID_RAID10] = {
4262 .devs_max = 0, /* 0 == as many as possible */
4264 .devs_increment = 2,
4267 [BTRFS_RAID_RAID1] = {
4272 .devs_increment = 2,
4275 [BTRFS_RAID_DUP] = {
4280 .devs_increment = 1,
4283 [BTRFS_RAID_RAID0] = {
4288 .devs_increment = 1,
4291 [BTRFS_RAID_SINGLE] = {
4296 .devs_increment = 1,
4299 [BTRFS_RAID_RAID5] = {
4304 .devs_increment = 1,
4307 [BTRFS_RAID_RAID6] = {
4312 .devs_increment = 1,
4317 static u32 find_raid56_stripe_len(u32 data_devices, u32 dev_stripe_target)
4319 /* TODO allow them to set a preferred stripe size */
4323 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4325 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4328 btrfs_set_fs_incompat(info, RAID56);
4331 #define BTRFS_MAX_DEVS(r) ((BTRFS_LEAF_DATA_SIZE(r) \
4332 - sizeof(struct btrfs_item) \
4333 - sizeof(struct btrfs_chunk)) \
4334 / sizeof(struct btrfs_stripe) + 1)
4336 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4337 - 2 * sizeof(struct btrfs_disk_key) \
4338 - 2 * sizeof(struct btrfs_chunk)) \
4339 / sizeof(struct btrfs_stripe) + 1)
4341 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4342 struct btrfs_root *extent_root, u64 start,
4345 struct btrfs_fs_info *info = extent_root->fs_info;
4346 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4347 struct list_head *cur;
4348 struct map_lookup *map = NULL;
4349 struct extent_map_tree *em_tree;
4350 struct extent_map *em;
4351 struct btrfs_device_info *devices_info = NULL;
4353 int num_stripes; /* total number of stripes to allocate */
4354 int data_stripes; /* number of stripes that count for
4356 int sub_stripes; /* sub_stripes info for map */
4357 int dev_stripes; /* stripes per dev */
4358 int devs_max; /* max devs to use */
4359 int devs_min; /* min devs needed */
4360 int devs_increment; /* ndevs has to be a multiple of this */
4361 int ncopies; /* how many copies to data has */
4363 u64 max_stripe_size;
4367 u64 raid_stripe_len = BTRFS_STRIPE_LEN;
4373 BUG_ON(!alloc_profile_is_valid(type, 0));
4375 if (list_empty(&fs_devices->alloc_list))
4378 index = __get_raid_index(type);
4380 sub_stripes = btrfs_raid_array[index].sub_stripes;
4381 dev_stripes = btrfs_raid_array[index].dev_stripes;
4382 devs_max = btrfs_raid_array[index].devs_max;
4383 devs_min = btrfs_raid_array[index].devs_min;
4384 devs_increment = btrfs_raid_array[index].devs_increment;
4385 ncopies = btrfs_raid_array[index].ncopies;
4387 if (type & BTRFS_BLOCK_GROUP_DATA) {
4388 max_stripe_size = 1024 * 1024 * 1024;
4389 max_chunk_size = 10 * max_stripe_size;
4391 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4392 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4393 /* for larger filesystems, use larger metadata chunks */
4394 if (fs_devices->total_rw_bytes > 50ULL * 1024 * 1024 * 1024)
4395 max_stripe_size = 1024 * 1024 * 1024;
4397 max_stripe_size = 256 * 1024 * 1024;
4398 max_chunk_size = max_stripe_size;
4400 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4401 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4402 max_stripe_size = 32 * 1024 * 1024;
4403 max_chunk_size = 2 * max_stripe_size;
4405 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4407 btrfs_err(info, "invalid chunk type 0x%llx requested",
4412 /* we don't want a chunk larger than 10% of writeable space */
4413 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4416 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4421 cur = fs_devices->alloc_list.next;
4424 * in the first pass through the devices list, we gather information
4425 * about the available holes on each device.
4428 while (cur != &fs_devices->alloc_list) {
4429 struct btrfs_device *device;
4433 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
4437 if (!device->writeable) {
4439 "BTRFS: read-only device in alloc_list\n");
4443 if (!device->in_fs_metadata ||
4444 device->is_tgtdev_for_dev_replace)
4447 if (device->total_bytes > device->bytes_used)
4448 total_avail = device->total_bytes - device->bytes_used;
4452 /* If there is no space on this device, skip it. */
4453 if (total_avail == 0)
4456 ret = find_free_dev_extent(trans, device,
4457 max_stripe_size * dev_stripes,
4458 &dev_offset, &max_avail);
4459 if (ret && ret != -ENOSPC)
4463 max_avail = max_stripe_size * dev_stripes;
4465 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
4468 if (ndevs == fs_devices->rw_devices) {
4469 WARN(1, "%s: found more than %llu devices\n",
4470 __func__, fs_devices->rw_devices);
4473 devices_info[ndevs].dev_offset = dev_offset;
4474 devices_info[ndevs].max_avail = max_avail;
4475 devices_info[ndevs].total_avail = total_avail;
4476 devices_info[ndevs].dev = device;
4481 * now sort the devices by hole size / available space
4483 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4484 btrfs_cmp_device_info, NULL);
4486 /* round down to number of usable stripes */
4487 ndevs -= ndevs % devs_increment;
4489 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
4494 if (devs_max && ndevs > devs_max)
4497 * the primary goal is to maximize the number of stripes, so use as many
4498 * devices as possible, even if the stripes are not maximum sized.
4500 stripe_size = devices_info[ndevs-1].max_avail;
4501 num_stripes = ndevs * dev_stripes;
4504 * this will have to be fixed for RAID1 and RAID10 over
4507 data_stripes = num_stripes / ncopies;
4509 if (type & BTRFS_BLOCK_GROUP_RAID5) {
4510 raid_stripe_len = find_raid56_stripe_len(ndevs - 1,
4511 btrfs_super_stripesize(info->super_copy));
4512 data_stripes = num_stripes - 1;
4514 if (type & BTRFS_BLOCK_GROUP_RAID6) {
4515 raid_stripe_len = find_raid56_stripe_len(ndevs - 2,
4516 btrfs_super_stripesize(info->super_copy));
4517 data_stripes = num_stripes - 2;
4521 * Use the number of data stripes to figure out how big this chunk
4522 * is really going to be in terms of logical address space,
4523 * and compare that answer with the max chunk size
4525 if (stripe_size * data_stripes > max_chunk_size) {
4526 u64 mask = (1ULL << 24) - 1;
4528 stripe_size = div_u64(max_chunk_size, data_stripes);
4530 /* bump the answer up to a 16MB boundary */
4531 stripe_size = (stripe_size + mask) & ~mask;
4533 /* but don't go higher than the limits we found
4534 * while searching for free extents
4536 if (stripe_size > devices_info[ndevs-1].max_avail)
4537 stripe_size = devices_info[ndevs-1].max_avail;
4540 stripe_size = div_u64(stripe_size, dev_stripes);
4542 /* align to BTRFS_STRIPE_LEN */
4543 stripe_size = div_u64(stripe_size, raid_stripe_len);
4544 stripe_size *= raid_stripe_len;
4546 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4551 map->num_stripes = num_stripes;
4553 for (i = 0; i < ndevs; ++i) {
4554 for (j = 0; j < dev_stripes; ++j) {
4555 int s = i * dev_stripes + j;
4556 map->stripes[s].dev = devices_info[i].dev;
4557 map->stripes[s].physical = devices_info[i].dev_offset +
4561 map->sector_size = extent_root->sectorsize;
4562 map->stripe_len = raid_stripe_len;
4563 map->io_align = raid_stripe_len;
4564 map->io_width = raid_stripe_len;
4566 map->sub_stripes = sub_stripes;
4568 num_bytes = stripe_size * data_stripes;
4570 trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
4572 em = alloc_extent_map();
4578 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4579 em->bdev = (struct block_device *)map;
4581 em->len = num_bytes;
4582 em->block_start = 0;
4583 em->block_len = em->len;
4584 em->orig_block_len = stripe_size;
4586 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4587 write_lock(&em_tree->lock);
4588 ret = add_extent_mapping(em_tree, em, 0);
4590 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4591 atomic_inc(&em->refs);
4593 write_unlock(&em_tree->lock);
4595 free_extent_map(em);
4599 ret = btrfs_make_block_group(trans, extent_root, 0, type,
4600 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4603 goto error_del_extent;
4605 for (i = 0; i < map->num_stripes; i++) {
4606 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4607 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4610 spin_lock(&extent_root->fs_info->free_chunk_lock);
4611 extent_root->fs_info->free_chunk_space -= (stripe_size *
4613 spin_unlock(&extent_root->fs_info->free_chunk_lock);
4615 free_extent_map(em);
4616 check_raid56_incompat_flag(extent_root->fs_info, type);
4618 kfree(devices_info);
4622 write_lock(&em_tree->lock);
4623 remove_extent_mapping(em_tree, em);
4624 write_unlock(&em_tree->lock);
4626 /* One for our allocation */
4627 free_extent_map(em);
4628 /* One for the tree reference */
4629 free_extent_map(em);
4630 /* One for the pending_chunks list reference */
4631 free_extent_map(em);
4633 kfree(devices_info);
4637 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4638 struct btrfs_root *extent_root,
4639 u64 chunk_offset, u64 chunk_size)
4641 struct btrfs_key key;
4642 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
4643 struct btrfs_device *device;
4644 struct btrfs_chunk *chunk;
4645 struct btrfs_stripe *stripe;
4646 struct extent_map_tree *em_tree;
4647 struct extent_map *em;
4648 struct map_lookup *map;
4655 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4656 read_lock(&em_tree->lock);
4657 em = lookup_extent_mapping(em_tree, chunk_offset, chunk_size);
4658 read_unlock(&em_tree->lock);
4661 btrfs_crit(extent_root->fs_info, "unable to find logical "
4662 "%Lu len %Lu", chunk_offset, chunk_size);
4666 if (em->start != chunk_offset || em->len != chunk_size) {
4667 btrfs_crit(extent_root->fs_info, "found a bad mapping, wanted"
4668 " %Lu-%Lu, found %Lu-%Lu", chunk_offset,
4669 chunk_size, em->start, em->len);
4670 free_extent_map(em);
4674 map = (struct map_lookup *)em->bdev;
4675 item_size = btrfs_chunk_item_size(map->num_stripes);
4676 stripe_size = em->orig_block_len;
4678 chunk = kzalloc(item_size, GFP_NOFS);
4684 for (i = 0; i < map->num_stripes; i++) {
4685 device = map->stripes[i].dev;
4686 dev_offset = map->stripes[i].physical;
4688 ret = btrfs_update_device(trans, device);
4691 ret = btrfs_alloc_dev_extent(trans, device,
4692 chunk_root->root_key.objectid,
4693 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4694 chunk_offset, dev_offset,
4700 stripe = &chunk->stripe;
4701 for (i = 0; i < map->num_stripes; i++) {
4702 device = map->stripes[i].dev;
4703 dev_offset = map->stripes[i].physical;
4705 btrfs_set_stack_stripe_devid(stripe, device->devid);
4706 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4707 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4711 btrfs_set_stack_chunk_length(chunk, chunk_size);
4712 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4713 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4714 btrfs_set_stack_chunk_type(chunk, map->type);
4715 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4716 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4717 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4718 btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
4719 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
4721 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4722 key.type = BTRFS_CHUNK_ITEM_KEY;
4723 key.offset = chunk_offset;
4725 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4726 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4728 * TODO: Cleanup of inserted chunk root in case of
4731 ret = btrfs_add_system_chunk(chunk_root, &key, chunk,
4737 free_extent_map(em);
4742 * Chunk allocation falls into two parts. The first part does works
4743 * that make the new allocated chunk useable, but not do any operation
4744 * that modifies the chunk tree. The second part does the works that
4745 * require modifying the chunk tree. This division is important for the
4746 * bootstrap process of adding storage to a seed btrfs.
4748 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4749 struct btrfs_root *extent_root, u64 type)
4753 ASSERT(mutex_is_locked(&extent_root->fs_info->chunk_mutex));
4754 chunk_offset = find_next_chunk(extent_root->fs_info);
4755 return __btrfs_alloc_chunk(trans, extent_root, chunk_offset, type);
4758 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
4759 struct btrfs_root *root,
4760 struct btrfs_device *device)
4763 u64 sys_chunk_offset;
4765 struct btrfs_fs_info *fs_info = root->fs_info;
4766 struct btrfs_root *extent_root = fs_info->extent_root;
4769 chunk_offset = find_next_chunk(fs_info);
4770 alloc_profile = btrfs_get_alloc_profile(extent_root, 0);
4771 ret = __btrfs_alloc_chunk(trans, extent_root, chunk_offset,
4776 sys_chunk_offset = find_next_chunk(root->fs_info);
4777 alloc_profile = btrfs_get_alloc_profile(fs_info->chunk_root, 0);
4778 ret = __btrfs_alloc_chunk(trans, extent_root, sys_chunk_offset,
4783 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
4787 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
4788 BTRFS_BLOCK_GROUP_RAID10 |
4789 BTRFS_BLOCK_GROUP_RAID5 |
4790 BTRFS_BLOCK_GROUP_DUP)) {
4792 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
4801 int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
4803 struct extent_map *em;
4804 struct map_lookup *map;
4805 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4810 read_lock(&map_tree->map_tree.lock);
4811 em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
4812 read_unlock(&map_tree->map_tree.lock);
4816 map = (struct map_lookup *)em->bdev;
4817 for (i = 0; i < map->num_stripes; i++) {
4818 if (map->stripes[i].dev->missing) {
4823 if (!map->stripes[i].dev->writeable) {
4830 * If the number of missing devices is larger than max errors,
4831 * we can not write the data into that chunk successfully, so
4834 if (miss_ndevs > btrfs_chunk_max_errors(map))
4837 free_extent_map(em);
4841 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
4843 extent_map_tree_init(&tree->map_tree);
4846 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
4848 struct extent_map *em;
4851 write_lock(&tree->map_tree.lock);
4852 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
4854 remove_extent_mapping(&tree->map_tree, em);
4855 write_unlock(&tree->map_tree.lock);
4859 free_extent_map(em);
4860 /* once for the tree */
4861 free_extent_map(em);
4865 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
4867 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
4868 struct extent_map *em;
4869 struct map_lookup *map;
4870 struct extent_map_tree *em_tree = &map_tree->map_tree;
4873 read_lock(&em_tree->lock);
4874 em = lookup_extent_mapping(em_tree, logical, len);
4875 read_unlock(&em_tree->lock);
4878 * We could return errors for these cases, but that could get ugly and
4879 * we'd probably do the same thing which is just not do anything else
4880 * and exit, so return 1 so the callers don't try to use other copies.
4883 btrfs_crit(fs_info, "No mapping for %Lu-%Lu", logical,
4888 if (em->start > logical || em->start + em->len < logical) {
4889 btrfs_crit(fs_info, "Invalid mapping for %Lu-%Lu, got "
4890 "%Lu-%Lu", logical, logical+len, em->start,
4891 em->start + em->len);
4892 free_extent_map(em);
4896 map = (struct map_lookup *)em->bdev;
4897 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
4898 ret = map->num_stripes;
4899 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
4900 ret = map->sub_stripes;
4901 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
4903 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
4907 free_extent_map(em);
4909 btrfs_dev_replace_lock(&fs_info->dev_replace);
4910 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))
4912 btrfs_dev_replace_unlock(&fs_info->dev_replace);
4917 unsigned long btrfs_full_stripe_len(struct btrfs_root *root,
4918 struct btrfs_mapping_tree *map_tree,
4921 struct extent_map *em;
4922 struct map_lookup *map;
4923 struct extent_map_tree *em_tree = &map_tree->map_tree;
4924 unsigned long len = root->sectorsize;
4926 read_lock(&em_tree->lock);
4927 em = lookup_extent_mapping(em_tree, logical, len);
4928 read_unlock(&em_tree->lock);
4931 BUG_ON(em->start > logical || em->start + em->len < logical);
4932 map = (struct map_lookup *)em->bdev;
4933 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
4934 len = map->stripe_len * nr_data_stripes(map);
4935 free_extent_map(em);
4939 int btrfs_is_parity_mirror(struct btrfs_mapping_tree *map_tree,
4940 u64 logical, u64 len, int mirror_num)
4942 struct extent_map *em;
4943 struct map_lookup *map;
4944 struct extent_map_tree *em_tree = &map_tree->map_tree;
4947 read_lock(&em_tree->lock);
4948 em = lookup_extent_mapping(em_tree, logical, len);
4949 read_unlock(&em_tree->lock);
4952 BUG_ON(em->start > logical || em->start + em->len < logical);
4953 map = (struct map_lookup *)em->bdev;
4954 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
4956 free_extent_map(em);
4960 static int find_live_mirror(struct btrfs_fs_info *fs_info,
4961 struct map_lookup *map, int first, int num,
4962 int optimal, int dev_replace_is_ongoing)
4966 struct btrfs_device *srcdev;
4968 if (dev_replace_is_ongoing &&
4969 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
4970 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
4971 srcdev = fs_info->dev_replace.srcdev;
4976 * try to avoid the drive that is the source drive for a
4977 * dev-replace procedure, only choose it if no other non-missing
4978 * mirror is available
4980 for (tolerance = 0; tolerance < 2; tolerance++) {
4981 if (map->stripes[optimal].dev->bdev &&
4982 (tolerance || map->stripes[optimal].dev != srcdev))
4984 for (i = first; i < first + num; i++) {
4985 if (map->stripes[i].dev->bdev &&
4986 (tolerance || map->stripes[i].dev != srcdev))
4991 /* we couldn't find one that doesn't fail. Just return something
4992 * and the io error handling code will clean up eventually
4997 static inline int parity_smaller(u64 a, u64 b)
5002 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5003 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5005 struct btrfs_bio_stripe s;
5012 for (i = 0; i < num_stripes - 1; i++) {
5013 if (parity_smaller(bbio->raid_map[i],
5014 bbio->raid_map[i+1])) {
5015 s = bbio->stripes[i];
5016 l = bbio->raid_map[i];
5017 bbio->stripes[i] = bbio->stripes[i+1];
5018 bbio->raid_map[i] = bbio->raid_map[i+1];
5019 bbio->stripes[i+1] = s;
5020 bbio->raid_map[i+1] = l;
5028 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5030 struct btrfs_bio *bbio = kzalloc(
5031 /* the size of the btrfs_bio */
5032 sizeof(struct btrfs_bio) +
5033 /* plus the variable array for the stripes */
5034 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5035 /* plus the variable array for the tgt dev */
5036 sizeof(int) * (real_stripes) +
5038 * plus the raid_map, which includes both the tgt dev
5041 sizeof(u64) * (total_stripes),
5042 GFP_NOFS|__GFP_NOFAIL);
5044 atomic_set(&bbio->error, 0);
5045 atomic_set(&bbio->refs, 1);
5050 void btrfs_get_bbio(struct btrfs_bio *bbio)
5052 WARN_ON(!atomic_read(&bbio->refs));
5053 atomic_inc(&bbio->refs);
5056 void btrfs_put_bbio(struct btrfs_bio *bbio)
5060 if (atomic_dec_and_test(&bbio->refs))
5064 static int __btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
5065 u64 logical, u64 *length,
5066 struct btrfs_bio **bbio_ret,
5067 int mirror_num, int need_raid_map)
5069 struct extent_map *em;
5070 struct map_lookup *map;
5071 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
5072 struct extent_map_tree *em_tree = &map_tree->map_tree;
5075 u64 stripe_end_offset;
5085 int tgtdev_indexes = 0;
5086 struct btrfs_bio *bbio = NULL;
5087 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5088 int dev_replace_is_ongoing = 0;
5089 int num_alloc_stripes;
5090 int patch_the_first_stripe_for_dev_replace = 0;
5091 u64 physical_to_patch_in_first_stripe = 0;
5092 u64 raid56_full_stripe_start = (u64)-1;
5094 read_lock(&em_tree->lock);
5095 em = lookup_extent_mapping(em_tree, logical, *length);
5096 read_unlock(&em_tree->lock);
5099 btrfs_crit(fs_info, "unable to find logical %llu len %llu",
5104 if (em->start > logical || em->start + em->len < logical) {
5105 btrfs_crit(fs_info, "found a bad mapping, wanted %Lu, "
5106 "found %Lu-%Lu", logical, em->start,
5107 em->start + em->len);
5108 free_extent_map(em);
5112 map = (struct map_lookup *)em->bdev;
5113 offset = logical - em->start;
5115 stripe_len = map->stripe_len;
5118 * stripe_nr counts the total number of stripes we have to stride
5119 * to get to this block
5121 stripe_nr = div64_u64(stripe_nr, stripe_len);
5123 stripe_offset = stripe_nr * stripe_len;
5124 BUG_ON(offset < stripe_offset);
5126 /* stripe_offset is the offset of this block in its stripe*/
5127 stripe_offset = offset - stripe_offset;
5129 /* if we're here for raid56, we need to know the stripe aligned start */
5130 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5131 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5132 raid56_full_stripe_start = offset;
5134 /* allow a write of a full stripe, but make sure we don't
5135 * allow straddling of stripes
5137 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5139 raid56_full_stripe_start *= full_stripe_len;
5142 if (rw & REQ_DISCARD) {
5143 /* we don't discard raid56 yet */
5144 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5148 *length = min_t(u64, em->len - offset, *length);
5149 } else if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5151 /* For writes to RAID[56], allow a full stripeset across all disks.
5152 For other RAID types and for RAID[56] reads, just allow a single
5153 stripe (on a single disk). */
5154 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5156 max_len = stripe_len * nr_data_stripes(map) -
5157 (offset - raid56_full_stripe_start);
5159 /* we limit the length of each bio to what fits in a stripe */
5160 max_len = stripe_len - stripe_offset;
5162 *length = min_t(u64, em->len - offset, max_len);
5164 *length = em->len - offset;
5167 /* This is for when we're called from btrfs_merge_bio_hook() and all
5168 it cares about is the length */
5172 btrfs_dev_replace_lock(dev_replace);
5173 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5174 if (!dev_replace_is_ongoing)
5175 btrfs_dev_replace_unlock(dev_replace);
5177 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5178 !(rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) &&
5179 dev_replace->tgtdev != NULL) {
5181 * in dev-replace case, for repair case (that's the only
5182 * case where the mirror is selected explicitly when
5183 * calling btrfs_map_block), blocks left of the left cursor
5184 * can also be read from the target drive.
5185 * For REQ_GET_READ_MIRRORS, the target drive is added as
5186 * the last one to the array of stripes. For READ, it also
5187 * needs to be supported using the same mirror number.
5188 * If the requested block is not left of the left cursor,
5189 * EIO is returned. This can happen because btrfs_num_copies()
5190 * returns one more in the dev-replace case.
5192 u64 tmp_length = *length;
5193 struct btrfs_bio *tmp_bbio = NULL;
5194 int tmp_num_stripes;
5195 u64 srcdev_devid = dev_replace->srcdev->devid;
5196 int index_srcdev = 0;
5198 u64 physical_of_found = 0;
5200 ret = __btrfs_map_block(fs_info, REQ_GET_READ_MIRRORS,
5201 logical, &tmp_length, &tmp_bbio, 0, 0);
5203 WARN_ON(tmp_bbio != NULL);
5207 tmp_num_stripes = tmp_bbio->num_stripes;
5208 if (mirror_num > tmp_num_stripes) {
5210 * REQ_GET_READ_MIRRORS does not contain this
5211 * mirror, that means that the requested area
5212 * is not left of the left cursor
5215 btrfs_put_bbio(tmp_bbio);
5220 * process the rest of the function using the mirror_num
5221 * of the source drive. Therefore look it up first.
5222 * At the end, patch the device pointer to the one of the
5225 for (i = 0; i < tmp_num_stripes; i++) {
5226 if (tmp_bbio->stripes[i].dev->devid == srcdev_devid) {
5228 * In case of DUP, in order to keep it
5229 * simple, only add the mirror with the
5230 * lowest physical address
5233 physical_of_found <=
5234 tmp_bbio->stripes[i].physical)
5239 tmp_bbio->stripes[i].physical;
5244 mirror_num = index_srcdev + 1;
5245 patch_the_first_stripe_for_dev_replace = 1;
5246 physical_to_patch_in_first_stripe = physical_of_found;
5250 btrfs_put_bbio(tmp_bbio);
5254 btrfs_put_bbio(tmp_bbio);
5255 } else if (mirror_num > map->num_stripes) {
5261 stripe_nr_orig = stripe_nr;
5262 stripe_nr_end = ALIGN(offset + *length, map->stripe_len);
5263 stripe_nr_end = div_u64(stripe_nr_end, map->stripe_len);
5264 stripe_end_offset = stripe_nr_end * map->stripe_len -
5267 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5268 if (rw & REQ_DISCARD)
5269 num_stripes = min_t(u64, map->num_stripes,
5270 stripe_nr_end - stripe_nr_orig);
5271 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5273 if (!(rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)))
5275 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5276 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS))
5277 num_stripes = map->num_stripes;
5278 else if (mirror_num)
5279 stripe_index = mirror_num - 1;
5281 stripe_index = find_live_mirror(fs_info, map, 0,
5283 current->pid % map->num_stripes,
5284 dev_replace_is_ongoing);
5285 mirror_num = stripe_index + 1;
5288 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5289 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) {
5290 num_stripes = map->num_stripes;
5291 } else if (mirror_num) {
5292 stripe_index = mirror_num - 1;
5297 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5298 u32 factor = map->num_stripes / map->sub_stripes;
5300 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5301 stripe_index *= map->sub_stripes;
5303 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
5304 num_stripes = map->sub_stripes;
5305 else if (rw & REQ_DISCARD)
5306 num_stripes = min_t(u64, map->sub_stripes *
5307 (stripe_nr_end - stripe_nr_orig),
5309 else if (mirror_num)
5310 stripe_index += mirror_num - 1;
5312 int old_stripe_index = stripe_index;
5313 stripe_index = find_live_mirror(fs_info, map,
5315 map->sub_stripes, stripe_index +
5316 current->pid % map->sub_stripes,
5317 dev_replace_is_ongoing);
5318 mirror_num = stripe_index - old_stripe_index + 1;
5321 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5322 if (need_raid_map &&
5323 ((rw & (REQ_WRITE | REQ_GET_READ_MIRRORS)) ||
5325 /* push stripe_nr back to the start of the full stripe */
5326 stripe_nr = div_u64(raid56_full_stripe_start,
5327 stripe_len * nr_data_stripes(map));
5329 /* RAID[56] write or recovery. Return all stripes */
5330 num_stripes = map->num_stripes;
5331 max_errors = nr_parity_stripes(map);
5333 *length = map->stripe_len;
5338 * Mirror #0 or #1 means the original data block.
5339 * Mirror #2 is RAID5 parity block.
5340 * Mirror #3 is RAID6 Q block.
5342 stripe_nr = div_u64_rem(stripe_nr,
5343 nr_data_stripes(map), &stripe_index);
5345 stripe_index = nr_data_stripes(map) +
5348 /* We distribute the parity blocks across stripes */
5349 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5351 if (!(rw & (REQ_WRITE | REQ_DISCARD |
5352 REQ_GET_READ_MIRRORS)) && mirror_num <= 1)
5357 * after this, stripe_nr is the number of stripes on this
5358 * device we have to walk to find the data, and stripe_index is
5359 * the number of our device in the stripe array
5361 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5363 mirror_num = stripe_index + 1;
5365 BUG_ON(stripe_index >= map->num_stripes);
5367 num_alloc_stripes = num_stripes;
5368 if (dev_replace_is_ongoing) {
5369 if (rw & (REQ_WRITE | REQ_DISCARD))
5370 num_alloc_stripes <<= 1;
5371 if (rw & REQ_GET_READ_MIRRORS)
5372 num_alloc_stripes++;
5373 tgtdev_indexes = num_stripes;
5376 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5381 if (dev_replace_is_ongoing)
5382 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5384 /* build raid_map */
5385 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK &&
5386 need_raid_map && ((rw & (REQ_WRITE | REQ_GET_READ_MIRRORS)) ||
5391 bbio->raid_map = (u64 *)((void *)bbio->stripes +
5392 sizeof(struct btrfs_bio_stripe) *
5394 sizeof(int) * tgtdev_indexes);
5396 /* Work out the disk rotation on this stripe-set */
5397 div_u64_rem(stripe_nr, num_stripes, &rot);
5399 /* Fill in the logical address of each stripe */
5400 tmp = stripe_nr * nr_data_stripes(map);
5401 for (i = 0; i < nr_data_stripes(map); i++)
5402 bbio->raid_map[(i+rot) % num_stripes] =
5403 em->start + (tmp + i) * map->stripe_len;
5405 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5406 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5407 bbio->raid_map[(i+rot+1) % num_stripes] =
5411 if (rw & REQ_DISCARD) {
5413 u32 sub_stripes = 0;
5414 u64 stripes_per_dev = 0;
5415 u32 remaining_stripes = 0;
5416 u32 last_stripe = 0;
5419 (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
5420 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5423 sub_stripes = map->sub_stripes;
5425 factor = map->num_stripes / sub_stripes;
5426 stripes_per_dev = div_u64_rem(stripe_nr_end -
5429 &remaining_stripes);
5430 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5431 last_stripe *= sub_stripes;
5434 for (i = 0; i < num_stripes; i++) {
5435 bbio->stripes[i].physical =
5436 map->stripes[stripe_index].physical +
5437 stripe_offset + stripe_nr * map->stripe_len;
5438 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5440 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5441 BTRFS_BLOCK_GROUP_RAID10)) {
5442 bbio->stripes[i].length = stripes_per_dev *
5445 if (i / sub_stripes < remaining_stripes)
5446 bbio->stripes[i].length +=
5450 * Special for the first stripe and
5453 * |-------|...|-------|
5457 if (i < sub_stripes)
5458 bbio->stripes[i].length -=
5461 if (stripe_index >= last_stripe &&
5462 stripe_index <= (last_stripe +
5464 bbio->stripes[i].length -=
5467 if (i == sub_stripes - 1)
5470 bbio->stripes[i].length = *length;
5473 if (stripe_index == map->num_stripes) {
5474 /* This could only happen for RAID0/10 */
5480 for (i = 0; i < num_stripes; i++) {
5481 bbio->stripes[i].physical =
5482 map->stripes[stripe_index].physical +
5484 stripe_nr * map->stripe_len;
5485 bbio->stripes[i].dev =
5486 map->stripes[stripe_index].dev;
5491 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
5492 max_errors = btrfs_chunk_max_errors(map);
5495 sort_parity_stripes(bbio, num_stripes);
5498 if (dev_replace_is_ongoing && (rw & (REQ_WRITE | REQ_DISCARD)) &&
5499 dev_replace->tgtdev != NULL) {
5500 int index_where_to_add;
5501 u64 srcdev_devid = dev_replace->srcdev->devid;
5504 * duplicate the write operations while the dev replace
5505 * procedure is running. Since the copying of the old disk
5506 * to the new disk takes place at run time while the
5507 * filesystem is mounted writable, the regular write
5508 * operations to the old disk have to be duplicated to go
5509 * to the new disk as well.
5510 * Note that device->missing is handled by the caller, and
5511 * that the write to the old disk is already set up in the
5514 index_where_to_add = num_stripes;
5515 for (i = 0; i < num_stripes; i++) {
5516 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5517 /* write to new disk, too */
5518 struct btrfs_bio_stripe *new =
5519 bbio->stripes + index_where_to_add;
5520 struct btrfs_bio_stripe *old =
5523 new->physical = old->physical;
5524 new->length = old->length;
5525 new->dev = dev_replace->tgtdev;
5526 bbio->tgtdev_map[i] = index_where_to_add;
5527 index_where_to_add++;
5532 num_stripes = index_where_to_add;
5533 } else if (dev_replace_is_ongoing && (rw & REQ_GET_READ_MIRRORS) &&
5534 dev_replace->tgtdev != NULL) {
5535 u64 srcdev_devid = dev_replace->srcdev->devid;
5536 int index_srcdev = 0;
5538 u64 physical_of_found = 0;
5541 * During the dev-replace procedure, the target drive can
5542 * also be used to read data in case it is needed to repair
5543 * a corrupt block elsewhere. This is possible if the
5544 * requested area is left of the left cursor. In this area,
5545 * the target drive is a full copy of the source drive.
5547 for (i = 0; i < num_stripes; i++) {
5548 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5550 * In case of DUP, in order to keep it
5551 * simple, only add the mirror with the
5552 * lowest physical address
5555 physical_of_found <=
5556 bbio->stripes[i].physical)
5560 physical_of_found = bbio->stripes[i].physical;
5564 if (physical_of_found + map->stripe_len <=
5565 dev_replace->cursor_left) {
5566 struct btrfs_bio_stripe *tgtdev_stripe =
5567 bbio->stripes + num_stripes;
5569 tgtdev_stripe->physical = physical_of_found;
5570 tgtdev_stripe->length =
5571 bbio->stripes[index_srcdev].length;
5572 tgtdev_stripe->dev = dev_replace->tgtdev;
5573 bbio->tgtdev_map[index_srcdev] = num_stripes;
5582 bbio->map_type = map->type;
5583 bbio->num_stripes = num_stripes;
5584 bbio->max_errors = max_errors;
5585 bbio->mirror_num = mirror_num;
5586 bbio->num_tgtdevs = tgtdev_indexes;
5589 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5590 * mirror_num == num_stripes + 1 && dev_replace target drive is
5591 * available as a mirror
5593 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5594 WARN_ON(num_stripes > 1);
5595 bbio->stripes[0].dev = dev_replace->tgtdev;
5596 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5597 bbio->mirror_num = map->num_stripes + 1;
5600 if (dev_replace_is_ongoing)
5601 btrfs_dev_replace_unlock(dev_replace);
5602 free_extent_map(em);
5606 int btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
5607 u64 logical, u64 *length,
5608 struct btrfs_bio **bbio_ret, int mirror_num)
5610 return __btrfs_map_block(fs_info, rw, logical, length, bbio_ret,
5614 /* For Scrub/replace */
5615 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, int rw,
5616 u64 logical, u64 *length,
5617 struct btrfs_bio **bbio_ret, int mirror_num,
5620 return __btrfs_map_block(fs_info, rw, logical, length, bbio_ret,
5621 mirror_num, need_raid_map);
5624 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
5625 u64 chunk_start, u64 physical, u64 devid,
5626 u64 **logical, int *naddrs, int *stripe_len)
5628 struct extent_map_tree *em_tree = &map_tree->map_tree;
5629 struct extent_map *em;
5630 struct map_lookup *map;
5638 read_lock(&em_tree->lock);
5639 em = lookup_extent_mapping(em_tree, chunk_start, 1);
5640 read_unlock(&em_tree->lock);
5643 printk(KERN_ERR "BTRFS: couldn't find em for chunk %Lu\n",
5648 if (em->start != chunk_start) {
5649 printk(KERN_ERR "BTRFS: bad chunk start, em=%Lu, wanted=%Lu\n",
5650 em->start, chunk_start);
5651 free_extent_map(em);
5654 map = (struct map_lookup *)em->bdev;
5657 rmap_len = map->stripe_len;
5659 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5660 length = div_u64(length, map->num_stripes / map->sub_stripes);
5661 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5662 length = div_u64(length, map->num_stripes);
5663 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5664 length = div_u64(length, nr_data_stripes(map));
5665 rmap_len = map->stripe_len * nr_data_stripes(map);
5668 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
5669 BUG_ON(!buf); /* -ENOMEM */
5671 for (i = 0; i < map->num_stripes; i++) {
5672 if (devid && map->stripes[i].dev->devid != devid)
5674 if (map->stripes[i].physical > physical ||
5675 map->stripes[i].physical + length <= physical)
5678 stripe_nr = physical - map->stripes[i].physical;
5679 stripe_nr = div_u64(stripe_nr, map->stripe_len);
5681 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5682 stripe_nr = stripe_nr * map->num_stripes + i;
5683 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
5684 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5685 stripe_nr = stripe_nr * map->num_stripes + i;
5686 } /* else if RAID[56], multiply by nr_data_stripes().
5687 * Alternatively, just use rmap_len below instead of
5688 * map->stripe_len */
5690 bytenr = chunk_start + stripe_nr * rmap_len;
5691 WARN_ON(nr >= map->num_stripes);
5692 for (j = 0; j < nr; j++) {
5693 if (buf[j] == bytenr)
5697 WARN_ON(nr >= map->num_stripes);
5704 *stripe_len = rmap_len;
5706 free_extent_map(em);
5710 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
5712 bio->bi_private = bbio->private;
5713 bio->bi_end_io = bbio->end_io;
5716 btrfs_put_bbio(bbio);
5719 static void btrfs_end_bio(struct bio *bio)
5721 struct btrfs_bio *bbio = bio->bi_private;
5722 int is_orig_bio = 0;
5724 if (bio->bi_error) {
5725 atomic_inc(&bbio->error);
5726 if (bio->bi_error == -EIO || bio->bi_error == -EREMOTEIO) {
5727 unsigned int stripe_index =
5728 btrfs_io_bio(bio)->stripe_index;
5729 struct btrfs_device *dev;
5731 BUG_ON(stripe_index >= bbio->num_stripes);
5732 dev = bbio->stripes[stripe_index].dev;
5734 if (bio->bi_rw & WRITE)
5735 btrfs_dev_stat_inc(dev,
5736 BTRFS_DEV_STAT_WRITE_ERRS);
5738 btrfs_dev_stat_inc(dev,
5739 BTRFS_DEV_STAT_READ_ERRS);
5740 if ((bio->bi_rw & WRITE_FLUSH) == WRITE_FLUSH)
5741 btrfs_dev_stat_inc(dev,
5742 BTRFS_DEV_STAT_FLUSH_ERRS);
5743 btrfs_dev_stat_print_on_error(dev);
5748 if (bio == bbio->orig_bio)
5751 btrfs_bio_counter_dec(bbio->fs_info);
5753 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5756 bio = bbio->orig_bio;
5759 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5760 /* only send an error to the higher layers if it is
5761 * beyond the tolerance of the btrfs bio
5763 if (atomic_read(&bbio->error) > bbio->max_errors) {
5764 bio->bi_error = -EIO;
5767 * this bio is actually up to date, we didn't
5768 * go over the max number of errors
5773 btrfs_end_bbio(bbio, bio);
5774 } else if (!is_orig_bio) {
5780 * see run_scheduled_bios for a description of why bios are collected for
5783 * This will add one bio to the pending list for a device and make sure
5784 * the work struct is scheduled.
5786 static noinline void btrfs_schedule_bio(struct btrfs_root *root,
5787 struct btrfs_device *device,
5788 int rw, struct bio *bio)
5790 int should_queue = 1;
5791 struct btrfs_pending_bios *pending_bios;
5793 if (device->missing || !device->bdev) {
5798 /* don't bother with additional async steps for reads, right now */
5799 if (!(rw & REQ_WRITE)) {
5801 btrfsic_submit_bio(rw, bio);
5807 * nr_async_bios allows us to reliably return congestion to the
5808 * higher layers. Otherwise, the async bio makes it appear we have
5809 * made progress against dirty pages when we've really just put it
5810 * on a queue for later
5812 atomic_inc(&root->fs_info->nr_async_bios);
5813 WARN_ON(bio->bi_next);
5814 bio->bi_next = NULL;
5817 spin_lock(&device->io_lock);
5818 if (bio->bi_rw & REQ_SYNC)
5819 pending_bios = &device->pending_sync_bios;
5821 pending_bios = &device->pending_bios;
5823 if (pending_bios->tail)
5824 pending_bios->tail->bi_next = bio;
5826 pending_bios->tail = bio;
5827 if (!pending_bios->head)
5828 pending_bios->head = bio;
5829 if (device->running_pending)
5832 spin_unlock(&device->io_lock);
5835 btrfs_queue_work(root->fs_info->submit_workers,
5839 static void submit_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5840 struct bio *bio, u64 physical, int dev_nr,
5843 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
5845 bio->bi_private = bbio;
5846 btrfs_io_bio(bio)->stripe_index = dev_nr;
5847 bio->bi_end_io = btrfs_end_bio;
5848 bio->bi_iter.bi_sector = physical >> 9;
5851 struct rcu_string *name;
5854 name = rcu_dereference(dev->name);
5855 pr_debug("btrfs_map_bio: rw %d, sector=%llu, dev=%lu "
5856 "(%s id %llu), size=%u\n", rw,
5857 (u64)bio->bi_iter.bi_sector, (u_long)dev->bdev->bd_dev,
5858 name->str, dev->devid, bio->bi_iter.bi_size);
5862 bio->bi_bdev = dev->bdev;
5864 btrfs_bio_counter_inc_noblocked(root->fs_info);
5867 btrfs_schedule_bio(root, dev, rw, bio);
5869 btrfsic_submit_bio(rw, bio);
5872 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
5874 atomic_inc(&bbio->error);
5875 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5876 /* Shoud be the original bio. */
5877 WARN_ON(bio != bbio->orig_bio);
5879 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5880 bio->bi_iter.bi_sector = logical >> 9;
5881 bio->bi_error = -EIO;
5882 btrfs_end_bbio(bbio, bio);
5886 int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
5887 int mirror_num, int async_submit)
5889 struct btrfs_device *dev;
5890 struct bio *first_bio = bio;
5891 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
5897 struct btrfs_bio *bbio = NULL;
5899 length = bio->bi_iter.bi_size;
5900 map_length = length;
5902 btrfs_bio_counter_inc_blocked(root->fs_info);
5903 ret = __btrfs_map_block(root->fs_info, rw, logical, &map_length, &bbio,
5906 btrfs_bio_counter_dec(root->fs_info);
5910 total_devs = bbio->num_stripes;
5911 bbio->orig_bio = first_bio;
5912 bbio->private = first_bio->bi_private;
5913 bbio->end_io = first_bio->bi_end_io;
5914 bbio->fs_info = root->fs_info;
5915 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
5917 if (bbio->raid_map) {
5918 /* In this case, map_length has been set to the length of
5919 a single stripe; not the whole write */
5921 ret = raid56_parity_write(root, bio, bbio, map_length);
5923 ret = raid56_parity_recover(root, bio, bbio, map_length,
5927 btrfs_bio_counter_dec(root->fs_info);
5931 if (map_length < length) {
5932 btrfs_crit(root->fs_info, "mapping failed logical %llu bio len %llu len %llu",
5933 logical, length, map_length);
5937 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
5938 dev = bbio->stripes[dev_nr].dev;
5939 if (!dev || !dev->bdev || (rw & WRITE && !dev->writeable)) {
5940 bbio_error(bbio, first_bio, logical);
5944 if (dev_nr < total_devs - 1) {
5945 bio = btrfs_bio_clone(first_bio, GFP_NOFS);
5946 BUG_ON(!bio); /* -ENOMEM */
5950 submit_stripe_bio(root, bbio, bio,
5951 bbio->stripes[dev_nr].physical, dev_nr, rw,
5954 btrfs_bio_counter_dec(root->fs_info);
5958 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
5961 struct btrfs_device *device;
5962 struct btrfs_fs_devices *cur_devices;
5964 cur_devices = fs_info->fs_devices;
5965 while (cur_devices) {
5967 !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
5968 device = __find_device(&cur_devices->devices,
5973 cur_devices = cur_devices->seed;
5978 static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
5979 struct btrfs_fs_devices *fs_devices,
5980 u64 devid, u8 *dev_uuid)
5982 struct btrfs_device *device;
5984 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
5988 list_add(&device->dev_list, &fs_devices->devices);
5989 device->fs_devices = fs_devices;
5990 fs_devices->num_devices++;
5992 device->missing = 1;
5993 fs_devices->missing_devices++;
5999 * btrfs_alloc_device - allocate struct btrfs_device
6000 * @fs_info: used only for generating a new devid, can be NULL if
6001 * devid is provided (i.e. @devid != NULL).
6002 * @devid: a pointer to devid for this device. If NULL a new devid
6004 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6007 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6008 * on error. Returned struct is not linked onto any lists and can be
6009 * destroyed with kfree() right away.
6011 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6015 struct btrfs_device *dev;
6018 if (WARN_ON(!devid && !fs_info))
6019 return ERR_PTR(-EINVAL);
6021 dev = __alloc_device();
6030 ret = find_next_devid(fs_info, &tmp);
6033 return ERR_PTR(ret);
6039 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6041 generate_random_uuid(dev->uuid);
6043 btrfs_init_work(&dev->work, btrfs_submit_helper,
6044 pending_bios_fn, NULL, NULL);
6049 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
6050 struct extent_buffer *leaf,
6051 struct btrfs_chunk *chunk)
6053 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
6054 struct map_lookup *map;
6055 struct extent_map *em;
6059 u8 uuid[BTRFS_UUID_SIZE];
6064 logical = key->offset;
6065 length = btrfs_chunk_length(leaf, chunk);
6067 read_lock(&map_tree->map_tree.lock);
6068 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6069 read_unlock(&map_tree->map_tree.lock);
6071 /* already mapped? */
6072 if (em && em->start <= logical && em->start + em->len > logical) {
6073 free_extent_map(em);
6076 free_extent_map(em);
6079 em = alloc_extent_map();
6082 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6083 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6085 free_extent_map(em);
6089 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6090 em->bdev = (struct block_device *)map;
6091 em->start = logical;
6094 em->block_start = 0;
6095 em->block_len = em->len;
6097 map->num_stripes = num_stripes;
6098 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6099 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6100 map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
6101 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6102 map->type = btrfs_chunk_type(leaf, chunk);
6103 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6104 for (i = 0; i < num_stripes; i++) {
6105 map->stripes[i].physical =
6106 btrfs_stripe_offset_nr(leaf, chunk, i);
6107 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6108 read_extent_buffer(leaf, uuid, (unsigned long)
6109 btrfs_stripe_dev_uuid_nr(chunk, i),
6111 map->stripes[i].dev = btrfs_find_device(root->fs_info, devid,
6113 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
6114 free_extent_map(em);
6117 if (!map->stripes[i].dev) {
6118 map->stripes[i].dev =
6119 add_missing_dev(root, root->fs_info->fs_devices,
6121 if (!map->stripes[i].dev) {
6122 free_extent_map(em);
6125 btrfs_warn(root->fs_info, "devid %llu uuid %pU is missing",
6128 map->stripes[i].dev->in_fs_metadata = 1;
6131 write_lock(&map_tree->map_tree.lock);
6132 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6133 write_unlock(&map_tree->map_tree.lock);
6134 BUG_ON(ret); /* Tree corruption */
6135 free_extent_map(em);
6140 static void fill_device_from_item(struct extent_buffer *leaf,
6141 struct btrfs_dev_item *dev_item,
6142 struct btrfs_device *device)
6146 device->devid = btrfs_device_id(leaf, dev_item);
6147 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6148 device->total_bytes = device->disk_total_bytes;
6149 device->commit_total_bytes = device->disk_total_bytes;
6150 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6151 device->commit_bytes_used = device->bytes_used;
6152 device->type = btrfs_device_type(leaf, dev_item);
6153 device->io_align = btrfs_device_io_align(leaf, dev_item);
6154 device->io_width = btrfs_device_io_width(leaf, dev_item);
6155 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6156 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6157 device->is_tgtdev_for_dev_replace = 0;
6159 ptr = btrfs_device_uuid(dev_item);
6160 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6163 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_root *root,
6166 struct btrfs_fs_devices *fs_devices;
6169 BUG_ON(!mutex_is_locked(&uuid_mutex));
6171 fs_devices = root->fs_info->fs_devices->seed;
6172 while (fs_devices) {
6173 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE))
6176 fs_devices = fs_devices->seed;
6179 fs_devices = find_fsid(fsid);
6181 if (!btrfs_test_opt(root, DEGRADED))
6182 return ERR_PTR(-ENOENT);
6184 fs_devices = alloc_fs_devices(fsid);
6185 if (IS_ERR(fs_devices))
6188 fs_devices->seeding = 1;
6189 fs_devices->opened = 1;
6193 fs_devices = clone_fs_devices(fs_devices);
6194 if (IS_ERR(fs_devices))
6197 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
6198 root->fs_info->bdev_holder);
6200 free_fs_devices(fs_devices);
6201 fs_devices = ERR_PTR(ret);
6205 if (!fs_devices->seeding) {
6206 __btrfs_close_devices(fs_devices);
6207 free_fs_devices(fs_devices);
6208 fs_devices = ERR_PTR(-EINVAL);
6212 fs_devices->seed = root->fs_info->fs_devices->seed;
6213 root->fs_info->fs_devices->seed = fs_devices;
6218 static int read_one_dev(struct btrfs_root *root,
6219 struct extent_buffer *leaf,
6220 struct btrfs_dev_item *dev_item)
6222 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
6223 struct btrfs_device *device;
6226 u8 fs_uuid[BTRFS_UUID_SIZE];
6227 u8 dev_uuid[BTRFS_UUID_SIZE];
6229 devid = btrfs_device_id(leaf, dev_item);
6230 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6232 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6235 if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
6236 fs_devices = open_seed_devices(root, fs_uuid);
6237 if (IS_ERR(fs_devices))
6238 return PTR_ERR(fs_devices);
6241 device = btrfs_find_device(root->fs_info, devid, dev_uuid, fs_uuid);
6243 if (!btrfs_test_opt(root, DEGRADED))
6246 device = add_missing_dev(root, fs_devices, devid, dev_uuid);
6249 btrfs_warn(root->fs_info, "devid %llu uuid %pU missing",
6252 if (!device->bdev && !btrfs_test_opt(root, DEGRADED))
6255 if(!device->bdev && !device->missing) {
6257 * this happens when a device that was properly setup
6258 * in the device info lists suddenly goes bad.
6259 * device->bdev is NULL, and so we have to set
6260 * device->missing to one here
6262 device->fs_devices->missing_devices++;
6263 device->missing = 1;
6266 /* Move the device to its own fs_devices */
6267 if (device->fs_devices != fs_devices) {
6268 ASSERT(device->missing);
6270 list_move(&device->dev_list, &fs_devices->devices);
6271 device->fs_devices->num_devices--;
6272 fs_devices->num_devices++;
6274 device->fs_devices->missing_devices--;
6275 fs_devices->missing_devices++;
6277 device->fs_devices = fs_devices;
6281 if (device->fs_devices != root->fs_info->fs_devices) {
6282 BUG_ON(device->writeable);
6283 if (device->generation !=
6284 btrfs_device_generation(leaf, dev_item))
6288 fill_device_from_item(leaf, dev_item, device);
6289 device->in_fs_metadata = 1;
6290 if (device->writeable && !device->is_tgtdev_for_dev_replace) {
6291 device->fs_devices->total_rw_bytes += device->total_bytes;
6292 spin_lock(&root->fs_info->free_chunk_lock);
6293 root->fs_info->free_chunk_space += device->total_bytes -
6295 spin_unlock(&root->fs_info->free_chunk_lock);
6301 int btrfs_read_sys_array(struct btrfs_root *root)
6303 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
6304 struct extent_buffer *sb;
6305 struct btrfs_disk_key *disk_key;
6306 struct btrfs_chunk *chunk;
6308 unsigned long sb_array_offset;
6314 struct btrfs_key key;
6316 ASSERT(BTRFS_SUPER_INFO_SIZE <= root->nodesize);
6318 * This will create extent buffer of nodesize, superblock size is
6319 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6320 * overallocate but we can keep it as-is, only the first page is used.
6322 sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET);
6325 btrfs_set_buffer_uptodate(sb);
6326 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6328 * The sb extent buffer is artifical and just used to read the system array.
6329 * btrfs_set_buffer_uptodate() call does not properly mark all it's
6330 * pages up-to-date when the page is larger: extent does not cover the
6331 * whole page and consequently check_page_uptodate does not find all
6332 * the page's extents up-to-date (the hole beyond sb),
6333 * write_extent_buffer then triggers a WARN_ON.
6335 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6336 * but sb spans only this function. Add an explicit SetPageUptodate call
6337 * to silence the warning eg. on PowerPC 64.
6339 if (PAGE_CACHE_SIZE > BTRFS_SUPER_INFO_SIZE)
6340 SetPageUptodate(sb->pages[0]);
6342 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6343 array_size = btrfs_super_sys_array_size(super_copy);
6345 array_ptr = super_copy->sys_chunk_array;
6346 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6349 while (cur_offset < array_size) {
6350 disk_key = (struct btrfs_disk_key *)array_ptr;
6351 len = sizeof(*disk_key);
6352 if (cur_offset + len > array_size)
6353 goto out_short_read;
6355 btrfs_disk_key_to_cpu(&key, disk_key);
6358 sb_array_offset += len;
6361 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6362 chunk = (struct btrfs_chunk *)sb_array_offset;
6364 * At least one btrfs_chunk with one stripe must be
6365 * present, exact stripe count check comes afterwards
6367 len = btrfs_chunk_item_size(1);
6368 if (cur_offset + len > array_size)
6369 goto out_short_read;
6371 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6372 len = btrfs_chunk_item_size(num_stripes);
6373 if (cur_offset + len > array_size)
6374 goto out_short_read;
6376 ret = read_one_chunk(root, &key, sb, chunk);
6384 sb_array_offset += len;
6387 free_extent_buffer(sb);
6391 printk(KERN_ERR "BTRFS: sys_array too short to read %u bytes at offset %u\n",
6393 free_extent_buffer(sb);
6397 int btrfs_read_chunk_tree(struct btrfs_root *root)
6399 struct btrfs_path *path;
6400 struct extent_buffer *leaf;
6401 struct btrfs_key key;
6402 struct btrfs_key found_key;
6406 root = root->fs_info->chunk_root;
6408 path = btrfs_alloc_path();
6412 mutex_lock(&uuid_mutex);
6416 * Read all device items, and then all the chunk items. All
6417 * device items are found before any chunk item (their object id
6418 * is smaller than the lowest possible object id for a chunk
6419 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6421 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6424 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6428 leaf = path->nodes[0];
6429 slot = path->slots[0];
6430 if (slot >= btrfs_header_nritems(leaf)) {
6431 ret = btrfs_next_leaf(root, path);
6438 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6439 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6440 struct btrfs_dev_item *dev_item;
6441 dev_item = btrfs_item_ptr(leaf, slot,
6442 struct btrfs_dev_item);
6443 ret = read_one_dev(root, leaf, dev_item);
6446 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6447 struct btrfs_chunk *chunk;
6448 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6449 ret = read_one_chunk(root, &found_key, leaf, chunk);
6457 unlock_chunks(root);
6458 mutex_unlock(&uuid_mutex);
6460 btrfs_free_path(path);
6464 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6466 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6467 struct btrfs_device *device;
6469 while (fs_devices) {
6470 mutex_lock(&fs_devices->device_list_mutex);
6471 list_for_each_entry(device, &fs_devices->devices, dev_list)
6472 device->dev_root = fs_info->dev_root;
6473 mutex_unlock(&fs_devices->device_list_mutex);
6475 fs_devices = fs_devices->seed;
6479 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
6483 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6484 btrfs_dev_stat_reset(dev, i);
6487 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
6489 struct btrfs_key key;
6490 struct btrfs_key found_key;
6491 struct btrfs_root *dev_root = fs_info->dev_root;
6492 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6493 struct extent_buffer *eb;
6496 struct btrfs_device *device;
6497 struct btrfs_path *path = NULL;
6500 path = btrfs_alloc_path();
6506 mutex_lock(&fs_devices->device_list_mutex);
6507 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6509 struct btrfs_dev_stats_item *ptr;
6512 key.type = BTRFS_DEV_STATS_KEY;
6513 key.offset = device->devid;
6514 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
6516 __btrfs_reset_dev_stats(device);
6517 device->dev_stats_valid = 1;
6518 btrfs_release_path(path);
6521 slot = path->slots[0];
6522 eb = path->nodes[0];
6523 btrfs_item_key_to_cpu(eb, &found_key, slot);
6524 item_size = btrfs_item_size_nr(eb, slot);
6526 ptr = btrfs_item_ptr(eb, slot,
6527 struct btrfs_dev_stats_item);
6529 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6530 if (item_size >= (1 + i) * sizeof(__le64))
6531 btrfs_dev_stat_set(device, i,
6532 btrfs_dev_stats_value(eb, ptr, i));
6534 btrfs_dev_stat_reset(device, i);
6537 device->dev_stats_valid = 1;
6538 btrfs_dev_stat_print_on_load(device);
6539 btrfs_release_path(path);
6541 mutex_unlock(&fs_devices->device_list_mutex);
6544 btrfs_free_path(path);
6545 return ret < 0 ? ret : 0;
6548 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
6549 struct btrfs_root *dev_root,
6550 struct btrfs_device *device)
6552 struct btrfs_path *path;
6553 struct btrfs_key key;
6554 struct extent_buffer *eb;
6555 struct btrfs_dev_stats_item *ptr;
6560 key.type = BTRFS_DEV_STATS_KEY;
6561 key.offset = device->devid;
6563 path = btrfs_alloc_path();
6565 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
6567 printk_in_rcu(KERN_WARNING "BTRFS: "
6568 "error %d while searching for dev_stats item for device %s!\n",
6569 ret, rcu_str_deref(device->name));
6574 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
6575 /* need to delete old one and insert a new one */
6576 ret = btrfs_del_item(trans, dev_root, path);
6578 printk_in_rcu(KERN_WARNING "BTRFS: "
6579 "delete too small dev_stats item for device %s failed %d!\n",
6580 rcu_str_deref(device->name), ret);
6587 /* need to insert a new item */
6588 btrfs_release_path(path);
6589 ret = btrfs_insert_empty_item(trans, dev_root, path,
6590 &key, sizeof(*ptr));
6592 printk_in_rcu(KERN_WARNING "BTRFS: "
6593 "insert dev_stats item for device %s failed %d!\n",
6594 rcu_str_deref(device->name), ret);
6599 eb = path->nodes[0];
6600 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
6601 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6602 btrfs_set_dev_stats_value(eb, ptr, i,
6603 btrfs_dev_stat_read(device, i));
6604 btrfs_mark_buffer_dirty(eb);
6607 btrfs_free_path(path);
6612 * called from commit_transaction. Writes all changed device stats to disk.
6614 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
6615 struct btrfs_fs_info *fs_info)
6617 struct btrfs_root *dev_root = fs_info->dev_root;
6618 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6619 struct btrfs_device *device;
6623 mutex_lock(&fs_devices->device_list_mutex);
6624 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6625 if (!device->dev_stats_valid || !btrfs_dev_stats_dirty(device))
6628 stats_cnt = atomic_read(&device->dev_stats_ccnt);
6629 ret = update_dev_stat_item(trans, dev_root, device);
6631 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
6633 mutex_unlock(&fs_devices->device_list_mutex);
6638 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
6640 btrfs_dev_stat_inc(dev, index);
6641 btrfs_dev_stat_print_on_error(dev);
6644 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
6646 if (!dev->dev_stats_valid)
6648 printk_ratelimited_in_rcu(KERN_ERR "BTRFS: "
6649 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
6650 rcu_str_deref(dev->name),
6651 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6652 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6653 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6654 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6655 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6658 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
6662 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6663 if (btrfs_dev_stat_read(dev, i) != 0)
6665 if (i == BTRFS_DEV_STAT_VALUES_MAX)
6666 return; /* all values == 0, suppress message */
6668 printk_in_rcu(KERN_INFO "BTRFS: "
6669 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
6670 rcu_str_deref(dev->name),
6671 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6672 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6673 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6674 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6675 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6678 int btrfs_get_dev_stats(struct btrfs_root *root,
6679 struct btrfs_ioctl_get_dev_stats *stats)
6681 struct btrfs_device *dev;
6682 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
6685 mutex_lock(&fs_devices->device_list_mutex);
6686 dev = btrfs_find_device(root->fs_info, stats->devid, NULL, NULL);
6687 mutex_unlock(&fs_devices->device_list_mutex);
6690 btrfs_warn(root->fs_info, "get dev_stats failed, device not found");
6692 } else if (!dev->dev_stats_valid) {
6693 btrfs_warn(root->fs_info, "get dev_stats failed, not yet valid");
6695 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
6696 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6697 if (stats->nr_items > i)
6699 btrfs_dev_stat_read_and_reset(dev, i);
6701 btrfs_dev_stat_reset(dev, i);
6704 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6705 if (stats->nr_items > i)
6706 stats->values[i] = btrfs_dev_stat_read(dev, i);
6708 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
6709 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
6713 void btrfs_scratch_superblocks(struct block_device *bdev, char *device_path)
6715 struct buffer_head *bh;
6716 struct btrfs_super_block *disk_super;
6722 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
6725 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
6728 disk_super = (struct btrfs_super_block *)bh->b_data;
6730 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
6731 set_buffer_dirty(bh);
6732 sync_dirty_buffer(bh);
6736 /* Notify udev that device has changed */
6737 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
6739 /* Update ctime/mtime for device path for libblkid */
6740 update_dev_time(device_path);
6744 * Update the size of all devices, which is used for writing out the
6747 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
6749 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6750 struct btrfs_device *curr, *next;
6752 if (list_empty(&fs_devices->resized_devices))
6755 mutex_lock(&fs_devices->device_list_mutex);
6756 lock_chunks(fs_info->dev_root);
6757 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
6759 list_del_init(&curr->resized_list);
6760 curr->commit_total_bytes = curr->disk_total_bytes;
6762 unlock_chunks(fs_info->dev_root);
6763 mutex_unlock(&fs_devices->device_list_mutex);
6766 /* Must be invoked during the transaction commit */
6767 void btrfs_update_commit_device_bytes_used(struct btrfs_root *root,
6768 struct btrfs_transaction *transaction)
6770 struct extent_map *em;
6771 struct map_lookup *map;
6772 struct btrfs_device *dev;
6775 if (list_empty(&transaction->pending_chunks))
6778 /* In order to kick the device replace finish process */
6780 list_for_each_entry(em, &transaction->pending_chunks, list) {
6781 map = (struct map_lookup *)em->bdev;
6783 for (i = 0; i < map->num_stripes; i++) {
6784 dev = map->stripes[i].dev;
6785 dev->commit_bytes_used = dev->bytes_used;
6788 unlock_chunks(root);
6791 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
6793 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6794 while (fs_devices) {
6795 fs_devices->fs_info = fs_info;
6796 fs_devices = fs_devices->seed;
6800 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
6802 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6803 while (fs_devices) {
6804 fs_devices->fs_info = NULL;
6805 fs_devices = fs_devices->seed;
6809 void btrfs_close_one_device(struct btrfs_device *device)
6811 struct btrfs_fs_devices *fs_devices = device->fs_devices;
6812 struct btrfs_device *new_device;
6813 struct rcu_string *name;
6816 fs_devices->open_devices--;
6818 if (device->writeable &&
6819 device->devid != BTRFS_DEV_REPLACE_DEVID) {
6820 list_del_init(&device->dev_alloc_list);
6821 fs_devices->rw_devices--;
6824 if (device->missing)
6825 fs_devices->missing_devices--;
6827 new_device = btrfs_alloc_device(NULL, &device->devid,
6829 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
6831 /* Safe because we are under uuid_mutex */
6833 name = rcu_string_strdup(device->name->str, GFP_NOFS);
6834 BUG_ON(!name); /* -ENOMEM */
6835 rcu_assign_pointer(new_device->name, name);
6838 list_replace_rcu(&device->dev_list, &new_device->dev_list);
6839 new_device->fs_devices = device->fs_devices;
6841 call_rcu(&device->rcu, free_device);