Linux 3.12.28
[linux/fpc-iii.git] / fs / btrfs / volumes.c
blob7fae00b72283799f9d99f7443e8703a7f5328b77
1 /*
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>
31 #include "compat.h"
32 #include "ctree.h"
33 #include "extent_map.h"
34 #include "disk-io.h"
35 #include "transaction.h"
36 #include "print-tree.h"
37 #include "volumes.h"
38 #include "raid56.h"
39 #include "async-thread.h"
40 #include "check-integrity.h"
41 #include "rcu-string.h"
42 #include "math.h"
43 #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);
71 if (!fs_devs)
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);
80 return fs_devs;
83 /**
84 * alloc_fs_devices - allocate struct btrfs_fs_devices
85 * @fsid: a pointer to UUID for this FS. If NULL a new UUID is
86 * generated.
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();
97 if (IS_ERR(fs_devs))
98 return fs_devs;
100 if (fsid)
101 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
102 else
103 generate_random_uuid(fs_devs->fsid);
105 return fs_devs;
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);
117 kfree(device);
119 kfree(fs_devices);
122 static void btrfs_kobject_uevent(struct block_device *bdev,
123 enum kobject_action action)
125 int ret;
127 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
128 if (ret)
129 pr_warn("Sending event '%d' to kobject: '%s' (%p): failed\n",
130 action,
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);
152 if (!dev)
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);
165 return dev;
168 static noinline struct btrfs_device *__find_device(struct list_head *head,
169 u64 devid, u8 *uuid)
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))) {
176 return dev;
179 return NULL;
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)
188 return fs_devices;
190 return NULL;
193 static int
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)
198 int ret;
200 *bdev = blkdev_get_by_path(device_path, flags, holder);
202 if (IS_ERR(*bdev)) {
203 ret = PTR_ERR(*bdev);
204 printk(KERN_INFO "btrfs: open %s failed\n", device_path);
205 goto error;
208 if (flush)
209 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
210 ret = set_blocksize(*bdev, 4096);
211 if (ret) {
212 blkdev_put(*bdev, flags);
213 goto error;
215 invalidate_bdev(*bdev);
216 *bh = btrfs_read_dev_super(*bdev);
217 if (!*bh) {
218 ret = -EINVAL;
219 blkdev_put(*bdev, flags);
220 goto error;
223 return 0;
225 error:
226 *bdev = NULL;
227 *bh = NULL;
228 return ret;
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;
241 else
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)
258 struct bio *pending;
259 struct backing_dev_info *bdi;
260 struct btrfs_fs_info *fs_info;
261 struct btrfs_pending_bios *pending_bios;
262 struct bio *tail;
263 struct bio *cur;
264 int again = 0;
265 unsigned long num_run;
266 unsigned long batch_run = 0;
267 unsigned long limit;
268 unsigned long last_waited = 0;
269 int force_reg = 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;
286 loop:
287 spin_lock(&device->io_lock);
289 loop_lock:
290 num_run = 0;
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;
299 force_reg = 1;
300 } else {
301 pending_bios = &device->pending_bios;
302 force_reg = 0;
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
315 * schedule_bio code.
317 if (device->pending_sync_bios.head == NULL &&
318 device->pending_bios.head == NULL) {
319 again = 0;
320 device->running_pending = 0;
321 } else {
322 again = 1;
323 device->running_pending = 1;
326 pending_bios->head = NULL;
327 pending_bios->tail = NULL;
329 spin_unlock(&device->io_lock);
331 while (pending) {
333 rmb();
334 /* we want to work on both lists, but do more bios on the
335 * sync list than the regular list
337 if ((num_run > 32 &&
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);
344 goto loop_lock;
347 cur = pending;
348 pending = pending->bi_next;
349 cur->bi_next = NULL;
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
363 * we add more
365 if (pending_bios == &device->pending_sync_bios) {
366 sync_pending = 1;
367 } else if (sync_pending) {
368 blk_finish_plug(&plug);
369 blk_start_plug(&plug);
370 sync_pending = 0;
373 btrfsic_submit_bio(cur->bi_rw, cur);
374 num_run++;
375 batch_run++;
376 if (need_resched())
377 cond_resched();
380 * we made progress, there is more work to do and the bdi
381 * is now congested. Back off and let other work structs
382 * run instead
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) &&
401 (last_waited == 0 ||
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;
410 if (need_resched())
411 cond_resched();
412 continue;
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_requeue_work(&device->work);
420 goto done;
422 /* unplug every 64 requests just for good measure */
423 if (batch_run % 64 == 0) {
424 blk_finish_plug(&plug);
425 blk_start_plug(&plug);
426 sync_pending = 0;
430 cond_resched();
431 if (again)
432 goto loop;
434 spin_lock(&device->io_lock);
435 if (device->pending_bios.head || device->pending_sync_bios.head)
436 goto loop_lock;
437 spin_unlock(&device->io_lock);
439 done:
440 blk_finish_plug(&plug);
443 static void pending_bios_fn(struct btrfs_work *work)
445 struct btrfs_device *device;
447 device = container_of(work, struct btrfs_device, work);
448 run_scheduled_bios(device);
451 static noinline int device_list_add(const char *path,
452 struct btrfs_super_block *disk_super,
453 u64 devid, struct btrfs_fs_devices **fs_devices_ret)
455 struct btrfs_device *device;
456 struct btrfs_fs_devices *fs_devices;
457 struct rcu_string *name;
458 u64 found_transid = btrfs_super_generation(disk_super);
460 fs_devices = find_fsid(disk_super->fsid);
461 if (!fs_devices) {
462 fs_devices = alloc_fs_devices(disk_super->fsid);
463 if (IS_ERR(fs_devices))
464 return PTR_ERR(fs_devices);
466 list_add(&fs_devices->list, &fs_uuids);
467 fs_devices->latest_devid = devid;
468 fs_devices->latest_trans = found_transid;
470 device = NULL;
471 } else {
472 device = __find_device(&fs_devices->devices, devid,
473 disk_super->dev_item.uuid);
475 if (!device) {
476 if (fs_devices->opened)
477 return -EBUSY;
479 device = btrfs_alloc_device(NULL, &devid,
480 disk_super->dev_item.uuid);
481 if (IS_ERR(device)) {
482 /* we can safely leave the fs_devices entry around */
483 return PTR_ERR(device);
486 name = rcu_string_strdup(path, GFP_NOFS);
487 if (!name) {
488 kfree(device);
489 return -ENOMEM;
491 rcu_assign_pointer(device->name, name);
493 mutex_lock(&fs_devices->device_list_mutex);
494 list_add_rcu(&device->dev_list, &fs_devices->devices);
495 fs_devices->num_devices++;
496 mutex_unlock(&fs_devices->device_list_mutex);
498 device->fs_devices = fs_devices;
499 } else if (!device->name || strcmp(device->name->str, path)) {
500 name = rcu_string_strdup(path, GFP_NOFS);
501 if (!name)
502 return -ENOMEM;
503 rcu_string_free(device->name);
504 rcu_assign_pointer(device->name, name);
505 if (device->missing) {
506 fs_devices->missing_devices--;
507 device->missing = 0;
511 if (found_transid > fs_devices->latest_trans) {
512 fs_devices->latest_devid = devid;
513 fs_devices->latest_trans = found_transid;
515 *fs_devices_ret = fs_devices;
516 return 0;
519 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
521 struct btrfs_fs_devices *fs_devices;
522 struct btrfs_device *device;
523 struct btrfs_device *orig_dev;
525 fs_devices = alloc_fs_devices(orig->fsid);
526 if (IS_ERR(fs_devices))
527 return fs_devices;
529 fs_devices->latest_devid = orig->latest_devid;
530 fs_devices->latest_trans = orig->latest_trans;
531 fs_devices->total_devices = orig->total_devices;
533 /* We have held the volume lock, it is safe to get the devices. */
534 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
535 struct rcu_string *name;
537 device = btrfs_alloc_device(NULL, &orig_dev->devid,
538 orig_dev->uuid);
539 if (IS_ERR(device))
540 goto error;
543 * This is ok to do without rcu read locked because we hold the
544 * uuid mutex so nothing we touch in here is going to disappear.
546 name = rcu_string_strdup(orig_dev->name->str, GFP_NOFS);
547 if (!name) {
548 kfree(device);
549 goto error;
551 rcu_assign_pointer(device->name, name);
553 list_add(&device->dev_list, &fs_devices->devices);
554 device->fs_devices = fs_devices;
555 fs_devices->num_devices++;
557 return fs_devices;
558 error:
559 free_fs_devices(fs_devices);
560 return ERR_PTR(-ENOMEM);
563 void btrfs_close_extra_devices(struct btrfs_fs_info *fs_info,
564 struct btrfs_fs_devices *fs_devices, int step)
566 struct btrfs_device *device, *next;
568 struct block_device *latest_bdev = NULL;
569 u64 latest_devid = 0;
570 u64 latest_transid = 0;
572 mutex_lock(&uuid_mutex);
573 again:
574 /* This is the initialized path, it is safe to release the devices. */
575 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
576 if (device->in_fs_metadata) {
577 if (!device->is_tgtdev_for_dev_replace &&
578 (!latest_transid ||
579 device->generation > latest_transid)) {
580 latest_devid = device->devid;
581 latest_transid = device->generation;
582 latest_bdev = device->bdev;
584 continue;
587 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
589 * In the first step, keep the device which has
590 * the correct fsid and the devid that is used
591 * for the dev_replace procedure.
592 * In the second step, the dev_replace state is
593 * read from the device tree and it is known
594 * whether the procedure is really active or
595 * not, which means whether this device is
596 * used or whether it should be removed.
598 if (step == 0 || device->is_tgtdev_for_dev_replace) {
599 continue;
602 if (device->bdev) {
603 blkdev_put(device->bdev, device->mode);
604 device->bdev = NULL;
605 fs_devices->open_devices--;
607 if (device->writeable) {
608 list_del_init(&device->dev_alloc_list);
609 device->writeable = 0;
610 if (!device->is_tgtdev_for_dev_replace)
611 fs_devices->rw_devices--;
613 list_del_init(&device->dev_list);
614 fs_devices->num_devices--;
615 rcu_string_free(device->name);
616 kfree(device);
619 if (fs_devices->seed) {
620 fs_devices = fs_devices->seed;
621 goto again;
624 fs_devices->latest_bdev = latest_bdev;
625 fs_devices->latest_devid = latest_devid;
626 fs_devices->latest_trans = latest_transid;
628 mutex_unlock(&uuid_mutex);
631 static void __free_device(struct work_struct *work)
633 struct btrfs_device *device;
635 device = container_of(work, struct btrfs_device, rcu_work);
637 if (device->bdev)
638 blkdev_put(device->bdev, device->mode);
640 rcu_string_free(device->name);
641 kfree(device);
644 static void free_device(struct rcu_head *head)
646 struct btrfs_device *device;
648 device = container_of(head, struct btrfs_device, rcu);
650 INIT_WORK(&device->rcu_work, __free_device);
651 schedule_work(&device->rcu_work);
654 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
656 struct btrfs_device *device;
658 if (--fs_devices->opened > 0)
659 return 0;
661 mutex_lock(&fs_devices->device_list_mutex);
662 list_for_each_entry(device, &fs_devices->devices, dev_list) {
663 struct btrfs_device *new_device;
664 struct rcu_string *name;
666 if (device->bdev)
667 fs_devices->open_devices--;
669 if (device->writeable && !device->is_tgtdev_for_dev_replace) {
670 list_del_init(&device->dev_alloc_list);
671 fs_devices->rw_devices--;
674 if (device->can_discard)
675 fs_devices->num_can_discard--;
676 if (device->missing)
677 fs_devices->missing_devices--;
679 new_device = btrfs_alloc_device(NULL, &device->devid,
680 device->uuid);
681 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
683 /* Safe because we are under uuid_mutex */
684 if (device->name) {
685 name = rcu_string_strdup(device->name->str, GFP_NOFS);
686 BUG_ON(!name); /* -ENOMEM */
687 rcu_assign_pointer(new_device->name, name);
690 list_replace_rcu(&device->dev_list, &new_device->dev_list);
691 new_device->fs_devices = device->fs_devices;
693 call_rcu(&device->rcu, free_device);
695 mutex_unlock(&fs_devices->device_list_mutex);
697 WARN_ON(fs_devices->open_devices);
698 WARN_ON(fs_devices->rw_devices);
699 fs_devices->opened = 0;
700 fs_devices->seeding = 0;
702 return 0;
705 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
707 struct btrfs_fs_devices *seed_devices = NULL;
708 int ret;
710 mutex_lock(&uuid_mutex);
711 ret = __btrfs_close_devices(fs_devices);
712 if (!fs_devices->opened) {
713 seed_devices = fs_devices->seed;
714 fs_devices->seed = NULL;
716 mutex_unlock(&uuid_mutex);
718 while (seed_devices) {
719 fs_devices = seed_devices;
720 seed_devices = fs_devices->seed;
721 __btrfs_close_devices(fs_devices);
722 free_fs_devices(fs_devices);
725 * Wait for rcu kworkers under __btrfs_close_devices
726 * to finish all blkdev_puts so device is really
727 * free when umount is done.
729 rcu_barrier();
730 return ret;
733 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
734 fmode_t flags, void *holder)
736 struct request_queue *q;
737 struct block_device *bdev;
738 struct list_head *head = &fs_devices->devices;
739 struct btrfs_device *device;
740 struct block_device *latest_bdev = NULL;
741 struct buffer_head *bh;
742 struct btrfs_super_block *disk_super;
743 u64 latest_devid = 0;
744 u64 latest_transid = 0;
745 u64 devid;
746 int seeding = 1;
747 int ret = 0;
749 flags |= FMODE_EXCL;
751 list_for_each_entry(device, head, dev_list) {
752 if (device->bdev)
753 continue;
754 if (!device->name)
755 continue;
757 /* Just open everything we can; ignore failures here */
758 if (btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
759 &bdev, &bh))
760 continue;
762 disk_super = (struct btrfs_super_block *)bh->b_data;
763 devid = btrfs_stack_device_id(&disk_super->dev_item);
764 if (devid != device->devid)
765 goto error_brelse;
767 if (memcmp(device->uuid, disk_super->dev_item.uuid,
768 BTRFS_UUID_SIZE))
769 goto error_brelse;
771 device->generation = btrfs_super_generation(disk_super);
772 if (!latest_transid || device->generation > latest_transid) {
773 latest_devid = devid;
774 latest_transid = device->generation;
775 latest_bdev = bdev;
778 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
779 device->writeable = 0;
780 } else {
781 device->writeable = !bdev_read_only(bdev);
782 seeding = 0;
785 q = bdev_get_queue(bdev);
786 if (blk_queue_discard(q)) {
787 device->can_discard = 1;
788 fs_devices->num_can_discard++;
791 device->bdev = bdev;
792 device->in_fs_metadata = 0;
793 device->mode = flags;
795 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
796 fs_devices->rotating = 1;
798 fs_devices->open_devices++;
799 if (device->writeable &&
800 device->devid != BTRFS_DEV_REPLACE_DEVID) {
801 fs_devices->rw_devices++;
802 list_add(&device->dev_alloc_list,
803 &fs_devices->alloc_list);
805 brelse(bh);
806 continue;
808 error_brelse:
809 brelse(bh);
810 blkdev_put(bdev, flags);
811 continue;
813 if (fs_devices->open_devices == 0) {
814 ret = -EINVAL;
815 goto out;
817 fs_devices->seeding = seeding;
818 fs_devices->opened = 1;
819 fs_devices->latest_bdev = latest_bdev;
820 fs_devices->latest_devid = latest_devid;
821 fs_devices->latest_trans = latest_transid;
822 fs_devices->total_rw_bytes = 0;
823 out:
824 return ret;
827 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
828 fmode_t flags, void *holder)
830 int ret;
832 mutex_lock(&uuid_mutex);
833 if (fs_devices->opened) {
834 fs_devices->opened++;
835 ret = 0;
836 } else {
837 ret = __btrfs_open_devices(fs_devices, flags, holder);
839 mutex_unlock(&uuid_mutex);
840 return ret;
844 * Look for a btrfs signature on a device. This may be called out of the mount path
845 * and we are not allowed to call set_blocksize during the scan. The superblock
846 * is read via pagecache
848 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
849 struct btrfs_fs_devices **fs_devices_ret)
851 struct btrfs_super_block *disk_super;
852 struct block_device *bdev;
853 struct page *page;
854 void *p;
855 int ret = -EINVAL;
856 u64 devid;
857 u64 transid;
858 u64 total_devices;
859 u64 bytenr;
860 pgoff_t index;
863 * we would like to check all the supers, but that would make
864 * a btrfs mount succeed after a mkfs from a different FS.
865 * So, we need to add a special mount option to scan for
866 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
868 bytenr = btrfs_sb_offset(0);
869 flags |= FMODE_EXCL;
870 mutex_lock(&uuid_mutex);
872 bdev = blkdev_get_by_path(path, flags, holder);
874 if (IS_ERR(bdev)) {
875 ret = PTR_ERR(bdev);
876 goto error;
879 /* make sure our super fits in the device */
880 if (bytenr + PAGE_CACHE_SIZE >= i_size_read(bdev->bd_inode))
881 goto error_bdev_put;
883 /* make sure our super fits in the page */
884 if (sizeof(*disk_super) > PAGE_CACHE_SIZE)
885 goto error_bdev_put;
887 /* make sure our super doesn't straddle pages on disk */
888 index = bytenr >> PAGE_CACHE_SHIFT;
889 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_CACHE_SHIFT != index)
890 goto error_bdev_put;
892 /* pull in the page with our super */
893 page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
894 index, GFP_NOFS);
896 if (IS_ERR_OR_NULL(page))
897 goto error_bdev_put;
899 p = kmap(page);
901 /* align our pointer to the offset of the super block */
902 disk_super = p + (bytenr & ~PAGE_CACHE_MASK);
904 if (btrfs_super_bytenr(disk_super) != bytenr ||
905 btrfs_super_magic(disk_super) != BTRFS_MAGIC)
906 goto error_unmap;
908 devid = btrfs_stack_device_id(&disk_super->dev_item);
909 transid = btrfs_super_generation(disk_super);
910 total_devices = btrfs_super_num_devices(disk_super);
912 if (disk_super->label[0]) {
913 if (disk_super->label[BTRFS_LABEL_SIZE - 1])
914 disk_super->label[BTRFS_LABEL_SIZE - 1] = '\0';
915 printk(KERN_INFO "btrfs: device label %s ", disk_super->label);
916 } else {
917 printk(KERN_INFO "btrfs: device fsid %pU ", disk_super->fsid);
920 printk(KERN_CONT "devid %llu transid %llu %s\n", devid, transid, path);
922 ret = device_list_add(path, disk_super, devid, fs_devices_ret);
923 if (!ret && fs_devices_ret)
924 (*fs_devices_ret)->total_devices = total_devices;
926 error_unmap:
927 kunmap(page);
928 page_cache_release(page);
930 error_bdev_put:
931 blkdev_put(bdev, flags);
932 error:
933 mutex_unlock(&uuid_mutex);
934 return ret;
937 /* helper to account the used device space in the range */
938 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
939 u64 end, u64 *length)
941 struct btrfs_key key;
942 struct btrfs_root *root = device->dev_root;
943 struct btrfs_dev_extent *dev_extent;
944 struct btrfs_path *path;
945 u64 extent_end;
946 int ret;
947 int slot;
948 struct extent_buffer *l;
950 *length = 0;
952 if (start >= device->total_bytes || device->is_tgtdev_for_dev_replace)
953 return 0;
955 path = btrfs_alloc_path();
956 if (!path)
957 return -ENOMEM;
958 path->reada = 2;
960 key.objectid = device->devid;
961 key.offset = start;
962 key.type = BTRFS_DEV_EXTENT_KEY;
964 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
965 if (ret < 0)
966 goto out;
967 if (ret > 0) {
968 ret = btrfs_previous_item(root, path, key.objectid, key.type);
969 if (ret < 0)
970 goto out;
973 while (1) {
974 l = path->nodes[0];
975 slot = path->slots[0];
976 if (slot >= btrfs_header_nritems(l)) {
977 ret = btrfs_next_leaf(root, path);
978 if (ret == 0)
979 continue;
980 if (ret < 0)
981 goto out;
983 break;
985 btrfs_item_key_to_cpu(l, &key, slot);
987 if (key.objectid < device->devid)
988 goto next;
990 if (key.objectid > device->devid)
991 break;
993 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
994 goto next;
996 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
997 extent_end = key.offset + btrfs_dev_extent_length(l,
998 dev_extent);
999 if (key.offset <= start && extent_end > end) {
1000 *length = end - start + 1;
1001 break;
1002 } else if (key.offset <= start && extent_end > start)
1003 *length += extent_end - start;
1004 else if (key.offset > start && extent_end <= end)
1005 *length += extent_end - key.offset;
1006 else if (key.offset > start && key.offset <= end) {
1007 *length += end - key.offset + 1;
1008 break;
1009 } else if (key.offset > end)
1010 break;
1012 next:
1013 path->slots[0]++;
1015 ret = 0;
1016 out:
1017 btrfs_free_path(path);
1018 return ret;
1021 static int contains_pending_extent(struct btrfs_trans_handle *trans,
1022 struct btrfs_device *device,
1023 u64 *start, u64 len)
1025 struct extent_map *em;
1026 int ret = 0;
1028 list_for_each_entry(em, &trans->transaction->pending_chunks, list) {
1029 struct map_lookup *map;
1030 int i;
1032 map = (struct map_lookup *)em->bdev;
1033 for (i = 0; i < map->num_stripes; i++) {
1034 if (map->stripes[i].dev != device)
1035 continue;
1036 if (map->stripes[i].physical >= *start + len ||
1037 map->stripes[i].physical + em->orig_block_len <=
1038 *start)
1039 continue;
1040 *start = map->stripes[i].physical +
1041 em->orig_block_len;
1042 ret = 1;
1046 return ret;
1051 * find_free_dev_extent - find free space in the specified device
1052 * @device: the device which we search the free space in
1053 * @num_bytes: the size of the free space that we need
1054 * @start: store the start of the free space.
1055 * @len: the size of the free space. that we find, or the size of the max
1056 * free space if we don't find suitable free space
1058 * this uses a pretty simple search, the expectation is that it is
1059 * called very infrequently and that a given device has a small number
1060 * of extents
1062 * @start is used to store the start of the free space if we find. But if we
1063 * don't find suitable free space, it will be used to store the start position
1064 * of the max free space.
1066 * @len is used to store the size of the free space that we find.
1067 * But if we don't find suitable free space, it is used to store the size of
1068 * the max free space.
1070 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1071 struct btrfs_device *device, u64 num_bytes,
1072 u64 *start, u64 *len)
1074 struct btrfs_key key;
1075 struct btrfs_root *root = device->dev_root;
1076 struct btrfs_dev_extent *dev_extent;
1077 struct btrfs_path *path;
1078 u64 hole_size;
1079 u64 max_hole_start;
1080 u64 max_hole_size;
1081 u64 extent_end;
1082 u64 search_start;
1083 u64 search_end = device->total_bytes;
1084 int ret;
1085 int slot;
1086 struct extent_buffer *l;
1088 /* FIXME use last free of some kind */
1090 /* we don't want to overwrite the superblock on the drive,
1091 * so we make sure to start at an offset of at least 1MB
1093 search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
1095 path = btrfs_alloc_path();
1096 if (!path)
1097 return -ENOMEM;
1098 again:
1099 max_hole_start = search_start;
1100 max_hole_size = 0;
1101 hole_size = 0;
1103 if (search_start >= search_end || device->is_tgtdev_for_dev_replace) {
1104 ret = -ENOSPC;
1105 goto out;
1108 path->reada = 2;
1109 path->search_commit_root = 1;
1110 path->skip_locking = 1;
1112 key.objectid = device->devid;
1113 key.offset = search_start;
1114 key.type = BTRFS_DEV_EXTENT_KEY;
1116 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1117 if (ret < 0)
1118 goto out;
1119 if (ret > 0) {
1120 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1121 if (ret < 0)
1122 goto out;
1125 while (1) {
1126 l = path->nodes[0];
1127 slot = path->slots[0];
1128 if (slot >= btrfs_header_nritems(l)) {
1129 ret = btrfs_next_leaf(root, path);
1130 if (ret == 0)
1131 continue;
1132 if (ret < 0)
1133 goto out;
1135 break;
1137 btrfs_item_key_to_cpu(l, &key, slot);
1139 if (key.objectid < device->devid)
1140 goto next;
1142 if (key.objectid > device->devid)
1143 break;
1145 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
1146 goto next;
1148 if (key.offset > search_start) {
1149 hole_size = key.offset - search_start;
1152 * Have to check before we set max_hole_start, otherwise
1153 * we could end up sending back this offset anyway.
1155 if (contains_pending_extent(trans, device,
1156 &search_start,
1157 hole_size))
1158 hole_size = 0;
1160 if (hole_size > max_hole_size) {
1161 max_hole_start = search_start;
1162 max_hole_size = hole_size;
1166 * If this free space is greater than which we need,
1167 * it must be the max free space that we have found
1168 * until now, so max_hole_start must point to the start
1169 * of this free space and the length of this free space
1170 * is stored in max_hole_size. Thus, we return
1171 * max_hole_start and max_hole_size and go back to the
1172 * caller.
1174 if (hole_size >= num_bytes) {
1175 ret = 0;
1176 goto out;
1180 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1181 extent_end = key.offset + btrfs_dev_extent_length(l,
1182 dev_extent);
1183 if (extent_end > search_start)
1184 search_start = extent_end;
1185 next:
1186 path->slots[0]++;
1187 cond_resched();
1191 * At this point, search_start should be the end of
1192 * allocated dev extents, and when shrinking the device,
1193 * search_end may be smaller than search_start.
1195 if (search_end > search_start)
1196 hole_size = search_end - search_start;
1198 if (hole_size > max_hole_size) {
1199 max_hole_start = search_start;
1200 max_hole_size = hole_size;
1203 if (contains_pending_extent(trans, device, &search_start, hole_size)) {
1204 btrfs_release_path(path);
1205 goto again;
1208 /* See above. */
1209 if (hole_size < num_bytes)
1210 ret = -ENOSPC;
1211 else
1212 ret = 0;
1214 out:
1215 btrfs_free_path(path);
1216 *start = max_hole_start;
1217 if (len)
1218 *len = max_hole_size;
1219 return ret;
1222 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1223 struct btrfs_device *device,
1224 u64 start)
1226 int ret;
1227 struct btrfs_path *path;
1228 struct btrfs_root *root = device->dev_root;
1229 struct btrfs_key key;
1230 struct btrfs_key found_key;
1231 struct extent_buffer *leaf = NULL;
1232 struct btrfs_dev_extent *extent = NULL;
1234 path = btrfs_alloc_path();
1235 if (!path)
1236 return -ENOMEM;
1238 key.objectid = device->devid;
1239 key.offset = start;
1240 key.type = BTRFS_DEV_EXTENT_KEY;
1241 again:
1242 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1243 if (ret > 0) {
1244 ret = btrfs_previous_item(root, path, key.objectid,
1245 BTRFS_DEV_EXTENT_KEY);
1246 if (ret)
1247 goto out;
1248 leaf = path->nodes[0];
1249 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1250 extent = btrfs_item_ptr(leaf, path->slots[0],
1251 struct btrfs_dev_extent);
1252 BUG_ON(found_key.offset > start || found_key.offset +
1253 btrfs_dev_extent_length(leaf, extent) < start);
1254 key = found_key;
1255 btrfs_release_path(path);
1256 goto again;
1257 } else if (ret == 0) {
1258 leaf = path->nodes[0];
1259 extent = btrfs_item_ptr(leaf, path->slots[0],
1260 struct btrfs_dev_extent);
1261 } else {
1262 btrfs_error(root->fs_info, ret, "Slot search failed");
1263 goto out;
1266 if (device->bytes_used > 0) {
1267 u64 len = btrfs_dev_extent_length(leaf, extent);
1268 device->bytes_used -= len;
1269 spin_lock(&root->fs_info->free_chunk_lock);
1270 root->fs_info->free_chunk_space += len;
1271 spin_unlock(&root->fs_info->free_chunk_lock);
1273 ret = btrfs_del_item(trans, root, path);
1274 if (ret) {
1275 btrfs_error(root->fs_info, ret,
1276 "Failed to remove dev extent item");
1278 out:
1279 btrfs_free_path(path);
1280 return ret;
1283 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1284 struct btrfs_device *device,
1285 u64 chunk_tree, u64 chunk_objectid,
1286 u64 chunk_offset, u64 start, u64 num_bytes)
1288 int ret;
1289 struct btrfs_path *path;
1290 struct btrfs_root *root = device->dev_root;
1291 struct btrfs_dev_extent *extent;
1292 struct extent_buffer *leaf;
1293 struct btrfs_key key;
1295 WARN_ON(!device->in_fs_metadata);
1296 WARN_ON(device->is_tgtdev_for_dev_replace);
1297 path = btrfs_alloc_path();
1298 if (!path)
1299 return -ENOMEM;
1301 key.objectid = device->devid;
1302 key.offset = start;
1303 key.type = BTRFS_DEV_EXTENT_KEY;
1304 ret = btrfs_insert_empty_item(trans, root, path, &key,
1305 sizeof(*extent));
1306 if (ret)
1307 goto out;
1309 leaf = path->nodes[0];
1310 extent = btrfs_item_ptr(leaf, path->slots[0],
1311 struct btrfs_dev_extent);
1312 btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1313 btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1314 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1316 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1317 btrfs_dev_extent_chunk_tree_uuid(extent), BTRFS_UUID_SIZE);
1319 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1320 btrfs_mark_buffer_dirty(leaf);
1321 out:
1322 btrfs_free_path(path);
1323 return ret;
1326 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1328 struct extent_map_tree *em_tree;
1329 struct extent_map *em;
1330 struct rb_node *n;
1331 u64 ret = 0;
1333 em_tree = &fs_info->mapping_tree.map_tree;
1334 read_lock(&em_tree->lock);
1335 n = rb_last(&em_tree->map);
1336 if (n) {
1337 em = rb_entry(n, struct extent_map, rb_node);
1338 ret = em->start + em->len;
1340 read_unlock(&em_tree->lock);
1342 return ret;
1345 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1346 u64 *devid_ret)
1348 int ret;
1349 struct btrfs_key key;
1350 struct btrfs_key found_key;
1351 struct btrfs_path *path;
1353 path = btrfs_alloc_path();
1354 if (!path)
1355 return -ENOMEM;
1357 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1358 key.type = BTRFS_DEV_ITEM_KEY;
1359 key.offset = (u64)-1;
1361 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1362 if (ret < 0)
1363 goto error;
1365 BUG_ON(ret == 0); /* Corruption */
1367 ret = btrfs_previous_item(fs_info->chunk_root, path,
1368 BTRFS_DEV_ITEMS_OBJECTID,
1369 BTRFS_DEV_ITEM_KEY);
1370 if (ret) {
1371 *devid_ret = 1;
1372 } else {
1373 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1374 path->slots[0]);
1375 *devid_ret = found_key.offset + 1;
1377 ret = 0;
1378 error:
1379 btrfs_free_path(path);
1380 return ret;
1384 * the device information is stored in the chunk root
1385 * the btrfs_device struct should be fully filled in
1387 static int btrfs_add_device(struct btrfs_trans_handle *trans,
1388 struct btrfs_root *root,
1389 struct btrfs_device *device)
1391 int ret;
1392 struct btrfs_path *path;
1393 struct btrfs_dev_item *dev_item;
1394 struct extent_buffer *leaf;
1395 struct btrfs_key key;
1396 unsigned long ptr;
1398 root = root->fs_info->chunk_root;
1400 path = btrfs_alloc_path();
1401 if (!path)
1402 return -ENOMEM;
1404 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1405 key.type = BTRFS_DEV_ITEM_KEY;
1406 key.offset = device->devid;
1408 ret = btrfs_insert_empty_item(trans, root, path, &key,
1409 sizeof(*dev_item));
1410 if (ret)
1411 goto out;
1413 leaf = path->nodes[0];
1414 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1416 btrfs_set_device_id(leaf, dev_item, device->devid);
1417 btrfs_set_device_generation(leaf, dev_item, 0);
1418 btrfs_set_device_type(leaf, dev_item, device->type);
1419 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1420 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1421 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1422 btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
1423 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1424 btrfs_set_device_group(leaf, dev_item, 0);
1425 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1426 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1427 btrfs_set_device_start_offset(leaf, dev_item, 0);
1429 ptr = btrfs_device_uuid(dev_item);
1430 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1431 ptr = btrfs_device_fsid(dev_item);
1432 write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
1433 btrfs_mark_buffer_dirty(leaf);
1435 ret = 0;
1436 out:
1437 btrfs_free_path(path);
1438 return ret;
1442 * Function to update ctime/mtime for a given device path.
1443 * Mainly used for ctime/mtime based probe like libblkid.
1445 static void update_dev_time(char *path_name)
1447 struct file *filp;
1449 filp = filp_open(path_name, O_RDWR, 0);
1450 if (!filp)
1451 return;
1452 file_update_time(filp);
1453 filp_close(filp, NULL);
1454 return;
1457 static int btrfs_rm_dev_item(struct btrfs_root *root,
1458 struct btrfs_device *device)
1460 int ret;
1461 struct btrfs_path *path;
1462 struct btrfs_key key;
1463 struct btrfs_trans_handle *trans;
1465 root = root->fs_info->chunk_root;
1467 path = btrfs_alloc_path();
1468 if (!path)
1469 return -ENOMEM;
1471 trans = btrfs_start_transaction(root, 0);
1472 if (IS_ERR(trans)) {
1473 btrfs_free_path(path);
1474 return PTR_ERR(trans);
1476 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1477 key.type = BTRFS_DEV_ITEM_KEY;
1478 key.offset = device->devid;
1479 lock_chunks(root);
1481 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1482 if (ret < 0)
1483 goto out;
1485 if (ret > 0) {
1486 ret = -ENOENT;
1487 goto out;
1490 ret = btrfs_del_item(trans, root, path);
1491 if (ret)
1492 goto out;
1493 out:
1494 btrfs_free_path(path);
1495 unlock_chunks(root);
1496 btrfs_commit_transaction(trans, root);
1497 return ret;
1500 int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1502 struct btrfs_device *device;
1503 struct btrfs_device *next_device;
1504 struct block_device *bdev;
1505 struct buffer_head *bh = NULL;
1506 struct btrfs_super_block *disk_super;
1507 struct btrfs_fs_devices *cur_devices;
1508 u64 all_avail;
1509 u64 devid;
1510 u64 num_devices;
1511 u8 *dev_uuid;
1512 unsigned seq;
1513 int ret = 0;
1514 bool clear_super = false;
1516 mutex_lock(&uuid_mutex);
1518 do {
1519 seq = read_seqbegin(&root->fs_info->profiles_lock);
1521 all_avail = root->fs_info->avail_data_alloc_bits |
1522 root->fs_info->avail_system_alloc_bits |
1523 root->fs_info->avail_metadata_alloc_bits;
1524 } while (read_seqretry(&root->fs_info->profiles_lock, seq));
1526 num_devices = root->fs_info->fs_devices->num_devices;
1527 btrfs_dev_replace_lock(&root->fs_info->dev_replace);
1528 if (btrfs_dev_replace_is_ongoing(&root->fs_info->dev_replace)) {
1529 WARN_ON(num_devices < 1);
1530 num_devices--;
1532 btrfs_dev_replace_unlock(&root->fs_info->dev_replace);
1534 if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) && num_devices <= 4) {
1535 ret = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET;
1536 goto out;
1539 if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) && num_devices <= 2) {
1540 ret = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET;
1541 goto out;
1544 if ((all_avail & BTRFS_BLOCK_GROUP_RAID5) &&
1545 root->fs_info->fs_devices->rw_devices <= 2) {
1546 ret = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET;
1547 goto out;
1549 if ((all_avail & BTRFS_BLOCK_GROUP_RAID6) &&
1550 root->fs_info->fs_devices->rw_devices <= 3) {
1551 ret = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET;
1552 goto out;
1555 if (strcmp(device_path, "missing") == 0) {
1556 struct list_head *devices;
1557 struct btrfs_device *tmp;
1559 device = NULL;
1560 devices = &root->fs_info->fs_devices->devices;
1562 * It is safe to read the devices since the volume_mutex
1563 * is held.
1565 list_for_each_entry(tmp, devices, dev_list) {
1566 if (tmp->in_fs_metadata &&
1567 !tmp->is_tgtdev_for_dev_replace &&
1568 !tmp->bdev) {
1569 device = tmp;
1570 break;
1573 bdev = NULL;
1574 bh = NULL;
1575 disk_super = NULL;
1576 if (!device) {
1577 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
1578 goto out;
1580 } else {
1581 ret = btrfs_get_bdev_and_sb(device_path,
1582 FMODE_WRITE | FMODE_EXCL,
1583 root->fs_info->bdev_holder, 0,
1584 &bdev, &bh);
1585 if (ret)
1586 goto out;
1587 disk_super = (struct btrfs_super_block *)bh->b_data;
1588 devid = btrfs_stack_device_id(&disk_super->dev_item);
1589 dev_uuid = disk_super->dev_item.uuid;
1590 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1591 disk_super->fsid);
1592 if (!device) {
1593 ret = -ENOENT;
1594 goto error_brelse;
1598 if (device->is_tgtdev_for_dev_replace) {
1599 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1600 goto error_brelse;
1603 if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
1604 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1605 goto error_brelse;
1608 if (device->writeable) {
1609 lock_chunks(root);
1610 list_del_init(&device->dev_alloc_list);
1611 unlock_chunks(root);
1612 root->fs_info->fs_devices->rw_devices--;
1613 clear_super = true;
1616 mutex_unlock(&uuid_mutex);
1617 ret = btrfs_shrink_device(device, 0);
1618 mutex_lock(&uuid_mutex);
1619 if (ret)
1620 goto error_undo;
1623 * TODO: the superblock still includes this device in its num_devices
1624 * counter although write_all_supers() is not locked out. This
1625 * could give a filesystem state which requires a degraded mount.
1627 ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1628 if (ret)
1629 goto error_undo;
1631 spin_lock(&root->fs_info->free_chunk_lock);
1632 root->fs_info->free_chunk_space = device->total_bytes -
1633 device->bytes_used;
1634 spin_unlock(&root->fs_info->free_chunk_lock);
1636 device->in_fs_metadata = 0;
1637 btrfs_scrub_cancel_dev(root->fs_info, device);
1640 * the device list mutex makes sure that we don't change
1641 * the device list while someone else is writing out all
1642 * the device supers. Whoever is writing all supers, should
1643 * lock the device list mutex before getting the number of
1644 * devices in the super block (super_copy). Conversely,
1645 * whoever updates the number of devices in the super block
1646 * (super_copy) should hold the device list mutex.
1649 cur_devices = device->fs_devices;
1650 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1651 list_del_rcu(&device->dev_list);
1653 device->fs_devices->num_devices--;
1654 device->fs_devices->total_devices--;
1656 if (device->missing)
1657 root->fs_info->fs_devices->missing_devices--;
1659 next_device = list_entry(root->fs_info->fs_devices->devices.next,
1660 struct btrfs_device, dev_list);
1661 if (device->bdev == root->fs_info->sb->s_bdev)
1662 root->fs_info->sb->s_bdev = next_device->bdev;
1663 if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1664 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1666 if (device->bdev)
1667 device->fs_devices->open_devices--;
1669 call_rcu(&device->rcu, free_device);
1671 num_devices = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
1672 btrfs_set_super_num_devices(root->fs_info->super_copy, num_devices);
1673 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1675 if (cur_devices->open_devices == 0) {
1676 struct btrfs_fs_devices *fs_devices;
1677 fs_devices = root->fs_info->fs_devices;
1678 while (fs_devices) {
1679 if (fs_devices->seed == cur_devices) {
1680 fs_devices->seed = cur_devices->seed;
1681 break;
1683 fs_devices = fs_devices->seed;
1685 cur_devices->seed = NULL;
1686 lock_chunks(root);
1687 __btrfs_close_devices(cur_devices);
1688 unlock_chunks(root);
1689 free_fs_devices(cur_devices);
1692 root->fs_info->num_tolerated_disk_barrier_failures =
1693 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
1696 * at this point, the device is zero sized. We want to
1697 * remove it from the devices list and zero out the old super
1699 if (clear_super && disk_super) {
1700 /* make sure this device isn't detected as part of
1701 * the FS anymore
1703 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1704 set_buffer_dirty(bh);
1705 sync_dirty_buffer(bh);
1708 ret = 0;
1710 if (bdev) {
1711 /* Notify udev that device has changed */
1712 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
1714 /* Update ctime/mtime for device path for libblkid */
1715 update_dev_time(device_path);
1718 error_brelse:
1719 brelse(bh);
1720 if (bdev)
1721 blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
1722 out:
1723 mutex_unlock(&uuid_mutex);
1724 return ret;
1725 error_undo:
1726 if (device->writeable) {
1727 lock_chunks(root);
1728 list_add(&device->dev_alloc_list,
1729 &root->fs_info->fs_devices->alloc_list);
1730 unlock_chunks(root);
1731 root->fs_info->fs_devices->rw_devices++;
1733 goto error_brelse;
1736 void btrfs_rm_dev_replace_srcdev(struct btrfs_fs_info *fs_info,
1737 struct btrfs_device *srcdev)
1739 WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
1741 list_del_rcu(&srcdev->dev_list);
1742 list_del_rcu(&srcdev->dev_alloc_list);
1743 fs_info->fs_devices->num_devices--;
1744 if (srcdev->missing) {
1745 fs_info->fs_devices->missing_devices--;
1746 fs_info->fs_devices->rw_devices++;
1748 if (srcdev->can_discard)
1749 fs_info->fs_devices->num_can_discard--;
1750 if (srcdev->bdev) {
1751 fs_info->fs_devices->open_devices--;
1753 /* zero out the old super */
1754 btrfs_scratch_superblock(srcdev);
1757 call_rcu(&srcdev->rcu, free_device);
1760 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
1761 struct btrfs_device *tgtdev)
1763 struct btrfs_device *next_device;
1765 WARN_ON(!tgtdev);
1766 mutex_lock(&fs_info->fs_devices->device_list_mutex);
1767 if (tgtdev->bdev) {
1768 btrfs_scratch_superblock(tgtdev);
1769 fs_info->fs_devices->open_devices--;
1771 fs_info->fs_devices->num_devices--;
1772 if (tgtdev->can_discard)
1773 fs_info->fs_devices->num_can_discard++;
1775 next_device = list_entry(fs_info->fs_devices->devices.next,
1776 struct btrfs_device, dev_list);
1777 if (tgtdev->bdev == fs_info->sb->s_bdev)
1778 fs_info->sb->s_bdev = next_device->bdev;
1779 if (tgtdev->bdev == fs_info->fs_devices->latest_bdev)
1780 fs_info->fs_devices->latest_bdev = next_device->bdev;
1781 list_del_rcu(&tgtdev->dev_list);
1783 call_rcu(&tgtdev->rcu, free_device);
1785 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1788 static int btrfs_find_device_by_path(struct btrfs_root *root, char *device_path,
1789 struct btrfs_device **device)
1791 int ret = 0;
1792 struct btrfs_super_block *disk_super;
1793 u64 devid;
1794 u8 *dev_uuid;
1795 struct block_device *bdev;
1796 struct buffer_head *bh;
1798 *device = NULL;
1799 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
1800 root->fs_info->bdev_holder, 0, &bdev, &bh);
1801 if (ret)
1802 return ret;
1803 disk_super = (struct btrfs_super_block *)bh->b_data;
1804 devid = btrfs_stack_device_id(&disk_super->dev_item);
1805 dev_uuid = disk_super->dev_item.uuid;
1806 *device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1807 disk_super->fsid);
1808 brelse(bh);
1809 if (!*device)
1810 ret = -ENOENT;
1811 blkdev_put(bdev, FMODE_READ);
1812 return ret;
1815 int btrfs_find_device_missing_or_by_path(struct btrfs_root *root,
1816 char *device_path,
1817 struct btrfs_device **device)
1819 *device = NULL;
1820 if (strcmp(device_path, "missing") == 0) {
1821 struct list_head *devices;
1822 struct btrfs_device *tmp;
1824 devices = &root->fs_info->fs_devices->devices;
1826 * It is safe to read the devices since the volume_mutex
1827 * is held by the caller.
1829 list_for_each_entry(tmp, devices, dev_list) {
1830 if (tmp->in_fs_metadata && !tmp->bdev) {
1831 *device = tmp;
1832 break;
1836 if (!*device) {
1837 pr_err("btrfs: no missing device found\n");
1838 return -ENOENT;
1841 return 0;
1842 } else {
1843 return btrfs_find_device_by_path(root, device_path, device);
1848 * does all the dirty work required for changing file system's UUID.
1850 static int btrfs_prepare_sprout(struct btrfs_root *root)
1852 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
1853 struct btrfs_fs_devices *old_devices;
1854 struct btrfs_fs_devices *seed_devices;
1855 struct btrfs_super_block *disk_super = root->fs_info->super_copy;
1856 struct btrfs_device *device;
1857 u64 super_flags;
1859 BUG_ON(!mutex_is_locked(&uuid_mutex));
1860 if (!fs_devices->seeding)
1861 return -EINVAL;
1863 seed_devices = __alloc_fs_devices();
1864 if (IS_ERR(seed_devices))
1865 return PTR_ERR(seed_devices);
1867 old_devices = clone_fs_devices(fs_devices);
1868 if (IS_ERR(old_devices)) {
1869 kfree(seed_devices);
1870 return PTR_ERR(old_devices);
1873 list_add(&old_devices->list, &fs_uuids);
1875 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
1876 seed_devices->opened = 1;
1877 INIT_LIST_HEAD(&seed_devices->devices);
1878 INIT_LIST_HEAD(&seed_devices->alloc_list);
1879 mutex_init(&seed_devices->device_list_mutex);
1881 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1882 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
1883 synchronize_rcu);
1885 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
1886 list_for_each_entry(device, &seed_devices->devices, dev_list) {
1887 device->fs_devices = seed_devices;
1890 fs_devices->seeding = 0;
1891 fs_devices->num_devices = 0;
1892 fs_devices->open_devices = 0;
1893 fs_devices->seed = seed_devices;
1895 generate_random_uuid(fs_devices->fsid);
1896 memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1897 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1898 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1900 super_flags = btrfs_super_flags(disk_super) &
1901 ~BTRFS_SUPER_FLAG_SEEDING;
1902 btrfs_set_super_flags(disk_super, super_flags);
1904 return 0;
1908 * strore the expected generation for seed devices in device items.
1910 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
1911 struct btrfs_root *root)
1913 struct btrfs_path *path;
1914 struct extent_buffer *leaf;
1915 struct btrfs_dev_item *dev_item;
1916 struct btrfs_device *device;
1917 struct btrfs_key key;
1918 u8 fs_uuid[BTRFS_UUID_SIZE];
1919 u8 dev_uuid[BTRFS_UUID_SIZE];
1920 u64 devid;
1921 int ret;
1923 path = btrfs_alloc_path();
1924 if (!path)
1925 return -ENOMEM;
1927 root = root->fs_info->chunk_root;
1928 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1929 key.offset = 0;
1930 key.type = BTRFS_DEV_ITEM_KEY;
1932 while (1) {
1933 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1934 if (ret < 0)
1935 goto error;
1937 leaf = path->nodes[0];
1938 next_slot:
1939 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1940 ret = btrfs_next_leaf(root, path);
1941 if (ret > 0)
1942 break;
1943 if (ret < 0)
1944 goto error;
1945 leaf = path->nodes[0];
1946 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1947 btrfs_release_path(path);
1948 continue;
1951 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1952 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
1953 key.type != BTRFS_DEV_ITEM_KEY)
1954 break;
1956 dev_item = btrfs_item_ptr(leaf, path->slots[0],
1957 struct btrfs_dev_item);
1958 devid = btrfs_device_id(leaf, dev_item);
1959 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
1960 BTRFS_UUID_SIZE);
1961 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
1962 BTRFS_UUID_SIZE);
1963 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1964 fs_uuid);
1965 BUG_ON(!device); /* Logic error */
1967 if (device->fs_devices->seeding) {
1968 btrfs_set_device_generation(leaf, dev_item,
1969 device->generation);
1970 btrfs_mark_buffer_dirty(leaf);
1973 path->slots[0]++;
1974 goto next_slot;
1976 ret = 0;
1977 error:
1978 btrfs_free_path(path);
1979 return ret;
1982 int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
1984 struct request_queue *q;
1985 struct btrfs_trans_handle *trans;
1986 struct btrfs_device *device;
1987 struct block_device *bdev;
1988 struct list_head *devices;
1989 struct super_block *sb = root->fs_info->sb;
1990 struct rcu_string *name;
1991 u64 total_bytes;
1992 int seeding_dev = 0;
1993 int ret = 0;
1995 if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
1996 return -EROFS;
1998 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
1999 root->fs_info->bdev_holder);
2000 if (IS_ERR(bdev))
2001 return PTR_ERR(bdev);
2003 if (root->fs_info->fs_devices->seeding) {
2004 seeding_dev = 1;
2005 down_write(&sb->s_umount);
2006 mutex_lock(&uuid_mutex);
2009 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2011 devices = &root->fs_info->fs_devices->devices;
2013 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2014 list_for_each_entry(device, devices, dev_list) {
2015 if (device->bdev == bdev) {
2016 ret = -EEXIST;
2017 mutex_unlock(
2018 &root->fs_info->fs_devices->device_list_mutex);
2019 goto error;
2022 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2024 device = btrfs_alloc_device(root->fs_info, NULL, NULL);
2025 if (IS_ERR(device)) {
2026 /* we can safely leave the fs_devices entry around */
2027 ret = PTR_ERR(device);
2028 goto error;
2031 name = rcu_string_strdup(device_path, GFP_NOFS);
2032 if (!name) {
2033 kfree(device);
2034 ret = -ENOMEM;
2035 goto error;
2037 rcu_assign_pointer(device->name, name);
2039 trans = btrfs_start_transaction(root, 0);
2040 if (IS_ERR(trans)) {
2041 rcu_string_free(device->name);
2042 kfree(device);
2043 ret = PTR_ERR(trans);
2044 goto error;
2047 lock_chunks(root);
2049 q = bdev_get_queue(bdev);
2050 if (blk_queue_discard(q))
2051 device->can_discard = 1;
2052 device->writeable = 1;
2053 device->generation = trans->transid;
2054 device->io_width = root->sectorsize;
2055 device->io_align = root->sectorsize;
2056 device->sector_size = root->sectorsize;
2057 device->total_bytes = i_size_read(bdev->bd_inode);
2058 device->disk_total_bytes = device->total_bytes;
2059 device->dev_root = root->fs_info->dev_root;
2060 device->bdev = bdev;
2061 device->in_fs_metadata = 1;
2062 device->is_tgtdev_for_dev_replace = 0;
2063 device->mode = FMODE_EXCL;
2064 set_blocksize(device->bdev, 4096);
2066 if (seeding_dev) {
2067 sb->s_flags &= ~MS_RDONLY;
2068 ret = btrfs_prepare_sprout(root);
2069 BUG_ON(ret); /* -ENOMEM */
2072 device->fs_devices = root->fs_info->fs_devices;
2074 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2075 list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
2076 list_add(&device->dev_alloc_list,
2077 &root->fs_info->fs_devices->alloc_list);
2078 root->fs_info->fs_devices->num_devices++;
2079 root->fs_info->fs_devices->open_devices++;
2080 root->fs_info->fs_devices->rw_devices++;
2081 root->fs_info->fs_devices->total_devices++;
2082 if (device->can_discard)
2083 root->fs_info->fs_devices->num_can_discard++;
2084 root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2086 spin_lock(&root->fs_info->free_chunk_lock);
2087 root->fs_info->free_chunk_space += device->total_bytes;
2088 spin_unlock(&root->fs_info->free_chunk_lock);
2090 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
2091 root->fs_info->fs_devices->rotating = 1;
2093 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
2094 btrfs_set_super_total_bytes(root->fs_info->super_copy,
2095 total_bytes + device->total_bytes);
2097 total_bytes = btrfs_super_num_devices(root->fs_info->super_copy);
2098 btrfs_set_super_num_devices(root->fs_info->super_copy,
2099 total_bytes + 1);
2100 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2102 if (seeding_dev) {
2103 ret = init_first_rw_device(trans, root, device);
2104 if (ret) {
2105 btrfs_abort_transaction(trans, root, ret);
2106 goto error_trans;
2108 ret = btrfs_finish_sprout(trans, root);
2109 if (ret) {
2110 btrfs_abort_transaction(trans, root, ret);
2111 goto error_trans;
2113 } else {
2114 ret = btrfs_add_device(trans, root, device);
2115 if (ret) {
2116 btrfs_abort_transaction(trans, root, ret);
2117 goto error_trans;
2122 * we've got more storage, clear any full flags on the space
2123 * infos
2125 btrfs_clear_space_info_full(root->fs_info);
2127 unlock_chunks(root);
2128 root->fs_info->num_tolerated_disk_barrier_failures =
2129 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
2130 ret = btrfs_commit_transaction(trans, root);
2132 if (seeding_dev) {
2133 mutex_unlock(&uuid_mutex);
2134 up_write(&sb->s_umount);
2136 if (ret) /* transaction commit */
2137 return ret;
2139 ret = btrfs_relocate_sys_chunks(root);
2140 if (ret < 0)
2141 btrfs_error(root->fs_info, ret,
2142 "Failed to relocate sys chunks after "
2143 "device initialization. This can be fixed "
2144 "using the \"btrfs balance\" command.");
2145 trans = btrfs_attach_transaction(root);
2146 if (IS_ERR(trans)) {
2147 if (PTR_ERR(trans) == -ENOENT)
2148 return 0;
2149 return PTR_ERR(trans);
2151 ret = btrfs_commit_transaction(trans, root);
2154 /* Update ctime/mtime for libblkid */
2155 update_dev_time(device_path);
2156 return ret;
2158 error_trans:
2159 unlock_chunks(root);
2160 btrfs_end_transaction(trans, root);
2161 rcu_string_free(device->name);
2162 kfree(device);
2163 error:
2164 blkdev_put(bdev, FMODE_EXCL);
2165 if (seeding_dev) {
2166 mutex_unlock(&uuid_mutex);
2167 up_write(&sb->s_umount);
2169 return ret;
2172 int btrfs_init_dev_replace_tgtdev(struct btrfs_root *root, char *device_path,
2173 struct btrfs_device **device_out)
2175 struct request_queue *q;
2176 struct btrfs_device *device;
2177 struct block_device *bdev;
2178 struct btrfs_fs_info *fs_info = root->fs_info;
2179 struct list_head *devices;
2180 struct rcu_string *name;
2181 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2182 int ret = 0;
2184 *device_out = NULL;
2185 if (fs_info->fs_devices->seeding)
2186 return -EINVAL;
2188 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2189 fs_info->bdev_holder);
2190 if (IS_ERR(bdev))
2191 return PTR_ERR(bdev);
2193 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2195 devices = &fs_info->fs_devices->devices;
2196 list_for_each_entry(device, devices, dev_list) {
2197 if (device->bdev == bdev) {
2198 ret = -EEXIST;
2199 goto error;
2203 device = btrfs_alloc_device(NULL, &devid, NULL);
2204 if (IS_ERR(device)) {
2205 ret = PTR_ERR(device);
2206 goto error;
2209 name = rcu_string_strdup(device_path, GFP_NOFS);
2210 if (!name) {
2211 kfree(device);
2212 ret = -ENOMEM;
2213 goto error;
2215 rcu_assign_pointer(device->name, name);
2217 q = bdev_get_queue(bdev);
2218 if (blk_queue_discard(q))
2219 device->can_discard = 1;
2220 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2221 device->writeable = 1;
2222 device->generation = 0;
2223 device->io_width = root->sectorsize;
2224 device->io_align = root->sectorsize;
2225 device->sector_size = root->sectorsize;
2226 device->total_bytes = i_size_read(bdev->bd_inode);
2227 device->disk_total_bytes = device->total_bytes;
2228 device->dev_root = fs_info->dev_root;
2229 device->bdev = bdev;
2230 device->in_fs_metadata = 1;
2231 device->is_tgtdev_for_dev_replace = 1;
2232 device->mode = FMODE_EXCL;
2233 set_blocksize(device->bdev, 4096);
2234 device->fs_devices = fs_info->fs_devices;
2235 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2236 fs_info->fs_devices->num_devices++;
2237 fs_info->fs_devices->open_devices++;
2238 if (device->can_discard)
2239 fs_info->fs_devices->num_can_discard++;
2240 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2242 *device_out = device;
2243 return ret;
2245 error:
2246 blkdev_put(bdev, FMODE_EXCL);
2247 return ret;
2250 void btrfs_init_dev_replace_tgtdev_for_resume(struct btrfs_fs_info *fs_info,
2251 struct btrfs_device *tgtdev)
2253 WARN_ON(fs_info->fs_devices->rw_devices == 0);
2254 tgtdev->io_width = fs_info->dev_root->sectorsize;
2255 tgtdev->io_align = fs_info->dev_root->sectorsize;
2256 tgtdev->sector_size = fs_info->dev_root->sectorsize;
2257 tgtdev->dev_root = fs_info->dev_root;
2258 tgtdev->in_fs_metadata = 1;
2261 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2262 struct btrfs_device *device)
2264 int ret;
2265 struct btrfs_path *path;
2266 struct btrfs_root *root;
2267 struct btrfs_dev_item *dev_item;
2268 struct extent_buffer *leaf;
2269 struct btrfs_key key;
2271 root = device->dev_root->fs_info->chunk_root;
2273 path = btrfs_alloc_path();
2274 if (!path)
2275 return -ENOMEM;
2277 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2278 key.type = BTRFS_DEV_ITEM_KEY;
2279 key.offset = device->devid;
2281 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2282 if (ret < 0)
2283 goto out;
2285 if (ret > 0) {
2286 ret = -ENOENT;
2287 goto out;
2290 leaf = path->nodes[0];
2291 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2293 btrfs_set_device_id(leaf, dev_item, device->devid);
2294 btrfs_set_device_type(leaf, dev_item, device->type);
2295 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2296 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2297 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2298 btrfs_set_device_total_bytes(leaf, dev_item, device->disk_total_bytes);
2299 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
2300 btrfs_mark_buffer_dirty(leaf);
2302 out:
2303 btrfs_free_path(path);
2304 return ret;
2307 static int __btrfs_grow_device(struct btrfs_trans_handle *trans,
2308 struct btrfs_device *device, u64 new_size)
2310 struct btrfs_super_block *super_copy =
2311 device->dev_root->fs_info->super_copy;
2312 u64 old_total = btrfs_super_total_bytes(super_copy);
2313 u64 diff = new_size - device->total_bytes;
2315 if (!device->writeable)
2316 return -EACCES;
2317 if (new_size <= device->total_bytes ||
2318 device->is_tgtdev_for_dev_replace)
2319 return -EINVAL;
2321 btrfs_set_super_total_bytes(super_copy, old_total + diff);
2322 device->fs_devices->total_rw_bytes += diff;
2324 device->total_bytes = new_size;
2325 device->disk_total_bytes = new_size;
2326 btrfs_clear_space_info_full(device->dev_root->fs_info);
2328 return btrfs_update_device(trans, device);
2331 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2332 struct btrfs_device *device, u64 new_size)
2334 int ret;
2335 lock_chunks(device->dev_root);
2336 ret = __btrfs_grow_device(trans, device, new_size);
2337 unlock_chunks(device->dev_root);
2338 return ret;
2341 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2342 struct btrfs_root *root,
2343 u64 chunk_tree, u64 chunk_objectid,
2344 u64 chunk_offset)
2346 int ret;
2347 struct btrfs_path *path;
2348 struct btrfs_key key;
2350 root = root->fs_info->chunk_root;
2351 path = btrfs_alloc_path();
2352 if (!path)
2353 return -ENOMEM;
2355 key.objectid = chunk_objectid;
2356 key.offset = chunk_offset;
2357 key.type = BTRFS_CHUNK_ITEM_KEY;
2359 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2360 if (ret < 0)
2361 goto out;
2362 else if (ret > 0) { /* Logic error or corruption */
2363 btrfs_error(root->fs_info, -ENOENT,
2364 "Failed lookup while freeing chunk.");
2365 ret = -ENOENT;
2366 goto out;
2369 ret = btrfs_del_item(trans, root, path);
2370 if (ret < 0)
2371 btrfs_error(root->fs_info, ret,
2372 "Failed to delete chunk item.");
2373 out:
2374 btrfs_free_path(path);
2375 return ret;
2378 static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
2379 chunk_offset)
2381 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
2382 struct btrfs_disk_key *disk_key;
2383 struct btrfs_chunk *chunk;
2384 u8 *ptr;
2385 int ret = 0;
2386 u32 num_stripes;
2387 u32 array_size;
2388 u32 len = 0;
2389 u32 cur;
2390 struct btrfs_key key;
2392 array_size = btrfs_super_sys_array_size(super_copy);
2394 ptr = super_copy->sys_chunk_array;
2395 cur = 0;
2397 while (cur < array_size) {
2398 disk_key = (struct btrfs_disk_key *)ptr;
2399 btrfs_disk_key_to_cpu(&key, disk_key);
2401 len = sizeof(*disk_key);
2403 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2404 chunk = (struct btrfs_chunk *)(ptr + len);
2405 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2406 len += btrfs_chunk_item_size(num_stripes);
2407 } else {
2408 ret = -EIO;
2409 break;
2411 if (key.objectid == chunk_objectid &&
2412 key.offset == chunk_offset) {
2413 memmove(ptr, ptr + len, array_size - (cur + len));
2414 array_size -= len;
2415 btrfs_set_super_sys_array_size(super_copy, array_size);
2416 } else {
2417 ptr += len;
2418 cur += len;
2421 return ret;
2424 static int btrfs_relocate_chunk(struct btrfs_root *root,
2425 u64 chunk_tree, u64 chunk_objectid,
2426 u64 chunk_offset)
2428 struct extent_map_tree *em_tree;
2429 struct btrfs_root *extent_root;
2430 struct btrfs_trans_handle *trans;
2431 struct extent_map *em;
2432 struct map_lookup *map;
2433 int ret;
2434 int i;
2436 root = root->fs_info->chunk_root;
2437 extent_root = root->fs_info->extent_root;
2438 em_tree = &root->fs_info->mapping_tree.map_tree;
2440 ret = btrfs_can_relocate(extent_root, chunk_offset);
2441 if (ret)
2442 return -ENOSPC;
2444 /* step one, relocate all the extents inside this chunk */
2445 ret = btrfs_relocate_block_group(extent_root, chunk_offset);
2446 if (ret)
2447 return ret;
2449 trans = btrfs_start_transaction(root, 0);
2450 if (IS_ERR(trans)) {
2451 ret = PTR_ERR(trans);
2452 btrfs_std_error(root->fs_info, ret);
2453 return ret;
2456 lock_chunks(root);
2459 * step two, delete the device extents and the
2460 * chunk tree entries
2462 read_lock(&em_tree->lock);
2463 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
2464 read_unlock(&em_tree->lock);
2466 BUG_ON(!em || em->start > chunk_offset ||
2467 em->start + em->len < chunk_offset);
2468 map = (struct map_lookup *)em->bdev;
2470 for (i = 0; i < map->num_stripes; i++) {
2471 ret = btrfs_free_dev_extent(trans, map->stripes[i].dev,
2472 map->stripes[i].physical);
2473 BUG_ON(ret);
2475 if (map->stripes[i].dev) {
2476 ret = btrfs_update_device(trans, map->stripes[i].dev);
2477 BUG_ON(ret);
2480 ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
2481 chunk_offset);
2483 BUG_ON(ret);
2485 trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
2487 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2488 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
2489 BUG_ON(ret);
2492 ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
2493 BUG_ON(ret);
2495 write_lock(&em_tree->lock);
2496 remove_extent_mapping(em_tree, em);
2497 write_unlock(&em_tree->lock);
2499 kfree(map);
2500 em->bdev = NULL;
2502 /* once for the tree */
2503 free_extent_map(em);
2504 /* once for us */
2505 free_extent_map(em);
2507 unlock_chunks(root);
2508 btrfs_end_transaction(trans, root);
2509 return 0;
2512 static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
2514 struct btrfs_root *chunk_root = root->fs_info->chunk_root;
2515 struct btrfs_path *path;
2516 struct extent_buffer *leaf;
2517 struct btrfs_chunk *chunk;
2518 struct btrfs_key key;
2519 struct btrfs_key found_key;
2520 u64 chunk_tree = chunk_root->root_key.objectid;
2521 u64 chunk_type;
2522 bool retried = false;
2523 int failed = 0;
2524 int ret;
2526 path = btrfs_alloc_path();
2527 if (!path)
2528 return -ENOMEM;
2530 again:
2531 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2532 key.offset = (u64)-1;
2533 key.type = BTRFS_CHUNK_ITEM_KEY;
2535 while (1) {
2536 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2537 if (ret < 0)
2538 goto error;
2539 BUG_ON(ret == 0); /* Corruption */
2541 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2542 key.type);
2543 if (ret < 0)
2544 goto error;
2545 if (ret > 0)
2546 break;
2548 leaf = path->nodes[0];
2549 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2551 chunk = btrfs_item_ptr(leaf, path->slots[0],
2552 struct btrfs_chunk);
2553 chunk_type = btrfs_chunk_type(leaf, chunk);
2554 btrfs_release_path(path);
2556 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2557 ret = btrfs_relocate_chunk(chunk_root, chunk_tree,
2558 found_key.objectid,
2559 found_key.offset);
2560 if (ret == -ENOSPC)
2561 failed++;
2562 else if (ret)
2563 BUG();
2566 if (found_key.offset == 0)
2567 break;
2568 key.offset = found_key.offset - 1;
2570 ret = 0;
2571 if (failed && !retried) {
2572 failed = 0;
2573 retried = true;
2574 goto again;
2575 } else if (failed && retried) {
2576 WARN_ON(1);
2577 ret = -ENOSPC;
2579 error:
2580 btrfs_free_path(path);
2581 return ret;
2584 static int insert_balance_item(struct btrfs_root *root,
2585 struct btrfs_balance_control *bctl)
2587 struct btrfs_trans_handle *trans;
2588 struct btrfs_balance_item *item;
2589 struct btrfs_disk_balance_args disk_bargs;
2590 struct btrfs_path *path;
2591 struct extent_buffer *leaf;
2592 struct btrfs_key key;
2593 int ret, err;
2595 path = btrfs_alloc_path();
2596 if (!path)
2597 return -ENOMEM;
2599 trans = btrfs_start_transaction(root, 0);
2600 if (IS_ERR(trans)) {
2601 btrfs_free_path(path);
2602 return PTR_ERR(trans);
2605 key.objectid = BTRFS_BALANCE_OBJECTID;
2606 key.type = BTRFS_BALANCE_ITEM_KEY;
2607 key.offset = 0;
2609 ret = btrfs_insert_empty_item(trans, root, path, &key,
2610 sizeof(*item));
2611 if (ret)
2612 goto out;
2614 leaf = path->nodes[0];
2615 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2617 memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
2619 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
2620 btrfs_set_balance_data(leaf, item, &disk_bargs);
2621 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
2622 btrfs_set_balance_meta(leaf, item, &disk_bargs);
2623 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
2624 btrfs_set_balance_sys(leaf, item, &disk_bargs);
2626 btrfs_set_balance_flags(leaf, item, bctl->flags);
2628 btrfs_mark_buffer_dirty(leaf);
2629 out:
2630 btrfs_free_path(path);
2631 err = btrfs_commit_transaction(trans, root);
2632 if (err && !ret)
2633 ret = err;
2634 return ret;
2637 static int del_balance_item(struct btrfs_root *root)
2639 struct btrfs_trans_handle *trans;
2640 struct btrfs_path *path;
2641 struct btrfs_key key;
2642 int ret, err;
2644 path = btrfs_alloc_path();
2645 if (!path)
2646 return -ENOMEM;
2648 trans = btrfs_start_transaction(root, 0);
2649 if (IS_ERR(trans)) {
2650 btrfs_free_path(path);
2651 return PTR_ERR(trans);
2654 key.objectid = BTRFS_BALANCE_OBJECTID;
2655 key.type = BTRFS_BALANCE_ITEM_KEY;
2656 key.offset = 0;
2658 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2659 if (ret < 0)
2660 goto out;
2661 if (ret > 0) {
2662 ret = -ENOENT;
2663 goto out;
2666 ret = btrfs_del_item(trans, root, path);
2667 out:
2668 btrfs_free_path(path);
2669 err = btrfs_commit_transaction(trans, root);
2670 if (err && !ret)
2671 ret = err;
2672 return ret;
2676 * This is a heuristic used to reduce the number of chunks balanced on
2677 * resume after balance was interrupted.
2679 static void update_balance_args(struct btrfs_balance_control *bctl)
2682 * Turn on soft mode for chunk types that were being converted.
2684 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
2685 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
2686 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
2687 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
2688 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
2689 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
2692 * Turn on usage filter if is not already used. The idea is
2693 * that chunks that we have already balanced should be
2694 * reasonably full. Don't do it for chunks that are being
2695 * converted - that will keep us from relocating unconverted
2696 * (albeit full) chunks.
2698 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2699 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2700 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
2701 bctl->data.usage = 90;
2703 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2704 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2705 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
2706 bctl->sys.usage = 90;
2708 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2709 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2710 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
2711 bctl->meta.usage = 90;
2716 * Should be called with both balance and volume mutexes held to
2717 * serialize other volume operations (add_dev/rm_dev/resize) with
2718 * restriper. Same goes for unset_balance_control.
2720 static void set_balance_control(struct btrfs_balance_control *bctl)
2722 struct btrfs_fs_info *fs_info = bctl->fs_info;
2724 BUG_ON(fs_info->balance_ctl);
2726 spin_lock(&fs_info->balance_lock);
2727 fs_info->balance_ctl = bctl;
2728 spin_unlock(&fs_info->balance_lock);
2731 static void unset_balance_control(struct btrfs_fs_info *fs_info)
2733 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
2735 BUG_ON(!fs_info->balance_ctl);
2737 spin_lock(&fs_info->balance_lock);
2738 fs_info->balance_ctl = NULL;
2739 spin_unlock(&fs_info->balance_lock);
2741 kfree(bctl);
2745 * Balance filters. Return 1 if chunk should be filtered out
2746 * (should not be balanced).
2748 static int chunk_profiles_filter(u64 chunk_type,
2749 struct btrfs_balance_args *bargs)
2751 chunk_type = chunk_to_extended(chunk_type) &
2752 BTRFS_EXTENDED_PROFILE_MASK;
2754 if (bargs->profiles & chunk_type)
2755 return 0;
2757 return 1;
2760 static int chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
2761 struct btrfs_balance_args *bargs)
2763 struct btrfs_block_group_cache *cache;
2764 u64 chunk_used, user_thresh;
2765 int ret = 1;
2767 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2768 chunk_used = btrfs_block_group_used(&cache->item);
2770 if (bargs->usage == 0)
2771 user_thresh = 1;
2772 else if (bargs->usage > 100)
2773 user_thresh = cache->key.offset;
2774 else
2775 user_thresh = div_factor_fine(cache->key.offset,
2776 bargs->usage);
2778 if (chunk_used < user_thresh)
2779 ret = 0;
2781 btrfs_put_block_group(cache);
2782 return ret;
2785 static int chunk_devid_filter(struct extent_buffer *leaf,
2786 struct btrfs_chunk *chunk,
2787 struct btrfs_balance_args *bargs)
2789 struct btrfs_stripe *stripe;
2790 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2791 int i;
2793 for (i = 0; i < num_stripes; i++) {
2794 stripe = btrfs_stripe_nr(chunk, i);
2795 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
2796 return 0;
2799 return 1;
2802 /* [pstart, pend) */
2803 static int chunk_drange_filter(struct extent_buffer *leaf,
2804 struct btrfs_chunk *chunk,
2805 u64 chunk_offset,
2806 struct btrfs_balance_args *bargs)
2808 struct btrfs_stripe *stripe;
2809 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2810 u64 stripe_offset;
2811 u64 stripe_length;
2812 int factor;
2813 int i;
2815 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
2816 return 0;
2818 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
2819 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
2820 factor = num_stripes / 2;
2821 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
2822 factor = num_stripes - 1;
2823 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
2824 factor = num_stripes - 2;
2825 } else {
2826 factor = num_stripes;
2829 for (i = 0; i < num_stripes; i++) {
2830 stripe = btrfs_stripe_nr(chunk, i);
2831 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
2832 continue;
2834 stripe_offset = btrfs_stripe_offset(leaf, stripe);
2835 stripe_length = btrfs_chunk_length(leaf, chunk);
2836 do_div(stripe_length, factor);
2838 if (stripe_offset < bargs->pend &&
2839 stripe_offset + stripe_length > bargs->pstart)
2840 return 0;
2843 return 1;
2846 /* [vstart, vend) */
2847 static int chunk_vrange_filter(struct extent_buffer *leaf,
2848 struct btrfs_chunk *chunk,
2849 u64 chunk_offset,
2850 struct btrfs_balance_args *bargs)
2852 if (chunk_offset < bargs->vend &&
2853 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
2854 /* at least part of the chunk is inside this vrange */
2855 return 0;
2857 return 1;
2860 static int chunk_soft_convert_filter(u64 chunk_type,
2861 struct btrfs_balance_args *bargs)
2863 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
2864 return 0;
2866 chunk_type = chunk_to_extended(chunk_type) &
2867 BTRFS_EXTENDED_PROFILE_MASK;
2869 if (bargs->target == chunk_type)
2870 return 1;
2872 return 0;
2875 static int should_balance_chunk(struct btrfs_root *root,
2876 struct extent_buffer *leaf,
2877 struct btrfs_chunk *chunk, u64 chunk_offset)
2879 struct btrfs_balance_control *bctl = root->fs_info->balance_ctl;
2880 struct btrfs_balance_args *bargs = NULL;
2881 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
2883 /* type filter */
2884 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
2885 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
2886 return 0;
2889 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
2890 bargs = &bctl->data;
2891 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
2892 bargs = &bctl->sys;
2893 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
2894 bargs = &bctl->meta;
2896 /* profiles filter */
2897 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
2898 chunk_profiles_filter(chunk_type, bargs)) {
2899 return 0;
2902 /* usage filter */
2903 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
2904 chunk_usage_filter(bctl->fs_info, chunk_offset, bargs)) {
2905 return 0;
2908 /* devid filter */
2909 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
2910 chunk_devid_filter(leaf, chunk, bargs)) {
2911 return 0;
2914 /* drange filter, makes sense only with devid filter */
2915 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
2916 chunk_drange_filter(leaf, chunk, chunk_offset, bargs)) {
2917 return 0;
2920 /* vrange filter */
2921 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
2922 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
2923 return 0;
2926 /* soft profile changing mode */
2927 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
2928 chunk_soft_convert_filter(chunk_type, bargs)) {
2929 return 0;
2932 return 1;
2935 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
2937 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
2938 struct btrfs_root *chunk_root = fs_info->chunk_root;
2939 struct btrfs_root *dev_root = fs_info->dev_root;
2940 struct list_head *devices;
2941 struct btrfs_device *device;
2942 u64 old_size;
2943 u64 size_to_free;
2944 struct btrfs_chunk *chunk;
2945 struct btrfs_path *path;
2946 struct btrfs_key key;
2947 struct btrfs_key found_key;
2948 struct btrfs_trans_handle *trans;
2949 struct extent_buffer *leaf;
2950 int slot;
2951 int ret;
2952 int enospc_errors = 0;
2953 bool counting = true;
2955 /* step one make some room on all the devices */
2956 devices = &fs_info->fs_devices->devices;
2957 list_for_each_entry(device, devices, dev_list) {
2958 old_size = device->total_bytes;
2959 size_to_free = div_factor(old_size, 1);
2960 size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
2961 if (!device->writeable ||
2962 device->total_bytes - device->bytes_used > size_to_free ||
2963 device->is_tgtdev_for_dev_replace)
2964 continue;
2966 ret = btrfs_shrink_device(device, old_size - size_to_free);
2967 if (ret == -ENOSPC)
2968 break;
2969 BUG_ON(ret);
2971 trans = btrfs_start_transaction(dev_root, 0);
2972 BUG_ON(IS_ERR(trans));
2974 ret = btrfs_grow_device(trans, device, old_size);
2975 BUG_ON(ret);
2977 btrfs_end_transaction(trans, dev_root);
2980 /* step two, relocate all the chunks */
2981 path = btrfs_alloc_path();
2982 if (!path) {
2983 ret = -ENOMEM;
2984 goto error;
2987 /* zero out stat counters */
2988 spin_lock(&fs_info->balance_lock);
2989 memset(&bctl->stat, 0, sizeof(bctl->stat));
2990 spin_unlock(&fs_info->balance_lock);
2991 again:
2992 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2993 key.offset = (u64)-1;
2994 key.type = BTRFS_CHUNK_ITEM_KEY;
2996 while (1) {
2997 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
2998 atomic_read(&fs_info->balance_cancel_req)) {
2999 ret = -ECANCELED;
3000 goto error;
3003 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3004 if (ret < 0)
3005 goto error;
3008 * this shouldn't happen, it means the last relocate
3009 * failed
3011 if (ret == 0)
3012 BUG(); /* FIXME break ? */
3014 ret = btrfs_previous_item(chunk_root, path, 0,
3015 BTRFS_CHUNK_ITEM_KEY);
3016 if (ret) {
3017 ret = 0;
3018 break;
3021 leaf = path->nodes[0];
3022 slot = path->slots[0];
3023 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3025 if (found_key.objectid != key.objectid)
3026 break;
3028 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3030 if (!counting) {
3031 spin_lock(&fs_info->balance_lock);
3032 bctl->stat.considered++;
3033 spin_unlock(&fs_info->balance_lock);
3036 ret = should_balance_chunk(chunk_root, leaf, chunk,
3037 found_key.offset);
3038 btrfs_release_path(path);
3039 if (!ret)
3040 goto loop;
3042 if (counting) {
3043 spin_lock(&fs_info->balance_lock);
3044 bctl->stat.expected++;
3045 spin_unlock(&fs_info->balance_lock);
3046 goto loop;
3049 ret = btrfs_relocate_chunk(chunk_root,
3050 chunk_root->root_key.objectid,
3051 found_key.objectid,
3052 found_key.offset);
3053 if (ret && ret != -ENOSPC)
3054 goto error;
3055 if (ret == -ENOSPC) {
3056 enospc_errors++;
3057 } else {
3058 spin_lock(&fs_info->balance_lock);
3059 bctl->stat.completed++;
3060 spin_unlock(&fs_info->balance_lock);
3062 loop:
3063 if (found_key.offset == 0)
3064 break;
3065 key.offset = found_key.offset - 1;
3068 if (counting) {
3069 btrfs_release_path(path);
3070 counting = false;
3071 goto again;
3073 error:
3074 btrfs_free_path(path);
3075 if (enospc_errors) {
3076 printk(KERN_INFO "btrfs: %d enospc errors during balance\n",
3077 enospc_errors);
3078 if (!ret)
3079 ret = -ENOSPC;
3082 return ret;
3086 * alloc_profile_is_valid - see if a given profile is valid and reduced
3087 * @flags: profile to validate
3088 * @extended: if true @flags is treated as an extended profile
3090 static int alloc_profile_is_valid(u64 flags, int extended)
3092 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3093 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3095 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3097 /* 1) check that all other bits are zeroed */
3098 if (flags & ~mask)
3099 return 0;
3101 /* 2) see if profile is reduced */
3102 if (flags == 0)
3103 return !extended; /* "0" is valid for usual profiles */
3105 /* true if exactly one bit set */
3106 return (flags & (flags - 1)) == 0;
3109 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3111 /* cancel requested || normal exit path */
3112 return atomic_read(&fs_info->balance_cancel_req) ||
3113 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3114 atomic_read(&fs_info->balance_cancel_req) == 0);
3117 static void __cancel_balance(struct btrfs_fs_info *fs_info)
3119 int ret;
3121 unset_balance_control(fs_info);
3122 ret = del_balance_item(fs_info->tree_root);
3123 if (ret)
3124 btrfs_std_error(fs_info, ret);
3126 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3130 * Should be called with both balance and volume mutexes held
3132 int btrfs_balance(struct btrfs_balance_control *bctl,
3133 struct btrfs_ioctl_balance_args *bargs)
3135 struct btrfs_fs_info *fs_info = bctl->fs_info;
3136 u64 allowed;
3137 int mixed = 0;
3138 int ret;
3139 u64 num_devices;
3140 unsigned seq;
3142 if (btrfs_fs_closing(fs_info) ||
3143 atomic_read(&fs_info->balance_pause_req) ||
3144 atomic_read(&fs_info->balance_cancel_req)) {
3145 ret = -EINVAL;
3146 goto out;
3149 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3150 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3151 mixed = 1;
3154 * In case of mixed groups both data and meta should be picked,
3155 * and identical options should be given for both of them.
3157 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3158 if (mixed && (bctl->flags & allowed)) {
3159 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3160 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3161 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3162 printk(KERN_ERR "btrfs: with mixed groups data and "
3163 "metadata balance options must be the same\n");
3164 ret = -EINVAL;
3165 goto out;
3169 num_devices = fs_info->fs_devices->num_devices;
3170 btrfs_dev_replace_lock(&fs_info->dev_replace);
3171 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3172 BUG_ON(num_devices < 1);
3173 num_devices--;
3175 btrfs_dev_replace_unlock(&fs_info->dev_replace);
3176 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
3177 if (num_devices == 1)
3178 allowed |= BTRFS_BLOCK_GROUP_DUP;
3179 else if (num_devices > 1)
3180 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3181 if (num_devices > 2)
3182 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3183 if (num_devices > 3)
3184 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3185 BTRFS_BLOCK_GROUP_RAID6);
3186 if ((bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3187 (!alloc_profile_is_valid(bctl->data.target, 1) ||
3188 (bctl->data.target & ~allowed))) {
3189 printk(KERN_ERR "btrfs: unable to start balance with target "
3190 "data profile %llu\n",
3191 bctl->data.target);
3192 ret = -EINVAL;
3193 goto out;
3195 if ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3196 (!alloc_profile_is_valid(bctl->meta.target, 1) ||
3197 (bctl->meta.target & ~allowed))) {
3198 printk(KERN_ERR "btrfs: unable to start balance with target "
3199 "metadata profile %llu\n",
3200 bctl->meta.target);
3201 ret = -EINVAL;
3202 goto out;
3204 if ((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3205 (!alloc_profile_is_valid(bctl->sys.target, 1) ||
3206 (bctl->sys.target & ~allowed))) {
3207 printk(KERN_ERR "btrfs: unable to start balance with target "
3208 "system profile %llu\n",
3209 bctl->sys.target);
3210 ret = -EINVAL;
3211 goto out;
3214 /* allow dup'ed data chunks only in mixed mode */
3215 if (!mixed && (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3216 (bctl->data.target & BTRFS_BLOCK_GROUP_DUP)) {
3217 printk(KERN_ERR "btrfs: dup for data is not allowed\n");
3218 ret = -EINVAL;
3219 goto out;
3222 /* allow to reduce meta or sys integrity only if force set */
3223 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3224 BTRFS_BLOCK_GROUP_RAID10 |
3225 BTRFS_BLOCK_GROUP_RAID5 |
3226 BTRFS_BLOCK_GROUP_RAID6;
3227 do {
3228 seq = read_seqbegin(&fs_info->profiles_lock);
3230 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3231 (fs_info->avail_system_alloc_bits & allowed) &&
3232 !(bctl->sys.target & allowed)) ||
3233 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3234 (fs_info->avail_metadata_alloc_bits & allowed) &&
3235 !(bctl->meta.target & allowed))) {
3236 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3237 printk(KERN_INFO "btrfs: force reducing metadata "
3238 "integrity\n");
3239 } else {
3240 printk(KERN_ERR "btrfs: balance will reduce metadata "
3241 "integrity, use force if you want this\n");
3242 ret = -EINVAL;
3243 goto out;
3246 } while (read_seqretry(&fs_info->profiles_lock, seq));
3248 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3249 int num_tolerated_disk_barrier_failures;
3250 u64 target = bctl->sys.target;
3252 num_tolerated_disk_barrier_failures =
3253 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3254 if (num_tolerated_disk_barrier_failures > 0 &&
3255 (target &
3256 (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID0 |
3257 BTRFS_AVAIL_ALLOC_BIT_SINGLE)))
3258 num_tolerated_disk_barrier_failures = 0;
3259 else if (num_tolerated_disk_barrier_failures > 1 &&
3260 (target &
3261 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)))
3262 num_tolerated_disk_barrier_failures = 1;
3264 fs_info->num_tolerated_disk_barrier_failures =
3265 num_tolerated_disk_barrier_failures;
3268 ret = insert_balance_item(fs_info->tree_root, bctl);
3269 if (ret && ret != -EEXIST)
3270 goto out;
3272 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3273 BUG_ON(ret == -EEXIST);
3274 set_balance_control(bctl);
3275 } else {
3276 BUG_ON(ret != -EEXIST);
3277 spin_lock(&fs_info->balance_lock);
3278 update_balance_args(bctl);
3279 spin_unlock(&fs_info->balance_lock);
3282 atomic_inc(&fs_info->balance_running);
3283 mutex_unlock(&fs_info->balance_mutex);
3285 ret = __btrfs_balance(fs_info);
3287 mutex_lock(&fs_info->balance_mutex);
3288 atomic_dec(&fs_info->balance_running);
3290 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3291 fs_info->num_tolerated_disk_barrier_failures =
3292 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3295 if (bargs) {
3296 memset(bargs, 0, sizeof(*bargs));
3297 update_ioctl_balance_args(fs_info, 0, bargs);
3300 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3301 balance_need_close(fs_info)) {
3302 __cancel_balance(fs_info);
3305 wake_up(&fs_info->balance_wait_q);
3307 return ret;
3308 out:
3309 if (bctl->flags & BTRFS_BALANCE_RESUME)
3310 __cancel_balance(fs_info);
3311 else {
3312 kfree(bctl);
3313 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3315 return ret;
3318 static int balance_kthread(void *data)
3320 struct btrfs_fs_info *fs_info = data;
3321 int ret = 0;
3323 mutex_lock(&fs_info->volume_mutex);
3324 mutex_lock(&fs_info->balance_mutex);
3326 if (fs_info->balance_ctl) {
3327 printk(KERN_INFO "btrfs: continuing balance\n");
3328 ret = btrfs_balance(fs_info->balance_ctl, NULL);
3331 mutex_unlock(&fs_info->balance_mutex);
3332 mutex_unlock(&fs_info->volume_mutex);
3334 return ret;
3337 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3339 struct task_struct *tsk;
3341 spin_lock(&fs_info->balance_lock);
3342 if (!fs_info->balance_ctl) {
3343 spin_unlock(&fs_info->balance_lock);
3344 return 0;
3346 spin_unlock(&fs_info->balance_lock);
3348 if (btrfs_test_opt(fs_info->tree_root, SKIP_BALANCE)) {
3349 printk(KERN_INFO "btrfs: force skipping balance\n");
3350 return 0;
3353 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3354 return PTR_ERR_OR_ZERO(tsk);
3357 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3359 struct btrfs_balance_control *bctl;
3360 struct btrfs_balance_item *item;
3361 struct btrfs_disk_balance_args disk_bargs;
3362 struct btrfs_path *path;
3363 struct extent_buffer *leaf;
3364 struct btrfs_key key;
3365 int ret;
3367 path = btrfs_alloc_path();
3368 if (!path)
3369 return -ENOMEM;
3371 key.objectid = BTRFS_BALANCE_OBJECTID;
3372 key.type = BTRFS_BALANCE_ITEM_KEY;
3373 key.offset = 0;
3375 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3376 if (ret < 0)
3377 goto out;
3378 if (ret > 0) { /* ret = -ENOENT; */
3379 ret = 0;
3380 goto out;
3383 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3384 if (!bctl) {
3385 ret = -ENOMEM;
3386 goto out;
3389 leaf = path->nodes[0];
3390 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3392 bctl->fs_info = fs_info;
3393 bctl->flags = btrfs_balance_flags(leaf, item);
3394 bctl->flags |= BTRFS_BALANCE_RESUME;
3396 btrfs_balance_data(leaf, item, &disk_bargs);
3397 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
3398 btrfs_balance_meta(leaf, item, &disk_bargs);
3399 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
3400 btrfs_balance_sys(leaf, item, &disk_bargs);
3401 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
3403 WARN_ON(atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1));
3405 mutex_lock(&fs_info->volume_mutex);
3406 mutex_lock(&fs_info->balance_mutex);
3408 set_balance_control(bctl);
3410 mutex_unlock(&fs_info->balance_mutex);
3411 mutex_unlock(&fs_info->volume_mutex);
3412 out:
3413 btrfs_free_path(path);
3414 return ret;
3417 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
3419 int ret = 0;
3421 mutex_lock(&fs_info->balance_mutex);
3422 if (!fs_info->balance_ctl) {
3423 mutex_unlock(&fs_info->balance_mutex);
3424 return -ENOTCONN;
3427 if (atomic_read(&fs_info->balance_running)) {
3428 atomic_inc(&fs_info->balance_pause_req);
3429 mutex_unlock(&fs_info->balance_mutex);
3431 wait_event(fs_info->balance_wait_q,
3432 atomic_read(&fs_info->balance_running) == 0);
3434 mutex_lock(&fs_info->balance_mutex);
3435 /* we are good with balance_ctl ripped off from under us */
3436 BUG_ON(atomic_read(&fs_info->balance_running));
3437 atomic_dec(&fs_info->balance_pause_req);
3438 } else {
3439 ret = -ENOTCONN;
3442 mutex_unlock(&fs_info->balance_mutex);
3443 return ret;
3446 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
3448 mutex_lock(&fs_info->balance_mutex);
3449 if (!fs_info->balance_ctl) {
3450 mutex_unlock(&fs_info->balance_mutex);
3451 return -ENOTCONN;
3454 atomic_inc(&fs_info->balance_cancel_req);
3456 * if we are running just wait and return, balance item is
3457 * deleted in btrfs_balance in this case
3459 if (atomic_read(&fs_info->balance_running)) {
3460 mutex_unlock(&fs_info->balance_mutex);
3461 wait_event(fs_info->balance_wait_q,
3462 atomic_read(&fs_info->balance_running) == 0);
3463 mutex_lock(&fs_info->balance_mutex);
3464 } else {
3465 /* __cancel_balance needs volume_mutex */
3466 mutex_unlock(&fs_info->balance_mutex);
3467 mutex_lock(&fs_info->volume_mutex);
3468 mutex_lock(&fs_info->balance_mutex);
3470 if (fs_info->balance_ctl)
3471 __cancel_balance(fs_info);
3473 mutex_unlock(&fs_info->volume_mutex);
3476 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
3477 atomic_dec(&fs_info->balance_cancel_req);
3478 mutex_unlock(&fs_info->balance_mutex);
3479 return 0;
3482 static int btrfs_uuid_scan_kthread(void *data)
3484 struct btrfs_fs_info *fs_info = data;
3485 struct btrfs_root *root = fs_info->tree_root;
3486 struct btrfs_key key;
3487 struct btrfs_key max_key;
3488 struct btrfs_path *path = NULL;
3489 int ret = 0;
3490 struct extent_buffer *eb;
3491 int slot;
3492 struct btrfs_root_item root_item;
3493 u32 item_size;
3494 struct btrfs_trans_handle *trans = NULL;
3496 path = btrfs_alloc_path();
3497 if (!path) {
3498 ret = -ENOMEM;
3499 goto out;
3502 key.objectid = 0;
3503 key.type = BTRFS_ROOT_ITEM_KEY;
3504 key.offset = 0;
3506 max_key.objectid = (u64)-1;
3507 max_key.type = BTRFS_ROOT_ITEM_KEY;
3508 max_key.offset = (u64)-1;
3510 path->keep_locks = 1;
3512 while (1) {
3513 ret = btrfs_search_forward(root, &key, &max_key, path, 0);
3514 if (ret) {
3515 if (ret > 0)
3516 ret = 0;
3517 break;
3520 if (key.type != BTRFS_ROOT_ITEM_KEY ||
3521 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
3522 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
3523 key.objectid > BTRFS_LAST_FREE_OBJECTID)
3524 goto skip;
3526 eb = path->nodes[0];
3527 slot = path->slots[0];
3528 item_size = btrfs_item_size_nr(eb, slot);
3529 if (item_size < sizeof(root_item))
3530 goto skip;
3532 read_extent_buffer(eb, &root_item,
3533 btrfs_item_ptr_offset(eb, slot),
3534 (int)sizeof(root_item));
3535 if (btrfs_root_refs(&root_item) == 0)
3536 goto skip;
3538 if (!btrfs_is_empty_uuid(root_item.uuid) ||
3539 !btrfs_is_empty_uuid(root_item.received_uuid)) {
3540 if (trans)
3541 goto update_tree;
3543 btrfs_release_path(path);
3545 * 1 - subvol uuid item
3546 * 1 - received_subvol uuid item
3548 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
3549 if (IS_ERR(trans)) {
3550 ret = PTR_ERR(trans);
3551 break;
3553 continue;
3554 } else {
3555 goto skip;
3557 update_tree:
3558 if (!btrfs_is_empty_uuid(root_item.uuid)) {
3559 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
3560 root_item.uuid,
3561 BTRFS_UUID_KEY_SUBVOL,
3562 key.objectid);
3563 if (ret < 0) {
3564 pr_warn("btrfs: uuid_tree_add failed %d\n",
3565 ret);
3566 break;
3570 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
3571 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
3572 root_item.received_uuid,
3573 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
3574 key.objectid);
3575 if (ret < 0) {
3576 pr_warn("btrfs: uuid_tree_add failed %d\n",
3577 ret);
3578 break;
3582 skip:
3583 if (trans) {
3584 ret = btrfs_end_transaction(trans, fs_info->uuid_root);
3585 trans = NULL;
3586 if (ret)
3587 break;
3590 btrfs_release_path(path);
3591 if (key.offset < (u64)-1) {
3592 key.offset++;
3593 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
3594 key.offset = 0;
3595 key.type = BTRFS_ROOT_ITEM_KEY;
3596 } else if (key.objectid < (u64)-1) {
3597 key.offset = 0;
3598 key.type = BTRFS_ROOT_ITEM_KEY;
3599 key.objectid++;
3600 } else {
3601 break;
3603 cond_resched();
3606 out:
3607 btrfs_free_path(path);
3608 if (trans && !IS_ERR(trans))
3609 btrfs_end_transaction(trans, fs_info->uuid_root);
3610 if (ret)
3611 pr_warn("btrfs: btrfs_uuid_scan_kthread failed %d\n", ret);
3612 else
3613 fs_info->update_uuid_tree_gen = 1;
3614 up(&fs_info->uuid_tree_rescan_sem);
3615 return 0;
3619 * Callback for btrfs_uuid_tree_iterate().
3620 * returns:
3621 * 0 check succeeded, the entry is not outdated.
3622 * < 0 if an error occured.
3623 * > 0 if the check failed, which means the caller shall remove the entry.
3625 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
3626 u8 *uuid, u8 type, u64 subid)
3628 struct btrfs_key key;
3629 int ret = 0;
3630 struct btrfs_root *subvol_root;
3632 if (type != BTRFS_UUID_KEY_SUBVOL &&
3633 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
3634 goto out;
3636 key.objectid = subid;
3637 key.type = BTRFS_ROOT_ITEM_KEY;
3638 key.offset = (u64)-1;
3639 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
3640 if (IS_ERR(subvol_root)) {
3641 ret = PTR_ERR(subvol_root);
3642 if (ret == -ENOENT)
3643 ret = 1;
3644 goto out;
3647 switch (type) {
3648 case BTRFS_UUID_KEY_SUBVOL:
3649 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
3650 ret = 1;
3651 break;
3652 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
3653 if (memcmp(uuid, subvol_root->root_item.received_uuid,
3654 BTRFS_UUID_SIZE))
3655 ret = 1;
3656 break;
3659 out:
3660 return ret;
3663 static int btrfs_uuid_rescan_kthread(void *data)
3665 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
3666 int ret;
3669 * 1st step is to iterate through the existing UUID tree and
3670 * to delete all entries that contain outdated data.
3671 * 2nd step is to add all missing entries to the UUID tree.
3673 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
3674 if (ret < 0) {
3675 pr_warn("btrfs: iterating uuid_tree failed %d\n", ret);
3676 up(&fs_info->uuid_tree_rescan_sem);
3677 return ret;
3679 return btrfs_uuid_scan_kthread(data);
3682 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
3684 struct btrfs_trans_handle *trans;
3685 struct btrfs_root *tree_root = fs_info->tree_root;
3686 struct btrfs_root *uuid_root;
3687 struct task_struct *task;
3688 int ret;
3691 * 1 - root node
3692 * 1 - root item
3694 trans = btrfs_start_transaction(tree_root, 2);
3695 if (IS_ERR(trans))
3696 return PTR_ERR(trans);
3698 uuid_root = btrfs_create_tree(trans, fs_info,
3699 BTRFS_UUID_TREE_OBJECTID);
3700 if (IS_ERR(uuid_root)) {
3701 btrfs_abort_transaction(trans, tree_root,
3702 PTR_ERR(uuid_root));
3703 return PTR_ERR(uuid_root);
3706 fs_info->uuid_root = uuid_root;
3708 ret = btrfs_commit_transaction(trans, tree_root);
3709 if (ret)
3710 return ret;
3712 down(&fs_info->uuid_tree_rescan_sem);
3713 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
3714 if (IS_ERR(task)) {
3715 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
3716 pr_warn("btrfs: failed to start uuid_scan task\n");
3717 up(&fs_info->uuid_tree_rescan_sem);
3718 return PTR_ERR(task);
3721 return 0;
3724 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
3726 struct task_struct *task;
3728 down(&fs_info->uuid_tree_rescan_sem);
3729 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
3730 if (IS_ERR(task)) {
3731 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
3732 pr_warn("btrfs: failed to start uuid_rescan task\n");
3733 up(&fs_info->uuid_tree_rescan_sem);
3734 return PTR_ERR(task);
3737 return 0;
3741 * shrinking a device means finding all of the device extents past
3742 * the new size, and then following the back refs to the chunks.
3743 * The chunk relocation code actually frees the device extent
3745 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
3747 struct btrfs_trans_handle *trans;
3748 struct btrfs_root *root = device->dev_root;
3749 struct btrfs_dev_extent *dev_extent = NULL;
3750 struct btrfs_path *path;
3751 u64 length;
3752 u64 chunk_tree;
3753 u64 chunk_objectid;
3754 u64 chunk_offset;
3755 int ret;
3756 int slot;
3757 int failed = 0;
3758 bool retried = false;
3759 struct extent_buffer *l;
3760 struct btrfs_key key;
3761 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
3762 u64 old_total = btrfs_super_total_bytes(super_copy);
3763 u64 old_size = device->total_bytes;
3764 u64 diff = device->total_bytes - new_size;
3766 if (device->is_tgtdev_for_dev_replace)
3767 return -EINVAL;
3769 path = btrfs_alloc_path();
3770 if (!path)
3771 return -ENOMEM;
3773 path->reada = 2;
3775 lock_chunks(root);
3777 device->total_bytes = new_size;
3778 if (device->writeable) {
3779 device->fs_devices->total_rw_bytes -= diff;
3780 spin_lock(&root->fs_info->free_chunk_lock);
3781 root->fs_info->free_chunk_space -= diff;
3782 spin_unlock(&root->fs_info->free_chunk_lock);
3784 unlock_chunks(root);
3786 again:
3787 key.objectid = device->devid;
3788 key.offset = (u64)-1;
3789 key.type = BTRFS_DEV_EXTENT_KEY;
3791 do {
3792 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3793 if (ret < 0)
3794 goto done;
3796 ret = btrfs_previous_item(root, path, 0, key.type);
3797 if (ret < 0)
3798 goto done;
3799 if (ret) {
3800 ret = 0;
3801 btrfs_release_path(path);
3802 break;
3805 l = path->nodes[0];
3806 slot = path->slots[0];
3807 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
3809 if (key.objectid != device->devid) {
3810 btrfs_release_path(path);
3811 break;
3814 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
3815 length = btrfs_dev_extent_length(l, dev_extent);
3817 if (key.offset + length <= new_size) {
3818 btrfs_release_path(path);
3819 break;
3822 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
3823 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
3824 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
3825 btrfs_release_path(path);
3827 ret = btrfs_relocate_chunk(root, chunk_tree, chunk_objectid,
3828 chunk_offset);
3829 if (ret && ret != -ENOSPC)
3830 goto done;
3831 if (ret == -ENOSPC)
3832 failed++;
3833 } while (key.offset-- > 0);
3835 if (failed && !retried) {
3836 failed = 0;
3837 retried = true;
3838 goto again;
3839 } else if (failed && retried) {
3840 ret = -ENOSPC;
3841 lock_chunks(root);
3843 device->total_bytes = old_size;
3844 if (device->writeable)
3845 device->fs_devices->total_rw_bytes += diff;
3846 spin_lock(&root->fs_info->free_chunk_lock);
3847 root->fs_info->free_chunk_space += diff;
3848 spin_unlock(&root->fs_info->free_chunk_lock);
3849 unlock_chunks(root);
3850 goto done;
3853 /* Shrinking succeeded, else we would be at "done". */
3854 trans = btrfs_start_transaction(root, 0);
3855 if (IS_ERR(trans)) {
3856 ret = PTR_ERR(trans);
3857 goto done;
3860 lock_chunks(root);
3862 device->disk_total_bytes = new_size;
3863 /* Now btrfs_update_device() will change the on-disk size. */
3864 ret = btrfs_update_device(trans, device);
3865 if (ret) {
3866 unlock_chunks(root);
3867 btrfs_end_transaction(trans, root);
3868 goto done;
3870 WARN_ON(diff > old_total);
3871 btrfs_set_super_total_bytes(super_copy, old_total - diff);
3872 unlock_chunks(root);
3873 btrfs_end_transaction(trans, root);
3874 done:
3875 btrfs_free_path(path);
3876 return ret;
3879 static int btrfs_add_system_chunk(struct btrfs_root *root,
3880 struct btrfs_key *key,
3881 struct btrfs_chunk *chunk, int item_size)
3883 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
3884 struct btrfs_disk_key disk_key;
3885 u32 array_size;
3886 u8 *ptr;
3888 array_size = btrfs_super_sys_array_size(super_copy);
3889 if (array_size + item_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
3890 return -EFBIG;
3892 ptr = super_copy->sys_chunk_array + array_size;
3893 btrfs_cpu_key_to_disk(&disk_key, key);
3894 memcpy(ptr, &disk_key, sizeof(disk_key));
3895 ptr += sizeof(disk_key);
3896 memcpy(ptr, chunk, item_size);
3897 item_size += sizeof(disk_key);
3898 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
3899 return 0;
3903 * sort the devices in descending order by max_avail, total_avail
3905 static int btrfs_cmp_device_info(const void *a, const void *b)
3907 const struct btrfs_device_info *di_a = a;
3908 const struct btrfs_device_info *di_b = b;
3910 if (di_a->max_avail > di_b->max_avail)
3911 return -1;
3912 if (di_a->max_avail < di_b->max_avail)
3913 return 1;
3914 if (di_a->total_avail > di_b->total_avail)
3915 return -1;
3916 if (di_a->total_avail < di_b->total_avail)
3917 return 1;
3918 return 0;
3921 static struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
3922 [BTRFS_RAID_RAID10] = {
3923 .sub_stripes = 2,
3924 .dev_stripes = 1,
3925 .devs_max = 0, /* 0 == as many as possible */
3926 .devs_min = 4,
3927 .devs_increment = 2,
3928 .ncopies = 2,
3930 [BTRFS_RAID_RAID1] = {
3931 .sub_stripes = 1,
3932 .dev_stripes = 1,
3933 .devs_max = 2,
3934 .devs_min = 2,
3935 .devs_increment = 2,
3936 .ncopies = 2,
3938 [BTRFS_RAID_DUP] = {
3939 .sub_stripes = 1,
3940 .dev_stripes = 2,
3941 .devs_max = 1,
3942 .devs_min = 1,
3943 .devs_increment = 1,
3944 .ncopies = 2,
3946 [BTRFS_RAID_RAID0] = {
3947 .sub_stripes = 1,
3948 .dev_stripes = 1,
3949 .devs_max = 0,
3950 .devs_min = 2,
3951 .devs_increment = 1,
3952 .ncopies = 1,
3954 [BTRFS_RAID_SINGLE] = {
3955 .sub_stripes = 1,
3956 .dev_stripes = 1,
3957 .devs_max = 1,
3958 .devs_min = 1,
3959 .devs_increment = 1,
3960 .ncopies = 1,
3962 [BTRFS_RAID_RAID5] = {
3963 .sub_stripes = 1,
3964 .dev_stripes = 1,
3965 .devs_max = 0,
3966 .devs_min = 2,
3967 .devs_increment = 1,
3968 .ncopies = 2,
3970 [BTRFS_RAID_RAID6] = {
3971 .sub_stripes = 1,
3972 .dev_stripes = 1,
3973 .devs_max = 0,
3974 .devs_min = 3,
3975 .devs_increment = 1,
3976 .ncopies = 3,
3980 static u32 find_raid56_stripe_len(u32 data_devices, u32 dev_stripe_target)
3982 /* TODO allow them to set a preferred stripe size */
3983 return 64 * 1024;
3986 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
3988 if (!(type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)))
3989 return;
3991 btrfs_set_fs_incompat(info, RAID56);
3994 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
3995 struct btrfs_root *extent_root, u64 start,
3996 u64 type)
3998 struct btrfs_fs_info *info = extent_root->fs_info;
3999 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4000 struct list_head *cur;
4001 struct map_lookup *map = NULL;
4002 struct extent_map_tree *em_tree;
4003 struct extent_map *em;
4004 struct btrfs_device_info *devices_info = NULL;
4005 u64 total_avail;
4006 int num_stripes; /* total number of stripes to allocate */
4007 int data_stripes; /* number of stripes that count for
4008 block group size */
4009 int sub_stripes; /* sub_stripes info for map */
4010 int dev_stripes; /* stripes per dev */
4011 int devs_max; /* max devs to use */
4012 int devs_min; /* min devs needed */
4013 int devs_increment; /* ndevs has to be a multiple of this */
4014 int ncopies; /* how many copies to data has */
4015 int ret;
4016 u64 max_stripe_size;
4017 u64 max_chunk_size;
4018 u64 stripe_size;
4019 u64 num_bytes;
4020 u64 raid_stripe_len = BTRFS_STRIPE_LEN;
4021 int ndevs;
4022 int i;
4023 int j;
4024 int index;
4026 BUG_ON(!alloc_profile_is_valid(type, 0));
4028 if (list_empty(&fs_devices->alloc_list))
4029 return -ENOSPC;
4031 index = __get_raid_index(type);
4033 sub_stripes = btrfs_raid_array[index].sub_stripes;
4034 dev_stripes = btrfs_raid_array[index].dev_stripes;
4035 devs_max = btrfs_raid_array[index].devs_max;
4036 devs_min = btrfs_raid_array[index].devs_min;
4037 devs_increment = btrfs_raid_array[index].devs_increment;
4038 ncopies = btrfs_raid_array[index].ncopies;
4040 if (type & BTRFS_BLOCK_GROUP_DATA) {
4041 max_stripe_size = 1024 * 1024 * 1024;
4042 max_chunk_size = 10 * max_stripe_size;
4043 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4044 /* for larger filesystems, use larger metadata chunks */
4045 if (fs_devices->total_rw_bytes > 50ULL * 1024 * 1024 * 1024)
4046 max_stripe_size = 1024 * 1024 * 1024;
4047 else
4048 max_stripe_size = 256 * 1024 * 1024;
4049 max_chunk_size = max_stripe_size;
4050 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4051 max_stripe_size = 32 * 1024 * 1024;
4052 max_chunk_size = 2 * max_stripe_size;
4053 } else {
4054 printk(KERN_ERR "btrfs: invalid chunk type 0x%llx requested\n",
4055 type);
4056 BUG_ON(1);
4059 /* we don't want a chunk larger than 10% of writeable space */
4060 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4061 max_chunk_size);
4063 devices_info = kzalloc(sizeof(*devices_info) * fs_devices->rw_devices,
4064 GFP_NOFS);
4065 if (!devices_info)
4066 return -ENOMEM;
4068 cur = fs_devices->alloc_list.next;
4071 * in the first pass through the devices list, we gather information
4072 * about the available holes on each device.
4074 ndevs = 0;
4075 while (cur != &fs_devices->alloc_list) {
4076 struct btrfs_device *device;
4077 u64 max_avail;
4078 u64 dev_offset;
4080 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
4082 cur = cur->next;
4084 if (!device->writeable) {
4085 WARN(1, KERN_ERR
4086 "btrfs: read-only device in alloc_list\n");
4087 continue;
4090 if (!device->in_fs_metadata ||
4091 device->is_tgtdev_for_dev_replace)
4092 continue;
4094 if (device->total_bytes > device->bytes_used)
4095 total_avail = device->total_bytes - device->bytes_used;
4096 else
4097 total_avail = 0;
4099 /* If there is no space on this device, skip it. */
4100 if (total_avail == 0)
4101 continue;
4103 ret = find_free_dev_extent(trans, device,
4104 max_stripe_size * dev_stripes,
4105 &dev_offset, &max_avail);
4106 if (ret && ret != -ENOSPC)
4107 goto error;
4109 if (ret == 0)
4110 max_avail = max_stripe_size * dev_stripes;
4112 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
4113 continue;
4115 if (ndevs == fs_devices->rw_devices) {
4116 WARN(1, "%s: found more than %llu devices\n",
4117 __func__, fs_devices->rw_devices);
4118 break;
4120 devices_info[ndevs].dev_offset = dev_offset;
4121 devices_info[ndevs].max_avail = max_avail;
4122 devices_info[ndevs].total_avail = total_avail;
4123 devices_info[ndevs].dev = device;
4124 ++ndevs;
4128 * now sort the devices by hole size / available space
4130 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4131 btrfs_cmp_device_info, NULL);
4133 /* round down to number of usable stripes */
4134 ndevs -= ndevs % devs_increment;
4136 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
4137 ret = -ENOSPC;
4138 goto error;
4141 if (devs_max && ndevs > devs_max)
4142 ndevs = devs_max;
4144 * the primary goal is to maximize the number of stripes, so use as many
4145 * devices as possible, even if the stripes are not maximum sized.
4147 stripe_size = devices_info[ndevs-1].max_avail;
4148 num_stripes = ndevs * dev_stripes;
4151 * this will have to be fixed for RAID1 and RAID10 over
4152 * more drives
4154 data_stripes = num_stripes / ncopies;
4156 if (type & BTRFS_BLOCK_GROUP_RAID5) {
4157 raid_stripe_len = find_raid56_stripe_len(ndevs - 1,
4158 btrfs_super_stripesize(info->super_copy));
4159 data_stripes = num_stripes - 1;
4161 if (type & BTRFS_BLOCK_GROUP_RAID6) {
4162 raid_stripe_len = find_raid56_stripe_len(ndevs - 2,
4163 btrfs_super_stripesize(info->super_copy));
4164 data_stripes = num_stripes - 2;
4168 * Use the number of data stripes to figure out how big this chunk
4169 * is really going to be in terms of logical address space,
4170 * and compare that answer with the max chunk size
4172 if (stripe_size * data_stripes > max_chunk_size) {
4173 u64 mask = (1ULL << 24) - 1;
4174 stripe_size = max_chunk_size;
4175 do_div(stripe_size, data_stripes);
4177 /* bump the answer up to a 16MB boundary */
4178 stripe_size = (stripe_size + mask) & ~mask;
4180 /* but don't go higher than the limits we found
4181 * while searching for free extents
4183 if (stripe_size > devices_info[ndevs-1].max_avail)
4184 stripe_size = devices_info[ndevs-1].max_avail;
4187 do_div(stripe_size, dev_stripes);
4189 /* align to BTRFS_STRIPE_LEN */
4190 do_div(stripe_size, raid_stripe_len);
4191 stripe_size *= raid_stripe_len;
4193 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4194 if (!map) {
4195 ret = -ENOMEM;
4196 goto error;
4198 map->num_stripes = num_stripes;
4200 for (i = 0; i < ndevs; ++i) {
4201 for (j = 0; j < dev_stripes; ++j) {
4202 int s = i * dev_stripes + j;
4203 map->stripes[s].dev = devices_info[i].dev;
4204 map->stripes[s].physical = devices_info[i].dev_offset +
4205 j * stripe_size;
4208 map->sector_size = extent_root->sectorsize;
4209 map->stripe_len = raid_stripe_len;
4210 map->io_align = raid_stripe_len;
4211 map->io_width = raid_stripe_len;
4212 map->type = type;
4213 map->sub_stripes = sub_stripes;
4215 num_bytes = stripe_size * data_stripes;
4217 trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
4219 em = alloc_extent_map();
4220 if (!em) {
4221 ret = -ENOMEM;
4222 goto error;
4224 em->bdev = (struct block_device *)map;
4225 em->start = start;
4226 em->len = num_bytes;
4227 em->block_start = 0;
4228 em->block_len = em->len;
4229 em->orig_block_len = stripe_size;
4231 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4232 write_lock(&em_tree->lock);
4233 ret = add_extent_mapping(em_tree, em, 0);
4234 if (!ret) {
4235 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4236 atomic_inc(&em->refs);
4238 write_unlock(&em_tree->lock);
4239 if (ret) {
4240 free_extent_map(em);
4241 goto error;
4244 ret = btrfs_make_block_group(trans, extent_root, 0, type,
4245 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4246 start, num_bytes);
4247 if (ret)
4248 goto error_del_extent;
4250 free_extent_map(em);
4251 check_raid56_incompat_flag(extent_root->fs_info, type);
4253 kfree(devices_info);
4254 return 0;
4256 error_del_extent:
4257 write_lock(&em_tree->lock);
4258 remove_extent_mapping(em_tree, em);
4259 write_unlock(&em_tree->lock);
4261 /* One for our allocation */
4262 free_extent_map(em);
4263 /* One for the tree reference */
4264 free_extent_map(em);
4265 error:
4266 kfree(map);
4267 kfree(devices_info);
4268 return ret;
4271 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4272 struct btrfs_root *extent_root,
4273 u64 chunk_offset, u64 chunk_size)
4275 struct btrfs_key key;
4276 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
4277 struct btrfs_device *device;
4278 struct btrfs_chunk *chunk;
4279 struct btrfs_stripe *stripe;
4280 struct extent_map_tree *em_tree;
4281 struct extent_map *em;
4282 struct map_lookup *map;
4283 size_t item_size;
4284 u64 dev_offset;
4285 u64 stripe_size;
4286 int i = 0;
4287 int ret;
4289 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4290 read_lock(&em_tree->lock);
4291 em = lookup_extent_mapping(em_tree, chunk_offset, chunk_size);
4292 read_unlock(&em_tree->lock);
4294 if (!em) {
4295 btrfs_crit(extent_root->fs_info, "unable to find logical "
4296 "%Lu len %Lu", chunk_offset, chunk_size);
4297 return -EINVAL;
4300 if (em->start != chunk_offset || em->len != chunk_size) {
4301 btrfs_crit(extent_root->fs_info, "found a bad mapping, wanted"
4302 " %Lu-%Lu, found %Lu-%Lu\n", chunk_offset,
4303 chunk_size, em->start, em->len);
4304 free_extent_map(em);
4305 return -EINVAL;
4308 map = (struct map_lookup *)em->bdev;
4309 item_size = btrfs_chunk_item_size(map->num_stripes);
4310 stripe_size = em->orig_block_len;
4312 chunk = kzalloc(item_size, GFP_NOFS);
4313 if (!chunk) {
4314 ret = -ENOMEM;
4315 goto out;
4318 for (i = 0; i < map->num_stripes; i++) {
4319 device = map->stripes[i].dev;
4320 dev_offset = map->stripes[i].physical;
4322 device->bytes_used += stripe_size;
4323 ret = btrfs_update_device(trans, device);
4324 if (ret)
4325 goto out;
4326 ret = btrfs_alloc_dev_extent(trans, device,
4327 chunk_root->root_key.objectid,
4328 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4329 chunk_offset, dev_offset,
4330 stripe_size);
4331 if (ret)
4332 goto out;
4335 spin_lock(&extent_root->fs_info->free_chunk_lock);
4336 extent_root->fs_info->free_chunk_space -= (stripe_size *
4337 map->num_stripes);
4338 spin_unlock(&extent_root->fs_info->free_chunk_lock);
4340 stripe = &chunk->stripe;
4341 for (i = 0; i < map->num_stripes; i++) {
4342 device = map->stripes[i].dev;
4343 dev_offset = map->stripes[i].physical;
4345 btrfs_set_stack_stripe_devid(stripe, device->devid);
4346 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4347 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4348 stripe++;
4351 btrfs_set_stack_chunk_length(chunk, chunk_size);
4352 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4353 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4354 btrfs_set_stack_chunk_type(chunk, map->type);
4355 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4356 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4357 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4358 btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
4359 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
4361 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4362 key.type = BTRFS_CHUNK_ITEM_KEY;
4363 key.offset = chunk_offset;
4365 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4366 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4368 * TODO: Cleanup of inserted chunk root in case of
4369 * failure.
4371 ret = btrfs_add_system_chunk(chunk_root, &key, chunk,
4372 item_size);
4375 out:
4376 kfree(chunk);
4377 free_extent_map(em);
4378 return ret;
4382 * Chunk allocation falls into two parts. The first part does works
4383 * that make the new allocated chunk useable, but not do any operation
4384 * that modifies the chunk tree. The second part does the works that
4385 * require modifying the chunk tree. This division is important for the
4386 * bootstrap process of adding storage to a seed btrfs.
4388 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4389 struct btrfs_root *extent_root, u64 type)
4391 u64 chunk_offset;
4393 chunk_offset = find_next_chunk(extent_root->fs_info);
4394 return __btrfs_alloc_chunk(trans, extent_root, chunk_offset, type);
4397 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
4398 struct btrfs_root *root,
4399 struct btrfs_device *device)
4401 u64 chunk_offset;
4402 u64 sys_chunk_offset;
4403 u64 alloc_profile;
4404 struct btrfs_fs_info *fs_info = root->fs_info;
4405 struct btrfs_root *extent_root = fs_info->extent_root;
4406 int ret;
4408 chunk_offset = find_next_chunk(fs_info);
4409 alloc_profile = btrfs_get_alloc_profile(extent_root, 0);
4410 ret = __btrfs_alloc_chunk(trans, extent_root, chunk_offset,
4411 alloc_profile);
4412 if (ret)
4413 return ret;
4415 sys_chunk_offset = find_next_chunk(root->fs_info);
4416 alloc_profile = btrfs_get_alloc_profile(fs_info->chunk_root, 0);
4417 ret = __btrfs_alloc_chunk(trans, extent_root, sys_chunk_offset,
4418 alloc_profile);
4419 if (ret) {
4420 btrfs_abort_transaction(trans, root, ret);
4421 goto out;
4424 ret = btrfs_add_device(trans, fs_info->chunk_root, device);
4425 if (ret)
4426 btrfs_abort_transaction(trans, root, ret);
4427 out:
4428 return ret;
4431 int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
4433 struct extent_map *em;
4434 struct map_lookup *map;
4435 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4436 int readonly = 0;
4437 int i;
4439 read_lock(&map_tree->map_tree.lock);
4440 em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
4441 read_unlock(&map_tree->map_tree.lock);
4442 if (!em)
4443 return 1;
4445 if (btrfs_test_opt(root, DEGRADED)) {
4446 free_extent_map(em);
4447 return 0;
4450 map = (struct map_lookup *)em->bdev;
4451 for (i = 0; i < map->num_stripes; i++) {
4452 if (!map->stripes[i].dev->writeable) {
4453 readonly = 1;
4454 break;
4457 free_extent_map(em);
4458 return readonly;
4461 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
4463 extent_map_tree_init(&tree->map_tree);
4466 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
4468 struct extent_map *em;
4470 while (1) {
4471 write_lock(&tree->map_tree.lock);
4472 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
4473 if (em)
4474 remove_extent_mapping(&tree->map_tree, em);
4475 write_unlock(&tree->map_tree.lock);
4476 if (!em)
4477 break;
4478 kfree(em->bdev);
4479 /* once for us */
4480 free_extent_map(em);
4481 /* once for the tree */
4482 free_extent_map(em);
4486 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
4488 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
4489 struct extent_map *em;
4490 struct map_lookup *map;
4491 struct extent_map_tree *em_tree = &map_tree->map_tree;
4492 int ret;
4494 read_lock(&em_tree->lock);
4495 em = lookup_extent_mapping(em_tree, logical, len);
4496 read_unlock(&em_tree->lock);
4499 * We could return errors for these cases, but that could get ugly and
4500 * we'd probably do the same thing which is just not do anything else
4501 * and exit, so return 1 so the callers don't try to use other copies.
4503 if (!em) {
4504 btrfs_crit(fs_info, "No mapping for %Lu-%Lu\n", logical,
4505 logical+len);
4506 return 1;
4509 if (em->start > logical || em->start + em->len < logical) {
4510 btrfs_crit(fs_info, "Invalid mapping for %Lu-%Lu, got "
4511 "%Lu-%Lu\n", logical, logical+len, em->start,
4512 em->start + em->len);
4513 free_extent_map(em);
4514 return 1;
4517 map = (struct map_lookup *)em->bdev;
4518 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
4519 ret = map->num_stripes;
4520 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
4521 ret = map->sub_stripes;
4522 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
4523 ret = 2;
4524 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
4525 ret = 3;
4526 else
4527 ret = 1;
4528 free_extent_map(em);
4530 btrfs_dev_replace_lock(&fs_info->dev_replace);
4531 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))
4532 ret++;
4533 btrfs_dev_replace_unlock(&fs_info->dev_replace);
4535 return ret;
4538 unsigned long btrfs_full_stripe_len(struct btrfs_root *root,
4539 struct btrfs_mapping_tree *map_tree,
4540 u64 logical)
4542 struct extent_map *em;
4543 struct map_lookup *map;
4544 struct extent_map_tree *em_tree = &map_tree->map_tree;
4545 unsigned long len = root->sectorsize;
4547 read_lock(&em_tree->lock);
4548 em = lookup_extent_mapping(em_tree, logical, len);
4549 read_unlock(&em_tree->lock);
4550 BUG_ON(!em);
4552 BUG_ON(em->start > logical || em->start + em->len < logical);
4553 map = (struct map_lookup *)em->bdev;
4554 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4555 BTRFS_BLOCK_GROUP_RAID6)) {
4556 len = map->stripe_len * nr_data_stripes(map);
4558 free_extent_map(em);
4559 return len;
4562 int btrfs_is_parity_mirror(struct btrfs_mapping_tree *map_tree,
4563 u64 logical, u64 len, int mirror_num)
4565 struct extent_map *em;
4566 struct map_lookup *map;
4567 struct extent_map_tree *em_tree = &map_tree->map_tree;
4568 int ret = 0;
4570 read_lock(&em_tree->lock);
4571 em = lookup_extent_mapping(em_tree, logical, len);
4572 read_unlock(&em_tree->lock);
4573 BUG_ON(!em);
4575 BUG_ON(em->start > logical || em->start + em->len < logical);
4576 map = (struct map_lookup *)em->bdev;
4577 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4578 BTRFS_BLOCK_GROUP_RAID6))
4579 ret = 1;
4580 free_extent_map(em);
4581 return ret;
4584 static int find_live_mirror(struct btrfs_fs_info *fs_info,
4585 struct map_lookup *map, int first, int num,
4586 int optimal, int dev_replace_is_ongoing)
4588 int i;
4589 int tolerance;
4590 struct btrfs_device *srcdev;
4592 if (dev_replace_is_ongoing &&
4593 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
4594 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
4595 srcdev = fs_info->dev_replace.srcdev;
4596 else
4597 srcdev = NULL;
4600 * try to avoid the drive that is the source drive for a
4601 * dev-replace procedure, only choose it if no other non-missing
4602 * mirror is available
4604 for (tolerance = 0; tolerance < 2; tolerance++) {
4605 if (map->stripes[optimal].dev->bdev &&
4606 (tolerance || map->stripes[optimal].dev != srcdev))
4607 return optimal;
4608 for (i = first; i < first + num; i++) {
4609 if (map->stripes[i].dev->bdev &&
4610 (tolerance || map->stripes[i].dev != srcdev))
4611 return i;
4615 /* we couldn't find one that doesn't fail. Just return something
4616 * and the io error handling code will clean up eventually
4618 return optimal;
4621 static inline int parity_smaller(u64 a, u64 b)
4623 return a > b;
4626 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
4627 static void sort_parity_stripes(struct btrfs_bio *bbio, u64 *raid_map)
4629 struct btrfs_bio_stripe s;
4630 int i;
4631 u64 l;
4632 int again = 1;
4634 while (again) {
4635 again = 0;
4636 for (i = 0; i < bbio->num_stripes - 1; i++) {
4637 if (parity_smaller(raid_map[i], raid_map[i+1])) {
4638 s = bbio->stripes[i];
4639 l = raid_map[i];
4640 bbio->stripes[i] = bbio->stripes[i+1];
4641 raid_map[i] = raid_map[i+1];
4642 bbio->stripes[i+1] = s;
4643 raid_map[i+1] = l;
4644 again = 1;
4650 static int __btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
4651 u64 logical, u64 *length,
4652 struct btrfs_bio **bbio_ret,
4653 int mirror_num, u64 **raid_map_ret)
4655 struct extent_map *em;
4656 struct map_lookup *map;
4657 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
4658 struct extent_map_tree *em_tree = &map_tree->map_tree;
4659 u64 offset;
4660 u64 stripe_offset;
4661 u64 stripe_end_offset;
4662 u64 stripe_nr;
4663 u64 stripe_nr_orig;
4664 u64 stripe_nr_end;
4665 u64 stripe_len;
4666 u64 *raid_map = NULL;
4667 int stripe_index;
4668 int i;
4669 int ret = 0;
4670 int num_stripes;
4671 int max_errors = 0;
4672 struct btrfs_bio *bbio = NULL;
4673 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
4674 int dev_replace_is_ongoing = 0;
4675 int num_alloc_stripes;
4676 int patch_the_first_stripe_for_dev_replace = 0;
4677 u64 physical_to_patch_in_first_stripe = 0;
4678 u64 raid56_full_stripe_start = (u64)-1;
4680 read_lock(&em_tree->lock);
4681 em = lookup_extent_mapping(em_tree, logical, *length);
4682 read_unlock(&em_tree->lock);
4684 if (!em) {
4685 btrfs_crit(fs_info, "unable to find logical %llu len %llu",
4686 logical, *length);
4687 return -EINVAL;
4690 if (em->start > logical || em->start + em->len < logical) {
4691 btrfs_crit(fs_info, "found a bad mapping, wanted %Lu, "
4692 "found %Lu-%Lu\n", logical, em->start,
4693 em->start + em->len);
4694 free_extent_map(em);
4695 return -EINVAL;
4698 map = (struct map_lookup *)em->bdev;
4699 offset = logical - em->start;
4701 stripe_len = map->stripe_len;
4702 stripe_nr = offset;
4704 * stripe_nr counts the total number of stripes we have to stride
4705 * to get to this block
4707 do_div(stripe_nr, stripe_len);
4709 stripe_offset = stripe_nr * stripe_len;
4710 BUG_ON(offset < stripe_offset);
4712 /* stripe_offset is the offset of this block in its stripe*/
4713 stripe_offset = offset - stripe_offset;
4715 /* if we're here for raid56, we need to know the stripe aligned start */
4716 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
4717 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
4718 raid56_full_stripe_start = offset;
4720 /* allow a write of a full stripe, but make sure we don't
4721 * allow straddling of stripes
4723 do_div(raid56_full_stripe_start, full_stripe_len);
4724 raid56_full_stripe_start *= full_stripe_len;
4727 if (rw & REQ_DISCARD) {
4728 /* we don't discard raid56 yet */
4729 if (map->type &
4730 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
4731 ret = -EOPNOTSUPP;
4732 goto out;
4734 *length = min_t(u64, em->len - offset, *length);
4735 } else if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
4736 u64 max_len;
4737 /* For writes to RAID[56], allow a full stripeset across all disks.
4738 For other RAID types and for RAID[56] reads, just allow a single
4739 stripe (on a single disk). */
4740 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6) &&
4741 (rw & REQ_WRITE)) {
4742 max_len = stripe_len * nr_data_stripes(map) -
4743 (offset - raid56_full_stripe_start);
4744 } else {
4745 /* we limit the length of each bio to what fits in a stripe */
4746 max_len = stripe_len - stripe_offset;
4748 *length = min_t(u64, em->len - offset, max_len);
4749 } else {
4750 *length = em->len - offset;
4753 /* This is for when we're called from btrfs_merge_bio_hook() and all
4754 it cares about is the length */
4755 if (!bbio_ret)
4756 goto out;
4758 btrfs_dev_replace_lock(dev_replace);
4759 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
4760 if (!dev_replace_is_ongoing)
4761 btrfs_dev_replace_unlock(dev_replace);
4763 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
4764 !(rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) &&
4765 dev_replace->tgtdev != NULL) {
4767 * in dev-replace case, for repair case (that's the only
4768 * case where the mirror is selected explicitly when
4769 * calling btrfs_map_block), blocks left of the left cursor
4770 * can also be read from the target drive.
4771 * For REQ_GET_READ_MIRRORS, the target drive is added as
4772 * the last one to the array of stripes. For READ, it also
4773 * needs to be supported using the same mirror number.
4774 * If the requested block is not left of the left cursor,
4775 * EIO is returned. This can happen because btrfs_num_copies()
4776 * returns one more in the dev-replace case.
4778 u64 tmp_length = *length;
4779 struct btrfs_bio *tmp_bbio = NULL;
4780 int tmp_num_stripes;
4781 u64 srcdev_devid = dev_replace->srcdev->devid;
4782 int index_srcdev = 0;
4783 int found = 0;
4784 u64 physical_of_found = 0;
4786 ret = __btrfs_map_block(fs_info, REQ_GET_READ_MIRRORS,
4787 logical, &tmp_length, &tmp_bbio, 0, NULL);
4788 if (ret) {
4789 WARN_ON(tmp_bbio != NULL);
4790 goto out;
4793 tmp_num_stripes = tmp_bbio->num_stripes;
4794 if (mirror_num > tmp_num_stripes) {
4796 * REQ_GET_READ_MIRRORS does not contain this
4797 * mirror, that means that the requested area
4798 * is not left of the left cursor
4800 ret = -EIO;
4801 kfree(tmp_bbio);
4802 goto out;
4806 * process the rest of the function using the mirror_num
4807 * of the source drive. Therefore look it up first.
4808 * At the end, patch the device pointer to the one of the
4809 * target drive.
4811 for (i = 0; i < tmp_num_stripes; i++) {
4812 if (tmp_bbio->stripes[i].dev->devid == srcdev_devid) {
4814 * In case of DUP, in order to keep it
4815 * simple, only add the mirror with the
4816 * lowest physical address
4818 if (found &&
4819 physical_of_found <=
4820 tmp_bbio->stripes[i].physical)
4821 continue;
4822 index_srcdev = i;
4823 found = 1;
4824 physical_of_found =
4825 tmp_bbio->stripes[i].physical;
4829 if (found) {
4830 mirror_num = index_srcdev + 1;
4831 patch_the_first_stripe_for_dev_replace = 1;
4832 physical_to_patch_in_first_stripe = physical_of_found;
4833 } else {
4834 WARN_ON(1);
4835 ret = -EIO;
4836 kfree(tmp_bbio);
4837 goto out;
4840 kfree(tmp_bbio);
4841 } else if (mirror_num > map->num_stripes) {
4842 mirror_num = 0;
4845 num_stripes = 1;
4846 stripe_index = 0;
4847 stripe_nr_orig = stripe_nr;
4848 stripe_nr_end = ALIGN(offset + *length, map->stripe_len);
4849 do_div(stripe_nr_end, map->stripe_len);
4850 stripe_end_offset = stripe_nr_end * map->stripe_len -
4851 (offset + *length);
4853 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
4854 if (rw & REQ_DISCARD)
4855 num_stripes = min_t(u64, map->num_stripes,
4856 stripe_nr_end - stripe_nr_orig);
4857 stripe_index = do_div(stripe_nr, map->num_stripes);
4858 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
4859 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS))
4860 num_stripes = map->num_stripes;
4861 else if (mirror_num)
4862 stripe_index = mirror_num - 1;
4863 else {
4864 stripe_index = find_live_mirror(fs_info, map, 0,
4865 map->num_stripes,
4866 current->pid % map->num_stripes,
4867 dev_replace_is_ongoing);
4868 mirror_num = stripe_index + 1;
4871 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
4872 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) {
4873 num_stripes = map->num_stripes;
4874 } else if (mirror_num) {
4875 stripe_index = mirror_num - 1;
4876 } else {
4877 mirror_num = 1;
4880 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
4881 int factor = map->num_stripes / map->sub_stripes;
4883 stripe_index = do_div(stripe_nr, factor);
4884 stripe_index *= map->sub_stripes;
4886 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
4887 num_stripes = map->sub_stripes;
4888 else if (rw & REQ_DISCARD)
4889 num_stripes = min_t(u64, map->sub_stripes *
4890 (stripe_nr_end - stripe_nr_orig),
4891 map->num_stripes);
4892 else if (mirror_num)
4893 stripe_index += mirror_num - 1;
4894 else {
4895 int old_stripe_index = stripe_index;
4896 stripe_index = find_live_mirror(fs_info, map,
4897 stripe_index,
4898 map->sub_stripes, stripe_index +
4899 current->pid % map->sub_stripes,
4900 dev_replace_is_ongoing);
4901 mirror_num = stripe_index - old_stripe_index + 1;
4904 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4905 BTRFS_BLOCK_GROUP_RAID6)) {
4906 u64 tmp;
4908 if (bbio_ret && ((rw & REQ_WRITE) || mirror_num > 1)
4909 && raid_map_ret) {
4910 int i, rot;
4912 /* push stripe_nr back to the start of the full stripe */
4913 stripe_nr = raid56_full_stripe_start;
4914 do_div(stripe_nr, stripe_len);
4916 stripe_index = do_div(stripe_nr, nr_data_stripes(map));
4918 /* RAID[56] write or recovery. Return all stripes */
4919 num_stripes = map->num_stripes;
4920 max_errors = nr_parity_stripes(map);
4922 raid_map = kmalloc(sizeof(u64) * num_stripes,
4923 GFP_NOFS);
4924 if (!raid_map) {
4925 ret = -ENOMEM;
4926 goto out;
4929 /* Work out the disk rotation on this stripe-set */
4930 tmp = stripe_nr;
4931 rot = do_div(tmp, num_stripes);
4933 /* Fill in the logical address of each stripe */
4934 tmp = stripe_nr * nr_data_stripes(map);
4935 for (i = 0; i < nr_data_stripes(map); i++)
4936 raid_map[(i+rot) % num_stripes] =
4937 em->start + (tmp + i) * map->stripe_len;
4939 raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
4940 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
4941 raid_map[(i+rot+1) % num_stripes] =
4942 RAID6_Q_STRIPE;
4944 *length = map->stripe_len;
4945 stripe_index = 0;
4946 stripe_offset = 0;
4947 } else {
4949 * Mirror #0 or #1 means the original data block.
4950 * Mirror #2 is RAID5 parity block.
4951 * Mirror #3 is RAID6 Q block.
4953 stripe_index = do_div(stripe_nr, nr_data_stripes(map));
4954 if (mirror_num > 1)
4955 stripe_index = nr_data_stripes(map) +
4956 mirror_num - 2;
4958 /* We distribute the parity blocks across stripes */
4959 tmp = stripe_nr + stripe_index;
4960 stripe_index = do_div(tmp, map->num_stripes);
4962 } else {
4964 * after this do_div call, stripe_nr is the number of stripes
4965 * on this device we have to walk to find the data, and
4966 * stripe_index is the number of our device in the stripe array
4968 stripe_index = do_div(stripe_nr, map->num_stripes);
4969 mirror_num = stripe_index + 1;
4971 BUG_ON(stripe_index >= map->num_stripes);
4973 num_alloc_stripes = num_stripes;
4974 if (dev_replace_is_ongoing) {
4975 if (rw & (REQ_WRITE | REQ_DISCARD))
4976 num_alloc_stripes <<= 1;
4977 if (rw & REQ_GET_READ_MIRRORS)
4978 num_alloc_stripes++;
4980 bbio = kzalloc(btrfs_bio_size(num_alloc_stripes), GFP_NOFS);
4981 if (!bbio) {
4982 kfree(raid_map);
4983 ret = -ENOMEM;
4984 goto out;
4986 atomic_set(&bbio->error, 0);
4988 if (rw & REQ_DISCARD) {
4989 int factor = 0;
4990 int sub_stripes = 0;
4991 u64 stripes_per_dev = 0;
4992 u32 remaining_stripes = 0;
4993 u32 last_stripe = 0;
4995 if (map->type &
4996 (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
4997 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
4998 sub_stripes = 1;
4999 else
5000 sub_stripes = map->sub_stripes;
5002 factor = map->num_stripes / sub_stripes;
5003 stripes_per_dev = div_u64_rem(stripe_nr_end -
5004 stripe_nr_orig,
5005 factor,
5006 &remaining_stripes);
5007 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5008 last_stripe *= sub_stripes;
5011 for (i = 0; i < num_stripes; i++) {
5012 bbio->stripes[i].physical =
5013 map->stripes[stripe_index].physical +
5014 stripe_offset + stripe_nr * map->stripe_len;
5015 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5017 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5018 BTRFS_BLOCK_GROUP_RAID10)) {
5019 bbio->stripes[i].length = stripes_per_dev *
5020 map->stripe_len;
5022 if (i / sub_stripes < remaining_stripes)
5023 bbio->stripes[i].length +=
5024 map->stripe_len;
5027 * Special for the first stripe and
5028 * the last stripe:
5030 * |-------|...|-------|
5031 * |----------|
5032 * off end_off
5034 if (i < sub_stripes)
5035 bbio->stripes[i].length -=
5036 stripe_offset;
5038 if (stripe_index >= last_stripe &&
5039 stripe_index <= (last_stripe +
5040 sub_stripes - 1))
5041 bbio->stripes[i].length -=
5042 stripe_end_offset;
5044 if (i == sub_stripes - 1)
5045 stripe_offset = 0;
5046 } else
5047 bbio->stripes[i].length = *length;
5049 stripe_index++;
5050 if (stripe_index == map->num_stripes) {
5051 /* This could only happen for RAID0/10 */
5052 stripe_index = 0;
5053 stripe_nr++;
5056 } else {
5057 for (i = 0; i < num_stripes; i++) {
5058 bbio->stripes[i].physical =
5059 map->stripes[stripe_index].physical +
5060 stripe_offset +
5061 stripe_nr * map->stripe_len;
5062 bbio->stripes[i].dev =
5063 map->stripes[stripe_index].dev;
5064 stripe_index++;
5068 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS)) {
5069 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5070 BTRFS_BLOCK_GROUP_RAID10 |
5071 BTRFS_BLOCK_GROUP_RAID5 |
5072 BTRFS_BLOCK_GROUP_DUP)) {
5073 max_errors = 1;
5074 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5075 max_errors = 2;
5079 if (dev_replace_is_ongoing && (rw & (REQ_WRITE | REQ_DISCARD)) &&
5080 dev_replace->tgtdev != NULL) {
5081 int index_where_to_add;
5082 u64 srcdev_devid = dev_replace->srcdev->devid;
5085 * duplicate the write operations while the dev replace
5086 * procedure is running. Since the copying of the old disk
5087 * to the new disk takes place at run time while the
5088 * filesystem is mounted writable, the regular write
5089 * operations to the old disk have to be duplicated to go
5090 * to the new disk as well.
5091 * Note that device->missing is handled by the caller, and
5092 * that the write to the old disk is already set up in the
5093 * stripes array.
5095 index_where_to_add = num_stripes;
5096 for (i = 0; i < num_stripes; i++) {
5097 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5098 /* write to new disk, too */
5099 struct btrfs_bio_stripe *new =
5100 bbio->stripes + index_where_to_add;
5101 struct btrfs_bio_stripe *old =
5102 bbio->stripes + i;
5104 new->physical = old->physical;
5105 new->length = old->length;
5106 new->dev = dev_replace->tgtdev;
5107 index_where_to_add++;
5108 max_errors++;
5111 num_stripes = index_where_to_add;
5112 } else if (dev_replace_is_ongoing && (rw & REQ_GET_READ_MIRRORS) &&
5113 dev_replace->tgtdev != NULL) {
5114 u64 srcdev_devid = dev_replace->srcdev->devid;
5115 int index_srcdev = 0;
5116 int found = 0;
5117 u64 physical_of_found = 0;
5120 * During the dev-replace procedure, the target drive can
5121 * also be used to read data in case it is needed to repair
5122 * a corrupt block elsewhere. This is possible if the
5123 * requested area is left of the left cursor. In this area,
5124 * the target drive is a full copy of the source drive.
5126 for (i = 0; i < num_stripes; i++) {
5127 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5129 * In case of DUP, in order to keep it
5130 * simple, only add the mirror with the
5131 * lowest physical address
5133 if (found &&
5134 physical_of_found <=
5135 bbio->stripes[i].physical)
5136 continue;
5137 index_srcdev = i;
5138 found = 1;
5139 physical_of_found = bbio->stripes[i].physical;
5142 if (found) {
5143 u64 length = map->stripe_len;
5145 if (physical_of_found + length <=
5146 dev_replace->cursor_left) {
5147 struct btrfs_bio_stripe *tgtdev_stripe =
5148 bbio->stripes + num_stripes;
5150 tgtdev_stripe->physical = physical_of_found;
5151 tgtdev_stripe->length =
5152 bbio->stripes[index_srcdev].length;
5153 tgtdev_stripe->dev = dev_replace->tgtdev;
5155 num_stripes++;
5160 *bbio_ret = bbio;
5161 bbio->num_stripes = num_stripes;
5162 bbio->max_errors = max_errors;
5163 bbio->mirror_num = mirror_num;
5166 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5167 * mirror_num == num_stripes + 1 && dev_replace target drive is
5168 * available as a mirror
5170 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5171 WARN_ON(num_stripes > 1);
5172 bbio->stripes[0].dev = dev_replace->tgtdev;
5173 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5174 bbio->mirror_num = map->num_stripes + 1;
5176 if (raid_map) {
5177 sort_parity_stripes(bbio, raid_map);
5178 *raid_map_ret = raid_map;
5180 out:
5181 if (dev_replace_is_ongoing)
5182 btrfs_dev_replace_unlock(dev_replace);
5183 free_extent_map(em);
5184 return ret;
5187 int btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
5188 u64 logical, u64 *length,
5189 struct btrfs_bio **bbio_ret, int mirror_num)
5191 return __btrfs_map_block(fs_info, rw, logical, length, bbio_ret,
5192 mirror_num, NULL);
5195 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
5196 u64 chunk_start, u64 physical, u64 devid,
5197 u64 **logical, int *naddrs, int *stripe_len)
5199 struct extent_map_tree *em_tree = &map_tree->map_tree;
5200 struct extent_map *em;
5201 struct map_lookup *map;
5202 u64 *buf;
5203 u64 bytenr;
5204 u64 length;
5205 u64 stripe_nr;
5206 u64 rmap_len;
5207 int i, j, nr = 0;
5209 read_lock(&em_tree->lock);
5210 em = lookup_extent_mapping(em_tree, chunk_start, 1);
5211 read_unlock(&em_tree->lock);
5213 if (!em) {
5214 printk(KERN_ERR "btrfs: couldn't find em for chunk %Lu\n",
5215 chunk_start);
5216 return -EIO;
5219 if (em->start != chunk_start) {
5220 printk(KERN_ERR "btrfs: bad chunk start, em=%Lu, wanted=%Lu\n",
5221 em->start, chunk_start);
5222 free_extent_map(em);
5223 return -EIO;
5225 map = (struct map_lookup *)em->bdev;
5227 length = em->len;
5228 rmap_len = map->stripe_len;
5230 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5231 do_div(length, map->num_stripes / map->sub_stripes);
5232 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5233 do_div(length, map->num_stripes);
5234 else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
5235 BTRFS_BLOCK_GROUP_RAID6)) {
5236 do_div(length, nr_data_stripes(map));
5237 rmap_len = map->stripe_len * nr_data_stripes(map);
5240 buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
5241 BUG_ON(!buf); /* -ENOMEM */
5243 for (i = 0; i < map->num_stripes; i++) {
5244 if (devid && map->stripes[i].dev->devid != devid)
5245 continue;
5246 if (map->stripes[i].physical > physical ||
5247 map->stripes[i].physical + length <= physical)
5248 continue;
5250 stripe_nr = physical - map->stripes[i].physical;
5251 do_div(stripe_nr, map->stripe_len);
5253 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5254 stripe_nr = stripe_nr * map->num_stripes + i;
5255 do_div(stripe_nr, map->sub_stripes);
5256 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5257 stripe_nr = stripe_nr * map->num_stripes + i;
5258 } /* else if RAID[56], multiply by nr_data_stripes().
5259 * Alternatively, just use rmap_len below instead of
5260 * map->stripe_len */
5262 bytenr = chunk_start + stripe_nr * rmap_len;
5263 WARN_ON(nr >= map->num_stripes);
5264 for (j = 0; j < nr; j++) {
5265 if (buf[j] == bytenr)
5266 break;
5268 if (j == nr) {
5269 WARN_ON(nr >= map->num_stripes);
5270 buf[nr++] = bytenr;
5274 *logical = buf;
5275 *naddrs = nr;
5276 *stripe_len = rmap_len;
5278 free_extent_map(em);
5279 return 0;
5282 static void btrfs_end_bio(struct bio *bio, int err)
5284 struct btrfs_bio *bbio = bio->bi_private;
5285 int is_orig_bio = 0;
5287 if (err) {
5288 atomic_inc(&bbio->error);
5289 if (err == -EIO || err == -EREMOTEIO) {
5290 unsigned int stripe_index =
5291 btrfs_io_bio(bio)->stripe_index;
5292 struct btrfs_device *dev;
5294 BUG_ON(stripe_index >= bbio->num_stripes);
5295 dev = bbio->stripes[stripe_index].dev;
5296 if (dev->bdev) {
5297 if (bio->bi_rw & WRITE)
5298 btrfs_dev_stat_inc(dev,
5299 BTRFS_DEV_STAT_WRITE_ERRS);
5300 else
5301 btrfs_dev_stat_inc(dev,
5302 BTRFS_DEV_STAT_READ_ERRS);
5303 if ((bio->bi_rw & WRITE_FLUSH) == WRITE_FLUSH)
5304 btrfs_dev_stat_inc(dev,
5305 BTRFS_DEV_STAT_FLUSH_ERRS);
5306 btrfs_dev_stat_print_on_error(dev);
5311 if (bio == bbio->orig_bio)
5312 is_orig_bio = 1;
5314 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5315 if (!is_orig_bio) {
5316 bio_put(bio);
5317 bio = bbio->orig_bio;
5319 bio->bi_private = bbio->private;
5320 bio->bi_end_io = bbio->end_io;
5321 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5322 /* only send an error to the higher layers if it is
5323 * beyond the tolerance of the btrfs bio
5325 if (atomic_read(&bbio->error) > bbio->max_errors) {
5326 err = -EIO;
5327 } else {
5329 * this bio is actually up to date, we didn't
5330 * go over the max number of errors
5332 set_bit(BIO_UPTODATE, &bio->bi_flags);
5333 err = 0;
5335 kfree(bbio);
5337 bio_endio(bio, err);
5338 } else if (!is_orig_bio) {
5339 bio_put(bio);
5343 struct async_sched {
5344 struct bio *bio;
5345 int rw;
5346 struct btrfs_fs_info *info;
5347 struct btrfs_work work;
5351 * see run_scheduled_bios for a description of why bios are collected for
5352 * async submit.
5354 * This will add one bio to the pending list for a device and make sure
5355 * the work struct is scheduled.
5357 static noinline void btrfs_schedule_bio(struct btrfs_root *root,
5358 struct btrfs_device *device,
5359 int rw, struct bio *bio)
5361 int should_queue = 1;
5362 struct btrfs_pending_bios *pending_bios;
5364 if (device->missing || !device->bdev) {
5365 bio_endio(bio, -EIO);
5366 return;
5369 /* don't bother with additional async steps for reads, right now */
5370 if (!(rw & REQ_WRITE)) {
5371 bio_get(bio);
5372 btrfsic_submit_bio(rw, bio);
5373 bio_put(bio);
5374 return;
5378 * nr_async_bios allows us to reliably return congestion to the
5379 * higher layers. Otherwise, the async bio makes it appear we have
5380 * made progress against dirty pages when we've really just put it
5381 * on a queue for later
5383 atomic_inc(&root->fs_info->nr_async_bios);
5384 WARN_ON(bio->bi_next);
5385 bio->bi_next = NULL;
5386 bio->bi_rw |= rw;
5388 spin_lock(&device->io_lock);
5389 if (bio->bi_rw & REQ_SYNC)
5390 pending_bios = &device->pending_sync_bios;
5391 else
5392 pending_bios = &device->pending_bios;
5394 if (pending_bios->tail)
5395 pending_bios->tail->bi_next = bio;
5397 pending_bios->tail = bio;
5398 if (!pending_bios->head)
5399 pending_bios->head = bio;
5400 if (device->running_pending)
5401 should_queue = 0;
5403 spin_unlock(&device->io_lock);
5405 if (should_queue)
5406 btrfs_queue_worker(&root->fs_info->submit_workers,
5407 &device->work);
5410 static int bio_size_ok(struct block_device *bdev, struct bio *bio,
5411 sector_t sector)
5413 struct bio_vec *prev;
5414 struct request_queue *q = bdev_get_queue(bdev);
5415 unsigned short max_sectors = queue_max_sectors(q);
5416 struct bvec_merge_data bvm = {
5417 .bi_bdev = bdev,
5418 .bi_sector = sector,
5419 .bi_rw = bio->bi_rw,
5422 if (bio->bi_vcnt == 0) {
5423 WARN_ON(1);
5424 return 1;
5427 prev = &bio->bi_io_vec[bio->bi_vcnt - 1];
5428 if (bio_sectors(bio) > max_sectors)
5429 return 0;
5431 if (!q->merge_bvec_fn)
5432 return 1;
5434 bvm.bi_size = bio->bi_size - prev->bv_len;
5435 if (q->merge_bvec_fn(q, &bvm, prev) < prev->bv_len)
5436 return 0;
5437 return 1;
5440 static void submit_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5441 struct bio *bio, u64 physical, int dev_nr,
5442 int rw, int async)
5444 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
5446 bio->bi_private = bbio;
5447 btrfs_io_bio(bio)->stripe_index = dev_nr;
5448 bio->bi_end_io = btrfs_end_bio;
5449 bio->bi_sector = physical >> 9;
5450 #ifdef DEBUG
5452 struct rcu_string *name;
5454 rcu_read_lock();
5455 name = rcu_dereference(dev->name);
5456 pr_debug("btrfs_map_bio: rw %d, sector=%llu, dev=%lu "
5457 "(%s id %llu), size=%u\n", rw,
5458 (u64)bio->bi_sector, (u_long)dev->bdev->bd_dev,
5459 name->str, dev->devid, bio->bi_size);
5460 rcu_read_unlock();
5462 #endif
5463 bio->bi_bdev = dev->bdev;
5464 if (async)
5465 btrfs_schedule_bio(root, dev, rw, bio);
5466 else
5467 btrfsic_submit_bio(rw, bio);
5470 static int breakup_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5471 struct bio *first_bio, struct btrfs_device *dev,
5472 int dev_nr, int rw, int async)
5474 struct bio_vec *bvec = first_bio->bi_io_vec;
5475 struct bio *bio;
5476 int nr_vecs = bio_get_nr_vecs(dev->bdev);
5477 u64 physical = bbio->stripes[dev_nr].physical;
5479 again:
5480 bio = btrfs_bio_alloc(dev->bdev, physical >> 9, nr_vecs, GFP_NOFS);
5481 if (!bio)
5482 return -ENOMEM;
5484 while (bvec <= (first_bio->bi_io_vec + first_bio->bi_vcnt - 1)) {
5485 if (bio_add_page(bio, bvec->bv_page, bvec->bv_len,
5486 bvec->bv_offset) < bvec->bv_len) {
5487 u64 len = bio->bi_size;
5489 atomic_inc(&bbio->stripes_pending);
5490 submit_stripe_bio(root, bbio, bio, physical, dev_nr,
5491 rw, async);
5492 physical += len;
5493 goto again;
5495 bvec++;
5498 submit_stripe_bio(root, bbio, bio, physical, dev_nr, rw, async);
5499 return 0;
5502 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
5504 atomic_inc(&bbio->error);
5505 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5506 bio->bi_private = bbio->private;
5507 bio->bi_end_io = bbio->end_io;
5508 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5509 bio->bi_sector = logical >> 9;
5510 kfree(bbio);
5511 bio_endio(bio, -EIO);
5515 int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
5516 int mirror_num, int async_submit)
5518 struct btrfs_device *dev;
5519 struct bio *first_bio = bio;
5520 u64 logical = (u64)bio->bi_sector << 9;
5521 u64 length = 0;
5522 u64 map_length;
5523 u64 *raid_map = NULL;
5524 int ret;
5525 int dev_nr = 0;
5526 int total_devs = 1;
5527 struct btrfs_bio *bbio = NULL;
5529 length = bio->bi_size;
5530 map_length = length;
5532 ret = __btrfs_map_block(root->fs_info, rw, logical, &map_length, &bbio,
5533 mirror_num, &raid_map);
5534 if (ret) /* -ENOMEM */
5535 return ret;
5537 total_devs = bbio->num_stripes;
5538 bbio->orig_bio = first_bio;
5539 bbio->private = first_bio->bi_private;
5540 bbio->end_io = first_bio->bi_end_io;
5541 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
5543 if (raid_map) {
5544 /* In this case, map_length has been set to the length of
5545 a single stripe; not the whole write */
5546 if (rw & WRITE) {
5547 return raid56_parity_write(root, bio, bbio,
5548 raid_map, map_length);
5549 } else {
5550 return raid56_parity_recover(root, bio, bbio,
5551 raid_map, map_length,
5552 mirror_num);
5556 if (map_length < length) {
5557 btrfs_crit(root->fs_info, "mapping failed logical %llu bio len %llu len %llu",
5558 logical, length, map_length);
5559 BUG();
5562 while (dev_nr < total_devs) {
5563 dev = bbio->stripes[dev_nr].dev;
5564 if (!dev || !dev->bdev || (rw & WRITE && !dev->writeable)) {
5565 bbio_error(bbio, first_bio, logical);
5566 dev_nr++;
5567 continue;
5571 * Check and see if we're ok with this bio based on it's size
5572 * and offset with the given device.
5574 if (!bio_size_ok(dev->bdev, first_bio,
5575 bbio->stripes[dev_nr].physical >> 9)) {
5576 ret = breakup_stripe_bio(root, bbio, first_bio, dev,
5577 dev_nr, rw, async_submit);
5578 BUG_ON(ret);
5579 dev_nr++;
5580 continue;
5583 if (dev_nr < total_devs - 1) {
5584 bio = btrfs_bio_clone(first_bio, GFP_NOFS);
5585 BUG_ON(!bio); /* -ENOMEM */
5586 } else {
5587 bio = first_bio;
5590 submit_stripe_bio(root, bbio, bio,
5591 bbio->stripes[dev_nr].physical, dev_nr, rw,
5592 async_submit);
5593 dev_nr++;
5595 return 0;
5598 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
5599 u8 *uuid, u8 *fsid)
5601 struct btrfs_device *device;
5602 struct btrfs_fs_devices *cur_devices;
5604 cur_devices = fs_info->fs_devices;
5605 while (cur_devices) {
5606 if (!fsid ||
5607 !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
5608 device = __find_device(&cur_devices->devices,
5609 devid, uuid);
5610 if (device)
5611 return device;
5613 cur_devices = cur_devices->seed;
5615 return NULL;
5618 static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
5619 u64 devid, u8 *dev_uuid)
5621 struct btrfs_device *device;
5622 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
5624 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
5625 if (IS_ERR(device))
5626 return NULL;
5628 list_add(&device->dev_list, &fs_devices->devices);
5629 device->fs_devices = fs_devices;
5630 fs_devices->num_devices++;
5632 device->missing = 1;
5633 fs_devices->missing_devices++;
5635 return device;
5639 * btrfs_alloc_device - allocate struct btrfs_device
5640 * @fs_info: used only for generating a new devid, can be NULL if
5641 * devid is provided (i.e. @devid != NULL).
5642 * @devid: a pointer to devid for this device. If NULL a new devid
5643 * is generated.
5644 * @uuid: a pointer to UUID for this device. If NULL a new UUID
5645 * is generated.
5647 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
5648 * on error. Returned struct is not linked onto any lists and can be
5649 * destroyed with kfree() right away.
5651 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
5652 const u64 *devid,
5653 const u8 *uuid)
5655 struct btrfs_device *dev;
5656 u64 tmp;
5658 if (!devid && !fs_info) {
5659 WARN_ON(1);
5660 return ERR_PTR(-EINVAL);
5663 dev = __alloc_device();
5664 if (IS_ERR(dev))
5665 return dev;
5667 if (devid)
5668 tmp = *devid;
5669 else {
5670 int ret;
5672 ret = find_next_devid(fs_info, &tmp);
5673 if (ret) {
5674 kfree(dev);
5675 return ERR_PTR(ret);
5678 dev->devid = tmp;
5680 if (uuid)
5681 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
5682 else
5683 generate_random_uuid(dev->uuid);
5685 dev->work.func = pending_bios_fn;
5687 return dev;
5690 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
5691 struct extent_buffer *leaf,
5692 struct btrfs_chunk *chunk)
5694 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
5695 struct map_lookup *map;
5696 struct extent_map *em;
5697 u64 logical;
5698 u64 length;
5699 u64 devid;
5700 u8 uuid[BTRFS_UUID_SIZE];
5701 int num_stripes;
5702 int ret;
5703 int i;
5705 logical = key->offset;
5706 length = btrfs_chunk_length(leaf, chunk);
5708 read_lock(&map_tree->map_tree.lock);
5709 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
5710 read_unlock(&map_tree->map_tree.lock);
5712 /* already mapped? */
5713 if (em && em->start <= logical && em->start + em->len > logical) {
5714 free_extent_map(em);
5715 return 0;
5716 } else if (em) {
5717 free_extent_map(em);
5720 em = alloc_extent_map();
5721 if (!em)
5722 return -ENOMEM;
5723 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
5724 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
5725 if (!map) {
5726 free_extent_map(em);
5727 return -ENOMEM;
5730 em->bdev = (struct block_device *)map;
5731 em->start = logical;
5732 em->len = length;
5733 em->orig_start = 0;
5734 em->block_start = 0;
5735 em->block_len = em->len;
5737 map->num_stripes = num_stripes;
5738 map->io_width = btrfs_chunk_io_width(leaf, chunk);
5739 map->io_align = btrfs_chunk_io_align(leaf, chunk);
5740 map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
5741 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
5742 map->type = btrfs_chunk_type(leaf, chunk);
5743 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
5744 for (i = 0; i < num_stripes; i++) {
5745 map->stripes[i].physical =
5746 btrfs_stripe_offset_nr(leaf, chunk, i);
5747 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
5748 read_extent_buffer(leaf, uuid, (unsigned long)
5749 btrfs_stripe_dev_uuid_nr(chunk, i),
5750 BTRFS_UUID_SIZE);
5751 map->stripes[i].dev = btrfs_find_device(root->fs_info, devid,
5752 uuid, NULL);
5753 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
5754 kfree(map);
5755 free_extent_map(em);
5756 return -EIO;
5758 if (!map->stripes[i].dev) {
5759 map->stripes[i].dev =
5760 add_missing_dev(root, devid, uuid);
5761 if (!map->stripes[i].dev) {
5762 kfree(map);
5763 free_extent_map(em);
5764 return -EIO;
5767 map->stripes[i].dev->in_fs_metadata = 1;
5770 write_lock(&map_tree->map_tree.lock);
5771 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
5772 write_unlock(&map_tree->map_tree.lock);
5773 BUG_ON(ret); /* Tree corruption */
5774 free_extent_map(em);
5776 return 0;
5779 static void fill_device_from_item(struct extent_buffer *leaf,
5780 struct btrfs_dev_item *dev_item,
5781 struct btrfs_device *device)
5783 unsigned long ptr;
5785 device->devid = btrfs_device_id(leaf, dev_item);
5786 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
5787 device->total_bytes = device->disk_total_bytes;
5788 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
5789 device->type = btrfs_device_type(leaf, dev_item);
5790 device->io_align = btrfs_device_io_align(leaf, dev_item);
5791 device->io_width = btrfs_device_io_width(leaf, dev_item);
5792 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
5793 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
5794 device->is_tgtdev_for_dev_replace = 0;
5796 ptr = btrfs_device_uuid(dev_item);
5797 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
5800 static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
5802 struct btrfs_fs_devices *fs_devices;
5803 int ret;
5805 BUG_ON(!mutex_is_locked(&uuid_mutex));
5807 fs_devices = root->fs_info->fs_devices->seed;
5808 while (fs_devices) {
5809 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
5810 ret = 0;
5811 goto out;
5813 fs_devices = fs_devices->seed;
5816 fs_devices = find_fsid(fsid);
5817 if (!fs_devices) {
5818 ret = -ENOENT;
5819 goto out;
5822 fs_devices = clone_fs_devices(fs_devices);
5823 if (IS_ERR(fs_devices)) {
5824 ret = PTR_ERR(fs_devices);
5825 goto out;
5828 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
5829 root->fs_info->bdev_holder);
5830 if (ret) {
5831 free_fs_devices(fs_devices);
5832 goto out;
5835 if (!fs_devices->seeding) {
5836 __btrfs_close_devices(fs_devices);
5837 free_fs_devices(fs_devices);
5838 ret = -EINVAL;
5839 goto out;
5842 fs_devices->seed = root->fs_info->fs_devices->seed;
5843 root->fs_info->fs_devices->seed = fs_devices;
5844 out:
5845 return ret;
5848 static int read_one_dev(struct btrfs_root *root,
5849 struct extent_buffer *leaf,
5850 struct btrfs_dev_item *dev_item)
5852 struct btrfs_device *device;
5853 u64 devid;
5854 int ret;
5855 u8 fs_uuid[BTRFS_UUID_SIZE];
5856 u8 dev_uuid[BTRFS_UUID_SIZE];
5858 devid = btrfs_device_id(leaf, dev_item);
5859 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
5860 BTRFS_UUID_SIZE);
5861 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
5862 BTRFS_UUID_SIZE);
5864 if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
5865 ret = open_seed_devices(root, fs_uuid);
5866 if (ret && !btrfs_test_opt(root, DEGRADED))
5867 return ret;
5870 device = btrfs_find_device(root->fs_info, devid, dev_uuid, fs_uuid);
5871 if (!device || !device->bdev) {
5872 if (!btrfs_test_opt(root, DEGRADED))
5873 return -EIO;
5875 if (!device) {
5876 btrfs_warn(root->fs_info, "devid %llu missing", devid);
5877 device = add_missing_dev(root, devid, dev_uuid);
5878 if (!device)
5879 return -ENOMEM;
5880 } else if (!device->missing) {
5882 * this happens when a device that was properly setup
5883 * in the device info lists suddenly goes bad.
5884 * device->bdev is NULL, and so we have to set
5885 * device->missing to one here
5887 root->fs_info->fs_devices->missing_devices++;
5888 device->missing = 1;
5892 if (device->fs_devices != root->fs_info->fs_devices) {
5893 BUG_ON(device->writeable);
5894 if (device->generation !=
5895 btrfs_device_generation(leaf, dev_item))
5896 return -EINVAL;
5899 fill_device_from_item(leaf, dev_item, device);
5900 device->in_fs_metadata = 1;
5901 if (device->writeable && !device->is_tgtdev_for_dev_replace) {
5902 device->fs_devices->total_rw_bytes += device->total_bytes;
5903 spin_lock(&root->fs_info->free_chunk_lock);
5904 root->fs_info->free_chunk_space += device->total_bytes -
5905 device->bytes_used;
5906 spin_unlock(&root->fs_info->free_chunk_lock);
5908 ret = 0;
5909 return ret;
5912 int btrfs_read_sys_array(struct btrfs_root *root)
5914 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
5915 struct extent_buffer *sb;
5916 struct btrfs_disk_key *disk_key;
5917 struct btrfs_chunk *chunk;
5918 u8 *ptr;
5919 unsigned long sb_ptr;
5920 int ret = 0;
5921 u32 num_stripes;
5922 u32 array_size;
5923 u32 len = 0;
5924 u32 cur;
5925 struct btrfs_key key;
5927 sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
5928 BTRFS_SUPER_INFO_SIZE);
5929 if (!sb)
5930 return -ENOMEM;
5931 btrfs_set_buffer_uptodate(sb);
5932 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
5934 * The sb extent buffer is artifical and just used to read the system array.
5935 * btrfs_set_buffer_uptodate() call does not properly mark all it's
5936 * pages up-to-date when the page is larger: extent does not cover the
5937 * whole page and consequently check_page_uptodate does not find all
5938 * the page's extents up-to-date (the hole beyond sb),
5939 * write_extent_buffer then triggers a WARN_ON.
5941 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
5942 * but sb spans only this function. Add an explicit SetPageUptodate call
5943 * to silence the warning eg. on PowerPC 64.
5945 if (PAGE_CACHE_SIZE > BTRFS_SUPER_INFO_SIZE)
5946 SetPageUptodate(sb->pages[0]);
5948 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
5949 array_size = btrfs_super_sys_array_size(super_copy);
5951 ptr = super_copy->sys_chunk_array;
5952 sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
5953 cur = 0;
5955 while (cur < array_size) {
5956 disk_key = (struct btrfs_disk_key *)ptr;
5957 btrfs_disk_key_to_cpu(&key, disk_key);
5959 len = sizeof(*disk_key); ptr += len;
5960 sb_ptr += len;
5961 cur += len;
5963 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
5964 chunk = (struct btrfs_chunk *)sb_ptr;
5965 ret = read_one_chunk(root, &key, sb, chunk);
5966 if (ret)
5967 break;
5968 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
5969 len = btrfs_chunk_item_size(num_stripes);
5970 } else {
5971 ret = -EIO;
5972 break;
5974 ptr += len;
5975 sb_ptr += len;
5976 cur += len;
5978 free_extent_buffer(sb);
5979 return ret;
5982 int btrfs_read_chunk_tree(struct btrfs_root *root)
5984 struct btrfs_path *path;
5985 struct extent_buffer *leaf;
5986 struct btrfs_key key;
5987 struct btrfs_key found_key;
5988 int ret;
5989 int slot;
5991 root = root->fs_info->chunk_root;
5993 path = btrfs_alloc_path();
5994 if (!path)
5995 return -ENOMEM;
5997 mutex_lock(&uuid_mutex);
5998 lock_chunks(root);
6001 * Read all device items, and then all the chunk items. All
6002 * device items are found before any chunk item (their object id
6003 * is smaller than the lowest possible object id for a chunk
6004 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6006 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6007 key.offset = 0;
6008 key.type = 0;
6009 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6010 if (ret < 0)
6011 goto error;
6012 while (1) {
6013 leaf = path->nodes[0];
6014 slot = path->slots[0];
6015 if (slot >= btrfs_header_nritems(leaf)) {
6016 ret = btrfs_next_leaf(root, path);
6017 if (ret == 0)
6018 continue;
6019 if (ret < 0)
6020 goto error;
6021 break;
6023 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6024 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6025 struct btrfs_dev_item *dev_item;
6026 dev_item = btrfs_item_ptr(leaf, slot,
6027 struct btrfs_dev_item);
6028 ret = read_one_dev(root, leaf, dev_item);
6029 if (ret)
6030 goto error;
6031 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6032 struct btrfs_chunk *chunk;
6033 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6034 ret = read_one_chunk(root, &found_key, leaf, chunk);
6035 if (ret)
6036 goto error;
6038 path->slots[0]++;
6040 ret = 0;
6041 error:
6042 unlock_chunks(root);
6043 mutex_unlock(&uuid_mutex);
6045 btrfs_free_path(path);
6046 return ret;
6049 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6051 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6052 struct btrfs_device *device;
6054 while (fs_devices) {
6055 mutex_lock(&fs_devices->device_list_mutex);
6056 list_for_each_entry(device, &fs_devices->devices, dev_list)
6057 device->dev_root = fs_info->dev_root;
6058 mutex_unlock(&fs_devices->device_list_mutex);
6060 fs_devices = fs_devices->seed;
6064 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
6066 int i;
6068 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6069 btrfs_dev_stat_reset(dev, i);
6072 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
6074 struct btrfs_key key;
6075 struct btrfs_key found_key;
6076 struct btrfs_root *dev_root = fs_info->dev_root;
6077 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6078 struct extent_buffer *eb;
6079 int slot;
6080 int ret = 0;
6081 struct btrfs_device *device;
6082 struct btrfs_path *path = NULL;
6083 int i;
6085 path = btrfs_alloc_path();
6086 if (!path) {
6087 ret = -ENOMEM;
6088 goto out;
6091 mutex_lock(&fs_devices->device_list_mutex);
6092 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6093 int item_size;
6094 struct btrfs_dev_stats_item *ptr;
6096 key.objectid = 0;
6097 key.type = BTRFS_DEV_STATS_KEY;
6098 key.offset = device->devid;
6099 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
6100 if (ret) {
6101 __btrfs_reset_dev_stats(device);
6102 device->dev_stats_valid = 1;
6103 btrfs_release_path(path);
6104 continue;
6106 slot = path->slots[0];
6107 eb = path->nodes[0];
6108 btrfs_item_key_to_cpu(eb, &found_key, slot);
6109 item_size = btrfs_item_size_nr(eb, slot);
6111 ptr = btrfs_item_ptr(eb, slot,
6112 struct btrfs_dev_stats_item);
6114 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6115 if (item_size >= (1 + i) * sizeof(__le64))
6116 btrfs_dev_stat_set(device, i,
6117 btrfs_dev_stats_value(eb, ptr, i));
6118 else
6119 btrfs_dev_stat_reset(device, i);
6122 device->dev_stats_valid = 1;
6123 btrfs_dev_stat_print_on_load(device);
6124 btrfs_release_path(path);
6126 mutex_unlock(&fs_devices->device_list_mutex);
6128 out:
6129 btrfs_free_path(path);
6130 return ret < 0 ? ret : 0;
6133 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
6134 struct btrfs_root *dev_root,
6135 struct btrfs_device *device)
6137 struct btrfs_path *path;
6138 struct btrfs_key key;
6139 struct extent_buffer *eb;
6140 struct btrfs_dev_stats_item *ptr;
6141 int ret;
6142 int i;
6144 key.objectid = 0;
6145 key.type = BTRFS_DEV_STATS_KEY;
6146 key.offset = device->devid;
6148 path = btrfs_alloc_path();
6149 BUG_ON(!path);
6150 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
6151 if (ret < 0) {
6152 printk_in_rcu(KERN_WARNING "btrfs: error %d while searching for dev_stats item for device %s!\n",
6153 ret, rcu_str_deref(device->name));
6154 goto out;
6157 if (ret == 0 &&
6158 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
6159 /* need to delete old one and insert a new one */
6160 ret = btrfs_del_item(trans, dev_root, path);
6161 if (ret != 0) {
6162 printk_in_rcu(KERN_WARNING "btrfs: delete too small dev_stats item for device %s failed %d!\n",
6163 rcu_str_deref(device->name), ret);
6164 goto out;
6166 ret = 1;
6169 if (ret == 1) {
6170 /* need to insert a new item */
6171 btrfs_release_path(path);
6172 ret = btrfs_insert_empty_item(trans, dev_root, path,
6173 &key, sizeof(*ptr));
6174 if (ret < 0) {
6175 printk_in_rcu(KERN_WARNING "btrfs: insert dev_stats item for device %s failed %d!\n",
6176 rcu_str_deref(device->name), ret);
6177 goto out;
6181 eb = path->nodes[0];
6182 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
6183 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6184 btrfs_set_dev_stats_value(eb, ptr, i,
6185 btrfs_dev_stat_read(device, i));
6186 btrfs_mark_buffer_dirty(eb);
6188 out:
6189 btrfs_free_path(path);
6190 return ret;
6194 * called from commit_transaction. Writes all changed device stats to disk.
6196 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
6197 struct btrfs_fs_info *fs_info)
6199 struct btrfs_root *dev_root = fs_info->dev_root;
6200 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6201 struct btrfs_device *device;
6202 int ret = 0;
6204 mutex_lock(&fs_devices->device_list_mutex);
6205 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6206 if (!device->dev_stats_valid || !device->dev_stats_dirty)
6207 continue;
6209 ret = update_dev_stat_item(trans, dev_root, device);
6210 if (!ret)
6211 device->dev_stats_dirty = 0;
6213 mutex_unlock(&fs_devices->device_list_mutex);
6215 return ret;
6218 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
6220 btrfs_dev_stat_inc(dev, index);
6221 btrfs_dev_stat_print_on_error(dev);
6224 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
6226 if (!dev->dev_stats_valid)
6227 return;
6228 printk_ratelimited_in_rcu(KERN_ERR
6229 "btrfs: bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
6230 rcu_str_deref(dev->name),
6231 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6232 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6233 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6234 btrfs_dev_stat_read(dev,
6235 BTRFS_DEV_STAT_CORRUPTION_ERRS),
6236 btrfs_dev_stat_read(dev,
6237 BTRFS_DEV_STAT_GENERATION_ERRS));
6240 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
6242 int i;
6244 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6245 if (btrfs_dev_stat_read(dev, i) != 0)
6246 break;
6247 if (i == BTRFS_DEV_STAT_VALUES_MAX)
6248 return; /* all values == 0, suppress message */
6250 printk_in_rcu(KERN_INFO "btrfs: bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
6251 rcu_str_deref(dev->name),
6252 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6253 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6254 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6255 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6256 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6259 int btrfs_get_dev_stats(struct btrfs_root *root,
6260 struct btrfs_ioctl_get_dev_stats *stats)
6262 struct btrfs_device *dev;
6263 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
6264 int i;
6266 mutex_lock(&fs_devices->device_list_mutex);
6267 dev = btrfs_find_device(root->fs_info, stats->devid, NULL, NULL);
6268 mutex_unlock(&fs_devices->device_list_mutex);
6270 if (!dev) {
6271 printk(KERN_WARNING
6272 "btrfs: get dev_stats failed, device not found\n");
6273 return -ENODEV;
6274 } else if (!dev->dev_stats_valid) {
6275 printk(KERN_WARNING
6276 "btrfs: get dev_stats failed, not yet valid\n");
6277 return -ENODEV;
6278 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
6279 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6280 if (stats->nr_items > i)
6281 stats->values[i] =
6282 btrfs_dev_stat_read_and_reset(dev, i);
6283 else
6284 btrfs_dev_stat_reset(dev, i);
6286 } else {
6287 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6288 if (stats->nr_items > i)
6289 stats->values[i] = btrfs_dev_stat_read(dev, i);
6291 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
6292 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
6293 return 0;
6296 int btrfs_scratch_superblock(struct btrfs_device *device)
6298 struct buffer_head *bh;
6299 struct btrfs_super_block *disk_super;
6301 bh = btrfs_read_dev_super(device->bdev);
6302 if (!bh)
6303 return -EINVAL;
6304 disk_super = (struct btrfs_super_block *)bh->b_data;
6306 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
6307 set_buffer_dirty(bh);
6308 sync_dirty_buffer(bh);
6309 brelse(bh);
6311 return 0;