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 static DEFINE_MUTEX(uuid_mutex);
54 static LIST_HEAD(fs_uuids);
56 static void lock_chunks(struct btrfs_root *root)
58 mutex_lock(&root->fs_info->chunk_mutex);
61 static void unlock_chunks(struct btrfs_root *root)
63 mutex_unlock(&root->fs_info->chunk_mutex);
66 static struct btrfs_fs_devices *__alloc_fs_devices(void)
68 struct btrfs_fs_devices *fs_devs;
70 fs_devs = kzalloc(sizeof(*fs_devs), GFP_NOFS);
72 return ERR_PTR(-ENOMEM);
74 mutex_init(&fs_devs->device_list_mutex);
76 INIT_LIST_HEAD(&fs_devs->devices);
77 INIT_LIST_HEAD(&fs_devs->alloc_list);
78 INIT_LIST_HEAD(&fs_devs->list);
84 * alloc_fs_devices - allocate struct btrfs_fs_devices
85 * @fsid: a pointer to UUID for this FS. If NULL a new UUID is
88 * Return: a pointer to a new &struct btrfs_fs_devices on success;
89 * ERR_PTR() on error. Returned struct is not linked onto any lists and
90 * can be destroyed with kfree() right away.
92 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
94 struct btrfs_fs_devices *fs_devs;
96 fs_devs = __alloc_fs_devices();
101 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
103 generate_random_uuid(fs_devs->fsid);
108 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
110 struct btrfs_device *device;
111 WARN_ON(fs_devices->opened);
112 while (!list_empty(&fs_devices->devices)) {
113 device = list_entry(fs_devices->devices.next,
114 struct btrfs_device, dev_list);
115 list_del(&device->dev_list);
116 rcu_string_free(device->name);
122 static void btrfs_kobject_uevent(struct block_device *bdev,
123 enum kobject_action action)
127 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
129 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
131 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
132 &disk_to_dev(bdev->bd_disk)->kobj);
135 void btrfs_cleanup_fs_uuids(void)
137 struct btrfs_fs_devices *fs_devices;
139 while (!list_empty(&fs_uuids)) {
140 fs_devices = list_entry(fs_uuids.next,
141 struct btrfs_fs_devices, list);
142 list_del(&fs_devices->list);
143 free_fs_devices(fs_devices);
147 static struct btrfs_device *__alloc_device(void)
149 struct btrfs_device *dev;
151 dev = kzalloc(sizeof(*dev), GFP_NOFS);
153 return ERR_PTR(-ENOMEM);
155 INIT_LIST_HEAD(&dev->dev_list);
156 INIT_LIST_HEAD(&dev->dev_alloc_list);
158 spin_lock_init(&dev->io_lock);
160 spin_lock_init(&dev->reada_lock);
161 atomic_set(&dev->reada_in_flight, 0);
162 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_WAIT);
163 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_WAIT);
168 static noinline struct btrfs_device *__find_device(struct list_head *head,
171 struct btrfs_device *dev;
173 list_for_each_entry(dev, head, dev_list) {
174 if (dev->devid == devid &&
175 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
182 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
184 struct btrfs_fs_devices *fs_devices;
186 list_for_each_entry(fs_devices, &fs_uuids, list) {
187 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
194 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
195 int flush, struct block_device **bdev,
196 struct buffer_head **bh)
200 *bdev = blkdev_get_by_path(device_path, flags, holder);
203 ret = PTR_ERR(*bdev);
204 printk(KERN_INFO "BTRFS: open %s failed\n", device_path);
209 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
210 ret = set_blocksize(*bdev, 4096);
212 blkdev_put(*bdev, flags);
215 invalidate_bdev(*bdev);
216 *bh = btrfs_read_dev_super(*bdev);
219 blkdev_put(*bdev, flags);
231 static void requeue_list(struct btrfs_pending_bios *pending_bios,
232 struct bio *head, struct bio *tail)
235 struct bio *old_head;
237 old_head = pending_bios->head;
238 pending_bios->head = head;
239 if (pending_bios->tail)
240 tail->bi_next = old_head;
242 pending_bios->tail = tail;
246 * we try to collect pending bios for a device so we don't get a large
247 * number of procs sending bios down to the same device. This greatly
248 * improves the schedulers ability to collect and merge the bios.
250 * But, it also turns into a long list of bios to process and that is sure
251 * to eventually make the worker thread block. The solution here is to
252 * make some progress and then put this work struct back at the end of
253 * the list if the block device is congested. This way, multiple devices
254 * can make progress from a single worker thread.
256 static noinline void run_scheduled_bios(struct btrfs_device *device)
259 struct backing_dev_info *bdi;
260 struct btrfs_fs_info *fs_info;
261 struct btrfs_pending_bios *pending_bios;
265 unsigned long num_run;
266 unsigned long batch_run = 0;
268 unsigned long last_waited = 0;
270 int sync_pending = 0;
271 struct blk_plug plug;
274 * this function runs all the bios we've collected for
275 * a particular device. We don't want to wander off to
276 * another device without first sending all of these down.
277 * So, setup a plug here and finish it off before we return
279 blk_start_plug(&plug);
281 bdi = blk_get_backing_dev_info(device->bdev);
282 fs_info = device->dev_root->fs_info;
283 limit = btrfs_async_submit_limit(fs_info);
284 limit = limit * 2 / 3;
287 spin_lock(&device->io_lock);
292 /* take all the bios off the list at once and process them
293 * later on (without the lock held). But, remember the
294 * tail and other pointers so the bios can be properly reinserted
295 * into the list if we hit congestion
297 if (!force_reg && device->pending_sync_bios.head) {
298 pending_bios = &device->pending_sync_bios;
301 pending_bios = &device->pending_bios;
305 pending = pending_bios->head;
306 tail = pending_bios->tail;
307 WARN_ON(pending && !tail);
310 * if pending was null this time around, no bios need processing
311 * at all and we can stop. Otherwise it'll loop back up again
312 * and do an additional check so no bios are missed.
314 * device->running_pending is used to synchronize with the
317 if (device->pending_sync_bios.head == NULL &&
318 device->pending_bios.head == NULL) {
320 device->running_pending = 0;
323 device->running_pending = 1;
326 pending_bios->head = NULL;
327 pending_bios->tail = NULL;
329 spin_unlock(&device->io_lock);
334 /* we want to work on both lists, but do more bios on the
335 * sync list than the regular list
338 pending_bios != &device->pending_sync_bios &&
339 device->pending_sync_bios.head) ||
340 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
341 device->pending_bios.head)) {
342 spin_lock(&device->io_lock);
343 requeue_list(pending_bios, pending, tail);
348 pending = pending->bi_next;
351 if (atomic_dec_return(&fs_info->nr_async_bios) < limit &&
352 waitqueue_active(&fs_info->async_submit_wait))
353 wake_up(&fs_info->async_submit_wait);
355 BUG_ON(atomic_read(&cur->bi_cnt) == 0);
358 * if we're doing the sync list, record that our
359 * plug has some sync requests on it
361 * If we're doing the regular list and there are
362 * sync requests sitting around, unplug before
365 if (pending_bios == &device->pending_sync_bios) {
367 } else if (sync_pending) {
368 blk_finish_plug(&plug);
369 blk_start_plug(&plug);
373 btrfsic_submit_bio(cur->bi_rw, cur);
380 * we made progress, there is more work to do and the bdi
381 * is now congested. Back off and let other work structs
384 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
385 fs_info->fs_devices->open_devices > 1) {
386 struct io_context *ioc;
388 ioc = current->io_context;
391 * the main goal here is that we don't want to
392 * block if we're going to be able to submit
393 * more requests without blocking.
395 * This code does two great things, it pokes into
396 * the elevator code from a filesystem _and_
397 * it makes assumptions about how batching works.
399 if (ioc && ioc->nr_batch_requests > 0 &&
400 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
402 ioc->last_waited == last_waited)) {
404 * we want to go through our batch of
405 * requests and stop. So, we copy out
406 * the ioc->last_waited time and test
407 * against it before looping
409 last_waited = ioc->last_waited;
414 spin_lock(&device->io_lock);
415 requeue_list(pending_bios, pending, tail);
416 device->running_pending = 1;
418 spin_unlock(&device->io_lock);
419 btrfs_queue_work(fs_info->submit_workers,
423 /* unplug every 64 requests just for good measure */
424 if (batch_run % 64 == 0) {
425 blk_finish_plug(&plug);
426 blk_start_plug(&plug);
435 spin_lock(&device->io_lock);
436 if (device->pending_bios.head || device->pending_sync_bios.head)
438 spin_unlock(&device->io_lock);
441 blk_finish_plug(&plug);
444 static void pending_bios_fn(struct btrfs_work *work)
446 struct btrfs_device *device;
448 device = container_of(work, struct btrfs_device, work);
449 run_scheduled_bios(device);
453 * Add new device to list of registered devices
456 * 1 - first time device is seen
457 * 0 - device already known
460 static noinline int device_list_add(const char *path,
461 struct btrfs_super_block *disk_super,
462 u64 devid, struct btrfs_fs_devices **fs_devices_ret)
464 struct btrfs_device *device;
465 struct btrfs_fs_devices *fs_devices;
466 struct rcu_string *name;
468 u64 found_transid = btrfs_super_generation(disk_super);
470 fs_devices = find_fsid(disk_super->fsid);
472 fs_devices = alloc_fs_devices(disk_super->fsid);
473 if (IS_ERR(fs_devices))
474 return PTR_ERR(fs_devices);
476 list_add(&fs_devices->list, &fs_uuids);
477 fs_devices->latest_devid = devid;
478 fs_devices->latest_trans = found_transid;
482 device = __find_device(&fs_devices->devices, devid,
483 disk_super->dev_item.uuid);
486 if (fs_devices->opened)
489 device = btrfs_alloc_device(NULL, &devid,
490 disk_super->dev_item.uuid);
491 if (IS_ERR(device)) {
492 /* we can safely leave the fs_devices entry around */
493 return PTR_ERR(device);
496 name = rcu_string_strdup(path, GFP_NOFS);
501 rcu_assign_pointer(device->name, name);
503 mutex_lock(&fs_devices->device_list_mutex);
504 list_add_rcu(&device->dev_list, &fs_devices->devices);
505 fs_devices->num_devices++;
506 mutex_unlock(&fs_devices->device_list_mutex);
509 device->fs_devices = fs_devices;
510 } else if (!device->name || strcmp(device->name->str, path)) {
512 * When FS is already mounted.
513 * 1. If you are here and if the device->name is NULL that
514 * means this device was missing at time of FS mount.
515 * 2. If you are here and if the device->name is different
516 * from 'path' that means either
517 * a. The same device disappeared and reappeared with
519 * b. The missing-disk-which-was-replaced, has
522 * We must allow 1 and 2a above. But 2b would be a spurious
525 * Further in case of 1 and 2a above, the disk at 'path'
526 * would have missed some transaction when it was away and
527 * in case of 2a the stale bdev has to be updated as well.
528 * 2b must not be allowed at all time.
532 * For now, we do allow update to btrfs_fs_device through the
533 * btrfs dev scan cli after FS has been mounted. We're still
534 * tracking a problem where systems fail mount by subvolume id
535 * when we reject replacement on a mounted FS.
537 if (!fs_devices->opened && found_transid < device->generation) {
539 * That is if the FS is _not_ mounted and if you
540 * are here, that means there is more than one
541 * disk with same uuid and devid.We keep the one
542 * with larger generation number or the last-in if
543 * generation are equal.
548 name = rcu_string_strdup(path, GFP_NOFS);
551 rcu_string_free(device->name);
552 rcu_assign_pointer(device->name, name);
553 if (device->missing) {
554 fs_devices->missing_devices--;
560 * Unmount does not free the btrfs_device struct but would zero
561 * generation along with most of the other members. So just update
562 * it back. We need it to pick the disk with largest generation
565 if (!fs_devices->opened)
566 device->generation = found_transid;
568 if (found_transid > fs_devices->latest_trans) {
569 fs_devices->latest_devid = devid;
570 fs_devices->latest_trans = found_transid;
572 *fs_devices_ret = fs_devices;
577 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
579 struct btrfs_fs_devices *fs_devices;
580 struct btrfs_device *device;
581 struct btrfs_device *orig_dev;
583 fs_devices = alloc_fs_devices(orig->fsid);
584 if (IS_ERR(fs_devices))
587 fs_devices->latest_devid = orig->latest_devid;
588 fs_devices->latest_trans = orig->latest_trans;
589 fs_devices->total_devices = orig->total_devices;
591 /* We have held the volume lock, it is safe to get the devices. */
592 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
593 struct rcu_string *name;
595 device = btrfs_alloc_device(NULL, &orig_dev->devid,
601 * This is ok to do without rcu read locked because we hold the
602 * uuid mutex so nothing we touch in here is going to disappear.
604 if (orig_dev->name) {
605 name = rcu_string_strdup(orig_dev->name->str, GFP_NOFS);
610 rcu_assign_pointer(device->name, name);
613 list_add(&device->dev_list, &fs_devices->devices);
614 device->fs_devices = fs_devices;
615 fs_devices->num_devices++;
619 free_fs_devices(fs_devices);
620 return ERR_PTR(-ENOMEM);
623 void btrfs_close_extra_devices(struct btrfs_fs_info *fs_info,
624 struct btrfs_fs_devices *fs_devices, int step)
626 struct btrfs_device *device, *next;
628 struct block_device *latest_bdev = NULL;
629 u64 latest_devid = 0;
630 u64 latest_transid = 0;
632 mutex_lock(&uuid_mutex);
634 /* This is the initialized path, it is safe to release the devices. */
635 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
636 if (device->in_fs_metadata) {
637 if (!device->is_tgtdev_for_dev_replace &&
639 device->generation > latest_transid)) {
640 latest_devid = device->devid;
641 latest_transid = device->generation;
642 latest_bdev = device->bdev;
647 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
649 * In the first step, keep the device which has
650 * the correct fsid and the devid that is used
651 * for the dev_replace procedure.
652 * In the second step, the dev_replace state is
653 * read from the device tree and it is known
654 * whether the procedure is really active or
655 * not, which means whether this device is
656 * used or whether it should be removed.
658 if (step == 0 || device->is_tgtdev_for_dev_replace) {
663 blkdev_put(device->bdev, device->mode);
665 fs_devices->open_devices--;
667 if (device->writeable) {
668 list_del_init(&device->dev_alloc_list);
669 device->writeable = 0;
670 if (!device->is_tgtdev_for_dev_replace)
671 fs_devices->rw_devices--;
673 list_del_init(&device->dev_list);
674 fs_devices->num_devices--;
675 rcu_string_free(device->name);
679 if (fs_devices->seed) {
680 fs_devices = fs_devices->seed;
684 fs_devices->latest_bdev = latest_bdev;
685 fs_devices->latest_devid = latest_devid;
686 fs_devices->latest_trans = latest_transid;
688 mutex_unlock(&uuid_mutex);
691 static void __free_device(struct work_struct *work)
693 struct btrfs_device *device;
695 device = container_of(work, struct btrfs_device, rcu_work);
698 blkdev_put(device->bdev, device->mode);
700 rcu_string_free(device->name);
704 static void free_device(struct rcu_head *head)
706 struct btrfs_device *device;
708 device = container_of(head, struct btrfs_device, rcu);
710 INIT_WORK(&device->rcu_work, __free_device);
711 schedule_work(&device->rcu_work);
714 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
716 struct btrfs_device *device;
718 if (--fs_devices->opened > 0)
721 mutex_lock(&fs_devices->device_list_mutex);
722 list_for_each_entry(device, &fs_devices->devices, dev_list) {
723 struct btrfs_device *new_device;
724 struct rcu_string *name;
727 fs_devices->open_devices--;
729 if (device->writeable &&
730 device->devid != BTRFS_DEV_REPLACE_DEVID) {
731 list_del_init(&device->dev_alloc_list);
732 fs_devices->rw_devices--;
735 if (device->can_discard)
736 fs_devices->num_can_discard--;
738 fs_devices->missing_devices--;
740 new_device = btrfs_alloc_device(NULL, &device->devid,
742 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
744 /* Safe because we are under uuid_mutex */
746 name = rcu_string_strdup(device->name->str, GFP_NOFS);
747 BUG_ON(!name); /* -ENOMEM */
748 rcu_assign_pointer(new_device->name, name);
751 list_replace_rcu(&device->dev_list, &new_device->dev_list);
752 new_device->fs_devices = device->fs_devices;
754 call_rcu(&device->rcu, free_device);
756 mutex_unlock(&fs_devices->device_list_mutex);
758 WARN_ON(fs_devices->open_devices);
759 WARN_ON(fs_devices->rw_devices);
760 fs_devices->opened = 0;
761 fs_devices->seeding = 0;
766 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
768 struct btrfs_fs_devices *seed_devices = NULL;
771 mutex_lock(&uuid_mutex);
772 ret = __btrfs_close_devices(fs_devices);
773 if (!fs_devices->opened) {
774 seed_devices = fs_devices->seed;
775 fs_devices->seed = NULL;
777 mutex_unlock(&uuid_mutex);
779 while (seed_devices) {
780 fs_devices = seed_devices;
781 seed_devices = fs_devices->seed;
782 __btrfs_close_devices(fs_devices);
783 free_fs_devices(fs_devices);
786 * Wait for rcu kworkers under __btrfs_close_devices
787 * to finish all blkdev_puts so device is really
788 * free when umount is done.
794 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
795 fmode_t flags, void *holder)
797 struct request_queue *q;
798 struct block_device *bdev;
799 struct list_head *head = &fs_devices->devices;
800 struct btrfs_device *device;
801 struct block_device *latest_bdev = NULL;
802 struct buffer_head *bh;
803 struct btrfs_super_block *disk_super;
804 u64 latest_devid = 0;
805 u64 latest_transid = 0;
812 list_for_each_entry(device, head, dev_list) {
818 /* Just open everything we can; ignore failures here */
819 if (btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
823 disk_super = (struct btrfs_super_block *)bh->b_data;
824 devid = btrfs_stack_device_id(&disk_super->dev_item);
825 if (devid != device->devid)
828 if (memcmp(device->uuid, disk_super->dev_item.uuid,
832 device->generation = btrfs_super_generation(disk_super);
833 if (!latest_transid || device->generation > latest_transid) {
834 latest_devid = devid;
835 latest_transid = device->generation;
839 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
840 device->writeable = 0;
842 device->writeable = !bdev_read_only(bdev);
846 q = bdev_get_queue(bdev);
847 if (blk_queue_discard(q)) {
848 device->can_discard = 1;
849 fs_devices->num_can_discard++;
853 device->in_fs_metadata = 0;
854 device->mode = flags;
856 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
857 fs_devices->rotating = 1;
859 fs_devices->open_devices++;
860 if (device->writeable &&
861 device->devid != BTRFS_DEV_REPLACE_DEVID) {
862 fs_devices->rw_devices++;
863 list_add(&device->dev_alloc_list,
864 &fs_devices->alloc_list);
871 blkdev_put(bdev, flags);
874 if (fs_devices->open_devices == 0) {
878 fs_devices->seeding = seeding;
879 fs_devices->opened = 1;
880 fs_devices->latest_bdev = latest_bdev;
881 fs_devices->latest_devid = latest_devid;
882 fs_devices->latest_trans = latest_transid;
883 fs_devices->total_rw_bytes = 0;
888 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
889 fmode_t flags, void *holder)
893 mutex_lock(&uuid_mutex);
894 if (fs_devices->opened) {
895 fs_devices->opened++;
898 ret = __btrfs_open_devices(fs_devices, flags, holder);
900 mutex_unlock(&uuid_mutex);
905 * Look for a btrfs signature on a device. This may be called out of the mount path
906 * and we are not allowed to call set_blocksize during the scan. The superblock
907 * is read via pagecache
909 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
910 struct btrfs_fs_devices **fs_devices_ret)
912 struct btrfs_super_block *disk_super;
913 struct block_device *bdev;
924 * we would like to check all the supers, but that would make
925 * a btrfs mount succeed after a mkfs from a different FS.
926 * So, we need to add a special mount option to scan for
927 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
929 bytenr = btrfs_sb_offset(0);
931 mutex_lock(&uuid_mutex);
933 bdev = blkdev_get_by_path(path, flags, holder);
940 /* make sure our super fits in the device */
941 if (bytenr + PAGE_CACHE_SIZE >= i_size_read(bdev->bd_inode))
944 /* make sure our super fits in the page */
945 if (sizeof(*disk_super) > PAGE_CACHE_SIZE)
948 /* make sure our super doesn't straddle pages on disk */
949 index = bytenr >> PAGE_CACHE_SHIFT;
950 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_CACHE_SHIFT != index)
953 /* pull in the page with our super */
954 page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
957 if (IS_ERR_OR_NULL(page))
962 /* align our pointer to the offset of the super block */
963 disk_super = p + (bytenr & ~PAGE_CACHE_MASK);
965 if (btrfs_super_bytenr(disk_super) != bytenr ||
966 btrfs_super_magic(disk_super) != BTRFS_MAGIC)
969 devid = btrfs_stack_device_id(&disk_super->dev_item);
970 transid = btrfs_super_generation(disk_super);
971 total_devices = btrfs_super_num_devices(disk_super);
973 ret = device_list_add(path, disk_super, devid, fs_devices_ret);
975 if (disk_super->label[0]) {
976 if (disk_super->label[BTRFS_LABEL_SIZE - 1])
977 disk_super->label[BTRFS_LABEL_SIZE - 1] = '\0';
978 printk(KERN_INFO "BTRFS: device label %s ", disk_super->label);
980 printk(KERN_INFO "BTRFS: device fsid %pU ", disk_super->fsid);
983 printk(KERN_CONT "devid %llu transid %llu %s\n", devid, transid, path);
986 if (!ret && fs_devices_ret)
987 (*fs_devices_ret)->total_devices = total_devices;
991 page_cache_release(page);
994 blkdev_put(bdev, flags);
996 mutex_unlock(&uuid_mutex);
1000 /* helper to account the used device space in the range */
1001 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1002 u64 end, u64 *length)
1004 struct btrfs_key key;
1005 struct btrfs_root *root = device->dev_root;
1006 struct btrfs_dev_extent *dev_extent;
1007 struct btrfs_path *path;
1011 struct extent_buffer *l;
1015 if (start >= device->total_bytes || device->is_tgtdev_for_dev_replace)
1018 path = btrfs_alloc_path();
1023 key.objectid = device->devid;
1025 key.type = BTRFS_DEV_EXTENT_KEY;
1027 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1031 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1038 slot = path->slots[0];
1039 if (slot >= btrfs_header_nritems(l)) {
1040 ret = btrfs_next_leaf(root, path);
1048 btrfs_item_key_to_cpu(l, &key, slot);
1050 if (key.objectid < device->devid)
1053 if (key.objectid > device->devid)
1056 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
1059 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1060 extent_end = key.offset + btrfs_dev_extent_length(l,
1062 if (key.offset <= start && extent_end > end) {
1063 *length = end - start + 1;
1065 } else if (key.offset <= start && extent_end > start)
1066 *length += extent_end - start;
1067 else if (key.offset > start && extent_end <= end)
1068 *length += extent_end - key.offset;
1069 else if (key.offset > start && key.offset <= end) {
1070 *length += end - key.offset + 1;
1072 } else if (key.offset > end)
1080 btrfs_free_path(path);
1084 static int contains_pending_extent(struct btrfs_trans_handle *trans,
1085 struct btrfs_device *device,
1086 u64 *start, u64 len)
1088 struct extent_map *em;
1091 list_for_each_entry(em, &trans->transaction->pending_chunks, list) {
1092 struct map_lookup *map;
1095 map = (struct map_lookup *)em->bdev;
1096 for (i = 0; i < map->num_stripes; i++) {
1097 if (map->stripes[i].dev != device)
1099 if (map->stripes[i].physical >= *start + len ||
1100 map->stripes[i].physical + em->orig_block_len <=
1103 *start = map->stripes[i].physical +
1114 * find_free_dev_extent - find free space in the specified device
1115 * @device: the device which we search the free space in
1116 * @num_bytes: the size of the free space that we need
1117 * @start: store the start of the free space.
1118 * @len: the size of the free space. that we find, or the size of the max
1119 * free space if we don't find suitable free space
1121 * this uses a pretty simple search, the expectation is that it is
1122 * called very infrequently and that a given device has a small number
1125 * @start is used to store the start of the free space if we find. But if we
1126 * don't find suitable free space, it will be used to store the start position
1127 * of the max free space.
1129 * @len is used to store the size of the free space that we find.
1130 * But if we don't find suitable free space, it is used to store the size of
1131 * the max free space.
1133 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1134 struct btrfs_device *device, u64 num_bytes,
1135 u64 *start, u64 *len)
1137 struct btrfs_key key;
1138 struct btrfs_root *root = device->dev_root;
1139 struct btrfs_dev_extent *dev_extent;
1140 struct btrfs_path *path;
1146 u64 search_end = device->total_bytes;
1149 struct extent_buffer *l;
1151 /* FIXME use last free of some kind */
1153 /* we don't want to overwrite the superblock on the drive,
1154 * so we make sure to start at an offset of at least 1MB
1156 search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
1158 path = btrfs_alloc_path();
1162 max_hole_start = search_start;
1166 if (search_start >= search_end || device->is_tgtdev_for_dev_replace) {
1172 path->search_commit_root = 1;
1173 path->skip_locking = 1;
1175 key.objectid = device->devid;
1176 key.offset = search_start;
1177 key.type = BTRFS_DEV_EXTENT_KEY;
1179 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1183 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1190 slot = path->slots[0];
1191 if (slot >= btrfs_header_nritems(l)) {
1192 ret = btrfs_next_leaf(root, path);
1200 btrfs_item_key_to_cpu(l, &key, slot);
1202 if (key.objectid < device->devid)
1205 if (key.objectid > device->devid)
1208 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
1211 if (key.offset > search_start) {
1212 hole_size = key.offset - search_start;
1215 * Have to check before we set max_hole_start, otherwise
1216 * we could end up sending back this offset anyway.
1218 if (contains_pending_extent(trans, device,
1223 if (hole_size > max_hole_size) {
1224 max_hole_start = search_start;
1225 max_hole_size = hole_size;
1229 * If this free space is greater than which we need,
1230 * it must be the max free space that we have found
1231 * until now, so max_hole_start must point to the start
1232 * of this free space and the length of this free space
1233 * is stored in max_hole_size. Thus, we return
1234 * max_hole_start and max_hole_size and go back to the
1237 if (hole_size >= num_bytes) {
1243 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1244 extent_end = key.offset + btrfs_dev_extent_length(l,
1246 if (extent_end > search_start)
1247 search_start = extent_end;
1254 * At this point, search_start should be the end of
1255 * allocated dev extents, and when shrinking the device,
1256 * search_end may be smaller than search_start.
1258 if (search_end > search_start)
1259 hole_size = search_end - search_start;
1261 if (hole_size > max_hole_size) {
1262 max_hole_start = search_start;
1263 max_hole_size = hole_size;
1266 if (contains_pending_extent(trans, device, &search_start, hole_size)) {
1267 btrfs_release_path(path);
1272 if (hole_size < num_bytes)
1278 btrfs_free_path(path);
1279 *start = max_hole_start;
1281 *len = max_hole_size;
1285 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1286 struct btrfs_device *device,
1290 struct btrfs_path *path;
1291 struct btrfs_root *root = device->dev_root;
1292 struct btrfs_key key;
1293 struct btrfs_key found_key;
1294 struct extent_buffer *leaf = NULL;
1295 struct btrfs_dev_extent *extent = NULL;
1297 path = btrfs_alloc_path();
1301 key.objectid = device->devid;
1303 key.type = BTRFS_DEV_EXTENT_KEY;
1305 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1307 ret = btrfs_previous_item(root, path, key.objectid,
1308 BTRFS_DEV_EXTENT_KEY);
1311 leaf = path->nodes[0];
1312 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1313 extent = btrfs_item_ptr(leaf, path->slots[0],
1314 struct btrfs_dev_extent);
1315 BUG_ON(found_key.offset > start || found_key.offset +
1316 btrfs_dev_extent_length(leaf, extent) < start);
1318 btrfs_release_path(path);
1320 } else if (ret == 0) {
1321 leaf = path->nodes[0];
1322 extent = btrfs_item_ptr(leaf, path->slots[0],
1323 struct btrfs_dev_extent);
1325 btrfs_error(root->fs_info, ret, "Slot search failed");
1329 if (device->bytes_used > 0) {
1330 u64 len = btrfs_dev_extent_length(leaf, extent);
1331 device->bytes_used -= len;
1332 spin_lock(&root->fs_info->free_chunk_lock);
1333 root->fs_info->free_chunk_space += len;
1334 spin_unlock(&root->fs_info->free_chunk_lock);
1336 ret = btrfs_del_item(trans, root, path);
1338 btrfs_error(root->fs_info, ret,
1339 "Failed to remove dev extent item");
1342 btrfs_free_path(path);
1346 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1347 struct btrfs_device *device,
1348 u64 chunk_tree, u64 chunk_objectid,
1349 u64 chunk_offset, u64 start, u64 num_bytes)
1352 struct btrfs_path *path;
1353 struct btrfs_root *root = device->dev_root;
1354 struct btrfs_dev_extent *extent;
1355 struct extent_buffer *leaf;
1356 struct btrfs_key key;
1358 WARN_ON(!device->in_fs_metadata);
1359 WARN_ON(device->is_tgtdev_for_dev_replace);
1360 path = btrfs_alloc_path();
1364 key.objectid = device->devid;
1366 key.type = BTRFS_DEV_EXTENT_KEY;
1367 ret = btrfs_insert_empty_item(trans, root, path, &key,
1372 leaf = path->nodes[0];
1373 extent = btrfs_item_ptr(leaf, path->slots[0],
1374 struct btrfs_dev_extent);
1375 btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1376 btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1377 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1379 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1380 btrfs_dev_extent_chunk_tree_uuid(extent), BTRFS_UUID_SIZE);
1382 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1383 btrfs_mark_buffer_dirty(leaf);
1385 btrfs_free_path(path);
1389 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1391 struct extent_map_tree *em_tree;
1392 struct extent_map *em;
1396 em_tree = &fs_info->mapping_tree.map_tree;
1397 read_lock(&em_tree->lock);
1398 n = rb_last(&em_tree->map);
1400 em = rb_entry(n, struct extent_map, rb_node);
1401 ret = em->start + em->len;
1403 read_unlock(&em_tree->lock);
1408 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1412 struct btrfs_key key;
1413 struct btrfs_key found_key;
1414 struct btrfs_path *path;
1416 path = btrfs_alloc_path();
1420 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1421 key.type = BTRFS_DEV_ITEM_KEY;
1422 key.offset = (u64)-1;
1424 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1428 BUG_ON(ret == 0); /* Corruption */
1430 ret = btrfs_previous_item(fs_info->chunk_root, path,
1431 BTRFS_DEV_ITEMS_OBJECTID,
1432 BTRFS_DEV_ITEM_KEY);
1436 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1438 *devid_ret = found_key.offset + 1;
1442 btrfs_free_path(path);
1447 * the device information is stored in the chunk root
1448 * the btrfs_device struct should be fully filled in
1450 static int btrfs_add_device(struct btrfs_trans_handle *trans,
1451 struct btrfs_root *root,
1452 struct btrfs_device *device)
1455 struct btrfs_path *path;
1456 struct btrfs_dev_item *dev_item;
1457 struct extent_buffer *leaf;
1458 struct btrfs_key key;
1461 root = root->fs_info->chunk_root;
1463 path = btrfs_alloc_path();
1467 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1468 key.type = BTRFS_DEV_ITEM_KEY;
1469 key.offset = device->devid;
1471 ret = btrfs_insert_empty_item(trans, root, path, &key,
1476 leaf = path->nodes[0];
1477 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1479 btrfs_set_device_id(leaf, dev_item, device->devid);
1480 btrfs_set_device_generation(leaf, dev_item, 0);
1481 btrfs_set_device_type(leaf, dev_item, device->type);
1482 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1483 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1484 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1485 btrfs_set_device_total_bytes(leaf, dev_item, device->disk_total_bytes);
1486 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1487 btrfs_set_device_group(leaf, dev_item, 0);
1488 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1489 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1490 btrfs_set_device_start_offset(leaf, dev_item, 0);
1492 ptr = btrfs_device_uuid(dev_item);
1493 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1494 ptr = btrfs_device_fsid(dev_item);
1495 write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
1496 btrfs_mark_buffer_dirty(leaf);
1500 btrfs_free_path(path);
1505 * Function to update ctime/mtime for a given device path.
1506 * Mainly used for ctime/mtime based probe like libblkid.
1508 static void update_dev_time(char *path_name)
1512 filp = filp_open(path_name, O_RDWR, 0);
1515 file_update_time(filp);
1516 filp_close(filp, NULL);
1520 static int btrfs_rm_dev_item(struct btrfs_root *root,
1521 struct btrfs_device *device)
1524 struct btrfs_path *path;
1525 struct btrfs_key key;
1526 struct btrfs_trans_handle *trans;
1528 root = root->fs_info->chunk_root;
1530 path = btrfs_alloc_path();
1534 trans = btrfs_start_transaction(root, 0);
1535 if (IS_ERR(trans)) {
1536 btrfs_free_path(path);
1537 return PTR_ERR(trans);
1539 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1540 key.type = BTRFS_DEV_ITEM_KEY;
1541 key.offset = device->devid;
1544 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1553 ret = btrfs_del_item(trans, root, path);
1557 btrfs_free_path(path);
1558 unlock_chunks(root);
1559 btrfs_commit_transaction(trans, root);
1563 int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1565 struct btrfs_device *device;
1566 struct btrfs_device *next_device;
1567 struct block_device *bdev;
1568 struct buffer_head *bh = NULL;
1569 struct btrfs_super_block *disk_super;
1570 struct btrfs_fs_devices *cur_devices;
1577 bool clear_super = false;
1579 mutex_lock(&uuid_mutex);
1582 seq = read_seqbegin(&root->fs_info->profiles_lock);
1584 all_avail = root->fs_info->avail_data_alloc_bits |
1585 root->fs_info->avail_system_alloc_bits |
1586 root->fs_info->avail_metadata_alloc_bits;
1587 } while (read_seqretry(&root->fs_info->profiles_lock, seq));
1589 num_devices = root->fs_info->fs_devices->num_devices;
1590 btrfs_dev_replace_lock(&root->fs_info->dev_replace);
1591 if (btrfs_dev_replace_is_ongoing(&root->fs_info->dev_replace)) {
1592 WARN_ON(num_devices < 1);
1595 btrfs_dev_replace_unlock(&root->fs_info->dev_replace);
1597 if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) && num_devices <= 4) {
1598 ret = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET;
1602 if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) && num_devices <= 2) {
1603 ret = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET;
1607 if ((all_avail & BTRFS_BLOCK_GROUP_RAID5) &&
1608 root->fs_info->fs_devices->rw_devices <= 2) {
1609 ret = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET;
1612 if ((all_avail & BTRFS_BLOCK_GROUP_RAID6) &&
1613 root->fs_info->fs_devices->rw_devices <= 3) {
1614 ret = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET;
1618 if (strcmp(device_path, "missing") == 0) {
1619 struct list_head *devices;
1620 struct btrfs_device *tmp;
1623 devices = &root->fs_info->fs_devices->devices;
1625 * It is safe to read the devices since the volume_mutex
1628 list_for_each_entry(tmp, devices, dev_list) {
1629 if (tmp->in_fs_metadata &&
1630 !tmp->is_tgtdev_for_dev_replace &&
1640 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
1644 ret = btrfs_get_bdev_and_sb(device_path,
1645 FMODE_WRITE | FMODE_EXCL,
1646 root->fs_info->bdev_holder, 0,
1650 disk_super = (struct btrfs_super_block *)bh->b_data;
1651 devid = btrfs_stack_device_id(&disk_super->dev_item);
1652 dev_uuid = disk_super->dev_item.uuid;
1653 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1661 if (device->is_tgtdev_for_dev_replace) {
1662 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1666 if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
1667 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1671 if (device->writeable) {
1673 list_del_init(&device->dev_alloc_list);
1674 unlock_chunks(root);
1675 root->fs_info->fs_devices->rw_devices--;
1679 mutex_unlock(&uuid_mutex);
1680 ret = btrfs_shrink_device(device, 0);
1681 mutex_lock(&uuid_mutex);
1686 * TODO: the superblock still includes this device in its num_devices
1687 * counter although write_all_supers() is not locked out. This
1688 * could give a filesystem state which requires a degraded mount.
1690 ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1694 spin_lock(&root->fs_info->free_chunk_lock);
1695 root->fs_info->free_chunk_space = device->total_bytes -
1697 spin_unlock(&root->fs_info->free_chunk_lock);
1699 device->in_fs_metadata = 0;
1700 btrfs_scrub_cancel_dev(root->fs_info, device);
1703 * the device list mutex makes sure that we don't change
1704 * the device list while someone else is writing out all
1705 * the device supers. Whoever is writing all supers, should
1706 * lock the device list mutex before getting the number of
1707 * devices in the super block (super_copy). Conversely,
1708 * whoever updates the number of devices in the super block
1709 * (super_copy) should hold the device list mutex.
1712 cur_devices = device->fs_devices;
1713 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1714 list_del_rcu(&device->dev_list);
1716 device->fs_devices->num_devices--;
1717 device->fs_devices->total_devices--;
1719 if (device->missing)
1720 device->fs_devices->missing_devices--;
1722 next_device = list_entry(root->fs_info->fs_devices->devices.next,
1723 struct btrfs_device, dev_list);
1724 if (device->bdev == root->fs_info->sb->s_bdev)
1725 root->fs_info->sb->s_bdev = next_device->bdev;
1726 if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1727 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1730 device->fs_devices->open_devices--;
1731 /* remove sysfs entry */
1732 btrfs_kobj_rm_device(root->fs_info, device);
1735 call_rcu(&device->rcu, free_device);
1737 num_devices = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
1738 btrfs_set_super_num_devices(root->fs_info->super_copy, num_devices);
1739 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1741 if (cur_devices->open_devices == 0) {
1742 struct btrfs_fs_devices *fs_devices;
1743 fs_devices = root->fs_info->fs_devices;
1744 while (fs_devices) {
1745 if (fs_devices->seed == cur_devices) {
1746 fs_devices->seed = cur_devices->seed;
1749 fs_devices = fs_devices->seed;
1751 cur_devices->seed = NULL;
1753 __btrfs_close_devices(cur_devices);
1754 unlock_chunks(root);
1755 free_fs_devices(cur_devices);
1758 root->fs_info->num_tolerated_disk_barrier_failures =
1759 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
1762 * at this point, the device is zero sized. We want to
1763 * remove it from the devices list and zero out the old super
1765 if (clear_super && disk_super) {
1769 /* make sure this device isn't detected as part of
1772 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1773 set_buffer_dirty(bh);
1774 sync_dirty_buffer(bh);
1776 /* clear the mirror copies of super block on the disk
1777 * being removed, 0th copy is been taken care above and
1778 * the below would take of the rest
1780 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1781 bytenr = btrfs_sb_offset(i);
1782 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
1783 i_size_read(bdev->bd_inode))
1787 bh = __bread(bdev, bytenr / 4096,
1788 BTRFS_SUPER_INFO_SIZE);
1792 disk_super = (struct btrfs_super_block *)bh->b_data;
1794 if (btrfs_super_bytenr(disk_super) != bytenr ||
1795 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1798 memset(&disk_super->magic, 0,
1799 sizeof(disk_super->magic));
1800 set_buffer_dirty(bh);
1801 sync_dirty_buffer(bh);
1808 /* Notify udev that device has changed */
1809 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
1811 /* Update ctime/mtime for device path for libblkid */
1812 update_dev_time(device_path);
1818 blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
1820 mutex_unlock(&uuid_mutex);
1823 if (device->writeable) {
1825 list_add(&device->dev_alloc_list,
1826 &root->fs_info->fs_devices->alloc_list);
1827 unlock_chunks(root);
1828 root->fs_info->fs_devices->rw_devices++;
1833 void btrfs_rm_dev_replace_srcdev(struct btrfs_fs_info *fs_info,
1834 struct btrfs_device *srcdev)
1836 WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
1838 list_del_rcu(&srcdev->dev_list);
1839 list_del_rcu(&srcdev->dev_alloc_list);
1840 fs_info->fs_devices->num_devices--;
1841 if (srcdev->missing) {
1842 fs_info->fs_devices->missing_devices--;
1843 fs_info->fs_devices->rw_devices++;
1845 if (srcdev->can_discard)
1846 fs_info->fs_devices->num_can_discard--;
1848 fs_info->fs_devices->open_devices--;
1851 * zero out the old super if it is not writable
1852 * (e.g. seed device)
1854 if (srcdev->writeable)
1855 btrfs_scratch_superblock(srcdev);
1858 call_rcu(&srcdev->rcu, free_device);
1861 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
1862 struct btrfs_device *tgtdev)
1864 struct btrfs_device *next_device;
1867 mutex_lock(&fs_info->fs_devices->device_list_mutex);
1869 btrfs_scratch_superblock(tgtdev);
1870 fs_info->fs_devices->open_devices--;
1872 fs_info->fs_devices->num_devices--;
1873 if (tgtdev->can_discard)
1874 fs_info->fs_devices->num_can_discard++;
1876 next_device = list_entry(fs_info->fs_devices->devices.next,
1877 struct btrfs_device, dev_list);
1878 if (tgtdev->bdev == fs_info->sb->s_bdev)
1879 fs_info->sb->s_bdev = next_device->bdev;
1880 if (tgtdev->bdev == fs_info->fs_devices->latest_bdev)
1881 fs_info->fs_devices->latest_bdev = next_device->bdev;
1882 list_del_rcu(&tgtdev->dev_list);
1884 call_rcu(&tgtdev->rcu, free_device);
1886 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1889 static int btrfs_find_device_by_path(struct btrfs_root *root, char *device_path,
1890 struct btrfs_device **device)
1893 struct btrfs_super_block *disk_super;
1896 struct block_device *bdev;
1897 struct buffer_head *bh;
1900 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
1901 root->fs_info->bdev_holder, 0, &bdev, &bh);
1904 disk_super = (struct btrfs_super_block *)bh->b_data;
1905 devid = btrfs_stack_device_id(&disk_super->dev_item);
1906 dev_uuid = disk_super->dev_item.uuid;
1907 *device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1912 blkdev_put(bdev, FMODE_READ);
1916 int btrfs_find_device_missing_or_by_path(struct btrfs_root *root,
1918 struct btrfs_device **device)
1921 if (strcmp(device_path, "missing") == 0) {
1922 struct list_head *devices;
1923 struct btrfs_device *tmp;
1925 devices = &root->fs_info->fs_devices->devices;
1927 * It is safe to read the devices since the volume_mutex
1928 * is held by the caller.
1930 list_for_each_entry(tmp, devices, dev_list) {
1931 if (tmp->in_fs_metadata && !tmp->bdev) {
1938 btrfs_err(root->fs_info, "no missing device found");
1944 return btrfs_find_device_by_path(root, device_path, device);
1949 * does all the dirty work required for changing file system's UUID.
1951 static int btrfs_prepare_sprout(struct btrfs_root *root)
1953 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
1954 struct btrfs_fs_devices *old_devices;
1955 struct btrfs_fs_devices *seed_devices;
1956 struct btrfs_super_block *disk_super = root->fs_info->super_copy;
1957 struct btrfs_device *device;
1960 BUG_ON(!mutex_is_locked(&uuid_mutex));
1961 if (!fs_devices->seeding)
1964 seed_devices = __alloc_fs_devices();
1965 if (IS_ERR(seed_devices))
1966 return PTR_ERR(seed_devices);
1968 old_devices = clone_fs_devices(fs_devices);
1969 if (IS_ERR(old_devices)) {
1970 kfree(seed_devices);
1971 return PTR_ERR(old_devices);
1974 list_add(&old_devices->list, &fs_uuids);
1976 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
1977 seed_devices->opened = 1;
1978 INIT_LIST_HEAD(&seed_devices->devices);
1979 INIT_LIST_HEAD(&seed_devices->alloc_list);
1980 mutex_init(&seed_devices->device_list_mutex);
1982 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1983 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
1986 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
1987 list_for_each_entry(device, &seed_devices->devices, dev_list) {
1988 device->fs_devices = seed_devices;
1991 fs_devices->seeding = 0;
1992 fs_devices->num_devices = 0;
1993 fs_devices->open_devices = 0;
1994 fs_devices->missing_devices = 0;
1995 fs_devices->num_can_discard = 0;
1996 fs_devices->rotating = 0;
1997 fs_devices->seed = seed_devices;
1999 generate_random_uuid(fs_devices->fsid);
2000 memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2001 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2002 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2004 super_flags = btrfs_super_flags(disk_super) &
2005 ~BTRFS_SUPER_FLAG_SEEDING;
2006 btrfs_set_super_flags(disk_super, super_flags);
2012 * strore the expected generation for seed devices in device items.
2014 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2015 struct btrfs_root *root)
2017 struct btrfs_path *path;
2018 struct extent_buffer *leaf;
2019 struct btrfs_dev_item *dev_item;
2020 struct btrfs_device *device;
2021 struct btrfs_key key;
2022 u8 fs_uuid[BTRFS_UUID_SIZE];
2023 u8 dev_uuid[BTRFS_UUID_SIZE];
2027 path = btrfs_alloc_path();
2031 root = root->fs_info->chunk_root;
2032 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2034 key.type = BTRFS_DEV_ITEM_KEY;
2037 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2041 leaf = path->nodes[0];
2043 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2044 ret = btrfs_next_leaf(root, path);
2049 leaf = path->nodes[0];
2050 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2051 btrfs_release_path(path);
2055 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2056 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2057 key.type != BTRFS_DEV_ITEM_KEY)
2060 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2061 struct btrfs_dev_item);
2062 devid = btrfs_device_id(leaf, dev_item);
2063 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2065 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2067 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
2069 BUG_ON(!device); /* Logic error */
2071 if (device->fs_devices->seeding) {
2072 btrfs_set_device_generation(leaf, dev_item,
2073 device->generation);
2074 btrfs_mark_buffer_dirty(leaf);
2082 btrfs_free_path(path);
2086 int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
2088 struct request_queue *q;
2089 struct btrfs_trans_handle *trans;
2090 struct btrfs_device *device;
2091 struct block_device *bdev;
2092 struct list_head *devices;
2093 struct super_block *sb = root->fs_info->sb;
2094 struct rcu_string *name;
2096 int seeding_dev = 0;
2099 if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
2102 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2103 root->fs_info->bdev_holder);
2105 return PTR_ERR(bdev);
2107 if (root->fs_info->fs_devices->seeding) {
2109 down_write(&sb->s_umount);
2110 mutex_lock(&uuid_mutex);
2113 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2115 devices = &root->fs_info->fs_devices->devices;
2117 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2118 list_for_each_entry(device, devices, dev_list) {
2119 if (device->bdev == bdev) {
2122 &root->fs_info->fs_devices->device_list_mutex);
2126 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2128 device = btrfs_alloc_device(root->fs_info, NULL, NULL);
2129 if (IS_ERR(device)) {
2130 /* we can safely leave the fs_devices entry around */
2131 ret = PTR_ERR(device);
2135 name = rcu_string_strdup(device_path, GFP_NOFS);
2141 rcu_assign_pointer(device->name, name);
2143 trans = btrfs_start_transaction(root, 0);
2144 if (IS_ERR(trans)) {
2145 rcu_string_free(device->name);
2147 ret = PTR_ERR(trans);
2153 q = bdev_get_queue(bdev);
2154 if (blk_queue_discard(q))
2155 device->can_discard = 1;
2156 device->writeable = 1;
2157 device->generation = trans->transid;
2158 device->io_width = root->sectorsize;
2159 device->io_align = root->sectorsize;
2160 device->sector_size = root->sectorsize;
2161 device->total_bytes = i_size_read(bdev->bd_inode);
2162 device->disk_total_bytes = device->total_bytes;
2163 device->dev_root = root->fs_info->dev_root;
2164 device->bdev = bdev;
2165 device->in_fs_metadata = 1;
2166 device->is_tgtdev_for_dev_replace = 0;
2167 device->mode = FMODE_EXCL;
2168 device->dev_stats_valid = 1;
2169 set_blocksize(device->bdev, 4096);
2172 sb->s_flags &= ~MS_RDONLY;
2173 ret = btrfs_prepare_sprout(root);
2174 BUG_ON(ret); /* -ENOMEM */
2177 device->fs_devices = root->fs_info->fs_devices;
2179 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2180 list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
2181 list_add(&device->dev_alloc_list,
2182 &root->fs_info->fs_devices->alloc_list);
2183 root->fs_info->fs_devices->num_devices++;
2184 root->fs_info->fs_devices->open_devices++;
2185 root->fs_info->fs_devices->rw_devices++;
2186 root->fs_info->fs_devices->total_devices++;
2187 if (device->can_discard)
2188 root->fs_info->fs_devices->num_can_discard++;
2189 root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2191 spin_lock(&root->fs_info->free_chunk_lock);
2192 root->fs_info->free_chunk_space += device->total_bytes;
2193 spin_unlock(&root->fs_info->free_chunk_lock);
2195 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
2196 root->fs_info->fs_devices->rotating = 1;
2198 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
2199 btrfs_set_super_total_bytes(root->fs_info->super_copy,
2200 total_bytes + device->total_bytes);
2202 total_bytes = btrfs_super_num_devices(root->fs_info->super_copy);
2203 btrfs_set_super_num_devices(root->fs_info->super_copy,
2206 /* add sysfs device entry */
2207 btrfs_kobj_add_device(root->fs_info, device);
2209 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2212 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2213 ret = init_first_rw_device(trans, root, device);
2215 btrfs_abort_transaction(trans, root, ret);
2218 ret = btrfs_finish_sprout(trans, root);
2220 btrfs_abort_transaction(trans, root, ret);
2224 /* Sprouting would change fsid of the mounted root,
2225 * so rename the fsid on the sysfs
2227 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2228 root->fs_info->fsid);
2229 if (kobject_rename(&root->fs_info->super_kobj, fsid_buf))
2232 ret = btrfs_add_device(trans, root, device);
2234 btrfs_abort_transaction(trans, root, ret);
2240 * we've got more storage, clear any full flags on the space
2243 btrfs_clear_space_info_full(root->fs_info);
2245 unlock_chunks(root);
2246 root->fs_info->num_tolerated_disk_barrier_failures =
2247 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
2248 ret = btrfs_commit_transaction(trans, root);
2251 mutex_unlock(&uuid_mutex);
2252 up_write(&sb->s_umount);
2254 if (ret) /* transaction commit */
2257 ret = btrfs_relocate_sys_chunks(root);
2259 btrfs_error(root->fs_info, ret,
2260 "Failed to relocate sys chunks after "
2261 "device initialization. This can be fixed "
2262 "using the \"btrfs balance\" command.");
2263 trans = btrfs_attach_transaction(root);
2264 if (IS_ERR(trans)) {
2265 if (PTR_ERR(trans) == -ENOENT)
2267 return PTR_ERR(trans);
2269 ret = btrfs_commit_transaction(trans, root);
2272 /* Update ctime/mtime for libblkid */
2273 update_dev_time(device_path);
2277 unlock_chunks(root);
2278 btrfs_end_transaction(trans, root);
2279 rcu_string_free(device->name);
2280 btrfs_kobj_rm_device(root->fs_info, device);
2283 blkdev_put(bdev, FMODE_EXCL);
2285 mutex_unlock(&uuid_mutex);
2286 up_write(&sb->s_umount);
2291 int btrfs_init_dev_replace_tgtdev(struct btrfs_root *root, char *device_path,
2292 struct btrfs_device **device_out)
2294 struct request_queue *q;
2295 struct btrfs_device *device;
2296 struct block_device *bdev;
2297 struct btrfs_fs_info *fs_info = root->fs_info;
2298 struct list_head *devices;
2299 struct rcu_string *name;
2300 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2304 if (fs_info->fs_devices->seeding)
2307 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2308 fs_info->bdev_holder);
2310 return PTR_ERR(bdev);
2312 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2314 devices = &fs_info->fs_devices->devices;
2315 list_for_each_entry(device, devices, dev_list) {
2316 if (device->bdev == bdev) {
2322 device = btrfs_alloc_device(NULL, &devid, NULL);
2323 if (IS_ERR(device)) {
2324 ret = PTR_ERR(device);
2328 name = rcu_string_strdup(device_path, GFP_NOFS);
2334 rcu_assign_pointer(device->name, name);
2336 q = bdev_get_queue(bdev);
2337 if (blk_queue_discard(q))
2338 device->can_discard = 1;
2339 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2340 device->writeable = 1;
2341 device->generation = 0;
2342 device->io_width = root->sectorsize;
2343 device->io_align = root->sectorsize;
2344 device->sector_size = root->sectorsize;
2345 device->total_bytes = i_size_read(bdev->bd_inode);
2346 device->disk_total_bytes = device->total_bytes;
2347 device->dev_root = fs_info->dev_root;
2348 device->bdev = bdev;
2349 device->in_fs_metadata = 1;
2350 device->is_tgtdev_for_dev_replace = 1;
2351 device->mode = FMODE_EXCL;
2352 device->dev_stats_valid = 1;
2353 set_blocksize(device->bdev, 4096);
2354 device->fs_devices = fs_info->fs_devices;
2355 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2356 fs_info->fs_devices->num_devices++;
2357 fs_info->fs_devices->open_devices++;
2358 if (device->can_discard)
2359 fs_info->fs_devices->num_can_discard++;
2360 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2362 *device_out = device;
2366 blkdev_put(bdev, FMODE_EXCL);
2370 void btrfs_init_dev_replace_tgtdev_for_resume(struct btrfs_fs_info *fs_info,
2371 struct btrfs_device *tgtdev)
2373 WARN_ON(fs_info->fs_devices->rw_devices == 0);
2374 tgtdev->io_width = fs_info->dev_root->sectorsize;
2375 tgtdev->io_align = fs_info->dev_root->sectorsize;
2376 tgtdev->sector_size = fs_info->dev_root->sectorsize;
2377 tgtdev->dev_root = fs_info->dev_root;
2378 tgtdev->in_fs_metadata = 1;
2381 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2382 struct btrfs_device *device)
2385 struct btrfs_path *path;
2386 struct btrfs_root *root;
2387 struct btrfs_dev_item *dev_item;
2388 struct extent_buffer *leaf;
2389 struct btrfs_key key;
2391 root = device->dev_root->fs_info->chunk_root;
2393 path = btrfs_alloc_path();
2397 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2398 key.type = BTRFS_DEV_ITEM_KEY;
2399 key.offset = device->devid;
2401 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2410 leaf = path->nodes[0];
2411 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2413 btrfs_set_device_id(leaf, dev_item, device->devid);
2414 btrfs_set_device_type(leaf, dev_item, device->type);
2415 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2416 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2417 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2418 btrfs_set_device_total_bytes(leaf, dev_item, device->disk_total_bytes);
2419 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
2420 btrfs_mark_buffer_dirty(leaf);
2423 btrfs_free_path(path);
2427 static int __btrfs_grow_device(struct btrfs_trans_handle *trans,
2428 struct btrfs_device *device, u64 new_size)
2430 struct btrfs_super_block *super_copy =
2431 device->dev_root->fs_info->super_copy;
2432 u64 old_total = btrfs_super_total_bytes(super_copy);
2433 u64 diff = new_size - device->total_bytes;
2435 if (!device->writeable)
2437 if (new_size <= device->total_bytes ||
2438 device->is_tgtdev_for_dev_replace)
2441 btrfs_set_super_total_bytes(super_copy, old_total + diff);
2442 device->fs_devices->total_rw_bytes += diff;
2444 device->total_bytes = new_size;
2445 device->disk_total_bytes = new_size;
2446 btrfs_clear_space_info_full(device->dev_root->fs_info);
2448 return btrfs_update_device(trans, device);
2451 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2452 struct btrfs_device *device, u64 new_size)
2455 lock_chunks(device->dev_root);
2456 ret = __btrfs_grow_device(trans, device, new_size);
2457 unlock_chunks(device->dev_root);
2461 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2462 struct btrfs_root *root,
2463 u64 chunk_tree, u64 chunk_objectid,
2467 struct btrfs_path *path;
2468 struct btrfs_key key;
2470 root = root->fs_info->chunk_root;
2471 path = btrfs_alloc_path();
2475 key.objectid = chunk_objectid;
2476 key.offset = chunk_offset;
2477 key.type = BTRFS_CHUNK_ITEM_KEY;
2479 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2482 else if (ret > 0) { /* Logic error or corruption */
2483 btrfs_error(root->fs_info, -ENOENT,
2484 "Failed lookup while freeing chunk.");
2489 ret = btrfs_del_item(trans, root, path);
2491 btrfs_error(root->fs_info, ret,
2492 "Failed to delete chunk item.");
2494 btrfs_free_path(path);
2498 static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
2501 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
2502 struct btrfs_disk_key *disk_key;
2503 struct btrfs_chunk *chunk;
2510 struct btrfs_key key;
2512 array_size = btrfs_super_sys_array_size(super_copy);
2514 ptr = super_copy->sys_chunk_array;
2517 while (cur < array_size) {
2518 disk_key = (struct btrfs_disk_key *)ptr;
2519 btrfs_disk_key_to_cpu(&key, disk_key);
2521 len = sizeof(*disk_key);
2523 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2524 chunk = (struct btrfs_chunk *)(ptr + len);
2525 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2526 len += btrfs_chunk_item_size(num_stripes);
2531 if (key.objectid == chunk_objectid &&
2532 key.offset == chunk_offset) {
2533 memmove(ptr, ptr + len, array_size - (cur + len));
2535 btrfs_set_super_sys_array_size(super_copy, array_size);
2544 static int btrfs_relocate_chunk(struct btrfs_root *root,
2545 u64 chunk_tree, u64 chunk_objectid,
2548 struct extent_map_tree *em_tree;
2549 struct btrfs_root *extent_root;
2550 struct btrfs_trans_handle *trans;
2551 struct extent_map *em;
2552 struct map_lookup *map;
2556 root = root->fs_info->chunk_root;
2557 extent_root = root->fs_info->extent_root;
2558 em_tree = &root->fs_info->mapping_tree.map_tree;
2560 ret = btrfs_can_relocate(extent_root, chunk_offset);
2564 /* step one, relocate all the extents inside this chunk */
2565 ret = btrfs_relocate_block_group(extent_root, chunk_offset);
2569 trans = btrfs_start_transaction(root, 0);
2570 if (IS_ERR(trans)) {
2571 ret = PTR_ERR(trans);
2572 btrfs_std_error(root->fs_info, ret);
2579 * step two, delete the device extents and the
2580 * chunk tree entries
2582 read_lock(&em_tree->lock);
2583 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
2584 read_unlock(&em_tree->lock);
2586 BUG_ON(!em || em->start > chunk_offset ||
2587 em->start + em->len < chunk_offset);
2588 map = (struct map_lookup *)em->bdev;
2590 for (i = 0; i < map->num_stripes; i++) {
2591 ret = btrfs_free_dev_extent(trans, map->stripes[i].dev,
2592 map->stripes[i].physical);
2595 if (map->stripes[i].dev) {
2596 ret = btrfs_update_device(trans, map->stripes[i].dev);
2600 ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
2605 trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
2607 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2608 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
2612 ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
2615 write_lock(&em_tree->lock);
2616 remove_extent_mapping(em_tree, em);
2617 write_unlock(&em_tree->lock);
2619 /* once for the tree */
2620 free_extent_map(em);
2622 free_extent_map(em);
2624 unlock_chunks(root);
2625 btrfs_end_transaction(trans, root);
2629 static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
2631 struct btrfs_root *chunk_root = root->fs_info->chunk_root;
2632 struct btrfs_path *path;
2633 struct extent_buffer *leaf;
2634 struct btrfs_chunk *chunk;
2635 struct btrfs_key key;
2636 struct btrfs_key found_key;
2637 u64 chunk_tree = chunk_root->root_key.objectid;
2639 bool retried = false;
2643 path = btrfs_alloc_path();
2648 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2649 key.offset = (u64)-1;
2650 key.type = BTRFS_CHUNK_ITEM_KEY;
2653 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2656 BUG_ON(ret == 0); /* Corruption */
2658 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2665 leaf = path->nodes[0];
2666 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2668 chunk = btrfs_item_ptr(leaf, path->slots[0],
2669 struct btrfs_chunk);
2670 chunk_type = btrfs_chunk_type(leaf, chunk);
2671 btrfs_release_path(path);
2673 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2674 ret = btrfs_relocate_chunk(chunk_root, chunk_tree,
2683 if (found_key.offset == 0)
2685 key.offset = found_key.offset - 1;
2688 if (failed && !retried) {
2692 } else if (WARN_ON(failed && retried)) {
2696 btrfs_free_path(path);
2700 static int insert_balance_item(struct btrfs_root *root,
2701 struct btrfs_balance_control *bctl)
2703 struct btrfs_trans_handle *trans;
2704 struct btrfs_balance_item *item;
2705 struct btrfs_disk_balance_args disk_bargs;
2706 struct btrfs_path *path;
2707 struct extent_buffer *leaf;
2708 struct btrfs_key key;
2711 path = btrfs_alloc_path();
2715 trans = btrfs_start_transaction(root, 0);
2716 if (IS_ERR(trans)) {
2717 btrfs_free_path(path);
2718 return PTR_ERR(trans);
2721 key.objectid = BTRFS_BALANCE_OBJECTID;
2722 key.type = BTRFS_BALANCE_ITEM_KEY;
2725 ret = btrfs_insert_empty_item(trans, root, path, &key,
2730 leaf = path->nodes[0];
2731 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2733 memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
2735 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
2736 btrfs_set_balance_data(leaf, item, &disk_bargs);
2737 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
2738 btrfs_set_balance_meta(leaf, item, &disk_bargs);
2739 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
2740 btrfs_set_balance_sys(leaf, item, &disk_bargs);
2742 btrfs_set_balance_flags(leaf, item, bctl->flags);
2744 btrfs_mark_buffer_dirty(leaf);
2746 btrfs_free_path(path);
2747 err = btrfs_commit_transaction(trans, root);
2753 static int del_balance_item(struct btrfs_root *root)
2755 struct btrfs_trans_handle *trans;
2756 struct btrfs_path *path;
2757 struct btrfs_key key;
2760 path = btrfs_alloc_path();
2764 trans = btrfs_start_transaction(root, 0);
2765 if (IS_ERR(trans)) {
2766 btrfs_free_path(path);
2767 return PTR_ERR(trans);
2770 key.objectid = BTRFS_BALANCE_OBJECTID;
2771 key.type = BTRFS_BALANCE_ITEM_KEY;
2774 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2782 ret = btrfs_del_item(trans, root, path);
2784 btrfs_free_path(path);
2785 err = btrfs_commit_transaction(trans, root);
2792 * This is a heuristic used to reduce the number of chunks balanced on
2793 * resume after balance was interrupted.
2795 static void update_balance_args(struct btrfs_balance_control *bctl)
2798 * Turn on soft mode for chunk types that were being converted.
2800 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
2801 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
2802 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
2803 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
2804 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
2805 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
2808 * Turn on usage filter if is not already used. The idea is
2809 * that chunks that we have already balanced should be
2810 * reasonably full. Don't do it for chunks that are being
2811 * converted - that will keep us from relocating unconverted
2812 * (albeit full) chunks.
2814 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2815 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2816 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
2817 bctl->data.usage = 90;
2819 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2820 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2821 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
2822 bctl->sys.usage = 90;
2824 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2825 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2826 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
2827 bctl->meta.usage = 90;
2832 * Should be called with both balance and volume mutexes held to
2833 * serialize other volume operations (add_dev/rm_dev/resize) with
2834 * restriper. Same goes for unset_balance_control.
2836 static void set_balance_control(struct btrfs_balance_control *bctl)
2838 struct btrfs_fs_info *fs_info = bctl->fs_info;
2840 BUG_ON(fs_info->balance_ctl);
2842 spin_lock(&fs_info->balance_lock);
2843 fs_info->balance_ctl = bctl;
2844 spin_unlock(&fs_info->balance_lock);
2847 static void unset_balance_control(struct btrfs_fs_info *fs_info)
2849 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
2851 BUG_ON(!fs_info->balance_ctl);
2853 spin_lock(&fs_info->balance_lock);
2854 fs_info->balance_ctl = NULL;
2855 spin_unlock(&fs_info->balance_lock);
2861 * Balance filters. Return 1 if chunk should be filtered out
2862 * (should not be balanced).
2864 static int chunk_profiles_filter(u64 chunk_type,
2865 struct btrfs_balance_args *bargs)
2867 chunk_type = chunk_to_extended(chunk_type) &
2868 BTRFS_EXTENDED_PROFILE_MASK;
2870 if (bargs->profiles & chunk_type)
2876 static int chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
2877 struct btrfs_balance_args *bargs)
2879 struct btrfs_block_group_cache *cache;
2880 u64 chunk_used, user_thresh;
2883 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2884 chunk_used = btrfs_block_group_used(&cache->item);
2886 if (bargs->usage == 0)
2888 else if (bargs->usage > 100)
2889 user_thresh = cache->key.offset;
2891 user_thresh = div_factor_fine(cache->key.offset,
2894 if (chunk_used < user_thresh)
2897 btrfs_put_block_group(cache);
2901 static int chunk_devid_filter(struct extent_buffer *leaf,
2902 struct btrfs_chunk *chunk,
2903 struct btrfs_balance_args *bargs)
2905 struct btrfs_stripe *stripe;
2906 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2909 for (i = 0; i < num_stripes; i++) {
2910 stripe = btrfs_stripe_nr(chunk, i);
2911 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
2918 /* [pstart, pend) */
2919 static int chunk_drange_filter(struct extent_buffer *leaf,
2920 struct btrfs_chunk *chunk,
2922 struct btrfs_balance_args *bargs)
2924 struct btrfs_stripe *stripe;
2925 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2931 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
2934 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
2935 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
2936 factor = num_stripes / 2;
2937 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
2938 factor = num_stripes - 1;
2939 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
2940 factor = num_stripes - 2;
2942 factor = num_stripes;
2945 for (i = 0; i < num_stripes; i++) {
2946 stripe = btrfs_stripe_nr(chunk, i);
2947 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
2950 stripe_offset = btrfs_stripe_offset(leaf, stripe);
2951 stripe_length = btrfs_chunk_length(leaf, chunk);
2952 do_div(stripe_length, factor);
2954 if (stripe_offset < bargs->pend &&
2955 stripe_offset + stripe_length > bargs->pstart)
2962 /* [vstart, vend) */
2963 static int chunk_vrange_filter(struct extent_buffer *leaf,
2964 struct btrfs_chunk *chunk,
2966 struct btrfs_balance_args *bargs)
2968 if (chunk_offset < bargs->vend &&
2969 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
2970 /* at least part of the chunk is inside this vrange */
2976 static int chunk_soft_convert_filter(u64 chunk_type,
2977 struct btrfs_balance_args *bargs)
2979 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
2982 chunk_type = chunk_to_extended(chunk_type) &
2983 BTRFS_EXTENDED_PROFILE_MASK;
2985 if (bargs->target == chunk_type)
2991 static int should_balance_chunk(struct btrfs_root *root,
2992 struct extent_buffer *leaf,
2993 struct btrfs_chunk *chunk, u64 chunk_offset)
2995 struct btrfs_balance_control *bctl = root->fs_info->balance_ctl;
2996 struct btrfs_balance_args *bargs = NULL;
2997 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3000 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3001 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3005 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3006 bargs = &bctl->data;
3007 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3009 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3010 bargs = &bctl->meta;
3012 /* profiles filter */
3013 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3014 chunk_profiles_filter(chunk_type, bargs)) {
3019 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3020 chunk_usage_filter(bctl->fs_info, chunk_offset, bargs)) {
3025 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3026 chunk_devid_filter(leaf, chunk, bargs)) {
3030 /* drange filter, makes sense only with devid filter */
3031 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3032 chunk_drange_filter(leaf, chunk, chunk_offset, bargs)) {
3037 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3038 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3042 /* soft profile changing mode */
3043 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3044 chunk_soft_convert_filter(chunk_type, bargs)) {
3049 * limited by count, must be the last filter
3051 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3052 if (bargs->limit == 0)
3061 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3063 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3064 struct btrfs_root *chunk_root = fs_info->chunk_root;
3065 struct btrfs_root *dev_root = fs_info->dev_root;
3066 struct list_head *devices;
3067 struct btrfs_device *device;
3070 struct btrfs_chunk *chunk;
3071 struct btrfs_path *path;
3072 struct btrfs_key key;
3073 struct btrfs_key found_key;
3074 struct btrfs_trans_handle *trans;
3075 struct extent_buffer *leaf;
3078 int enospc_errors = 0;
3079 bool counting = true;
3080 u64 limit_data = bctl->data.limit;
3081 u64 limit_meta = bctl->meta.limit;
3082 u64 limit_sys = bctl->sys.limit;
3084 /* step one make some room on all the devices */
3085 devices = &fs_info->fs_devices->devices;
3086 list_for_each_entry(device, devices, dev_list) {
3087 old_size = device->total_bytes;
3088 size_to_free = div_factor(old_size, 1);
3089 size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
3090 if (!device->writeable ||
3091 device->total_bytes - device->bytes_used > size_to_free ||
3092 device->is_tgtdev_for_dev_replace)
3095 ret = btrfs_shrink_device(device, old_size - size_to_free);
3100 trans = btrfs_start_transaction(dev_root, 0);
3101 BUG_ON(IS_ERR(trans));
3103 ret = btrfs_grow_device(trans, device, old_size);
3106 btrfs_end_transaction(trans, dev_root);
3109 /* step two, relocate all the chunks */
3110 path = btrfs_alloc_path();
3116 /* zero out stat counters */
3117 spin_lock(&fs_info->balance_lock);
3118 memset(&bctl->stat, 0, sizeof(bctl->stat));
3119 spin_unlock(&fs_info->balance_lock);
3122 bctl->data.limit = limit_data;
3123 bctl->meta.limit = limit_meta;
3124 bctl->sys.limit = limit_sys;
3126 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3127 key.offset = (u64)-1;
3128 key.type = BTRFS_CHUNK_ITEM_KEY;
3131 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3132 atomic_read(&fs_info->balance_cancel_req)) {
3137 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3142 * this shouldn't happen, it means the last relocate
3146 BUG(); /* FIXME break ? */
3148 ret = btrfs_previous_item(chunk_root, path, 0,
3149 BTRFS_CHUNK_ITEM_KEY);
3155 leaf = path->nodes[0];
3156 slot = path->slots[0];
3157 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3159 if (found_key.objectid != key.objectid)
3162 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3165 spin_lock(&fs_info->balance_lock);
3166 bctl->stat.considered++;
3167 spin_unlock(&fs_info->balance_lock);
3170 ret = should_balance_chunk(chunk_root, leaf, chunk,
3172 btrfs_release_path(path);
3177 spin_lock(&fs_info->balance_lock);
3178 bctl->stat.expected++;
3179 spin_unlock(&fs_info->balance_lock);
3183 ret = btrfs_relocate_chunk(chunk_root,
3184 chunk_root->root_key.objectid,
3187 if (ret && ret != -ENOSPC)
3189 if (ret == -ENOSPC) {
3192 spin_lock(&fs_info->balance_lock);
3193 bctl->stat.completed++;
3194 spin_unlock(&fs_info->balance_lock);
3197 if (found_key.offset == 0)
3199 key.offset = found_key.offset - 1;
3203 btrfs_release_path(path);
3208 btrfs_free_path(path);
3209 if (enospc_errors) {
3210 btrfs_info(fs_info, "%d enospc errors during balance",
3220 * alloc_profile_is_valid - see if a given profile is valid and reduced
3221 * @flags: profile to validate
3222 * @extended: if true @flags is treated as an extended profile
3224 static int alloc_profile_is_valid(u64 flags, int extended)
3226 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3227 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3229 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3231 /* 1) check that all other bits are zeroed */
3235 /* 2) see if profile is reduced */
3237 return !extended; /* "0" is valid for usual profiles */
3239 /* true if exactly one bit set */
3240 return (flags & (flags - 1)) == 0;
3243 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3245 /* cancel requested || normal exit path */
3246 return atomic_read(&fs_info->balance_cancel_req) ||
3247 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3248 atomic_read(&fs_info->balance_cancel_req) == 0);
3251 static void __cancel_balance(struct btrfs_fs_info *fs_info)
3255 unset_balance_control(fs_info);
3256 ret = del_balance_item(fs_info->tree_root);
3258 btrfs_std_error(fs_info, ret);
3260 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3264 * Should be called with both balance and volume mutexes held
3266 int btrfs_balance(struct btrfs_balance_control *bctl,
3267 struct btrfs_ioctl_balance_args *bargs)
3269 struct btrfs_fs_info *fs_info = bctl->fs_info;
3276 if (btrfs_fs_closing(fs_info) ||
3277 atomic_read(&fs_info->balance_pause_req) ||
3278 atomic_read(&fs_info->balance_cancel_req)) {
3283 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3284 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3288 * In case of mixed groups both data and meta should be picked,
3289 * and identical options should be given for both of them.
3291 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3292 if (mixed && (bctl->flags & allowed)) {
3293 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3294 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3295 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3296 btrfs_err(fs_info, "with mixed groups data and "
3297 "metadata balance options must be the same");
3303 num_devices = fs_info->fs_devices->num_devices;
3304 btrfs_dev_replace_lock(&fs_info->dev_replace);
3305 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3306 BUG_ON(num_devices < 1);
3309 btrfs_dev_replace_unlock(&fs_info->dev_replace);
3310 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
3311 if (num_devices == 1)
3312 allowed |= BTRFS_BLOCK_GROUP_DUP;
3313 else if (num_devices > 1)
3314 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3315 if (num_devices > 2)
3316 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3317 if (num_devices > 3)
3318 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3319 BTRFS_BLOCK_GROUP_RAID6);
3320 if ((bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3321 (!alloc_profile_is_valid(bctl->data.target, 1) ||
3322 (bctl->data.target & ~allowed))) {
3323 btrfs_err(fs_info, "unable to start balance with target "
3324 "data profile %llu",
3329 if ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3330 (!alloc_profile_is_valid(bctl->meta.target, 1) ||
3331 (bctl->meta.target & ~allowed))) {
3333 "unable to start balance with target metadata profile %llu",
3338 if ((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3339 (!alloc_profile_is_valid(bctl->sys.target, 1) ||
3340 (bctl->sys.target & ~allowed))) {
3342 "unable to start balance with target system profile %llu",
3348 /* allow dup'ed data chunks only in mixed mode */
3349 if (!mixed && (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3350 (bctl->data.target & BTRFS_BLOCK_GROUP_DUP)) {
3351 btrfs_err(fs_info, "dup for data is not allowed");
3356 /* allow to reduce meta or sys integrity only if force set */
3357 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3358 BTRFS_BLOCK_GROUP_RAID10 |
3359 BTRFS_BLOCK_GROUP_RAID5 |
3360 BTRFS_BLOCK_GROUP_RAID6;
3362 seq = read_seqbegin(&fs_info->profiles_lock);
3364 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3365 (fs_info->avail_system_alloc_bits & allowed) &&
3366 !(bctl->sys.target & allowed)) ||
3367 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3368 (fs_info->avail_metadata_alloc_bits & allowed) &&
3369 !(bctl->meta.target & allowed))) {
3370 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3371 btrfs_info(fs_info, "force reducing metadata integrity");
3373 btrfs_err(fs_info, "balance will reduce metadata "
3374 "integrity, use force if you want this");
3379 } while (read_seqretry(&fs_info->profiles_lock, seq));
3381 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3382 int num_tolerated_disk_barrier_failures;
3383 u64 target = bctl->sys.target;
3385 num_tolerated_disk_barrier_failures =
3386 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3387 if (num_tolerated_disk_barrier_failures > 0 &&
3389 (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID0 |
3390 BTRFS_AVAIL_ALLOC_BIT_SINGLE)))
3391 num_tolerated_disk_barrier_failures = 0;
3392 else if (num_tolerated_disk_barrier_failures > 1 &&
3394 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)))
3395 num_tolerated_disk_barrier_failures = 1;
3397 fs_info->num_tolerated_disk_barrier_failures =
3398 num_tolerated_disk_barrier_failures;
3401 ret = insert_balance_item(fs_info->tree_root, bctl);
3402 if (ret && ret != -EEXIST)
3405 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3406 BUG_ON(ret == -EEXIST);
3407 set_balance_control(bctl);
3409 BUG_ON(ret != -EEXIST);
3410 spin_lock(&fs_info->balance_lock);
3411 update_balance_args(bctl);
3412 spin_unlock(&fs_info->balance_lock);
3415 atomic_inc(&fs_info->balance_running);
3416 mutex_unlock(&fs_info->balance_mutex);
3418 ret = __btrfs_balance(fs_info);
3420 mutex_lock(&fs_info->balance_mutex);
3421 atomic_dec(&fs_info->balance_running);
3423 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3424 fs_info->num_tolerated_disk_barrier_failures =
3425 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3429 memset(bargs, 0, sizeof(*bargs));
3430 update_ioctl_balance_args(fs_info, 0, bargs);
3433 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3434 balance_need_close(fs_info)) {
3435 __cancel_balance(fs_info);
3438 wake_up(&fs_info->balance_wait_q);
3442 if (bctl->flags & BTRFS_BALANCE_RESUME)
3443 __cancel_balance(fs_info);
3446 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3451 static int balance_kthread(void *data)
3453 struct btrfs_fs_info *fs_info = data;
3456 mutex_lock(&fs_info->volume_mutex);
3457 mutex_lock(&fs_info->balance_mutex);
3459 if (fs_info->balance_ctl) {
3460 btrfs_info(fs_info, "continuing balance");
3461 ret = btrfs_balance(fs_info->balance_ctl, NULL);
3464 mutex_unlock(&fs_info->balance_mutex);
3465 mutex_unlock(&fs_info->volume_mutex);
3470 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3472 struct task_struct *tsk;
3474 spin_lock(&fs_info->balance_lock);
3475 if (!fs_info->balance_ctl) {
3476 spin_unlock(&fs_info->balance_lock);
3479 spin_unlock(&fs_info->balance_lock);
3481 if (btrfs_test_opt(fs_info->tree_root, SKIP_BALANCE)) {
3482 btrfs_info(fs_info, "force skipping balance");
3486 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3487 return PTR_ERR_OR_ZERO(tsk);
3490 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3492 struct btrfs_balance_control *bctl;
3493 struct btrfs_balance_item *item;
3494 struct btrfs_disk_balance_args disk_bargs;
3495 struct btrfs_path *path;
3496 struct extent_buffer *leaf;
3497 struct btrfs_key key;
3500 path = btrfs_alloc_path();
3504 key.objectid = BTRFS_BALANCE_OBJECTID;
3505 key.type = BTRFS_BALANCE_ITEM_KEY;
3508 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3511 if (ret > 0) { /* ret = -ENOENT; */
3516 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3522 leaf = path->nodes[0];
3523 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3525 bctl->fs_info = fs_info;
3526 bctl->flags = btrfs_balance_flags(leaf, item);
3527 bctl->flags |= BTRFS_BALANCE_RESUME;
3529 btrfs_balance_data(leaf, item, &disk_bargs);
3530 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
3531 btrfs_balance_meta(leaf, item, &disk_bargs);
3532 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
3533 btrfs_balance_sys(leaf, item, &disk_bargs);
3534 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
3536 WARN_ON(atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1));
3538 mutex_lock(&fs_info->volume_mutex);
3539 mutex_lock(&fs_info->balance_mutex);
3541 set_balance_control(bctl);
3543 mutex_unlock(&fs_info->balance_mutex);
3544 mutex_unlock(&fs_info->volume_mutex);
3546 btrfs_free_path(path);
3550 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
3554 mutex_lock(&fs_info->balance_mutex);
3555 if (!fs_info->balance_ctl) {
3556 mutex_unlock(&fs_info->balance_mutex);
3560 if (atomic_read(&fs_info->balance_running)) {
3561 atomic_inc(&fs_info->balance_pause_req);
3562 mutex_unlock(&fs_info->balance_mutex);
3564 wait_event(fs_info->balance_wait_q,
3565 atomic_read(&fs_info->balance_running) == 0);
3567 mutex_lock(&fs_info->balance_mutex);
3568 /* we are good with balance_ctl ripped off from under us */
3569 BUG_ON(atomic_read(&fs_info->balance_running));
3570 atomic_dec(&fs_info->balance_pause_req);
3575 mutex_unlock(&fs_info->balance_mutex);
3579 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
3581 if (fs_info->sb->s_flags & MS_RDONLY)
3584 mutex_lock(&fs_info->balance_mutex);
3585 if (!fs_info->balance_ctl) {
3586 mutex_unlock(&fs_info->balance_mutex);
3590 atomic_inc(&fs_info->balance_cancel_req);
3592 * if we are running just wait and return, balance item is
3593 * deleted in btrfs_balance in this case
3595 if (atomic_read(&fs_info->balance_running)) {
3596 mutex_unlock(&fs_info->balance_mutex);
3597 wait_event(fs_info->balance_wait_q,
3598 atomic_read(&fs_info->balance_running) == 0);
3599 mutex_lock(&fs_info->balance_mutex);
3601 /* __cancel_balance needs volume_mutex */
3602 mutex_unlock(&fs_info->balance_mutex);
3603 mutex_lock(&fs_info->volume_mutex);
3604 mutex_lock(&fs_info->balance_mutex);
3606 if (fs_info->balance_ctl)
3607 __cancel_balance(fs_info);
3609 mutex_unlock(&fs_info->volume_mutex);
3612 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
3613 atomic_dec(&fs_info->balance_cancel_req);
3614 mutex_unlock(&fs_info->balance_mutex);
3618 static int btrfs_uuid_scan_kthread(void *data)
3620 struct btrfs_fs_info *fs_info = data;
3621 struct btrfs_root *root = fs_info->tree_root;
3622 struct btrfs_key key;
3623 struct btrfs_key max_key;
3624 struct btrfs_path *path = NULL;
3626 struct extent_buffer *eb;
3628 struct btrfs_root_item root_item;
3630 struct btrfs_trans_handle *trans = NULL;
3632 path = btrfs_alloc_path();
3639 key.type = BTRFS_ROOT_ITEM_KEY;
3642 max_key.objectid = (u64)-1;
3643 max_key.type = BTRFS_ROOT_ITEM_KEY;
3644 max_key.offset = (u64)-1;
3646 path->keep_locks = 1;
3649 ret = btrfs_search_forward(root, &key, path, 0);
3656 if (key.type != BTRFS_ROOT_ITEM_KEY ||
3657 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
3658 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
3659 key.objectid > BTRFS_LAST_FREE_OBJECTID)
3662 eb = path->nodes[0];
3663 slot = path->slots[0];
3664 item_size = btrfs_item_size_nr(eb, slot);
3665 if (item_size < sizeof(root_item))
3668 read_extent_buffer(eb, &root_item,
3669 btrfs_item_ptr_offset(eb, slot),
3670 (int)sizeof(root_item));
3671 if (btrfs_root_refs(&root_item) == 0)
3674 if (!btrfs_is_empty_uuid(root_item.uuid) ||
3675 !btrfs_is_empty_uuid(root_item.received_uuid)) {
3679 btrfs_release_path(path);
3681 * 1 - subvol uuid item
3682 * 1 - received_subvol uuid item
3684 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
3685 if (IS_ERR(trans)) {
3686 ret = PTR_ERR(trans);
3694 if (!btrfs_is_empty_uuid(root_item.uuid)) {
3695 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
3697 BTRFS_UUID_KEY_SUBVOL,
3700 btrfs_warn(fs_info, "uuid_tree_add failed %d",
3706 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
3707 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
3708 root_item.received_uuid,
3709 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
3712 btrfs_warn(fs_info, "uuid_tree_add failed %d",
3720 ret = btrfs_end_transaction(trans, fs_info->uuid_root);
3726 btrfs_release_path(path);
3727 if (key.offset < (u64)-1) {
3729 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
3731 key.type = BTRFS_ROOT_ITEM_KEY;
3732 } else if (key.objectid < (u64)-1) {
3734 key.type = BTRFS_ROOT_ITEM_KEY;
3743 btrfs_free_path(path);
3744 if (trans && !IS_ERR(trans))
3745 btrfs_end_transaction(trans, fs_info->uuid_root);
3747 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
3749 fs_info->update_uuid_tree_gen = 1;
3750 up(&fs_info->uuid_tree_rescan_sem);
3755 * Callback for btrfs_uuid_tree_iterate().
3757 * 0 check succeeded, the entry is not outdated.
3758 * < 0 if an error occured.
3759 * > 0 if the check failed, which means the caller shall remove the entry.
3761 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
3762 u8 *uuid, u8 type, u64 subid)
3764 struct btrfs_key key;
3766 struct btrfs_root *subvol_root;
3768 if (type != BTRFS_UUID_KEY_SUBVOL &&
3769 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
3772 key.objectid = subid;
3773 key.type = BTRFS_ROOT_ITEM_KEY;
3774 key.offset = (u64)-1;
3775 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
3776 if (IS_ERR(subvol_root)) {
3777 ret = PTR_ERR(subvol_root);
3784 case BTRFS_UUID_KEY_SUBVOL:
3785 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
3788 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
3789 if (memcmp(uuid, subvol_root->root_item.received_uuid,
3799 static int btrfs_uuid_rescan_kthread(void *data)
3801 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
3805 * 1st step is to iterate through the existing UUID tree and
3806 * to delete all entries that contain outdated data.
3807 * 2nd step is to add all missing entries to the UUID tree.
3809 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
3811 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
3812 up(&fs_info->uuid_tree_rescan_sem);
3815 return btrfs_uuid_scan_kthread(data);
3818 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
3820 struct btrfs_trans_handle *trans;
3821 struct btrfs_root *tree_root = fs_info->tree_root;
3822 struct btrfs_root *uuid_root;
3823 struct task_struct *task;
3830 trans = btrfs_start_transaction(tree_root, 2);
3832 return PTR_ERR(trans);
3834 uuid_root = btrfs_create_tree(trans, fs_info,
3835 BTRFS_UUID_TREE_OBJECTID);
3836 if (IS_ERR(uuid_root)) {
3837 btrfs_abort_transaction(trans, tree_root,
3838 PTR_ERR(uuid_root));
3839 return PTR_ERR(uuid_root);
3842 fs_info->uuid_root = uuid_root;
3844 ret = btrfs_commit_transaction(trans, tree_root);
3848 down(&fs_info->uuid_tree_rescan_sem);
3849 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
3851 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
3852 btrfs_warn(fs_info, "failed to start uuid_scan task");
3853 up(&fs_info->uuid_tree_rescan_sem);
3854 return PTR_ERR(task);
3860 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
3862 struct task_struct *task;
3864 down(&fs_info->uuid_tree_rescan_sem);
3865 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
3867 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
3868 btrfs_warn(fs_info, "failed to start uuid_rescan task");
3869 up(&fs_info->uuid_tree_rescan_sem);
3870 return PTR_ERR(task);
3877 * shrinking a device means finding all of the device extents past
3878 * the new size, and then following the back refs to the chunks.
3879 * The chunk relocation code actually frees the device extent
3881 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
3883 struct btrfs_trans_handle *trans;
3884 struct btrfs_root *root = device->dev_root;
3885 struct btrfs_dev_extent *dev_extent = NULL;
3886 struct btrfs_path *path;
3894 bool retried = false;
3895 struct extent_buffer *l;
3896 struct btrfs_key key;
3897 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
3898 u64 old_total = btrfs_super_total_bytes(super_copy);
3899 u64 old_size = device->total_bytes;
3900 u64 diff = device->total_bytes - new_size;
3902 if (device->is_tgtdev_for_dev_replace)
3905 path = btrfs_alloc_path();
3913 device->total_bytes = new_size;
3914 if (device->writeable) {
3915 device->fs_devices->total_rw_bytes -= diff;
3916 spin_lock(&root->fs_info->free_chunk_lock);
3917 root->fs_info->free_chunk_space -= diff;
3918 spin_unlock(&root->fs_info->free_chunk_lock);
3920 unlock_chunks(root);
3923 key.objectid = device->devid;
3924 key.offset = (u64)-1;
3925 key.type = BTRFS_DEV_EXTENT_KEY;
3928 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3932 ret = btrfs_previous_item(root, path, 0, key.type);
3937 btrfs_release_path(path);
3942 slot = path->slots[0];
3943 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
3945 if (key.objectid != device->devid) {
3946 btrfs_release_path(path);
3950 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
3951 length = btrfs_dev_extent_length(l, dev_extent);
3953 if (key.offset + length <= new_size) {
3954 btrfs_release_path(path);
3958 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
3959 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
3960 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
3961 btrfs_release_path(path);
3963 ret = btrfs_relocate_chunk(root, chunk_tree, chunk_objectid,
3965 if (ret && ret != -ENOSPC)
3969 } while (key.offset-- > 0);
3971 if (failed && !retried) {
3975 } else if (failed && retried) {
3979 device->total_bytes = old_size;
3980 if (device->writeable)
3981 device->fs_devices->total_rw_bytes += diff;
3982 spin_lock(&root->fs_info->free_chunk_lock);
3983 root->fs_info->free_chunk_space += diff;
3984 spin_unlock(&root->fs_info->free_chunk_lock);
3985 unlock_chunks(root);
3989 /* Shrinking succeeded, else we would be at "done". */
3990 trans = btrfs_start_transaction(root, 0);
3991 if (IS_ERR(trans)) {
3992 ret = PTR_ERR(trans);
3998 device->disk_total_bytes = new_size;
3999 /* Now btrfs_update_device() will change the on-disk size. */
4000 ret = btrfs_update_device(trans, device);
4002 unlock_chunks(root);
4003 btrfs_end_transaction(trans, root);
4006 WARN_ON(diff > old_total);
4007 btrfs_set_super_total_bytes(super_copy, old_total - diff);
4008 unlock_chunks(root);
4009 btrfs_end_transaction(trans, root);
4011 btrfs_free_path(path);
4015 static int btrfs_add_system_chunk(struct btrfs_root *root,
4016 struct btrfs_key *key,
4017 struct btrfs_chunk *chunk, int item_size)
4019 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
4020 struct btrfs_disk_key disk_key;
4024 array_size = btrfs_super_sys_array_size(super_copy);
4025 if (array_size + item_size + sizeof(disk_key)
4026 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
4029 ptr = super_copy->sys_chunk_array + array_size;
4030 btrfs_cpu_key_to_disk(&disk_key, key);
4031 memcpy(ptr, &disk_key, sizeof(disk_key));
4032 ptr += sizeof(disk_key);
4033 memcpy(ptr, chunk, item_size);
4034 item_size += sizeof(disk_key);
4035 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4040 * sort the devices in descending order by max_avail, total_avail
4042 static int btrfs_cmp_device_info(const void *a, const void *b)
4044 const struct btrfs_device_info *di_a = a;
4045 const struct btrfs_device_info *di_b = b;
4047 if (di_a->max_avail > di_b->max_avail)
4049 if (di_a->max_avail < di_b->max_avail)
4051 if (di_a->total_avail > di_b->total_avail)
4053 if (di_a->total_avail < di_b->total_avail)
4058 static struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
4059 [BTRFS_RAID_RAID10] = {
4062 .devs_max = 0, /* 0 == as many as possible */
4064 .devs_increment = 2,
4067 [BTRFS_RAID_RAID1] = {
4072 .devs_increment = 2,
4075 [BTRFS_RAID_DUP] = {
4080 .devs_increment = 1,
4083 [BTRFS_RAID_RAID0] = {
4088 .devs_increment = 1,
4091 [BTRFS_RAID_SINGLE] = {
4096 .devs_increment = 1,
4099 [BTRFS_RAID_RAID5] = {
4104 .devs_increment = 1,
4107 [BTRFS_RAID_RAID6] = {
4112 .devs_increment = 1,
4117 static u32 find_raid56_stripe_len(u32 data_devices, u32 dev_stripe_target)
4119 /* TODO allow them to set a preferred stripe size */
4123 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4125 if (!(type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)))
4128 btrfs_set_fs_incompat(info, RAID56);
4131 #define BTRFS_MAX_DEVS(r) ((BTRFS_LEAF_DATA_SIZE(r) \
4132 - sizeof(struct btrfs_item) \
4133 - sizeof(struct btrfs_chunk)) \
4134 / sizeof(struct btrfs_stripe) + 1)
4136 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4137 - 2 * sizeof(struct btrfs_disk_key) \
4138 - 2 * sizeof(struct btrfs_chunk)) \
4139 / sizeof(struct btrfs_stripe) + 1)
4141 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4142 struct btrfs_root *extent_root, u64 start,
4145 struct btrfs_fs_info *info = extent_root->fs_info;
4146 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4147 struct list_head *cur;
4148 struct map_lookup *map = NULL;
4149 struct extent_map_tree *em_tree;
4150 struct extent_map *em;
4151 struct btrfs_device_info *devices_info = NULL;
4153 int num_stripes; /* total number of stripes to allocate */
4154 int data_stripes; /* number of stripes that count for
4156 int sub_stripes; /* sub_stripes info for map */
4157 int dev_stripes; /* stripes per dev */
4158 int devs_max; /* max devs to use */
4159 int devs_min; /* min devs needed */
4160 int devs_increment; /* ndevs has to be a multiple of this */
4161 int ncopies; /* how many copies to data has */
4163 u64 max_stripe_size;
4167 u64 raid_stripe_len = BTRFS_STRIPE_LEN;
4173 BUG_ON(!alloc_profile_is_valid(type, 0));
4175 if (list_empty(&fs_devices->alloc_list))
4178 index = __get_raid_index(type);
4180 sub_stripes = btrfs_raid_array[index].sub_stripes;
4181 dev_stripes = btrfs_raid_array[index].dev_stripes;
4182 devs_max = btrfs_raid_array[index].devs_max;
4183 devs_min = btrfs_raid_array[index].devs_min;
4184 devs_increment = btrfs_raid_array[index].devs_increment;
4185 ncopies = btrfs_raid_array[index].ncopies;
4187 if (type & BTRFS_BLOCK_GROUP_DATA) {
4188 max_stripe_size = 1024 * 1024 * 1024;
4189 max_chunk_size = 10 * max_stripe_size;
4191 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4192 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4193 /* for larger filesystems, use larger metadata chunks */
4194 if (fs_devices->total_rw_bytes > 50ULL * 1024 * 1024 * 1024)
4195 max_stripe_size = 1024 * 1024 * 1024;
4197 max_stripe_size = 256 * 1024 * 1024;
4198 max_chunk_size = max_stripe_size;
4200 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4201 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4202 max_stripe_size = 32 * 1024 * 1024;
4203 max_chunk_size = 2 * max_stripe_size;
4205 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4207 btrfs_err(info, "invalid chunk type 0x%llx requested",
4212 /* we don't want a chunk larger than 10% of writeable space */
4213 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4216 devices_info = kzalloc(sizeof(*devices_info) * fs_devices->rw_devices,
4221 cur = fs_devices->alloc_list.next;
4224 * in the first pass through the devices list, we gather information
4225 * about the available holes on each device.
4228 while (cur != &fs_devices->alloc_list) {
4229 struct btrfs_device *device;
4233 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
4237 if (!device->writeable) {
4239 "BTRFS: read-only device in alloc_list\n");
4243 if (!device->in_fs_metadata ||
4244 device->is_tgtdev_for_dev_replace)
4247 if (device->total_bytes > device->bytes_used)
4248 total_avail = device->total_bytes - device->bytes_used;
4252 /* If there is no space on this device, skip it. */
4253 if (total_avail == 0)
4256 ret = find_free_dev_extent(trans, device,
4257 max_stripe_size * dev_stripes,
4258 &dev_offset, &max_avail);
4259 if (ret && ret != -ENOSPC)
4263 max_avail = max_stripe_size * dev_stripes;
4265 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
4268 if (ndevs == fs_devices->rw_devices) {
4269 WARN(1, "%s: found more than %llu devices\n",
4270 __func__, fs_devices->rw_devices);
4273 devices_info[ndevs].dev_offset = dev_offset;
4274 devices_info[ndevs].max_avail = max_avail;
4275 devices_info[ndevs].total_avail = total_avail;
4276 devices_info[ndevs].dev = device;
4281 * now sort the devices by hole size / available space
4283 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4284 btrfs_cmp_device_info, NULL);
4286 /* round down to number of usable stripes */
4287 ndevs -= ndevs % devs_increment;
4289 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
4294 if (devs_max && ndevs > devs_max)
4297 * the primary goal is to maximize the number of stripes, so use as many
4298 * devices as possible, even if the stripes are not maximum sized.
4300 stripe_size = devices_info[ndevs-1].max_avail;
4301 num_stripes = ndevs * dev_stripes;
4304 * this will have to be fixed for RAID1 and RAID10 over
4307 data_stripes = num_stripes / ncopies;
4309 if (type & BTRFS_BLOCK_GROUP_RAID5) {
4310 raid_stripe_len = find_raid56_stripe_len(ndevs - 1,
4311 btrfs_super_stripesize(info->super_copy));
4312 data_stripes = num_stripes - 1;
4314 if (type & BTRFS_BLOCK_GROUP_RAID6) {
4315 raid_stripe_len = find_raid56_stripe_len(ndevs - 2,
4316 btrfs_super_stripesize(info->super_copy));
4317 data_stripes = num_stripes - 2;
4321 * Use the number of data stripes to figure out how big this chunk
4322 * is really going to be in terms of logical address space,
4323 * and compare that answer with the max chunk size
4325 if (stripe_size * data_stripes > max_chunk_size) {
4326 u64 mask = (1ULL << 24) - 1;
4327 stripe_size = max_chunk_size;
4328 do_div(stripe_size, data_stripes);
4330 /* bump the answer up to a 16MB boundary */
4331 stripe_size = (stripe_size + mask) & ~mask;
4333 /* but don't go higher than the limits we found
4334 * while searching for free extents
4336 if (stripe_size > devices_info[ndevs-1].max_avail)
4337 stripe_size = devices_info[ndevs-1].max_avail;
4340 do_div(stripe_size, dev_stripes);
4342 /* align to BTRFS_STRIPE_LEN */
4343 do_div(stripe_size, raid_stripe_len);
4344 stripe_size *= raid_stripe_len;
4346 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4351 map->num_stripes = num_stripes;
4353 for (i = 0; i < ndevs; ++i) {
4354 for (j = 0; j < dev_stripes; ++j) {
4355 int s = i * dev_stripes + j;
4356 map->stripes[s].dev = devices_info[i].dev;
4357 map->stripes[s].physical = devices_info[i].dev_offset +
4361 map->sector_size = extent_root->sectorsize;
4362 map->stripe_len = raid_stripe_len;
4363 map->io_align = raid_stripe_len;
4364 map->io_width = raid_stripe_len;
4366 map->sub_stripes = sub_stripes;
4368 num_bytes = stripe_size * data_stripes;
4370 trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
4372 em = alloc_extent_map();
4378 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4379 em->bdev = (struct block_device *)map;
4381 em->len = num_bytes;
4382 em->block_start = 0;
4383 em->block_len = em->len;
4384 em->orig_block_len = stripe_size;
4386 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4387 write_lock(&em_tree->lock);
4388 ret = add_extent_mapping(em_tree, em, 0);
4390 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4391 atomic_inc(&em->refs);
4393 write_unlock(&em_tree->lock);
4395 free_extent_map(em);
4399 ret = btrfs_make_block_group(trans, extent_root, 0, type,
4400 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4403 goto error_del_extent;
4405 free_extent_map(em);
4406 check_raid56_incompat_flag(extent_root->fs_info, type);
4408 kfree(devices_info);
4412 write_lock(&em_tree->lock);
4413 remove_extent_mapping(em_tree, em);
4414 write_unlock(&em_tree->lock);
4416 /* One for our allocation */
4417 free_extent_map(em);
4418 /* One for the tree reference */
4419 free_extent_map(em);
4421 kfree(devices_info);
4425 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4426 struct btrfs_root *extent_root,
4427 u64 chunk_offset, u64 chunk_size)
4429 struct btrfs_key key;
4430 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
4431 struct btrfs_device *device;
4432 struct btrfs_chunk *chunk;
4433 struct btrfs_stripe *stripe;
4434 struct extent_map_tree *em_tree;
4435 struct extent_map *em;
4436 struct map_lookup *map;
4443 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4444 read_lock(&em_tree->lock);
4445 em = lookup_extent_mapping(em_tree, chunk_offset, chunk_size);
4446 read_unlock(&em_tree->lock);
4449 btrfs_crit(extent_root->fs_info, "unable to find logical "
4450 "%Lu len %Lu", chunk_offset, chunk_size);
4454 if (em->start != chunk_offset || em->len != chunk_size) {
4455 btrfs_crit(extent_root->fs_info, "found a bad mapping, wanted"
4456 " %Lu-%Lu, found %Lu-%Lu", chunk_offset,
4457 chunk_size, em->start, em->len);
4458 free_extent_map(em);
4462 map = (struct map_lookup *)em->bdev;
4463 item_size = btrfs_chunk_item_size(map->num_stripes);
4464 stripe_size = em->orig_block_len;
4466 chunk = kzalloc(item_size, GFP_NOFS);
4472 for (i = 0; i < map->num_stripes; i++) {
4473 device = map->stripes[i].dev;
4474 dev_offset = map->stripes[i].physical;
4476 device->bytes_used += stripe_size;
4477 ret = btrfs_update_device(trans, device);
4480 ret = btrfs_alloc_dev_extent(trans, device,
4481 chunk_root->root_key.objectid,
4482 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4483 chunk_offset, dev_offset,
4489 spin_lock(&extent_root->fs_info->free_chunk_lock);
4490 extent_root->fs_info->free_chunk_space -= (stripe_size *
4492 spin_unlock(&extent_root->fs_info->free_chunk_lock);
4494 stripe = &chunk->stripe;
4495 for (i = 0; i < map->num_stripes; i++) {
4496 device = map->stripes[i].dev;
4497 dev_offset = map->stripes[i].physical;
4499 btrfs_set_stack_stripe_devid(stripe, device->devid);
4500 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4501 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4505 btrfs_set_stack_chunk_length(chunk, chunk_size);
4506 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4507 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4508 btrfs_set_stack_chunk_type(chunk, map->type);
4509 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4510 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4511 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4512 btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
4513 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
4515 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4516 key.type = BTRFS_CHUNK_ITEM_KEY;
4517 key.offset = chunk_offset;
4519 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4520 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4522 * TODO: Cleanup of inserted chunk root in case of
4525 ret = btrfs_add_system_chunk(chunk_root, &key, chunk,
4531 free_extent_map(em);
4536 * Chunk allocation falls into two parts. The first part does works
4537 * that make the new allocated chunk useable, but not do any operation
4538 * that modifies the chunk tree. The second part does the works that
4539 * require modifying the chunk tree. This division is important for the
4540 * bootstrap process of adding storage to a seed btrfs.
4542 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4543 struct btrfs_root *extent_root, u64 type)
4547 chunk_offset = find_next_chunk(extent_root->fs_info);
4548 return __btrfs_alloc_chunk(trans, extent_root, chunk_offset, type);
4551 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
4552 struct btrfs_root *root,
4553 struct btrfs_device *device)
4556 u64 sys_chunk_offset;
4558 struct btrfs_fs_info *fs_info = root->fs_info;
4559 struct btrfs_root *extent_root = fs_info->extent_root;
4562 chunk_offset = find_next_chunk(fs_info);
4563 alloc_profile = btrfs_get_alloc_profile(extent_root, 0);
4564 ret = __btrfs_alloc_chunk(trans, extent_root, chunk_offset,
4569 sys_chunk_offset = find_next_chunk(root->fs_info);
4570 alloc_profile = btrfs_get_alloc_profile(fs_info->chunk_root, 0);
4571 ret = __btrfs_alloc_chunk(trans, extent_root, sys_chunk_offset,
4574 btrfs_abort_transaction(trans, root, ret);
4578 ret = btrfs_add_device(trans, fs_info->chunk_root, device);
4580 btrfs_abort_transaction(trans, root, ret);
4585 int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
4587 struct extent_map *em;
4588 struct map_lookup *map;
4589 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4593 read_lock(&map_tree->map_tree.lock);
4594 em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
4595 read_unlock(&map_tree->map_tree.lock);
4599 if (btrfs_test_opt(root, DEGRADED)) {
4600 free_extent_map(em);
4604 map = (struct map_lookup *)em->bdev;
4605 for (i = 0; i < map->num_stripes; i++) {
4606 if (!map->stripes[i].dev->writeable) {
4611 free_extent_map(em);
4615 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
4617 extent_map_tree_init(&tree->map_tree);
4620 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
4622 struct extent_map *em;
4625 write_lock(&tree->map_tree.lock);
4626 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
4628 remove_extent_mapping(&tree->map_tree, em);
4629 write_unlock(&tree->map_tree.lock);
4633 free_extent_map(em);
4634 /* once for the tree */
4635 free_extent_map(em);
4639 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
4641 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
4642 struct extent_map *em;
4643 struct map_lookup *map;
4644 struct extent_map_tree *em_tree = &map_tree->map_tree;
4647 read_lock(&em_tree->lock);
4648 em = lookup_extent_mapping(em_tree, logical, len);
4649 read_unlock(&em_tree->lock);
4652 * We could return errors for these cases, but that could get ugly and
4653 * we'd probably do the same thing which is just not do anything else
4654 * and exit, so return 1 so the callers don't try to use other copies.
4657 btrfs_crit(fs_info, "No mapping for %Lu-%Lu", logical,
4662 if (em->start > logical || em->start + em->len < logical) {
4663 btrfs_crit(fs_info, "Invalid mapping for %Lu-%Lu, got "
4664 "%Lu-%Lu", logical, logical+len, em->start,
4665 em->start + em->len);
4666 free_extent_map(em);
4670 map = (struct map_lookup *)em->bdev;
4671 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
4672 ret = map->num_stripes;
4673 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
4674 ret = map->sub_stripes;
4675 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
4677 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
4681 free_extent_map(em);
4683 btrfs_dev_replace_lock(&fs_info->dev_replace);
4684 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))
4686 btrfs_dev_replace_unlock(&fs_info->dev_replace);
4691 unsigned long btrfs_full_stripe_len(struct btrfs_root *root,
4692 struct btrfs_mapping_tree *map_tree,
4695 struct extent_map *em;
4696 struct map_lookup *map;
4697 struct extent_map_tree *em_tree = &map_tree->map_tree;
4698 unsigned long len = root->sectorsize;
4700 read_lock(&em_tree->lock);
4701 em = lookup_extent_mapping(em_tree, logical, len);
4702 read_unlock(&em_tree->lock);
4705 BUG_ON(em->start > logical || em->start + em->len < logical);
4706 map = (struct map_lookup *)em->bdev;
4707 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4708 BTRFS_BLOCK_GROUP_RAID6)) {
4709 len = map->stripe_len * nr_data_stripes(map);
4711 free_extent_map(em);
4715 int btrfs_is_parity_mirror(struct btrfs_mapping_tree *map_tree,
4716 u64 logical, u64 len, int mirror_num)
4718 struct extent_map *em;
4719 struct map_lookup *map;
4720 struct extent_map_tree *em_tree = &map_tree->map_tree;
4723 read_lock(&em_tree->lock);
4724 em = lookup_extent_mapping(em_tree, logical, len);
4725 read_unlock(&em_tree->lock);
4728 BUG_ON(em->start > logical || em->start + em->len < logical);
4729 map = (struct map_lookup *)em->bdev;
4730 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4731 BTRFS_BLOCK_GROUP_RAID6))
4733 free_extent_map(em);
4737 static int find_live_mirror(struct btrfs_fs_info *fs_info,
4738 struct map_lookup *map, int first, int num,
4739 int optimal, int dev_replace_is_ongoing)
4743 struct btrfs_device *srcdev;
4745 if (dev_replace_is_ongoing &&
4746 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
4747 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
4748 srcdev = fs_info->dev_replace.srcdev;
4753 * try to avoid the drive that is the source drive for a
4754 * dev-replace procedure, only choose it if no other non-missing
4755 * mirror is available
4757 for (tolerance = 0; tolerance < 2; tolerance++) {
4758 if (map->stripes[optimal].dev->bdev &&
4759 (tolerance || map->stripes[optimal].dev != srcdev))
4761 for (i = first; i < first + num; i++) {
4762 if (map->stripes[i].dev->bdev &&
4763 (tolerance || map->stripes[i].dev != srcdev))
4768 /* we couldn't find one that doesn't fail. Just return something
4769 * and the io error handling code will clean up eventually
4774 static inline int parity_smaller(u64 a, u64 b)
4779 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
4780 static void sort_parity_stripes(struct btrfs_bio *bbio, u64 *raid_map)
4782 struct btrfs_bio_stripe s;
4789 for (i = 0; i < bbio->num_stripes - 1; i++) {
4790 if (parity_smaller(raid_map[i], raid_map[i+1])) {
4791 s = bbio->stripes[i];
4793 bbio->stripes[i] = bbio->stripes[i+1];
4794 raid_map[i] = raid_map[i+1];
4795 bbio->stripes[i+1] = s;
4803 static int __btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
4804 u64 logical, u64 *length,
4805 struct btrfs_bio **bbio_ret,
4806 int mirror_num, u64 **raid_map_ret)
4808 struct extent_map *em;
4809 struct map_lookup *map;
4810 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
4811 struct extent_map_tree *em_tree = &map_tree->map_tree;
4814 u64 stripe_end_offset;
4819 u64 *raid_map = NULL;
4825 struct btrfs_bio *bbio = NULL;
4826 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
4827 int dev_replace_is_ongoing = 0;
4828 int num_alloc_stripes;
4829 int patch_the_first_stripe_for_dev_replace = 0;
4830 u64 physical_to_patch_in_first_stripe = 0;
4831 u64 raid56_full_stripe_start = (u64)-1;
4833 read_lock(&em_tree->lock);
4834 em = lookup_extent_mapping(em_tree, logical, *length);
4835 read_unlock(&em_tree->lock);
4838 btrfs_crit(fs_info, "unable to find logical %llu len %llu",
4843 if (em->start > logical || em->start + em->len < logical) {
4844 btrfs_crit(fs_info, "found a bad mapping, wanted %Lu, "
4845 "found %Lu-%Lu", logical, em->start,
4846 em->start + em->len);
4847 free_extent_map(em);
4851 map = (struct map_lookup *)em->bdev;
4852 offset = logical - em->start;
4854 stripe_len = map->stripe_len;
4857 * stripe_nr counts the total number of stripes we have to stride
4858 * to get to this block
4860 do_div(stripe_nr, stripe_len);
4862 stripe_offset = stripe_nr * stripe_len;
4863 BUG_ON(offset < stripe_offset);
4865 /* stripe_offset is the offset of this block in its stripe*/
4866 stripe_offset = offset - stripe_offset;
4868 /* if we're here for raid56, we need to know the stripe aligned start */
4869 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
4870 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
4871 raid56_full_stripe_start = offset;
4873 /* allow a write of a full stripe, but make sure we don't
4874 * allow straddling of stripes
4876 do_div(raid56_full_stripe_start, full_stripe_len);
4877 raid56_full_stripe_start *= full_stripe_len;
4880 if (rw & REQ_DISCARD) {
4881 /* we don't discard raid56 yet */
4883 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
4887 *length = min_t(u64, em->len - offset, *length);
4888 } else if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
4890 /* For writes to RAID[56], allow a full stripeset across all disks.
4891 For other RAID types and for RAID[56] reads, just allow a single
4892 stripe (on a single disk). */
4893 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6) &&
4895 max_len = stripe_len * nr_data_stripes(map) -
4896 (offset - raid56_full_stripe_start);
4898 /* we limit the length of each bio to what fits in a stripe */
4899 max_len = stripe_len - stripe_offset;
4901 *length = min_t(u64, em->len - offset, max_len);
4903 *length = em->len - offset;
4906 /* This is for when we're called from btrfs_merge_bio_hook() and all
4907 it cares about is the length */
4911 btrfs_dev_replace_lock(dev_replace);
4912 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
4913 if (!dev_replace_is_ongoing)
4914 btrfs_dev_replace_unlock(dev_replace);
4916 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
4917 !(rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) &&
4918 dev_replace->tgtdev != NULL) {
4920 * in dev-replace case, for repair case (that's the only
4921 * case where the mirror is selected explicitly when
4922 * calling btrfs_map_block), blocks left of the left cursor
4923 * can also be read from the target drive.
4924 * For REQ_GET_READ_MIRRORS, the target drive is added as
4925 * the last one to the array of stripes. For READ, it also
4926 * needs to be supported using the same mirror number.
4927 * If the requested block is not left of the left cursor,
4928 * EIO is returned. This can happen because btrfs_num_copies()
4929 * returns one more in the dev-replace case.
4931 u64 tmp_length = *length;
4932 struct btrfs_bio *tmp_bbio = NULL;
4933 int tmp_num_stripes;
4934 u64 srcdev_devid = dev_replace->srcdev->devid;
4935 int index_srcdev = 0;
4937 u64 physical_of_found = 0;
4939 ret = __btrfs_map_block(fs_info, REQ_GET_READ_MIRRORS,
4940 logical, &tmp_length, &tmp_bbio, 0, NULL);
4942 WARN_ON(tmp_bbio != NULL);
4946 tmp_num_stripes = tmp_bbio->num_stripes;
4947 if (mirror_num > tmp_num_stripes) {
4949 * REQ_GET_READ_MIRRORS does not contain this
4950 * mirror, that means that the requested area
4951 * is not left of the left cursor
4959 * process the rest of the function using the mirror_num
4960 * of the source drive. Therefore look it up first.
4961 * At the end, patch the device pointer to the one of the
4964 for (i = 0; i < tmp_num_stripes; i++) {
4965 if (tmp_bbio->stripes[i].dev->devid == srcdev_devid) {
4967 * In case of DUP, in order to keep it
4968 * simple, only add the mirror with the
4969 * lowest physical address
4972 physical_of_found <=
4973 tmp_bbio->stripes[i].physical)
4978 tmp_bbio->stripes[i].physical;
4983 mirror_num = index_srcdev + 1;
4984 patch_the_first_stripe_for_dev_replace = 1;
4985 physical_to_patch_in_first_stripe = physical_of_found;
4994 } else if (mirror_num > map->num_stripes) {
5000 stripe_nr_orig = stripe_nr;
5001 stripe_nr_end = ALIGN(offset + *length, map->stripe_len);
5002 do_div(stripe_nr_end, map->stripe_len);
5003 stripe_end_offset = stripe_nr_end * map->stripe_len -
5006 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5007 if (rw & REQ_DISCARD)
5008 num_stripes = min_t(u64, map->num_stripes,
5009 stripe_nr_end - stripe_nr_orig);
5010 stripe_index = do_div(stripe_nr, map->num_stripes);
5011 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5012 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS))
5013 num_stripes = map->num_stripes;
5014 else if (mirror_num)
5015 stripe_index = mirror_num - 1;
5017 stripe_index = find_live_mirror(fs_info, map, 0,
5019 current->pid % map->num_stripes,
5020 dev_replace_is_ongoing);
5021 mirror_num = stripe_index + 1;
5024 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5025 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) {
5026 num_stripes = map->num_stripes;
5027 } else if (mirror_num) {
5028 stripe_index = mirror_num - 1;
5033 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5034 int factor = map->num_stripes / map->sub_stripes;
5036 stripe_index = do_div(stripe_nr, factor);
5037 stripe_index *= map->sub_stripes;
5039 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
5040 num_stripes = map->sub_stripes;
5041 else if (rw & REQ_DISCARD)
5042 num_stripes = min_t(u64, map->sub_stripes *
5043 (stripe_nr_end - stripe_nr_orig),
5045 else if (mirror_num)
5046 stripe_index += mirror_num - 1;
5048 int old_stripe_index = stripe_index;
5049 stripe_index = find_live_mirror(fs_info, map,
5051 map->sub_stripes, stripe_index +
5052 current->pid % map->sub_stripes,
5053 dev_replace_is_ongoing);
5054 mirror_num = stripe_index - old_stripe_index + 1;
5057 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
5058 BTRFS_BLOCK_GROUP_RAID6)) {
5061 if (bbio_ret && ((rw & REQ_WRITE) || mirror_num > 1)
5065 /* push stripe_nr back to the start of the full stripe */
5066 stripe_nr = raid56_full_stripe_start;
5067 do_div(stripe_nr, stripe_len);
5069 stripe_index = do_div(stripe_nr, nr_data_stripes(map));
5071 /* RAID[56] write or recovery. Return all stripes */
5072 num_stripes = map->num_stripes;
5073 max_errors = nr_parity_stripes(map);
5075 raid_map = kmalloc_array(num_stripes, sizeof(u64),
5082 /* Work out the disk rotation on this stripe-set */
5084 rot = do_div(tmp, num_stripes);
5086 /* Fill in the logical address of each stripe */
5087 tmp = stripe_nr * nr_data_stripes(map);
5088 for (i = 0; i < nr_data_stripes(map); i++)
5089 raid_map[(i+rot) % num_stripes] =
5090 em->start + (tmp + i) * map->stripe_len;
5092 raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5093 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5094 raid_map[(i+rot+1) % num_stripes] =
5097 *length = map->stripe_len;
5102 * Mirror #0 or #1 means the original data block.
5103 * Mirror #2 is RAID5 parity block.
5104 * Mirror #3 is RAID6 Q block.
5106 stripe_index = do_div(stripe_nr, nr_data_stripes(map));
5108 stripe_index = nr_data_stripes(map) +
5111 /* We distribute the parity blocks across stripes */
5112 tmp = stripe_nr + stripe_index;
5113 stripe_index = do_div(tmp, map->num_stripes);
5117 * after this do_div call, stripe_nr is the number of stripes
5118 * on this device we have to walk to find the data, and
5119 * stripe_index is the number of our device in the stripe array
5121 stripe_index = do_div(stripe_nr, map->num_stripes);
5122 mirror_num = stripe_index + 1;
5124 BUG_ON(stripe_index >= map->num_stripes);
5126 num_alloc_stripes = num_stripes;
5127 if (dev_replace_is_ongoing) {
5128 if (rw & (REQ_WRITE | REQ_DISCARD))
5129 num_alloc_stripes <<= 1;
5130 if (rw & REQ_GET_READ_MIRRORS)
5131 num_alloc_stripes++;
5133 bbio = kzalloc(btrfs_bio_size(num_alloc_stripes), GFP_NOFS);
5139 atomic_set(&bbio->error, 0);
5141 if (rw & REQ_DISCARD) {
5143 int sub_stripes = 0;
5144 u64 stripes_per_dev = 0;
5145 u32 remaining_stripes = 0;
5146 u32 last_stripe = 0;
5149 (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
5150 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5153 sub_stripes = map->sub_stripes;
5155 factor = map->num_stripes / sub_stripes;
5156 stripes_per_dev = div_u64_rem(stripe_nr_end -
5159 &remaining_stripes);
5160 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5161 last_stripe *= sub_stripes;
5164 for (i = 0; i < num_stripes; i++) {
5165 bbio->stripes[i].physical =
5166 map->stripes[stripe_index].physical +
5167 stripe_offset + stripe_nr * map->stripe_len;
5168 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5170 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5171 BTRFS_BLOCK_GROUP_RAID10)) {
5172 bbio->stripes[i].length = stripes_per_dev *
5175 if (i / sub_stripes < remaining_stripes)
5176 bbio->stripes[i].length +=
5180 * Special for the first stripe and
5183 * |-------|...|-------|
5187 if (i < sub_stripes)
5188 bbio->stripes[i].length -=
5191 if (stripe_index >= last_stripe &&
5192 stripe_index <= (last_stripe +
5194 bbio->stripes[i].length -=
5197 if (i == sub_stripes - 1)
5200 bbio->stripes[i].length = *length;
5203 if (stripe_index == map->num_stripes) {
5204 /* This could only happen for RAID0/10 */
5210 for (i = 0; i < num_stripes; i++) {
5211 bbio->stripes[i].physical =
5212 map->stripes[stripe_index].physical +
5214 stripe_nr * map->stripe_len;
5215 bbio->stripes[i].dev =
5216 map->stripes[stripe_index].dev;
5221 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS)) {
5222 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5223 BTRFS_BLOCK_GROUP_RAID10 |
5224 BTRFS_BLOCK_GROUP_RAID5 |
5225 BTRFS_BLOCK_GROUP_DUP)) {
5227 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5232 if (dev_replace_is_ongoing && (rw & (REQ_WRITE | REQ_DISCARD)) &&
5233 dev_replace->tgtdev != NULL) {
5234 int index_where_to_add;
5235 u64 srcdev_devid = dev_replace->srcdev->devid;
5238 * duplicate the write operations while the dev replace
5239 * procedure is running. Since the copying of the old disk
5240 * to the new disk takes place at run time while the
5241 * filesystem is mounted writable, the regular write
5242 * operations to the old disk have to be duplicated to go
5243 * to the new disk as well.
5244 * Note that device->missing is handled by the caller, and
5245 * that the write to the old disk is already set up in the
5248 index_where_to_add = num_stripes;
5249 for (i = 0; i < num_stripes; i++) {
5250 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5251 /* write to new disk, too */
5252 struct btrfs_bio_stripe *new =
5253 bbio->stripes + index_where_to_add;
5254 struct btrfs_bio_stripe *old =
5257 new->physical = old->physical;
5258 new->length = old->length;
5259 new->dev = dev_replace->tgtdev;
5260 index_where_to_add++;
5264 num_stripes = index_where_to_add;
5265 } else if (dev_replace_is_ongoing && (rw & REQ_GET_READ_MIRRORS) &&
5266 dev_replace->tgtdev != NULL) {
5267 u64 srcdev_devid = dev_replace->srcdev->devid;
5268 int index_srcdev = 0;
5270 u64 physical_of_found = 0;
5273 * During the dev-replace procedure, the target drive can
5274 * also be used to read data in case it is needed to repair
5275 * a corrupt block elsewhere. This is possible if the
5276 * requested area is left of the left cursor. In this area,
5277 * the target drive is a full copy of the source drive.
5279 for (i = 0; i < num_stripes; i++) {
5280 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5282 * In case of DUP, in order to keep it
5283 * simple, only add the mirror with the
5284 * lowest physical address
5287 physical_of_found <=
5288 bbio->stripes[i].physical)
5292 physical_of_found = bbio->stripes[i].physical;
5296 u64 length = map->stripe_len;
5298 if (physical_of_found + length <=
5299 dev_replace->cursor_left) {
5300 struct btrfs_bio_stripe *tgtdev_stripe =
5301 bbio->stripes + num_stripes;
5303 tgtdev_stripe->physical = physical_of_found;
5304 tgtdev_stripe->length =
5305 bbio->stripes[index_srcdev].length;
5306 tgtdev_stripe->dev = dev_replace->tgtdev;
5314 bbio->num_stripes = num_stripes;
5315 bbio->max_errors = max_errors;
5316 bbio->mirror_num = mirror_num;
5319 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5320 * mirror_num == num_stripes + 1 && dev_replace target drive is
5321 * available as a mirror
5323 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5324 WARN_ON(num_stripes > 1);
5325 bbio->stripes[0].dev = dev_replace->tgtdev;
5326 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5327 bbio->mirror_num = map->num_stripes + 1;
5330 sort_parity_stripes(bbio, raid_map);
5331 *raid_map_ret = raid_map;
5334 if (dev_replace_is_ongoing)
5335 btrfs_dev_replace_unlock(dev_replace);
5336 free_extent_map(em);
5340 int btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
5341 u64 logical, u64 *length,
5342 struct btrfs_bio **bbio_ret, int mirror_num)
5344 return __btrfs_map_block(fs_info, rw, logical, length, bbio_ret,
5348 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
5349 u64 chunk_start, u64 physical, u64 devid,
5350 u64 **logical, int *naddrs, int *stripe_len)
5352 struct extent_map_tree *em_tree = &map_tree->map_tree;
5353 struct extent_map *em;
5354 struct map_lookup *map;
5362 read_lock(&em_tree->lock);
5363 em = lookup_extent_mapping(em_tree, chunk_start, 1);
5364 read_unlock(&em_tree->lock);
5367 printk(KERN_ERR "BTRFS: couldn't find em for chunk %Lu\n",
5372 if (em->start != chunk_start) {
5373 printk(KERN_ERR "BTRFS: bad chunk start, em=%Lu, wanted=%Lu\n",
5374 em->start, chunk_start);
5375 free_extent_map(em);
5378 map = (struct map_lookup *)em->bdev;
5381 rmap_len = map->stripe_len;
5383 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5384 do_div(length, map->num_stripes / map->sub_stripes);
5385 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5386 do_div(length, map->num_stripes);
5387 else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
5388 BTRFS_BLOCK_GROUP_RAID6)) {
5389 do_div(length, nr_data_stripes(map));
5390 rmap_len = map->stripe_len * nr_data_stripes(map);
5393 buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
5394 BUG_ON(!buf); /* -ENOMEM */
5396 for (i = 0; i < map->num_stripes; i++) {
5397 if (devid && map->stripes[i].dev->devid != devid)
5399 if (map->stripes[i].physical > physical ||
5400 map->stripes[i].physical + length <= physical)
5403 stripe_nr = physical - map->stripes[i].physical;
5404 do_div(stripe_nr, map->stripe_len);
5406 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5407 stripe_nr = stripe_nr * map->num_stripes + i;
5408 do_div(stripe_nr, map->sub_stripes);
5409 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5410 stripe_nr = stripe_nr * map->num_stripes + i;
5411 } /* else if RAID[56], multiply by nr_data_stripes().
5412 * Alternatively, just use rmap_len below instead of
5413 * map->stripe_len */
5415 bytenr = chunk_start + stripe_nr * rmap_len;
5416 WARN_ON(nr >= map->num_stripes);
5417 for (j = 0; j < nr; j++) {
5418 if (buf[j] == bytenr)
5422 WARN_ON(nr >= map->num_stripes);
5429 *stripe_len = rmap_len;
5431 free_extent_map(em);
5435 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio, int err)
5437 if (likely(bbio->flags & BTRFS_BIO_ORIG_BIO_SUBMITTED))
5438 bio_endio_nodec(bio, err);
5440 bio_endio(bio, err);
5444 static void btrfs_end_bio(struct bio *bio, int err)
5446 struct btrfs_bio *bbio = bio->bi_private;
5447 struct btrfs_device *dev = bbio->stripes[0].dev;
5448 int is_orig_bio = 0;
5451 atomic_inc(&bbio->error);
5452 if (err == -EIO || err == -EREMOTEIO) {
5453 unsigned int stripe_index =
5454 btrfs_io_bio(bio)->stripe_index;
5456 BUG_ON(stripe_index >= bbio->num_stripes);
5457 dev = bbio->stripes[stripe_index].dev;
5459 if (bio->bi_rw & WRITE)
5460 btrfs_dev_stat_inc(dev,
5461 BTRFS_DEV_STAT_WRITE_ERRS);
5463 btrfs_dev_stat_inc(dev,
5464 BTRFS_DEV_STAT_READ_ERRS);
5465 if ((bio->bi_rw & WRITE_FLUSH) == WRITE_FLUSH)
5466 btrfs_dev_stat_inc(dev,
5467 BTRFS_DEV_STAT_FLUSH_ERRS);
5468 btrfs_dev_stat_print_on_error(dev);
5473 if (bio == bbio->orig_bio)
5476 btrfs_bio_counter_dec(bbio->fs_info);
5478 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5481 bio = bbio->orig_bio;
5484 bio->bi_private = bbio->private;
5485 bio->bi_end_io = bbio->end_io;
5486 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5487 /* only send an error to the higher layers if it is
5488 * beyond the tolerance of the btrfs bio
5490 if (atomic_read(&bbio->error) > bbio->max_errors) {
5494 * this bio is actually up to date, we didn't
5495 * go over the max number of errors
5497 set_bit(BIO_UPTODATE, &bio->bi_flags);
5501 btrfs_end_bbio(bbio, bio, err);
5502 } else if (!is_orig_bio) {
5508 * see run_scheduled_bios for a description of why bios are collected for
5511 * This will add one bio to the pending list for a device and make sure
5512 * the work struct is scheduled.
5514 static noinline void btrfs_schedule_bio(struct btrfs_root *root,
5515 struct btrfs_device *device,
5516 int rw, struct bio *bio)
5518 int should_queue = 1;
5519 struct btrfs_pending_bios *pending_bios;
5521 if (device->missing || !device->bdev) {
5522 bio_endio(bio, -EIO);
5526 /* don't bother with additional async steps for reads, right now */
5527 if (!(rw & REQ_WRITE)) {
5529 btrfsic_submit_bio(rw, bio);
5535 * nr_async_bios allows us to reliably return congestion to the
5536 * higher layers. Otherwise, the async bio makes it appear we have
5537 * made progress against dirty pages when we've really just put it
5538 * on a queue for later
5540 atomic_inc(&root->fs_info->nr_async_bios);
5541 WARN_ON(bio->bi_next);
5542 bio->bi_next = NULL;
5545 spin_lock(&device->io_lock);
5546 if (bio->bi_rw & REQ_SYNC)
5547 pending_bios = &device->pending_sync_bios;
5549 pending_bios = &device->pending_bios;
5551 if (pending_bios->tail)
5552 pending_bios->tail->bi_next = bio;
5554 pending_bios->tail = bio;
5555 if (!pending_bios->head)
5556 pending_bios->head = bio;
5557 if (device->running_pending)
5560 spin_unlock(&device->io_lock);
5563 btrfs_queue_work(root->fs_info->submit_workers,
5567 static int bio_size_ok(struct block_device *bdev, struct bio *bio,
5570 struct bio_vec *prev;
5571 struct request_queue *q = bdev_get_queue(bdev);
5572 unsigned int max_sectors = queue_max_sectors(q);
5573 struct bvec_merge_data bvm = {
5575 .bi_sector = sector,
5576 .bi_rw = bio->bi_rw,
5579 if (WARN_ON(bio->bi_vcnt == 0))
5582 prev = &bio->bi_io_vec[bio->bi_vcnt - 1];
5583 if (bio_sectors(bio) > max_sectors)
5586 if (!q->merge_bvec_fn)
5589 bvm.bi_size = bio->bi_iter.bi_size - prev->bv_len;
5590 if (q->merge_bvec_fn(q, &bvm, prev) < prev->bv_len)
5595 static void submit_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5596 struct bio *bio, u64 physical, int dev_nr,
5599 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
5601 bio->bi_private = bbio;
5602 btrfs_io_bio(bio)->stripe_index = dev_nr;
5603 bio->bi_end_io = btrfs_end_bio;
5604 bio->bi_iter.bi_sector = physical >> 9;
5607 struct rcu_string *name;
5610 name = rcu_dereference(dev->name);
5611 pr_debug("btrfs_map_bio: rw %d, sector=%llu, dev=%lu "
5612 "(%s id %llu), size=%u\n", rw,
5613 (u64)bio->bi_sector, (u_long)dev->bdev->bd_dev,
5614 name->str, dev->devid, bio->bi_size);
5618 bio->bi_bdev = dev->bdev;
5620 btrfs_bio_counter_inc_noblocked(root->fs_info);
5623 btrfs_schedule_bio(root, dev, rw, bio);
5625 btrfsic_submit_bio(rw, bio);
5628 static int breakup_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5629 struct bio *first_bio, struct btrfs_device *dev,
5630 int dev_nr, int rw, int async)
5632 struct bio_vec *bvec = first_bio->bi_io_vec;
5634 int nr_vecs = bio_get_nr_vecs(dev->bdev);
5635 u64 physical = bbio->stripes[dev_nr].physical;
5638 bio = btrfs_bio_alloc(dev->bdev, physical >> 9, nr_vecs, GFP_NOFS);
5642 while (bvec <= (first_bio->bi_io_vec + first_bio->bi_vcnt - 1)) {
5643 if (bio_add_page(bio, bvec->bv_page, bvec->bv_len,
5644 bvec->bv_offset) < bvec->bv_len) {
5645 u64 len = bio->bi_iter.bi_size;
5647 atomic_inc(&bbio->stripes_pending);
5648 submit_stripe_bio(root, bbio, bio, physical, dev_nr,
5656 submit_stripe_bio(root, bbio, bio, physical, dev_nr, rw, async);
5660 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
5662 atomic_inc(&bbio->error);
5663 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5664 /* Shoud be the original bio. */
5665 WARN_ON(bio != bbio->orig_bio);
5667 bio->bi_private = bbio->private;
5668 bio->bi_end_io = bbio->end_io;
5669 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5670 bio->bi_iter.bi_sector = logical >> 9;
5672 btrfs_end_bbio(bbio, bio, -EIO);
5676 int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
5677 int mirror_num, int async_submit)
5679 struct btrfs_device *dev;
5680 struct bio *first_bio = bio;
5681 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
5684 u64 *raid_map = NULL;
5688 struct btrfs_bio *bbio = NULL;
5690 length = bio->bi_iter.bi_size;
5691 map_length = length;
5693 btrfs_bio_counter_inc_blocked(root->fs_info);
5694 ret = __btrfs_map_block(root->fs_info, rw, logical, &map_length, &bbio,
5695 mirror_num, &raid_map);
5697 btrfs_bio_counter_dec(root->fs_info);
5701 total_devs = bbio->num_stripes;
5702 bbio->orig_bio = first_bio;
5703 bbio->private = first_bio->bi_private;
5704 bbio->end_io = first_bio->bi_end_io;
5705 bbio->fs_info = root->fs_info;
5706 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
5709 /* In this case, map_length has been set to the length of
5710 a single stripe; not the whole write */
5712 ret = raid56_parity_write(root, bio, bbio,
5713 raid_map, map_length);
5715 ret = raid56_parity_recover(root, bio, bbio,
5716 raid_map, map_length,
5720 * FIXME, replace dosen't support raid56 yet, please fix
5723 btrfs_bio_counter_dec(root->fs_info);
5727 if (map_length < length) {
5728 btrfs_crit(root->fs_info, "mapping failed logical %llu bio len %llu len %llu",
5729 logical, length, map_length);
5733 while (dev_nr < total_devs) {
5734 dev = bbio->stripes[dev_nr].dev;
5735 if (!dev || !dev->bdev || (rw & WRITE && !dev->writeable)) {
5736 bbio_error(bbio, first_bio, logical);
5742 * Check and see if we're ok with this bio based on it's size
5743 * and offset with the given device.
5745 if (!bio_size_ok(dev->bdev, first_bio,
5746 bbio->stripes[dev_nr].physical >> 9)) {
5747 ret = breakup_stripe_bio(root, bbio, first_bio, dev,
5748 dev_nr, rw, async_submit);
5754 if (dev_nr < total_devs - 1) {
5755 bio = btrfs_bio_clone(first_bio, GFP_NOFS);
5756 BUG_ON(!bio); /* -ENOMEM */
5759 bbio->flags |= BTRFS_BIO_ORIG_BIO_SUBMITTED;
5762 submit_stripe_bio(root, bbio, bio,
5763 bbio->stripes[dev_nr].physical, dev_nr, rw,
5767 btrfs_bio_counter_dec(root->fs_info);
5771 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
5774 struct btrfs_device *device;
5775 struct btrfs_fs_devices *cur_devices;
5777 cur_devices = fs_info->fs_devices;
5778 while (cur_devices) {
5780 !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
5781 device = __find_device(&cur_devices->devices,
5786 cur_devices = cur_devices->seed;
5791 static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
5792 u64 devid, u8 *dev_uuid)
5794 struct btrfs_device *device;
5795 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
5797 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
5801 list_add(&device->dev_list, &fs_devices->devices);
5802 device->fs_devices = fs_devices;
5803 fs_devices->num_devices++;
5805 device->missing = 1;
5806 fs_devices->missing_devices++;
5812 * btrfs_alloc_device - allocate struct btrfs_device
5813 * @fs_info: used only for generating a new devid, can be NULL if
5814 * devid is provided (i.e. @devid != NULL).
5815 * @devid: a pointer to devid for this device. If NULL a new devid
5817 * @uuid: a pointer to UUID for this device. If NULL a new UUID
5820 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
5821 * on error. Returned struct is not linked onto any lists and can be
5822 * destroyed with kfree() right away.
5824 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
5828 struct btrfs_device *dev;
5831 if (WARN_ON(!devid && !fs_info))
5832 return ERR_PTR(-EINVAL);
5834 dev = __alloc_device();
5843 ret = find_next_devid(fs_info, &tmp);
5846 return ERR_PTR(ret);
5852 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
5854 generate_random_uuid(dev->uuid);
5856 btrfs_init_work(&dev->work, btrfs_submit_helper,
5857 pending_bios_fn, NULL, NULL);
5862 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
5863 struct extent_buffer *leaf,
5864 struct btrfs_chunk *chunk)
5866 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
5867 struct map_lookup *map;
5868 struct extent_map *em;
5872 u8 uuid[BTRFS_UUID_SIZE];
5877 logical = key->offset;
5878 length = btrfs_chunk_length(leaf, chunk);
5880 read_lock(&map_tree->map_tree.lock);
5881 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
5882 read_unlock(&map_tree->map_tree.lock);
5884 /* already mapped? */
5885 if (em && em->start <= logical && em->start + em->len > logical) {
5886 free_extent_map(em);
5889 free_extent_map(em);
5892 em = alloc_extent_map();
5895 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
5896 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
5898 free_extent_map(em);
5902 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5903 em->bdev = (struct block_device *)map;
5904 em->start = logical;
5907 em->block_start = 0;
5908 em->block_len = em->len;
5910 map->num_stripes = num_stripes;
5911 map->io_width = btrfs_chunk_io_width(leaf, chunk);
5912 map->io_align = btrfs_chunk_io_align(leaf, chunk);
5913 map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
5914 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
5915 map->type = btrfs_chunk_type(leaf, chunk);
5916 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
5917 for (i = 0; i < num_stripes; i++) {
5918 map->stripes[i].physical =
5919 btrfs_stripe_offset_nr(leaf, chunk, i);
5920 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
5921 read_extent_buffer(leaf, uuid, (unsigned long)
5922 btrfs_stripe_dev_uuid_nr(chunk, i),
5924 map->stripes[i].dev = btrfs_find_device(root->fs_info, devid,
5926 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
5927 free_extent_map(em);
5930 if (!map->stripes[i].dev) {
5931 map->stripes[i].dev =
5932 add_missing_dev(root, devid, uuid);
5933 if (!map->stripes[i].dev) {
5934 free_extent_map(em);
5938 map->stripes[i].dev->in_fs_metadata = 1;
5941 write_lock(&map_tree->map_tree.lock);
5942 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
5943 write_unlock(&map_tree->map_tree.lock);
5944 BUG_ON(ret); /* Tree corruption */
5945 free_extent_map(em);
5950 static void fill_device_from_item(struct extent_buffer *leaf,
5951 struct btrfs_dev_item *dev_item,
5952 struct btrfs_device *device)
5956 device->devid = btrfs_device_id(leaf, dev_item);
5957 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
5958 device->total_bytes = device->disk_total_bytes;
5959 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
5960 device->type = btrfs_device_type(leaf, dev_item);
5961 device->io_align = btrfs_device_io_align(leaf, dev_item);
5962 device->io_width = btrfs_device_io_width(leaf, dev_item);
5963 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
5964 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
5965 device->is_tgtdev_for_dev_replace = 0;
5967 ptr = btrfs_device_uuid(dev_item);
5968 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
5971 static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
5973 struct btrfs_fs_devices *fs_devices;
5976 BUG_ON(!mutex_is_locked(&uuid_mutex));
5978 fs_devices = root->fs_info->fs_devices->seed;
5979 while (fs_devices) {
5980 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
5984 fs_devices = fs_devices->seed;
5987 fs_devices = find_fsid(fsid);
5993 fs_devices = clone_fs_devices(fs_devices);
5994 if (IS_ERR(fs_devices)) {
5995 ret = PTR_ERR(fs_devices);
5999 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
6000 root->fs_info->bdev_holder);
6002 free_fs_devices(fs_devices);
6006 if (!fs_devices->seeding) {
6007 __btrfs_close_devices(fs_devices);
6008 free_fs_devices(fs_devices);
6013 fs_devices->seed = root->fs_info->fs_devices->seed;
6014 root->fs_info->fs_devices->seed = fs_devices;
6019 static int read_one_dev(struct btrfs_root *root,
6020 struct extent_buffer *leaf,
6021 struct btrfs_dev_item *dev_item)
6023 struct btrfs_device *device;
6026 u8 fs_uuid[BTRFS_UUID_SIZE];
6027 u8 dev_uuid[BTRFS_UUID_SIZE];
6029 devid = btrfs_device_id(leaf, dev_item);
6030 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6032 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6035 if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
6036 ret = open_seed_devices(root, fs_uuid);
6037 if (ret && !btrfs_test_opt(root, DEGRADED))
6041 device = btrfs_find_device(root->fs_info, devid, dev_uuid, fs_uuid);
6042 if (!device || !device->bdev) {
6043 if (!btrfs_test_opt(root, DEGRADED))
6047 btrfs_warn(root->fs_info, "devid %llu missing", devid);
6048 device = add_missing_dev(root, devid, dev_uuid);
6051 } else if (!device->missing) {
6053 * this happens when a device that was properly setup
6054 * in the device info lists suddenly goes bad.
6055 * device->bdev is NULL, and so we have to set
6056 * device->missing to one here
6058 root->fs_info->fs_devices->missing_devices++;
6059 device->missing = 1;
6063 if (device->fs_devices != root->fs_info->fs_devices) {
6064 BUG_ON(device->writeable);
6065 if (device->generation !=
6066 btrfs_device_generation(leaf, dev_item))
6070 fill_device_from_item(leaf, dev_item, device);
6071 device->in_fs_metadata = 1;
6072 if (device->writeable && !device->is_tgtdev_for_dev_replace) {
6073 device->fs_devices->total_rw_bytes += device->total_bytes;
6074 spin_lock(&root->fs_info->free_chunk_lock);
6075 root->fs_info->free_chunk_space += device->total_bytes -
6077 spin_unlock(&root->fs_info->free_chunk_lock);
6083 int btrfs_read_sys_array(struct btrfs_root *root)
6085 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
6086 struct extent_buffer *sb;
6087 struct btrfs_disk_key *disk_key;
6088 struct btrfs_chunk *chunk;
6090 unsigned long sb_ptr;
6096 struct btrfs_key key;
6098 sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
6099 BTRFS_SUPER_INFO_SIZE);
6102 btrfs_set_buffer_uptodate(sb);
6103 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6105 * The sb extent buffer is artifical and just used to read the system array.
6106 * btrfs_set_buffer_uptodate() call does not properly mark all it's
6107 * pages up-to-date when the page is larger: extent does not cover the
6108 * whole page and consequently check_page_uptodate does not find all
6109 * the page's extents up-to-date (the hole beyond sb),
6110 * write_extent_buffer then triggers a WARN_ON.
6112 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6113 * but sb spans only this function. Add an explicit SetPageUptodate call
6114 * to silence the warning eg. on PowerPC 64.
6116 if (PAGE_CACHE_SIZE > BTRFS_SUPER_INFO_SIZE)
6117 SetPageUptodate(sb->pages[0]);
6119 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6120 array_size = btrfs_super_sys_array_size(super_copy);
6122 ptr = super_copy->sys_chunk_array;
6123 sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
6126 while (cur < array_size) {
6127 disk_key = (struct btrfs_disk_key *)ptr;
6128 btrfs_disk_key_to_cpu(&key, disk_key);
6130 len = sizeof(*disk_key); ptr += len;
6134 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6135 chunk = (struct btrfs_chunk *)sb_ptr;
6136 ret = read_one_chunk(root, &key, sb, chunk);
6139 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6140 len = btrfs_chunk_item_size(num_stripes);
6149 free_extent_buffer(sb);
6153 int btrfs_read_chunk_tree(struct btrfs_root *root)
6155 struct btrfs_path *path;
6156 struct extent_buffer *leaf;
6157 struct btrfs_key key;
6158 struct btrfs_key found_key;
6162 root = root->fs_info->chunk_root;
6164 path = btrfs_alloc_path();
6168 mutex_lock(&uuid_mutex);
6172 * Read all device items, and then all the chunk items. All
6173 * device items are found before any chunk item (their object id
6174 * is smaller than the lowest possible object id for a chunk
6175 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6177 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6180 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6184 leaf = path->nodes[0];
6185 slot = path->slots[0];
6186 if (slot >= btrfs_header_nritems(leaf)) {
6187 ret = btrfs_next_leaf(root, path);
6194 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6195 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6196 struct btrfs_dev_item *dev_item;
6197 dev_item = btrfs_item_ptr(leaf, slot,
6198 struct btrfs_dev_item);
6199 ret = read_one_dev(root, leaf, dev_item);
6202 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6203 struct btrfs_chunk *chunk;
6204 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6205 ret = read_one_chunk(root, &found_key, leaf, chunk);
6213 unlock_chunks(root);
6214 mutex_unlock(&uuid_mutex);
6216 btrfs_free_path(path);
6220 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6222 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6223 struct btrfs_device *device;
6225 while (fs_devices) {
6226 mutex_lock(&fs_devices->device_list_mutex);
6227 list_for_each_entry(device, &fs_devices->devices, dev_list)
6228 device->dev_root = fs_info->dev_root;
6229 mutex_unlock(&fs_devices->device_list_mutex);
6231 fs_devices = fs_devices->seed;
6235 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
6239 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6240 btrfs_dev_stat_reset(dev, i);
6243 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
6245 struct btrfs_key key;
6246 struct btrfs_key found_key;
6247 struct btrfs_root *dev_root = fs_info->dev_root;
6248 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6249 struct extent_buffer *eb;
6252 struct btrfs_device *device;
6253 struct btrfs_path *path = NULL;
6256 path = btrfs_alloc_path();
6262 mutex_lock(&fs_devices->device_list_mutex);
6263 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6265 struct btrfs_dev_stats_item *ptr;
6268 key.type = BTRFS_DEV_STATS_KEY;
6269 key.offset = device->devid;
6270 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
6272 __btrfs_reset_dev_stats(device);
6273 device->dev_stats_valid = 1;
6274 btrfs_release_path(path);
6277 slot = path->slots[0];
6278 eb = path->nodes[0];
6279 btrfs_item_key_to_cpu(eb, &found_key, slot);
6280 item_size = btrfs_item_size_nr(eb, slot);
6282 ptr = btrfs_item_ptr(eb, slot,
6283 struct btrfs_dev_stats_item);
6285 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6286 if (item_size >= (1 + i) * sizeof(__le64))
6287 btrfs_dev_stat_set(device, i,
6288 btrfs_dev_stats_value(eb, ptr, i));
6290 btrfs_dev_stat_reset(device, i);
6293 device->dev_stats_valid = 1;
6294 btrfs_dev_stat_print_on_load(device);
6295 btrfs_release_path(path);
6297 mutex_unlock(&fs_devices->device_list_mutex);
6300 btrfs_free_path(path);
6301 return ret < 0 ? ret : 0;
6304 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
6305 struct btrfs_root *dev_root,
6306 struct btrfs_device *device)
6308 struct btrfs_path *path;
6309 struct btrfs_key key;
6310 struct extent_buffer *eb;
6311 struct btrfs_dev_stats_item *ptr;
6316 key.type = BTRFS_DEV_STATS_KEY;
6317 key.offset = device->devid;
6319 path = btrfs_alloc_path();
6321 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
6323 printk_in_rcu(KERN_WARNING "BTRFS: "
6324 "error %d while searching for dev_stats item for device %s!\n",
6325 ret, rcu_str_deref(device->name));
6330 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
6331 /* need to delete old one and insert a new one */
6332 ret = btrfs_del_item(trans, dev_root, path);
6334 printk_in_rcu(KERN_WARNING "BTRFS: "
6335 "delete too small dev_stats item for device %s failed %d!\n",
6336 rcu_str_deref(device->name), ret);
6343 /* need to insert a new item */
6344 btrfs_release_path(path);
6345 ret = btrfs_insert_empty_item(trans, dev_root, path,
6346 &key, sizeof(*ptr));
6348 printk_in_rcu(KERN_WARNING "BTRFS: "
6349 "insert dev_stats item for device %s failed %d!\n",
6350 rcu_str_deref(device->name), ret);
6355 eb = path->nodes[0];
6356 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
6357 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6358 btrfs_set_dev_stats_value(eb, ptr, i,
6359 btrfs_dev_stat_read(device, i));
6360 btrfs_mark_buffer_dirty(eb);
6363 btrfs_free_path(path);
6368 * called from commit_transaction. Writes all changed device stats to disk.
6370 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
6371 struct btrfs_fs_info *fs_info)
6373 struct btrfs_root *dev_root = fs_info->dev_root;
6374 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6375 struct btrfs_device *device;
6378 mutex_lock(&fs_devices->device_list_mutex);
6379 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6380 if (!device->dev_stats_valid || !device->dev_stats_dirty)
6383 ret = update_dev_stat_item(trans, dev_root, device);
6385 device->dev_stats_dirty = 0;
6387 mutex_unlock(&fs_devices->device_list_mutex);
6392 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
6394 btrfs_dev_stat_inc(dev, index);
6395 btrfs_dev_stat_print_on_error(dev);
6398 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
6400 if (!dev->dev_stats_valid)
6402 printk_ratelimited_in_rcu(KERN_ERR "BTRFS: "
6403 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
6404 rcu_str_deref(dev->name),
6405 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6406 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6407 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6408 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6409 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6412 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
6416 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6417 if (btrfs_dev_stat_read(dev, i) != 0)
6419 if (i == BTRFS_DEV_STAT_VALUES_MAX)
6420 return; /* all values == 0, suppress message */
6422 printk_in_rcu(KERN_INFO "BTRFS: "
6423 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
6424 rcu_str_deref(dev->name),
6425 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6426 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6427 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6428 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6429 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6432 int btrfs_get_dev_stats(struct btrfs_root *root,
6433 struct btrfs_ioctl_get_dev_stats *stats)
6435 struct btrfs_device *dev;
6436 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
6439 mutex_lock(&fs_devices->device_list_mutex);
6440 dev = btrfs_find_device(root->fs_info, stats->devid, NULL, NULL);
6441 mutex_unlock(&fs_devices->device_list_mutex);
6444 btrfs_warn(root->fs_info, "get dev_stats failed, device not found");
6446 } else if (!dev->dev_stats_valid) {
6447 btrfs_warn(root->fs_info, "get dev_stats failed, not yet valid");
6449 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
6450 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6451 if (stats->nr_items > i)
6453 btrfs_dev_stat_read_and_reset(dev, i);
6455 btrfs_dev_stat_reset(dev, i);
6458 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6459 if (stats->nr_items > i)
6460 stats->values[i] = btrfs_dev_stat_read(dev, i);
6462 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
6463 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
6467 int btrfs_scratch_superblock(struct btrfs_device *device)
6469 struct buffer_head *bh;
6470 struct btrfs_super_block *disk_super;
6472 bh = btrfs_read_dev_super(device->bdev);
6475 disk_super = (struct btrfs_super_block *)bh->b_data;
6477 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
6478 set_buffer_dirty(bh);
6479 sync_dirty_buffer(bh);