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);
56 static void lock_chunks(struct btrfs_root *root)
58 mutex_lock(&root->fs_info->chunk_mutex);
61 static void unlock_chunks(struct btrfs_root *root)
63 mutex_unlock(&root->fs_info->chunk_mutex);
66 static struct btrfs_fs_devices *__alloc_fs_devices(void)
68 struct btrfs_fs_devices *fs_devs;
70 fs_devs = kzalloc(sizeof(*fs_devs), GFP_NOFS);
72 return ERR_PTR(-ENOMEM);
74 mutex_init(&fs_devs->device_list_mutex);
76 INIT_LIST_HEAD(&fs_devs->devices);
77 INIT_LIST_HEAD(&fs_devs->resized_devices);
78 INIT_LIST_HEAD(&fs_devs->alloc_list);
79 INIT_LIST_HEAD(&fs_devs->list);
85 * alloc_fs_devices - allocate struct btrfs_fs_devices
86 * @fsid: a pointer to UUID for this FS. If NULL a new UUID is
89 * Return: a pointer to a new &struct btrfs_fs_devices on success;
90 * ERR_PTR() on error. Returned struct is not linked onto any lists and
91 * can be destroyed with kfree() right away.
93 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
95 struct btrfs_fs_devices *fs_devs;
97 fs_devs = __alloc_fs_devices();
102 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
104 generate_random_uuid(fs_devs->fsid);
109 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
111 struct btrfs_device *device;
112 WARN_ON(fs_devices->opened);
113 while (!list_empty(&fs_devices->devices)) {
114 device = list_entry(fs_devices->devices.next,
115 struct btrfs_device, dev_list);
116 list_del(&device->dev_list);
117 rcu_string_free(device->name);
123 static void btrfs_kobject_uevent(struct block_device *bdev,
124 enum kobject_action action)
128 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
130 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
132 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
133 &disk_to_dev(bdev->bd_disk)->kobj);
136 void btrfs_cleanup_fs_uuids(void)
138 struct btrfs_fs_devices *fs_devices;
140 while (!list_empty(&fs_uuids)) {
141 fs_devices = list_entry(fs_uuids.next,
142 struct btrfs_fs_devices, list);
143 list_del(&fs_devices->list);
144 free_fs_devices(fs_devices);
148 static struct btrfs_device *__alloc_device(void)
150 struct btrfs_device *dev;
152 dev = kzalloc(sizeof(*dev), GFP_NOFS);
154 return ERR_PTR(-ENOMEM);
156 INIT_LIST_HEAD(&dev->dev_list);
157 INIT_LIST_HEAD(&dev->dev_alloc_list);
158 INIT_LIST_HEAD(&dev->resized_list);
160 spin_lock_init(&dev->io_lock);
162 spin_lock_init(&dev->reada_lock);
163 atomic_set(&dev->reada_in_flight, 0);
164 atomic_set(&dev->dev_stats_ccnt, 0);
165 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_WAIT);
166 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_WAIT);
171 static noinline struct btrfs_device *__find_device(struct list_head *head,
174 struct btrfs_device *dev;
176 list_for_each_entry(dev, head, dev_list) {
177 if (dev->devid == devid &&
178 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
185 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
187 struct btrfs_fs_devices *fs_devices;
189 list_for_each_entry(fs_devices, &fs_uuids, list) {
190 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
197 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
198 int flush, struct block_device **bdev,
199 struct buffer_head **bh)
203 *bdev = blkdev_get_by_path(device_path, flags, holder);
206 ret = PTR_ERR(*bdev);
207 printk(KERN_INFO "BTRFS: open %s failed\n", device_path);
212 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
213 ret = set_blocksize(*bdev, 4096);
215 blkdev_put(*bdev, flags);
218 invalidate_bdev(*bdev);
219 *bh = btrfs_read_dev_super(*bdev);
222 blkdev_put(*bdev, flags);
234 static void requeue_list(struct btrfs_pending_bios *pending_bios,
235 struct bio *head, struct bio *tail)
238 struct bio *old_head;
240 old_head = pending_bios->head;
241 pending_bios->head = head;
242 if (pending_bios->tail)
243 tail->bi_next = old_head;
245 pending_bios->tail = tail;
249 * we try to collect pending bios for a device so we don't get a large
250 * number of procs sending bios down to the same device. This greatly
251 * improves the schedulers ability to collect and merge the bios.
253 * But, it also turns into a long list of bios to process and that is sure
254 * to eventually make the worker thread block. The solution here is to
255 * make some progress and then put this work struct back at the end of
256 * the list if the block device is congested. This way, multiple devices
257 * can make progress from a single worker thread.
259 static noinline void run_scheduled_bios(struct btrfs_device *device)
262 struct backing_dev_info *bdi;
263 struct btrfs_fs_info *fs_info;
264 struct btrfs_pending_bios *pending_bios;
268 unsigned long num_run;
269 unsigned long batch_run = 0;
271 unsigned long last_waited = 0;
273 int sync_pending = 0;
274 struct blk_plug plug;
277 * this function runs all the bios we've collected for
278 * a particular device. We don't want to wander off to
279 * another device without first sending all of these down.
280 * So, setup a plug here and finish it off before we return
282 blk_start_plug(&plug);
284 bdi = blk_get_backing_dev_info(device->bdev);
285 fs_info = device->dev_root->fs_info;
286 limit = btrfs_async_submit_limit(fs_info);
287 limit = limit * 2 / 3;
290 spin_lock(&device->io_lock);
295 /* take all the bios off the list at once and process them
296 * later on (without the lock held). But, remember the
297 * tail and other pointers so the bios can be properly reinserted
298 * into the list if we hit congestion
300 if (!force_reg && device->pending_sync_bios.head) {
301 pending_bios = &device->pending_sync_bios;
304 pending_bios = &device->pending_bios;
308 pending = pending_bios->head;
309 tail = pending_bios->tail;
310 WARN_ON(pending && !tail);
313 * if pending was null this time around, no bios need processing
314 * at all and we can stop. Otherwise it'll loop back up again
315 * and do an additional check so no bios are missed.
317 * device->running_pending is used to synchronize with the
320 if (device->pending_sync_bios.head == NULL &&
321 device->pending_bios.head == NULL) {
323 device->running_pending = 0;
326 device->running_pending = 1;
329 pending_bios->head = NULL;
330 pending_bios->tail = NULL;
332 spin_unlock(&device->io_lock);
337 /* we want to work on both lists, but do more bios on the
338 * sync list than the regular list
341 pending_bios != &device->pending_sync_bios &&
342 device->pending_sync_bios.head) ||
343 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
344 device->pending_bios.head)) {
345 spin_lock(&device->io_lock);
346 requeue_list(pending_bios, pending, tail);
351 pending = pending->bi_next;
354 if (atomic_dec_return(&fs_info->nr_async_bios) < limit &&
355 waitqueue_active(&fs_info->async_submit_wait))
356 wake_up(&fs_info->async_submit_wait);
358 BUG_ON(atomic_read(&cur->bi_cnt) == 0);
361 * if we're doing the sync list, record that our
362 * plug has some sync requests on it
364 * If we're doing the regular list and there are
365 * sync requests sitting around, unplug before
368 if (pending_bios == &device->pending_sync_bios) {
370 } else if (sync_pending) {
371 blk_finish_plug(&plug);
372 blk_start_plug(&plug);
376 btrfsic_submit_bio(cur->bi_rw, cur);
383 * we made progress, there is more work to do and the bdi
384 * is now congested. Back off and let other work structs
387 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
388 fs_info->fs_devices->open_devices > 1) {
389 struct io_context *ioc;
391 ioc = current->io_context;
394 * the main goal here is that we don't want to
395 * block if we're going to be able to submit
396 * more requests without blocking.
398 * This code does two great things, it pokes into
399 * the elevator code from a filesystem _and_
400 * it makes assumptions about how batching works.
402 if (ioc && ioc->nr_batch_requests > 0 &&
403 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
405 ioc->last_waited == last_waited)) {
407 * we want to go through our batch of
408 * requests and stop. So, we copy out
409 * the ioc->last_waited time and test
410 * against it before looping
412 last_waited = ioc->last_waited;
417 spin_lock(&device->io_lock);
418 requeue_list(pending_bios, pending, tail);
419 device->running_pending = 1;
421 spin_unlock(&device->io_lock);
422 btrfs_queue_work(fs_info->submit_workers,
426 /* unplug every 64 requests just for good measure */
427 if (batch_run % 64 == 0) {
428 blk_finish_plug(&plug);
429 blk_start_plug(&plug);
438 spin_lock(&device->io_lock);
439 if (device->pending_bios.head || device->pending_sync_bios.head)
441 spin_unlock(&device->io_lock);
444 blk_finish_plug(&plug);
447 static void pending_bios_fn(struct btrfs_work *work)
449 struct btrfs_device *device;
451 device = container_of(work, struct btrfs_device, work);
452 run_scheduled_bios(device);
456 * Add new device to list of registered devices
459 * 1 - first time device is seen
460 * 0 - device already known
463 static noinline int device_list_add(const char *path,
464 struct btrfs_super_block *disk_super,
465 u64 devid, struct btrfs_fs_devices **fs_devices_ret)
467 struct btrfs_device *device;
468 struct btrfs_fs_devices *fs_devices;
469 struct rcu_string *name;
471 u64 found_transid = btrfs_super_generation(disk_super);
473 fs_devices = find_fsid(disk_super->fsid);
475 fs_devices = alloc_fs_devices(disk_super->fsid);
476 if (IS_ERR(fs_devices))
477 return PTR_ERR(fs_devices);
479 list_add(&fs_devices->list, &fs_uuids);
483 device = __find_device(&fs_devices->devices, devid,
484 disk_super->dev_item.uuid);
488 if (fs_devices->opened)
491 device = btrfs_alloc_device(NULL, &devid,
492 disk_super->dev_item.uuid);
493 if (IS_ERR(device)) {
494 /* we can safely leave the fs_devices entry around */
495 return PTR_ERR(device);
498 name = rcu_string_strdup(path, GFP_NOFS);
503 rcu_assign_pointer(device->name, name);
505 mutex_lock(&fs_devices->device_list_mutex);
506 list_add_rcu(&device->dev_list, &fs_devices->devices);
507 fs_devices->num_devices++;
508 mutex_unlock(&fs_devices->device_list_mutex);
511 device->fs_devices = fs_devices;
512 } else if (!device->name || strcmp(device->name->str, path)) {
514 * When FS is already mounted.
515 * 1. If you are here and if the device->name is NULL that
516 * means this device was missing at time of FS mount.
517 * 2. If you are here and if the device->name is different
518 * from 'path' that means either
519 * a. The same device disappeared and reappeared with
521 * b. The missing-disk-which-was-replaced, has
524 * We must allow 1 and 2a above. But 2b would be a spurious
527 * Further in case of 1 and 2a above, the disk at 'path'
528 * would have missed some transaction when it was away and
529 * in case of 2a the stale bdev has to be updated as well.
530 * 2b must not be allowed at all time.
534 * As of now don't allow update to btrfs_fs_device through
535 * the btrfs dev scan cli, after FS has been mounted.
537 if (fs_devices->opened) {
541 * That is if the FS is _not_ mounted and if you
542 * are here, that means there is more than one
543 * disk with same uuid and devid.We keep the one
544 * with larger generation number or the last-in if
545 * generation are equal.
547 if (found_transid < device->generation)
551 name = rcu_string_strdup(path, GFP_NOFS);
554 rcu_string_free(device->name);
555 rcu_assign_pointer(device->name, name);
556 if (device->missing) {
557 fs_devices->missing_devices--;
563 * Unmount does not free the btrfs_device struct but would zero
564 * generation along with most of the other members. So just update
565 * it back. We need it to pick the disk with largest generation
568 if (!fs_devices->opened)
569 device->generation = found_transid;
571 *fs_devices_ret = fs_devices;
576 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
578 struct btrfs_fs_devices *fs_devices;
579 struct btrfs_device *device;
580 struct btrfs_device *orig_dev;
582 fs_devices = alloc_fs_devices(orig->fsid);
583 if (IS_ERR(fs_devices))
586 mutex_lock(&orig->device_list_mutex);
587 fs_devices->total_devices = orig->total_devices;
589 /* We have held the volume lock, it is safe to get the devices. */
590 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
591 struct rcu_string *name;
593 device = btrfs_alloc_device(NULL, &orig_dev->devid,
599 * This is ok to do without rcu read locked because we hold the
600 * uuid mutex so nothing we touch in here is going to disappear.
602 if (orig_dev->name) {
603 name = rcu_string_strdup(orig_dev->name->str, GFP_NOFS);
608 rcu_assign_pointer(device->name, name);
611 list_add(&device->dev_list, &fs_devices->devices);
612 device->fs_devices = fs_devices;
613 fs_devices->num_devices++;
615 mutex_unlock(&orig->device_list_mutex);
618 mutex_unlock(&orig->device_list_mutex);
619 free_fs_devices(fs_devices);
620 return ERR_PTR(-ENOMEM);
623 void btrfs_close_extra_devices(struct btrfs_fs_info *fs_info,
624 struct btrfs_fs_devices *fs_devices, int step)
626 struct btrfs_device *device, *next;
627 struct btrfs_device *latest_dev = NULL;
629 mutex_lock(&uuid_mutex);
631 /* This is the initialized path, it is safe to release the devices. */
632 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
633 if (device->in_fs_metadata) {
634 if (!device->is_tgtdev_for_dev_replace &&
636 device->generation > latest_dev->generation)) {
642 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
644 * In the first step, keep the device which has
645 * the correct fsid and the devid that is used
646 * for the dev_replace procedure.
647 * In the second step, the dev_replace state is
648 * read from the device tree and it is known
649 * whether the procedure is really active or
650 * not, which means whether this device is
651 * used or whether it should be removed.
653 if (step == 0 || device->is_tgtdev_for_dev_replace) {
658 blkdev_put(device->bdev, device->mode);
660 fs_devices->open_devices--;
662 if (device->writeable) {
663 list_del_init(&device->dev_alloc_list);
664 device->writeable = 0;
665 if (!device->is_tgtdev_for_dev_replace)
666 fs_devices->rw_devices--;
668 list_del_init(&device->dev_list);
669 fs_devices->num_devices--;
670 rcu_string_free(device->name);
674 if (fs_devices->seed) {
675 fs_devices = fs_devices->seed;
679 fs_devices->latest_bdev = latest_dev->bdev;
681 mutex_unlock(&uuid_mutex);
684 static void __free_device(struct work_struct *work)
686 struct btrfs_device *device;
688 device = container_of(work, struct btrfs_device, rcu_work);
691 blkdev_put(device->bdev, device->mode);
693 rcu_string_free(device->name);
697 static void free_device(struct rcu_head *head)
699 struct btrfs_device *device;
701 device = container_of(head, struct btrfs_device, rcu);
703 INIT_WORK(&device->rcu_work, __free_device);
704 schedule_work(&device->rcu_work);
707 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
709 struct btrfs_device *device;
711 if (--fs_devices->opened > 0)
714 mutex_lock(&fs_devices->device_list_mutex);
715 list_for_each_entry(device, &fs_devices->devices, dev_list) {
716 struct btrfs_device *new_device;
717 struct rcu_string *name;
720 fs_devices->open_devices--;
722 if (device->writeable &&
723 device->devid != BTRFS_DEV_REPLACE_DEVID) {
724 list_del_init(&device->dev_alloc_list);
725 fs_devices->rw_devices--;
729 fs_devices->missing_devices--;
731 new_device = btrfs_alloc_device(NULL, &device->devid,
733 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
735 /* Safe because we are under uuid_mutex */
737 name = rcu_string_strdup(device->name->str, GFP_NOFS);
738 BUG_ON(!name); /* -ENOMEM */
739 rcu_assign_pointer(new_device->name, name);
742 list_replace_rcu(&device->dev_list, &new_device->dev_list);
743 new_device->fs_devices = device->fs_devices;
745 call_rcu(&device->rcu, free_device);
747 mutex_unlock(&fs_devices->device_list_mutex);
749 WARN_ON(fs_devices->open_devices);
750 WARN_ON(fs_devices->rw_devices);
751 fs_devices->opened = 0;
752 fs_devices->seeding = 0;
757 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
759 struct btrfs_fs_devices *seed_devices = NULL;
762 mutex_lock(&uuid_mutex);
763 ret = __btrfs_close_devices(fs_devices);
764 if (!fs_devices->opened) {
765 seed_devices = fs_devices->seed;
766 fs_devices->seed = NULL;
768 mutex_unlock(&uuid_mutex);
770 while (seed_devices) {
771 fs_devices = seed_devices;
772 seed_devices = fs_devices->seed;
773 __btrfs_close_devices(fs_devices);
774 free_fs_devices(fs_devices);
777 * Wait for rcu kworkers under __btrfs_close_devices
778 * to finish all blkdev_puts so device is really
779 * free when umount is done.
785 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
786 fmode_t flags, void *holder)
788 struct request_queue *q;
789 struct block_device *bdev;
790 struct list_head *head = &fs_devices->devices;
791 struct btrfs_device *device;
792 struct btrfs_device *latest_dev = NULL;
793 struct buffer_head *bh;
794 struct btrfs_super_block *disk_super;
801 list_for_each_entry(device, head, dev_list) {
807 /* Just open everything we can; ignore failures here */
808 if (btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
812 disk_super = (struct btrfs_super_block *)bh->b_data;
813 devid = btrfs_stack_device_id(&disk_super->dev_item);
814 if (devid != device->devid)
817 if (memcmp(device->uuid, disk_super->dev_item.uuid,
821 device->generation = btrfs_super_generation(disk_super);
823 device->generation > latest_dev->generation)
826 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
827 device->writeable = 0;
829 device->writeable = !bdev_read_only(bdev);
833 q = bdev_get_queue(bdev);
834 if (blk_queue_discard(q))
835 device->can_discard = 1;
838 device->in_fs_metadata = 0;
839 device->mode = flags;
841 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
842 fs_devices->rotating = 1;
844 fs_devices->open_devices++;
845 if (device->writeable &&
846 device->devid != BTRFS_DEV_REPLACE_DEVID) {
847 fs_devices->rw_devices++;
848 list_add(&device->dev_alloc_list,
849 &fs_devices->alloc_list);
856 blkdev_put(bdev, flags);
859 if (fs_devices->open_devices == 0) {
863 fs_devices->seeding = seeding;
864 fs_devices->opened = 1;
865 fs_devices->latest_bdev = latest_dev->bdev;
866 fs_devices->total_rw_bytes = 0;
871 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
872 fmode_t flags, void *holder)
876 mutex_lock(&uuid_mutex);
877 if (fs_devices->opened) {
878 fs_devices->opened++;
881 ret = __btrfs_open_devices(fs_devices, flags, holder);
883 mutex_unlock(&uuid_mutex);
888 * Look for a btrfs signature on a device. This may be called out of the mount path
889 * and we are not allowed to call set_blocksize during the scan. The superblock
890 * is read via pagecache
892 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
893 struct btrfs_fs_devices **fs_devices_ret)
895 struct btrfs_super_block *disk_super;
896 struct block_device *bdev;
907 * we would like to check all the supers, but that would make
908 * a btrfs mount succeed after a mkfs from a different FS.
909 * So, we need to add a special mount option to scan for
910 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
912 bytenr = btrfs_sb_offset(0);
914 mutex_lock(&uuid_mutex);
916 bdev = blkdev_get_by_path(path, flags, holder);
923 /* make sure our super fits in the device */
924 if (bytenr + PAGE_CACHE_SIZE >= i_size_read(bdev->bd_inode))
927 /* make sure our super fits in the page */
928 if (sizeof(*disk_super) > PAGE_CACHE_SIZE)
931 /* make sure our super doesn't straddle pages on disk */
932 index = bytenr >> PAGE_CACHE_SHIFT;
933 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_CACHE_SHIFT != index)
936 /* pull in the page with our super */
937 page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
940 if (IS_ERR_OR_NULL(page))
945 /* align our pointer to the offset of the super block */
946 disk_super = p + (bytenr & ~PAGE_CACHE_MASK);
948 if (btrfs_super_bytenr(disk_super) != bytenr ||
949 btrfs_super_magic(disk_super) != BTRFS_MAGIC)
952 devid = btrfs_stack_device_id(&disk_super->dev_item);
953 transid = btrfs_super_generation(disk_super);
954 total_devices = btrfs_super_num_devices(disk_super);
956 ret = device_list_add(path, disk_super, devid, fs_devices_ret);
958 if (disk_super->label[0]) {
959 if (disk_super->label[BTRFS_LABEL_SIZE - 1])
960 disk_super->label[BTRFS_LABEL_SIZE - 1] = '\0';
961 printk(KERN_INFO "BTRFS: device label %s ", disk_super->label);
963 printk(KERN_INFO "BTRFS: device fsid %pU ", disk_super->fsid);
966 printk(KERN_CONT "devid %llu transid %llu %s\n", devid, transid, path);
969 if (!ret && fs_devices_ret)
970 (*fs_devices_ret)->total_devices = total_devices;
974 page_cache_release(page);
977 blkdev_put(bdev, flags);
979 mutex_unlock(&uuid_mutex);
983 /* helper to account the used device space in the range */
984 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
985 u64 end, u64 *length)
987 struct btrfs_key key;
988 struct btrfs_root *root = device->dev_root;
989 struct btrfs_dev_extent *dev_extent;
990 struct btrfs_path *path;
994 struct extent_buffer *l;
998 if (start >= device->total_bytes || device->is_tgtdev_for_dev_replace)
1001 path = btrfs_alloc_path();
1006 key.objectid = device->devid;
1008 key.type = BTRFS_DEV_EXTENT_KEY;
1010 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1014 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1021 slot = path->slots[0];
1022 if (slot >= btrfs_header_nritems(l)) {
1023 ret = btrfs_next_leaf(root, path);
1031 btrfs_item_key_to_cpu(l, &key, slot);
1033 if (key.objectid < device->devid)
1036 if (key.objectid > device->devid)
1039 if (key.type != BTRFS_DEV_EXTENT_KEY)
1042 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1043 extent_end = key.offset + btrfs_dev_extent_length(l,
1045 if (key.offset <= start && extent_end > end) {
1046 *length = end - start + 1;
1048 } else if (key.offset <= start && extent_end > start)
1049 *length += extent_end - start;
1050 else if (key.offset > start && extent_end <= end)
1051 *length += extent_end - key.offset;
1052 else if (key.offset > start && key.offset <= end) {
1053 *length += end - key.offset + 1;
1055 } else if (key.offset > end)
1063 btrfs_free_path(path);
1067 static int contains_pending_extent(struct btrfs_trans_handle *trans,
1068 struct btrfs_device *device,
1069 u64 *start, u64 len)
1071 struct extent_map *em;
1074 list_for_each_entry(em, &trans->transaction->pending_chunks, list) {
1075 struct map_lookup *map;
1078 map = (struct map_lookup *)em->bdev;
1079 for (i = 0; i < map->num_stripes; i++) {
1080 if (map->stripes[i].dev != device)
1082 if (map->stripes[i].physical >= *start + len ||
1083 map->stripes[i].physical + em->orig_block_len <=
1086 *start = map->stripes[i].physical +
1097 * find_free_dev_extent - find free space in the specified device
1098 * @device: the device which we search the free space in
1099 * @num_bytes: the size of the free space that we need
1100 * @start: store the start of the free space.
1101 * @len: the size of the free space. that we find, or the size of the max
1102 * free space if we don't find suitable free space
1104 * this uses a pretty simple search, the expectation is that it is
1105 * called very infrequently and that a given device has a small number
1108 * @start is used to store the start of the free space if we find. But if we
1109 * don't find suitable free space, it will be used to store the start position
1110 * of the max free space.
1112 * @len is used to store the size of the free space that we find.
1113 * But if we don't find suitable free space, it is used to store the size of
1114 * the max free space.
1116 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1117 struct btrfs_device *device, u64 num_bytes,
1118 u64 *start, u64 *len)
1120 struct btrfs_key key;
1121 struct btrfs_root *root = device->dev_root;
1122 struct btrfs_dev_extent *dev_extent;
1123 struct btrfs_path *path;
1129 u64 search_end = device->total_bytes;
1132 struct extent_buffer *l;
1134 /* FIXME use last free of some kind */
1136 /* we don't want to overwrite the superblock on the drive,
1137 * so we make sure to start at an offset of at least 1MB
1139 search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
1141 path = btrfs_alloc_path();
1145 max_hole_start = search_start;
1149 if (search_start >= search_end || device->is_tgtdev_for_dev_replace) {
1155 path->search_commit_root = 1;
1156 path->skip_locking = 1;
1158 key.objectid = device->devid;
1159 key.offset = search_start;
1160 key.type = BTRFS_DEV_EXTENT_KEY;
1162 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1166 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1173 slot = path->slots[0];
1174 if (slot >= btrfs_header_nritems(l)) {
1175 ret = btrfs_next_leaf(root, path);
1183 btrfs_item_key_to_cpu(l, &key, slot);
1185 if (key.objectid < device->devid)
1188 if (key.objectid > device->devid)
1191 if (key.type != BTRFS_DEV_EXTENT_KEY)
1194 if (key.offset > search_start) {
1195 hole_size = key.offset - search_start;
1198 * Have to check before we set max_hole_start, otherwise
1199 * we could end up sending back this offset anyway.
1201 if (contains_pending_extent(trans, device,
1206 if (hole_size > max_hole_size) {
1207 max_hole_start = search_start;
1208 max_hole_size = hole_size;
1212 * If this free space is greater than which we need,
1213 * it must be the max free space that we have found
1214 * until now, so max_hole_start must point to the start
1215 * of this free space and the length of this free space
1216 * is stored in max_hole_size. Thus, we return
1217 * max_hole_start and max_hole_size and go back to the
1220 if (hole_size >= num_bytes) {
1226 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1227 extent_end = key.offset + btrfs_dev_extent_length(l,
1229 if (extent_end > search_start)
1230 search_start = extent_end;
1237 * At this point, search_start should be the end of
1238 * allocated dev extents, and when shrinking the device,
1239 * search_end may be smaller than search_start.
1241 if (search_end > search_start)
1242 hole_size = search_end - search_start;
1244 if (hole_size > max_hole_size) {
1245 max_hole_start = search_start;
1246 max_hole_size = hole_size;
1249 if (contains_pending_extent(trans, device, &search_start, hole_size)) {
1250 btrfs_release_path(path);
1255 if (hole_size < num_bytes)
1261 btrfs_free_path(path);
1262 *start = max_hole_start;
1264 *len = max_hole_size;
1268 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1269 struct btrfs_device *device,
1270 u64 start, u64 *dev_extent_len)
1273 struct btrfs_path *path;
1274 struct btrfs_root *root = device->dev_root;
1275 struct btrfs_key key;
1276 struct btrfs_key found_key;
1277 struct extent_buffer *leaf = NULL;
1278 struct btrfs_dev_extent *extent = NULL;
1280 path = btrfs_alloc_path();
1284 key.objectid = device->devid;
1286 key.type = BTRFS_DEV_EXTENT_KEY;
1288 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1290 ret = btrfs_previous_item(root, path, key.objectid,
1291 BTRFS_DEV_EXTENT_KEY);
1294 leaf = path->nodes[0];
1295 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1296 extent = btrfs_item_ptr(leaf, path->slots[0],
1297 struct btrfs_dev_extent);
1298 BUG_ON(found_key.offset > start || found_key.offset +
1299 btrfs_dev_extent_length(leaf, extent) < start);
1301 btrfs_release_path(path);
1303 } else if (ret == 0) {
1304 leaf = path->nodes[0];
1305 extent = btrfs_item_ptr(leaf, path->slots[0],
1306 struct btrfs_dev_extent);
1308 btrfs_error(root->fs_info, ret, "Slot search failed");
1312 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1314 ret = btrfs_del_item(trans, root, path);
1316 btrfs_error(root->fs_info, ret,
1317 "Failed to remove dev extent item");
1320 btrfs_free_path(path);
1324 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1325 struct btrfs_device *device,
1326 u64 chunk_tree, u64 chunk_objectid,
1327 u64 chunk_offset, u64 start, u64 num_bytes)
1330 struct btrfs_path *path;
1331 struct btrfs_root *root = device->dev_root;
1332 struct btrfs_dev_extent *extent;
1333 struct extent_buffer *leaf;
1334 struct btrfs_key key;
1336 WARN_ON(!device->in_fs_metadata);
1337 WARN_ON(device->is_tgtdev_for_dev_replace);
1338 path = btrfs_alloc_path();
1342 key.objectid = device->devid;
1344 key.type = BTRFS_DEV_EXTENT_KEY;
1345 ret = btrfs_insert_empty_item(trans, root, path, &key,
1350 leaf = path->nodes[0];
1351 extent = btrfs_item_ptr(leaf, path->slots[0],
1352 struct btrfs_dev_extent);
1353 btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1354 btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1355 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1357 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1358 btrfs_dev_extent_chunk_tree_uuid(extent), BTRFS_UUID_SIZE);
1360 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1361 btrfs_mark_buffer_dirty(leaf);
1363 btrfs_free_path(path);
1367 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1369 struct extent_map_tree *em_tree;
1370 struct extent_map *em;
1374 em_tree = &fs_info->mapping_tree.map_tree;
1375 read_lock(&em_tree->lock);
1376 n = rb_last(&em_tree->map);
1378 em = rb_entry(n, struct extent_map, rb_node);
1379 ret = em->start + em->len;
1381 read_unlock(&em_tree->lock);
1386 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1390 struct btrfs_key key;
1391 struct btrfs_key found_key;
1392 struct btrfs_path *path;
1394 path = btrfs_alloc_path();
1398 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1399 key.type = BTRFS_DEV_ITEM_KEY;
1400 key.offset = (u64)-1;
1402 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1406 BUG_ON(ret == 0); /* Corruption */
1408 ret = btrfs_previous_item(fs_info->chunk_root, path,
1409 BTRFS_DEV_ITEMS_OBJECTID,
1410 BTRFS_DEV_ITEM_KEY);
1414 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1416 *devid_ret = found_key.offset + 1;
1420 btrfs_free_path(path);
1425 * the device information is stored in the chunk root
1426 * the btrfs_device struct should be fully filled in
1428 static int btrfs_add_device(struct btrfs_trans_handle *trans,
1429 struct btrfs_root *root,
1430 struct btrfs_device *device)
1433 struct btrfs_path *path;
1434 struct btrfs_dev_item *dev_item;
1435 struct extent_buffer *leaf;
1436 struct btrfs_key key;
1439 root = root->fs_info->chunk_root;
1441 path = btrfs_alloc_path();
1445 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1446 key.type = BTRFS_DEV_ITEM_KEY;
1447 key.offset = device->devid;
1449 ret = btrfs_insert_empty_item(trans, root, path, &key,
1454 leaf = path->nodes[0];
1455 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1457 btrfs_set_device_id(leaf, dev_item, device->devid);
1458 btrfs_set_device_generation(leaf, dev_item, 0);
1459 btrfs_set_device_type(leaf, dev_item, device->type);
1460 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1461 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1462 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1463 btrfs_set_device_total_bytes(leaf, dev_item,
1464 btrfs_device_get_disk_total_bytes(device));
1465 btrfs_set_device_bytes_used(leaf, dev_item,
1466 btrfs_device_get_bytes_used(device));
1467 btrfs_set_device_group(leaf, dev_item, 0);
1468 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1469 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1470 btrfs_set_device_start_offset(leaf, dev_item, 0);
1472 ptr = btrfs_device_uuid(dev_item);
1473 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1474 ptr = btrfs_device_fsid(dev_item);
1475 write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
1476 btrfs_mark_buffer_dirty(leaf);
1480 btrfs_free_path(path);
1485 * Function to update ctime/mtime for a given device path.
1486 * Mainly used for ctime/mtime based probe like libblkid.
1488 static void update_dev_time(char *path_name)
1492 filp = filp_open(path_name, O_RDWR, 0);
1495 file_update_time(filp);
1496 filp_close(filp, NULL);
1500 static int btrfs_rm_dev_item(struct btrfs_root *root,
1501 struct btrfs_device *device)
1504 struct btrfs_path *path;
1505 struct btrfs_key key;
1506 struct btrfs_trans_handle *trans;
1508 root = root->fs_info->chunk_root;
1510 path = btrfs_alloc_path();
1514 trans = btrfs_start_transaction(root, 0);
1515 if (IS_ERR(trans)) {
1516 btrfs_free_path(path);
1517 return PTR_ERR(trans);
1519 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1520 key.type = BTRFS_DEV_ITEM_KEY;
1521 key.offset = device->devid;
1523 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1532 ret = btrfs_del_item(trans, root, path);
1536 btrfs_free_path(path);
1537 btrfs_commit_transaction(trans, root);
1541 int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1543 struct btrfs_device *device;
1544 struct btrfs_device *next_device;
1545 struct block_device *bdev;
1546 struct buffer_head *bh = NULL;
1547 struct btrfs_super_block *disk_super;
1548 struct btrfs_fs_devices *cur_devices;
1555 bool clear_super = false;
1557 mutex_lock(&uuid_mutex);
1560 seq = read_seqbegin(&root->fs_info->profiles_lock);
1562 all_avail = root->fs_info->avail_data_alloc_bits |
1563 root->fs_info->avail_system_alloc_bits |
1564 root->fs_info->avail_metadata_alloc_bits;
1565 } while (read_seqretry(&root->fs_info->profiles_lock, seq));
1567 num_devices = root->fs_info->fs_devices->num_devices;
1568 btrfs_dev_replace_lock(&root->fs_info->dev_replace);
1569 if (btrfs_dev_replace_is_ongoing(&root->fs_info->dev_replace)) {
1570 WARN_ON(num_devices < 1);
1573 btrfs_dev_replace_unlock(&root->fs_info->dev_replace);
1575 if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) && num_devices <= 4) {
1576 ret = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET;
1580 if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) && num_devices <= 2) {
1581 ret = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET;
1585 if ((all_avail & BTRFS_BLOCK_GROUP_RAID5) &&
1586 root->fs_info->fs_devices->rw_devices <= 2) {
1587 ret = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET;
1590 if ((all_avail & BTRFS_BLOCK_GROUP_RAID6) &&
1591 root->fs_info->fs_devices->rw_devices <= 3) {
1592 ret = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET;
1596 if (strcmp(device_path, "missing") == 0) {
1597 struct list_head *devices;
1598 struct btrfs_device *tmp;
1601 devices = &root->fs_info->fs_devices->devices;
1603 * It is safe to read the devices since the volume_mutex
1606 list_for_each_entry(tmp, devices, dev_list) {
1607 if (tmp->in_fs_metadata &&
1608 !tmp->is_tgtdev_for_dev_replace &&
1618 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
1622 ret = btrfs_get_bdev_and_sb(device_path,
1623 FMODE_WRITE | FMODE_EXCL,
1624 root->fs_info->bdev_holder, 0,
1628 disk_super = (struct btrfs_super_block *)bh->b_data;
1629 devid = btrfs_stack_device_id(&disk_super->dev_item);
1630 dev_uuid = disk_super->dev_item.uuid;
1631 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1639 if (device->is_tgtdev_for_dev_replace) {
1640 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1644 if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
1645 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1649 if (device->writeable) {
1651 list_del_init(&device->dev_alloc_list);
1652 unlock_chunks(root);
1653 root->fs_info->fs_devices->rw_devices--;
1657 mutex_unlock(&uuid_mutex);
1658 ret = btrfs_shrink_device(device, 0);
1659 mutex_lock(&uuid_mutex);
1664 * TODO: the superblock still includes this device in its num_devices
1665 * counter although write_all_supers() is not locked out. This
1666 * could give a filesystem state which requires a degraded mount.
1668 ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1672 device->in_fs_metadata = 0;
1673 btrfs_scrub_cancel_dev(root->fs_info, device);
1676 * the device list mutex makes sure that we don't change
1677 * the device list while someone else is writing out all
1678 * the device supers. Whoever is writing all supers, should
1679 * lock the device list mutex before getting the number of
1680 * devices in the super block (super_copy). Conversely,
1681 * whoever updates the number of devices in the super block
1682 * (super_copy) should hold the device list mutex.
1685 cur_devices = device->fs_devices;
1686 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1687 list_del_rcu(&device->dev_list);
1689 device->fs_devices->num_devices--;
1690 device->fs_devices->total_devices--;
1692 if (device->missing)
1693 device->fs_devices->missing_devices--;
1695 next_device = list_entry(root->fs_info->fs_devices->devices.next,
1696 struct btrfs_device, dev_list);
1697 if (device->bdev == root->fs_info->sb->s_bdev)
1698 root->fs_info->sb->s_bdev = next_device->bdev;
1699 if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1700 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1703 device->fs_devices->open_devices--;
1704 /* remove sysfs entry */
1705 btrfs_kobj_rm_device(root->fs_info, device);
1708 call_rcu(&device->rcu, free_device);
1710 num_devices = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
1711 btrfs_set_super_num_devices(root->fs_info->super_copy, num_devices);
1712 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1714 if (cur_devices->open_devices == 0) {
1715 struct btrfs_fs_devices *fs_devices;
1716 fs_devices = root->fs_info->fs_devices;
1717 while (fs_devices) {
1718 if (fs_devices->seed == cur_devices) {
1719 fs_devices->seed = cur_devices->seed;
1722 fs_devices = fs_devices->seed;
1724 cur_devices->seed = NULL;
1725 __btrfs_close_devices(cur_devices);
1726 free_fs_devices(cur_devices);
1729 root->fs_info->num_tolerated_disk_barrier_failures =
1730 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
1733 * at this point, the device is zero sized. We want to
1734 * remove it from the devices list and zero out the old super
1736 if (clear_super && disk_super) {
1740 /* make sure this device isn't detected as part of
1743 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1744 set_buffer_dirty(bh);
1745 sync_dirty_buffer(bh);
1747 /* clear the mirror copies of super block on the disk
1748 * being removed, 0th copy is been taken care above and
1749 * the below would take of the rest
1751 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1752 bytenr = btrfs_sb_offset(i);
1753 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
1754 i_size_read(bdev->bd_inode))
1758 bh = __bread(bdev, bytenr / 4096,
1759 BTRFS_SUPER_INFO_SIZE);
1763 disk_super = (struct btrfs_super_block *)bh->b_data;
1765 if (btrfs_super_bytenr(disk_super) != bytenr ||
1766 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1769 memset(&disk_super->magic, 0,
1770 sizeof(disk_super->magic));
1771 set_buffer_dirty(bh);
1772 sync_dirty_buffer(bh);
1779 /* Notify udev that device has changed */
1780 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
1782 /* Update ctime/mtime for device path for libblkid */
1783 update_dev_time(device_path);
1789 blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
1791 mutex_unlock(&uuid_mutex);
1794 if (device->writeable) {
1796 list_add(&device->dev_alloc_list,
1797 &root->fs_info->fs_devices->alloc_list);
1798 unlock_chunks(root);
1799 root->fs_info->fs_devices->rw_devices++;
1804 void btrfs_rm_dev_replace_srcdev(struct btrfs_fs_info *fs_info,
1805 struct btrfs_device *srcdev)
1807 struct btrfs_fs_devices *fs_devices;
1809 WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
1812 * in case of fs with no seed, srcdev->fs_devices will point
1813 * to fs_devices of fs_info. However when the dev being replaced is
1814 * a seed dev it will point to the seed's local fs_devices. In short
1815 * srcdev will have its correct fs_devices in both the cases.
1817 fs_devices = srcdev->fs_devices;
1819 list_del_rcu(&srcdev->dev_list);
1820 list_del_rcu(&srcdev->dev_alloc_list);
1821 fs_devices->num_devices--;
1822 if (srcdev->missing)
1823 fs_devices->missing_devices--;
1825 if (srcdev->writeable) {
1826 fs_devices->rw_devices--;
1827 /* zero out the old super if it is writable */
1828 btrfs_scratch_superblock(srcdev);
1832 fs_devices->open_devices--;
1834 call_rcu(&srcdev->rcu, free_device);
1837 * unless fs_devices is seed fs, num_devices shouldn't go
1840 BUG_ON(!fs_devices->num_devices && !fs_devices->seeding);
1842 /* if this is no devs we rather delete the fs_devices */
1843 if (!fs_devices->num_devices) {
1844 struct btrfs_fs_devices *tmp_fs_devices;
1846 tmp_fs_devices = fs_info->fs_devices;
1847 while (tmp_fs_devices) {
1848 if (tmp_fs_devices->seed == fs_devices) {
1849 tmp_fs_devices->seed = fs_devices->seed;
1852 tmp_fs_devices = tmp_fs_devices->seed;
1854 fs_devices->seed = NULL;
1855 __btrfs_close_devices(fs_devices);
1856 free_fs_devices(fs_devices);
1860 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
1861 struct btrfs_device *tgtdev)
1863 struct btrfs_device *next_device;
1865 mutex_lock(&uuid_mutex);
1867 mutex_lock(&fs_info->fs_devices->device_list_mutex);
1869 btrfs_scratch_superblock(tgtdev);
1870 fs_info->fs_devices->open_devices--;
1872 fs_info->fs_devices->num_devices--;
1874 next_device = list_entry(fs_info->fs_devices->devices.next,
1875 struct btrfs_device, dev_list);
1876 if (tgtdev->bdev == fs_info->sb->s_bdev)
1877 fs_info->sb->s_bdev = next_device->bdev;
1878 if (tgtdev->bdev == fs_info->fs_devices->latest_bdev)
1879 fs_info->fs_devices->latest_bdev = next_device->bdev;
1880 list_del_rcu(&tgtdev->dev_list);
1882 call_rcu(&tgtdev->rcu, free_device);
1884 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1885 mutex_unlock(&uuid_mutex);
1888 static int btrfs_find_device_by_path(struct btrfs_root *root, char *device_path,
1889 struct btrfs_device **device)
1892 struct btrfs_super_block *disk_super;
1895 struct block_device *bdev;
1896 struct buffer_head *bh;
1899 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
1900 root->fs_info->bdev_holder, 0, &bdev, &bh);
1903 disk_super = (struct btrfs_super_block *)bh->b_data;
1904 devid = btrfs_stack_device_id(&disk_super->dev_item);
1905 dev_uuid = disk_super->dev_item.uuid;
1906 *device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1911 blkdev_put(bdev, FMODE_READ);
1915 int btrfs_find_device_missing_or_by_path(struct btrfs_root *root,
1917 struct btrfs_device **device)
1920 if (strcmp(device_path, "missing") == 0) {
1921 struct list_head *devices;
1922 struct btrfs_device *tmp;
1924 devices = &root->fs_info->fs_devices->devices;
1926 * It is safe to read the devices since the volume_mutex
1927 * is held by the caller.
1929 list_for_each_entry(tmp, devices, dev_list) {
1930 if (tmp->in_fs_metadata && !tmp->bdev) {
1937 btrfs_err(root->fs_info, "no missing device found");
1943 return btrfs_find_device_by_path(root, device_path, device);
1948 * does all the dirty work required for changing file system's UUID.
1950 static int btrfs_prepare_sprout(struct btrfs_root *root)
1952 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
1953 struct btrfs_fs_devices *old_devices;
1954 struct btrfs_fs_devices *seed_devices;
1955 struct btrfs_super_block *disk_super = root->fs_info->super_copy;
1956 struct btrfs_device *device;
1959 BUG_ON(!mutex_is_locked(&uuid_mutex));
1960 if (!fs_devices->seeding)
1963 seed_devices = __alloc_fs_devices();
1964 if (IS_ERR(seed_devices))
1965 return PTR_ERR(seed_devices);
1967 old_devices = clone_fs_devices(fs_devices);
1968 if (IS_ERR(old_devices)) {
1969 kfree(seed_devices);
1970 return PTR_ERR(old_devices);
1973 list_add(&old_devices->list, &fs_uuids);
1975 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
1976 seed_devices->opened = 1;
1977 INIT_LIST_HEAD(&seed_devices->devices);
1978 INIT_LIST_HEAD(&seed_devices->alloc_list);
1979 mutex_init(&seed_devices->device_list_mutex);
1981 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1982 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
1984 list_for_each_entry(device, &seed_devices->devices, dev_list)
1985 device->fs_devices = seed_devices;
1988 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
1989 unlock_chunks(root);
1991 fs_devices->seeding = 0;
1992 fs_devices->num_devices = 0;
1993 fs_devices->open_devices = 0;
1994 fs_devices->missing_devices = 0;
1995 fs_devices->rotating = 0;
1996 fs_devices->seed = seed_devices;
1998 generate_random_uuid(fs_devices->fsid);
1999 memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2000 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2001 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2003 super_flags = btrfs_super_flags(disk_super) &
2004 ~BTRFS_SUPER_FLAG_SEEDING;
2005 btrfs_set_super_flags(disk_super, super_flags);
2011 * strore the expected generation for seed devices in device items.
2013 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2014 struct btrfs_root *root)
2016 struct btrfs_path *path;
2017 struct extent_buffer *leaf;
2018 struct btrfs_dev_item *dev_item;
2019 struct btrfs_device *device;
2020 struct btrfs_key key;
2021 u8 fs_uuid[BTRFS_UUID_SIZE];
2022 u8 dev_uuid[BTRFS_UUID_SIZE];
2026 path = btrfs_alloc_path();
2030 root = root->fs_info->chunk_root;
2031 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2033 key.type = BTRFS_DEV_ITEM_KEY;
2036 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2040 leaf = path->nodes[0];
2042 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2043 ret = btrfs_next_leaf(root, path);
2048 leaf = path->nodes[0];
2049 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2050 btrfs_release_path(path);
2054 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2055 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2056 key.type != BTRFS_DEV_ITEM_KEY)
2059 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2060 struct btrfs_dev_item);
2061 devid = btrfs_device_id(leaf, dev_item);
2062 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2064 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2066 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
2068 BUG_ON(!device); /* Logic error */
2070 if (device->fs_devices->seeding) {
2071 btrfs_set_device_generation(leaf, dev_item,
2072 device->generation);
2073 btrfs_mark_buffer_dirty(leaf);
2081 btrfs_free_path(path);
2085 int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
2087 struct request_queue *q;
2088 struct btrfs_trans_handle *trans;
2089 struct btrfs_device *device;
2090 struct block_device *bdev;
2091 struct list_head *devices;
2092 struct super_block *sb = root->fs_info->sb;
2093 struct rcu_string *name;
2095 int seeding_dev = 0;
2098 if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
2101 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2102 root->fs_info->bdev_holder);
2104 return PTR_ERR(bdev);
2106 if (root->fs_info->fs_devices->seeding) {
2108 down_write(&sb->s_umount);
2109 mutex_lock(&uuid_mutex);
2112 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2114 devices = &root->fs_info->fs_devices->devices;
2116 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2117 list_for_each_entry(device, devices, dev_list) {
2118 if (device->bdev == bdev) {
2121 &root->fs_info->fs_devices->device_list_mutex);
2125 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2127 device = btrfs_alloc_device(root->fs_info, NULL, NULL);
2128 if (IS_ERR(device)) {
2129 /* we can safely leave the fs_devices entry around */
2130 ret = PTR_ERR(device);
2134 name = rcu_string_strdup(device_path, GFP_NOFS);
2140 rcu_assign_pointer(device->name, name);
2142 trans = btrfs_start_transaction(root, 0);
2143 if (IS_ERR(trans)) {
2144 rcu_string_free(device->name);
2146 ret = PTR_ERR(trans);
2150 q = bdev_get_queue(bdev);
2151 if (blk_queue_discard(q))
2152 device->can_discard = 1;
2153 device->writeable = 1;
2154 device->generation = trans->transid;
2155 device->io_width = root->sectorsize;
2156 device->io_align = root->sectorsize;
2157 device->sector_size = root->sectorsize;
2158 device->total_bytes = i_size_read(bdev->bd_inode);
2159 device->disk_total_bytes = device->total_bytes;
2160 device->commit_total_bytes = device->total_bytes;
2161 device->dev_root = root->fs_info->dev_root;
2162 device->bdev = bdev;
2163 device->in_fs_metadata = 1;
2164 device->is_tgtdev_for_dev_replace = 0;
2165 device->mode = FMODE_EXCL;
2166 device->dev_stats_valid = 1;
2167 set_blocksize(device->bdev, 4096);
2170 sb->s_flags &= ~MS_RDONLY;
2171 ret = btrfs_prepare_sprout(root);
2172 BUG_ON(ret); /* -ENOMEM */
2175 device->fs_devices = root->fs_info->fs_devices;
2177 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2179 list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
2180 list_add(&device->dev_alloc_list,
2181 &root->fs_info->fs_devices->alloc_list);
2182 root->fs_info->fs_devices->num_devices++;
2183 root->fs_info->fs_devices->open_devices++;
2184 root->fs_info->fs_devices->rw_devices++;
2185 root->fs_info->fs_devices->total_devices++;
2186 root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2188 spin_lock(&root->fs_info->free_chunk_lock);
2189 root->fs_info->free_chunk_space += device->total_bytes;
2190 spin_unlock(&root->fs_info->free_chunk_lock);
2192 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
2193 root->fs_info->fs_devices->rotating = 1;
2195 tmp = btrfs_super_total_bytes(root->fs_info->super_copy);
2196 btrfs_set_super_total_bytes(root->fs_info->super_copy,
2197 tmp + device->total_bytes);
2199 tmp = btrfs_super_num_devices(root->fs_info->super_copy);
2200 btrfs_set_super_num_devices(root->fs_info->super_copy,
2203 /* add sysfs device entry */
2204 btrfs_kobj_add_device(root->fs_info, device);
2207 * we've got more storage, clear any full flags on the space
2210 btrfs_clear_space_info_full(root->fs_info);
2212 unlock_chunks(root);
2213 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2217 ret = init_first_rw_device(trans, root, device);
2218 unlock_chunks(root);
2220 btrfs_abort_transaction(trans, root, ret);
2225 ret = btrfs_add_device(trans, root, device);
2227 btrfs_abort_transaction(trans, root, ret);
2232 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2234 ret = btrfs_finish_sprout(trans, root);
2236 btrfs_abort_transaction(trans, root, ret);
2240 /* Sprouting would change fsid of the mounted root,
2241 * so rename the fsid on the sysfs
2243 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2244 root->fs_info->fsid);
2245 if (kobject_rename(&root->fs_info->super_kobj, fsid_buf))
2249 root->fs_info->num_tolerated_disk_barrier_failures =
2250 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
2251 ret = btrfs_commit_transaction(trans, root);
2254 mutex_unlock(&uuid_mutex);
2255 up_write(&sb->s_umount);
2257 if (ret) /* transaction commit */
2260 ret = btrfs_relocate_sys_chunks(root);
2262 btrfs_error(root->fs_info, ret,
2263 "Failed to relocate sys chunks after "
2264 "device initialization. This can be fixed "
2265 "using the \"btrfs balance\" command.");
2266 trans = btrfs_attach_transaction(root);
2267 if (IS_ERR(trans)) {
2268 if (PTR_ERR(trans) == -ENOENT)
2270 return PTR_ERR(trans);
2272 ret = btrfs_commit_transaction(trans, root);
2275 /* Update ctime/mtime for libblkid */
2276 update_dev_time(device_path);
2280 btrfs_end_transaction(trans, root);
2281 rcu_string_free(device->name);
2282 btrfs_kobj_rm_device(root->fs_info, device);
2285 blkdev_put(bdev, FMODE_EXCL);
2287 mutex_unlock(&uuid_mutex);
2288 up_write(&sb->s_umount);
2293 int btrfs_init_dev_replace_tgtdev(struct btrfs_root *root, char *device_path,
2294 struct btrfs_device *srcdev,
2295 struct btrfs_device **device_out)
2297 struct request_queue *q;
2298 struct btrfs_device *device;
2299 struct block_device *bdev;
2300 struct btrfs_fs_info *fs_info = root->fs_info;
2301 struct list_head *devices;
2302 struct rcu_string *name;
2303 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2307 if (fs_info->fs_devices->seeding) {
2308 btrfs_err(fs_info, "the filesystem is a seed filesystem!");
2312 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2313 fs_info->bdev_holder);
2315 btrfs_err(fs_info, "target device %s is invalid!", device_path);
2316 return PTR_ERR(bdev);
2319 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2321 devices = &fs_info->fs_devices->devices;
2322 list_for_each_entry(device, devices, dev_list) {
2323 if (device->bdev == bdev) {
2324 btrfs_err(fs_info, "target device is in the filesystem!");
2331 if (i_size_read(bdev->bd_inode) <
2332 btrfs_device_get_total_bytes(srcdev)) {
2333 btrfs_err(fs_info, "target device is smaller than source device!");
2339 device = btrfs_alloc_device(NULL, &devid, NULL);
2340 if (IS_ERR(device)) {
2341 ret = PTR_ERR(device);
2345 name = rcu_string_strdup(device_path, GFP_NOFS);
2351 rcu_assign_pointer(device->name, name);
2353 q = bdev_get_queue(bdev);
2354 if (blk_queue_discard(q))
2355 device->can_discard = 1;
2356 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2357 device->writeable = 1;
2358 device->generation = 0;
2359 device->io_width = root->sectorsize;
2360 device->io_align = root->sectorsize;
2361 device->sector_size = root->sectorsize;
2362 device->total_bytes = btrfs_device_get_total_bytes(srcdev);
2363 device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
2364 device->bytes_used = btrfs_device_get_bytes_used(srcdev);
2365 ASSERT(list_empty(&srcdev->resized_list));
2366 device->commit_total_bytes = srcdev->commit_total_bytes;
2367 device->commit_bytes_used = device->bytes_used;
2368 device->dev_root = fs_info->dev_root;
2369 device->bdev = bdev;
2370 device->in_fs_metadata = 1;
2371 device->is_tgtdev_for_dev_replace = 1;
2372 device->mode = FMODE_EXCL;
2373 device->dev_stats_valid = 1;
2374 set_blocksize(device->bdev, 4096);
2375 device->fs_devices = fs_info->fs_devices;
2376 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2377 fs_info->fs_devices->num_devices++;
2378 fs_info->fs_devices->open_devices++;
2379 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2381 *device_out = device;
2385 blkdev_put(bdev, FMODE_EXCL);
2389 void btrfs_init_dev_replace_tgtdev_for_resume(struct btrfs_fs_info *fs_info,
2390 struct btrfs_device *tgtdev)
2392 WARN_ON(fs_info->fs_devices->rw_devices == 0);
2393 tgtdev->io_width = fs_info->dev_root->sectorsize;
2394 tgtdev->io_align = fs_info->dev_root->sectorsize;
2395 tgtdev->sector_size = fs_info->dev_root->sectorsize;
2396 tgtdev->dev_root = fs_info->dev_root;
2397 tgtdev->in_fs_metadata = 1;
2400 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2401 struct btrfs_device *device)
2404 struct btrfs_path *path;
2405 struct btrfs_root *root;
2406 struct btrfs_dev_item *dev_item;
2407 struct extent_buffer *leaf;
2408 struct btrfs_key key;
2410 root = device->dev_root->fs_info->chunk_root;
2412 path = btrfs_alloc_path();
2416 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2417 key.type = BTRFS_DEV_ITEM_KEY;
2418 key.offset = device->devid;
2420 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2429 leaf = path->nodes[0];
2430 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2432 btrfs_set_device_id(leaf, dev_item, device->devid);
2433 btrfs_set_device_type(leaf, dev_item, device->type);
2434 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2435 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2436 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2437 btrfs_set_device_total_bytes(leaf, dev_item,
2438 btrfs_device_get_disk_total_bytes(device));
2439 btrfs_set_device_bytes_used(leaf, dev_item,
2440 btrfs_device_get_bytes_used(device));
2441 btrfs_mark_buffer_dirty(leaf);
2444 btrfs_free_path(path);
2448 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2449 struct btrfs_device *device, u64 new_size)
2451 struct btrfs_super_block *super_copy =
2452 device->dev_root->fs_info->super_copy;
2453 struct btrfs_fs_devices *fs_devices;
2457 if (!device->writeable)
2460 lock_chunks(device->dev_root);
2461 old_total = btrfs_super_total_bytes(super_copy);
2462 diff = new_size - device->total_bytes;
2464 if (new_size <= device->total_bytes ||
2465 device->is_tgtdev_for_dev_replace) {
2466 unlock_chunks(device->dev_root);
2470 fs_devices = device->dev_root->fs_info->fs_devices;
2472 btrfs_set_super_total_bytes(super_copy, old_total + diff);
2473 device->fs_devices->total_rw_bytes += diff;
2475 btrfs_device_set_total_bytes(device, new_size);
2476 btrfs_device_set_disk_total_bytes(device, new_size);
2477 btrfs_clear_space_info_full(device->dev_root->fs_info);
2478 if (list_empty(&device->resized_list))
2479 list_add_tail(&device->resized_list,
2480 &fs_devices->resized_devices);
2481 unlock_chunks(device->dev_root);
2483 return btrfs_update_device(trans, device);
2486 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2487 struct btrfs_root *root,
2488 u64 chunk_tree, u64 chunk_objectid,
2492 struct btrfs_path *path;
2493 struct btrfs_key key;
2495 root = root->fs_info->chunk_root;
2496 path = btrfs_alloc_path();
2500 key.objectid = chunk_objectid;
2501 key.offset = chunk_offset;
2502 key.type = BTRFS_CHUNK_ITEM_KEY;
2504 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2507 else if (ret > 0) { /* Logic error or corruption */
2508 btrfs_error(root->fs_info, -ENOENT,
2509 "Failed lookup while freeing chunk.");
2514 ret = btrfs_del_item(trans, root, path);
2516 btrfs_error(root->fs_info, ret,
2517 "Failed to delete chunk item.");
2519 btrfs_free_path(path);
2523 static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
2526 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
2527 struct btrfs_disk_key *disk_key;
2528 struct btrfs_chunk *chunk;
2535 struct btrfs_key key;
2538 array_size = btrfs_super_sys_array_size(super_copy);
2540 ptr = super_copy->sys_chunk_array;
2543 while (cur < array_size) {
2544 disk_key = (struct btrfs_disk_key *)ptr;
2545 btrfs_disk_key_to_cpu(&key, disk_key);
2547 len = sizeof(*disk_key);
2549 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2550 chunk = (struct btrfs_chunk *)(ptr + len);
2551 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2552 len += btrfs_chunk_item_size(num_stripes);
2557 if (key.objectid == chunk_objectid &&
2558 key.offset == chunk_offset) {
2559 memmove(ptr, ptr + len, array_size - (cur + len));
2561 btrfs_set_super_sys_array_size(super_copy, array_size);
2567 unlock_chunks(root);
2571 static int btrfs_relocate_chunk(struct btrfs_root *root,
2572 u64 chunk_tree, u64 chunk_objectid,
2575 struct extent_map_tree *em_tree;
2576 struct btrfs_root *extent_root;
2577 struct btrfs_trans_handle *trans;
2578 struct btrfs_device *device;
2579 struct extent_map *em;
2580 struct map_lookup *map;
2581 u64 dev_extent_len = 0;
2585 root = root->fs_info->chunk_root;
2586 extent_root = root->fs_info->extent_root;
2587 em_tree = &root->fs_info->mapping_tree.map_tree;
2589 ret = btrfs_can_relocate(extent_root, chunk_offset);
2593 /* step one, relocate all the extents inside this chunk */
2594 ret = btrfs_relocate_block_group(extent_root, chunk_offset);
2598 trans = btrfs_start_transaction(root, 0);
2599 if (IS_ERR(trans)) {
2600 ret = PTR_ERR(trans);
2601 btrfs_std_error(root->fs_info, ret);
2606 * step two, delete the device extents and the
2607 * chunk tree entries
2609 read_lock(&em_tree->lock);
2610 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
2611 read_unlock(&em_tree->lock);
2613 BUG_ON(!em || em->start > chunk_offset ||
2614 em->start + em->len < chunk_offset);
2615 map = (struct map_lookup *)em->bdev;
2617 for (i = 0; i < map->num_stripes; i++) {
2618 device = map->stripes[i].dev;
2619 ret = btrfs_free_dev_extent(trans, device,
2620 map->stripes[i].physical,
2624 if (device->bytes_used > 0) {
2626 btrfs_device_set_bytes_used(device,
2627 device->bytes_used - dev_extent_len);
2628 spin_lock(&root->fs_info->free_chunk_lock);
2629 root->fs_info->free_chunk_space += dev_extent_len;
2630 spin_unlock(&root->fs_info->free_chunk_lock);
2631 btrfs_clear_space_info_full(root->fs_info);
2632 unlock_chunks(root);
2635 if (map->stripes[i].dev) {
2636 ret = btrfs_update_device(trans, map->stripes[i].dev);
2640 ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
2645 trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
2647 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2648 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
2652 ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
2655 write_lock(&em_tree->lock);
2656 remove_extent_mapping(em_tree, em);
2657 write_unlock(&em_tree->lock);
2659 /* once for the tree */
2660 free_extent_map(em);
2662 free_extent_map(em);
2664 btrfs_end_transaction(trans, root);
2668 static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
2670 struct btrfs_root *chunk_root = root->fs_info->chunk_root;
2671 struct btrfs_path *path;
2672 struct extent_buffer *leaf;
2673 struct btrfs_chunk *chunk;
2674 struct btrfs_key key;
2675 struct btrfs_key found_key;
2676 u64 chunk_tree = chunk_root->root_key.objectid;
2678 bool retried = false;
2682 path = btrfs_alloc_path();
2687 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2688 key.offset = (u64)-1;
2689 key.type = BTRFS_CHUNK_ITEM_KEY;
2692 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2695 BUG_ON(ret == 0); /* Corruption */
2697 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2704 leaf = path->nodes[0];
2705 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2707 chunk = btrfs_item_ptr(leaf, path->slots[0],
2708 struct btrfs_chunk);
2709 chunk_type = btrfs_chunk_type(leaf, chunk);
2710 btrfs_release_path(path);
2712 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2713 ret = btrfs_relocate_chunk(chunk_root, chunk_tree,
2722 if (found_key.offset == 0)
2724 key.offset = found_key.offset - 1;
2727 if (failed && !retried) {
2731 } else if (WARN_ON(failed && retried)) {
2735 btrfs_free_path(path);
2739 static int insert_balance_item(struct btrfs_root *root,
2740 struct btrfs_balance_control *bctl)
2742 struct btrfs_trans_handle *trans;
2743 struct btrfs_balance_item *item;
2744 struct btrfs_disk_balance_args disk_bargs;
2745 struct btrfs_path *path;
2746 struct extent_buffer *leaf;
2747 struct btrfs_key key;
2750 path = btrfs_alloc_path();
2754 trans = btrfs_start_transaction(root, 0);
2755 if (IS_ERR(trans)) {
2756 btrfs_free_path(path);
2757 return PTR_ERR(trans);
2760 key.objectid = BTRFS_BALANCE_OBJECTID;
2761 key.type = BTRFS_BALANCE_ITEM_KEY;
2764 ret = btrfs_insert_empty_item(trans, root, path, &key,
2769 leaf = path->nodes[0];
2770 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2772 memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
2774 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
2775 btrfs_set_balance_data(leaf, item, &disk_bargs);
2776 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
2777 btrfs_set_balance_meta(leaf, item, &disk_bargs);
2778 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
2779 btrfs_set_balance_sys(leaf, item, &disk_bargs);
2781 btrfs_set_balance_flags(leaf, item, bctl->flags);
2783 btrfs_mark_buffer_dirty(leaf);
2785 btrfs_free_path(path);
2786 err = btrfs_commit_transaction(trans, root);
2792 static int del_balance_item(struct btrfs_root *root)
2794 struct btrfs_trans_handle *trans;
2795 struct btrfs_path *path;
2796 struct btrfs_key key;
2799 path = btrfs_alloc_path();
2803 trans = btrfs_start_transaction(root, 0);
2804 if (IS_ERR(trans)) {
2805 btrfs_free_path(path);
2806 return PTR_ERR(trans);
2809 key.objectid = BTRFS_BALANCE_OBJECTID;
2810 key.type = BTRFS_BALANCE_ITEM_KEY;
2813 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2821 ret = btrfs_del_item(trans, root, path);
2823 btrfs_free_path(path);
2824 err = btrfs_commit_transaction(trans, root);
2831 * This is a heuristic used to reduce the number of chunks balanced on
2832 * resume after balance was interrupted.
2834 static void update_balance_args(struct btrfs_balance_control *bctl)
2837 * Turn on soft mode for chunk types that were being converted.
2839 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
2840 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
2841 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
2842 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
2843 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
2844 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
2847 * Turn on usage filter if is not already used. The idea is
2848 * that chunks that we have already balanced should be
2849 * reasonably full. Don't do it for chunks that are being
2850 * converted - that will keep us from relocating unconverted
2851 * (albeit full) chunks.
2853 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2854 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2855 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
2856 bctl->data.usage = 90;
2858 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2859 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2860 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
2861 bctl->sys.usage = 90;
2863 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2864 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2865 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
2866 bctl->meta.usage = 90;
2871 * Should be called with both balance and volume mutexes held to
2872 * serialize other volume operations (add_dev/rm_dev/resize) with
2873 * restriper. Same goes for unset_balance_control.
2875 static void set_balance_control(struct btrfs_balance_control *bctl)
2877 struct btrfs_fs_info *fs_info = bctl->fs_info;
2879 BUG_ON(fs_info->balance_ctl);
2881 spin_lock(&fs_info->balance_lock);
2882 fs_info->balance_ctl = bctl;
2883 spin_unlock(&fs_info->balance_lock);
2886 static void unset_balance_control(struct btrfs_fs_info *fs_info)
2888 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
2890 BUG_ON(!fs_info->balance_ctl);
2892 spin_lock(&fs_info->balance_lock);
2893 fs_info->balance_ctl = NULL;
2894 spin_unlock(&fs_info->balance_lock);
2900 * Balance filters. Return 1 if chunk should be filtered out
2901 * (should not be balanced).
2903 static int chunk_profiles_filter(u64 chunk_type,
2904 struct btrfs_balance_args *bargs)
2906 chunk_type = chunk_to_extended(chunk_type) &
2907 BTRFS_EXTENDED_PROFILE_MASK;
2909 if (bargs->profiles & chunk_type)
2915 static int chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
2916 struct btrfs_balance_args *bargs)
2918 struct btrfs_block_group_cache *cache;
2919 u64 chunk_used, user_thresh;
2922 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2923 chunk_used = btrfs_block_group_used(&cache->item);
2925 if (bargs->usage == 0)
2927 else if (bargs->usage > 100)
2928 user_thresh = cache->key.offset;
2930 user_thresh = div_factor_fine(cache->key.offset,
2933 if (chunk_used < user_thresh)
2936 btrfs_put_block_group(cache);
2940 static int chunk_devid_filter(struct extent_buffer *leaf,
2941 struct btrfs_chunk *chunk,
2942 struct btrfs_balance_args *bargs)
2944 struct btrfs_stripe *stripe;
2945 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2948 for (i = 0; i < num_stripes; i++) {
2949 stripe = btrfs_stripe_nr(chunk, i);
2950 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
2957 /* [pstart, pend) */
2958 static int chunk_drange_filter(struct extent_buffer *leaf,
2959 struct btrfs_chunk *chunk,
2961 struct btrfs_balance_args *bargs)
2963 struct btrfs_stripe *stripe;
2964 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2970 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
2973 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
2974 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
2975 factor = num_stripes / 2;
2976 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
2977 factor = num_stripes - 1;
2978 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
2979 factor = num_stripes - 2;
2981 factor = num_stripes;
2984 for (i = 0; i < num_stripes; i++) {
2985 stripe = btrfs_stripe_nr(chunk, i);
2986 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
2989 stripe_offset = btrfs_stripe_offset(leaf, stripe);
2990 stripe_length = btrfs_chunk_length(leaf, chunk);
2991 do_div(stripe_length, factor);
2993 if (stripe_offset < bargs->pend &&
2994 stripe_offset + stripe_length > bargs->pstart)
3001 /* [vstart, vend) */
3002 static int chunk_vrange_filter(struct extent_buffer *leaf,
3003 struct btrfs_chunk *chunk,
3005 struct btrfs_balance_args *bargs)
3007 if (chunk_offset < bargs->vend &&
3008 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3009 /* at least part of the chunk is inside this vrange */
3015 static int chunk_soft_convert_filter(u64 chunk_type,
3016 struct btrfs_balance_args *bargs)
3018 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3021 chunk_type = chunk_to_extended(chunk_type) &
3022 BTRFS_EXTENDED_PROFILE_MASK;
3024 if (bargs->target == chunk_type)
3030 static int should_balance_chunk(struct btrfs_root *root,
3031 struct extent_buffer *leaf,
3032 struct btrfs_chunk *chunk, u64 chunk_offset)
3034 struct btrfs_balance_control *bctl = root->fs_info->balance_ctl;
3035 struct btrfs_balance_args *bargs = NULL;
3036 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3039 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3040 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3044 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3045 bargs = &bctl->data;
3046 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3048 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3049 bargs = &bctl->meta;
3051 /* profiles filter */
3052 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3053 chunk_profiles_filter(chunk_type, bargs)) {
3058 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3059 chunk_usage_filter(bctl->fs_info, chunk_offset, bargs)) {
3064 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3065 chunk_devid_filter(leaf, chunk, bargs)) {
3069 /* drange filter, makes sense only with devid filter */
3070 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3071 chunk_drange_filter(leaf, chunk, chunk_offset, bargs)) {
3076 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3077 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3081 /* soft profile changing mode */
3082 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3083 chunk_soft_convert_filter(chunk_type, bargs)) {
3088 * limited by count, must be the last filter
3090 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3091 if (bargs->limit == 0)
3100 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3102 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3103 struct btrfs_root *chunk_root = fs_info->chunk_root;
3104 struct btrfs_root *dev_root = fs_info->dev_root;
3105 struct list_head *devices;
3106 struct btrfs_device *device;
3109 struct btrfs_chunk *chunk;
3110 struct btrfs_path *path;
3111 struct btrfs_key key;
3112 struct btrfs_key found_key;
3113 struct btrfs_trans_handle *trans;
3114 struct extent_buffer *leaf;
3117 int enospc_errors = 0;
3118 bool counting = true;
3119 u64 limit_data = bctl->data.limit;
3120 u64 limit_meta = bctl->meta.limit;
3121 u64 limit_sys = bctl->sys.limit;
3123 /* step one make some room on all the devices */
3124 devices = &fs_info->fs_devices->devices;
3125 list_for_each_entry(device, devices, dev_list) {
3126 old_size = btrfs_device_get_total_bytes(device);
3127 size_to_free = div_factor(old_size, 1);
3128 size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
3129 if (!device->writeable ||
3130 btrfs_device_get_total_bytes(device) -
3131 btrfs_device_get_bytes_used(device) > size_to_free ||
3132 device->is_tgtdev_for_dev_replace)
3135 ret = btrfs_shrink_device(device, old_size - size_to_free);
3140 trans = btrfs_start_transaction(dev_root, 0);
3141 BUG_ON(IS_ERR(trans));
3143 ret = btrfs_grow_device(trans, device, old_size);
3146 btrfs_end_transaction(trans, dev_root);
3149 /* step two, relocate all the chunks */
3150 path = btrfs_alloc_path();
3156 /* zero out stat counters */
3157 spin_lock(&fs_info->balance_lock);
3158 memset(&bctl->stat, 0, sizeof(bctl->stat));
3159 spin_unlock(&fs_info->balance_lock);
3162 bctl->data.limit = limit_data;
3163 bctl->meta.limit = limit_meta;
3164 bctl->sys.limit = limit_sys;
3166 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3167 key.offset = (u64)-1;
3168 key.type = BTRFS_CHUNK_ITEM_KEY;
3171 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3172 atomic_read(&fs_info->balance_cancel_req)) {
3177 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3182 * this shouldn't happen, it means the last relocate
3186 BUG(); /* FIXME break ? */
3188 ret = btrfs_previous_item(chunk_root, path, 0,
3189 BTRFS_CHUNK_ITEM_KEY);
3195 leaf = path->nodes[0];
3196 slot = path->slots[0];
3197 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3199 if (found_key.objectid != key.objectid)
3202 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3205 spin_lock(&fs_info->balance_lock);
3206 bctl->stat.considered++;
3207 spin_unlock(&fs_info->balance_lock);
3210 ret = should_balance_chunk(chunk_root, leaf, chunk,
3212 btrfs_release_path(path);
3217 spin_lock(&fs_info->balance_lock);
3218 bctl->stat.expected++;
3219 spin_unlock(&fs_info->balance_lock);
3223 ret = btrfs_relocate_chunk(chunk_root,
3224 chunk_root->root_key.objectid,
3227 if (ret && ret != -ENOSPC)
3229 if (ret == -ENOSPC) {
3232 spin_lock(&fs_info->balance_lock);
3233 bctl->stat.completed++;
3234 spin_unlock(&fs_info->balance_lock);
3237 if (found_key.offset == 0)
3239 key.offset = found_key.offset - 1;
3243 btrfs_release_path(path);
3248 btrfs_free_path(path);
3249 if (enospc_errors) {
3250 btrfs_info(fs_info, "%d enospc errors during balance",
3260 * alloc_profile_is_valid - see if a given profile is valid and reduced
3261 * @flags: profile to validate
3262 * @extended: if true @flags is treated as an extended profile
3264 static int alloc_profile_is_valid(u64 flags, int extended)
3266 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3267 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3269 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3271 /* 1) check that all other bits are zeroed */
3275 /* 2) see if profile is reduced */
3277 return !extended; /* "0" is valid for usual profiles */
3279 /* true if exactly one bit set */
3280 return (flags & (flags - 1)) == 0;
3283 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3285 /* cancel requested || normal exit path */
3286 return atomic_read(&fs_info->balance_cancel_req) ||
3287 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3288 atomic_read(&fs_info->balance_cancel_req) == 0);
3291 static void __cancel_balance(struct btrfs_fs_info *fs_info)
3295 unset_balance_control(fs_info);
3296 ret = del_balance_item(fs_info->tree_root);
3298 btrfs_std_error(fs_info, ret);
3300 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3304 * Should be called with both balance and volume mutexes held
3306 int btrfs_balance(struct btrfs_balance_control *bctl,
3307 struct btrfs_ioctl_balance_args *bargs)
3309 struct btrfs_fs_info *fs_info = bctl->fs_info;
3316 if (btrfs_fs_closing(fs_info) ||
3317 atomic_read(&fs_info->balance_pause_req) ||
3318 atomic_read(&fs_info->balance_cancel_req)) {
3323 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3324 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3328 * In case of mixed groups both data and meta should be picked,
3329 * and identical options should be given for both of them.
3331 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3332 if (mixed && (bctl->flags & allowed)) {
3333 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3334 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3335 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3336 btrfs_err(fs_info, "with mixed groups data and "
3337 "metadata balance options must be the same");
3343 num_devices = fs_info->fs_devices->num_devices;
3344 btrfs_dev_replace_lock(&fs_info->dev_replace);
3345 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3346 BUG_ON(num_devices < 1);
3349 btrfs_dev_replace_unlock(&fs_info->dev_replace);
3350 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
3351 if (num_devices == 1)
3352 allowed |= BTRFS_BLOCK_GROUP_DUP;
3353 else if (num_devices > 1)
3354 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3355 if (num_devices > 2)
3356 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3357 if (num_devices > 3)
3358 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3359 BTRFS_BLOCK_GROUP_RAID6);
3360 if ((bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3361 (!alloc_profile_is_valid(bctl->data.target, 1) ||
3362 (bctl->data.target & ~allowed))) {
3363 btrfs_err(fs_info, "unable to start balance with target "
3364 "data profile %llu",
3369 if ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3370 (!alloc_profile_is_valid(bctl->meta.target, 1) ||
3371 (bctl->meta.target & ~allowed))) {
3373 "unable to start balance with target metadata profile %llu",
3378 if ((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3379 (!alloc_profile_is_valid(bctl->sys.target, 1) ||
3380 (bctl->sys.target & ~allowed))) {
3382 "unable to start balance with target system profile %llu",
3388 /* allow dup'ed data chunks only in mixed mode */
3389 if (!mixed && (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3390 (bctl->data.target & BTRFS_BLOCK_GROUP_DUP)) {
3391 btrfs_err(fs_info, "dup for data is not allowed");
3396 /* allow to reduce meta or sys integrity only if force set */
3397 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3398 BTRFS_BLOCK_GROUP_RAID10 |
3399 BTRFS_BLOCK_GROUP_RAID5 |
3400 BTRFS_BLOCK_GROUP_RAID6;
3402 seq = read_seqbegin(&fs_info->profiles_lock);
3404 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3405 (fs_info->avail_system_alloc_bits & allowed) &&
3406 !(bctl->sys.target & allowed)) ||
3407 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3408 (fs_info->avail_metadata_alloc_bits & allowed) &&
3409 !(bctl->meta.target & allowed))) {
3410 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3411 btrfs_info(fs_info, "force reducing metadata integrity");
3413 btrfs_err(fs_info, "balance will reduce metadata "
3414 "integrity, use force if you want this");
3419 } while (read_seqretry(&fs_info->profiles_lock, seq));
3421 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3422 int num_tolerated_disk_barrier_failures;
3423 u64 target = bctl->sys.target;
3425 num_tolerated_disk_barrier_failures =
3426 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3427 if (num_tolerated_disk_barrier_failures > 0 &&
3429 (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID0 |
3430 BTRFS_AVAIL_ALLOC_BIT_SINGLE)))
3431 num_tolerated_disk_barrier_failures = 0;
3432 else if (num_tolerated_disk_barrier_failures > 1 &&
3434 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)))
3435 num_tolerated_disk_barrier_failures = 1;
3437 fs_info->num_tolerated_disk_barrier_failures =
3438 num_tolerated_disk_barrier_failures;
3441 ret = insert_balance_item(fs_info->tree_root, bctl);
3442 if (ret && ret != -EEXIST)
3445 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3446 BUG_ON(ret == -EEXIST);
3447 set_balance_control(bctl);
3449 BUG_ON(ret != -EEXIST);
3450 spin_lock(&fs_info->balance_lock);
3451 update_balance_args(bctl);
3452 spin_unlock(&fs_info->balance_lock);
3455 atomic_inc(&fs_info->balance_running);
3456 mutex_unlock(&fs_info->balance_mutex);
3458 ret = __btrfs_balance(fs_info);
3460 mutex_lock(&fs_info->balance_mutex);
3461 atomic_dec(&fs_info->balance_running);
3463 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3464 fs_info->num_tolerated_disk_barrier_failures =
3465 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3469 memset(bargs, 0, sizeof(*bargs));
3470 update_ioctl_balance_args(fs_info, 0, bargs);
3473 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3474 balance_need_close(fs_info)) {
3475 __cancel_balance(fs_info);
3478 wake_up(&fs_info->balance_wait_q);
3482 if (bctl->flags & BTRFS_BALANCE_RESUME)
3483 __cancel_balance(fs_info);
3486 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3491 static int balance_kthread(void *data)
3493 struct btrfs_fs_info *fs_info = data;
3496 mutex_lock(&fs_info->volume_mutex);
3497 mutex_lock(&fs_info->balance_mutex);
3499 if (fs_info->balance_ctl) {
3500 btrfs_info(fs_info, "continuing balance");
3501 ret = btrfs_balance(fs_info->balance_ctl, NULL);
3504 mutex_unlock(&fs_info->balance_mutex);
3505 mutex_unlock(&fs_info->volume_mutex);
3510 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3512 struct task_struct *tsk;
3514 spin_lock(&fs_info->balance_lock);
3515 if (!fs_info->balance_ctl) {
3516 spin_unlock(&fs_info->balance_lock);
3519 spin_unlock(&fs_info->balance_lock);
3521 if (btrfs_test_opt(fs_info->tree_root, SKIP_BALANCE)) {
3522 btrfs_info(fs_info, "force skipping balance");
3526 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3527 return PTR_ERR_OR_ZERO(tsk);
3530 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3532 struct btrfs_balance_control *bctl;
3533 struct btrfs_balance_item *item;
3534 struct btrfs_disk_balance_args disk_bargs;
3535 struct btrfs_path *path;
3536 struct extent_buffer *leaf;
3537 struct btrfs_key key;
3540 path = btrfs_alloc_path();
3544 key.objectid = BTRFS_BALANCE_OBJECTID;
3545 key.type = BTRFS_BALANCE_ITEM_KEY;
3548 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3551 if (ret > 0) { /* ret = -ENOENT; */
3556 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3562 leaf = path->nodes[0];
3563 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3565 bctl->fs_info = fs_info;
3566 bctl->flags = btrfs_balance_flags(leaf, item);
3567 bctl->flags |= BTRFS_BALANCE_RESUME;
3569 btrfs_balance_data(leaf, item, &disk_bargs);
3570 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
3571 btrfs_balance_meta(leaf, item, &disk_bargs);
3572 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
3573 btrfs_balance_sys(leaf, item, &disk_bargs);
3574 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
3576 WARN_ON(atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1));
3578 mutex_lock(&fs_info->volume_mutex);
3579 mutex_lock(&fs_info->balance_mutex);
3581 set_balance_control(bctl);
3583 mutex_unlock(&fs_info->balance_mutex);
3584 mutex_unlock(&fs_info->volume_mutex);
3586 btrfs_free_path(path);
3590 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
3594 mutex_lock(&fs_info->balance_mutex);
3595 if (!fs_info->balance_ctl) {
3596 mutex_unlock(&fs_info->balance_mutex);
3600 if (atomic_read(&fs_info->balance_running)) {
3601 atomic_inc(&fs_info->balance_pause_req);
3602 mutex_unlock(&fs_info->balance_mutex);
3604 wait_event(fs_info->balance_wait_q,
3605 atomic_read(&fs_info->balance_running) == 0);
3607 mutex_lock(&fs_info->balance_mutex);
3608 /* we are good with balance_ctl ripped off from under us */
3609 BUG_ON(atomic_read(&fs_info->balance_running));
3610 atomic_dec(&fs_info->balance_pause_req);
3615 mutex_unlock(&fs_info->balance_mutex);
3619 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
3621 if (fs_info->sb->s_flags & MS_RDONLY)
3624 mutex_lock(&fs_info->balance_mutex);
3625 if (!fs_info->balance_ctl) {
3626 mutex_unlock(&fs_info->balance_mutex);
3630 atomic_inc(&fs_info->balance_cancel_req);
3632 * if we are running just wait and return, balance item is
3633 * deleted in btrfs_balance in this case
3635 if (atomic_read(&fs_info->balance_running)) {
3636 mutex_unlock(&fs_info->balance_mutex);
3637 wait_event(fs_info->balance_wait_q,
3638 atomic_read(&fs_info->balance_running) == 0);
3639 mutex_lock(&fs_info->balance_mutex);
3641 /* __cancel_balance needs volume_mutex */
3642 mutex_unlock(&fs_info->balance_mutex);
3643 mutex_lock(&fs_info->volume_mutex);
3644 mutex_lock(&fs_info->balance_mutex);
3646 if (fs_info->balance_ctl)
3647 __cancel_balance(fs_info);
3649 mutex_unlock(&fs_info->volume_mutex);
3652 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
3653 atomic_dec(&fs_info->balance_cancel_req);
3654 mutex_unlock(&fs_info->balance_mutex);
3658 static int btrfs_uuid_scan_kthread(void *data)
3660 struct btrfs_fs_info *fs_info = data;
3661 struct btrfs_root *root = fs_info->tree_root;
3662 struct btrfs_key key;
3663 struct btrfs_key max_key;
3664 struct btrfs_path *path = NULL;
3666 struct extent_buffer *eb;
3668 struct btrfs_root_item root_item;
3670 struct btrfs_trans_handle *trans = NULL;
3672 path = btrfs_alloc_path();
3679 key.type = BTRFS_ROOT_ITEM_KEY;
3682 max_key.objectid = (u64)-1;
3683 max_key.type = BTRFS_ROOT_ITEM_KEY;
3684 max_key.offset = (u64)-1;
3687 ret = btrfs_search_forward(root, &key, path, 0);
3694 if (key.type != BTRFS_ROOT_ITEM_KEY ||
3695 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
3696 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
3697 key.objectid > BTRFS_LAST_FREE_OBJECTID)
3700 eb = path->nodes[0];
3701 slot = path->slots[0];
3702 item_size = btrfs_item_size_nr(eb, slot);
3703 if (item_size < sizeof(root_item))
3706 read_extent_buffer(eb, &root_item,
3707 btrfs_item_ptr_offset(eb, slot),
3708 (int)sizeof(root_item));
3709 if (btrfs_root_refs(&root_item) == 0)
3712 if (!btrfs_is_empty_uuid(root_item.uuid) ||
3713 !btrfs_is_empty_uuid(root_item.received_uuid)) {
3717 btrfs_release_path(path);
3719 * 1 - subvol uuid item
3720 * 1 - received_subvol uuid item
3722 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
3723 if (IS_ERR(trans)) {
3724 ret = PTR_ERR(trans);
3732 if (!btrfs_is_empty_uuid(root_item.uuid)) {
3733 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
3735 BTRFS_UUID_KEY_SUBVOL,
3738 btrfs_warn(fs_info, "uuid_tree_add failed %d",
3744 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
3745 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
3746 root_item.received_uuid,
3747 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
3750 btrfs_warn(fs_info, "uuid_tree_add failed %d",
3758 ret = btrfs_end_transaction(trans, fs_info->uuid_root);
3764 btrfs_release_path(path);
3765 if (key.offset < (u64)-1) {
3767 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
3769 key.type = BTRFS_ROOT_ITEM_KEY;
3770 } else if (key.objectid < (u64)-1) {
3772 key.type = BTRFS_ROOT_ITEM_KEY;
3781 btrfs_free_path(path);
3782 if (trans && !IS_ERR(trans))
3783 btrfs_end_transaction(trans, fs_info->uuid_root);
3785 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
3787 fs_info->update_uuid_tree_gen = 1;
3788 up(&fs_info->uuid_tree_rescan_sem);
3793 * Callback for btrfs_uuid_tree_iterate().
3795 * 0 check succeeded, the entry is not outdated.
3796 * < 0 if an error occured.
3797 * > 0 if the check failed, which means the caller shall remove the entry.
3799 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
3800 u8 *uuid, u8 type, u64 subid)
3802 struct btrfs_key key;
3804 struct btrfs_root *subvol_root;
3806 if (type != BTRFS_UUID_KEY_SUBVOL &&
3807 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
3810 key.objectid = subid;
3811 key.type = BTRFS_ROOT_ITEM_KEY;
3812 key.offset = (u64)-1;
3813 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
3814 if (IS_ERR(subvol_root)) {
3815 ret = PTR_ERR(subvol_root);
3822 case BTRFS_UUID_KEY_SUBVOL:
3823 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
3826 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
3827 if (memcmp(uuid, subvol_root->root_item.received_uuid,
3837 static int btrfs_uuid_rescan_kthread(void *data)
3839 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
3843 * 1st step is to iterate through the existing UUID tree and
3844 * to delete all entries that contain outdated data.
3845 * 2nd step is to add all missing entries to the UUID tree.
3847 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
3849 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
3850 up(&fs_info->uuid_tree_rescan_sem);
3853 return btrfs_uuid_scan_kthread(data);
3856 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
3858 struct btrfs_trans_handle *trans;
3859 struct btrfs_root *tree_root = fs_info->tree_root;
3860 struct btrfs_root *uuid_root;
3861 struct task_struct *task;
3868 trans = btrfs_start_transaction(tree_root, 2);
3870 return PTR_ERR(trans);
3872 uuid_root = btrfs_create_tree(trans, fs_info,
3873 BTRFS_UUID_TREE_OBJECTID);
3874 if (IS_ERR(uuid_root)) {
3875 btrfs_abort_transaction(trans, tree_root,
3876 PTR_ERR(uuid_root));
3877 return PTR_ERR(uuid_root);
3880 fs_info->uuid_root = uuid_root;
3882 ret = btrfs_commit_transaction(trans, tree_root);
3886 down(&fs_info->uuid_tree_rescan_sem);
3887 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
3889 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
3890 btrfs_warn(fs_info, "failed to start uuid_scan task");
3891 up(&fs_info->uuid_tree_rescan_sem);
3892 return PTR_ERR(task);
3898 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
3900 struct task_struct *task;
3902 down(&fs_info->uuid_tree_rescan_sem);
3903 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
3905 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
3906 btrfs_warn(fs_info, "failed to start uuid_rescan task");
3907 up(&fs_info->uuid_tree_rescan_sem);
3908 return PTR_ERR(task);
3915 * shrinking a device means finding all of the device extents past
3916 * the new size, and then following the back refs to the chunks.
3917 * The chunk relocation code actually frees the device extent
3919 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
3921 struct btrfs_trans_handle *trans;
3922 struct btrfs_root *root = device->dev_root;
3923 struct btrfs_dev_extent *dev_extent = NULL;
3924 struct btrfs_path *path;
3932 bool retried = false;
3933 struct extent_buffer *l;
3934 struct btrfs_key key;
3935 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
3936 u64 old_total = btrfs_super_total_bytes(super_copy);
3937 u64 old_size = btrfs_device_get_total_bytes(device);
3938 u64 diff = old_size - new_size;
3940 if (device->is_tgtdev_for_dev_replace)
3943 path = btrfs_alloc_path();
3951 btrfs_device_set_total_bytes(device, new_size);
3952 if (device->writeable) {
3953 device->fs_devices->total_rw_bytes -= diff;
3954 spin_lock(&root->fs_info->free_chunk_lock);
3955 root->fs_info->free_chunk_space -= diff;
3956 spin_unlock(&root->fs_info->free_chunk_lock);
3958 unlock_chunks(root);
3961 key.objectid = device->devid;
3962 key.offset = (u64)-1;
3963 key.type = BTRFS_DEV_EXTENT_KEY;
3966 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3970 ret = btrfs_previous_item(root, path, 0, key.type);
3975 btrfs_release_path(path);
3980 slot = path->slots[0];
3981 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
3983 if (key.objectid != device->devid) {
3984 btrfs_release_path(path);
3988 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
3989 length = btrfs_dev_extent_length(l, dev_extent);
3991 if (key.offset + length <= new_size) {
3992 btrfs_release_path(path);
3996 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
3997 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
3998 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
3999 btrfs_release_path(path);
4001 ret = btrfs_relocate_chunk(root, chunk_tree, chunk_objectid,
4003 if (ret && ret != -ENOSPC)
4007 } while (key.offset-- > 0);
4009 if (failed && !retried) {
4013 } else if (failed && retried) {
4017 btrfs_device_set_total_bytes(device, old_size);
4018 if (device->writeable)
4019 device->fs_devices->total_rw_bytes += diff;
4020 spin_lock(&root->fs_info->free_chunk_lock);
4021 root->fs_info->free_chunk_space += diff;
4022 spin_unlock(&root->fs_info->free_chunk_lock);
4023 unlock_chunks(root);
4027 /* Shrinking succeeded, else we would be at "done". */
4028 trans = btrfs_start_transaction(root, 0);
4029 if (IS_ERR(trans)) {
4030 ret = PTR_ERR(trans);
4035 btrfs_device_set_disk_total_bytes(device, new_size);
4036 if (list_empty(&device->resized_list))
4037 list_add_tail(&device->resized_list,
4038 &root->fs_info->fs_devices->resized_devices);
4040 WARN_ON(diff > old_total);
4041 btrfs_set_super_total_bytes(super_copy, old_total - diff);
4042 unlock_chunks(root);
4044 /* Now btrfs_update_device() will change the on-disk size. */
4045 ret = btrfs_update_device(trans, device);
4046 btrfs_end_transaction(trans, root);
4048 btrfs_free_path(path);
4052 static int btrfs_add_system_chunk(struct btrfs_root *root,
4053 struct btrfs_key *key,
4054 struct btrfs_chunk *chunk, int item_size)
4056 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
4057 struct btrfs_disk_key disk_key;
4062 array_size = btrfs_super_sys_array_size(super_copy);
4063 if (array_size + item_size + sizeof(disk_key)
4064 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4065 unlock_chunks(root);
4069 ptr = super_copy->sys_chunk_array + array_size;
4070 btrfs_cpu_key_to_disk(&disk_key, key);
4071 memcpy(ptr, &disk_key, sizeof(disk_key));
4072 ptr += sizeof(disk_key);
4073 memcpy(ptr, chunk, item_size);
4074 item_size += sizeof(disk_key);
4075 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4076 unlock_chunks(root);
4082 * sort the devices in descending order by max_avail, total_avail
4084 static int btrfs_cmp_device_info(const void *a, const void *b)
4086 const struct btrfs_device_info *di_a = a;
4087 const struct btrfs_device_info *di_b = b;
4089 if (di_a->max_avail > di_b->max_avail)
4091 if (di_a->max_avail < di_b->max_avail)
4093 if (di_a->total_avail > di_b->total_avail)
4095 if (di_a->total_avail < di_b->total_avail)
4100 static struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
4101 [BTRFS_RAID_RAID10] = {
4104 .devs_max = 0, /* 0 == as many as possible */
4106 .devs_increment = 2,
4109 [BTRFS_RAID_RAID1] = {
4114 .devs_increment = 2,
4117 [BTRFS_RAID_DUP] = {
4122 .devs_increment = 1,
4125 [BTRFS_RAID_RAID0] = {
4130 .devs_increment = 1,
4133 [BTRFS_RAID_SINGLE] = {
4138 .devs_increment = 1,
4141 [BTRFS_RAID_RAID5] = {
4146 .devs_increment = 1,
4149 [BTRFS_RAID_RAID6] = {
4154 .devs_increment = 1,
4159 static u32 find_raid56_stripe_len(u32 data_devices, u32 dev_stripe_target)
4161 /* TODO allow them to set a preferred stripe size */
4165 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4167 if (!(type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)))
4170 btrfs_set_fs_incompat(info, RAID56);
4173 #define BTRFS_MAX_DEVS(r) ((BTRFS_LEAF_DATA_SIZE(r) \
4174 - sizeof(struct btrfs_item) \
4175 - sizeof(struct btrfs_chunk)) \
4176 / sizeof(struct btrfs_stripe) + 1)
4178 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4179 - 2 * sizeof(struct btrfs_disk_key) \
4180 - 2 * sizeof(struct btrfs_chunk)) \
4181 / sizeof(struct btrfs_stripe) + 1)
4183 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4184 struct btrfs_root *extent_root, u64 start,
4187 struct btrfs_fs_info *info = extent_root->fs_info;
4188 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4189 struct list_head *cur;
4190 struct map_lookup *map = NULL;
4191 struct extent_map_tree *em_tree;
4192 struct extent_map *em;
4193 struct btrfs_device_info *devices_info = NULL;
4195 int num_stripes; /* total number of stripes to allocate */
4196 int data_stripes; /* number of stripes that count for
4198 int sub_stripes; /* sub_stripes info for map */
4199 int dev_stripes; /* stripes per dev */
4200 int devs_max; /* max devs to use */
4201 int devs_min; /* min devs needed */
4202 int devs_increment; /* ndevs has to be a multiple of this */
4203 int ncopies; /* how many copies to data has */
4205 u64 max_stripe_size;
4209 u64 raid_stripe_len = BTRFS_STRIPE_LEN;
4215 BUG_ON(!alloc_profile_is_valid(type, 0));
4217 if (list_empty(&fs_devices->alloc_list))
4220 index = __get_raid_index(type);
4222 sub_stripes = btrfs_raid_array[index].sub_stripes;
4223 dev_stripes = btrfs_raid_array[index].dev_stripes;
4224 devs_max = btrfs_raid_array[index].devs_max;
4225 devs_min = btrfs_raid_array[index].devs_min;
4226 devs_increment = btrfs_raid_array[index].devs_increment;
4227 ncopies = btrfs_raid_array[index].ncopies;
4229 if (type & BTRFS_BLOCK_GROUP_DATA) {
4230 max_stripe_size = 1024 * 1024 * 1024;
4231 max_chunk_size = 10 * max_stripe_size;
4233 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4234 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4235 /* for larger filesystems, use larger metadata chunks */
4236 if (fs_devices->total_rw_bytes > 50ULL * 1024 * 1024 * 1024)
4237 max_stripe_size = 1024 * 1024 * 1024;
4239 max_stripe_size = 256 * 1024 * 1024;
4240 max_chunk_size = max_stripe_size;
4242 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4243 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4244 max_stripe_size = 32 * 1024 * 1024;
4245 max_chunk_size = 2 * max_stripe_size;
4247 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4249 btrfs_err(info, "invalid chunk type 0x%llx requested",
4254 /* we don't want a chunk larger than 10% of writeable space */
4255 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4258 devices_info = kzalloc(sizeof(*devices_info) * fs_devices->rw_devices,
4263 cur = fs_devices->alloc_list.next;
4266 * in the first pass through the devices list, we gather information
4267 * about the available holes on each device.
4270 while (cur != &fs_devices->alloc_list) {
4271 struct btrfs_device *device;
4275 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
4279 if (!device->writeable) {
4281 "BTRFS: read-only device in alloc_list\n");
4285 if (!device->in_fs_metadata ||
4286 device->is_tgtdev_for_dev_replace)
4289 if (device->total_bytes > device->bytes_used)
4290 total_avail = device->total_bytes - device->bytes_used;
4294 /* If there is no space on this device, skip it. */
4295 if (total_avail == 0)
4298 ret = find_free_dev_extent(trans, device,
4299 max_stripe_size * dev_stripes,
4300 &dev_offset, &max_avail);
4301 if (ret && ret != -ENOSPC)
4305 max_avail = max_stripe_size * dev_stripes;
4307 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
4310 if (ndevs == fs_devices->rw_devices) {
4311 WARN(1, "%s: found more than %llu devices\n",
4312 __func__, fs_devices->rw_devices);
4315 devices_info[ndevs].dev_offset = dev_offset;
4316 devices_info[ndevs].max_avail = max_avail;
4317 devices_info[ndevs].total_avail = total_avail;
4318 devices_info[ndevs].dev = device;
4323 * now sort the devices by hole size / available space
4325 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4326 btrfs_cmp_device_info, NULL);
4328 /* round down to number of usable stripes */
4329 ndevs -= ndevs % devs_increment;
4331 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
4336 if (devs_max && ndevs > devs_max)
4339 * the primary goal is to maximize the number of stripes, so use as many
4340 * devices as possible, even if the stripes are not maximum sized.
4342 stripe_size = devices_info[ndevs-1].max_avail;
4343 num_stripes = ndevs * dev_stripes;
4346 * this will have to be fixed for RAID1 and RAID10 over
4349 data_stripes = num_stripes / ncopies;
4351 if (type & BTRFS_BLOCK_GROUP_RAID5) {
4352 raid_stripe_len = find_raid56_stripe_len(ndevs - 1,
4353 btrfs_super_stripesize(info->super_copy));
4354 data_stripes = num_stripes - 1;
4356 if (type & BTRFS_BLOCK_GROUP_RAID6) {
4357 raid_stripe_len = find_raid56_stripe_len(ndevs - 2,
4358 btrfs_super_stripesize(info->super_copy));
4359 data_stripes = num_stripes - 2;
4363 * Use the number of data stripes to figure out how big this chunk
4364 * is really going to be in terms of logical address space,
4365 * and compare that answer with the max chunk size
4367 if (stripe_size * data_stripes > max_chunk_size) {
4368 u64 mask = (1ULL << 24) - 1;
4369 stripe_size = max_chunk_size;
4370 do_div(stripe_size, data_stripes);
4372 /* bump the answer up to a 16MB boundary */
4373 stripe_size = (stripe_size + mask) & ~mask;
4375 /* but don't go higher than the limits we found
4376 * while searching for free extents
4378 if (stripe_size > devices_info[ndevs-1].max_avail)
4379 stripe_size = devices_info[ndevs-1].max_avail;
4382 do_div(stripe_size, dev_stripes);
4384 /* align to BTRFS_STRIPE_LEN */
4385 do_div(stripe_size, raid_stripe_len);
4386 stripe_size *= raid_stripe_len;
4388 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4393 map->num_stripes = num_stripes;
4395 for (i = 0; i < ndevs; ++i) {
4396 for (j = 0; j < dev_stripes; ++j) {
4397 int s = i * dev_stripes + j;
4398 map->stripes[s].dev = devices_info[i].dev;
4399 map->stripes[s].physical = devices_info[i].dev_offset +
4403 map->sector_size = extent_root->sectorsize;
4404 map->stripe_len = raid_stripe_len;
4405 map->io_align = raid_stripe_len;
4406 map->io_width = raid_stripe_len;
4408 map->sub_stripes = sub_stripes;
4410 num_bytes = stripe_size * data_stripes;
4412 trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
4414 em = alloc_extent_map();
4420 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4421 em->bdev = (struct block_device *)map;
4423 em->len = num_bytes;
4424 em->block_start = 0;
4425 em->block_len = em->len;
4426 em->orig_block_len = stripe_size;
4428 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4429 write_lock(&em_tree->lock);
4430 ret = add_extent_mapping(em_tree, em, 0);
4432 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4433 atomic_inc(&em->refs);
4435 write_unlock(&em_tree->lock);
4437 free_extent_map(em);
4441 ret = btrfs_make_block_group(trans, extent_root, 0, type,
4442 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4445 goto error_del_extent;
4447 for (i = 0; i < map->num_stripes; i++) {
4448 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4449 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4452 spin_lock(&extent_root->fs_info->free_chunk_lock);
4453 extent_root->fs_info->free_chunk_space -= (stripe_size *
4455 spin_unlock(&extent_root->fs_info->free_chunk_lock);
4457 free_extent_map(em);
4458 check_raid56_incompat_flag(extent_root->fs_info, type);
4460 kfree(devices_info);
4464 write_lock(&em_tree->lock);
4465 remove_extent_mapping(em_tree, em);
4466 write_unlock(&em_tree->lock);
4468 /* One for our allocation */
4469 free_extent_map(em);
4470 /* One for the tree reference */
4471 free_extent_map(em);
4473 kfree(devices_info);
4477 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4478 struct btrfs_root *extent_root,
4479 u64 chunk_offset, u64 chunk_size)
4481 struct btrfs_key key;
4482 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
4483 struct btrfs_device *device;
4484 struct btrfs_chunk *chunk;
4485 struct btrfs_stripe *stripe;
4486 struct extent_map_tree *em_tree;
4487 struct extent_map *em;
4488 struct map_lookup *map;
4495 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4496 read_lock(&em_tree->lock);
4497 em = lookup_extent_mapping(em_tree, chunk_offset, chunk_size);
4498 read_unlock(&em_tree->lock);
4501 btrfs_crit(extent_root->fs_info, "unable to find logical "
4502 "%Lu len %Lu", chunk_offset, chunk_size);
4506 if (em->start != chunk_offset || em->len != chunk_size) {
4507 btrfs_crit(extent_root->fs_info, "found a bad mapping, wanted"
4508 " %Lu-%Lu, found %Lu-%Lu", chunk_offset,
4509 chunk_size, em->start, em->len);
4510 free_extent_map(em);
4514 map = (struct map_lookup *)em->bdev;
4515 item_size = btrfs_chunk_item_size(map->num_stripes);
4516 stripe_size = em->orig_block_len;
4518 chunk = kzalloc(item_size, GFP_NOFS);
4524 for (i = 0; i < map->num_stripes; i++) {
4525 device = map->stripes[i].dev;
4526 dev_offset = map->stripes[i].physical;
4528 ret = btrfs_update_device(trans, device);
4531 ret = btrfs_alloc_dev_extent(trans, device,
4532 chunk_root->root_key.objectid,
4533 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4534 chunk_offset, dev_offset,
4540 stripe = &chunk->stripe;
4541 for (i = 0; i < map->num_stripes; i++) {
4542 device = map->stripes[i].dev;
4543 dev_offset = map->stripes[i].physical;
4545 btrfs_set_stack_stripe_devid(stripe, device->devid);
4546 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4547 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4551 btrfs_set_stack_chunk_length(chunk, chunk_size);
4552 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4553 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4554 btrfs_set_stack_chunk_type(chunk, map->type);
4555 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4556 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4557 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4558 btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
4559 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
4561 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4562 key.type = BTRFS_CHUNK_ITEM_KEY;
4563 key.offset = chunk_offset;
4565 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4566 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4568 * TODO: Cleanup of inserted chunk root in case of
4571 ret = btrfs_add_system_chunk(chunk_root, &key, chunk,
4577 free_extent_map(em);
4582 * Chunk allocation falls into two parts. The first part does works
4583 * that make the new allocated chunk useable, but not do any operation
4584 * that modifies the chunk tree. The second part does the works that
4585 * require modifying the chunk tree. This division is important for the
4586 * bootstrap process of adding storage to a seed btrfs.
4588 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4589 struct btrfs_root *extent_root, u64 type)
4593 chunk_offset = find_next_chunk(extent_root->fs_info);
4594 return __btrfs_alloc_chunk(trans, extent_root, chunk_offset, type);
4597 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
4598 struct btrfs_root *root,
4599 struct btrfs_device *device)
4602 u64 sys_chunk_offset;
4604 struct btrfs_fs_info *fs_info = root->fs_info;
4605 struct btrfs_root *extent_root = fs_info->extent_root;
4608 chunk_offset = find_next_chunk(fs_info);
4609 alloc_profile = btrfs_get_alloc_profile(extent_root, 0);
4610 ret = __btrfs_alloc_chunk(trans, extent_root, chunk_offset,
4615 sys_chunk_offset = find_next_chunk(root->fs_info);
4616 alloc_profile = btrfs_get_alloc_profile(fs_info->chunk_root, 0);
4617 ret = __btrfs_alloc_chunk(trans, extent_root, sys_chunk_offset,
4622 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
4626 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
4627 BTRFS_BLOCK_GROUP_RAID10 |
4628 BTRFS_BLOCK_GROUP_RAID5 |
4629 BTRFS_BLOCK_GROUP_DUP)) {
4631 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
4640 int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
4642 struct extent_map *em;
4643 struct map_lookup *map;
4644 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4649 read_lock(&map_tree->map_tree.lock);
4650 em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
4651 read_unlock(&map_tree->map_tree.lock);
4655 map = (struct map_lookup *)em->bdev;
4656 for (i = 0; i < map->num_stripes; i++) {
4657 if (map->stripes[i].dev->missing) {
4662 if (!map->stripes[i].dev->writeable) {
4669 * If the number of missing devices is larger than max errors,
4670 * we can not write the data into that chunk successfully, so
4673 if (miss_ndevs > btrfs_chunk_max_errors(map))
4676 free_extent_map(em);
4680 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
4682 extent_map_tree_init(&tree->map_tree);
4685 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
4687 struct extent_map *em;
4690 write_lock(&tree->map_tree.lock);
4691 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
4693 remove_extent_mapping(&tree->map_tree, em);
4694 write_unlock(&tree->map_tree.lock);
4698 free_extent_map(em);
4699 /* once for the tree */
4700 free_extent_map(em);
4704 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
4706 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
4707 struct extent_map *em;
4708 struct map_lookup *map;
4709 struct extent_map_tree *em_tree = &map_tree->map_tree;
4712 read_lock(&em_tree->lock);
4713 em = lookup_extent_mapping(em_tree, logical, len);
4714 read_unlock(&em_tree->lock);
4717 * We could return errors for these cases, but that could get ugly and
4718 * we'd probably do the same thing which is just not do anything else
4719 * and exit, so return 1 so the callers don't try to use other copies.
4722 btrfs_crit(fs_info, "No mapping for %Lu-%Lu", logical,
4727 if (em->start > logical || em->start + em->len < logical) {
4728 btrfs_crit(fs_info, "Invalid mapping for %Lu-%Lu, got "
4729 "%Lu-%Lu", logical, logical+len, em->start,
4730 em->start + em->len);
4731 free_extent_map(em);
4735 map = (struct map_lookup *)em->bdev;
4736 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
4737 ret = map->num_stripes;
4738 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
4739 ret = map->sub_stripes;
4740 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
4742 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
4746 free_extent_map(em);
4748 btrfs_dev_replace_lock(&fs_info->dev_replace);
4749 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))
4751 btrfs_dev_replace_unlock(&fs_info->dev_replace);
4756 unsigned long btrfs_full_stripe_len(struct btrfs_root *root,
4757 struct btrfs_mapping_tree *map_tree,
4760 struct extent_map *em;
4761 struct map_lookup *map;
4762 struct extent_map_tree *em_tree = &map_tree->map_tree;
4763 unsigned long len = root->sectorsize;
4765 read_lock(&em_tree->lock);
4766 em = lookup_extent_mapping(em_tree, logical, len);
4767 read_unlock(&em_tree->lock);
4770 BUG_ON(em->start > logical || em->start + em->len < logical);
4771 map = (struct map_lookup *)em->bdev;
4772 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4773 BTRFS_BLOCK_GROUP_RAID6)) {
4774 len = map->stripe_len * nr_data_stripes(map);
4776 free_extent_map(em);
4780 int btrfs_is_parity_mirror(struct btrfs_mapping_tree *map_tree,
4781 u64 logical, u64 len, int mirror_num)
4783 struct extent_map *em;
4784 struct map_lookup *map;
4785 struct extent_map_tree *em_tree = &map_tree->map_tree;
4788 read_lock(&em_tree->lock);
4789 em = lookup_extent_mapping(em_tree, logical, len);
4790 read_unlock(&em_tree->lock);
4793 BUG_ON(em->start > logical || em->start + em->len < logical);
4794 map = (struct map_lookup *)em->bdev;
4795 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4796 BTRFS_BLOCK_GROUP_RAID6))
4798 free_extent_map(em);
4802 static int find_live_mirror(struct btrfs_fs_info *fs_info,
4803 struct map_lookup *map, int first, int num,
4804 int optimal, int dev_replace_is_ongoing)
4808 struct btrfs_device *srcdev;
4810 if (dev_replace_is_ongoing &&
4811 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
4812 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
4813 srcdev = fs_info->dev_replace.srcdev;
4818 * try to avoid the drive that is the source drive for a
4819 * dev-replace procedure, only choose it if no other non-missing
4820 * mirror is available
4822 for (tolerance = 0; tolerance < 2; tolerance++) {
4823 if (map->stripes[optimal].dev->bdev &&
4824 (tolerance || map->stripes[optimal].dev != srcdev))
4826 for (i = first; i < first + num; i++) {
4827 if (map->stripes[i].dev->bdev &&
4828 (tolerance || map->stripes[i].dev != srcdev))
4833 /* we couldn't find one that doesn't fail. Just return something
4834 * and the io error handling code will clean up eventually
4839 static inline int parity_smaller(u64 a, u64 b)
4844 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
4845 static void sort_parity_stripes(struct btrfs_bio *bbio, u64 *raid_map)
4847 struct btrfs_bio_stripe s;
4854 for (i = 0; i < bbio->num_stripes - 1; i++) {
4855 if (parity_smaller(raid_map[i], raid_map[i+1])) {
4856 s = bbio->stripes[i];
4858 bbio->stripes[i] = bbio->stripes[i+1];
4859 raid_map[i] = raid_map[i+1];
4860 bbio->stripes[i+1] = s;
4868 static int __btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
4869 u64 logical, u64 *length,
4870 struct btrfs_bio **bbio_ret,
4871 int mirror_num, u64 **raid_map_ret)
4873 struct extent_map *em;
4874 struct map_lookup *map;
4875 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
4876 struct extent_map_tree *em_tree = &map_tree->map_tree;
4879 u64 stripe_end_offset;
4884 u64 *raid_map = NULL;
4890 struct btrfs_bio *bbio = NULL;
4891 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
4892 int dev_replace_is_ongoing = 0;
4893 int num_alloc_stripes;
4894 int patch_the_first_stripe_for_dev_replace = 0;
4895 u64 physical_to_patch_in_first_stripe = 0;
4896 u64 raid56_full_stripe_start = (u64)-1;
4898 read_lock(&em_tree->lock);
4899 em = lookup_extent_mapping(em_tree, logical, *length);
4900 read_unlock(&em_tree->lock);
4903 btrfs_crit(fs_info, "unable to find logical %llu len %llu",
4908 if (em->start > logical || em->start + em->len < logical) {
4909 btrfs_crit(fs_info, "found a bad mapping, wanted %Lu, "
4910 "found %Lu-%Lu", logical, em->start,
4911 em->start + em->len);
4912 free_extent_map(em);
4916 map = (struct map_lookup *)em->bdev;
4917 offset = logical - em->start;
4919 stripe_len = map->stripe_len;
4922 * stripe_nr counts the total number of stripes we have to stride
4923 * to get to this block
4925 do_div(stripe_nr, stripe_len);
4927 stripe_offset = stripe_nr * stripe_len;
4928 BUG_ON(offset < stripe_offset);
4930 /* stripe_offset is the offset of this block in its stripe*/
4931 stripe_offset = offset - stripe_offset;
4933 /* if we're here for raid56, we need to know the stripe aligned start */
4934 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
4935 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
4936 raid56_full_stripe_start = offset;
4938 /* allow a write of a full stripe, but make sure we don't
4939 * allow straddling of stripes
4941 do_div(raid56_full_stripe_start, full_stripe_len);
4942 raid56_full_stripe_start *= full_stripe_len;
4945 if (rw & REQ_DISCARD) {
4946 /* we don't discard raid56 yet */
4948 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
4952 *length = min_t(u64, em->len - offset, *length);
4953 } else if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
4955 /* For writes to RAID[56], allow a full stripeset across all disks.
4956 For other RAID types and for RAID[56] reads, just allow a single
4957 stripe (on a single disk). */
4958 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6) &&
4960 max_len = stripe_len * nr_data_stripes(map) -
4961 (offset - raid56_full_stripe_start);
4963 /* we limit the length of each bio to what fits in a stripe */
4964 max_len = stripe_len - stripe_offset;
4966 *length = min_t(u64, em->len - offset, max_len);
4968 *length = em->len - offset;
4971 /* This is for when we're called from btrfs_merge_bio_hook() and all
4972 it cares about is the length */
4976 btrfs_dev_replace_lock(dev_replace);
4977 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
4978 if (!dev_replace_is_ongoing)
4979 btrfs_dev_replace_unlock(dev_replace);
4981 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
4982 !(rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) &&
4983 dev_replace->tgtdev != NULL) {
4985 * in dev-replace case, for repair case (that's the only
4986 * case where the mirror is selected explicitly when
4987 * calling btrfs_map_block), blocks left of the left cursor
4988 * can also be read from the target drive.
4989 * For REQ_GET_READ_MIRRORS, the target drive is added as
4990 * the last one to the array of stripes. For READ, it also
4991 * needs to be supported using the same mirror number.
4992 * If the requested block is not left of the left cursor,
4993 * EIO is returned. This can happen because btrfs_num_copies()
4994 * returns one more in the dev-replace case.
4996 u64 tmp_length = *length;
4997 struct btrfs_bio *tmp_bbio = NULL;
4998 int tmp_num_stripes;
4999 u64 srcdev_devid = dev_replace->srcdev->devid;
5000 int index_srcdev = 0;
5002 u64 physical_of_found = 0;
5004 ret = __btrfs_map_block(fs_info, REQ_GET_READ_MIRRORS,
5005 logical, &tmp_length, &tmp_bbio, 0, NULL);
5007 WARN_ON(tmp_bbio != NULL);
5011 tmp_num_stripes = tmp_bbio->num_stripes;
5012 if (mirror_num > tmp_num_stripes) {
5014 * REQ_GET_READ_MIRRORS does not contain this
5015 * mirror, that means that the requested area
5016 * is not left of the left cursor
5024 * process the rest of the function using the mirror_num
5025 * of the source drive. Therefore look it up first.
5026 * At the end, patch the device pointer to the one of the
5029 for (i = 0; i < tmp_num_stripes; i++) {
5030 if (tmp_bbio->stripes[i].dev->devid == srcdev_devid) {
5032 * In case of DUP, in order to keep it
5033 * simple, only add the mirror with the
5034 * lowest physical address
5037 physical_of_found <=
5038 tmp_bbio->stripes[i].physical)
5043 tmp_bbio->stripes[i].physical;
5048 mirror_num = index_srcdev + 1;
5049 patch_the_first_stripe_for_dev_replace = 1;
5050 physical_to_patch_in_first_stripe = physical_of_found;
5059 } else if (mirror_num > map->num_stripes) {
5065 stripe_nr_orig = stripe_nr;
5066 stripe_nr_end = ALIGN(offset + *length, map->stripe_len);
5067 do_div(stripe_nr_end, map->stripe_len);
5068 stripe_end_offset = stripe_nr_end * map->stripe_len -
5071 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5072 if (rw & REQ_DISCARD)
5073 num_stripes = min_t(u64, map->num_stripes,
5074 stripe_nr_end - stripe_nr_orig);
5075 stripe_index = do_div(stripe_nr, map->num_stripes);
5076 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5077 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS))
5078 num_stripes = map->num_stripes;
5079 else if (mirror_num)
5080 stripe_index = mirror_num - 1;
5082 stripe_index = find_live_mirror(fs_info, map, 0,
5084 current->pid % map->num_stripes,
5085 dev_replace_is_ongoing);
5086 mirror_num = stripe_index + 1;
5089 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5090 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) {
5091 num_stripes = map->num_stripes;
5092 } else if (mirror_num) {
5093 stripe_index = mirror_num - 1;
5098 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5099 int factor = map->num_stripes / map->sub_stripes;
5101 stripe_index = do_div(stripe_nr, factor);
5102 stripe_index *= map->sub_stripes;
5104 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
5105 num_stripes = map->sub_stripes;
5106 else if (rw & REQ_DISCARD)
5107 num_stripes = min_t(u64, map->sub_stripes *
5108 (stripe_nr_end - stripe_nr_orig),
5110 else if (mirror_num)
5111 stripe_index += mirror_num - 1;
5113 int old_stripe_index = stripe_index;
5114 stripe_index = find_live_mirror(fs_info, map,
5116 map->sub_stripes, stripe_index +
5117 current->pid % map->sub_stripes,
5118 dev_replace_is_ongoing);
5119 mirror_num = stripe_index - old_stripe_index + 1;
5122 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
5123 BTRFS_BLOCK_GROUP_RAID6)) {
5126 if (bbio_ret && ((rw & REQ_WRITE) || mirror_num > 1)
5130 /* push stripe_nr back to the start of the full stripe */
5131 stripe_nr = raid56_full_stripe_start;
5132 do_div(stripe_nr, stripe_len);
5134 stripe_index = do_div(stripe_nr, nr_data_stripes(map));
5136 /* RAID[56] write or recovery. Return all stripes */
5137 num_stripes = map->num_stripes;
5138 max_errors = nr_parity_stripes(map);
5140 raid_map = kmalloc_array(num_stripes, sizeof(u64),
5147 /* Work out the disk rotation on this stripe-set */
5149 rot = do_div(tmp, num_stripes);
5151 /* Fill in the logical address of each stripe */
5152 tmp = stripe_nr * nr_data_stripes(map);
5153 for (i = 0; i < nr_data_stripes(map); i++)
5154 raid_map[(i+rot) % num_stripes] =
5155 em->start + (tmp + i) * map->stripe_len;
5157 raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5158 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5159 raid_map[(i+rot+1) % num_stripes] =
5162 *length = map->stripe_len;
5167 * Mirror #0 or #1 means the original data block.
5168 * Mirror #2 is RAID5 parity block.
5169 * Mirror #3 is RAID6 Q block.
5171 stripe_index = do_div(stripe_nr, nr_data_stripes(map));
5173 stripe_index = nr_data_stripes(map) +
5176 /* We distribute the parity blocks across stripes */
5177 tmp = stripe_nr + stripe_index;
5178 stripe_index = do_div(tmp, map->num_stripes);
5182 * after this do_div call, stripe_nr is the number of stripes
5183 * on this device we have to walk to find the data, and
5184 * stripe_index is the number of our device in the stripe array
5186 stripe_index = do_div(stripe_nr, map->num_stripes);
5187 mirror_num = stripe_index + 1;
5189 BUG_ON(stripe_index >= map->num_stripes);
5191 num_alloc_stripes = num_stripes;
5192 if (dev_replace_is_ongoing) {
5193 if (rw & (REQ_WRITE | REQ_DISCARD))
5194 num_alloc_stripes <<= 1;
5195 if (rw & REQ_GET_READ_MIRRORS)
5196 num_alloc_stripes++;
5198 bbio = kzalloc(btrfs_bio_size(num_alloc_stripes), GFP_NOFS);
5204 atomic_set(&bbio->error, 0);
5206 if (rw & REQ_DISCARD) {
5208 int sub_stripes = 0;
5209 u64 stripes_per_dev = 0;
5210 u32 remaining_stripes = 0;
5211 u32 last_stripe = 0;
5214 (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
5215 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5218 sub_stripes = map->sub_stripes;
5220 factor = map->num_stripes / sub_stripes;
5221 stripes_per_dev = div_u64_rem(stripe_nr_end -
5224 &remaining_stripes);
5225 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5226 last_stripe *= sub_stripes;
5229 for (i = 0; i < num_stripes; i++) {
5230 bbio->stripes[i].physical =
5231 map->stripes[stripe_index].physical +
5232 stripe_offset + stripe_nr * map->stripe_len;
5233 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5235 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5236 BTRFS_BLOCK_GROUP_RAID10)) {
5237 bbio->stripes[i].length = stripes_per_dev *
5240 if (i / sub_stripes < remaining_stripes)
5241 bbio->stripes[i].length +=
5245 * Special for the first stripe and
5248 * |-------|...|-------|
5252 if (i < sub_stripes)
5253 bbio->stripes[i].length -=
5256 if (stripe_index >= last_stripe &&
5257 stripe_index <= (last_stripe +
5259 bbio->stripes[i].length -=
5262 if (i == sub_stripes - 1)
5265 bbio->stripes[i].length = *length;
5268 if (stripe_index == map->num_stripes) {
5269 /* This could only happen for RAID0/10 */
5275 for (i = 0; i < num_stripes; i++) {
5276 bbio->stripes[i].physical =
5277 map->stripes[stripe_index].physical +
5279 stripe_nr * map->stripe_len;
5280 bbio->stripes[i].dev =
5281 map->stripes[stripe_index].dev;
5286 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
5287 max_errors = btrfs_chunk_max_errors(map);
5289 if (dev_replace_is_ongoing && (rw & (REQ_WRITE | REQ_DISCARD)) &&
5290 dev_replace->tgtdev != NULL) {
5291 int index_where_to_add;
5292 u64 srcdev_devid = dev_replace->srcdev->devid;
5295 * duplicate the write operations while the dev replace
5296 * procedure is running. Since the copying of the old disk
5297 * to the new disk takes place at run time while the
5298 * filesystem is mounted writable, the regular write
5299 * operations to the old disk have to be duplicated to go
5300 * to the new disk as well.
5301 * Note that device->missing is handled by the caller, and
5302 * that the write to the old disk is already set up in the
5305 index_where_to_add = num_stripes;
5306 for (i = 0; i < num_stripes; i++) {
5307 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5308 /* write to new disk, too */
5309 struct btrfs_bio_stripe *new =
5310 bbio->stripes + index_where_to_add;
5311 struct btrfs_bio_stripe *old =
5314 new->physical = old->physical;
5315 new->length = old->length;
5316 new->dev = dev_replace->tgtdev;
5317 index_where_to_add++;
5321 num_stripes = index_where_to_add;
5322 } else if (dev_replace_is_ongoing && (rw & REQ_GET_READ_MIRRORS) &&
5323 dev_replace->tgtdev != NULL) {
5324 u64 srcdev_devid = dev_replace->srcdev->devid;
5325 int index_srcdev = 0;
5327 u64 physical_of_found = 0;
5330 * During the dev-replace procedure, the target drive can
5331 * also be used to read data in case it is needed to repair
5332 * a corrupt block elsewhere. This is possible if the
5333 * requested area is left of the left cursor. In this area,
5334 * the target drive is a full copy of the source drive.
5336 for (i = 0; i < num_stripes; i++) {
5337 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5339 * In case of DUP, in order to keep it
5340 * simple, only add the mirror with the
5341 * lowest physical address
5344 physical_of_found <=
5345 bbio->stripes[i].physical)
5349 physical_of_found = bbio->stripes[i].physical;
5353 u64 length = map->stripe_len;
5355 if (physical_of_found + length <=
5356 dev_replace->cursor_left) {
5357 struct btrfs_bio_stripe *tgtdev_stripe =
5358 bbio->stripes + num_stripes;
5360 tgtdev_stripe->physical = physical_of_found;
5361 tgtdev_stripe->length =
5362 bbio->stripes[index_srcdev].length;
5363 tgtdev_stripe->dev = dev_replace->tgtdev;
5371 bbio->num_stripes = num_stripes;
5372 bbio->max_errors = max_errors;
5373 bbio->mirror_num = mirror_num;
5376 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5377 * mirror_num == num_stripes + 1 && dev_replace target drive is
5378 * available as a mirror
5380 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5381 WARN_ON(num_stripes > 1);
5382 bbio->stripes[0].dev = dev_replace->tgtdev;
5383 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5384 bbio->mirror_num = map->num_stripes + 1;
5387 sort_parity_stripes(bbio, raid_map);
5388 *raid_map_ret = raid_map;
5391 if (dev_replace_is_ongoing)
5392 btrfs_dev_replace_unlock(dev_replace);
5393 free_extent_map(em);
5397 int btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
5398 u64 logical, u64 *length,
5399 struct btrfs_bio **bbio_ret, int mirror_num)
5401 return __btrfs_map_block(fs_info, rw, logical, length, bbio_ret,
5405 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
5406 u64 chunk_start, u64 physical, u64 devid,
5407 u64 **logical, int *naddrs, int *stripe_len)
5409 struct extent_map_tree *em_tree = &map_tree->map_tree;
5410 struct extent_map *em;
5411 struct map_lookup *map;
5419 read_lock(&em_tree->lock);
5420 em = lookup_extent_mapping(em_tree, chunk_start, 1);
5421 read_unlock(&em_tree->lock);
5424 printk(KERN_ERR "BTRFS: couldn't find em for chunk %Lu\n",
5429 if (em->start != chunk_start) {
5430 printk(KERN_ERR "BTRFS: bad chunk start, em=%Lu, wanted=%Lu\n",
5431 em->start, chunk_start);
5432 free_extent_map(em);
5435 map = (struct map_lookup *)em->bdev;
5438 rmap_len = map->stripe_len;
5440 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5441 do_div(length, map->num_stripes / map->sub_stripes);
5442 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5443 do_div(length, map->num_stripes);
5444 else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
5445 BTRFS_BLOCK_GROUP_RAID6)) {
5446 do_div(length, nr_data_stripes(map));
5447 rmap_len = map->stripe_len * nr_data_stripes(map);
5450 buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
5451 BUG_ON(!buf); /* -ENOMEM */
5453 for (i = 0; i < map->num_stripes; i++) {
5454 if (devid && map->stripes[i].dev->devid != devid)
5456 if (map->stripes[i].physical > physical ||
5457 map->stripes[i].physical + length <= physical)
5460 stripe_nr = physical - map->stripes[i].physical;
5461 do_div(stripe_nr, map->stripe_len);
5463 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5464 stripe_nr = stripe_nr * map->num_stripes + i;
5465 do_div(stripe_nr, map->sub_stripes);
5466 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5467 stripe_nr = stripe_nr * map->num_stripes + i;
5468 } /* else if RAID[56], multiply by nr_data_stripes().
5469 * Alternatively, just use rmap_len below instead of
5470 * map->stripe_len */
5472 bytenr = chunk_start + stripe_nr * rmap_len;
5473 WARN_ON(nr >= map->num_stripes);
5474 for (j = 0; j < nr; j++) {
5475 if (buf[j] == bytenr)
5479 WARN_ON(nr >= map->num_stripes);
5486 *stripe_len = rmap_len;
5488 free_extent_map(em);
5492 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio, int err)
5494 if (likely(bbio->flags & BTRFS_BIO_ORIG_BIO_SUBMITTED))
5495 bio_endio_nodec(bio, err);
5497 bio_endio(bio, err);
5501 static void btrfs_end_bio(struct bio *bio, int err)
5503 struct btrfs_bio *bbio = bio->bi_private;
5504 struct btrfs_device *dev = bbio->stripes[0].dev;
5505 int is_orig_bio = 0;
5508 atomic_inc(&bbio->error);
5509 if (err == -EIO || err == -EREMOTEIO) {
5510 unsigned int stripe_index =
5511 btrfs_io_bio(bio)->stripe_index;
5513 BUG_ON(stripe_index >= bbio->num_stripes);
5514 dev = bbio->stripes[stripe_index].dev;
5516 if (bio->bi_rw & WRITE)
5517 btrfs_dev_stat_inc(dev,
5518 BTRFS_DEV_STAT_WRITE_ERRS);
5520 btrfs_dev_stat_inc(dev,
5521 BTRFS_DEV_STAT_READ_ERRS);
5522 if ((bio->bi_rw & WRITE_FLUSH) == WRITE_FLUSH)
5523 btrfs_dev_stat_inc(dev,
5524 BTRFS_DEV_STAT_FLUSH_ERRS);
5525 btrfs_dev_stat_print_on_error(dev);
5530 if (bio == bbio->orig_bio)
5533 btrfs_bio_counter_dec(bbio->fs_info);
5535 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5538 bio = bbio->orig_bio;
5541 bio->bi_private = bbio->private;
5542 bio->bi_end_io = bbio->end_io;
5543 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5544 /* only send an error to the higher layers if it is
5545 * beyond the tolerance of the btrfs bio
5547 if (atomic_read(&bbio->error) > bbio->max_errors) {
5551 * this bio is actually up to date, we didn't
5552 * go over the max number of errors
5554 set_bit(BIO_UPTODATE, &bio->bi_flags);
5558 btrfs_end_bbio(bbio, bio, err);
5559 } else if (!is_orig_bio) {
5565 * see run_scheduled_bios for a description of why bios are collected for
5568 * This will add one bio to the pending list for a device and make sure
5569 * the work struct is scheduled.
5571 static noinline void btrfs_schedule_bio(struct btrfs_root *root,
5572 struct btrfs_device *device,
5573 int rw, struct bio *bio)
5575 int should_queue = 1;
5576 struct btrfs_pending_bios *pending_bios;
5578 if (device->missing || !device->bdev) {
5579 bio_endio(bio, -EIO);
5583 /* don't bother with additional async steps for reads, right now */
5584 if (!(rw & REQ_WRITE)) {
5586 btrfsic_submit_bio(rw, bio);
5592 * nr_async_bios allows us to reliably return congestion to the
5593 * higher layers. Otherwise, the async bio makes it appear we have
5594 * made progress against dirty pages when we've really just put it
5595 * on a queue for later
5597 atomic_inc(&root->fs_info->nr_async_bios);
5598 WARN_ON(bio->bi_next);
5599 bio->bi_next = NULL;
5602 spin_lock(&device->io_lock);
5603 if (bio->bi_rw & REQ_SYNC)
5604 pending_bios = &device->pending_sync_bios;
5606 pending_bios = &device->pending_bios;
5608 if (pending_bios->tail)
5609 pending_bios->tail->bi_next = bio;
5611 pending_bios->tail = bio;
5612 if (!pending_bios->head)
5613 pending_bios->head = bio;
5614 if (device->running_pending)
5617 spin_unlock(&device->io_lock);
5620 btrfs_queue_work(root->fs_info->submit_workers,
5624 static int bio_size_ok(struct block_device *bdev, struct bio *bio,
5627 struct bio_vec *prev;
5628 struct request_queue *q = bdev_get_queue(bdev);
5629 unsigned int max_sectors = queue_max_sectors(q);
5630 struct bvec_merge_data bvm = {
5632 .bi_sector = sector,
5633 .bi_rw = bio->bi_rw,
5636 if (WARN_ON(bio->bi_vcnt == 0))
5639 prev = &bio->bi_io_vec[bio->bi_vcnt - 1];
5640 if (bio_sectors(bio) > max_sectors)
5643 if (!q->merge_bvec_fn)
5646 bvm.bi_size = bio->bi_iter.bi_size - prev->bv_len;
5647 if (q->merge_bvec_fn(q, &bvm, prev) < prev->bv_len)
5652 static void submit_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5653 struct bio *bio, u64 physical, int dev_nr,
5656 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
5658 bio->bi_private = bbio;
5659 btrfs_io_bio(bio)->stripe_index = dev_nr;
5660 bio->bi_end_io = btrfs_end_bio;
5661 bio->bi_iter.bi_sector = physical >> 9;
5664 struct rcu_string *name;
5667 name = rcu_dereference(dev->name);
5668 pr_debug("btrfs_map_bio: rw %d, sector=%llu, dev=%lu "
5669 "(%s id %llu), size=%u\n", rw,
5670 (u64)bio->bi_sector, (u_long)dev->bdev->bd_dev,
5671 name->str, dev->devid, bio->bi_size);
5675 bio->bi_bdev = dev->bdev;
5677 btrfs_bio_counter_inc_noblocked(root->fs_info);
5680 btrfs_schedule_bio(root, dev, rw, bio);
5682 btrfsic_submit_bio(rw, bio);
5685 static int breakup_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5686 struct bio *first_bio, struct btrfs_device *dev,
5687 int dev_nr, int rw, int async)
5689 struct bio_vec *bvec = first_bio->bi_io_vec;
5691 int nr_vecs = bio_get_nr_vecs(dev->bdev);
5692 u64 physical = bbio->stripes[dev_nr].physical;
5695 bio = btrfs_bio_alloc(dev->bdev, physical >> 9, nr_vecs, GFP_NOFS);
5699 while (bvec <= (first_bio->bi_io_vec + first_bio->bi_vcnt - 1)) {
5700 if (bio_add_page(bio, bvec->bv_page, bvec->bv_len,
5701 bvec->bv_offset) < bvec->bv_len) {
5702 u64 len = bio->bi_iter.bi_size;
5704 atomic_inc(&bbio->stripes_pending);
5705 submit_stripe_bio(root, bbio, bio, physical, dev_nr,
5713 submit_stripe_bio(root, bbio, bio, physical, dev_nr, rw, async);
5717 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
5719 atomic_inc(&bbio->error);
5720 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5721 /* Shoud be the original bio. */
5722 WARN_ON(bio != bbio->orig_bio);
5724 bio->bi_private = bbio->private;
5725 bio->bi_end_io = bbio->end_io;
5726 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5727 bio->bi_iter.bi_sector = logical >> 9;
5729 btrfs_end_bbio(bbio, bio, -EIO);
5733 int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
5734 int mirror_num, int async_submit)
5736 struct btrfs_device *dev;
5737 struct bio *first_bio = bio;
5738 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
5741 u64 *raid_map = NULL;
5745 struct btrfs_bio *bbio = NULL;
5747 length = bio->bi_iter.bi_size;
5748 map_length = length;
5750 btrfs_bio_counter_inc_blocked(root->fs_info);
5751 ret = __btrfs_map_block(root->fs_info, rw, logical, &map_length, &bbio,
5752 mirror_num, &raid_map);
5754 btrfs_bio_counter_dec(root->fs_info);
5758 total_devs = bbio->num_stripes;
5759 bbio->orig_bio = first_bio;
5760 bbio->private = first_bio->bi_private;
5761 bbio->end_io = first_bio->bi_end_io;
5762 bbio->fs_info = root->fs_info;
5763 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
5766 /* In this case, map_length has been set to the length of
5767 a single stripe; not the whole write */
5769 ret = raid56_parity_write(root, bio, bbio,
5770 raid_map, map_length);
5772 ret = raid56_parity_recover(root, bio, bbio,
5773 raid_map, map_length,
5777 * FIXME, replace dosen't support raid56 yet, please fix
5780 btrfs_bio_counter_dec(root->fs_info);
5784 if (map_length < length) {
5785 btrfs_crit(root->fs_info, "mapping failed logical %llu bio len %llu len %llu",
5786 logical, length, map_length);
5790 while (dev_nr < total_devs) {
5791 dev = bbio->stripes[dev_nr].dev;
5792 if (!dev || !dev->bdev || (rw & WRITE && !dev->writeable)) {
5793 bbio_error(bbio, first_bio, logical);
5799 * Check and see if we're ok with this bio based on it's size
5800 * and offset with the given device.
5802 if (!bio_size_ok(dev->bdev, first_bio,
5803 bbio->stripes[dev_nr].physical >> 9)) {
5804 ret = breakup_stripe_bio(root, bbio, first_bio, dev,
5805 dev_nr, rw, async_submit);
5811 if (dev_nr < total_devs - 1) {
5812 bio = btrfs_bio_clone(first_bio, GFP_NOFS);
5813 BUG_ON(!bio); /* -ENOMEM */
5816 bbio->flags |= BTRFS_BIO_ORIG_BIO_SUBMITTED;
5819 submit_stripe_bio(root, bbio, bio,
5820 bbio->stripes[dev_nr].physical, dev_nr, rw,
5824 btrfs_bio_counter_dec(root->fs_info);
5828 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
5831 struct btrfs_device *device;
5832 struct btrfs_fs_devices *cur_devices;
5834 cur_devices = fs_info->fs_devices;
5835 while (cur_devices) {
5837 !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
5838 device = __find_device(&cur_devices->devices,
5843 cur_devices = cur_devices->seed;
5848 static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
5849 u64 devid, u8 *dev_uuid)
5851 struct btrfs_device *device;
5852 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
5854 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
5858 list_add(&device->dev_list, &fs_devices->devices);
5859 device->fs_devices = fs_devices;
5860 fs_devices->num_devices++;
5862 device->missing = 1;
5863 fs_devices->missing_devices++;
5869 * btrfs_alloc_device - allocate struct btrfs_device
5870 * @fs_info: used only for generating a new devid, can be NULL if
5871 * devid is provided (i.e. @devid != NULL).
5872 * @devid: a pointer to devid for this device. If NULL a new devid
5874 * @uuid: a pointer to UUID for this device. If NULL a new UUID
5877 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
5878 * on error. Returned struct is not linked onto any lists and can be
5879 * destroyed with kfree() right away.
5881 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
5885 struct btrfs_device *dev;
5888 if (WARN_ON(!devid && !fs_info))
5889 return ERR_PTR(-EINVAL);
5891 dev = __alloc_device();
5900 ret = find_next_devid(fs_info, &tmp);
5903 return ERR_PTR(ret);
5909 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
5911 generate_random_uuid(dev->uuid);
5913 btrfs_init_work(&dev->work, btrfs_submit_helper,
5914 pending_bios_fn, NULL, NULL);
5919 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
5920 struct extent_buffer *leaf,
5921 struct btrfs_chunk *chunk)
5923 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
5924 struct map_lookup *map;
5925 struct extent_map *em;
5929 u8 uuid[BTRFS_UUID_SIZE];
5934 logical = key->offset;
5935 length = btrfs_chunk_length(leaf, chunk);
5937 read_lock(&map_tree->map_tree.lock);
5938 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
5939 read_unlock(&map_tree->map_tree.lock);
5941 /* already mapped? */
5942 if (em && em->start <= logical && em->start + em->len > logical) {
5943 free_extent_map(em);
5946 free_extent_map(em);
5949 em = alloc_extent_map();
5952 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
5953 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
5955 free_extent_map(em);
5959 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5960 em->bdev = (struct block_device *)map;
5961 em->start = logical;
5964 em->block_start = 0;
5965 em->block_len = em->len;
5967 map->num_stripes = num_stripes;
5968 map->io_width = btrfs_chunk_io_width(leaf, chunk);
5969 map->io_align = btrfs_chunk_io_align(leaf, chunk);
5970 map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
5971 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
5972 map->type = btrfs_chunk_type(leaf, chunk);
5973 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
5974 for (i = 0; i < num_stripes; i++) {
5975 map->stripes[i].physical =
5976 btrfs_stripe_offset_nr(leaf, chunk, i);
5977 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
5978 read_extent_buffer(leaf, uuid, (unsigned long)
5979 btrfs_stripe_dev_uuid_nr(chunk, i),
5981 map->stripes[i].dev = btrfs_find_device(root->fs_info, devid,
5983 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
5984 free_extent_map(em);
5987 if (!map->stripes[i].dev) {
5988 map->stripes[i].dev =
5989 add_missing_dev(root, devid, uuid);
5990 if (!map->stripes[i].dev) {
5991 free_extent_map(em);
5995 map->stripes[i].dev->in_fs_metadata = 1;
5998 write_lock(&map_tree->map_tree.lock);
5999 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6000 write_unlock(&map_tree->map_tree.lock);
6001 BUG_ON(ret); /* Tree corruption */
6002 free_extent_map(em);
6007 static void fill_device_from_item(struct extent_buffer *leaf,
6008 struct btrfs_dev_item *dev_item,
6009 struct btrfs_device *device)
6013 device->devid = btrfs_device_id(leaf, dev_item);
6014 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6015 device->total_bytes = device->disk_total_bytes;
6016 device->commit_total_bytes = device->disk_total_bytes;
6017 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6018 device->commit_bytes_used = device->bytes_used;
6019 device->type = btrfs_device_type(leaf, dev_item);
6020 device->io_align = btrfs_device_io_align(leaf, dev_item);
6021 device->io_width = btrfs_device_io_width(leaf, dev_item);
6022 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6023 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6024 device->is_tgtdev_for_dev_replace = 0;
6026 ptr = btrfs_device_uuid(dev_item);
6027 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6030 static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
6032 struct btrfs_fs_devices *fs_devices;
6035 BUG_ON(!mutex_is_locked(&uuid_mutex));
6037 fs_devices = root->fs_info->fs_devices->seed;
6038 while (fs_devices) {
6039 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
6043 fs_devices = fs_devices->seed;
6046 fs_devices = find_fsid(fsid);
6052 fs_devices = clone_fs_devices(fs_devices);
6053 if (IS_ERR(fs_devices)) {
6054 ret = PTR_ERR(fs_devices);
6058 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
6059 root->fs_info->bdev_holder);
6061 free_fs_devices(fs_devices);
6065 if (!fs_devices->seeding) {
6066 __btrfs_close_devices(fs_devices);
6067 free_fs_devices(fs_devices);
6072 fs_devices->seed = root->fs_info->fs_devices->seed;
6073 root->fs_info->fs_devices->seed = fs_devices;
6078 static int read_one_dev(struct btrfs_root *root,
6079 struct extent_buffer *leaf,
6080 struct btrfs_dev_item *dev_item)
6082 struct btrfs_device *device;
6085 u8 fs_uuid[BTRFS_UUID_SIZE];
6086 u8 dev_uuid[BTRFS_UUID_SIZE];
6088 devid = btrfs_device_id(leaf, dev_item);
6089 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6091 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6094 if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
6095 ret = open_seed_devices(root, fs_uuid);
6096 if (ret && !(ret == -ENOENT && btrfs_test_opt(root, DEGRADED)))
6100 device = btrfs_find_device(root->fs_info, devid, dev_uuid, fs_uuid);
6101 if (!device || !device->bdev) {
6102 if (!btrfs_test_opt(root, DEGRADED))
6106 btrfs_warn(root->fs_info, "devid %llu missing", devid);
6107 device = add_missing_dev(root, devid, dev_uuid);
6110 } else if (!device->missing) {
6112 * this happens when a device that was properly setup
6113 * in the device info lists suddenly goes bad.
6114 * device->bdev is NULL, and so we have to set
6115 * device->missing to one here
6117 root->fs_info->fs_devices->missing_devices++;
6118 device->missing = 1;
6122 if (device->fs_devices != root->fs_info->fs_devices) {
6123 BUG_ON(device->writeable);
6124 if (device->generation !=
6125 btrfs_device_generation(leaf, dev_item))
6129 fill_device_from_item(leaf, dev_item, device);
6130 device->in_fs_metadata = 1;
6131 if (device->writeable && !device->is_tgtdev_for_dev_replace) {
6132 device->fs_devices->total_rw_bytes += device->total_bytes;
6133 spin_lock(&root->fs_info->free_chunk_lock);
6134 root->fs_info->free_chunk_space += device->total_bytes -
6136 spin_unlock(&root->fs_info->free_chunk_lock);
6142 int btrfs_read_sys_array(struct btrfs_root *root)
6144 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
6145 struct extent_buffer *sb;
6146 struct btrfs_disk_key *disk_key;
6147 struct btrfs_chunk *chunk;
6149 unsigned long sb_ptr;
6155 struct btrfs_key key;
6157 sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
6158 BTRFS_SUPER_INFO_SIZE);
6161 btrfs_set_buffer_uptodate(sb);
6162 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6164 * The sb extent buffer is artifical and just used to read the system array.
6165 * btrfs_set_buffer_uptodate() call does not properly mark all it's
6166 * pages up-to-date when the page is larger: extent does not cover the
6167 * whole page and consequently check_page_uptodate does not find all
6168 * the page's extents up-to-date (the hole beyond sb),
6169 * write_extent_buffer then triggers a WARN_ON.
6171 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6172 * but sb spans only this function. Add an explicit SetPageUptodate call
6173 * to silence the warning eg. on PowerPC 64.
6175 if (PAGE_CACHE_SIZE > BTRFS_SUPER_INFO_SIZE)
6176 SetPageUptodate(sb->pages[0]);
6178 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6179 array_size = btrfs_super_sys_array_size(super_copy);
6181 ptr = super_copy->sys_chunk_array;
6182 sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
6185 while (cur < array_size) {
6186 disk_key = (struct btrfs_disk_key *)ptr;
6187 btrfs_disk_key_to_cpu(&key, disk_key);
6189 len = sizeof(*disk_key); ptr += len;
6193 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6194 chunk = (struct btrfs_chunk *)sb_ptr;
6195 ret = read_one_chunk(root, &key, sb, chunk);
6198 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6199 len = btrfs_chunk_item_size(num_stripes);
6208 free_extent_buffer(sb);
6212 int btrfs_read_chunk_tree(struct btrfs_root *root)
6214 struct btrfs_path *path;
6215 struct extent_buffer *leaf;
6216 struct btrfs_key key;
6217 struct btrfs_key found_key;
6221 root = root->fs_info->chunk_root;
6223 path = btrfs_alloc_path();
6227 mutex_lock(&uuid_mutex);
6231 * Read all device items, and then all the chunk items. All
6232 * device items are found before any chunk item (their object id
6233 * is smaller than the lowest possible object id for a chunk
6234 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6236 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6239 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6243 leaf = path->nodes[0];
6244 slot = path->slots[0];
6245 if (slot >= btrfs_header_nritems(leaf)) {
6246 ret = btrfs_next_leaf(root, path);
6253 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6254 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6255 struct btrfs_dev_item *dev_item;
6256 dev_item = btrfs_item_ptr(leaf, slot,
6257 struct btrfs_dev_item);
6258 ret = read_one_dev(root, leaf, dev_item);
6261 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6262 struct btrfs_chunk *chunk;
6263 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6264 ret = read_one_chunk(root, &found_key, leaf, chunk);
6272 unlock_chunks(root);
6273 mutex_unlock(&uuid_mutex);
6275 btrfs_free_path(path);
6279 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6281 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6282 struct btrfs_device *device;
6284 while (fs_devices) {
6285 mutex_lock(&fs_devices->device_list_mutex);
6286 list_for_each_entry(device, &fs_devices->devices, dev_list)
6287 device->dev_root = fs_info->dev_root;
6288 mutex_unlock(&fs_devices->device_list_mutex);
6290 fs_devices = fs_devices->seed;
6294 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
6298 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6299 btrfs_dev_stat_reset(dev, i);
6302 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
6304 struct btrfs_key key;
6305 struct btrfs_key found_key;
6306 struct btrfs_root *dev_root = fs_info->dev_root;
6307 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6308 struct extent_buffer *eb;
6311 struct btrfs_device *device;
6312 struct btrfs_path *path = NULL;
6315 path = btrfs_alloc_path();
6321 mutex_lock(&fs_devices->device_list_mutex);
6322 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6324 struct btrfs_dev_stats_item *ptr;
6327 key.type = BTRFS_DEV_STATS_KEY;
6328 key.offset = device->devid;
6329 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
6331 __btrfs_reset_dev_stats(device);
6332 device->dev_stats_valid = 1;
6333 btrfs_release_path(path);
6336 slot = path->slots[0];
6337 eb = path->nodes[0];
6338 btrfs_item_key_to_cpu(eb, &found_key, slot);
6339 item_size = btrfs_item_size_nr(eb, slot);
6341 ptr = btrfs_item_ptr(eb, slot,
6342 struct btrfs_dev_stats_item);
6344 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6345 if (item_size >= (1 + i) * sizeof(__le64))
6346 btrfs_dev_stat_set(device, i,
6347 btrfs_dev_stats_value(eb, ptr, i));
6349 btrfs_dev_stat_reset(device, i);
6352 device->dev_stats_valid = 1;
6353 btrfs_dev_stat_print_on_load(device);
6354 btrfs_release_path(path);
6356 mutex_unlock(&fs_devices->device_list_mutex);
6359 btrfs_free_path(path);
6360 return ret < 0 ? ret : 0;
6363 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
6364 struct btrfs_root *dev_root,
6365 struct btrfs_device *device)
6367 struct btrfs_path *path;
6368 struct btrfs_key key;
6369 struct extent_buffer *eb;
6370 struct btrfs_dev_stats_item *ptr;
6375 key.type = BTRFS_DEV_STATS_KEY;
6376 key.offset = device->devid;
6378 path = btrfs_alloc_path();
6380 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
6382 printk_in_rcu(KERN_WARNING "BTRFS: "
6383 "error %d while searching for dev_stats item for device %s!\n",
6384 ret, rcu_str_deref(device->name));
6389 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
6390 /* need to delete old one and insert a new one */
6391 ret = btrfs_del_item(trans, dev_root, path);
6393 printk_in_rcu(KERN_WARNING "BTRFS: "
6394 "delete too small dev_stats item for device %s failed %d!\n",
6395 rcu_str_deref(device->name), ret);
6402 /* need to insert a new item */
6403 btrfs_release_path(path);
6404 ret = btrfs_insert_empty_item(trans, dev_root, path,
6405 &key, sizeof(*ptr));
6407 printk_in_rcu(KERN_WARNING "BTRFS: "
6408 "insert dev_stats item for device %s failed %d!\n",
6409 rcu_str_deref(device->name), ret);
6414 eb = path->nodes[0];
6415 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
6416 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6417 btrfs_set_dev_stats_value(eb, ptr, i,
6418 btrfs_dev_stat_read(device, i));
6419 btrfs_mark_buffer_dirty(eb);
6422 btrfs_free_path(path);
6427 * called from commit_transaction. Writes all changed device stats to disk.
6429 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
6430 struct btrfs_fs_info *fs_info)
6432 struct btrfs_root *dev_root = fs_info->dev_root;
6433 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6434 struct btrfs_device *device;
6438 mutex_lock(&fs_devices->device_list_mutex);
6439 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6440 if (!device->dev_stats_valid || !btrfs_dev_stats_dirty(device))
6443 stats_cnt = atomic_read(&device->dev_stats_ccnt);
6444 ret = update_dev_stat_item(trans, dev_root, device);
6446 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
6448 mutex_unlock(&fs_devices->device_list_mutex);
6453 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
6455 btrfs_dev_stat_inc(dev, index);
6456 btrfs_dev_stat_print_on_error(dev);
6459 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
6461 if (!dev->dev_stats_valid)
6463 printk_ratelimited_in_rcu(KERN_ERR "BTRFS: "
6464 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
6465 rcu_str_deref(dev->name),
6466 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6467 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6468 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6469 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6470 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6473 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
6477 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6478 if (btrfs_dev_stat_read(dev, i) != 0)
6480 if (i == BTRFS_DEV_STAT_VALUES_MAX)
6481 return; /* all values == 0, suppress message */
6483 printk_in_rcu(KERN_INFO "BTRFS: "
6484 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
6485 rcu_str_deref(dev->name),
6486 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6487 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6488 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6489 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6490 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6493 int btrfs_get_dev_stats(struct btrfs_root *root,
6494 struct btrfs_ioctl_get_dev_stats *stats)
6496 struct btrfs_device *dev;
6497 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
6500 mutex_lock(&fs_devices->device_list_mutex);
6501 dev = btrfs_find_device(root->fs_info, stats->devid, NULL, NULL);
6502 mutex_unlock(&fs_devices->device_list_mutex);
6505 btrfs_warn(root->fs_info, "get dev_stats failed, device not found");
6507 } else if (!dev->dev_stats_valid) {
6508 btrfs_warn(root->fs_info, "get dev_stats failed, not yet valid");
6510 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
6511 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6512 if (stats->nr_items > i)
6514 btrfs_dev_stat_read_and_reset(dev, i);
6516 btrfs_dev_stat_reset(dev, i);
6519 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6520 if (stats->nr_items > i)
6521 stats->values[i] = btrfs_dev_stat_read(dev, i);
6523 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
6524 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
6528 int btrfs_scratch_superblock(struct btrfs_device *device)
6530 struct buffer_head *bh;
6531 struct btrfs_super_block *disk_super;
6533 bh = btrfs_read_dev_super(device->bdev);
6536 disk_super = (struct btrfs_super_block *)bh->b_data;
6538 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
6539 set_buffer_dirty(bh);
6540 sync_dirty_buffer(bh);
6547 * Update the size of all devices, which is used for writing out the
6550 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
6552 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6553 struct btrfs_device *curr, *next;
6555 if (list_empty(&fs_devices->resized_devices))
6558 mutex_lock(&fs_devices->device_list_mutex);
6559 lock_chunks(fs_info->dev_root);
6560 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
6562 list_del_init(&curr->resized_list);
6563 curr->commit_total_bytes = curr->disk_total_bytes;
6565 unlock_chunks(fs_info->dev_root);
6566 mutex_unlock(&fs_devices->device_list_mutex);
6569 /* Must be invoked during the transaction commit */
6570 void btrfs_update_commit_device_bytes_used(struct btrfs_root *root,
6571 struct btrfs_transaction *transaction)
6573 struct extent_map *em;
6574 struct map_lookup *map;
6575 struct btrfs_device *dev;
6578 if (list_empty(&transaction->pending_chunks))
6581 /* In order to kick the device replace finish process */
6583 list_for_each_entry(em, &transaction->pending_chunks, list) {
6584 map = (struct map_lookup *)em->bdev;
6586 for (i = 0; i < map->num_stripes; i++) {
6587 dev = map->stripes[i].dev;
6588 dev->commit_bytes_used = dev->bytes_used;
6591 unlock_chunks(root);