2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
18 #include <linux/sched.h>
19 #include <linux/bio.h>
20 #include <linux/slab.h>
21 #include <linux/buffer_head.h>
22 #include <linux/blkdev.h>
23 #include <linux/random.h>
24 #include <linux/iocontext.h>
25 #include <linux/capability.h>
26 #include <linux/ratelimit.h>
27 #include <linux/kthread.h>
28 #include <linux/raid/pq.h>
29 #include <linux/semaphore.h>
30 #include <asm/div64.h>
32 #include "extent_map.h"
34 #include "transaction.h"
35 #include "print-tree.h"
38 #include "async-thread.h"
39 #include "check-integrity.h"
40 #include "rcu-string.h"
42 #include "dev-replace.h"
45 static int init_first_rw_device(struct btrfs_trans_handle *trans,
46 struct btrfs_root *root,
47 struct btrfs_device *device);
48 static int btrfs_relocate_sys_chunks(struct btrfs_root *root);
49 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
50 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
51 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
53 DEFINE_MUTEX(uuid_mutex);
54 static LIST_HEAD(fs_uuids);
55 struct list_head *btrfs_get_fs_uuids(void)
60 static struct btrfs_fs_devices *__alloc_fs_devices(void)
62 struct btrfs_fs_devices *fs_devs;
64 fs_devs = kzalloc(sizeof(*fs_devs), GFP_NOFS);
66 return ERR_PTR(-ENOMEM);
68 mutex_init(&fs_devs->device_list_mutex);
70 INIT_LIST_HEAD(&fs_devs->devices);
71 INIT_LIST_HEAD(&fs_devs->resized_devices);
72 INIT_LIST_HEAD(&fs_devs->alloc_list);
73 INIT_LIST_HEAD(&fs_devs->list);
79 * alloc_fs_devices - allocate struct btrfs_fs_devices
80 * @fsid: a pointer to UUID for this FS. If NULL a new UUID is
83 * Return: a pointer to a new &struct btrfs_fs_devices on success;
84 * ERR_PTR() on error. Returned struct is not linked onto any lists and
85 * can be destroyed with kfree() right away.
87 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
89 struct btrfs_fs_devices *fs_devs;
91 fs_devs = __alloc_fs_devices();
96 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
98 generate_random_uuid(fs_devs->fsid);
103 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
105 struct btrfs_device *device;
106 WARN_ON(fs_devices->opened);
107 while (!list_empty(&fs_devices->devices)) {
108 device = list_entry(fs_devices->devices.next,
109 struct btrfs_device, dev_list);
110 list_del(&device->dev_list);
111 rcu_string_free(device->name);
117 static void btrfs_kobject_uevent(struct block_device *bdev,
118 enum kobject_action action)
122 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
124 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
126 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
127 &disk_to_dev(bdev->bd_disk)->kobj);
130 void btrfs_cleanup_fs_uuids(void)
132 struct btrfs_fs_devices *fs_devices;
134 while (!list_empty(&fs_uuids)) {
135 fs_devices = list_entry(fs_uuids.next,
136 struct btrfs_fs_devices, list);
137 list_del(&fs_devices->list);
138 free_fs_devices(fs_devices);
142 static struct btrfs_device *__alloc_device(void)
144 struct btrfs_device *dev;
146 dev = kzalloc(sizeof(*dev), GFP_NOFS);
148 return ERR_PTR(-ENOMEM);
150 INIT_LIST_HEAD(&dev->dev_list);
151 INIT_LIST_HEAD(&dev->dev_alloc_list);
152 INIT_LIST_HEAD(&dev->resized_list);
154 spin_lock_init(&dev->io_lock);
156 spin_lock_init(&dev->reada_lock);
157 atomic_set(&dev->reada_in_flight, 0);
158 atomic_set(&dev->dev_stats_ccnt, 0);
159 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_WAIT);
160 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_WAIT);
165 static noinline struct btrfs_device *__find_device(struct list_head *head,
168 struct btrfs_device *dev;
170 list_for_each_entry(dev, head, dev_list) {
171 if (dev->devid == devid &&
172 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
179 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
181 struct btrfs_fs_devices *fs_devices;
183 list_for_each_entry(fs_devices, &fs_uuids, list) {
184 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
191 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
192 int flush, struct block_device **bdev,
193 struct buffer_head **bh)
197 *bdev = blkdev_get_by_path(device_path, flags, holder);
200 ret = PTR_ERR(*bdev);
201 printk(KERN_INFO "BTRFS: open %s failed\n", device_path);
206 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
207 ret = set_blocksize(*bdev, 4096);
209 blkdev_put(*bdev, flags);
212 invalidate_bdev(*bdev);
213 *bh = btrfs_read_dev_super(*bdev);
216 blkdev_put(*bdev, flags);
228 static void requeue_list(struct btrfs_pending_bios *pending_bios,
229 struct bio *head, struct bio *tail)
232 struct bio *old_head;
234 old_head = pending_bios->head;
235 pending_bios->head = head;
236 if (pending_bios->tail)
237 tail->bi_next = old_head;
239 pending_bios->tail = tail;
243 * we try to collect pending bios for a device so we don't get a large
244 * number of procs sending bios down to the same device. This greatly
245 * improves the schedulers ability to collect and merge the bios.
247 * But, it also turns into a long list of bios to process and that is sure
248 * to eventually make the worker thread block. The solution here is to
249 * make some progress and then put this work struct back at the end of
250 * the list if the block device is congested. This way, multiple devices
251 * can make progress from a single worker thread.
253 static noinline void run_scheduled_bios(struct btrfs_device *device)
256 struct backing_dev_info *bdi;
257 struct btrfs_fs_info *fs_info;
258 struct btrfs_pending_bios *pending_bios;
262 unsigned long num_run;
263 unsigned long batch_run = 0;
265 unsigned long last_waited = 0;
267 int sync_pending = 0;
268 struct blk_plug plug;
271 * this function runs all the bios we've collected for
272 * a particular device. We don't want to wander off to
273 * another device without first sending all of these down.
274 * So, setup a plug here and finish it off before we return
276 blk_start_plug(&plug);
278 bdi = blk_get_backing_dev_info(device->bdev);
279 fs_info = device->dev_root->fs_info;
280 limit = btrfs_async_submit_limit(fs_info);
281 limit = limit * 2 / 3;
284 spin_lock(&device->io_lock);
289 /* take all the bios off the list at once and process them
290 * later on (without the lock held). But, remember the
291 * tail and other pointers so the bios can be properly reinserted
292 * into the list if we hit congestion
294 if (!force_reg && device->pending_sync_bios.head) {
295 pending_bios = &device->pending_sync_bios;
298 pending_bios = &device->pending_bios;
302 pending = pending_bios->head;
303 tail = pending_bios->tail;
304 WARN_ON(pending && !tail);
307 * if pending was null this time around, no bios need processing
308 * at all and we can stop. Otherwise it'll loop back up again
309 * and do an additional check so no bios are missed.
311 * device->running_pending is used to synchronize with the
314 if (device->pending_sync_bios.head == NULL &&
315 device->pending_bios.head == NULL) {
317 device->running_pending = 0;
320 device->running_pending = 1;
323 pending_bios->head = NULL;
324 pending_bios->tail = NULL;
326 spin_unlock(&device->io_lock);
331 /* we want to work on both lists, but do more bios on the
332 * sync list than the regular list
335 pending_bios != &device->pending_sync_bios &&
336 device->pending_sync_bios.head) ||
337 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
338 device->pending_bios.head)) {
339 spin_lock(&device->io_lock);
340 requeue_list(pending_bios, pending, tail);
345 pending = pending->bi_next;
348 if (atomic_dec_return(&fs_info->nr_async_bios) < limit &&
349 waitqueue_active(&fs_info->async_submit_wait))
350 wake_up(&fs_info->async_submit_wait);
352 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
355 * if we're doing the sync list, record that our
356 * plug has some sync requests on it
358 * If we're doing the regular list and there are
359 * sync requests sitting around, unplug before
362 if (pending_bios == &device->pending_sync_bios) {
364 } else if (sync_pending) {
365 blk_finish_plug(&plug);
366 blk_start_plug(&plug);
370 btrfsic_submit_bio(cur->bi_rw, cur);
377 * we made progress, there is more work to do and the bdi
378 * is now congested. Back off and let other work structs
381 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
382 fs_info->fs_devices->open_devices > 1) {
383 struct io_context *ioc;
385 ioc = current->io_context;
388 * the main goal here is that we don't want to
389 * block if we're going to be able to submit
390 * more requests without blocking.
392 * This code does two great things, it pokes into
393 * the elevator code from a filesystem _and_
394 * it makes assumptions about how batching works.
396 if (ioc && ioc->nr_batch_requests > 0 &&
397 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
399 ioc->last_waited == last_waited)) {
401 * we want to go through our batch of
402 * requests and stop. So, we copy out
403 * the ioc->last_waited time and test
404 * against it before looping
406 last_waited = ioc->last_waited;
410 spin_lock(&device->io_lock);
411 requeue_list(pending_bios, pending, tail);
412 device->running_pending = 1;
414 spin_unlock(&device->io_lock);
415 btrfs_queue_work(fs_info->submit_workers,
419 /* unplug every 64 requests just for good measure */
420 if (batch_run % 64 == 0) {
421 blk_finish_plug(&plug);
422 blk_start_plug(&plug);
431 spin_lock(&device->io_lock);
432 if (device->pending_bios.head || device->pending_sync_bios.head)
434 spin_unlock(&device->io_lock);
437 blk_finish_plug(&plug);
440 static void pending_bios_fn(struct btrfs_work *work)
442 struct btrfs_device *device;
444 device = container_of(work, struct btrfs_device, work);
445 run_scheduled_bios(device);
449 void btrfs_free_stale_device(struct btrfs_device *cur_dev)
451 struct btrfs_fs_devices *fs_devs;
452 struct btrfs_device *dev;
457 list_for_each_entry(fs_devs, &fs_uuids, list) {
462 if (fs_devs->seeding)
465 list_for_each_entry(dev, &fs_devs->devices, dev_list) {
473 * Todo: This won't be enough. What if the same device
474 * comes back (with new uuid and) with its mapper path?
475 * But for now, this does help as mostly an admin will
476 * either use mapper or non mapper path throughout.
479 del = strcmp(rcu_str_deref(dev->name),
480 rcu_str_deref(cur_dev->name));
487 /* delete the stale device */
488 if (fs_devs->num_devices == 1) {
489 btrfs_sysfs_remove_fsid(fs_devs);
490 list_del(&fs_devs->list);
491 free_fs_devices(fs_devs);
493 fs_devs->num_devices--;
494 list_del(&dev->dev_list);
495 rcu_string_free(dev->name);
504 * Add new device to list of registered devices
507 * 1 - first time device is seen
508 * 0 - device already known
511 static noinline int device_list_add(const char *path,
512 struct btrfs_super_block *disk_super,
513 u64 devid, struct btrfs_fs_devices **fs_devices_ret)
515 struct btrfs_device *device;
516 struct btrfs_fs_devices *fs_devices;
517 struct rcu_string *name;
519 u64 found_transid = btrfs_super_generation(disk_super);
521 fs_devices = find_fsid(disk_super->fsid);
523 fs_devices = alloc_fs_devices(disk_super->fsid);
524 if (IS_ERR(fs_devices))
525 return PTR_ERR(fs_devices);
527 list_add(&fs_devices->list, &fs_uuids);
531 device = __find_device(&fs_devices->devices, devid,
532 disk_super->dev_item.uuid);
536 if (fs_devices->opened)
539 device = btrfs_alloc_device(NULL, &devid,
540 disk_super->dev_item.uuid);
541 if (IS_ERR(device)) {
542 /* we can safely leave the fs_devices entry around */
543 return PTR_ERR(device);
546 name = rcu_string_strdup(path, GFP_NOFS);
551 rcu_assign_pointer(device->name, name);
553 mutex_lock(&fs_devices->device_list_mutex);
554 list_add_rcu(&device->dev_list, &fs_devices->devices);
555 fs_devices->num_devices++;
556 mutex_unlock(&fs_devices->device_list_mutex);
559 device->fs_devices = fs_devices;
560 } else if (!device->name || strcmp(device->name->str, path)) {
562 * When FS is already mounted.
563 * 1. If you are here and if the device->name is NULL that
564 * means this device was missing at time of FS mount.
565 * 2. If you are here and if the device->name is different
566 * from 'path' that means either
567 * a. The same device disappeared and reappeared with
569 * b. The missing-disk-which-was-replaced, has
572 * We must allow 1 and 2a above. But 2b would be a spurious
575 * Further in case of 1 and 2a above, the disk at 'path'
576 * would have missed some transaction when it was away and
577 * in case of 2a the stale bdev has to be updated as well.
578 * 2b must not be allowed at all time.
582 * For now, we do allow update to btrfs_fs_device through the
583 * btrfs dev scan cli after FS has been mounted. We're still
584 * tracking a problem where systems fail mount by subvolume id
585 * when we reject replacement on a mounted FS.
587 if (!fs_devices->opened && found_transid < device->generation) {
589 * That is if the FS is _not_ mounted and if you
590 * are here, that means there is more than one
591 * disk with same uuid and devid.We keep the one
592 * with larger generation number or the last-in if
593 * generation are equal.
598 name = rcu_string_strdup(path, GFP_NOFS);
601 rcu_string_free(device->name);
602 rcu_assign_pointer(device->name, name);
603 if (device->missing) {
604 fs_devices->missing_devices--;
610 * Unmount does not free the btrfs_device struct but would zero
611 * generation along with most of the other members. So just update
612 * it back. We need it to pick the disk with largest generation
615 if (!fs_devices->opened)
616 device->generation = found_transid;
619 * if there is new btrfs on an already registered device,
620 * then remove the stale device entry.
622 btrfs_free_stale_device(device);
624 *fs_devices_ret = fs_devices;
629 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
631 struct btrfs_fs_devices *fs_devices;
632 struct btrfs_device *device;
633 struct btrfs_device *orig_dev;
635 fs_devices = alloc_fs_devices(orig->fsid);
636 if (IS_ERR(fs_devices))
639 mutex_lock(&orig->device_list_mutex);
640 fs_devices->total_devices = orig->total_devices;
642 /* We have held the volume lock, it is safe to get the devices. */
643 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
644 struct rcu_string *name;
646 device = btrfs_alloc_device(NULL, &orig_dev->devid,
652 * This is ok to do without rcu read locked because we hold the
653 * uuid mutex so nothing we touch in here is going to disappear.
655 if (orig_dev->name) {
656 name = rcu_string_strdup(orig_dev->name->str, GFP_NOFS);
661 rcu_assign_pointer(device->name, name);
664 list_add(&device->dev_list, &fs_devices->devices);
665 device->fs_devices = fs_devices;
666 fs_devices->num_devices++;
668 mutex_unlock(&orig->device_list_mutex);
671 mutex_unlock(&orig->device_list_mutex);
672 free_fs_devices(fs_devices);
673 return ERR_PTR(-ENOMEM);
676 void btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices, int step)
678 struct btrfs_device *device, *next;
679 struct btrfs_device *latest_dev = NULL;
681 mutex_lock(&uuid_mutex);
683 /* This is the initialized path, it is safe to release the devices. */
684 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
685 if (device->in_fs_metadata) {
686 if (!device->is_tgtdev_for_dev_replace &&
688 device->generation > latest_dev->generation)) {
694 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
696 * In the first step, keep the device which has
697 * the correct fsid and the devid that is used
698 * for the dev_replace procedure.
699 * In the second step, the dev_replace state is
700 * read from the device tree and it is known
701 * whether the procedure is really active or
702 * not, which means whether this device is
703 * used or whether it should be removed.
705 if (step == 0 || device->is_tgtdev_for_dev_replace) {
710 blkdev_put(device->bdev, device->mode);
712 fs_devices->open_devices--;
714 if (device->writeable) {
715 list_del_init(&device->dev_alloc_list);
716 device->writeable = 0;
717 if (!device->is_tgtdev_for_dev_replace)
718 fs_devices->rw_devices--;
720 list_del_init(&device->dev_list);
721 fs_devices->num_devices--;
722 rcu_string_free(device->name);
726 if (fs_devices->seed) {
727 fs_devices = fs_devices->seed;
731 fs_devices->latest_bdev = latest_dev->bdev;
733 mutex_unlock(&uuid_mutex);
736 static void __free_device(struct work_struct *work)
738 struct btrfs_device *device;
740 device = container_of(work, struct btrfs_device, rcu_work);
743 blkdev_put(device->bdev, device->mode);
745 rcu_string_free(device->name);
749 static void free_device(struct rcu_head *head)
751 struct btrfs_device *device;
753 device = container_of(head, struct btrfs_device, rcu);
755 INIT_WORK(&device->rcu_work, __free_device);
756 schedule_work(&device->rcu_work);
759 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
761 struct btrfs_device *device, *tmp;
763 if (--fs_devices->opened > 0)
766 mutex_lock(&fs_devices->device_list_mutex);
767 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
768 struct btrfs_device *new_device;
769 struct rcu_string *name;
772 fs_devices->open_devices--;
774 if (device->writeable &&
775 device->devid != BTRFS_DEV_REPLACE_DEVID) {
776 list_del_init(&device->dev_alloc_list);
777 fs_devices->rw_devices--;
781 fs_devices->missing_devices--;
783 new_device = btrfs_alloc_device(NULL, &device->devid,
785 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
787 /* Safe because we are under uuid_mutex */
789 name = rcu_string_strdup(device->name->str, GFP_NOFS);
790 BUG_ON(!name); /* -ENOMEM */
791 rcu_assign_pointer(new_device->name, name);
794 list_replace_rcu(&device->dev_list, &new_device->dev_list);
795 new_device->fs_devices = device->fs_devices;
797 call_rcu(&device->rcu, free_device);
799 mutex_unlock(&fs_devices->device_list_mutex);
801 WARN_ON(fs_devices->open_devices);
802 WARN_ON(fs_devices->rw_devices);
803 fs_devices->opened = 0;
804 fs_devices->seeding = 0;
809 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
811 struct btrfs_fs_devices *seed_devices = NULL;
814 mutex_lock(&uuid_mutex);
815 ret = __btrfs_close_devices(fs_devices);
816 if (!fs_devices->opened) {
817 seed_devices = fs_devices->seed;
818 fs_devices->seed = NULL;
820 mutex_unlock(&uuid_mutex);
822 while (seed_devices) {
823 fs_devices = seed_devices;
824 seed_devices = fs_devices->seed;
825 __btrfs_close_devices(fs_devices);
826 free_fs_devices(fs_devices);
829 * Wait for rcu kworkers under __btrfs_close_devices
830 * to finish all blkdev_puts so device is really
831 * free when umount is done.
837 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
838 fmode_t flags, void *holder)
840 struct request_queue *q;
841 struct block_device *bdev;
842 struct list_head *head = &fs_devices->devices;
843 struct btrfs_device *device;
844 struct btrfs_device *latest_dev = NULL;
845 struct buffer_head *bh;
846 struct btrfs_super_block *disk_super;
853 list_for_each_entry(device, head, dev_list) {
859 /* Just open everything we can; ignore failures here */
860 if (btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
864 disk_super = (struct btrfs_super_block *)bh->b_data;
865 devid = btrfs_stack_device_id(&disk_super->dev_item);
866 if (devid != device->devid)
869 if (memcmp(device->uuid, disk_super->dev_item.uuid,
873 device->generation = btrfs_super_generation(disk_super);
875 device->generation > latest_dev->generation)
878 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
879 device->writeable = 0;
881 device->writeable = !bdev_read_only(bdev);
885 q = bdev_get_queue(bdev);
886 if (blk_queue_discard(q))
887 device->can_discard = 1;
890 device->in_fs_metadata = 0;
891 device->mode = flags;
893 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
894 fs_devices->rotating = 1;
896 fs_devices->open_devices++;
897 if (device->writeable &&
898 device->devid != BTRFS_DEV_REPLACE_DEVID) {
899 fs_devices->rw_devices++;
900 list_add(&device->dev_alloc_list,
901 &fs_devices->alloc_list);
908 blkdev_put(bdev, flags);
911 if (fs_devices->open_devices == 0) {
915 fs_devices->seeding = seeding;
916 fs_devices->opened = 1;
917 fs_devices->latest_bdev = latest_dev->bdev;
918 fs_devices->total_rw_bytes = 0;
923 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
924 fmode_t flags, void *holder)
928 mutex_lock(&uuid_mutex);
929 if (fs_devices->opened) {
930 fs_devices->opened++;
933 ret = __btrfs_open_devices(fs_devices, flags, holder);
935 mutex_unlock(&uuid_mutex);
940 * Look for a btrfs signature on a device. This may be called out of the mount path
941 * and we are not allowed to call set_blocksize during the scan. The superblock
942 * is read via pagecache
944 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
945 struct btrfs_fs_devices **fs_devices_ret)
947 struct btrfs_super_block *disk_super;
948 struct block_device *bdev;
959 * we would like to check all the supers, but that would make
960 * a btrfs mount succeed after a mkfs from a different FS.
961 * So, we need to add a special mount option to scan for
962 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
964 bytenr = btrfs_sb_offset(0);
966 mutex_lock(&uuid_mutex);
968 bdev = blkdev_get_by_path(path, flags, holder);
975 /* make sure our super fits in the device */
976 if (bytenr + PAGE_CACHE_SIZE >= i_size_read(bdev->bd_inode))
979 /* make sure our super fits in the page */
980 if (sizeof(*disk_super) > PAGE_CACHE_SIZE)
983 /* make sure our super doesn't straddle pages on disk */
984 index = bytenr >> PAGE_CACHE_SHIFT;
985 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_CACHE_SHIFT != index)
988 /* pull in the page with our super */
989 page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
992 if (IS_ERR_OR_NULL(page))
997 /* align our pointer to the offset of the super block */
998 disk_super = p + (bytenr & ~PAGE_CACHE_MASK);
1000 if (btrfs_super_bytenr(disk_super) != bytenr ||
1001 btrfs_super_magic(disk_super) != BTRFS_MAGIC)
1004 devid = btrfs_stack_device_id(&disk_super->dev_item);
1005 transid = btrfs_super_generation(disk_super);
1006 total_devices = btrfs_super_num_devices(disk_super);
1008 ret = device_list_add(path, disk_super, devid, fs_devices_ret);
1010 if (disk_super->label[0]) {
1011 if (disk_super->label[BTRFS_LABEL_SIZE - 1])
1012 disk_super->label[BTRFS_LABEL_SIZE - 1] = '\0';
1013 printk(KERN_INFO "BTRFS: device label %s ", disk_super->label);
1015 printk(KERN_INFO "BTRFS: device fsid %pU ", disk_super->fsid);
1018 printk(KERN_CONT "devid %llu transid %llu %s\n", devid, transid, path);
1021 if (!ret && fs_devices_ret)
1022 (*fs_devices_ret)->total_devices = total_devices;
1026 page_cache_release(page);
1029 blkdev_put(bdev, flags);
1031 mutex_unlock(&uuid_mutex);
1035 /* helper to account the used device space in the range */
1036 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1037 u64 end, u64 *length)
1039 struct btrfs_key key;
1040 struct btrfs_root *root = device->dev_root;
1041 struct btrfs_dev_extent *dev_extent;
1042 struct btrfs_path *path;
1046 struct extent_buffer *l;
1050 if (start >= device->total_bytes || device->is_tgtdev_for_dev_replace)
1053 path = btrfs_alloc_path();
1058 key.objectid = device->devid;
1060 key.type = BTRFS_DEV_EXTENT_KEY;
1062 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1066 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1073 slot = path->slots[0];
1074 if (slot >= btrfs_header_nritems(l)) {
1075 ret = btrfs_next_leaf(root, path);
1083 btrfs_item_key_to_cpu(l, &key, slot);
1085 if (key.objectid < device->devid)
1088 if (key.objectid > device->devid)
1091 if (key.type != BTRFS_DEV_EXTENT_KEY)
1094 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1095 extent_end = key.offset + btrfs_dev_extent_length(l,
1097 if (key.offset <= start && extent_end > end) {
1098 *length = end - start + 1;
1100 } else if (key.offset <= start && extent_end > start)
1101 *length += extent_end - start;
1102 else if (key.offset > start && extent_end <= end)
1103 *length += extent_end - key.offset;
1104 else if (key.offset > start && key.offset <= end) {
1105 *length += end - key.offset + 1;
1107 } else if (key.offset > end)
1115 btrfs_free_path(path);
1119 static int contains_pending_extent(struct btrfs_transaction *transaction,
1120 struct btrfs_device *device,
1121 u64 *start, u64 len)
1123 struct btrfs_fs_info *fs_info = device->dev_root->fs_info;
1124 struct extent_map *em;
1125 struct list_head *search_list = &fs_info->pinned_chunks;
1127 u64 physical_start = *start;
1130 search_list = &transaction->pending_chunks;
1132 list_for_each_entry(em, search_list, list) {
1133 struct map_lookup *map;
1136 map = (struct map_lookup *)em->bdev;
1137 for (i = 0; i < map->num_stripes; i++) {
1140 if (map->stripes[i].dev != device)
1142 if (map->stripes[i].physical >= physical_start + len ||
1143 map->stripes[i].physical + em->orig_block_len <=
1147 * Make sure that while processing the pinned list we do
1148 * not override our *start with a lower value, because
1149 * we can have pinned chunks that fall within this
1150 * device hole and that have lower physical addresses
1151 * than the pending chunks we processed before. If we
1152 * do not take this special care we can end up getting
1153 * 2 pending chunks that start at the same physical
1154 * device offsets because the end offset of a pinned
1155 * chunk can be equal to the start offset of some
1158 end = map->stripes[i].physical + em->orig_block_len;
1165 if (search_list != &fs_info->pinned_chunks) {
1166 search_list = &fs_info->pinned_chunks;
1175 * find_free_dev_extent_start - find free space in the specified device
1176 * @device: the device which we search the free space in
1177 * @num_bytes: the size of the free space that we need
1178 * @search_start: the position from which to begin the search
1179 * @start: store the start of the free space.
1180 * @len: the size of the free space. that we find, or the size
1181 * of the max free space if we don't find suitable free space
1183 * this uses a pretty simple search, the expectation is that it is
1184 * called very infrequently and that a given device has a small number
1187 * @start is used to store the start of the free space if we find. But if we
1188 * don't find suitable free space, it will be used to store the start position
1189 * of the max free space.
1191 * @len is used to store the size of the free space that we find.
1192 * But if we don't find suitable free space, it is used to store the size of
1193 * the max free space.
1195 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1196 struct btrfs_device *device, u64 num_bytes,
1197 u64 search_start, u64 *start, u64 *len)
1199 struct btrfs_key key;
1200 struct btrfs_root *root = device->dev_root;
1201 struct btrfs_dev_extent *dev_extent;
1202 struct btrfs_path *path;
1207 u64 search_end = device->total_bytes;
1210 struct extent_buffer *l;
1212 path = btrfs_alloc_path();
1216 max_hole_start = search_start;
1220 if (search_start >= search_end || device->is_tgtdev_for_dev_replace) {
1226 path->search_commit_root = 1;
1227 path->skip_locking = 1;
1229 key.objectid = device->devid;
1230 key.offset = search_start;
1231 key.type = BTRFS_DEV_EXTENT_KEY;
1233 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1237 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1244 slot = path->slots[0];
1245 if (slot >= btrfs_header_nritems(l)) {
1246 ret = btrfs_next_leaf(root, path);
1254 btrfs_item_key_to_cpu(l, &key, slot);
1256 if (key.objectid < device->devid)
1259 if (key.objectid > device->devid)
1262 if (key.type != BTRFS_DEV_EXTENT_KEY)
1265 if (key.offset > search_start) {
1266 hole_size = key.offset - search_start;
1269 * Have to check before we set max_hole_start, otherwise
1270 * we could end up sending back this offset anyway.
1272 if (contains_pending_extent(transaction, device,
1275 if (key.offset >= search_start) {
1276 hole_size = key.offset - search_start;
1283 if (hole_size > max_hole_size) {
1284 max_hole_start = search_start;
1285 max_hole_size = hole_size;
1289 * If this free space is greater than which we need,
1290 * it must be the max free space that we have found
1291 * until now, so max_hole_start must point to the start
1292 * of this free space and the length of this free space
1293 * is stored in max_hole_size. Thus, we return
1294 * max_hole_start and max_hole_size and go back to the
1297 if (hole_size >= num_bytes) {
1303 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1304 extent_end = key.offset + btrfs_dev_extent_length(l,
1306 if (extent_end > search_start)
1307 search_start = extent_end;
1314 * At this point, search_start should be the end of
1315 * allocated dev extents, and when shrinking the device,
1316 * search_end may be smaller than search_start.
1318 if (search_end > search_start) {
1319 hole_size = search_end - search_start;
1321 if (contains_pending_extent(transaction, device, &search_start,
1323 btrfs_release_path(path);
1327 if (hole_size > max_hole_size) {
1328 max_hole_start = search_start;
1329 max_hole_size = hole_size;
1334 if (max_hole_size < num_bytes)
1340 btrfs_free_path(path);
1341 *start = max_hole_start;
1343 *len = max_hole_size;
1347 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1348 struct btrfs_device *device, u64 num_bytes,
1349 u64 *start, u64 *len)
1351 struct btrfs_root *root = device->dev_root;
1354 /* FIXME use last free of some kind */
1357 * we don't want to overwrite the superblock on the drive,
1358 * so we make sure to start at an offset of at least 1MB
1360 search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
1361 return find_free_dev_extent_start(trans->transaction, device,
1362 num_bytes, search_start, start, len);
1365 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1366 struct btrfs_device *device,
1367 u64 start, u64 *dev_extent_len)
1370 struct btrfs_path *path;
1371 struct btrfs_root *root = device->dev_root;
1372 struct btrfs_key key;
1373 struct btrfs_key found_key;
1374 struct extent_buffer *leaf = NULL;
1375 struct btrfs_dev_extent *extent = NULL;
1377 path = btrfs_alloc_path();
1381 key.objectid = device->devid;
1383 key.type = BTRFS_DEV_EXTENT_KEY;
1385 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1387 ret = btrfs_previous_item(root, path, key.objectid,
1388 BTRFS_DEV_EXTENT_KEY);
1391 leaf = path->nodes[0];
1392 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1393 extent = btrfs_item_ptr(leaf, path->slots[0],
1394 struct btrfs_dev_extent);
1395 BUG_ON(found_key.offset > start || found_key.offset +
1396 btrfs_dev_extent_length(leaf, extent) < start);
1398 btrfs_release_path(path);
1400 } else if (ret == 0) {
1401 leaf = path->nodes[0];
1402 extent = btrfs_item_ptr(leaf, path->slots[0],
1403 struct btrfs_dev_extent);
1405 btrfs_error(root->fs_info, ret, "Slot search failed");
1409 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1411 ret = btrfs_del_item(trans, root, path);
1413 btrfs_error(root->fs_info, ret,
1414 "Failed to remove dev extent item");
1416 trans->transaction->have_free_bgs = 1;
1419 btrfs_free_path(path);
1423 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1424 struct btrfs_device *device,
1425 u64 chunk_tree, u64 chunk_objectid,
1426 u64 chunk_offset, u64 start, u64 num_bytes)
1429 struct btrfs_path *path;
1430 struct btrfs_root *root = device->dev_root;
1431 struct btrfs_dev_extent *extent;
1432 struct extent_buffer *leaf;
1433 struct btrfs_key key;
1435 WARN_ON(!device->in_fs_metadata);
1436 WARN_ON(device->is_tgtdev_for_dev_replace);
1437 path = btrfs_alloc_path();
1441 key.objectid = device->devid;
1443 key.type = BTRFS_DEV_EXTENT_KEY;
1444 ret = btrfs_insert_empty_item(trans, root, path, &key,
1449 leaf = path->nodes[0];
1450 extent = btrfs_item_ptr(leaf, path->slots[0],
1451 struct btrfs_dev_extent);
1452 btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1453 btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1454 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1456 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1457 btrfs_dev_extent_chunk_tree_uuid(extent), BTRFS_UUID_SIZE);
1459 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1460 btrfs_mark_buffer_dirty(leaf);
1462 btrfs_free_path(path);
1466 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1468 struct extent_map_tree *em_tree;
1469 struct extent_map *em;
1473 em_tree = &fs_info->mapping_tree.map_tree;
1474 read_lock(&em_tree->lock);
1475 n = rb_last(&em_tree->map);
1477 em = rb_entry(n, struct extent_map, rb_node);
1478 ret = em->start + em->len;
1480 read_unlock(&em_tree->lock);
1485 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1489 struct btrfs_key key;
1490 struct btrfs_key found_key;
1491 struct btrfs_path *path;
1493 path = btrfs_alloc_path();
1497 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1498 key.type = BTRFS_DEV_ITEM_KEY;
1499 key.offset = (u64)-1;
1501 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1505 BUG_ON(ret == 0); /* Corruption */
1507 ret = btrfs_previous_item(fs_info->chunk_root, path,
1508 BTRFS_DEV_ITEMS_OBJECTID,
1509 BTRFS_DEV_ITEM_KEY);
1513 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1515 *devid_ret = found_key.offset + 1;
1519 btrfs_free_path(path);
1524 * the device information is stored in the chunk root
1525 * the btrfs_device struct should be fully filled in
1527 static int btrfs_add_device(struct btrfs_trans_handle *trans,
1528 struct btrfs_root *root,
1529 struct btrfs_device *device)
1532 struct btrfs_path *path;
1533 struct btrfs_dev_item *dev_item;
1534 struct extent_buffer *leaf;
1535 struct btrfs_key key;
1538 root = root->fs_info->chunk_root;
1540 path = btrfs_alloc_path();
1544 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1545 key.type = BTRFS_DEV_ITEM_KEY;
1546 key.offset = device->devid;
1548 ret = btrfs_insert_empty_item(trans, root, path, &key,
1553 leaf = path->nodes[0];
1554 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1556 btrfs_set_device_id(leaf, dev_item, device->devid);
1557 btrfs_set_device_generation(leaf, dev_item, 0);
1558 btrfs_set_device_type(leaf, dev_item, device->type);
1559 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1560 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1561 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1562 btrfs_set_device_total_bytes(leaf, dev_item,
1563 btrfs_device_get_disk_total_bytes(device));
1564 btrfs_set_device_bytes_used(leaf, dev_item,
1565 btrfs_device_get_bytes_used(device));
1566 btrfs_set_device_group(leaf, dev_item, 0);
1567 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1568 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1569 btrfs_set_device_start_offset(leaf, dev_item, 0);
1571 ptr = btrfs_device_uuid(dev_item);
1572 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1573 ptr = btrfs_device_fsid(dev_item);
1574 write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
1575 btrfs_mark_buffer_dirty(leaf);
1579 btrfs_free_path(path);
1584 * Function to update ctime/mtime for a given device path.
1585 * Mainly used for ctime/mtime based probe like libblkid.
1587 static void update_dev_time(char *path_name)
1591 filp = filp_open(path_name, O_RDWR, 0);
1594 file_update_time(filp);
1595 filp_close(filp, NULL);
1599 static int btrfs_rm_dev_item(struct btrfs_root *root,
1600 struct btrfs_device *device)
1603 struct btrfs_path *path;
1604 struct btrfs_key key;
1605 struct btrfs_trans_handle *trans;
1607 root = root->fs_info->chunk_root;
1609 path = btrfs_alloc_path();
1613 trans = btrfs_start_transaction(root, 0);
1614 if (IS_ERR(trans)) {
1615 btrfs_free_path(path);
1616 return PTR_ERR(trans);
1618 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1619 key.type = BTRFS_DEV_ITEM_KEY;
1620 key.offset = device->devid;
1622 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1631 ret = btrfs_del_item(trans, root, path);
1635 btrfs_free_path(path);
1636 btrfs_commit_transaction(trans, root);
1640 int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1642 struct btrfs_device *device;
1643 struct btrfs_device *next_device;
1644 struct block_device *bdev;
1645 struct buffer_head *bh = NULL;
1646 struct btrfs_super_block *disk_super;
1647 struct btrfs_fs_devices *cur_devices;
1654 bool clear_super = false;
1656 mutex_lock(&uuid_mutex);
1659 seq = read_seqbegin(&root->fs_info->profiles_lock);
1661 all_avail = root->fs_info->avail_data_alloc_bits |
1662 root->fs_info->avail_system_alloc_bits |
1663 root->fs_info->avail_metadata_alloc_bits;
1664 } while (read_seqretry(&root->fs_info->profiles_lock, seq));
1666 num_devices = root->fs_info->fs_devices->num_devices;
1667 btrfs_dev_replace_lock(&root->fs_info->dev_replace);
1668 if (btrfs_dev_replace_is_ongoing(&root->fs_info->dev_replace)) {
1669 WARN_ON(num_devices < 1);
1672 btrfs_dev_replace_unlock(&root->fs_info->dev_replace);
1674 if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) && num_devices <= 4) {
1675 ret = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET;
1679 if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) && num_devices <= 2) {
1680 ret = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET;
1684 if ((all_avail & BTRFS_BLOCK_GROUP_RAID5) &&
1685 root->fs_info->fs_devices->rw_devices <= 2) {
1686 ret = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET;
1689 if ((all_avail & BTRFS_BLOCK_GROUP_RAID6) &&
1690 root->fs_info->fs_devices->rw_devices <= 3) {
1691 ret = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET;
1695 if (strcmp(device_path, "missing") == 0) {
1696 struct list_head *devices;
1697 struct btrfs_device *tmp;
1700 devices = &root->fs_info->fs_devices->devices;
1702 * It is safe to read the devices since the volume_mutex
1705 list_for_each_entry(tmp, devices, dev_list) {
1706 if (tmp->in_fs_metadata &&
1707 !tmp->is_tgtdev_for_dev_replace &&
1717 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
1721 ret = btrfs_get_bdev_and_sb(device_path,
1722 FMODE_WRITE | FMODE_EXCL,
1723 root->fs_info->bdev_holder, 0,
1727 disk_super = (struct btrfs_super_block *)bh->b_data;
1728 devid = btrfs_stack_device_id(&disk_super->dev_item);
1729 dev_uuid = disk_super->dev_item.uuid;
1730 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1738 if (device->is_tgtdev_for_dev_replace) {
1739 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1743 if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
1744 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1748 if (device->writeable) {
1750 list_del_init(&device->dev_alloc_list);
1751 device->fs_devices->rw_devices--;
1752 unlock_chunks(root);
1756 mutex_unlock(&uuid_mutex);
1757 ret = btrfs_shrink_device(device, 0);
1758 mutex_lock(&uuid_mutex);
1763 * TODO: the superblock still includes this device in its num_devices
1764 * counter although write_all_supers() is not locked out. This
1765 * could give a filesystem state which requires a degraded mount.
1767 ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1771 device->in_fs_metadata = 0;
1772 btrfs_scrub_cancel_dev(root->fs_info, device);
1775 * the device list mutex makes sure that we don't change
1776 * the device list while someone else is writing out all
1777 * the device supers. Whoever is writing all supers, should
1778 * lock the device list mutex before getting the number of
1779 * devices in the super block (super_copy). Conversely,
1780 * whoever updates the number of devices in the super block
1781 * (super_copy) should hold the device list mutex.
1784 cur_devices = device->fs_devices;
1785 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1786 list_del_rcu(&device->dev_list);
1788 device->fs_devices->num_devices--;
1789 device->fs_devices->total_devices--;
1791 if (device->missing)
1792 device->fs_devices->missing_devices--;
1794 next_device = list_entry(root->fs_info->fs_devices->devices.next,
1795 struct btrfs_device, dev_list);
1796 if (device->bdev == root->fs_info->sb->s_bdev)
1797 root->fs_info->sb->s_bdev = next_device->bdev;
1798 if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1799 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1802 device->fs_devices->open_devices--;
1803 /* remove sysfs entry */
1804 btrfs_kobj_rm_device(root->fs_info->fs_devices, device);
1807 call_rcu(&device->rcu, free_device);
1809 num_devices = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
1810 btrfs_set_super_num_devices(root->fs_info->super_copy, num_devices);
1811 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1813 if (cur_devices->open_devices == 0) {
1814 struct btrfs_fs_devices *fs_devices;
1815 fs_devices = root->fs_info->fs_devices;
1816 while (fs_devices) {
1817 if (fs_devices->seed == cur_devices) {
1818 fs_devices->seed = cur_devices->seed;
1821 fs_devices = fs_devices->seed;
1823 cur_devices->seed = NULL;
1824 __btrfs_close_devices(cur_devices);
1825 free_fs_devices(cur_devices);
1828 root->fs_info->num_tolerated_disk_barrier_failures =
1829 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
1832 * at this point, the device is zero sized. We want to
1833 * remove it from the devices list and zero out the old super
1835 if (clear_super && disk_super) {
1839 /* make sure this device isn't detected as part of
1842 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1843 set_buffer_dirty(bh);
1844 sync_dirty_buffer(bh);
1846 /* clear the mirror copies of super block on the disk
1847 * being removed, 0th copy is been taken care above and
1848 * the below would take of the rest
1850 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1851 bytenr = btrfs_sb_offset(i);
1852 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
1853 i_size_read(bdev->bd_inode))
1857 bh = __bread(bdev, bytenr / 4096,
1858 BTRFS_SUPER_INFO_SIZE);
1862 disk_super = (struct btrfs_super_block *)bh->b_data;
1864 if (btrfs_super_bytenr(disk_super) != bytenr ||
1865 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1868 memset(&disk_super->magic, 0,
1869 sizeof(disk_super->magic));
1870 set_buffer_dirty(bh);
1871 sync_dirty_buffer(bh);
1878 /* Notify udev that device has changed */
1879 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
1881 /* Update ctime/mtime for device path for libblkid */
1882 update_dev_time(device_path);
1888 blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
1890 mutex_unlock(&uuid_mutex);
1893 if (device->writeable) {
1895 list_add(&device->dev_alloc_list,
1896 &root->fs_info->fs_devices->alloc_list);
1897 device->fs_devices->rw_devices++;
1898 unlock_chunks(root);
1903 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
1904 struct btrfs_device *srcdev)
1906 struct btrfs_fs_devices *fs_devices;
1908 WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
1911 * in case of fs with no seed, srcdev->fs_devices will point
1912 * to fs_devices of fs_info. However when the dev being replaced is
1913 * a seed dev it will point to the seed's local fs_devices. In short
1914 * srcdev will have its correct fs_devices in both the cases.
1916 fs_devices = srcdev->fs_devices;
1918 list_del_rcu(&srcdev->dev_list);
1919 list_del_rcu(&srcdev->dev_alloc_list);
1920 fs_devices->num_devices--;
1921 if (srcdev->missing)
1922 fs_devices->missing_devices--;
1924 if (srcdev->writeable) {
1925 fs_devices->rw_devices--;
1926 /* zero out the old super if it is writable */
1927 btrfs_scratch_superblock(srcdev);
1931 fs_devices->open_devices--;
1934 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
1935 struct btrfs_device *srcdev)
1937 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
1939 call_rcu(&srcdev->rcu, free_device);
1942 * unless fs_devices is seed fs, num_devices shouldn't go
1945 BUG_ON(!fs_devices->num_devices && !fs_devices->seeding);
1947 /* if this is no devs we rather delete the fs_devices */
1948 if (!fs_devices->num_devices) {
1949 struct btrfs_fs_devices *tmp_fs_devices;
1951 tmp_fs_devices = fs_info->fs_devices;
1952 while (tmp_fs_devices) {
1953 if (tmp_fs_devices->seed == fs_devices) {
1954 tmp_fs_devices->seed = fs_devices->seed;
1957 tmp_fs_devices = tmp_fs_devices->seed;
1959 fs_devices->seed = NULL;
1960 __btrfs_close_devices(fs_devices);
1961 free_fs_devices(fs_devices);
1965 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
1966 struct btrfs_device *tgtdev)
1968 struct btrfs_device *next_device;
1970 mutex_lock(&uuid_mutex);
1972 mutex_lock(&fs_info->fs_devices->device_list_mutex);
1974 btrfs_kobj_rm_device(fs_info->fs_devices, tgtdev);
1977 btrfs_scratch_superblock(tgtdev);
1978 fs_info->fs_devices->open_devices--;
1980 fs_info->fs_devices->num_devices--;
1982 next_device = list_entry(fs_info->fs_devices->devices.next,
1983 struct btrfs_device, dev_list);
1984 if (tgtdev->bdev == fs_info->sb->s_bdev)
1985 fs_info->sb->s_bdev = next_device->bdev;
1986 if (tgtdev->bdev == fs_info->fs_devices->latest_bdev)
1987 fs_info->fs_devices->latest_bdev = next_device->bdev;
1988 list_del_rcu(&tgtdev->dev_list);
1990 call_rcu(&tgtdev->rcu, free_device);
1992 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1993 mutex_unlock(&uuid_mutex);
1996 static int btrfs_find_device_by_path(struct btrfs_root *root, char *device_path,
1997 struct btrfs_device **device)
2000 struct btrfs_super_block *disk_super;
2003 struct block_device *bdev;
2004 struct buffer_head *bh;
2007 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2008 root->fs_info->bdev_holder, 0, &bdev, &bh);
2011 disk_super = (struct btrfs_super_block *)bh->b_data;
2012 devid = btrfs_stack_device_id(&disk_super->dev_item);
2013 dev_uuid = disk_super->dev_item.uuid;
2014 *device = btrfs_find_device(root->fs_info, devid, dev_uuid,
2019 blkdev_put(bdev, FMODE_READ);
2023 int btrfs_find_device_missing_or_by_path(struct btrfs_root *root,
2025 struct btrfs_device **device)
2028 if (strcmp(device_path, "missing") == 0) {
2029 struct list_head *devices;
2030 struct btrfs_device *tmp;
2032 devices = &root->fs_info->fs_devices->devices;
2034 * It is safe to read the devices since the volume_mutex
2035 * is held by the caller.
2037 list_for_each_entry(tmp, devices, dev_list) {
2038 if (tmp->in_fs_metadata && !tmp->bdev) {
2045 btrfs_err(root->fs_info, "no missing device found");
2051 return btrfs_find_device_by_path(root, device_path, device);
2056 * does all the dirty work required for changing file system's UUID.
2058 static int btrfs_prepare_sprout(struct btrfs_root *root)
2060 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2061 struct btrfs_fs_devices *old_devices;
2062 struct btrfs_fs_devices *seed_devices;
2063 struct btrfs_super_block *disk_super = root->fs_info->super_copy;
2064 struct btrfs_device *device;
2067 BUG_ON(!mutex_is_locked(&uuid_mutex));
2068 if (!fs_devices->seeding)
2071 seed_devices = __alloc_fs_devices();
2072 if (IS_ERR(seed_devices))
2073 return PTR_ERR(seed_devices);
2075 old_devices = clone_fs_devices(fs_devices);
2076 if (IS_ERR(old_devices)) {
2077 kfree(seed_devices);
2078 return PTR_ERR(old_devices);
2081 list_add(&old_devices->list, &fs_uuids);
2083 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2084 seed_devices->opened = 1;
2085 INIT_LIST_HEAD(&seed_devices->devices);
2086 INIT_LIST_HEAD(&seed_devices->alloc_list);
2087 mutex_init(&seed_devices->device_list_mutex);
2089 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2090 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2092 list_for_each_entry(device, &seed_devices->devices, dev_list)
2093 device->fs_devices = seed_devices;
2096 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2097 unlock_chunks(root);
2099 fs_devices->seeding = 0;
2100 fs_devices->num_devices = 0;
2101 fs_devices->open_devices = 0;
2102 fs_devices->missing_devices = 0;
2103 fs_devices->rotating = 0;
2104 fs_devices->seed = seed_devices;
2106 generate_random_uuid(fs_devices->fsid);
2107 memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2108 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2109 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2111 super_flags = btrfs_super_flags(disk_super) &
2112 ~BTRFS_SUPER_FLAG_SEEDING;
2113 btrfs_set_super_flags(disk_super, super_flags);
2119 * strore the expected generation for seed devices in device items.
2121 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2122 struct btrfs_root *root)
2124 struct btrfs_path *path;
2125 struct extent_buffer *leaf;
2126 struct btrfs_dev_item *dev_item;
2127 struct btrfs_device *device;
2128 struct btrfs_key key;
2129 u8 fs_uuid[BTRFS_UUID_SIZE];
2130 u8 dev_uuid[BTRFS_UUID_SIZE];
2134 path = btrfs_alloc_path();
2138 root = root->fs_info->chunk_root;
2139 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2141 key.type = BTRFS_DEV_ITEM_KEY;
2144 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2148 leaf = path->nodes[0];
2150 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2151 ret = btrfs_next_leaf(root, path);
2156 leaf = path->nodes[0];
2157 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2158 btrfs_release_path(path);
2162 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2163 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2164 key.type != BTRFS_DEV_ITEM_KEY)
2167 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2168 struct btrfs_dev_item);
2169 devid = btrfs_device_id(leaf, dev_item);
2170 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2172 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2174 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
2176 BUG_ON(!device); /* Logic error */
2178 if (device->fs_devices->seeding) {
2179 btrfs_set_device_generation(leaf, dev_item,
2180 device->generation);
2181 btrfs_mark_buffer_dirty(leaf);
2189 btrfs_free_path(path);
2193 int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
2195 struct request_queue *q;
2196 struct btrfs_trans_handle *trans;
2197 struct btrfs_device *device;
2198 struct block_device *bdev;
2199 struct list_head *devices;
2200 struct super_block *sb = root->fs_info->sb;
2201 struct rcu_string *name;
2203 int seeding_dev = 0;
2206 if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
2209 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2210 root->fs_info->bdev_holder);
2212 return PTR_ERR(bdev);
2214 if (root->fs_info->fs_devices->seeding) {
2216 down_write(&sb->s_umount);
2217 mutex_lock(&uuid_mutex);
2220 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2222 devices = &root->fs_info->fs_devices->devices;
2224 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2225 list_for_each_entry(device, devices, dev_list) {
2226 if (device->bdev == bdev) {
2229 &root->fs_info->fs_devices->device_list_mutex);
2233 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2235 device = btrfs_alloc_device(root->fs_info, NULL, NULL);
2236 if (IS_ERR(device)) {
2237 /* we can safely leave the fs_devices entry around */
2238 ret = PTR_ERR(device);
2242 name = rcu_string_strdup(device_path, GFP_NOFS);
2248 rcu_assign_pointer(device->name, name);
2250 trans = btrfs_start_transaction(root, 0);
2251 if (IS_ERR(trans)) {
2252 rcu_string_free(device->name);
2254 ret = PTR_ERR(trans);
2258 q = bdev_get_queue(bdev);
2259 if (blk_queue_discard(q))
2260 device->can_discard = 1;
2261 device->writeable = 1;
2262 device->generation = trans->transid;
2263 device->io_width = root->sectorsize;
2264 device->io_align = root->sectorsize;
2265 device->sector_size = root->sectorsize;
2266 device->total_bytes = i_size_read(bdev->bd_inode);
2267 device->disk_total_bytes = device->total_bytes;
2268 device->commit_total_bytes = device->total_bytes;
2269 device->dev_root = root->fs_info->dev_root;
2270 device->bdev = bdev;
2271 device->in_fs_metadata = 1;
2272 device->is_tgtdev_for_dev_replace = 0;
2273 device->mode = FMODE_EXCL;
2274 device->dev_stats_valid = 1;
2275 set_blocksize(device->bdev, 4096);
2278 sb->s_flags &= ~MS_RDONLY;
2279 ret = btrfs_prepare_sprout(root);
2280 BUG_ON(ret); /* -ENOMEM */
2283 device->fs_devices = root->fs_info->fs_devices;
2285 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2287 list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
2288 list_add(&device->dev_alloc_list,
2289 &root->fs_info->fs_devices->alloc_list);
2290 root->fs_info->fs_devices->num_devices++;
2291 root->fs_info->fs_devices->open_devices++;
2292 root->fs_info->fs_devices->rw_devices++;
2293 root->fs_info->fs_devices->total_devices++;
2294 root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2296 spin_lock(&root->fs_info->free_chunk_lock);
2297 root->fs_info->free_chunk_space += device->total_bytes;
2298 spin_unlock(&root->fs_info->free_chunk_lock);
2300 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
2301 root->fs_info->fs_devices->rotating = 1;
2303 tmp = btrfs_super_total_bytes(root->fs_info->super_copy);
2304 btrfs_set_super_total_bytes(root->fs_info->super_copy,
2305 tmp + device->total_bytes);
2307 tmp = btrfs_super_num_devices(root->fs_info->super_copy);
2308 btrfs_set_super_num_devices(root->fs_info->super_copy,
2311 /* add sysfs device entry */
2312 btrfs_kobj_add_device(root->fs_info->fs_devices, device);
2315 * we've got more storage, clear any full flags on the space
2318 btrfs_clear_space_info_full(root->fs_info);
2320 unlock_chunks(root);
2321 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2325 ret = init_first_rw_device(trans, root, device);
2326 unlock_chunks(root);
2328 btrfs_abort_transaction(trans, root, ret);
2333 ret = btrfs_add_device(trans, root, device);
2335 btrfs_abort_transaction(trans, root, ret);
2340 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2342 ret = btrfs_finish_sprout(trans, root);
2344 btrfs_abort_transaction(trans, root, ret);
2348 /* Sprouting would change fsid of the mounted root,
2349 * so rename the fsid on the sysfs
2351 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2352 root->fs_info->fsid);
2353 if (kobject_rename(&root->fs_info->fs_devices->super_kobj,
2355 btrfs_warn(root->fs_info,
2356 "sysfs: failed to create fsid for sprout");
2359 root->fs_info->num_tolerated_disk_barrier_failures =
2360 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
2361 ret = btrfs_commit_transaction(trans, root);
2364 mutex_unlock(&uuid_mutex);
2365 up_write(&sb->s_umount);
2367 if (ret) /* transaction commit */
2370 ret = btrfs_relocate_sys_chunks(root);
2372 btrfs_error(root->fs_info, ret,
2373 "Failed to relocate sys chunks after "
2374 "device initialization. This can be fixed "
2375 "using the \"btrfs balance\" command.");
2376 trans = btrfs_attach_transaction(root);
2377 if (IS_ERR(trans)) {
2378 if (PTR_ERR(trans) == -ENOENT)
2380 return PTR_ERR(trans);
2382 ret = btrfs_commit_transaction(trans, root);
2385 /* Update ctime/mtime for libblkid */
2386 update_dev_time(device_path);
2390 btrfs_end_transaction(trans, root);
2391 rcu_string_free(device->name);
2392 btrfs_kobj_rm_device(root->fs_info->fs_devices, device);
2395 blkdev_put(bdev, FMODE_EXCL);
2397 mutex_unlock(&uuid_mutex);
2398 up_write(&sb->s_umount);
2403 int btrfs_init_dev_replace_tgtdev(struct btrfs_root *root, char *device_path,
2404 struct btrfs_device *srcdev,
2405 struct btrfs_device **device_out)
2407 struct request_queue *q;
2408 struct btrfs_device *device;
2409 struct block_device *bdev;
2410 struct btrfs_fs_info *fs_info = root->fs_info;
2411 struct list_head *devices;
2412 struct rcu_string *name;
2413 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2417 if (fs_info->fs_devices->seeding) {
2418 btrfs_err(fs_info, "the filesystem is a seed filesystem!");
2422 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2423 fs_info->bdev_holder);
2425 btrfs_err(fs_info, "target device %s is invalid!", device_path);
2426 return PTR_ERR(bdev);
2429 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2431 devices = &fs_info->fs_devices->devices;
2432 list_for_each_entry(device, devices, dev_list) {
2433 if (device->bdev == bdev) {
2434 btrfs_err(fs_info, "target device is in the filesystem!");
2441 if (i_size_read(bdev->bd_inode) <
2442 btrfs_device_get_total_bytes(srcdev)) {
2443 btrfs_err(fs_info, "target device is smaller than source device!");
2449 device = btrfs_alloc_device(NULL, &devid, NULL);
2450 if (IS_ERR(device)) {
2451 ret = PTR_ERR(device);
2455 name = rcu_string_strdup(device_path, GFP_NOFS);
2461 rcu_assign_pointer(device->name, name);
2463 q = bdev_get_queue(bdev);
2464 if (blk_queue_discard(q))
2465 device->can_discard = 1;
2466 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2467 device->writeable = 1;
2468 device->generation = 0;
2469 device->io_width = root->sectorsize;
2470 device->io_align = root->sectorsize;
2471 device->sector_size = root->sectorsize;
2472 device->total_bytes = btrfs_device_get_total_bytes(srcdev);
2473 device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
2474 device->bytes_used = btrfs_device_get_bytes_used(srcdev);
2475 ASSERT(list_empty(&srcdev->resized_list));
2476 device->commit_total_bytes = srcdev->commit_total_bytes;
2477 device->commit_bytes_used = device->bytes_used;
2478 device->dev_root = fs_info->dev_root;
2479 device->bdev = bdev;
2480 device->in_fs_metadata = 1;
2481 device->is_tgtdev_for_dev_replace = 1;
2482 device->mode = FMODE_EXCL;
2483 device->dev_stats_valid = 1;
2484 set_blocksize(device->bdev, 4096);
2485 device->fs_devices = fs_info->fs_devices;
2486 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2487 fs_info->fs_devices->num_devices++;
2488 fs_info->fs_devices->open_devices++;
2489 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2491 *device_out = device;
2495 blkdev_put(bdev, FMODE_EXCL);
2499 void btrfs_init_dev_replace_tgtdev_for_resume(struct btrfs_fs_info *fs_info,
2500 struct btrfs_device *tgtdev)
2502 WARN_ON(fs_info->fs_devices->rw_devices == 0);
2503 tgtdev->io_width = fs_info->dev_root->sectorsize;
2504 tgtdev->io_align = fs_info->dev_root->sectorsize;
2505 tgtdev->sector_size = fs_info->dev_root->sectorsize;
2506 tgtdev->dev_root = fs_info->dev_root;
2507 tgtdev->in_fs_metadata = 1;
2510 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2511 struct btrfs_device *device)
2514 struct btrfs_path *path;
2515 struct btrfs_root *root;
2516 struct btrfs_dev_item *dev_item;
2517 struct extent_buffer *leaf;
2518 struct btrfs_key key;
2520 root = device->dev_root->fs_info->chunk_root;
2522 path = btrfs_alloc_path();
2526 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2527 key.type = BTRFS_DEV_ITEM_KEY;
2528 key.offset = device->devid;
2530 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2539 leaf = path->nodes[0];
2540 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2542 btrfs_set_device_id(leaf, dev_item, device->devid);
2543 btrfs_set_device_type(leaf, dev_item, device->type);
2544 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2545 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2546 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2547 btrfs_set_device_total_bytes(leaf, dev_item,
2548 btrfs_device_get_disk_total_bytes(device));
2549 btrfs_set_device_bytes_used(leaf, dev_item,
2550 btrfs_device_get_bytes_used(device));
2551 btrfs_mark_buffer_dirty(leaf);
2554 btrfs_free_path(path);
2558 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2559 struct btrfs_device *device, u64 new_size)
2561 struct btrfs_super_block *super_copy =
2562 device->dev_root->fs_info->super_copy;
2563 struct btrfs_fs_devices *fs_devices;
2567 if (!device->writeable)
2570 lock_chunks(device->dev_root);
2571 old_total = btrfs_super_total_bytes(super_copy);
2572 diff = new_size - device->total_bytes;
2574 if (new_size <= device->total_bytes ||
2575 device->is_tgtdev_for_dev_replace) {
2576 unlock_chunks(device->dev_root);
2580 fs_devices = device->dev_root->fs_info->fs_devices;
2582 btrfs_set_super_total_bytes(super_copy, old_total + diff);
2583 device->fs_devices->total_rw_bytes += diff;
2585 btrfs_device_set_total_bytes(device, new_size);
2586 btrfs_device_set_disk_total_bytes(device, new_size);
2587 btrfs_clear_space_info_full(device->dev_root->fs_info);
2588 if (list_empty(&device->resized_list))
2589 list_add_tail(&device->resized_list,
2590 &fs_devices->resized_devices);
2591 unlock_chunks(device->dev_root);
2593 return btrfs_update_device(trans, device);
2596 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2597 struct btrfs_root *root, u64 chunk_objectid,
2601 struct btrfs_path *path;
2602 struct btrfs_key key;
2604 root = root->fs_info->chunk_root;
2605 path = btrfs_alloc_path();
2609 key.objectid = chunk_objectid;
2610 key.offset = chunk_offset;
2611 key.type = BTRFS_CHUNK_ITEM_KEY;
2613 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2616 else if (ret > 0) { /* Logic error or corruption */
2617 btrfs_error(root->fs_info, -ENOENT,
2618 "Failed lookup while freeing chunk.");
2623 ret = btrfs_del_item(trans, root, path);
2625 btrfs_error(root->fs_info, ret,
2626 "Failed to delete chunk item.");
2628 btrfs_free_path(path);
2632 static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
2635 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
2636 struct btrfs_disk_key *disk_key;
2637 struct btrfs_chunk *chunk;
2644 struct btrfs_key key;
2647 array_size = btrfs_super_sys_array_size(super_copy);
2649 ptr = super_copy->sys_chunk_array;
2652 while (cur < array_size) {
2653 disk_key = (struct btrfs_disk_key *)ptr;
2654 btrfs_disk_key_to_cpu(&key, disk_key);
2656 len = sizeof(*disk_key);
2658 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2659 chunk = (struct btrfs_chunk *)(ptr + len);
2660 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2661 len += btrfs_chunk_item_size(num_stripes);
2666 if (key.objectid == chunk_objectid &&
2667 key.offset == chunk_offset) {
2668 memmove(ptr, ptr + len, array_size - (cur + len));
2670 btrfs_set_super_sys_array_size(super_copy, array_size);
2676 unlock_chunks(root);
2680 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2681 struct btrfs_root *root, u64 chunk_offset)
2683 struct extent_map_tree *em_tree;
2684 struct extent_map *em;
2685 struct btrfs_root *extent_root = root->fs_info->extent_root;
2686 struct map_lookup *map;
2687 u64 dev_extent_len = 0;
2688 u64 chunk_objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2692 root = root->fs_info->chunk_root;
2693 em_tree = &root->fs_info->mapping_tree.map_tree;
2695 read_lock(&em_tree->lock);
2696 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
2697 read_unlock(&em_tree->lock);
2699 if (!em || em->start > chunk_offset ||
2700 em->start + em->len < chunk_offset) {
2702 * This is a logic error, but we don't want to just rely on the
2703 * user having built with ASSERT enabled, so if ASSERT doens't
2704 * do anything we still error out.
2708 free_extent_map(em);
2711 map = (struct map_lookup *)em->bdev;
2712 lock_chunks(root->fs_info->chunk_root);
2713 check_system_chunk(trans, extent_root, map->type);
2714 unlock_chunks(root->fs_info->chunk_root);
2716 for (i = 0; i < map->num_stripes; i++) {
2717 struct btrfs_device *device = map->stripes[i].dev;
2718 ret = btrfs_free_dev_extent(trans, device,
2719 map->stripes[i].physical,
2722 btrfs_abort_transaction(trans, root, ret);
2726 if (device->bytes_used > 0) {
2728 btrfs_device_set_bytes_used(device,
2729 device->bytes_used - dev_extent_len);
2730 spin_lock(&root->fs_info->free_chunk_lock);
2731 root->fs_info->free_chunk_space += dev_extent_len;
2732 spin_unlock(&root->fs_info->free_chunk_lock);
2733 btrfs_clear_space_info_full(root->fs_info);
2734 unlock_chunks(root);
2737 if (map->stripes[i].dev) {
2738 ret = btrfs_update_device(trans, map->stripes[i].dev);
2740 btrfs_abort_transaction(trans, root, ret);
2745 ret = btrfs_free_chunk(trans, root, chunk_objectid, chunk_offset);
2747 btrfs_abort_transaction(trans, root, ret);
2751 trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
2753 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2754 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
2756 btrfs_abort_transaction(trans, root, ret);
2761 ret = btrfs_remove_block_group(trans, extent_root, chunk_offset, em);
2763 btrfs_abort_transaction(trans, extent_root, ret);
2769 free_extent_map(em);
2773 static int btrfs_relocate_chunk(struct btrfs_root *root, u64 chunk_offset)
2775 struct btrfs_root *extent_root;
2776 struct btrfs_trans_handle *trans;
2779 root = root->fs_info->chunk_root;
2780 extent_root = root->fs_info->extent_root;
2783 * Prevent races with automatic removal of unused block groups.
2784 * After we relocate and before we remove the chunk with offset
2785 * chunk_offset, automatic removal of the block group can kick in,
2786 * resulting in a failure when calling btrfs_remove_chunk() below.
2788 * Make sure to acquire this mutex before doing a tree search (dev
2789 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2790 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2791 * we release the path used to search the chunk/dev tree and before
2792 * the current task acquires this mutex and calls us.
2794 ASSERT(mutex_is_locked(&root->fs_info->delete_unused_bgs_mutex));
2796 ret = btrfs_can_relocate(extent_root, chunk_offset);
2800 /* step one, relocate all the extents inside this chunk */
2801 btrfs_scrub_pause(root);
2802 ret = btrfs_relocate_block_group(extent_root, chunk_offset);
2803 btrfs_scrub_continue(root);
2807 trans = btrfs_start_transaction(root, 0);
2808 if (IS_ERR(trans)) {
2809 ret = PTR_ERR(trans);
2810 btrfs_std_error(root->fs_info, ret);
2815 * step two, delete the device extents and the
2816 * chunk tree entries
2818 ret = btrfs_remove_chunk(trans, root, chunk_offset);
2819 btrfs_end_transaction(trans, root);
2823 static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
2825 struct btrfs_root *chunk_root = root->fs_info->chunk_root;
2826 struct btrfs_path *path;
2827 struct extent_buffer *leaf;
2828 struct btrfs_chunk *chunk;
2829 struct btrfs_key key;
2830 struct btrfs_key found_key;
2832 bool retried = false;
2836 path = btrfs_alloc_path();
2841 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2842 key.offset = (u64)-1;
2843 key.type = BTRFS_CHUNK_ITEM_KEY;
2846 mutex_lock(&root->fs_info->delete_unused_bgs_mutex);
2847 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2849 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
2852 BUG_ON(ret == 0); /* Corruption */
2854 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2857 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
2863 leaf = path->nodes[0];
2864 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2866 chunk = btrfs_item_ptr(leaf, path->slots[0],
2867 struct btrfs_chunk);
2868 chunk_type = btrfs_chunk_type(leaf, chunk);
2869 btrfs_release_path(path);
2871 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2872 ret = btrfs_relocate_chunk(chunk_root,
2879 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
2881 if (found_key.offset == 0)
2883 key.offset = found_key.offset - 1;
2886 if (failed && !retried) {
2890 } else if (WARN_ON(failed && retried)) {
2894 btrfs_free_path(path);
2898 static int insert_balance_item(struct btrfs_root *root,
2899 struct btrfs_balance_control *bctl)
2901 struct btrfs_trans_handle *trans;
2902 struct btrfs_balance_item *item;
2903 struct btrfs_disk_balance_args disk_bargs;
2904 struct btrfs_path *path;
2905 struct extent_buffer *leaf;
2906 struct btrfs_key key;
2909 path = btrfs_alloc_path();
2913 trans = btrfs_start_transaction(root, 0);
2914 if (IS_ERR(trans)) {
2915 btrfs_free_path(path);
2916 return PTR_ERR(trans);
2919 key.objectid = BTRFS_BALANCE_OBJECTID;
2920 key.type = BTRFS_BALANCE_ITEM_KEY;
2923 ret = btrfs_insert_empty_item(trans, root, path, &key,
2928 leaf = path->nodes[0];
2929 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2931 memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
2933 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
2934 btrfs_set_balance_data(leaf, item, &disk_bargs);
2935 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
2936 btrfs_set_balance_meta(leaf, item, &disk_bargs);
2937 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
2938 btrfs_set_balance_sys(leaf, item, &disk_bargs);
2940 btrfs_set_balance_flags(leaf, item, bctl->flags);
2942 btrfs_mark_buffer_dirty(leaf);
2944 btrfs_free_path(path);
2945 err = btrfs_commit_transaction(trans, root);
2951 static int del_balance_item(struct btrfs_root *root)
2953 struct btrfs_trans_handle *trans;
2954 struct btrfs_path *path;
2955 struct btrfs_key key;
2958 path = btrfs_alloc_path();
2962 trans = btrfs_start_transaction(root, 0);
2963 if (IS_ERR(trans)) {
2964 btrfs_free_path(path);
2965 return PTR_ERR(trans);
2968 key.objectid = BTRFS_BALANCE_OBJECTID;
2969 key.type = BTRFS_BALANCE_ITEM_KEY;
2972 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2980 ret = btrfs_del_item(trans, root, path);
2982 btrfs_free_path(path);
2983 err = btrfs_commit_transaction(trans, root);
2990 * This is a heuristic used to reduce the number of chunks balanced on
2991 * resume after balance was interrupted.
2993 static void update_balance_args(struct btrfs_balance_control *bctl)
2996 * Turn on soft mode for chunk types that were being converted.
2998 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
2999 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3000 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3001 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3002 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3003 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3006 * Turn on usage filter if is not already used. The idea is
3007 * that chunks that we have already balanced should be
3008 * reasonably full. Don't do it for chunks that are being
3009 * converted - that will keep us from relocating unconverted
3010 * (albeit full) chunks.
3012 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3013 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3014 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3015 bctl->data.usage = 90;
3017 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3018 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3019 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3020 bctl->sys.usage = 90;
3022 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3023 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3024 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3025 bctl->meta.usage = 90;
3030 * Should be called with both balance and volume mutexes held to
3031 * serialize other volume operations (add_dev/rm_dev/resize) with
3032 * restriper. Same goes for unset_balance_control.
3034 static void set_balance_control(struct btrfs_balance_control *bctl)
3036 struct btrfs_fs_info *fs_info = bctl->fs_info;
3038 BUG_ON(fs_info->balance_ctl);
3040 spin_lock(&fs_info->balance_lock);
3041 fs_info->balance_ctl = bctl;
3042 spin_unlock(&fs_info->balance_lock);
3045 static void unset_balance_control(struct btrfs_fs_info *fs_info)
3047 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3049 BUG_ON(!fs_info->balance_ctl);
3051 spin_lock(&fs_info->balance_lock);
3052 fs_info->balance_ctl = NULL;
3053 spin_unlock(&fs_info->balance_lock);
3059 * Balance filters. Return 1 if chunk should be filtered out
3060 * (should not be balanced).
3062 static int chunk_profiles_filter(u64 chunk_type,
3063 struct btrfs_balance_args *bargs)
3065 chunk_type = chunk_to_extended(chunk_type) &
3066 BTRFS_EXTENDED_PROFILE_MASK;
3068 if (bargs->profiles & chunk_type)
3074 static int chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3075 struct btrfs_balance_args *bargs)
3077 struct btrfs_block_group_cache *cache;
3078 u64 chunk_used, user_thresh;
3081 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3082 chunk_used = btrfs_block_group_used(&cache->item);
3084 if (bargs->usage == 0)
3086 else if (bargs->usage > 100)
3087 user_thresh = cache->key.offset;
3089 user_thresh = div_factor_fine(cache->key.offset,
3092 if (chunk_used < user_thresh)
3095 btrfs_put_block_group(cache);
3099 static int chunk_devid_filter(struct extent_buffer *leaf,
3100 struct btrfs_chunk *chunk,
3101 struct btrfs_balance_args *bargs)
3103 struct btrfs_stripe *stripe;
3104 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3107 for (i = 0; i < num_stripes; i++) {
3108 stripe = btrfs_stripe_nr(chunk, i);
3109 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3116 /* [pstart, pend) */
3117 static int chunk_drange_filter(struct extent_buffer *leaf,
3118 struct btrfs_chunk *chunk,
3120 struct btrfs_balance_args *bargs)
3122 struct btrfs_stripe *stripe;
3123 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3129 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3132 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3133 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3134 factor = num_stripes / 2;
3135 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3136 factor = num_stripes - 1;
3137 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3138 factor = num_stripes - 2;
3140 factor = num_stripes;
3143 for (i = 0; i < num_stripes; i++) {
3144 stripe = btrfs_stripe_nr(chunk, i);
3145 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3148 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3149 stripe_length = btrfs_chunk_length(leaf, chunk);
3150 stripe_length = div_u64(stripe_length, factor);
3152 if (stripe_offset < bargs->pend &&
3153 stripe_offset + stripe_length > bargs->pstart)
3160 /* [vstart, vend) */
3161 static int chunk_vrange_filter(struct extent_buffer *leaf,
3162 struct btrfs_chunk *chunk,
3164 struct btrfs_balance_args *bargs)
3166 if (chunk_offset < bargs->vend &&
3167 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3168 /* at least part of the chunk is inside this vrange */
3174 static int chunk_soft_convert_filter(u64 chunk_type,
3175 struct btrfs_balance_args *bargs)
3177 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3180 chunk_type = chunk_to_extended(chunk_type) &
3181 BTRFS_EXTENDED_PROFILE_MASK;
3183 if (bargs->target == chunk_type)
3189 static int should_balance_chunk(struct btrfs_root *root,
3190 struct extent_buffer *leaf,
3191 struct btrfs_chunk *chunk, u64 chunk_offset)
3193 struct btrfs_balance_control *bctl = root->fs_info->balance_ctl;
3194 struct btrfs_balance_args *bargs = NULL;
3195 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3198 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3199 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3203 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3204 bargs = &bctl->data;
3205 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3207 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3208 bargs = &bctl->meta;
3210 /* profiles filter */
3211 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3212 chunk_profiles_filter(chunk_type, bargs)) {
3217 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3218 chunk_usage_filter(bctl->fs_info, chunk_offset, bargs)) {
3223 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3224 chunk_devid_filter(leaf, chunk, bargs)) {
3228 /* drange filter, makes sense only with devid filter */
3229 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3230 chunk_drange_filter(leaf, chunk, chunk_offset, bargs)) {
3235 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3236 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3240 /* soft profile changing mode */
3241 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3242 chunk_soft_convert_filter(chunk_type, bargs)) {
3247 * limited by count, must be the last filter
3249 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3250 if (bargs->limit == 0)
3259 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3261 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3262 struct btrfs_root *chunk_root = fs_info->chunk_root;
3263 struct btrfs_root *dev_root = fs_info->dev_root;
3264 struct list_head *devices;
3265 struct btrfs_device *device;
3268 struct btrfs_chunk *chunk;
3269 struct btrfs_path *path;
3270 struct btrfs_key key;
3271 struct btrfs_key found_key;
3272 struct btrfs_trans_handle *trans;
3273 struct extent_buffer *leaf;
3276 int enospc_errors = 0;
3277 bool counting = true;
3278 u64 limit_data = bctl->data.limit;
3279 u64 limit_meta = bctl->meta.limit;
3280 u64 limit_sys = bctl->sys.limit;
3282 /* step one make some room on all the devices */
3283 devices = &fs_info->fs_devices->devices;
3284 list_for_each_entry(device, devices, dev_list) {
3285 old_size = btrfs_device_get_total_bytes(device);
3286 size_to_free = div_factor(old_size, 1);
3287 size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
3288 if (!device->writeable ||
3289 btrfs_device_get_total_bytes(device) -
3290 btrfs_device_get_bytes_used(device) > size_to_free ||
3291 device->is_tgtdev_for_dev_replace)
3294 ret = btrfs_shrink_device(device, old_size - size_to_free);
3299 trans = btrfs_start_transaction(dev_root, 0);
3300 BUG_ON(IS_ERR(trans));
3302 ret = btrfs_grow_device(trans, device, old_size);
3305 btrfs_end_transaction(trans, dev_root);
3308 /* step two, relocate all the chunks */
3309 path = btrfs_alloc_path();
3315 /* zero out stat counters */
3316 spin_lock(&fs_info->balance_lock);
3317 memset(&bctl->stat, 0, sizeof(bctl->stat));
3318 spin_unlock(&fs_info->balance_lock);
3321 bctl->data.limit = limit_data;
3322 bctl->meta.limit = limit_meta;
3323 bctl->sys.limit = limit_sys;
3325 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3326 key.offset = (u64)-1;
3327 key.type = BTRFS_CHUNK_ITEM_KEY;
3330 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3331 atomic_read(&fs_info->balance_cancel_req)) {
3336 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3337 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3339 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3344 * this shouldn't happen, it means the last relocate
3348 BUG(); /* FIXME break ? */
3350 ret = btrfs_previous_item(chunk_root, path, 0,
3351 BTRFS_CHUNK_ITEM_KEY);
3353 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3358 leaf = path->nodes[0];
3359 slot = path->slots[0];
3360 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3362 if (found_key.objectid != key.objectid) {
3363 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3367 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3370 spin_lock(&fs_info->balance_lock);
3371 bctl->stat.considered++;
3372 spin_unlock(&fs_info->balance_lock);
3375 ret = should_balance_chunk(chunk_root, leaf, chunk,
3377 btrfs_release_path(path);
3379 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3384 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3385 spin_lock(&fs_info->balance_lock);
3386 bctl->stat.expected++;
3387 spin_unlock(&fs_info->balance_lock);
3391 ret = btrfs_relocate_chunk(chunk_root,
3393 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3394 if (ret && ret != -ENOSPC)
3396 if (ret == -ENOSPC) {
3399 spin_lock(&fs_info->balance_lock);
3400 bctl->stat.completed++;
3401 spin_unlock(&fs_info->balance_lock);
3404 if (found_key.offset == 0)
3406 key.offset = found_key.offset - 1;
3410 btrfs_release_path(path);
3415 btrfs_free_path(path);
3416 if (enospc_errors) {
3417 btrfs_info(fs_info, "%d enospc errors during balance",
3427 * alloc_profile_is_valid - see if a given profile is valid and reduced
3428 * @flags: profile to validate
3429 * @extended: if true @flags is treated as an extended profile
3431 static int alloc_profile_is_valid(u64 flags, int extended)
3433 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3434 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3436 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3438 /* 1) check that all other bits are zeroed */
3442 /* 2) see if profile is reduced */
3444 return !extended; /* "0" is valid for usual profiles */
3446 /* true if exactly one bit set */
3447 return (flags & (flags - 1)) == 0;
3450 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3452 /* cancel requested || normal exit path */
3453 return atomic_read(&fs_info->balance_cancel_req) ||
3454 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3455 atomic_read(&fs_info->balance_cancel_req) == 0);
3458 static void __cancel_balance(struct btrfs_fs_info *fs_info)
3462 unset_balance_control(fs_info);
3463 ret = del_balance_item(fs_info->tree_root);
3465 btrfs_std_error(fs_info, ret);
3467 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3471 * Should be called with both balance and volume mutexes held
3473 int btrfs_balance(struct btrfs_balance_control *bctl,
3474 struct btrfs_ioctl_balance_args *bargs)
3476 struct btrfs_fs_info *fs_info = bctl->fs_info;
3483 if (btrfs_fs_closing(fs_info) ||
3484 atomic_read(&fs_info->balance_pause_req) ||
3485 atomic_read(&fs_info->balance_cancel_req)) {
3490 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3491 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3495 * In case of mixed groups both data and meta should be picked,
3496 * and identical options should be given for both of them.
3498 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3499 if (mixed && (bctl->flags & allowed)) {
3500 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3501 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3502 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3503 btrfs_err(fs_info, "with mixed groups data and "
3504 "metadata balance options must be the same");
3510 num_devices = fs_info->fs_devices->num_devices;
3511 btrfs_dev_replace_lock(&fs_info->dev_replace);
3512 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3513 BUG_ON(num_devices < 1);
3516 btrfs_dev_replace_unlock(&fs_info->dev_replace);
3517 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
3518 if (num_devices == 1)
3519 allowed |= BTRFS_BLOCK_GROUP_DUP;
3520 else if (num_devices > 1)
3521 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3522 if (num_devices > 2)
3523 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3524 if (num_devices > 3)
3525 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3526 BTRFS_BLOCK_GROUP_RAID6);
3527 if ((bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3528 (!alloc_profile_is_valid(bctl->data.target, 1) ||
3529 (bctl->data.target & ~allowed))) {
3530 btrfs_err(fs_info, "unable to start balance with target "
3531 "data profile %llu",
3536 if ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3537 (!alloc_profile_is_valid(bctl->meta.target, 1) ||
3538 (bctl->meta.target & ~allowed))) {
3540 "unable to start balance with target metadata profile %llu",
3545 if ((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3546 (!alloc_profile_is_valid(bctl->sys.target, 1) ||
3547 (bctl->sys.target & ~allowed))) {
3549 "unable to start balance with target system profile %llu",
3555 /* allow dup'ed data chunks only in mixed mode */
3556 if (!mixed && (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3557 (bctl->data.target & BTRFS_BLOCK_GROUP_DUP)) {
3558 btrfs_err(fs_info, "dup for data is not allowed");
3563 /* allow to reduce meta or sys integrity only if force set */
3564 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3565 BTRFS_BLOCK_GROUP_RAID10 |
3566 BTRFS_BLOCK_GROUP_RAID5 |
3567 BTRFS_BLOCK_GROUP_RAID6;
3569 seq = read_seqbegin(&fs_info->profiles_lock);
3571 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3572 (fs_info->avail_system_alloc_bits & allowed) &&
3573 !(bctl->sys.target & allowed)) ||
3574 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3575 (fs_info->avail_metadata_alloc_bits & allowed) &&
3576 !(bctl->meta.target & allowed))) {
3577 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3578 btrfs_info(fs_info, "force reducing metadata integrity");
3580 btrfs_err(fs_info, "balance will reduce metadata "
3581 "integrity, use force if you want this");
3586 } while (read_seqretry(&fs_info->profiles_lock, seq));
3588 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3589 fs_info->num_tolerated_disk_barrier_failures = min(
3590 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info),
3591 btrfs_get_num_tolerated_disk_barrier_failures(
3595 ret = insert_balance_item(fs_info->tree_root, bctl);
3596 if (ret && ret != -EEXIST)
3599 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3600 BUG_ON(ret == -EEXIST);
3601 set_balance_control(bctl);
3603 BUG_ON(ret != -EEXIST);
3604 spin_lock(&fs_info->balance_lock);
3605 update_balance_args(bctl);
3606 spin_unlock(&fs_info->balance_lock);
3609 atomic_inc(&fs_info->balance_running);
3610 mutex_unlock(&fs_info->balance_mutex);
3612 ret = __btrfs_balance(fs_info);
3614 mutex_lock(&fs_info->balance_mutex);
3615 atomic_dec(&fs_info->balance_running);
3617 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3618 fs_info->num_tolerated_disk_barrier_failures =
3619 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3623 memset(bargs, 0, sizeof(*bargs));
3624 update_ioctl_balance_args(fs_info, 0, bargs);
3627 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3628 balance_need_close(fs_info)) {
3629 __cancel_balance(fs_info);
3632 wake_up(&fs_info->balance_wait_q);
3636 if (bctl->flags & BTRFS_BALANCE_RESUME)
3637 __cancel_balance(fs_info);
3640 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3645 static int balance_kthread(void *data)
3647 struct btrfs_fs_info *fs_info = data;
3650 mutex_lock(&fs_info->volume_mutex);
3651 mutex_lock(&fs_info->balance_mutex);
3653 if (fs_info->balance_ctl) {
3654 btrfs_info(fs_info, "continuing balance");
3655 ret = btrfs_balance(fs_info->balance_ctl, NULL);
3658 mutex_unlock(&fs_info->balance_mutex);
3659 mutex_unlock(&fs_info->volume_mutex);
3664 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3666 struct task_struct *tsk;
3668 spin_lock(&fs_info->balance_lock);
3669 if (!fs_info->balance_ctl) {
3670 spin_unlock(&fs_info->balance_lock);
3673 spin_unlock(&fs_info->balance_lock);
3675 if (btrfs_test_opt(fs_info->tree_root, SKIP_BALANCE)) {
3676 btrfs_info(fs_info, "force skipping balance");
3680 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3681 return PTR_ERR_OR_ZERO(tsk);
3684 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3686 struct btrfs_balance_control *bctl;
3687 struct btrfs_balance_item *item;
3688 struct btrfs_disk_balance_args disk_bargs;
3689 struct btrfs_path *path;
3690 struct extent_buffer *leaf;
3691 struct btrfs_key key;
3694 path = btrfs_alloc_path();
3698 key.objectid = BTRFS_BALANCE_OBJECTID;
3699 key.type = BTRFS_BALANCE_ITEM_KEY;
3702 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3705 if (ret > 0) { /* ret = -ENOENT; */
3710 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3716 leaf = path->nodes[0];
3717 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3719 bctl->fs_info = fs_info;
3720 bctl->flags = btrfs_balance_flags(leaf, item);
3721 bctl->flags |= BTRFS_BALANCE_RESUME;
3723 btrfs_balance_data(leaf, item, &disk_bargs);
3724 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
3725 btrfs_balance_meta(leaf, item, &disk_bargs);
3726 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
3727 btrfs_balance_sys(leaf, item, &disk_bargs);
3728 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
3730 WARN_ON(atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1));
3732 mutex_lock(&fs_info->volume_mutex);
3733 mutex_lock(&fs_info->balance_mutex);
3735 set_balance_control(bctl);
3737 mutex_unlock(&fs_info->balance_mutex);
3738 mutex_unlock(&fs_info->volume_mutex);
3740 btrfs_free_path(path);
3744 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
3748 mutex_lock(&fs_info->balance_mutex);
3749 if (!fs_info->balance_ctl) {
3750 mutex_unlock(&fs_info->balance_mutex);
3754 if (atomic_read(&fs_info->balance_running)) {
3755 atomic_inc(&fs_info->balance_pause_req);
3756 mutex_unlock(&fs_info->balance_mutex);
3758 wait_event(fs_info->balance_wait_q,
3759 atomic_read(&fs_info->balance_running) == 0);
3761 mutex_lock(&fs_info->balance_mutex);
3762 /* we are good with balance_ctl ripped off from under us */
3763 BUG_ON(atomic_read(&fs_info->balance_running));
3764 atomic_dec(&fs_info->balance_pause_req);
3769 mutex_unlock(&fs_info->balance_mutex);
3773 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
3775 if (fs_info->sb->s_flags & MS_RDONLY)
3778 mutex_lock(&fs_info->balance_mutex);
3779 if (!fs_info->balance_ctl) {
3780 mutex_unlock(&fs_info->balance_mutex);
3784 atomic_inc(&fs_info->balance_cancel_req);
3786 * if we are running just wait and return, balance item is
3787 * deleted in btrfs_balance in this case
3789 if (atomic_read(&fs_info->balance_running)) {
3790 mutex_unlock(&fs_info->balance_mutex);
3791 wait_event(fs_info->balance_wait_q,
3792 atomic_read(&fs_info->balance_running) == 0);
3793 mutex_lock(&fs_info->balance_mutex);
3795 /* __cancel_balance needs volume_mutex */
3796 mutex_unlock(&fs_info->balance_mutex);
3797 mutex_lock(&fs_info->volume_mutex);
3798 mutex_lock(&fs_info->balance_mutex);
3800 if (fs_info->balance_ctl)
3801 __cancel_balance(fs_info);
3803 mutex_unlock(&fs_info->volume_mutex);
3806 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
3807 atomic_dec(&fs_info->balance_cancel_req);
3808 mutex_unlock(&fs_info->balance_mutex);
3812 static int btrfs_uuid_scan_kthread(void *data)
3814 struct btrfs_fs_info *fs_info = data;
3815 struct btrfs_root *root = fs_info->tree_root;
3816 struct btrfs_key key;
3817 struct btrfs_key max_key;
3818 struct btrfs_path *path = NULL;
3820 struct extent_buffer *eb;
3822 struct btrfs_root_item root_item;
3824 struct btrfs_trans_handle *trans = NULL;
3826 path = btrfs_alloc_path();
3833 key.type = BTRFS_ROOT_ITEM_KEY;
3836 max_key.objectid = (u64)-1;
3837 max_key.type = BTRFS_ROOT_ITEM_KEY;
3838 max_key.offset = (u64)-1;
3841 ret = btrfs_search_forward(root, &key, path, 0);
3848 if (key.type != BTRFS_ROOT_ITEM_KEY ||
3849 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
3850 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
3851 key.objectid > BTRFS_LAST_FREE_OBJECTID)
3854 eb = path->nodes[0];
3855 slot = path->slots[0];
3856 item_size = btrfs_item_size_nr(eb, slot);
3857 if (item_size < sizeof(root_item))
3860 read_extent_buffer(eb, &root_item,
3861 btrfs_item_ptr_offset(eb, slot),
3862 (int)sizeof(root_item));
3863 if (btrfs_root_refs(&root_item) == 0)
3866 if (!btrfs_is_empty_uuid(root_item.uuid) ||
3867 !btrfs_is_empty_uuid(root_item.received_uuid)) {
3871 btrfs_release_path(path);
3873 * 1 - subvol uuid item
3874 * 1 - received_subvol uuid item
3876 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
3877 if (IS_ERR(trans)) {
3878 ret = PTR_ERR(trans);
3886 if (!btrfs_is_empty_uuid(root_item.uuid)) {
3887 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
3889 BTRFS_UUID_KEY_SUBVOL,
3892 btrfs_warn(fs_info, "uuid_tree_add failed %d",
3898 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
3899 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
3900 root_item.received_uuid,
3901 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
3904 btrfs_warn(fs_info, "uuid_tree_add failed %d",
3912 ret = btrfs_end_transaction(trans, fs_info->uuid_root);
3918 btrfs_release_path(path);
3919 if (key.offset < (u64)-1) {
3921 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
3923 key.type = BTRFS_ROOT_ITEM_KEY;
3924 } else if (key.objectid < (u64)-1) {
3926 key.type = BTRFS_ROOT_ITEM_KEY;
3935 btrfs_free_path(path);
3936 if (trans && !IS_ERR(trans))
3937 btrfs_end_transaction(trans, fs_info->uuid_root);
3939 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
3941 fs_info->update_uuid_tree_gen = 1;
3942 up(&fs_info->uuid_tree_rescan_sem);
3947 * Callback for btrfs_uuid_tree_iterate().
3949 * 0 check succeeded, the entry is not outdated.
3950 * < 0 if an error occured.
3951 * > 0 if the check failed, which means the caller shall remove the entry.
3953 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
3954 u8 *uuid, u8 type, u64 subid)
3956 struct btrfs_key key;
3958 struct btrfs_root *subvol_root;
3960 if (type != BTRFS_UUID_KEY_SUBVOL &&
3961 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
3964 key.objectid = subid;
3965 key.type = BTRFS_ROOT_ITEM_KEY;
3966 key.offset = (u64)-1;
3967 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
3968 if (IS_ERR(subvol_root)) {
3969 ret = PTR_ERR(subvol_root);
3976 case BTRFS_UUID_KEY_SUBVOL:
3977 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
3980 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
3981 if (memcmp(uuid, subvol_root->root_item.received_uuid,
3991 static int btrfs_uuid_rescan_kthread(void *data)
3993 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
3997 * 1st step is to iterate through the existing UUID tree and
3998 * to delete all entries that contain outdated data.
3999 * 2nd step is to add all missing entries to the UUID tree.
4001 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4003 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4004 up(&fs_info->uuid_tree_rescan_sem);
4007 return btrfs_uuid_scan_kthread(data);
4010 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4012 struct btrfs_trans_handle *trans;
4013 struct btrfs_root *tree_root = fs_info->tree_root;
4014 struct btrfs_root *uuid_root;
4015 struct task_struct *task;
4022 trans = btrfs_start_transaction(tree_root, 2);
4024 return PTR_ERR(trans);
4026 uuid_root = btrfs_create_tree(trans, fs_info,
4027 BTRFS_UUID_TREE_OBJECTID);
4028 if (IS_ERR(uuid_root)) {
4029 ret = PTR_ERR(uuid_root);
4030 btrfs_abort_transaction(trans, tree_root, ret);
4034 fs_info->uuid_root = uuid_root;
4036 ret = btrfs_commit_transaction(trans, tree_root);
4040 down(&fs_info->uuid_tree_rescan_sem);
4041 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4043 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4044 btrfs_warn(fs_info, "failed to start uuid_scan task");
4045 up(&fs_info->uuid_tree_rescan_sem);
4046 return PTR_ERR(task);
4052 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4054 struct task_struct *task;
4056 down(&fs_info->uuid_tree_rescan_sem);
4057 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4059 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4060 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4061 up(&fs_info->uuid_tree_rescan_sem);
4062 return PTR_ERR(task);
4069 * shrinking a device means finding all of the device extents past
4070 * the new size, and then following the back refs to the chunks.
4071 * The chunk relocation code actually frees the device extent
4073 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4075 struct btrfs_trans_handle *trans;
4076 struct btrfs_root *root = device->dev_root;
4077 struct btrfs_dev_extent *dev_extent = NULL;
4078 struct btrfs_path *path;
4084 bool retried = false;
4085 bool checked_pending_chunks = false;
4086 struct extent_buffer *l;
4087 struct btrfs_key key;
4088 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
4089 u64 old_total = btrfs_super_total_bytes(super_copy);
4090 u64 old_size = btrfs_device_get_total_bytes(device);
4091 u64 diff = old_size - new_size;
4093 if (device->is_tgtdev_for_dev_replace)
4096 path = btrfs_alloc_path();
4104 btrfs_device_set_total_bytes(device, new_size);
4105 if (device->writeable) {
4106 device->fs_devices->total_rw_bytes -= diff;
4107 spin_lock(&root->fs_info->free_chunk_lock);
4108 root->fs_info->free_chunk_space -= diff;
4109 spin_unlock(&root->fs_info->free_chunk_lock);
4111 unlock_chunks(root);
4114 key.objectid = device->devid;
4115 key.offset = (u64)-1;
4116 key.type = BTRFS_DEV_EXTENT_KEY;
4119 mutex_lock(&root->fs_info->delete_unused_bgs_mutex);
4120 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4122 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4126 ret = btrfs_previous_item(root, path, 0, key.type);
4128 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4133 btrfs_release_path(path);
4138 slot = path->slots[0];
4139 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4141 if (key.objectid != device->devid) {
4142 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4143 btrfs_release_path(path);
4147 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4148 length = btrfs_dev_extent_length(l, dev_extent);
4150 if (key.offset + length <= new_size) {
4151 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4152 btrfs_release_path(path);
4156 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4157 btrfs_release_path(path);
4159 ret = btrfs_relocate_chunk(root, chunk_offset);
4160 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4161 if (ret && ret != -ENOSPC)
4165 } while (key.offset-- > 0);
4167 if (failed && !retried) {
4171 } else if (failed && retried) {
4176 /* Shrinking succeeded, else we would be at "done". */
4177 trans = btrfs_start_transaction(root, 0);
4178 if (IS_ERR(trans)) {
4179 ret = PTR_ERR(trans);
4186 * We checked in the above loop all device extents that were already in
4187 * the device tree. However before we have updated the device's
4188 * total_bytes to the new size, we might have had chunk allocations that
4189 * have not complete yet (new block groups attached to transaction
4190 * handles), and therefore their device extents were not yet in the
4191 * device tree and we missed them in the loop above. So if we have any
4192 * pending chunk using a device extent that overlaps the device range
4193 * that we can not use anymore, commit the current transaction and
4194 * repeat the search on the device tree - this way we guarantee we will
4195 * not have chunks using device extents that end beyond 'new_size'.
4197 if (!checked_pending_chunks) {
4198 u64 start = new_size;
4199 u64 len = old_size - new_size;
4201 if (contains_pending_extent(trans->transaction, device,
4203 unlock_chunks(root);
4204 checked_pending_chunks = true;
4207 ret = btrfs_commit_transaction(trans, root);
4214 btrfs_device_set_disk_total_bytes(device, new_size);
4215 if (list_empty(&device->resized_list))
4216 list_add_tail(&device->resized_list,
4217 &root->fs_info->fs_devices->resized_devices);
4219 WARN_ON(diff > old_total);
4220 btrfs_set_super_total_bytes(super_copy, old_total - diff);
4221 unlock_chunks(root);
4223 /* Now btrfs_update_device() will change the on-disk size. */
4224 ret = btrfs_update_device(trans, device);
4225 btrfs_end_transaction(trans, root);
4227 btrfs_free_path(path);
4230 btrfs_device_set_total_bytes(device, old_size);
4231 if (device->writeable)
4232 device->fs_devices->total_rw_bytes += diff;
4233 spin_lock(&root->fs_info->free_chunk_lock);
4234 root->fs_info->free_chunk_space += diff;
4235 spin_unlock(&root->fs_info->free_chunk_lock);
4236 unlock_chunks(root);
4241 static int btrfs_add_system_chunk(struct btrfs_root *root,
4242 struct btrfs_key *key,
4243 struct btrfs_chunk *chunk, int item_size)
4245 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
4246 struct btrfs_disk_key disk_key;
4251 array_size = btrfs_super_sys_array_size(super_copy);
4252 if (array_size + item_size + sizeof(disk_key)
4253 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4254 unlock_chunks(root);
4258 ptr = super_copy->sys_chunk_array + array_size;
4259 btrfs_cpu_key_to_disk(&disk_key, key);
4260 memcpy(ptr, &disk_key, sizeof(disk_key));
4261 ptr += sizeof(disk_key);
4262 memcpy(ptr, chunk, item_size);
4263 item_size += sizeof(disk_key);
4264 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4265 unlock_chunks(root);
4271 * sort the devices in descending order by max_avail, total_avail
4273 static int btrfs_cmp_device_info(const void *a, const void *b)
4275 const struct btrfs_device_info *di_a = a;
4276 const struct btrfs_device_info *di_b = b;
4278 if (di_a->max_avail > di_b->max_avail)
4280 if (di_a->max_avail < di_b->max_avail)
4282 if (di_a->total_avail > di_b->total_avail)
4284 if (di_a->total_avail < di_b->total_avail)
4289 static const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
4290 [BTRFS_RAID_RAID10] = {
4293 .devs_max = 0, /* 0 == as many as possible */
4295 .devs_increment = 2,
4298 [BTRFS_RAID_RAID1] = {
4303 .devs_increment = 2,
4306 [BTRFS_RAID_DUP] = {
4311 .devs_increment = 1,
4314 [BTRFS_RAID_RAID0] = {
4319 .devs_increment = 1,
4322 [BTRFS_RAID_SINGLE] = {
4327 .devs_increment = 1,
4330 [BTRFS_RAID_RAID5] = {
4335 .devs_increment = 1,
4338 [BTRFS_RAID_RAID6] = {
4343 .devs_increment = 1,
4348 static u32 find_raid56_stripe_len(u32 data_devices, u32 dev_stripe_target)
4350 /* TODO allow them to set a preferred stripe size */
4354 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4356 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4359 btrfs_set_fs_incompat(info, RAID56);
4362 #define BTRFS_MAX_DEVS(r) ((BTRFS_LEAF_DATA_SIZE(r) \
4363 - sizeof(struct btrfs_item) \
4364 - sizeof(struct btrfs_chunk)) \
4365 / sizeof(struct btrfs_stripe) + 1)
4367 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4368 - 2 * sizeof(struct btrfs_disk_key) \
4369 - 2 * sizeof(struct btrfs_chunk)) \
4370 / sizeof(struct btrfs_stripe) + 1)
4372 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4373 struct btrfs_root *extent_root, u64 start,
4376 struct btrfs_fs_info *info = extent_root->fs_info;
4377 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4378 struct list_head *cur;
4379 struct map_lookup *map = NULL;
4380 struct extent_map_tree *em_tree;
4381 struct extent_map *em;
4382 struct btrfs_device_info *devices_info = NULL;
4384 int num_stripes; /* total number of stripes to allocate */
4385 int data_stripes; /* number of stripes that count for
4387 int sub_stripes; /* sub_stripes info for map */
4388 int dev_stripes; /* stripes per dev */
4389 int devs_max; /* max devs to use */
4390 int devs_min; /* min devs needed */
4391 int devs_increment; /* ndevs has to be a multiple of this */
4392 int ncopies; /* how many copies to data has */
4394 u64 max_stripe_size;
4398 u64 raid_stripe_len = BTRFS_STRIPE_LEN;
4404 BUG_ON(!alloc_profile_is_valid(type, 0));
4406 if (list_empty(&fs_devices->alloc_list))
4409 index = __get_raid_index(type);
4411 sub_stripes = btrfs_raid_array[index].sub_stripes;
4412 dev_stripes = btrfs_raid_array[index].dev_stripes;
4413 devs_max = btrfs_raid_array[index].devs_max;
4414 devs_min = btrfs_raid_array[index].devs_min;
4415 devs_increment = btrfs_raid_array[index].devs_increment;
4416 ncopies = btrfs_raid_array[index].ncopies;
4418 if (type & BTRFS_BLOCK_GROUP_DATA) {
4419 max_stripe_size = 1024 * 1024 * 1024;
4420 max_chunk_size = 10 * max_stripe_size;
4422 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4423 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4424 /* for larger filesystems, use larger metadata chunks */
4425 if (fs_devices->total_rw_bytes > 50ULL * 1024 * 1024 * 1024)
4426 max_stripe_size = 1024 * 1024 * 1024;
4428 max_stripe_size = 256 * 1024 * 1024;
4429 max_chunk_size = max_stripe_size;
4431 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4432 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4433 max_stripe_size = 32 * 1024 * 1024;
4434 max_chunk_size = 2 * max_stripe_size;
4436 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4438 btrfs_err(info, "invalid chunk type 0x%llx requested",
4443 /* we don't want a chunk larger than 10% of writeable space */
4444 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4447 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4452 cur = fs_devices->alloc_list.next;
4455 * in the first pass through the devices list, we gather information
4456 * about the available holes on each device.
4459 while (cur != &fs_devices->alloc_list) {
4460 struct btrfs_device *device;
4464 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
4468 if (!device->writeable) {
4470 "BTRFS: read-only device in alloc_list\n");
4474 if (!device->in_fs_metadata ||
4475 device->is_tgtdev_for_dev_replace)
4478 if (device->total_bytes > device->bytes_used)
4479 total_avail = device->total_bytes - device->bytes_used;
4483 /* If there is no space on this device, skip it. */
4484 if (total_avail == 0)
4487 ret = find_free_dev_extent(trans, device,
4488 max_stripe_size * dev_stripes,
4489 &dev_offset, &max_avail);
4490 if (ret && ret != -ENOSPC)
4494 max_avail = max_stripe_size * dev_stripes;
4496 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
4499 if (ndevs == fs_devices->rw_devices) {
4500 WARN(1, "%s: found more than %llu devices\n",
4501 __func__, fs_devices->rw_devices);
4504 devices_info[ndevs].dev_offset = dev_offset;
4505 devices_info[ndevs].max_avail = max_avail;
4506 devices_info[ndevs].total_avail = total_avail;
4507 devices_info[ndevs].dev = device;
4512 * now sort the devices by hole size / available space
4514 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4515 btrfs_cmp_device_info, NULL);
4517 /* round down to number of usable stripes */
4518 ndevs -= ndevs % devs_increment;
4520 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
4525 if (devs_max && ndevs > devs_max)
4528 * the primary goal is to maximize the number of stripes, so use as many
4529 * devices as possible, even if the stripes are not maximum sized.
4531 stripe_size = devices_info[ndevs-1].max_avail;
4532 num_stripes = ndevs * dev_stripes;
4535 * this will have to be fixed for RAID1 and RAID10 over
4538 data_stripes = num_stripes / ncopies;
4540 if (type & BTRFS_BLOCK_GROUP_RAID5) {
4541 raid_stripe_len = find_raid56_stripe_len(ndevs - 1,
4542 btrfs_super_stripesize(info->super_copy));
4543 data_stripes = num_stripes - 1;
4545 if (type & BTRFS_BLOCK_GROUP_RAID6) {
4546 raid_stripe_len = find_raid56_stripe_len(ndevs - 2,
4547 btrfs_super_stripesize(info->super_copy));
4548 data_stripes = num_stripes - 2;
4552 * Use the number of data stripes to figure out how big this chunk
4553 * is really going to be in terms of logical address space,
4554 * and compare that answer with the max chunk size
4556 if (stripe_size * data_stripes > max_chunk_size) {
4557 u64 mask = (1ULL << 24) - 1;
4559 stripe_size = div_u64(max_chunk_size, data_stripes);
4561 /* bump the answer up to a 16MB boundary */
4562 stripe_size = (stripe_size + mask) & ~mask;
4564 /* but don't go higher than the limits we found
4565 * while searching for free extents
4567 if (stripe_size > devices_info[ndevs-1].max_avail)
4568 stripe_size = devices_info[ndevs-1].max_avail;
4571 stripe_size = div_u64(stripe_size, dev_stripes);
4573 /* align to BTRFS_STRIPE_LEN */
4574 stripe_size = div_u64(stripe_size, raid_stripe_len);
4575 stripe_size *= raid_stripe_len;
4577 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4582 map->num_stripes = num_stripes;
4584 for (i = 0; i < ndevs; ++i) {
4585 for (j = 0; j < dev_stripes; ++j) {
4586 int s = i * dev_stripes + j;
4587 map->stripes[s].dev = devices_info[i].dev;
4588 map->stripes[s].physical = devices_info[i].dev_offset +
4592 map->sector_size = extent_root->sectorsize;
4593 map->stripe_len = raid_stripe_len;
4594 map->io_align = raid_stripe_len;
4595 map->io_width = raid_stripe_len;
4597 map->sub_stripes = sub_stripes;
4599 num_bytes = stripe_size * data_stripes;
4601 trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
4603 em = alloc_extent_map();
4609 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4610 em->bdev = (struct block_device *)map;
4612 em->len = num_bytes;
4613 em->block_start = 0;
4614 em->block_len = em->len;
4615 em->orig_block_len = stripe_size;
4617 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4618 write_lock(&em_tree->lock);
4619 ret = add_extent_mapping(em_tree, em, 0);
4621 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4622 atomic_inc(&em->refs);
4624 write_unlock(&em_tree->lock);
4626 free_extent_map(em);
4630 ret = btrfs_make_block_group(trans, extent_root, 0, type,
4631 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4634 goto error_del_extent;
4636 for (i = 0; i < map->num_stripes; i++) {
4637 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4638 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4641 spin_lock(&extent_root->fs_info->free_chunk_lock);
4642 extent_root->fs_info->free_chunk_space -= (stripe_size *
4644 spin_unlock(&extent_root->fs_info->free_chunk_lock);
4646 free_extent_map(em);
4647 check_raid56_incompat_flag(extent_root->fs_info, type);
4649 kfree(devices_info);
4653 write_lock(&em_tree->lock);
4654 remove_extent_mapping(em_tree, em);
4655 write_unlock(&em_tree->lock);
4657 /* One for our allocation */
4658 free_extent_map(em);
4659 /* One for the tree reference */
4660 free_extent_map(em);
4661 /* One for the pending_chunks list reference */
4662 free_extent_map(em);
4664 kfree(devices_info);
4668 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4669 struct btrfs_root *extent_root,
4670 u64 chunk_offset, u64 chunk_size)
4672 struct btrfs_key key;
4673 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
4674 struct btrfs_device *device;
4675 struct btrfs_chunk *chunk;
4676 struct btrfs_stripe *stripe;
4677 struct extent_map_tree *em_tree;
4678 struct extent_map *em;
4679 struct map_lookup *map;
4686 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4687 read_lock(&em_tree->lock);
4688 em = lookup_extent_mapping(em_tree, chunk_offset, chunk_size);
4689 read_unlock(&em_tree->lock);
4692 btrfs_crit(extent_root->fs_info, "unable to find logical "
4693 "%Lu len %Lu", chunk_offset, chunk_size);
4697 if (em->start != chunk_offset || em->len != chunk_size) {
4698 btrfs_crit(extent_root->fs_info, "found a bad mapping, wanted"
4699 " %Lu-%Lu, found %Lu-%Lu", chunk_offset,
4700 chunk_size, em->start, em->len);
4701 free_extent_map(em);
4705 map = (struct map_lookup *)em->bdev;
4706 item_size = btrfs_chunk_item_size(map->num_stripes);
4707 stripe_size = em->orig_block_len;
4709 chunk = kzalloc(item_size, GFP_NOFS);
4715 for (i = 0; i < map->num_stripes; i++) {
4716 device = map->stripes[i].dev;
4717 dev_offset = map->stripes[i].physical;
4719 ret = btrfs_update_device(trans, device);
4722 ret = btrfs_alloc_dev_extent(trans, device,
4723 chunk_root->root_key.objectid,
4724 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4725 chunk_offset, dev_offset,
4731 stripe = &chunk->stripe;
4732 for (i = 0; i < map->num_stripes; i++) {
4733 device = map->stripes[i].dev;
4734 dev_offset = map->stripes[i].physical;
4736 btrfs_set_stack_stripe_devid(stripe, device->devid);
4737 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4738 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4742 btrfs_set_stack_chunk_length(chunk, chunk_size);
4743 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4744 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4745 btrfs_set_stack_chunk_type(chunk, map->type);
4746 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4747 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4748 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4749 btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
4750 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
4752 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4753 key.type = BTRFS_CHUNK_ITEM_KEY;
4754 key.offset = chunk_offset;
4756 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4757 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4759 * TODO: Cleanup of inserted chunk root in case of
4762 ret = btrfs_add_system_chunk(chunk_root, &key, chunk,
4768 free_extent_map(em);
4773 * Chunk allocation falls into two parts. The first part does works
4774 * that make the new allocated chunk useable, but not do any operation
4775 * that modifies the chunk tree. The second part does the works that
4776 * require modifying the chunk tree. This division is important for the
4777 * bootstrap process of adding storage to a seed btrfs.
4779 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4780 struct btrfs_root *extent_root, u64 type)
4784 ASSERT(mutex_is_locked(&extent_root->fs_info->chunk_mutex));
4785 chunk_offset = find_next_chunk(extent_root->fs_info);
4786 return __btrfs_alloc_chunk(trans, extent_root, chunk_offset, type);
4789 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
4790 struct btrfs_root *root,
4791 struct btrfs_device *device)
4794 u64 sys_chunk_offset;
4796 struct btrfs_fs_info *fs_info = root->fs_info;
4797 struct btrfs_root *extent_root = fs_info->extent_root;
4800 chunk_offset = find_next_chunk(fs_info);
4801 alloc_profile = btrfs_get_alloc_profile(extent_root, 0);
4802 ret = __btrfs_alloc_chunk(trans, extent_root, chunk_offset,
4807 sys_chunk_offset = find_next_chunk(root->fs_info);
4808 alloc_profile = btrfs_get_alloc_profile(fs_info->chunk_root, 0);
4809 ret = __btrfs_alloc_chunk(trans, extent_root, sys_chunk_offset,
4814 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
4818 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
4819 BTRFS_BLOCK_GROUP_RAID10 |
4820 BTRFS_BLOCK_GROUP_RAID5 |
4821 BTRFS_BLOCK_GROUP_DUP)) {
4823 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
4832 int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
4834 struct extent_map *em;
4835 struct map_lookup *map;
4836 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4841 read_lock(&map_tree->map_tree.lock);
4842 em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
4843 read_unlock(&map_tree->map_tree.lock);
4847 map = (struct map_lookup *)em->bdev;
4848 for (i = 0; i < map->num_stripes; i++) {
4849 if (map->stripes[i].dev->missing) {
4854 if (!map->stripes[i].dev->writeable) {
4861 * If the number of missing devices is larger than max errors,
4862 * we can not write the data into that chunk successfully, so
4865 if (miss_ndevs > btrfs_chunk_max_errors(map))
4868 free_extent_map(em);
4872 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
4874 extent_map_tree_init(&tree->map_tree);
4877 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
4879 struct extent_map *em;
4882 write_lock(&tree->map_tree.lock);
4883 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
4885 remove_extent_mapping(&tree->map_tree, em);
4886 write_unlock(&tree->map_tree.lock);
4890 free_extent_map(em);
4891 /* once for the tree */
4892 free_extent_map(em);
4896 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
4898 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
4899 struct extent_map *em;
4900 struct map_lookup *map;
4901 struct extent_map_tree *em_tree = &map_tree->map_tree;
4904 read_lock(&em_tree->lock);
4905 em = lookup_extent_mapping(em_tree, logical, len);
4906 read_unlock(&em_tree->lock);
4909 * We could return errors for these cases, but that could get ugly and
4910 * we'd probably do the same thing which is just not do anything else
4911 * and exit, so return 1 so the callers don't try to use other copies.
4914 btrfs_crit(fs_info, "No mapping for %Lu-%Lu", logical,
4919 if (em->start > logical || em->start + em->len < logical) {
4920 btrfs_crit(fs_info, "Invalid mapping for %Lu-%Lu, got "
4921 "%Lu-%Lu", logical, logical+len, em->start,
4922 em->start + em->len);
4923 free_extent_map(em);
4927 map = (struct map_lookup *)em->bdev;
4928 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
4929 ret = map->num_stripes;
4930 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
4931 ret = map->sub_stripes;
4932 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
4934 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
4938 free_extent_map(em);
4940 btrfs_dev_replace_lock(&fs_info->dev_replace);
4941 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))
4943 btrfs_dev_replace_unlock(&fs_info->dev_replace);
4948 unsigned long btrfs_full_stripe_len(struct btrfs_root *root,
4949 struct btrfs_mapping_tree *map_tree,
4952 struct extent_map *em;
4953 struct map_lookup *map;
4954 struct extent_map_tree *em_tree = &map_tree->map_tree;
4955 unsigned long len = root->sectorsize;
4957 read_lock(&em_tree->lock);
4958 em = lookup_extent_mapping(em_tree, logical, len);
4959 read_unlock(&em_tree->lock);
4962 BUG_ON(em->start > logical || em->start + em->len < logical);
4963 map = (struct map_lookup *)em->bdev;
4964 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
4965 len = map->stripe_len * nr_data_stripes(map);
4966 free_extent_map(em);
4970 int btrfs_is_parity_mirror(struct btrfs_mapping_tree *map_tree,
4971 u64 logical, u64 len, int mirror_num)
4973 struct extent_map *em;
4974 struct map_lookup *map;
4975 struct extent_map_tree *em_tree = &map_tree->map_tree;
4978 read_lock(&em_tree->lock);
4979 em = lookup_extent_mapping(em_tree, logical, len);
4980 read_unlock(&em_tree->lock);
4983 BUG_ON(em->start > logical || em->start + em->len < logical);
4984 map = (struct map_lookup *)em->bdev;
4985 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
4987 free_extent_map(em);
4991 static int find_live_mirror(struct btrfs_fs_info *fs_info,
4992 struct map_lookup *map, int first, int num,
4993 int optimal, int dev_replace_is_ongoing)
4997 struct btrfs_device *srcdev;
4999 if (dev_replace_is_ongoing &&
5000 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5001 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5002 srcdev = fs_info->dev_replace.srcdev;
5007 * try to avoid the drive that is the source drive for a
5008 * dev-replace procedure, only choose it if no other non-missing
5009 * mirror is available
5011 for (tolerance = 0; tolerance < 2; tolerance++) {
5012 if (map->stripes[optimal].dev->bdev &&
5013 (tolerance || map->stripes[optimal].dev != srcdev))
5015 for (i = first; i < first + num; i++) {
5016 if (map->stripes[i].dev->bdev &&
5017 (tolerance || map->stripes[i].dev != srcdev))
5022 /* we couldn't find one that doesn't fail. Just return something
5023 * and the io error handling code will clean up eventually
5028 static inline int parity_smaller(u64 a, u64 b)
5033 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5034 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5036 struct btrfs_bio_stripe s;
5043 for (i = 0; i < num_stripes - 1; i++) {
5044 if (parity_smaller(bbio->raid_map[i],
5045 bbio->raid_map[i+1])) {
5046 s = bbio->stripes[i];
5047 l = bbio->raid_map[i];
5048 bbio->stripes[i] = bbio->stripes[i+1];
5049 bbio->raid_map[i] = bbio->raid_map[i+1];
5050 bbio->stripes[i+1] = s;
5051 bbio->raid_map[i+1] = l;
5059 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5061 struct btrfs_bio *bbio = kzalloc(
5062 /* the size of the btrfs_bio */
5063 sizeof(struct btrfs_bio) +
5064 /* plus the variable array for the stripes */
5065 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5066 /* plus the variable array for the tgt dev */
5067 sizeof(int) * (real_stripes) +
5069 * plus the raid_map, which includes both the tgt dev
5072 sizeof(u64) * (total_stripes),
5073 GFP_NOFS|__GFP_NOFAIL);
5075 atomic_set(&bbio->error, 0);
5076 atomic_set(&bbio->refs, 1);
5081 void btrfs_get_bbio(struct btrfs_bio *bbio)
5083 WARN_ON(!atomic_read(&bbio->refs));
5084 atomic_inc(&bbio->refs);
5087 void btrfs_put_bbio(struct btrfs_bio *bbio)
5091 if (atomic_dec_and_test(&bbio->refs))
5095 static int __btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
5096 u64 logical, u64 *length,
5097 struct btrfs_bio **bbio_ret,
5098 int mirror_num, int need_raid_map)
5100 struct extent_map *em;
5101 struct map_lookup *map;
5102 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
5103 struct extent_map_tree *em_tree = &map_tree->map_tree;
5106 u64 stripe_end_offset;
5116 int tgtdev_indexes = 0;
5117 struct btrfs_bio *bbio = NULL;
5118 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5119 int dev_replace_is_ongoing = 0;
5120 int num_alloc_stripes;
5121 int patch_the_first_stripe_for_dev_replace = 0;
5122 u64 physical_to_patch_in_first_stripe = 0;
5123 u64 raid56_full_stripe_start = (u64)-1;
5125 read_lock(&em_tree->lock);
5126 em = lookup_extent_mapping(em_tree, logical, *length);
5127 read_unlock(&em_tree->lock);
5130 btrfs_crit(fs_info, "unable to find logical %llu len %llu",
5135 if (em->start > logical || em->start + em->len < logical) {
5136 btrfs_crit(fs_info, "found a bad mapping, wanted %Lu, "
5137 "found %Lu-%Lu", logical, em->start,
5138 em->start + em->len);
5139 free_extent_map(em);
5143 map = (struct map_lookup *)em->bdev;
5144 offset = logical - em->start;
5146 stripe_len = map->stripe_len;
5149 * stripe_nr counts the total number of stripes we have to stride
5150 * to get to this block
5152 stripe_nr = div64_u64(stripe_nr, stripe_len);
5154 stripe_offset = stripe_nr * stripe_len;
5155 BUG_ON(offset < stripe_offset);
5157 /* stripe_offset is the offset of this block in its stripe*/
5158 stripe_offset = offset - stripe_offset;
5160 /* if we're here for raid56, we need to know the stripe aligned start */
5161 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5162 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5163 raid56_full_stripe_start = offset;
5165 /* allow a write of a full stripe, but make sure we don't
5166 * allow straddling of stripes
5168 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5170 raid56_full_stripe_start *= full_stripe_len;
5173 if (rw & REQ_DISCARD) {
5174 /* we don't discard raid56 yet */
5175 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5179 *length = min_t(u64, em->len - offset, *length);
5180 } else if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5182 /* For writes to RAID[56], allow a full stripeset across all disks.
5183 For other RAID types and for RAID[56] reads, just allow a single
5184 stripe (on a single disk). */
5185 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5187 max_len = stripe_len * nr_data_stripes(map) -
5188 (offset - raid56_full_stripe_start);
5190 /* we limit the length of each bio to what fits in a stripe */
5191 max_len = stripe_len - stripe_offset;
5193 *length = min_t(u64, em->len - offset, max_len);
5195 *length = em->len - offset;
5198 /* This is for when we're called from btrfs_merge_bio_hook() and all
5199 it cares about is the length */
5203 btrfs_dev_replace_lock(dev_replace);
5204 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5205 if (!dev_replace_is_ongoing)
5206 btrfs_dev_replace_unlock(dev_replace);
5208 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5209 !(rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) &&
5210 dev_replace->tgtdev != NULL) {
5212 * in dev-replace case, for repair case (that's the only
5213 * case where the mirror is selected explicitly when
5214 * calling btrfs_map_block), blocks left of the left cursor
5215 * can also be read from the target drive.
5216 * For REQ_GET_READ_MIRRORS, the target drive is added as
5217 * the last one to the array of stripes. For READ, it also
5218 * needs to be supported using the same mirror number.
5219 * If the requested block is not left of the left cursor,
5220 * EIO is returned. This can happen because btrfs_num_copies()
5221 * returns one more in the dev-replace case.
5223 u64 tmp_length = *length;
5224 struct btrfs_bio *tmp_bbio = NULL;
5225 int tmp_num_stripes;
5226 u64 srcdev_devid = dev_replace->srcdev->devid;
5227 int index_srcdev = 0;
5229 u64 physical_of_found = 0;
5231 ret = __btrfs_map_block(fs_info, REQ_GET_READ_MIRRORS,
5232 logical, &tmp_length, &tmp_bbio, 0, 0);
5234 WARN_ON(tmp_bbio != NULL);
5238 tmp_num_stripes = tmp_bbio->num_stripes;
5239 if (mirror_num > tmp_num_stripes) {
5241 * REQ_GET_READ_MIRRORS does not contain this
5242 * mirror, that means that the requested area
5243 * is not left of the left cursor
5246 btrfs_put_bbio(tmp_bbio);
5251 * process the rest of the function using the mirror_num
5252 * of the source drive. Therefore look it up first.
5253 * At the end, patch the device pointer to the one of the
5256 for (i = 0; i < tmp_num_stripes; i++) {
5257 if (tmp_bbio->stripes[i].dev->devid == srcdev_devid) {
5259 * In case of DUP, in order to keep it
5260 * simple, only add the mirror with the
5261 * lowest physical address
5264 physical_of_found <=
5265 tmp_bbio->stripes[i].physical)
5270 tmp_bbio->stripes[i].physical;
5275 mirror_num = index_srcdev + 1;
5276 patch_the_first_stripe_for_dev_replace = 1;
5277 physical_to_patch_in_first_stripe = physical_of_found;
5281 btrfs_put_bbio(tmp_bbio);
5285 btrfs_put_bbio(tmp_bbio);
5286 } else if (mirror_num > map->num_stripes) {
5292 stripe_nr_orig = stripe_nr;
5293 stripe_nr_end = ALIGN(offset + *length, map->stripe_len);
5294 stripe_nr_end = div_u64(stripe_nr_end, map->stripe_len);
5295 stripe_end_offset = stripe_nr_end * map->stripe_len -
5298 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5299 if (rw & REQ_DISCARD)
5300 num_stripes = min_t(u64, map->num_stripes,
5301 stripe_nr_end - stripe_nr_orig);
5302 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5304 if (!(rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)))
5306 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5307 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS))
5308 num_stripes = map->num_stripes;
5309 else if (mirror_num)
5310 stripe_index = mirror_num - 1;
5312 stripe_index = find_live_mirror(fs_info, map, 0,
5314 current->pid % map->num_stripes,
5315 dev_replace_is_ongoing);
5316 mirror_num = stripe_index + 1;
5319 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5320 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) {
5321 num_stripes = map->num_stripes;
5322 } else if (mirror_num) {
5323 stripe_index = mirror_num - 1;
5328 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5329 u32 factor = map->num_stripes / map->sub_stripes;
5331 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5332 stripe_index *= map->sub_stripes;
5334 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
5335 num_stripes = map->sub_stripes;
5336 else if (rw & REQ_DISCARD)
5337 num_stripes = min_t(u64, map->sub_stripes *
5338 (stripe_nr_end - stripe_nr_orig),
5340 else if (mirror_num)
5341 stripe_index += mirror_num - 1;
5343 int old_stripe_index = stripe_index;
5344 stripe_index = find_live_mirror(fs_info, map,
5346 map->sub_stripes, stripe_index +
5347 current->pid % map->sub_stripes,
5348 dev_replace_is_ongoing);
5349 mirror_num = stripe_index - old_stripe_index + 1;
5352 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5353 if (need_raid_map &&
5354 ((rw & (REQ_WRITE | REQ_GET_READ_MIRRORS)) ||
5356 /* push stripe_nr back to the start of the full stripe */
5357 stripe_nr = div_u64(raid56_full_stripe_start,
5358 stripe_len * nr_data_stripes(map));
5360 /* RAID[56] write or recovery. Return all stripes */
5361 num_stripes = map->num_stripes;
5362 max_errors = nr_parity_stripes(map);
5364 *length = map->stripe_len;
5369 * Mirror #0 or #1 means the original data block.
5370 * Mirror #2 is RAID5 parity block.
5371 * Mirror #3 is RAID6 Q block.
5373 stripe_nr = div_u64_rem(stripe_nr,
5374 nr_data_stripes(map), &stripe_index);
5376 stripe_index = nr_data_stripes(map) +
5379 /* We distribute the parity blocks across stripes */
5380 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5382 if (!(rw & (REQ_WRITE | REQ_DISCARD |
5383 REQ_GET_READ_MIRRORS)) && mirror_num <= 1)
5388 * after this, stripe_nr is the number of stripes on this
5389 * device we have to walk to find the data, and stripe_index is
5390 * the number of our device in the stripe array
5392 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5394 mirror_num = stripe_index + 1;
5396 BUG_ON(stripe_index >= map->num_stripes);
5398 num_alloc_stripes = num_stripes;
5399 if (dev_replace_is_ongoing) {
5400 if (rw & (REQ_WRITE | REQ_DISCARD))
5401 num_alloc_stripes <<= 1;
5402 if (rw & REQ_GET_READ_MIRRORS)
5403 num_alloc_stripes++;
5404 tgtdev_indexes = num_stripes;
5407 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5412 if (dev_replace_is_ongoing)
5413 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5415 /* build raid_map */
5416 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK &&
5417 need_raid_map && ((rw & (REQ_WRITE | REQ_GET_READ_MIRRORS)) ||
5422 bbio->raid_map = (u64 *)((void *)bbio->stripes +
5423 sizeof(struct btrfs_bio_stripe) *
5425 sizeof(int) * tgtdev_indexes);
5427 /* Work out the disk rotation on this stripe-set */
5428 div_u64_rem(stripe_nr, num_stripes, &rot);
5430 /* Fill in the logical address of each stripe */
5431 tmp = stripe_nr * nr_data_stripes(map);
5432 for (i = 0; i < nr_data_stripes(map); i++)
5433 bbio->raid_map[(i+rot) % num_stripes] =
5434 em->start + (tmp + i) * map->stripe_len;
5436 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5437 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5438 bbio->raid_map[(i+rot+1) % num_stripes] =
5442 if (rw & REQ_DISCARD) {
5444 u32 sub_stripes = 0;
5445 u64 stripes_per_dev = 0;
5446 u32 remaining_stripes = 0;
5447 u32 last_stripe = 0;
5450 (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
5451 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5454 sub_stripes = map->sub_stripes;
5456 factor = map->num_stripes / sub_stripes;
5457 stripes_per_dev = div_u64_rem(stripe_nr_end -
5460 &remaining_stripes);
5461 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5462 last_stripe *= sub_stripes;
5465 for (i = 0; i < num_stripes; i++) {
5466 bbio->stripes[i].physical =
5467 map->stripes[stripe_index].physical +
5468 stripe_offset + stripe_nr * map->stripe_len;
5469 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5471 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5472 BTRFS_BLOCK_GROUP_RAID10)) {
5473 bbio->stripes[i].length = stripes_per_dev *
5476 if (i / sub_stripes < remaining_stripes)
5477 bbio->stripes[i].length +=
5481 * Special for the first stripe and
5484 * |-------|...|-------|
5488 if (i < sub_stripes)
5489 bbio->stripes[i].length -=
5492 if (stripe_index >= last_stripe &&
5493 stripe_index <= (last_stripe +
5495 bbio->stripes[i].length -=
5498 if (i == sub_stripes - 1)
5501 bbio->stripes[i].length = *length;
5504 if (stripe_index == map->num_stripes) {
5505 /* This could only happen for RAID0/10 */
5511 for (i = 0; i < num_stripes; i++) {
5512 bbio->stripes[i].physical =
5513 map->stripes[stripe_index].physical +
5515 stripe_nr * map->stripe_len;
5516 bbio->stripes[i].dev =
5517 map->stripes[stripe_index].dev;
5522 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
5523 max_errors = btrfs_chunk_max_errors(map);
5526 sort_parity_stripes(bbio, num_stripes);
5529 if (dev_replace_is_ongoing && (rw & (REQ_WRITE | REQ_DISCARD)) &&
5530 dev_replace->tgtdev != NULL) {
5531 int index_where_to_add;
5532 u64 srcdev_devid = dev_replace->srcdev->devid;
5535 * duplicate the write operations while the dev replace
5536 * procedure is running. Since the copying of the old disk
5537 * to the new disk takes place at run time while the
5538 * filesystem is mounted writable, the regular write
5539 * operations to the old disk have to be duplicated to go
5540 * to the new disk as well.
5541 * Note that device->missing is handled by the caller, and
5542 * that the write to the old disk is already set up in the
5545 index_where_to_add = num_stripes;
5546 for (i = 0; i < num_stripes; i++) {
5547 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5548 /* write to new disk, too */
5549 struct btrfs_bio_stripe *new =
5550 bbio->stripes + index_where_to_add;
5551 struct btrfs_bio_stripe *old =
5554 new->physical = old->physical;
5555 new->length = old->length;
5556 new->dev = dev_replace->tgtdev;
5557 bbio->tgtdev_map[i] = index_where_to_add;
5558 index_where_to_add++;
5563 num_stripes = index_where_to_add;
5564 } else if (dev_replace_is_ongoing && (rw & REQ_GET_READ_MIRRORS) &&
5565 dev_replace->tgtdev != NULL) {
5566 u64 srcdev_devid = dev_replace->srcdev->devid;
5567 int index_srcdev = 0;
5569 u64 physical_of_found = 0;
5572 * During the dev-replace procedure, the target drive can
5573 * also be used to read data in case it is needed to repair
5574 * a corrupt block elsewhere. This is possible if the
5575 * requested area is left of the left cursor. In this area,
5576 * the target drive is a full copy of the source drive.
5578 for (i = 0; i < num_stripes; i++) {
5579 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5581 * In case of DUP, in order to keep it
5582 * simple, only add the mirror with the
5583 * lowest physical address
5586 physical_of_found <=
5587 bbio->stripes[i].physical)
5591 physical_of_found = bbio->stripes[i].physical;
5595 if (physical_of_found + map->stripe_len <=
5596 dev_replace->cursor_left) {
5597 struct btrfs_bio_stripe *tgtdev_stripe =
5598 bbio->stripes + num_stripes;
5600 tgtdev_stripe->physical = physical_of_found;
5601 tgtdev_stripe->length =
5602 bbio->stripes[index_srcdev].length;
5603 tgtdev_stripe->dev = dev_replace->tgtdev;
5604 bbio->tgtdev_map[index_srcdev] = num_stripes;
5613 bbio->map_type = map->type;
5614 bbio->num_stripes = num_stripes;
5615 bbio->max_errors = max_errors;
5616 bbio->mirror_num = mirror_num;
5617 bbio->num_tgtdevs = tgtdev_indexes;
5620 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5621 * mirror_num == num_stripes + 1 && dev_replace target drive is
5622 * available as a mirror
5624 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5625 WARN_ON(num_stripes > 1);
5626 bbio->stripes[0].dev = dev_replace->tgtdev;
5627 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5628 bbio->mirror_num = map->num_stripes + 1;
5631 if (dev_replace_is_ongoing)
5632 btrfs_dev_replace_unlock(dev_replace);
5633 free_extent_map(em);
5637 int btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
5638 u64 logical, u64 *length,
5639 struct btrfs_bio **bbio_ret, int mirror_num)
5641 return __btrfs_map_block(fs_info, rw, logical, length, bbio_ret,
5645 /* For Scrub/replace */
5646 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, int rw,
5647 u64 logical, u64 *length,
5648 struct btrfs_bio **bbio_ret, int mirror_num,
5651 return __btrfs_map_block(fs_info, rw, logical, length, bbio_ret,
5652 mirror_num, need_raid_map);
5655 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
5656 u64 chunk_start, u64 physical, u64 devid,
5657 u64 **logical, int *naddrs, int *stripe_len)
5659 struct extent_map_tree *em_tree = &map_tree->map_tree;
5660 struct extent_map *em;
5661 struct map_lookup *map;
5669 read_lock(&em_tree->lock);
5670 em = lookup_extent_mapping(em_tree, chunk_start, 1);
5671 read_unlock(&em_tree->lock);
5674 printk(KERN_ERR "BTRFS: couldn't find em for chunk %Lu\n",
5679 if (em->start != chunk_start) {
5680 printk(KERN_ERR "BTRFS: bad chunk start, em=%Lu, wanted=%Lu\n",
5681 em->start, chunk_start);
5682 free_extent_map(em);
5685 map = (struct map_lookup *)em->bdev;
5688 rmap_len = map->stripe_len;
5690 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5691 length = div_u64(length, map->num_stripes / map->sub_stripes);
5692 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5693 length = div_u64(length, map->num_stripes);
5694 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5695 length = div_u64(length, nr_data_stripes(map));
5696 rmap_len = map->stripe_len * nr_data_stripes(map);
5699 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
5700 BUG_ON(!buf); /* -ENOMEM */
5702 for (i = 0; i < map->num_stripes; i++) {
5703 if (devid && map->stripes[i].dev->devid != devid)
5705 if (map->stripes[i].physical > physical ||
5706 map->stripes[i].physical + length <= physical)
5709 stripe_nr = physical - map->stripes[i].physical;
5710 stripe_nr = div_u64(stripe_nr, map->stripe_len);
5712 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5713 stripe_nr = stripe_nr * map->num_stripes + i;
5714 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
5715 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5716 stripe_nr = stripe_nr * map->num_stripes + i;
5717 } /* else if RAID[56], multiply by nr_data_stripes().
5718 * Alternatively, just use rmap_len below instead of
5719 * map->stripe_len */
5721 bytenr = chunk_start + stripe_nr * rmap_len;
5722 WARN_ON(nr >= map->num_stripes);
5723 for (j = 0; j < nr; j++) {
5724 if (buf[j] == bytenr)
5728 WARN_ON(nr >= map->num_stripes);
5735 *stripe_len = rmap_len;
5737 free_extent_map(em);
5741 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
5743 bio->bi_private = bbio->private;
5744 bio->bi_end_io = bbio->end_io;
5747 btrfs_put_bbio(bbio);
5750 static void btrfs_end_bio(struct bio *bio)
5752 struct btrfs_bio *bbio = bio->bi_private;
5753 int is_orig_bio = 0;
5755 if (bio->bi_error) {
5756 atomic_inc(&bbio->error);
5757 if (bio->bi_error == -EIO || bio->bi_error == -EREMOTEIO) {
5758 unsigned int stripe_index =
5759 btrfs_io_bio(bio)->stripe_index;
5760 struct btrfs_device *dev;
5762 BUG_ON(stripe_index >= bbio->num_stripes);
5763 dev = bbio->stripes[stripe_index].dev;
5765 if (bio->bi_rw & WRITE)
5766 btrfs_dev_stat_inc(dev,
5767 BTRFS_DEV_STAT_WRITE_ERRS);
5769 btrfs_dev_stat_inc(dev,
5770 BTRFS_DEV_STAT_READ_ERRS);
5771 if ((bio->bi_rw & WRITE_FLUSH) == WRITE_FLUSH)
5772 btrfs_dev_stat_inc(dev,
5773 BTRFS_DEV_STAT_FLUSH_ERRS);
5774 btrfs_dev_stat_print_on_error(dev);
5779 if (bio == bbio->orig_bio)
5782 btrfs_bio_counter_dec(bbio->fs_info);
5784 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5787 bio = bbio->orig_bio;
5790 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5791 /* only send an error to the higher layers if it is
5792 * beyond the tolerance of the btrfs bio
5794 if (atomic_read(&bbio->error) > bbio->max_errors) {
5795 bio->bi_error = -EIO;
5798 * this bio is actually up to date, we didn't
5799 * go over the max number of errors
5804 btrfs_end_bbio(bbio, bio);
5805 } else if (!is_orig_bio) {
5811 * see run_scheduled_bios for a description of why bios are collected for
5814 * This will add one bio to the pending list for a device and make sure
5815 * the work struct is scheduled.
5817 static noinline void btrfs_schedule_bio(struct btrfs_root *root,
5818 struct btrfs_device *device,
5819 int rw, struct bio *bio)
5821 int should_queue = 1;
5822 struct btrfs_pending_bios *pending_bios;
5824 if (device->missing || !device->bdev) {
5829 /* don't bother with additional async steps for reads, right now */
5830 if (!(rw & REQ_WRITE)) {
5832 btrfsic_submit_bio(rw, bio);
5838 * nr_async_bios allows us to reliably return congestion to the
5839 * higher layers. Otherwise, the async bio makes it appear we have
5840 * made progress against dirty pages when we've really just put it
5841 * on a queue for later
5843 atomic_inc(&root->fs_info->nr_async_bios);
5844 WARN_ON(bio->bi_next);
5845 bio->bi_next = NULL;
5848 spin_lock(&device->io_lock);
5849 if (bio->bi_rw & REQ_SYNC)
5850 pending_bios = &device->pending_sync_bios;
5852 pending_bios = &device->pending_bios;
5854 if (pending_bios->tail)
5855 pending_bios->tail->bi_next = bio;
5857 pending_bios->tail = bio;
5858 if (!pending_bios->head)
5859 pending_bios->head = bio;
5860 if (device->running_pending)
5863 spin_unlock(&device->io_lock);
5866 btrfs_queue_work(root->fs_info->submit_workers,
5870 static void submit_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5871 struct bio *bio, u64 physical, int dev_nr,
5874 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
5876 bio->bi_private = bbio;
5877 btrfs_io_bio(bio)->stripe_index = dev_nr;
5878 bio->bi_end_io = btrfs_end_bio;
5879 bio->bi_iter.bi_sector = physical >> 9;
5882 struct rcu_string *name;
5885 name = rcu_dereference(dev->name);
5886 pr_debug("btrfs_map_bio: rw %d, sector=%llu, dev=%lu "
5887 "(%s id %llu), size=%u\n", rw,
5888 (u64)bio->bi_iter.bi_sector, (u_long)dev->bdev->bd_dev,
5889 name->str, dev->devid, bio->bi_iter.bi_size);
5893 bio->bi_bdev = dev->bdev;
5895 btrfs_bio_counter_inc_noblocked(root->fs_info);
5898 btrfs_schedule_bio(root, dev, rw, bio);
5900 btrfsic_submit_bio(rw, bio);
5903 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
5905 atomic_inc(&bbio->error);
5906 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5907 /* Shoud be the original bio. */
5908 WARN_ON(bio != bbio->orig_bio);
5910 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5911 bio->bi_iter.bi_sector = logical >> 9;
5912 bio->bi_error = -EIO;
5913 btrfs_end_bbio(bbio, bio);
5917 int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
5918 int mirror_num, int async_submit)
5920 struct btrfs_device *dev;
5921 struct bio *first_bio = bio;
5922 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
5928 struct btrfs_bio *bbio = NULL;
5930 length = bio->bi_iter.bi_size;
5931 map_length = length;
5933 btrfs_bio_counter_inc_blocked(root->fs_info);
5934 ret = __btrfs_map_block(root->fs_info, rw, logical, &map_length, &bbio,
5937 btrfs_bio_counter_dec(root->fs_info);
5941 total_devs = bbio->num_stripes;
5942 bbio->orig_bio = first_bio;
5943 bbio->private = first_bio->bi_private;
5944 bbio->end_io = first_bio->bi_end_io;
5945 bbio->fs_info = root->fs_info;
5946 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
5948 if (bbio->raid_map) {
5949 /* In this case, map_length has been set to the length of
5950 a single stripe; not the whole write */
5952 ret = raid56_parity_write(root, bio, bbio, map_length);
5954 ret = raid56_parity_recover(root, bio, bbio, map_length,
5958 btrfs_bio_counter_dec(root->fs_info);
5962 if (map_length < length) {
5963 btrfs_crit(root->fs_info, "mapping failed logical %llu bio len %llu len %llu",
5964 logical, length, map_length);
5968 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
5969 dev = bbio->stripes[dev_nr].dev;
5970 if (!dev || !dev->bdev || (rw & WRITE && !dev->writeable)) {
5971 bbio_error(bbio, first_bio, logical);
5975 if (dev_nr < total_devs - 1) {
5976 bio = btrfs_bio_clone(first_bio, GFP_NOFS);
5977 BUG_ON(!bio); /* -ENOMEM */
5981 submit_stripe_bio(root, bbio, bio,
5982 bbio->stripes[dev_nr].physical, dev_nr, rw,
5985 btrfs_bio_counter_dec(root->fs_info);
5989 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
5992 struct btrfs_device *device;
5993 struct btrfs_fs_devices *cur_devices;
5995 cur_devices = fs_info->fs_devices;
5996 while (cur_devices) {
5998 !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
5999 device = __find_device(&cur_devices->devices,
6004 cur_devices = cur_devices->seed;
6009 static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
6010 struct btrfs_fs_devices *fs_devices,
6011 u64 devid, u8 *dev_uuid)
6013 struct btrfs_device *device;
6015 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6019 list_add(&device->dev_list, &fs_devices->devices);
6020 device->fs_devices = fs_devices;
6021 fs_devices->num_devices++;
6023 device->missing = 1;
6024 fs_devices->missing_devices++;
6030 * btrfs_alloc_device - allocate struct btrfs_device
6031 * @fs_info: used only for generating a new devid, can be NULL if
6032 * devid is provided (i.e. @devid != NULL).
6033 * @devid: a pointer to devid for this device. If NULL a new devid
6035 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6038 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6039 * on error. Returned struct is not linked onto any lists and can be
6040 * destroyed with kfree() right away.
6042 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6046 struct btrfs_device *dev;
6049 if (WARN_ON(!devid && !fs_info))
6050 return ERR_PTR(-EINVAL);
6052 dev = __alloc_device();
6061 ret = find_next_devid(fs_info, &tmp);
6064 return ERR_PTR(ret);
6070 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6072 generate_random_uuid(dev->uuid);
6074 btrfs_init_work(&dev->work, btrfs_submit_helper,
6075 pending_bios_fn, NULL, NULL);
6080 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
6081 struct extent_buffer *leaf,
6082 struct btrfs_chunk *chunk)
6084 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
6085 struct map_lookup *map;
6086 struct extent_map *em;
6090 u8 uuid[BTRFS_UUID_SIZE];
6095 logical = key->offset;
6096 length = btrfs_chunk_length(leaf, chunk);
6098 read_lock(&map_tree->map_tree.lock);
6099 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6100 read_unlock(&map_tree->map_tree.lock);
6102 /* already mapped? */
6103 if (em && em->start <= logical && em->start + em->len > logical) {
6104 free_extent_map(em);
6107 free_extent_map(em);
6110 em = alloc_extent_map();
6113 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6114 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6116 free_extent_map(em);
6120 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6121 em->bdev = (struct block_device *)map;
6122 em->start = logical;
6125 em->block_start = 0;
6126 em->block_len = em->len;
6128 map->num_stripes = num_stripes;
6129 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6130 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6131 map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
6132 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6133 map->type = btrfs_chunk_type(leaf, chunk);
6134 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6135 for (i = 0; i < num_stripes; i++) {
6136 map->stripes[i].physical =
6137 btrfs_stripe_offset_nr(leaf, chunk, i);
6138 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6139 read_extent_buffer(leaf, uuid, (unsigned long)
6140 btrfs_stripe_dev_uuid_nr(chunk, i),
6142 map->stripes[i].dev = btrfs_find_device(root->fs_info, devid,
6144 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
6145 free_extent_map(em);
6148 if (!map->stripes[i].dev) {
6149 map->stripes[i].dev =
6150 add_missing_dev(root, root->fs_info->fs_devices,
6152 if (!map->stripes[i].dev) {
6153 free_extent_map(em);
6156 btrfs_warn(root->fs_info, "devid %llu uuid %pU is missing",
6159 map->stripes[i].dev->in_fs_metadata = 1;
6162 write_lock(&map_tree->map_tree.lock);
6163 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6164 write_unlock(&map_tree->map_tree.lock);
6165 BUG_ON(ret); /* Tree corruption */
6166 free_extent_map(em);
6171 static void fill_device_from_item(struct extent_buffer *leaf,
6172 struct btrfs_dev_item *dev_item,
6173 struct btrfs_device *device)
6177 device->devid = btrfs_device_id(leaf, dev_item);
6178 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6179 device->total_bytes = device->disk_total_bytes;
6180 device->commit_total_bytes = device->disk_total_bytes;
6181 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6182 device->commit_bytes_used = device->bytes_used;
6183 device->type = btrfs_device_type(leaf, dev_item);
6184 device->io_align = btrfs_device_io_align(leaf, dev_item);
6185 device->io_width = btrfs_device_io_width(leaf, dev_item);
6186 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6187 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6188 device->is_tgtdev_for_dev_replace = 0;
6190 ptr = btrfs_device_uuid(dev_item);
6191 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6194 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_root *root,
6197 struct btrfs_fs_devices *fs_devices;
6200 BUG_ON(!mutex_is_locked(&uuid_mutex));
6202 fs_devices = root->fs_info->fs_devices->seed;
6203 while (fs_devices) {
6204 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE))
6207 fs_devices = fs_devices->seed;
6210 fs_devices = find_fsid(fsid);
6212 if (!btrfs_test_opt(root, DEGRADED))
6213 return ERR_PTR(-ENOENT);
6215 fs_devices = alloc_fs_devices(fsid);
6216 if (IS_ERR(fs_devices))
6219 fs_devices->seeding = 1;
6220 fs_devices->opened = 1;
6224 fs_devices = clone_fs_devices(fs_devices);
6225 if (IS_ERR(fs_devices))
6228 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
6229 root->fs_info->bdev_holder);
6231 free_fs_devices(fs_devices);
6232 fs_devices = ERR_PTR(ret);
6236 if (!fs_devices->seeding) {
6237 __btrfs_close_devices(fs_devices);
6238 free_fs_devices(fs_devices);
6239 fs_devices = ERR_PTR(-EINVAL);
6243 fs_devices->seed = root->fs_info->fs_devices->seed;
6244 root->fs_info->fs_devices->seed = fs_devices;
6249 static int read_one_dev(struct btrfs_root *root,
6250 struct extent_buffer *leaf,
6251 struct btrfs_dev_item *dev_item)
6253 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
6254 struct btrfs_device *device;
6257 u8 fs_uuid[BTRFS_UUID_SIZE];
6258 u8 dev_uuid[BTRFS_UUID_SIZE];
6260 devid = btrfs_device_id(leaf, dev_item);
6261 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6263 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6266 if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
6267 fs_devices = open_seed_devices(root, fs_uuid);
6268 if (IS_ERR(fs_devices))
6269 return PTR_ERR(fs_devices);
6272 device = btrfs_find_device(root->fs_info, devid, dev_uuid, fs_uuid);
6274 if (!btrfs_test_opt(root, DEGRADED))
6277 device = add_missing_dev(root, fs_devices, devid, dev_uuid);
6280 btrfs_warn(root->fs_info, "devid %llu uuid %pU missing",
6283 if (!device->bdev && !btrfs_test_opt(root, DEGRADED))
6286 if(!device->bdev && !device->missing) {
6288 * this happens when a device that was properly setup
6289 * in the device info lists suddenly goes bad.
6290 * device->bdev is NULL, and so we have to set
6291 * device->missing to one here
6293 device->fs_devices->missing_devices++;
6294 device->missing = 1;
6297 /* Move the device to its own fs_devices */
6298 if (device->fs_devices != fs_devices) {
6299 ASSERT(device->missing);
6301 list_move(&device->dev_list, &fs_devices->devices);
6302 device->fs_devices->num_devices--;
6303 fs_devices->num_devices++;
6305 device->fs_devices->missing_devices--;
6306 fs_devices->missing_devices++;
6308 device->fs_devices = fs_devices;
6312 if (device->fs_devices != root->fs_info->fs_devices) {
6313 BUG_ON(device->writeable);
6314 if (device->generation !=
6315 btrfs_device_generation(leaf, dev_item))
6319 fill_device_from_item(leaf, dev_item, device);
6320 device->in_fs_metadata = 1;
6321 if (device->writeable && !device->is_tgtdev_for_dev_replace) {
6322 device->fs_devices->total_rw_bytes += device->total_bytes;
6323 spin_lock(&root->fs_info->free_chunk_lock);
6324 root->fs_info->free_chunk_space += device->total_bytes -
6326 spin_unlock(&root->fs_info->free_chunk_lock);
6332 int btrfs_read_sys_array(struct btrfs_root *root)
6334 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
6335 struct extent_buffer *sb;
6336 struct btrfs_disk_key *disk_key;
6337 struct btrfs_chunk *chunk;
6339 unsigned long sb_array_offset;
6345 struct btrfs_key key;
6347 ASSERT(BTRFS_SUPER_INFO_SIZE <= root->nodesize);
6349 * This will create extent buffer of nodesize, superblock size is
6350 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6351 * overallocate but we can keep it as-is, only the first page is used.
6353 sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET);
6356 btrfs_set_buffer_uptodate(sb);
6357 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6359 * The sb extent buffer is artifical and just used to read the system array.
6360 * btrfs_set_buffer_uptodate() call does not properly mark all it's
6361 * pages up-to-date when the page is larger: extent does not cover the
6362 * whole page and consequently check_page_uptodate does not find all
6363 * the page's extents up-to-date (the hole beyond sb),
6364 * write_extent_buffer then triggers a WARN_ON.
6366 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6367 * but sb spans only this function. Add an explicit SetPageUptodate call
6368 * to silence the warning eg. on PowerPC 64.
6370 if (PAGE_CACHE_SIZE > BTRFS_SUPER_INFO_SIZE)
6371 SetPageUptodate(sb->pages[0]);
6373 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6374 array_size = btrfs_super_sys_array_size(super_copy);
6376 array_ptr = super_copy->sys_chunk_array;
6377 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6380 while (cur_offset < array_size) {
6381 disk_key = (struct btrfs_disk_key *)array_ptr;
6382 len = sizeof(*disk_key);
6383 if (cur_offset + len > array_size)
6384 goto out_short_read;
6386 btrfs_disk_key_to_cpu(&key, disk_key);
6389 sb_array_offset += len;
6392 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6393 chunk = (struct btrfs_chunk *)sb_array_offset;
6395 * At least one btrfs_chunk with one stripe must be
6396 * present, exact stripe count check comes afterwards
6398 len = btrfs_chunk_item_size(1);
6399 if (cur_offset + len > array_size)
6400 goto out_short_read;
6402 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6403 len = btrfs_chunk_item_size(num_stripes);
6404 if (cur_offset + len > array_size)
6405 goto out_short_read;
6407 ret = read_one_chunk(root, &key, sb, chunk);
6415 sb_array_offset += len;
6418 free_extent_buffer(sb);
6422 printk(KERN_ERR "BTRFS: sys_array too short to read %u bytes at offset %u\n",
6424 free_extent_buffer(sb);
6428 int btrfs_read_chunk_tree(struct btrfs_root *root)
6430 struct btrfs_path *path;
6431 struct extent_buffer *leaf;
6432 struct btrfs_key key;
6433 struct btrfs_key found_key;
6437 root = root->fs_info->chunk_root;
6439 path = btrfs_alloc_path();
6443 mutex_lock(&uuid_mutex);
6447 * Read all device items, and then all the chunk items. All
6448 * device items are found before any chunk item (their object id
6449 * is smaller than the lowest possible object id for a chunk
6450 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6452 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6455 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6459 leaf = path->nodes[0];
6460 slot = path->slots[0];
6461 if (slot >= btrfs_header_nritems(leaf)) {
6462 ret = btrfs_next_leaf(root, path);
6469 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6470 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6471 struct btrfs_dev_item *dev_item;
6472 dev_item = btrfs_item_ptr(leaf, slot,
6473 struct btrfs_dev_item);
6474 ret = read_one_dev(root, leaf, dev_item);
6477 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6478 struct btrfs_chunk *chunk;
6479 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6480 ret = read_one_chunk(root, &found_key, leaf, chunk);
6488 unlock_chunks(root);
6489 mutex_unlock(&uuid_mutex);
6491 btrfs_free_path(path);
6495 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6497 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6498 struct btrfs_device *device;
6500 while (fs_devices) {
6501 mutex_lock(&fs_devices->device_list_mutex);
6502 list_for_each_entry(device, &fs_devices->devices, dev_list)
6503 device->dev_root = fs_info->dev_root;
6504 mutex_unlock(&fs_devices->device_list_mutex);
6506 fs_devices = fs_devices->seed;
6510 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
6514 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6515 btrfs_dev_stat_reset(dev, i);
6518 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
6520 struct btrfs_key key;
6521 struct btrfs_key found_key;
6522 struct btrfs_root *dev_root = fs_info->dev_root;
6523 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6524 struct extent_buffer *eb;
6527 struct btrfs_device *device;
6528 struct btrfs_path *path = NULL;
6531 path = btrfs_alloc_path();
6537 mutex_lock(&fs_devices->device_list_mutex);
6538 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6540 struct btrfs_dev_stats_item *ptr;
6543 key.type = BTRFS_DEV_STATS_KEY;
6544 key.offset = device->devid;
6545 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
6547 __btrfs_reset_dev_stats(device);
6548 device->dev_stats_valid = 1;
6549 btrfs_release_path(path);
6552 slot = path->slots[0];
6553 eb = path->nodes[0];
6554 btrfs_item_key_to_cpu(eb, &found_key, slot);
6555 item_size = btrfs_item_size_nr(eb, slot);
6557 ptr = btrfs_item_ptr(eb, slot,
6558 struct btrfs_dev_stats_item);
6560 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6561 if (item_size >= (1 + i) * sizeof(__le64))
6562 btrfs_dev_stat_set(device, i,
6563 btrfs_dev_stats_value(eb, ptr, i));
6565 btrfs_dev_stat_reset(device, i);
6568 device->dev_stats_valid = 1;
6569 btrfs_dev_stat_print_on_load(device);
6570 btrfs_release_path(path);
6572 mutex_unlock(&fs_devices->device_list_mutex);
6575 btrfs_free_path(path);
6576 return ret < 0 ? ret : 0;
6579 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
6580 struct btrfs_root *dev_root,
6581 struct btrfs_device *device)
6583 struct btrfs_path *path;
6584 struct btrfs_key key;
6585 struct extent_buffer *eb;
6586 struct btrfs_dev_stats_item *ptr;
6591 key.type = BTRFS_DEV_STATS_KEY;
6592 key.offset = device->devid;
6594 path = btrfs_alloc_path();
6596 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
6598 btrfs_warn_in_rcu(dev_root->fs_info,
6599 "error %d while searching for dev_stats item for device %s",
6600 ret, rcu_str_deref(device->name));
6605 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
6606 /* need to delete old one and insert a new one */
6607 ret = btrfs_del_item(trans, dev_root, path);
6609 btrfs_warn_in_rcu(dev_root->fs_info,
6610 "delete too small dev_stats item for device %s failed %d",
6611 rcu_str_deref(device->name), ret);
6618 /* need to insert a new item */
6619 btrfs_release_path(path);
6620 ret = btrfs_insert_empty_item(trans, dev_root, path,
6621 &key, sizeof(*ptr));
6623 btrfs_warn_in_rcu(dev_root->fs_info,
6624 "insert dev_stats item for device %s failed %d",
6625 rcu_str_deref(device->name), ret);
6630 eb = path->nodes[0];
6631 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
6632 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6633 btrfs_set_dev_stats_value(eb, ptr, i,
6634 btrfs_dev_stat_read(device, i));
6635 btrfs_mark_buffer_dirty(eb);
6638 btrfs_free_path(path);
6643 * called from commit_transaction. Writes all changed device stats to disk.
6645 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
6646 struct btrfs_fs_info *fs_info)
6648 struct btrfs_root *dev_root = fs_info->dev_root;
6649 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6650 struct btrfs_device *device;
6654 mutex_lock(&fs_devices->device_list_mutex);
6655 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6656 if (!device->dev_stats_valid || !btrfs_dev_stats_dirty(device))
6659 stats_cnt = atomic_read(&device->dev_stats_ccnt);
6660 ret = update_dev_stat_item(trans, dev_root, device);
6662 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
6664 mutex_unlock(&fs_devices->device_list_mutex);
6669 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
6671 btrfs_dev_stat_inc(dev, index);
6672 btrfs_dev_stat_print_on_error(dev);
6675 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
6677 if (!dev->dev_stats_valid)
6679 btrfs_err_rl_in_rcu(dev->dev_root->fs_info,
6680 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
6681 rcu_str_deref(dev->name),
6682 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6683 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6684 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6685 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6686 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6689 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
6693 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6694 if (btrfs_dev_stat_read(dev, i) != 0)
6696 if (i == BTRFS_DEV_STAT_VALUES_MAX)
6697 return; /* all values == 0, suppress message */
6699 btrfs_info_in_rcu(dev->dev_root->fs_info,
6700 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
6701 rcu_str_deref(dev->name),
6702 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6703 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6704 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6705 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6706 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6709 int btrfs_get_dev_stats(struct btrfs_root *root,
6710 struct btrfs_ioctl_get_dev_stats *stats)
6712 struct btrfs_device *dev;
6713 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
6716 mutex_lock(&fs_devices->device_list_mutex);
6717 dev = btrfs_find_device(root->fs_info, stats->devid, NULL, NULL);
6718 mutex_unlock(&fs_devices->device_list_mutex);
6721 btrfs_warn(root->fs_info, "get dev_stats failed, device not found");
6723 } else if (!dev->dev_stats_valid) {
6724 btrfs_warn(root->fs_info, "get dev_stats failed, not yet valid");
6726 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
6727 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6728 if (stats->nr_items > i)
6730 btrfs_dev_stat_read_and_reset(dev, i);
6732 btrfs_dev_stat_reset(dev, i);
6735 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6736 if (stats->nr_items > i)
6737 stats->values[i] = btrfs_dev_stat_read(dev, i);
6739 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
6740 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
6744 int btrfs_scratch_superblock(struct btrfs_device *device)
6746 struct buffer_head *bh;
6747 struct btrfs_super_block *disk_super;
6749 bh = btrfs_read_dev_super(device->bdev);
6752 disk_super = (struct btrfs_super_block *)bh->b_data;
6754 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
6755 set_buffer_dirty(bh);
6756 sync_dirty_buffer(bh);
6763 * Update the size of all devices, which is used for writing out the
6766 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
6768 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6769 struct btrfs_device *curr, *next;
6771 if (list_empty(&fs_devices->resized_devices))
6774 mutex_lock(&fs_devices->device_list_mutex);
6775 lock_chunks(fs_info->dev_root);
6776 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
6778 list_del_init(&curr->resized_list);
6779 curr->commit_total_bytes = curr->disk_total_bytes;
6781 unlock_chunks(fs_info->dev_root);
6782 mutex_unlock(&fs_devices->device_list_mutex);
6785 /* Must be invoked during the transaction commit */
6786 void btrfs_update_commit_device_bytes_used(struct btrfs_root *root,
6787 struct btrfs_transaction *transaction)
6789 struct extent_map *em;
6790 struct map_lookup *map;
6791 struct btrfs_device *dev;
6794 if (list_empty(&transaction->pending_chunks))
6797 /* In order to kick the device replace finish process */
6799 list_for_each_entry(em, &transaction->pending_chunks, list) {
6800 map = (struct map_lookup *)em->bdev;
6802 for (i = 0; i < map->num_stripes; i++) {
6803 dev = map->stripes[i].dev;
6804 dev->commit_bytes_used = dev->bytes_used;
6807 unlock_chunks(root);
6810 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
6812 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6813 while (fs_devices) {
6814 fs_devices->fs_info = fs_info;
6815 fs_devices = fs_devices->seed;
6819 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
6821 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6822 while (fs_devices) {
6823 fs_devices->fs_info = NULL;
6824 fs_devices = fs_devices->seed;