Btrfs: update the comment of total_bytes and disk_total_bytes of btrfs_devie
[deliverable/linux.git] / fs / btrfs / volumes.c
... / ...
CommitLineData
1/*
2 * Copyright (C) 2007 Oracle. All rights reserved.
3 *
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.
7 *
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.
12 *
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.
17 */
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 "ctree.h"
32#include "extent_map.h"
33#include "disk-io.h"
34#include "transaction.h"
35#include "print-tree.h"
36#include "volumes.h"
37#include "raid56.h"
38#include "async-thread.h"
39#include "check-integrity.h"
40#include "rcu-string.h"
41#include "math.h"
42#include "dev-replace.h"
43#include "sysfs.h"
44
45static int init_first_rw_device(struct btrfs_trans_handle *trans,
46 struct btrfs_root *root,
47 struct btrfs_device *device);
48static int btrfs_relocate_sys_chunks(struct btrfs_root *root);
49static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
50static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
51static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
52
53static DEFINE_MUTEX(uuid_mutex);
54static LIST_HEAD(fs_uuids);
55
56static void lock_chunks(struct btrfs_root *root)
57{
58 mutex_lock(&root->fs_info->chunk_mutex);
59}
60
61static void unlock_chunks(struct btrfs_root *root)
62{
63 mutex_unlock(&root->fs_info->chunk_mutex);
64}
65
66static struct btrfs_fs_devices *__alloc_fs_devices(void)
67{
68 struct btrfs_fs_devices *fs_devs;
69
70 fs_devs = kzalloc(sizeof(*fs_devs), GFP_NOFS);
71 if (!fs_devs)
72 return ERR_PTR(-ENOMEM);
73
74 mutex_init(&fs_devs->device_list_mutex);
75
76 INIT_LIST_HEAD(&fs_devs->devices);
77 INIT_LIST_HEAD(&fs_devs->alloc_list);
78 INIT_LIST_HEAD(&fs_devs->list);
79
80 return fs_devs;
81}
82
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.
87 *
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.
91 */
92static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
93{
94 struct btrfs_fs_devices *fs_devs;
95
96 fs_devs = __alloc_fs_devices();
97 if (IS_ERR(fs_devs))
98 return fs_devs;
99
100 if (fsid)
101 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
102 else
103 generate_random_uuid(fs_devs->fsid);
104
105 return fs_devs;
106}
107
108static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
109{
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);
118 }
119 kfree(fs_devices);
120}
121
122static void btrfs_kobject_uevent(struct block_device *bdev,
123 enum kobject_action action)
124{
125 int ret;
126
127 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
128 if (ret)
129 pr_warn("BTRFS: 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);
133}
134
135void btrfs_cleanup_fs_uuids(void)
136{
137 struct btrfs_fs_devices *fs_devices;
138
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);
144 }
145}
146
147static struct btrfs_device *__alloc_device(void)
148{
149 struct btrfs_device *dev;
150
151 dev = kzalloc(sizeof(*dev), GFP_NOFS);
152 if (!dev)
153 return ERR_PTR(-ENOMEM);
154
155 INIT_LIST_HEAD(&dev->dev_list);
156 INIT_LIST_HEAD(&dev->dev_alloc_list);
157
158 spin_lock_init(&dev->io_lock);
159
160 spin_lock_init(&dev->reada_lock);
161 atomic_set(&dev->reada_in_flight, 0);
162 atomic_set(&dev->dev_stats_ccnt, 0);
163 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_WAIT);
164 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_WAIT);
165
166 return dev;
167}
168
169static noinline struct btrfs_device *__find_device(struct list_head *head,
170 u64 devid, u8 *uuid)
171{
172 struct btrfs_device *dev;
173
174 list_for_each_entry(dev, head, dev_list) {
175 if (dev->devid == devid &&
176 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
177 return dev;
178 }
179 }
180 return NULL;
181}
182
183static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
184{
185 struct btrfs_fs_devices *fs_devices;
186
187 list_for_each_entry(fs_devices, &fs_uuids, list) {
188 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
189 return fs_devices;
190 }
191 return NULL;
192}
193
194static int
195btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
196 int flush, struct block_device **bdev,
197 struct buffer_head **bh)
198{
199 int ret;
200
201 *bdev = blkdev_get_by_path(device_path, flags, holder);
202
203 if (IS_ERR(*bdev)) {
204 ret = PTR_ERR(*bdev);
205 printk(KERN_INFO "BTRFS: open %s failed\n", device_path);
206 goto error;
207 }
208
209 if (flush)
210 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
211 ret = set_blocksize(*bdev, 4096);
212 if (ret) {
213 blkdev_put(*bdev, flags);
214 goto error;
215 }
216 invalidate_bdev(*bdev);
217 *bh = btrfs_read_dev_super(*bdev);
218 if (!*bh) {
219 ret = -EINVAL;
220 blkdev_put(*bdev, flags);
221 goto error;
222 }
223
224 return 0;
225
226error:
227 *bdev = NULL;
228 *bh = NULL;
229 return ret;
230}
231
232static void requeue_list(struct btrfs_pending_bios *pending_bios,
233 struct bio *head, struct bio *tail)
234{
235
236 struct bio *old_head;
237
238 old_head = pending_bios->head;
239 pending_bios->head = head;
240 if (pending_bios->tail)
241 tail->bi_next = old_head;
242 else
243 pending_bios->tail = tail;
244}
245
246/*
247 * we try to collect pending bios for a device so we don't get a large
248 * number of procs sending bios down to the same device. This greatly
249 * improves the schedulers ability to collect and merge the bios.
250 *
251 * But, it also turns into a long list of bios to process and that is sure
252 * to eventually make the worker thread block. The solution here is to
253 * make some progress and then put this work struct back at the end of
254 * the list if the block device is congested. This way, multiple devices
255 * can make progress from a single worker thread.
256 */
257static noinline void run_scheduled_bios(struct btrfs_device *device)
258{
259 struct bio *pending;
260 struct backing_dev_info *bdi;
261 struct btrfs_fs_info *fs_info;
262 struct btrfs_pending_bios *pending_bios;
263 struct bio *tail;
264 struct bio *cur;
265 int again = 0;
266 unsigned long num_run;
267 unsigned long batch_run = 0;
268 unsigned long limit;
269 unsigned long last_waited = 0;
270 int force_reg = 0;
271 int sync_pending = 0;
272 struct blk_plug plug;
273
274 /*
275 * this function runs all the bios we've collected for
276 * a particular device. We don't want to wander off to
277 * another device without first sending all of these down.
278 * So, setup a plug here and finish it off before we return
279 */
280 blk_start_plug(&plug);
281
282 bdi = blk_get_backing_dev_info(device->bdev);
283 fs_info = device->dev_root->fs_info;
284 limit = btrfs_async_submit_limit(fs_info);
285 limit = limit * 2 / 3;
286
287loop:
288 spin_lock(&device->io_lock);
289
290loop_lock:
291 num_run = 0;
292
293 /* take all the bios off the list at once and process them
294 * later on (without the lock held). But, remember the
295 * tail and other pointers so the bios can be properly reinserted
296 * into the list if we hit congestion
297 */
298 if (!force_reg && device->pending_sync_bios.head) {
299 pending_bios = &device->pending_sync_bios;
300 force_reg = 1;
301 } else {
302 pending_bios = &device->pending_bios;
303 force_reg = 0;
304 }
305
306 pending = pending_bios->head;
307 tail = pending_bios->tail;
308 WARN_ON(pending && !tail);
309
310 /*
311 * if pending was null this time around, no bios need processing
312 * at all and we can stop. Otherwise it'll loop back up again
313 * and do an additional check so no bios are missed.
314 *
315 * device->running_pending is used to synchronize with the
316 * schedule_bio code.
317 */
318 if (device->pending_sync_bios.head == NULL &&
319 device->pending_bios.head == NULL) {
320 again = 0;
321 device->running_pending = 0;
322 } else {
323 again = 1;
324 device->running_pending = 1;
325 }
326
327 pending_bios->head = NULL;
328 pending_bios->tail = NULL;
329
330 spin_unlock(&device->io_lock);
331
332 while (pending) {
333
334 rmb();
335 /* we want to work on both lists, but do more bios on the
336 * sync list than the regular list
337 */
338 if ((num_run > 32 &&
339 pending_bios != &device->pending_sync_bios &&
340 device->pending_sync_bios.head) ||
341 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
342 device->pending_bios.head)) {
343 spin_lock(&device->io_lock);
344 requeue_list(pending_bios, pending, tail);
345 goto loop_lock;
346 }
347
348 cur = pending;
349 pending = pending->bi_next;
350 cur->bi_next = NULL;
351
352 if (atomic_dec_return(&fs_info->nr_async_bios) < limit &&
353 waitqueue_active(&fs_info->async_submit_wait))
354 wake_up(&fs_info->async_submit_wait);
355
356 BUG_ON(atomic_read(&cur->bi_cnt) == 0);
357
358 /*
359 * if we're doing the sync list, record that our
360 * plug has some sync requests on it
361 *
362 * If we're doing the regular list and there are
363 * sync requests sitting around, unplug before
364 * we add more
365 */
366 if (pending_bios == &device->pending_sync_bios) {
367 sync_pending = 1;
368 } else if (sync_pending) {
369 blk_finish_plug(&plug);
370 blk_start_plug(&plug);
371 sync_pending = 0;
372 }
373
374 btrfsic_submit_bio(cur->bi_rw, cur);
375 num_run++;
376 batch_run++;
377 if (need_resched())
378 cond_resched();
379
380 /*
381 * we made progress, there is more work to do and the bdi
382 * is now congested. Back off and let other work structs
383 * run instead
384 */
385 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
386 fs_info->fs_devices->open_devices > 1) {
387 struct io_context *ioc;
388
389 ioc = current->io_context;
390
391 /*
392 * the main goal here is that we don't want to
393 * block if we're going to be able to submit
394 * more requests without blocking.
395 *
396 * This code does two great things, it pokes into
397 * the elevator code from a filesystem _and_
398 * it makes assumptions about how batching works.
399 */
400 if (ioc && ioc->nr_batch_requests > 0 &&
401 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
402 (last_waited == 0 ||
403 ioc->last_waited == last_waited)) {
404 /*
405 * we want to go through our batch of
406 * requests and stop. So, we copy out
407 * the ioc->last_waited time and test
408 * against it before looping
409 */
410 last_waited = ioc->last_waited;
411 if (need_resched())
412 cond_resched();
413 continue;
414 }
415 spin_lock(&device->io_lock);
416 requeue_list(pending_bios, pending, tail);
417 device->running_pending = 1;
418
419 spin_unlock(&device->io_lock);
420 btrfs_queue_work(fs_info->submit_workers,
421 &device->work);
422 goto done;
423 }
424 /* unplug every 64 requests just for good measure */
425 if (batch_run % 64 == 0) {
426 blk_finish_plug(&plug);
427 blk_start_plug(&plug);
428 sync_pending = 0;
429 }
430 }
431
432 cond_resched();
433 if (again)
434 goto loop;
435
436 spin_lock(&device->io_lock);
437 if (device->pending_bios.head || device->pending_sync_bios.head)
438 goto loop_lock;
439 spin_unlock(&device->io_lock);
440
441done:
442 blk_finish_plug(&plug);
443}
444
445static void pending_bios_fn(struct btrfs_work *work)
446{
447 struct btrfs_device *device;
448
449 device = container_of(work, struct btrfs_device, work);
450 run_scheduled_bios(device);
451}
452
453/*
454 * Add new device to list of registered devices
455 *
456 * Returns:
457 * 1 - first time device is seen
458 * 0 - device already known
459 * < 0 - error
460 */
461static noinline int device_list_add(const char *path,
462 struct btrfs_super_block *disk_super,
463 u64 devid, struct btrfs_fs_devices **fs_devices_ret)
464{
465 struct btrfs_device *device;
466 struct btrfs_fs_devices *fs_devices;
467 struct rcu_string *name;
468 int ret = 0;
469 u64 found_transid = btrfs_super_generation(disk_super);
470
471 fs_devices = find_fsid(disk_super->fsid);
472 if (!fs_devices) {
473 fs_devices = alloc_fs_devices(disk_super->fsid);
474 if (IS_ERR(fs_devices))
475 return PTR_ERR(fs_devices);
476
477 list_add(&fs_devices->list, &fs_uuids);
478 fs_devices->latest_devid = devid;
479 fs_devices->latest_trans = found_transid;
480
481 device = NULL;
482 } else {
483 device = __find_device(&fs_devices->devices, devid,
484 disk_super->dev_item.uuid);
485 }
486 if (!device) {
487 if (fs_devices->opened)
488 return -EBUSY;
489
490 device = btrfs_alloc_device(NULL, &devid,
491 disk_super->dev_item.uuid);
492 if (IS_ERR(device)) {
493 /* we can safely leave the fs_devices entry around */
494 return PTR_ERR(device);
495 }
496
497 name = rcu_string_strdup(path, GFP_NOFS);
498 if (!name) {
499 kfree(device);
500 return -ENOMEM;
501 }
502 rcu_assign_pointer(device->name, name);
503
504 mutex_lock(&fs_devices->device_list_mutex);
505 list_add_rcu(&device->dev_list, &fs_devices->devices);
506 fs_devices->num_devices++;
507 mutex_unlock(&fs_devices->device_list_mutex);
508
509 ret = 1;
510 device->fs_devices = fs_devices;
511 } else if (!device->name || strcmp(device->name->str, path)) {
512 /*
513 * When FS is already mounted.
514 * 1. If you are here and if the device->name is NULL that
515 * means this device was missing at time of FS mount.
516 * 2. If you are here and if the device->name is different
517 * from 'path' that means either
518 * a. The same device disappeared and reappeared with
519 * different name. or
520 * b. The missing-disk-which-was-replaced, has
521 * reappeared now.
522 *
523 * We must allow 1 and 2a above. But 2b would be a spurious
524 * and unintentional.
525 *
526 * Further in case of 1 and 2a above, the disk at 'path'
527 * would have missed some transaction when it was away and
528 * in case of 2a the stale bdev has to be updated as well.
529 * 2b must not be allowed at all time.
530 */
531
532 /*
533 * As of now don't allow update to btrfs_fs_device through
534 * the btrfs dev scan cli, after FS has been mounted.
535 */
536 if (fs_devices->opened) {
537 return -EBUSY;
538 } else {
539 /*
540 * That is if the FS is _not_ mounted and if you
541 * are here, that means there is more than one
542 * disk with same uuid and devid.We keep the one
543 * with larger generation number or the last-in if
544 * generation are equal.
545 */
546 if (found_transid < device->generation)
547 return -EEXIST;
548 }
549
550 name = rcu_string_strdup(path, GFP_NOFS);
551 if (!name)
552 return -ENOMEM;
553 rcu_string_free(device->name);
554 rcu_assign_pointer(device->name, name);
555 if (device->missing) {
556 fs_devices->missing_devices--;
557 device->missing = 0;
558 }
559 }
560
561 /*
562 * Unmount does not free the btrfs_device struct but would zero
563 * generation along with most of the other members. So just update
564 * it back. We need it to pick the disk with largest generation
565 * (as above).
566 */
567 if (!fs_devices->opened)
568 device->generation = found_transid;
569
570 if (found_transid > fs_devices->latest_trans) {
571 fs_devices->latest_devid = devid;
572 fs_devices->latest_trans = found_transid;
573 }
574 *fs_devices_ret = fs_devices;
575
576 return ret;
577}
578
579static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
580{
581 struct btrfs_fs_devices *fs_devices;
582 struct btrfs_device *device;
583 struct btrfs_device *orig_dev;
584
585 fs_devices = alloc_fs_devices(orig->fsid);
586 if (IS_ERR(fs_devices))
587 return fs_devices;
588
589 fs_devices->latest_devid = orig->latest_devid;
590 fs_devices->latest_trans = orig->latest_trans;
591 fs_devices->total_devices = orig->total_devices;
592
593 /* We have held the volume lock, it is safe to get the devices. */
594 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
595 struct rcu_string *name;
596
597 device = btrfs_alloc_device(NULL, &orig_dev->devid,
598 orig_dev->uuid);
599 if (IS_ERR(device))
600 goto error;
601
602 /*
603 * This is ok to do without rcu read locked because we hold the
604 * uuid mutex so nothing we touch in here is going to disappear.
605 */
606 if (orig_dev->name) {
607 name = rcu_string_strdup(orig_dev->name->str, GFP_NOFS);
608 if (!name) {
609 kfree(device);
610 goto error;
611 }
612 rcu_assign_pointer(device->name, name);
613 }
614
615 list_add(&device->dev_list, &fs_devices->devices);
616 device->fs_devices = fs_devices;
617 fs_devices->num_devices++;
618 }
619 return fs_devices;
620error:
621 free_fs_devices(fs_devices);
622 return ERR_PTR(-ENOMEM);
623}
624
625void btrfs_close_extra_devices(struct btrfs_fs_info *fs_info,
626 struct btrfs_fs_devices *fs_devices, int step)
627{
628 struct btrfs_device *device, *next;
629
630 struct block_device *latest_bdev = NULL;
631 u64 latest_devid = 0;
632 u64 latest_transid = 0;
633
634 mutex_lock(&uuid_mutex);
635again:
636 /* This is the initialized path, it is safe to release the devices. */
637 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
638 if (device->in_fs_metadata) {
639 if (!device->is_tgtdev_for_dev_replace &&
640 (!latest_transid ||
641 device->generation > latest_transid)) {
642 latest_devid = device->devid;
643 latest_transid = device->generation;
644 latest_bdev = device->bdev;
645 }
646 continue;
647 }
648
649 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
650 /*
651 * In the first step, keep the device which has
652 * the correct fsid and the devid that is used
653 * for the dev_replace procedure.
654 * In the second step, the dev_replace state is
655 * read from the device tree and it is known
656 * whether the procedure is really active or
657 * not, which means whether this device is
658 * used or whether it should be removed.
659 */
660 if (step == 0 || device->is_tgtdev_for_dev_replace) {
661 continue;
662 }
663 }
664 if (device->bdev) {
665 blkdev_put(device->bdev, device->mode);
666 device->bdev = NULL;
667 fs_devices->open_devices--;
668 }
669 if (device->writeable) {
670 list_del_init(&device->dev_alloc_list);
671 device->writeable = 0;
672 if (!device->is_tgtdev_for_dev_replace)
673 fs_devices->rw_devices--;
674 }
675 list_del_init(&device->dev_list);
676 fs_devices->num_devices--;
677 rcu_string_free(device->name);
678 kfree(device);
679 }
680
681 if (fs_devices->seed) {
682 fs_devices = fs_devices->seed;
683 goto again;
684 }
685
686 fs_devices->latest_bdev = latest_bdev;
687 fs_devices->latest_devid = latest_devid;
688 fs_devices->latest_trans = latest_transid;
689
690 mutex_unlock(&uuid_mutex);
691}
692
693static void __free_device(struct work_struct *work)
694{
695 struct btrfs_device *device;
696
697 device = container_of(work, struct btrfs_device, rcu_work);
698
699 if (device->bdev)
700 blkdev_put(device->bdev, device->mode);
701
702 rcu_string_free(device->name);
703 kfree(device);
704}
705
706static void free_device(struct rcu_head *head)
707{
708 struct btrfs_device *device;
709
710 device = container_of(head, struct btrfs_device, rcu);
711
712 INIT_WORK(&device->rcu_work, __free_device);
713 schedule_work(&device->rcu_work);
714}
715
716static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
717{
718 struct btrfs_device *device;
719
720 if (--fs_devices->opened > 0)
721 return 0;
722
723 mutex_lock(&fs_devices->device_list_mutex);
724 list_for_each_entry(device, &fs_devices->devices, dev_list) {
725 struct btrfs_device *new_device;
726 struct rcu_string *name;
727
728 if (device->bdev)
729 fs_devices->open_devices--;
730
731 if (device->writeable &&
732 device->devid != BTRFS_DEV_REPLACE_DEVID) {
733 list_del_init(&device->dev_alloc_list);
734 fs_devices->rw_devices--;
735 }
736
737 if (device->can_discard)
738 fs_devices->num_can_discard--;
739 if (device->missing)
740 fs_devices->missing_devices--;
741
742 new_device = btrfs_alloc_device(NULL, &device->devid,
743 device->uuid);
744 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
745
746 /* Safe because we are under uuid_mutex */
747 if (device->name) {
748 name = rcu_string_strdup(device->name->str, GFP_NOFS);
749 BUG_ON(!name); /* -ENOMEM */
750 rcu_assign_pointer(new_device->name, name);
751 }
752
753 list_replace_rcu(&device->dev_list, &new_device->dev_list);
754 new_device->fs_devices = device->fs_devices;
755
756 call_rcu(&device->rcu, free_device);
757 }
758 mutex_unlock(&fs_devices->device_list_mutex);
759
760 WARN_ON(fs_devices->open_devices);
761 WARN_ON(fs_devices->rw_devices);
762 fs_devices->opened = 0;
763 fs_devices->seeding = 0;
764
765 return 0;
766}
767
768int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
769{
770 struct btrfs_fs_devices *seed_devices = NULL;
771 int ret;
772
773 mutex_lock(&uuid_mutex);
774 ret = __btrfs_close_devices(fs_devices);
775 if (!fs_devices->opened) {
776 seed_devices = fs_devices->seed;
777 fs_devices->seed = NULL;
778 }
779 mutex_unlock(&uuid_mutex);
780
781 while (seed_devices) {
782 fs_devices = seed_devices;
783 seed_devices = fs_devices->seed;
784 __btrfs_close_devices(fs_devices);
785 free_fs_devices(fs_devices);
786 }
787 /*
788 * Wait for rcu kworkers under __btrfs_close_devices
789 * to finish all blkdev_puts so device is really
790 * free when umount is done.
791 */
792 rcu_barrier();
793 return ret;
794}
795
796static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
797 fmode_t flags, void *holder)
798{
799 struct request_queue *q;
800 struct block_device *bdev;
801 struct list_head *head = &fs_devices->devices;
802 struct btrfs_device *device;
803 struct block_device *latest_bdev = NULL;
804 struct buffer_head *bh;
805 struct btrfs_super_block *disk_super;
806 u64 latest_devid = 0;
807 u64 latest_transid = 0;
808 u64 devid;
809 int seeding = 1;
810 int ret = 0;
811
812 flags |= FMODE_EXCL;
813
814 list_for_each_entry(device, head, dev_list) {
815 if (device->bdev)
816 continue;
817 if (!device->name)
818 continue;
819
820 /* Just open everything we can; ignore failures here */
821 if (btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
822 &bdev, &bh))
823 continue;
824
825 disk_super = (struct btrfs_super_block *)bh->b_data;
826 devid = btrfs_stack_device_id(&disk_super->dev_item);
827 if (devid != device->devid)
828 goto error_brelse;
829
830 if (memcmp(device->uuid, disk_super->dev_item.uuid,
831 BTRFS_UUID_SIZE))
832 goto error_brelse;
833
834 device->generation = btrfs_super_generation(disk_super);
835 if (!latest_transid || device->generation > latest_transid) {
836 latest_devid = devid;
837 latest_transid = device->generation;
838 latest_bdev = bdev;
839 }
840
841 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
842 device->writeable = 0;
843 } else {
844 device->writeable = !bdev_read_only(bdev);
845 seeding = 0;
846 }
847
848 q = bdev_get_queue(bdev);
849 if (blk_queue_discard(q)) {
850 device->can_discard = 1;
851 fs_devices->num_can_discard++;
852 }
853
854 device->bdev = bdev;
855 device->in_fs_metadata = 0;
856 device->mode = flags;
857
858 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
859 fs_devices->rotating = 1;
860
861 fs_devices->open_devices++;
862 if (device->writeable &&
863 device->devid != BTRFS_DEV_REPLACE_DEVID) {
864 fs_devices->rw_devices++;
865 list_add(&device->dev_alloc_list,
866 &fs_devices->alloc_list);
867 }
868 brelse(bh);
869 continue;
870
871error_brelse:
872 brelse(bh);
873 blkdev_put(bdev, flags);
874 continue;
875 }
876 if (fs_devices->open_devices == 0) {
877 ret = -EINVAL;
878 goto out;
879 }
880 fs_devices->seeding = seeding;
881 fs_devices->opened = 1;
882 fs_devices->latest_bdev = latest_bdev;
883 fs_devices->latest_devid = latest_devid;
884 fs_devices->latest_trans = latest_transid;
885 fs_devices->total_rw_bytes = 0;
886out:
887 return ret;
888}
889
890int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
891 fmode_t flags, void *holder)
892{
893 int ret;
894
895 mutex_lock(&uuid_mutex);
896 if (fs_devices->opened) {
897 fs_devices->opened++;
898 ret = 0;
899 } else {
900 ret = __btrfs_open_devices(fs_devices, flags, holder);
901 }
902 mutex_unlock(&uuid_mutex);
903 return ret;
904}
905
906/*
907 * Look for a btrfs signature on a device. This may be called out of the mount path
908 * and we are not allowed to call set_blocksize during the scan. The superblock
909 * is read via pagecache
910 */
911int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
912 struct btrfs_fs_devices **fs_devices_ret)
913{
914 struct btrfs_super_block *disk_super;
915 struct block_device *bdev;
916 struct page *page;
917 void *p;
918 int ret = -EINVAL;
919 u64 devid;
920 u64 transid;
921 u64 total_devices;
922 u64 bytenr;
923 pgoff_t index;
924
925 /*
926 * we would like to check all the supers, but that would make
927 * a btrfs mount succeed after a mkfs from a different FS.
928 * So, we need to add a special mount option to scan for
929 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
930 */
931 bytenr = btrfs_sb_offset(0);
932 flags |= FMODE_EXCL;
933 mutex_lock(&uuid_mutex);
934
935 bdev = blkdev_get_by_path(path, flags, holder);
936
937 if (IS_ERR(bdev)) {
938 ret = PTR_ERR(bdev);
939 goto error;
940 }
941
942 /* make sure our super fits in the device */
943 if (bytenr + PAGE_CACHE_SIZE >= i_size_read(bdev->bd_inode))
944 goto error_bdev_put;
945
946 /* make sure our super fits in the page */
947 if (sizeof(*disk_super) > PAGE_CACHE_SIZE)
948 goto error_bdev_put;
949
950 /* make sure our super doesn't straddle pages on disk */
951 index = bytenr >> PAGE_CACHE_SHIFT;
952 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_CACHE_SHIFT != index)
953 goto error_bdev_put;
954
955 /* pull in the page with our super */
956 page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
957 index, GFP_NOFS);
958
959 if (IS_ERR_OR_NULL(page))
960 goto error_bdev_put;
961
962 p = kmap(page);
963
964 /* align our pointer to the offset of the super block */
965 disk_super = p + (bytenr & ~PAGE_CACHE_MASK);
966
967 if (btrfs_super_bytenr(disk_super) != bytenr ||
968 btrfs_super_magic(disk_super) != BTRFS_MAGIC)
969 goto error_unmap;
970
971 devid = btrfs_stack_device_id(&disk_super->dev_item);
972 transid = btrfs_super_generation(disk_super);
973 total_devices = btrfs_super_num_devices(disk_super);
974
975 ret = device_list_add(path, disk_super, devid, fs_devices_ret);
976 if (ret > 0) {
977 if (disk_super->label[0]) {
978 if (disk_super->label[BTRFS_LABEL_SIZE - 1])
979 disk_super->label[BTRFS_LABEL_SIZE - 1] = '\0';
980 printk(KERN_INFO "BTRFS: device label %s ", disk_super->label);
981 } else {
982 printk(KERN_INFO "BTRFS: device fsid %pU ", disk_super->fsid);
983 }
984
985 printk(KERN_CONT "devid %llu transid %llu %s\n", devid, transid, path);
986 ret = 0;
987 }
988 if (!ret && fs_devices_ret)
989 (*fs_devices_ret)->total_devices = total_devices;
990
991error_unmap:
992 kunmap(page);
993 page_cache_release(page);
994
995error_bdev_put:
996 blkdev_put(bdev, flags);
997error:
998 mutex_unlock(&uuid_mutex);
999 return ret;
1000}
1001
1002/* helper to account the used device space in the range */
1003int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1004 u64 end, u64 *length)
1005{
1006 struct btrfs_key key;
1007 struct btrfs_root *root = device->dev_root;
1008 struct btrfs_dev_extent *dev_extent;
1009 struct btrfs_path *path;
1010 u64 extent_end;
1011 int ret;
1012 int slot;
1013 struct extent_buffer *l;
1014
1015 *length = 0;
1016
1017 if (start >= device->total_bytes || device->is_tgtdev_for_dev_replace)
1018 return 0;
1019
1020 path = btrfs_alloc_path();
1021 if (!path)
1022 return -ENOMEM;
1023 path->reada = 2;
1024
1025 key.objectid = device->devid;
1026 key.offset = start;
1027 key.type = BTRFS_DEV_EXTENT_KEY;
1028
1029 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1030 if (ret < 0)
1031 goto out;
1032 if (ret > 0) {
1033 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1034 if (ret < 0)
1035 goto out;
1036 }
1037
1038 while (1) {
1039 l = path->nodes[0];
1040 slot = path->slots[0];
1041 if (slot >= btrfs_header_nritems(l)) {
1042 ret = btrfs_next_leaf(root, path);
1043 if (ret == 0)
1044 continue;
1045 if (ret < 0)
1046 goto out;
1047
1048 break;
1049 }
1050 btrfs_item_key_to_cpu(l, &key, slot);
1051
1052 if (key.objectid < device->devid)
1053 goto next;
1054
1055 if (key.objectid > device->devid)
1056 break;
1057
1058 if (key.type != BTRFS_DEV_EXTENT_KEY)
1059 goto next;
1060
1061 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1062 extent_end = key.offset + btrfs_dev_extent_length(l,
1063 dev_extent);
1064 if (key.offset <= start && extent_end > end) {
1065 *length = end - start + 1;
1066 break;
1067 } else if (key.offset <= start && extent_end > start)
1068 *length += extent_end - start;
1069 else if (key.offset > start && extent_end <= end)
1070 *length += extent_end - key.offset;
1071 else if (key.offset > start && key.offset <= end) {
1072 *length += end - key.offset + 1;
1073 break;
1074 } else if (key.offset > end)
1075 break;
1076
1077next:
1078 path->slots[0]++;
1079 }
1080 ret = 0;
1081out:
1082 btrfs_free_path(path);
1083 return ret;
1084}
1085
1086static int contains_pending_extent(struct btrfs_trans_handle *trans,
1087 struct btrfs_device *device,
1088 u64 *start, u64 len)
1089{
1090 struct extent_map *em;
1091 int ret = 0;
1092
1093 list_for_each_entry(em, &trans->transaction->pending_chunks, list) {
1094 struct map_lookup *map;
1095 int i;
1096
1097 map = (struct map_lookup *)em->bdev;
1098 for (i = 0; i < map->num_stripes; i++) {
1099 if (map->stripes[i].dev != device)
1100 continue;
1101 if (map->stripes[i].physical >= *start + len ||
1102 map->stripes[i].physical + em->orig_block_len <=
1103 *start)
1104 continue;
1105 *start = map->stripes[i].physical +
1106 em->orig_block_len;
1107 ret = 1;
1108 }
1109 }
1110
1111 return ret;
1112}
1113
1114
1115/*
1116 * find_free_dev_extent - find free space in the specified device
1117 * @device: the device which we search the free space in
1118 * @num_bytes: the size of the free space that we need
1119 * @start: store the start of the free space.
1120 * @len: the size of the free space. that we find, or the size of the max
1121 * free space if we don't find suitable free space
1122 *
1123 * this uses a pretty simple search, the expectation is that it is
1124 * called very infrequently and that a given device has a small number
1125 * of extents
1126 *
1127 * @start is used to store the start of the free space if we find. But if we
1128 * don't find suitable free space, it will be used to store the start position
1129 * of the max free space.
1130 *
1131 * @len is used to store the size of the free space that we find.
1132 * But if we don't find suitable free space, it is used to store the size of
1133 * the max free space.
1134 */
1135int find_free_dev_extent(struct btrfs_trans_handle *trans,
1136 struct btrfs_device *device, u64 num_bytes,
1137 u64 *start, u64 *len)
1138{
1139 struct btrfs_key key;
1140 struct btrfs_root *root = device->dev_root;
1141 struct btrfs_dev_extent *dev_extent;
1142 struct btrfs_path *path;
1143 u64 hole_size;
1144 u64 max_hole_start;
1145 u64 max_hole_size;
1146 u64 extent_end;
1147 u64 search_start;
1148 u64 search_end = device->total_bytes;
1149 int ret;
1150 int slot;
1151 struct extent_buffer *l;
1152
1153 /* FIXME use last free of some kind */
1154
1155 /* we don't want to overwrite the superblock on the drive,
1156 * so we make sure to start at an offset of at least 1MB
1157 */
1158 search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
1159
1160 path = btrfs_alloc_path();
1161 if (!path)
1162 return -ENOMEM;
1163again:
1164 max_hole_start = search_start;
1165 max_hole_size = 0;
1166 hole_size = 0;
1167
1168 if (search_start >= search_end || device->is_tgtdev_for_dev_replace) {
1169 ret = -ENOSPC;
1170 goto out;
1171 }
1172
1173 path->reada = 2;
1174 path->search_commit_root = 1;
1175 path->skip_locking = 1;
1176
1177 key.objectid = device->devid;
1178 key.offset = search_start;
1179 key.type = BTRFS_DEV_EXTENT_KEY;
1180
1181 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1182 if (ret < 0)
1183 goto out;
1184 if (ret > 0) {
1185 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1186 if (ret < 0)
1187 goto out;
1188 }
1189
1190 while (1) {
1191 l = path->nodes[0];
1192 slot = path->slots[0];
1193 if (slot >= btrfs_header_nritems(l)) {
1194 ret = btrfs_next_leaf(root, path);
1195 if (ret == 0)
1196 continue;
1197 if (ret < 0)
1198 goto out;
1199
1200 break;
1201 }
1202 btrfs_item_key_to_cpu(l, &key, slot);
1203
1204 if (key.objectid < device->devid)
1205 goto next;
1206
1207 if (key.objectid > device->devid)
1208 break;
1209
1210 if (key.type != BTRFS_DEV_EXTENT_KEY)
1211 goto next;
1212
1213 if (key.offset > search_start) {
1214 hole_size = key.offset - search_start;
1215
1216 /*
1217 * Have to check before we set max_hole_start, otherwise
1218 * we could end up sending back this offset anyway.
1219 */
1220 if (contains_pending_extent(trans, device,
1221 &search_start,
1222 hole_size))
1223 hole_size = 0;
1224
1225 if (hole_size > max_hole_size) {
1226 max_hole_start = search_start;
1227 max_hole_size = hole_size;
1228 }
1229
1230 /*
1231 * If this free space is greater than which we need,
1232 * it must be the max free space that we have found
1233 * until now, so max_hole_start must point to the start
1234 * of this free space and the length of this free space
1235 * is stored in max_hole_size. Thus, we return
1236 * max_hole_start and max_hole_size and go back to the
1237 * caller.
1238 */
1239 if (hole_size >= num_bytes) {
1240 ret = 0;
1241 goto out;
1242 }
1243 }
1244
1245 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1246 extent_end = key.offset + btrfs_dev_extent_length(l,
1247 dev_extent);
1248 if (extent_end > search_start)
1249 search_start = extent_end;
1250next:
1251 path->slots[0]++;
1252 cond_resched();
1253 }
1254
1255 /*
1256 * At this point, search_start should be the end of
1257 * allocated dev extents, and when shrinking the device,
1258 * search_end may be smaller than search_start.
1259 */
1260 if (search_end > search_start)
1261 hole_size = search_end - search_start;
1262
1263 if (hole_size > max_hole_size) {
1264 max_hole_start = search_start;
1265 max_hole_size = hole_size;
1266 }
1267
1268 if (contains_pending_extent(trans, device, &search_start, hole_size)) {
1269 btrfs_release_path(path);
1270 goto again;
1271 }
1272
1273 /* See above. */
1274 if (hole_size < num_bytes)
1275 ret = -ENOSPC;
1276 else
1277 ret = 0;
1278
1279out:
1280 btrfs_free_path(path);
1281 *start = max_hole_start;
1282 if (len)
1283 *len = max_hole_size;
1284 return ret;
1285}
1286
1287static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1288 struct btrfs_device *device,
1289 u64 start)
1290{
1291 int ret;
1292 struct btrfs_path *path;
1293 struct btrfs_root *root = device->dev_root;
1294 struct btrfs_key key;
1295 struct btrfs_key found_key;
1296 struct extent_buffer *leaf = NULL;
1297 struct btrfs_dev_extent *extent = NULL;
1298
1299 path = btrfs_alloc_path();
1300 if (!path)
1301 return -ENOMEM;
1302
1303 key.objectid = device->devid;
1304 key.offset = start;
1305 key.type = BTRFS_DEV_EXTENT_KEY;
1306again:
1307 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1308 if (ret > 0) {
1309 ret = btrfs_previous_item(root, path, key.objectid,
1310 BTRFS_DEV_EXTENT_KEY);
1311 if (ret)
1312 goto out;
1313 leaf = path->nodes[0];
1314 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1315 extent = btrfs_item_ptr(leaf, path->slots[0],
1316 struct btrfs_dev_extent);
1317 BUG_ON(found_key.offset > start || found_key.offset +
1318 btrfs_dev_extent_length(leaf, extent) < start);
1319 key = found_key;
1320 btrfs_release_path(path);
1321 goto again;
1322 } else if (ret == 0) {
1323 leaf = path->nodes[0];
1324 extent = btrfs_item_ptr(leaf, path->slots[0],
1325 struct btrfs_dev_extent);
1326 } else {
1327 btrfs_error(root->fs_info, ret, "Slot search failed");
1328 goto out;
1329 }
1330
1331 if (device->bytes_used > 0) {
1332 u64 len = btrfs_dev_extent_length(leaf, extent);
1333 device->bytes_used -= len;
1334 spin_lock(&root->fs_info->free_chunk_lock);
1335 root->fs_info->free_chunk_space += len;
1336 spin_unlock(&root->fs_info->free_chunk_lock);
1337 }
1338 ret = btrfs_del_item(trans, root, path);
1339 if (ret) {
1340 btrfs_error(root->fs_info, ret,
1341 "Failed to remove dev extent item");
1342 }
1343out:
1344 btrfs_free_path(path);
1345 return ret;
1346}
1347
1348static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1349 struct btrfs_device *device,
1350 u64 chunk_tree, u64 chunk_objectid,
1351 u64 chunk_offset, u64 start, u64 num_bytes)
1352{
1353 int ret;
1354 struct btrfs_path *path;
1355 struct btrfs_root *root = device->dev_root;
1356 struct btrfs_dev_extent *extent;
1357 struct extent_buffer *leaf;
1358 struct btrfs_key key;
1359
1360 WARN_ON(!device->in_fs_metadata);
1361 WARN_ON(device->is_tgtdev_for_dev_replace);
1362 path = btrfs_alloc_path();
1363 if (!path)
1364 return -ENOMEM;
1365
1366 key.objectid = device->devid;
1367 key.offset = start;
1368 key.type = BTRFS_DEV_EXTENT_KEY;
1369 ret = btrfs_insert_empty_item(trans, root, path, &key,
1370 sizeof(*extent));
1371 if (ret)
1372 goto out;
1373
1374 leaf = path->nodes[0];
1375 extent = btrfs_item_ptr(leaf, path->slots[0],
1376 struct btrfs_dev_extent);
1377 btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1378 btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1379 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1380
1381 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1382 btrfs_dev_extent_chunk_tree_uuid(extent), BTRFS_UUID_SIZE);
1383
1384 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1385 btrfs_mark_buffer_dirty(leaf);
1386out:
1387 btrfs_free_path(path);
1388 return ret;
1389}
1390
1391static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1392{
1393 struct extent_map_tree *em_tree;
1394 struct extent_map *em;
1395 struct rb_node *n;
1396 u64 ret = 0;
1397
1398 em_tree = &fs_info->mapping_tree.map_tree;
1399 read_lock(&em_tree->lock);
1400 n = rb_last(&em_tree->map);
1401 if (n) {
1402 em = rb_entry(n, struct extent_map, rb_node);
1403 ret = em->start + em->len;
1404 }
1405 read_unlock(&em_tree->lock);
1406
1407 return ret;
1408}
1409
1410static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1411 u64 *devid_ret)
1412{
1413 int ret;
1414 struct btrfs_key key;
1415 struct btrfs_key found_key;
1416 struct btrfs_path *path;
1417
1418 path = btrfs_alloc_path();
1419 if (!path)
1420 return -ENOMEM;
1421
1422 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1423 key.type = BTRFS_DEV_ITEM_KEY;
1424 key.offset = (u64)-1;
1425
1426 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1427 if (ret < 0)
1428 goto error;
1429
1430 BUG_ON(ret == 0); /* Corruption */
1431
1432 ret = btrfs_previous_item(fs_info->chunk_root, path,
1433 BTRFS_DEV_ITEMS_OBJECTID,
1434 BTRFS_DEV_ITEM_KEY);
1435 if (ret) {
1436 *devid_ret = 1;
1437 } else {
1438 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1439 path->slots[0]);
1440 *devid_ret = found_key.offset + 1;
1441 }
1442 ret = 0;
1443error:
1444 btrfs_free_path(path);
1445 return ret;
1446}
1447
1448/*
1449 * the device information is stored in the chunk root
1450 * the btrfs_device struct should be fully filled in
1451 */
1452static int btrfs_add_device(struct btrfs_trans_handle *trans,
1453 struct btrfs_root *root,
1454 struct btrfs_device *device)
1455{
1456 int ret;
1457 struct btrfs_path *path;
1458 struct btrfs_dev_item *dev_item;
1459 struct extent_buffer *leaf;
1460 struct btrfs_key key;
1461 unsigned long ptr;
1462
1463 root = root->fs_info->chunk_root;
1464
1465 path = btrfs_alloc_path();
1466 if (!path)
1467 return -ENOMEM;
1468
1469 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1470 key.type = BTRFS_DEV_ITEM_KEY;
1471 key.offset = device->devid;
1472
1473 ret = btrfs_insert_empty_item(trans, root, path, &key,
1474 sizeof(*dev_item));
1475 if (ret)
1476 goto out;
1477
1478 leaf = path->nodes[0];
1479 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1480
1481 btrfs_set_device_id(leaf, dev_item, device->devid);
1482 btrfs_set_device_generation(leaf, dev_item, 0);
1483 btrfs_set_device_type(leaf, dev_item, device->type);
1484 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1485 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1486 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1487 btrfs_set_device_total_bytes(leaf, dev_item, device->disk_total_bytes);
1488 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1489 btrfs_set_device_group(leaf, dev_item, 0);
1490 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1491 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1492 btrfs_set_device_start_offset(leaf, dev_item, 0);
1493
1494 ptr = btrfs_device_uuid(dev_item);
1495 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1496 ptr = btrfs_device_fsid(dev_item);
1497 write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
1498 btrfs_mark_buffer_dirty(leaf);
1499
1500 ret = 0;
1501out:
1502 btrfs_free_path(path);
1503 return ret;
1504}
1505
1506/*
1507 * Function to update ctime/mtime for a given device path.
1508 * Mainly used for ctime/mtime based probe like libblkid.
1509 */
1510static void update_dev_time(char *path_name)
1511{
1512 struct file *filp;
1513
1514 filp = filp_open(path_name, O_RDWR, 0);
1515 if (!filp)
1516 return;
1517 file_update_time(filp);
1518 filp_close(filp, NULL);
1519 return;
1520}
1521
1522static int btrfs_rm_dev_item(struct btrfs_root *root,
1523 struct btrfs_device *device)
1524{
1525 int ret;
1526 struct btrfs_path *path;
1527 struct btrfs_key key;
1528 struct btrfs_trans_handle *trans;
1529
1530 root = root->fs_info->chunk_root;
1531
1532 path = btrfs_alloc_path();
1533 if (!path)
1534 return -ENOMEM;
1535
1536 trans = btrfs_start_transaction(root, 0);
1537 if (IS_ERR(trans)) {
1538 btrfs_free_path(path);
1539 return PTR_ERR(trans);
1540 }
1541 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1542 key.type = BTRFS_DEV_ITEM_KEY;
1543 key.offset = device->devid;
1544 lock_chunks(root);
1545
1546 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1547 if (ret < 0)
1548 goto out;
1549
1550 if (ret > 0) {
1551 ret = -ENOENT;
1552 goto out;
1553 }
1554
1555 ret = btrfs_del_item(trans, root, path);
1556 if (ret)
1557 goto out;
1558out:
1559 btrfs_free_path(path);
1560 unlock_chunks(root);
1561 btrfs_commit_transaction(trans, root);
1562 return ret;
1563}
1564
1565int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1566{
1567 struct btrfs_device *device;
1568 struct btrfs_device *next_device;
1569 struct block_device *bdev;
1570 struct buffer_head *bh = NULL;
1571 struct btrfs_super_block *disk_super;
1572 struct btrfs_fs_devices *cur_devices;
1573 u64 all_avail;
1574 u64 devid;
1575 u64 num_devices;
1576 u8 *dev_uuid;
1577 unsigned seq;
1578 int ret = 0;
1579 bool clear_super = false;
1580
1581 mutex_lock(&uuid_mutex);
1582
1583 do {
1584 seq = read_seqbegin(&root->fs_info->profiles_lock);
1585
1586 all_avail = root->fs_info->avail_data_alloc_bits |
1587 root->fs_info->avail_system_alloc_bits |
1588 root->fs_info->avail_metadata_alloc_bits;
1589 } while (read_seqretry(&root->fs_info->profiles_lock, seq));
1590
1591 num_devices = root->fs_info->fs_devices->num_devices;
1592 btrfs_dev_replace_lock(&root->fs_info->dev_replace);
1593 if (btrfs_dev_replace_is_ongoing(&root->fs_info->dev_replace)) {
1594 WARN_ON(num_devices < 1);
1595 num_devices--;
1596 }
1597 btrfs_dev_replace_unlock(&root->fs_info->dev_replace);
1598
1599 if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) && num_devices <= 4) {
1600 ret = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET;
1601 goto out;
1602 }
1603
1604 if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) && num_devices <= 2) {
1605 ret = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET;
1606 goto out;
1607 }
1608
1609 if ((all_avail & BTRFS_BLOCK_GROUP_RAID5) &&
1610 root->fs_info->fs_devices->rw_devices <= 2) {
1611 ret = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET;
1612 goto out;
1613 }
1614 if ((all_avail & BTRFS_BLOCK_GROUP_RAID6) &&
1615 root->fs_info->fs_devices->rw_devices <= 3) {
1616 ret = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET;
1617 goto out;
1618 }
1619
1620 if (strcmp(device_path, "missing") == 0) {
1621 struct list_head *devices;
1622 struct btrfs_device *tmp;
1623
1624 device = NULL;
1625 devices = &root->fs_info->fs_devices->devices;
1626 /*
1627 * It is safe to read the devices since the volume_mutex
1628 * is held.
1629 */
1630 list_for_each_entry(tmp, devices, dev_list) {
1631 if (tmp->in_fs_metadata &&
1632 !tmp->is_tgtdev_for_dev_replace &&
1633 !tmp->bdev) {
1634 device = tmp;
1635 break;
1636 }
1637 }
1638 bdev = NULL;
1639 bh = NULL;
1640 disk_super = NULL;
1641 if (!device) {
1642 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
1643 goto out;
1644 }
1645 } else {
1646 ret = btrfs_get_bdev_and_sb(device_path,
1647 FMODE_WRITE | FMODE_EXCL,
1648 root->fs_info->bdev_holder, 0,
1649 &bdev, &bh);
1650 if (ret)
1651 goto out;
1652 disk_super = (struct btrfs_super_block *)bh->b_data;
1653 devid = btrfs_stack_device_id(&disk_super->dev_item);
1654 dev_uuid = disk_super->dev_item.uuid;
1655 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1656 disk_super->fsid);
1657 if (!device) {
1658 ret = -ENOENT;
1659 goto error_brelse;
1660 }
1661 }
1662
1663 if (device->is_tgtdev_for_dev_replace) {
1664 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1665 goto error_brelse;
1666 }
1667
1668 if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
1669 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1670 goto error_brelse;
1671 }
1672
1673 if (device->writeable) {
1674 lock_chunks(root);
1675 list_del_init(&device->dev_alloc_list);
1676 unlock_chunks(root);
1677 root->fs_info->fs_devices->rw_devices--;
1678 clear_super = true;
1679 }
1680
1681 mutex_unlock(&uuid_mutex);
1682 ret = btrfs_shrink_device(device, 0);
1683 mutex_lock(&uuid_mutex);
1684 if (ret)
1685 goto error_undo;
1686
1687 /*
1688 * TODO: the superblock still includes this device in its num_devices
1689 * counter although write_all_supers() is not locked out. This
1690 * could give a filesystem state which requires a degraded mount.
1691 */
1692 ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1693 if (ret)
1694 goto error_undo;
1695
1696 spin_lock(&root->fs_info->free_chunk_lock);
1697 root->fs_info->free_chunk_space = device->total_bytes -
1698 device->bytes_used;
1699 spin_unlock(&root->fs_info->free_chunk_lock);
1700
1701 device->in_fs_metadata = 0;
1702 btrfs_scrub_cancel_dev(root->fs_info, device);
1703
1704 /*
1705 * the device list mutex makes sure that we don't change
1706 * the device list while someone else is writing out all
1707 * the device supers. Whoever is writing all supers, should
1708 * lock the device list mutex before getting the number of
1709 * devices in the super block (super_copy). Conversely,
1710 * whoever updates the number of devices in the super block
1711 * (super_copy) should hold the device list mutex.
1712 */
1713
1714 cur_devices = device->fs_devices;
1715 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1716 list_del_rcu(&device->dev_list);
1717
1718 device->fs_devices->num_devices--;
1719 device->fs_devices->total_devices--;
1720
1721 if (device->missing)
1722 device->fs_devices->missing_devices--;
1723
1724 next_device = list_entry(root->fs_info->fs_devices->devices.next,
1725 struct btrfs_device, dev_list);
1726 if (device->bdev == root->fs_info->sb->s_bdev)
1727 root->fs_info->sb->s_bdev = next_device->bdev;
1728 if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1729 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1730
1731 if (device->bdev) {
1732 device->fs_devices->open_devices--;
1733 /* remove sysfs entry */
1734 btrfs_kobj_rm_device(root->fs_info, device);
1735 }
1736
1737 call_rcu(&device->rcu, free_device);
1738
1739 num_devices = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
1740 btrfs_set_super_num_devices(root->fs_info->super_copy, num_devices);
1741 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1742
1743 if (cur_devices->open_devices == 0) {
1744 struct btrfs_fs_devices *fs_devices;
1745 fs_devices = root->fs_info->fs_devices;
1746 while (fs_devices) {
1747 if (fs_devices->seed == cur_devices) {
1748 fs_devices->seed = cur_devices->seed;
1749 break;
1750 }
1751 fs_devices = fs_devices->seed;
1752 }
1753 cur_devices->seed = NULL;
1754 lock_chunks(root);
1755 __btrfs_close_devices(cur_devices);
1756 unlock_chunks(root);
1757 free_fs_devices(cur_devices);
1758 }
1759
1760 root->fs_info->num_tolerated_disk_barrier_failures =
1761 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
1762
1763 /*
1764 * at this point, the device is zero sized. We want to
1765 * remove it from the devices list and zero out the old super
1766 */
1767 if (clear_super && disk_super) {
1768 u64 bytenr;
1769 int i;
1770
1771 /* make sure this device isn't detected as part of
1772 * the FS anymore
1773 */
1774 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1775 set_buffer_dirty(bh);
1776 sync_dirty_buffer(bh);
1777
1778 /* clear the mirror copies of super block on the disk
1779 * being removed, 0th copy is been taken care above and
1780 * the below would take of the rest
1781 */
1782 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1783 bytenr = btrfs_sb_offset(i);
1784 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
1785 i_size_read(bdev->bd_inode))
1786 break;
1787
1788 brelse(bh);
1789 bh = __bread(bdev, bytenr / 4096,
1790 BTRFS_SUPER_INFO_SIZE);
1791 if (!bh)
1792 continue;
1793
1794 disk_super = (struct btrfs_super_block *)bh->b_data;
1795
1796 if (btrfs_super_bytenr(disk_super) != bytenr ||
1797 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1798 continue;
1799 }
1800 memset(&disk_super->magic, 0,
1801 sizeof(disk_super->magic));
1802 set_buffer_dirty(bh);
1803 sync_dirty_buffer(bh);
1804 }
1805 }
1806
1807 ret = 0;
1808
1809 if (bdev) {
1810 /* Notify udev that device has changed */
1811 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
1812
1813 /* Update ctime/mtime for device path for libblkid */
1814 update_dev_time(device_path);
1815 }
1816
1817error_brelse:
1818 brelse(bh);
1819 if (bdev)
1820 blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
1821out:
1822 mutex_unlock(&uuid_mutex);
1823 return ret;
1824error_undo:
1825 if (device->writeable) {
1826 lock_chunks(root);
1827 list_add(&device->dev_alloc_list,
1828 &root->fs_info->fs_devices->alloc_list);
1829 unlock_chunks(root);
1830 root->fs_info->fs_devices->rw_devices++;
1831 }
1832 goto error_brelse;
1833}
1834
1835void btrfs_rm_dev_replace_srcdev(struct btrfs_fs_info *fs_info,
1836 struct btrfs_device *srcdev)
1837{
1838 WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
1839
1840 list_del_rcu(&srcdev->dev_list);
1841 list_del_rcu(&srcdev->dev_alloc_list);
1842 fs_info->fs_devices->num_devices--;
1843 if (srcdev->missing) {
1844 fs_info->fs_devices->missing_devices--;
1845 fs_info->fs_devices->rw_devices++;
1846 }
1847 if (srcdev->can_discard)
1848 fs_info->fs_devices->num_can_discard--;
1849 if (srcdev->bdev) {
1850 fs_info->fs_devices->open_devices--;
1851
1852 /*
1853 * zero out the old super if it is not writable
1854 * (e.g. seed device)
1855 */
1856 if (srcdev->writeable)
1857 btrfs_scratch_superblock(srcdev);
1858 }
1859
1860 call_rcu(&srcdev->rcu, free_device);
1861}
1862
1863void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
1864 struct btrfs_device *tgtdev)
1865{
1866 struct btrfs_device *next_device;
1867
1868 WARN_ON(!tgtdev);
1869 mutex_lock(&fs_info->fs_devices->device_list_mutex);
1870 if (tgtdev->bdev) {
1871 btrfs_scratch_superblock(tgtdev);
1872 fs_info->fs_devices->open_devices--;
1873 }
1874 fs_info->fs_devices->num_devices--;
1875 if (tgtdev->can_discard)
1876 fs_info->fs_devices->num_can_discard++;
1877
1878 next_device = list_entry(fs_info->fs_devices->devices.next,
1879 struct btrfs_device, dev_list);
1880 if (tgtdev->bdev == fs_info->sb->s_bdev)
1881 fs_info->sb->s_bdev = next_device->bdev;
1882 if (tgtdev->bdev == fs_info->fs_devices->latest_bdev)
1883 fs_info->fs_devices->latest_bdev = next_device->bdev;
1884 list_del_rcu(&tgtdev->dev_list);
1885
1886 call_rcu(&tgtdev->rcu, free_device);
1887
1888 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1889}
1890
1891static int btrfs_find_device_by_path(struct btrfs_root *root, char *device_path,
1892 struct btrfs_device **device)
1893{
1894 int ret = 0;
1895 struct btrfs_super_block *disk_super;
1896 u64 devid;
1897 u8 *dev_uuid;
1898 struct block_device *bdev;
1899 struct buffer_head *bh;
1900
1901 *device = NULL;
1902 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
1903 root->fs_info->bdev_holder, 0, &bdev, &bh);
1904 if (ret)
1905 return ret;
1906 disk_super = (struct btrfs_super_block *)bh->b_data;
1907 devid = btrfs_stack_device_id(&disk_super->dev_item);
1908 dev_uuid = disk_super->dev_item.uuid;
1909 *device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1910 disk_super->fsid);
1911 brelse(bh);
1912 if (!*device)
1913 ret = -ENOENT;
1914 blkdev_put(bdev, FMODE_READ);
1915 return ret;
1916}
1917
1918int btrfs_find_device_missing_or_by_path(struct btrfs_root *root,
1919 char *device_path,
1920 struct btrfs_device **device)
1921{
1922 *device = NULL;
1923 if (strcmp(device_path, "missing") == 0) {
1924 struct list_head *devices;
1925 struct btrfs_device *tmp;
1926
1927 devices = &root->fs_info->fs_devices->devices;
1928 /*
1929 * It is safe to read the devices since the volume_mutex
1930 * is held by the caller.
1931 */
1932 list_for_each_entry(tmp, devices, dev_list) {
1933 if (tmp->in_fs_metadata && !tmp->bdev) {
1934 *device = tmp;
1935 break;
1936 }
1937 }
1938
1939 if (!*device) {
1940 btrfs_err(root->fs_info, "no missing device found");
1941 return -ENOENT;
1942 }
1943
1944 return 0;
1945 } else {
1946 return btrfs_find_device_by_path(root, device_path, device);
1947 }
1948}
1949
1950/*
1951 * does all the dirty work required for changing file system's UUID.
1952 */
1953static int btrfs_prepare_sprout(struct btrfs_root *root)
1954{
1955 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
1956 struct btrfs_fs_devices *old_devices;
1957 struct btrfs_fs_devices *seed_devices;
1958 struct btrfs_super_block *disk_super = root->fs_info->super_copy;
1959 struct btrfs_device *device;
1960 u64 super_flags;
1961
1962 BUG_ON(!mutex_is_locked(&uuid_mutex));
1963 if (!fs_devices->seeding)
1964 return -EINVAL;
1965
1966 seed_devices = __alloc_fs_devices();
1967 if (IS_ERR(seed_devices))
1968 return PTR_ERR(seed_devices);
1969
1970 old_devices = clone_fs_devices(fs_devices);
1971 if (IS_ERR(old_devices)) {
1972 kfree(seed_devices);
1973 return PTR_ERR(old_devices);
1974 }
1975
1976 list_add(&old_devices->list, &fs_uuids);
1977
1978 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
1979 seed_devices->opened = 1;
1980 INIT_LIST_HEAD(&seed_devices->devices);
1981 INIT_LIST_HEAD(&seed_devices->alloc_list);
1982 mutex_init(&seed_devices->device_list_mutex);
1983
1984 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1985 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
1986 synchronize_rcu);
1987
1988 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
1989 list_for_each_entry(device, &seed_devices->devices, dev_list) {
1990 device->fs_devices = seed_devices;
1991 }
1992
1993 fs_devices->seeding = 0;
1994 fs_devices->num_devices = 0;
1995 fs_devices->open_devices = 0;
1996 fs_devices->missing_devices = 0;
1997 fs_devices->num_can_discard = 0;
1998 fs_devices->rotating = 0;
1999 fs_devices->seed = seed_devices;
2000
2001 generate_random_uuid(fs_devices->fsid);
2002 memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2003 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2004 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2005
2006 super_flags = btrfs_super_flags(disk_super) &
2007 ~BTRFS_SUPER_FLAG_SEEDING;
2008 btrfs_set_super_flags(disk_super, super_flags);
2009
2010 return 0;
2011}
2012
2013/*
2014 * strore the expected generation for seed devices in device items.
2015 */
2016static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2017 struct btrfs_root *root)
2018{
2019 struct btrfs_path *path;
2020 struct extent_buffer *leaf;
2021 struct btrfs_dev_item *dev_item;
2022 struct btrfs_device *device;
2023 struct btrfs_key key;
2024 u8 fs_uuid[BTRFS_UUID_SIZE];
2025 u8 dev_uuid[BTRFS_UUID_SIZE];
2026 u64 devid;
2027 int ret;
2028
2029 path = btrfs_alloc_path();
2030 if (!path)
2031 return -ENOMEM;
2032
2033 root = root->fs_info->chunk_root;
2034 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2035 key.offset = 0;
2036 key.type = BTRFS_DEV_ITEM_KEY;
2037
2038 while (1) {
2039 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2040 if (ret < 0)
2041 goto error;
2042
2043 leaf = path->nodes[0];
2044next_slot:
2045 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2046 ret = btrfs_next_leaf(root, path);
2047 if (ret > 0)
2048 break;
2049 if (ret < 0)
2050 goto error;
2051 leaf = path->nodes[0];
2052 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2053 btrfs_release_path(path);
2054 continue;
2055 }
2056
2057 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2058 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2059 key.type != BTRFS_DEV_ITEM_KEY)
2060 break;
2061
2062 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2063 struct btrfs_dev_item);
2064 devid = btrfs_device_id(leaf, dev_item);
2065 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2066 BTRFS_UUID_SIZE);
2067 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2068 BTRFS_UUID_SIZE);
2069 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
2070 fs_uuid);
2071 BUG_ON(!device); /* Logic error */
2072
2073 if (device->fs_devices->seeding) {
2074 btrfs_set_device_generation(leaf, dev_item,
2075 device->generation);
2076 btrfs_mark_buffer_dirty(leaf);
2077 }
2078
2079 path->slots[0]++;
2080 goto next_slot;
2081 }
2082 ret = 0;
2083error:
2084 btrfs_free_path(path);
2085 return ret;
2086}
2087
2088int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
2089{
2090 struct request_queue *q;
2091 struct btrfs_trans_handle *trans;
2092 struct btrfs_device *device;
2093 struct block_device *bdev;
2094 struct list_head *devices;
2095 struct super_block *sb = root->fs_info->sb;
2096 struct rcu_string *name;
2097 u64 total_bytes;
2098 int seeding_dev = 0;
2099 int ret = 0;
2100
2101 if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
2102 return -EROFS;
2103
2104 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2105 root->fs_info->bdev_holder);
2106 if (IS_ERR(bdev))
2107 return PTR_ERR(bdev);
2108
2109 if (root->fs_info->fs_devices->seeding) {
2110 seeding_dev = 1;
2111 down_write(&sb->s_umount);
2112 mutex_lock(&uuid_mutex);
2113 }
2114
2115 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2116
2117 devices = &root->fs_info->fs_devices->devices;
2118
2119 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2120 list_for_each_entry(device, devices, dev_list) {
2121 if (device->bdev == bdev) {
2122 ret = -EEXIST;
2123 mutex_unlock(
2124 &root->fs_info->fs_devices->device_list_mutex);
2125 goto error;
2126 }
2127 }
2128 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2129
2130 device = btrfs_alloc_device(root->fs_info, NULL, NULL);
2131 if (IS_ERR(device)) {
2132 /* we can safely leave the fs_devices entry around */
2133 ret = PTR_ERR(device);
2134 goto error;
2135 }
2136
2137 name = rcu_string_strdup(device_path, GFP_NOFS);
2138 if (!name) {
2139 kfree(device);
2140 ret = -ENOMEM;
2141 goto error;
2142 }
2143 rcu_assign_pointer(device->name, name);
2144
2145 trans = btrfs_start_transaction(root, 0);
2146 if (IS_ERR(trans)) {
2147 rcu_string_free(device->name);
2148 kfree(device);
2149 ret = PTR_ERR(trans);
2150 goto error;
2151 }
2152
2153 lock_chunks(root);
2154
2155 q = bdev_get_queue(bdev);
2156 if (blk_queue_discard(q))
2157 device->can_discard = 1;
2158 device->writeable = 1;
2159 device->generation = trans->transid;
2160 device->io_width = root->sectorsize;
2161 device->io_align = root->sectorsize;
2162 device->sector_size = root->sectorsize;
2163 device->total_bytes = i_size_read(bdev->bd_inode);
2164 device->disk_total_bytes = device->total_bytes;
2165 device->dev_root = root->fs_info->dev_root;
2166 device->bdev = bdev;
2167 device->in_fs_metadata = 1;
2168 device->is_tgtdev_for_dev_replace = 0;
2169 device->mode = FMODE_EXCL;
2170 device->dev_stats_valid = 1;
2171 set_blocksize(device->bdev, 4096);
2172
2173 if (seeding_dev) {
2174 sb->s_flags &= ~MS_RDONLY;
2175 ret = btrfs_prepare_sprout(root);
2176 BUG_ON(ret); /* -ENOMEM */
2177 }
2178
2179 device->fs_devices = root->fs_info->fs_devices;
2180
2181 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2182 list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
2183 list_add(&device->dev_alloc_list,
2184 &root->fs_info->fs_devices->alloc_list);
2185 root->fs_info->fs_devices->num_devices++;
2186 root->fs_info->fs_devices->open_devices++;
2187 root->fs_info->fs_devices->rw_devices++;
2188 root->fs_info->fs_devices->total_devices++;
2189 if (device->can_discard)
2190 root->fs_info->fs_devices->num_can_discard++;
2191 root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2192
2193 spin_lock(&root->fs_info->free_chunk_lock);
2194 root->fs_info->free_chunk_space += device->total_bytes;
2195 spin_unlock(&root->fs_info->free_chunk_lock);
2196
2197 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
2198 root->fs_info->fs_devices->rotating = 1;
2199
2200 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
2201 btrfs_set_super_total_bytes(root->fs_info->super_copy,
2202 total_bytes + device->total_bytes);
2203
2204 total_bytes = btrfs_super_num_devices(root->fs_info->super_copy);
2205 btrfs_set_super_num_devices(root->fs_info->super_copy,
2206 total_bytes + 1);
2207
2208 /* add sysfs device entry */
2209 btrfs_kobj_add_device(root->fs_info, device);
2210
2211 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2212
2213 if (seeding_dev) {
2214 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2215 ret = init_first_rw_device(trans, root, device);
2216 if (ret) {
2217 btrfs_abort_transaction(trans, root, ret);
2218 goto error_trans;
2219 }
2220 ret = btrfs_finish_sprout(trans, root);
2221 if (ret) {
2222 btrfs_abort_transaction(trans, root, ret);
2223 goto error_trans;
2224 }
2225
2226 /* Sprouting would change fsid of the mounted root,
2227 * so rename the fsid on the sysfs
2228 */
2229 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2230 root->fs_info->fsid);
2231 if (kobject_rename(&root->fs_info->super_kobj, fsid_buf))
2232 goto error_trans;
2233 } else {
2234 ret = btrfs_add_device(trans, root, device);
2235 if (ret) {
2236 btrfs_abort_transaction(trans, root, ret);
2237 goto error_trans;
2238 }
2239 }
2240
2241 /*
2242 * we've got more storage, clear any full flags on the space
2243 * infos
2244 */
2245 btrfs_clear_space_info_full(root->fs_info);
2246
2247 unlock_chunks(root);
2248 root->fs_info->num_tolerated_disk_barrier_failures =
2249 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
2250 ret = btrfs_commit_transaction(trans, root);
2251
2252 if (seeding_dev) {
2253 mutex_unlock(&uuid_mutex);
2254 up_write(&sb->s_umount);
2255
2256 if (ret) /* transaction commit */
2257 return ret;
2258
2259 ret = btrfs_relocate_sys_chunks(root);
2260 if (ret < 0)
2261 btrfs_error(root->fs_info, ret,
2262 "Failed to relocate sys chunks after "
2263 "device initialization. This can be fixed "
2264 "using the \"btrfs balance\" command.");
2265 trans = btrfs_attach_transaction(root);
2266 if (IS_ERR(trans)) {
2267 if (PTR_ERR(trans) == -ENOENT)
2268 return 0;
2269 return PTR_ERR(trans);
2270 }
2271 ret = btrfs_commit_transaction(trans, root);
2272 }
2273
2274 /* Update ctime/mtime for libblkid */
2275 update_dev_time(device_path);
2276 return ret;
2277
2278error_trans:
2279 unlock_chunks(root);
2280 btrfs_end_transaction(trans, root);
2281 rcu_string_free(device->name);
2282 btrfs_kobj_rm_device(root->fs_info, device);
2283 kfree(device);
2284error:
2285 blkdev_put(bdev, FMODE_EXCL);
2286 if (seeding_dev) {
2287 mutex_unlock(&uuid_mutex);
2288 up_write(&sb->s_umount);
2289 }
2290 return ret;
2291}
2292
2293int btrfs_init_dev_replace_tgtdev(struct btrfs_root *root, char *device_path,
2294 struct btrfs_device **device_out)
2295{
2296 struct request_queue *q;
2297 struct btrfs_device *device;
2298 struct block_device *bdev;
2299 struct btrfs_fs_info *fs_info = root->fs_info;
2300 struct list_head *devices;
2301 struct rcu_string *name;
2302 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2303 int ret = 0;
2304
2305 *device_out = NULL;
2306 if (fs_info->fs_devices->seeding)
2307 return -EINVAL;
2308
2309 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2310 fs_info->bdev_holder);
2311 if (IS_ERR(bdev))
2312 return PTR_ERR(bdev);
2313
2314 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2315
2316 devices = &fs_info->fs_devices->devices;
2317 list_for_each_entry(device, devices, dev_list) {
2318 if (device->bdev == bdev) {
2319 ret = -EEXIST;
2320 goto error;
2321 }
2322 }
2323
2324 device = btrfs_alloc_device(NULL, &devid, NULL);
2325 if (IS_ERR(device)) {
2326 ret = PTR_ERR(device);
2327 goto error;
2328 }
2329
2330 name = rcu_string_strdup(device_path, GFP_NOFS);
2331 if (!name) {
2332 kfree(device);
2333 ret = -ENOMEM;
2334 goto error;
2335 }
2336 rcu_assign_pointer(device->name, name);
2337
2338 q = bdev_get_queue(bdev);
2339 if (blk_queue_discard(q))
2340 device->can_discard = 1;
2341 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2342 device->writeable = 1;
2343 device->generation = 0;
2344 device->io_width = root->sectorsize;
2345 device->io_align = root->sectorsize;
2346 device->sector_size = root->sectorsize;
2347 device->total_bytes = i_size_read(bdev->bd_inode);
2348 device->disk_total_bytes = device->total_bytes;
2349 device->dev_root = fs_info->dev_root;
2350 device->bdev = bdev;
2351 device->in_fs_metadata = 1;
2352 device->is_tgtdev_for_dev_replace = 1;
2353 device->mode = FMODE_EXCL;
2354 device->dev_stats_valid = 1;
2355 set_blocksize(device->bdev, 4096);
2356 device->fs_devices = fs_info->fs_devices;
2357 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2358 fs_info->fs_devices->num_devices++;
2359 fs_info->fs_devices->open_devices++;
2360 if (device->can_discard)
2361 fs_info->fs_devices->num_can_discard++;
2362 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2363
2364 *device_out = device;
2365 return ret;
2366
2367error:
2368 blkdev_put(bdev, FMODE_EXCL);
2369 return ret;
2370}
2371
2372void btrfs_init_dev_replace_tgtdev_for_resume(struct btrfs_fs_info *fs_info,
2373 struct btrfs_device *tgtdev)
2374{
2375 WARN_ON(fs_info->fs_devices->rw_devices == 0);
2376 tgtdev->io_width = fs_info->dev_root->sectorsize;
2377 tgtdev->io_align = fs_info->dev_root->sectorsize;
2378 tgtdev->sector_size = fs_info->dev_root->sectorsize;
2379 tgtdev->dev_root = fs_info->dev_root;
2380 tgtdev->in_fs_metadata = 1;
2381}
2382
2383static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2384 struct btrfs_device *device)
2385{
2386 int ret;
2387 struct btrfs_path *path;
2388 struct btrfs_root *root;
2389 struct btrfs_dev_item *dev_item;
2390 struct extent_buffer *leaf;
2391 struct btrfs_key key;
2392
2393 root = device->dev_root->fs_info->chunk_root;
2394
2395 path = btrfs_alloc_path();
2396 if (!path)
2397 return -ENOMEM;
2398
2399 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2400 key.type = BTRFS_DEV_ITEM_KEY;
2401 key.offset = device->devid;
2402
2403 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2404 if (ret < 0)
2405 goto out;
2406
2407 if (ret > 0) {
2408 ret = -ENOENT;
2409 goto out;
2410 }
2411
2412 leaf = path->nodes[0];
2413 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2414
2415 btrfs_set_device_id(leaf, dev_item, device->devid);
2416 btrfs_set_device_type(leaf, dev_item, device->type);
2417 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2418 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2419 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2420 btrfs_set_device_total_bytes(leaf, dev_item, device->disk_total_bytes);
2421 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
2422 btrfs_mark_buffer_dirty(leaf);
2423
2424out:
2425 btrfs_free_path(path);
2426 return ret;
2427}
2428
2429static int __btrfs_grow_device(struct btrfs_trans_handle *trans,
2430 struct btrfs_device *device, u64 new_size)
2431{
2432 struct btrfs_super_block *super_copy =
2433 device->dev_root->fs_info->super_copy;
2434 u64 old_total = btrfs_super_total_bytes(super_copy);
2435 u64 diff = new_size - device->total_bytes;
2436
2437 if (!device->writeable)
2438 return -EACCES;
2439 if (new_size <= device->total_bytes ||
2440 device->is_tgtdev_for_dev_replace)
2441 return -EINVAL;
2442
2443 btrfs_set_super_total_bytes(super_copy, old_total + diff);
2444 device->fs_devices->total_rw_bytes += diff;
2445
2446 device->total_bytes = new_size;
2447 device->disk_total_bytes = new_size;
2448 btrfs_clear_space_info_full(device->dev_root->fs_info);
2449
2450 return btrfs_update_device(trans, device);
2451}
2452
2453int btrfs_grow_device(struct btrfs_trans_handle *trans,
2454 struct btrfs_device *device, u64 new_size)
2455{
2456 int ret;
2457 lock_chunks(device->dev_root);
2458 ret = __btrfs_grow_device(trans, device, new_size);
2459 unlock_chunks(device->dev_root);
2460 return ret;
2461}
2462
2463static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2464 struct btrfs_root *root,
2465 u64 chunk_tree, u64 chunk_objectid,
2466 u64 chunk_offset)
2467{
2468 int ret;
2469 struct btrfs_path *path;
2470 struct btrfs_key key;
2471
2472 root = root->fs_info->chunk_root;
2473 path = btrfs_alloc_path();
2474 if (!path)
2475 return -ENOMEM;
2476
2477 key.objectid = chunk_objectid;
2478 key.offset = chunk_offset;
2479 key.type = BTRFS_CHUNK_ITEM_KEY;
2480
2481 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2482 if (ret < 0)
2483 goto out;
2484 else if (ret > 0) { /* Logic error or corruption */
2485 btrfs_error(root->fs_info, -ENOENT,
2486 "Failed lookup while freeing chunk.");
2487 ret = -ENOENT;
2488 goto out;
2489 }
2490
2491 ret = btrfs_del_item(trans, root, path);
2492 if (ret < 0)
2493 btrfs_error(root->fs_info, ret,
2494 "Failed to delete chunk item.");
2495out:
2496 btrfs_free_path(path);
2497 return ret;
2498}
2499
2500static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
2501 chunk_offset)
2502{
2503 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
2504 struct btrfs_disk_key *disk_key;
2505 struct btrfs_chunk *chunk;
2506 u8 *ptr;
2507 int ret = 0;
2508 u32 num_stripes;
2509 u32 array_size;
2510 u32 len = 0;
2511 u32 cur;
2512 struct btrfs_key key;
2513
2514 array_size = btrfs_super_sys_array_size(super_copy);
2515
2516 ptr = super_copy->sys_chunk_array;
2517 cur = 0;
2518
2519 while (cur < array_size) {
2520 disk_key = (struct btrfs_disk_key *)ptr;
2521 btrfs_disk_key_to_cpu(&key, disk_key);
2522
2523 len = sizeof(*disk_key);
2524
2525 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2526 chunk = (struct btrfs_chunk *)(ptr + len);
2527 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2528 len += btrfs_chunk_item_size(num_stripes);
2529 } else {
2530 ret = -EIO;
2531 break;
2532 }
2533 if (key.objectid == chunk_objectid &&
2534 key.offset == chunk_offset) {
2535 memmove(ptr, ptr + len, array_size - (cur + len));
2536 array_size -= len;
2537 btrfs_set_super_sys_array_size(super_copy, array_size);
2538 } else {
2539 ptr += len;
2540 cur += len;
2541 }
2542 }
2543 return ret;
2544}
2545
2546static int btrfs_relocate_chunk(struct btrfs_root *root,
2547 u64 chunk_tree, u64 chunk_objectid,
2548 u64 chunk_offset)
2549{
2550 struct extent_map_tree *em_tree;
2551 struct btrfs_root *extent_root;
2552 struct btrfs_trans_handle *trans;
2553 struct extent_map *em;
2554 struct map_lookup *map;
2555 int ret;
2556 int i;
2557
2558 root = root->fs_info->chunk_root;
2559 extent_root = root->fs_info->extent_root;
2560 em_tree = &root->fs_info->mapping_tree.map_tree;
2561
2562 ret = btrfs_can_relocate(extent_root, chunk_offset);
2563 if (ret)
2564 return -ENOSPC;
2565
2566 /* step one, relocate all the extents inside this chunk */
2567 ret = btrfs_relocate_block_group(extent_root, chunk_offset);
2568 if (ret)
2569 return ret;
2570
2571 trans = btrfs_start_transaction(root, 0);
2572 if (IS_ERR(trans)) {
2573 ret = PTR_ERR(trans);
2574 btrfs_std_error(root->fs_info, ret);
2575 return ret;
2576 }
2577
2578 lock_chunks(root);
2579
2580 /*
2581 * step two, delete the device extents and the
2582 * chunk tree entries
2583 */
2584 read_lock(&em_tree->lock);
2585 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
2586 read_unlock(&em_tree->lock);
2587
2588 BUG_ON(!em || em->start > chunk_offset ||
2589 em->start + em->len < chunk_offset);
2590 map = (struct map_lookup *)em->bdev;
2591
2592 for (i = 0; i < map->num_stripes; i++) {
2593 ret = btrfs_free_dev_extent(trans, map->stripes[i].dev,
2594 map->stripes[i].physical);
2595 BUG_ON(ret);
2596
2597 if (map->stripes[i].dev) {
2598 ret = btrfs_update_device(trans, map->stripes[i].dev);
2599 BUG_ON(ret);
2600 }
2601 }
2602 ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
2603 chunk_offset);
2604
2605 BUG_ON(ret);
2606
2607 trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
2608
2609 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2610 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
2611 BUG_ON(ret);
2612 }
2613
2614 ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
2615 BUG_ON(ret);
2616
2617 write_lock(&em_tree->lock);
2618 remove_extent_mapping(em_tree, em);
2619 write_unlock(&em_tree->lock);
2620
2621 /* once for the tree */
2622 free_extent_map(em);
2623 /* once for us */
2624 free_extent_map(em);
2625
2626 unlock_chunks(root);
2627 btrfs_end_transaction(trans, root);
2628 return 0;
2629}
2630
2631static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
2632{
2633 struct btrfs_root *chunk_root = root->fs_info->chunk_root;
2634 struct btrfs_path *path;
2635 struct extent_buffer *leaf;
2636 struct btrfs_chunk *chunk;
2637 struct btrfs_key key;
2638 struct btrfs_key found_key;
2639 u64 chunk_tree = chunk_root->root_key.objectid;
2640 u64 chunk_type;
2641 bool retried = false;
2642 int failed = 0;
2643 int ret;
2644
2645 path = btrfs_alloc_path();
2646 if (!path)
2647 return -ENOMEM;
2648
2649again:
2650 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2651 key.offset = (u64)-1;
2652 key.type = BTRFS_CHUNK_ITEM_KEY;
2653
2654 while (1) {
2655 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2656 if (ret < 0)
2657 goto error;
2658 BUG_ON(ret == 0); /* Corruption */
2659
2660 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2661 key.type);
2662 if (ret < 0)
2663 goto error;
2664 if (ret > 0)
2665 break;
2666
2667 leaf = path->nodes[0];
2668 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2669
2670 chunk = btrfs_item_ptr(leaf, path->slots[0],
2671 struct btrfs_chunk);
2672 chunk_type = btrfs_chunk_type(leaf, chunk);
2673 btrfs_release_path(path);
2674
2675 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2676 ret = btrfs_relocate_chunk(chunk_root, chunk_tree,
2677 found_key.objectid,
2678 found_key.offset);
2679 if (ret == -ENOSPC)
2680 failed++;
2681 else
2682 BUG_ON(ret);
2683 }
2684
2685 if (found_key.offset == 0)
2686 break;
2687 key.offset = found_key.offset - 1;
2688 }
2689 ret = 0;
2690 if (failed && !retried) {
2691 failed = 0;
2692 retried = true;
2693 goto again;
2694 } else if (WARN_ON(failed && retried)) {
2695 ret = -ENOSPC;
2696 }
2697error:
2698 btrfs_free_path(path);
2699 return ret;
2700}
2701
2702static int insert_balance_item(struct btrfs_root *root,
2703 struct btrfs_balance_control *bctl)
2704{
2705 struct btrfs_trans_handle *trans;
2706 struct btrfs_balance_item *item;
2707 struct btrfs_disk_balance_args disk_bargs;
2708 struct btrfs_path *path;
2709 struct extent_buffer *leaf;
2710 struct btrfs_key key;
2711 int ret, err;
2712
2713 path = btrfs_alloc_path();
2714 if (!path)
2715 return -ENOMEM;
2716
2717 trans = btrfs_start_transaction(root, 0);
2718 if (IS_ERR(trans)) {
2719 btrfs_free_path(path);
2720 return PTR_ERR(trans);
2721 }
2722
2723 key.objectid = BTRFS_BALANCE_OBJECTID;
2724 key.type = BTRFS_BALANCE_ITEM_KEY;
2725 key.offset = 0;
2726
2727 ret = btrfs_insert_empty_item(trans, root, path, &key,
2728 sizeof(*item));
2729 if (ret)
2730 goto out;
2731
2732 leaf = path->nodes[0];
2733 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2734
2735 memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
2736
2737 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
2738 btrfs_set_balance_data(leaf, item, &disk_bargs);
2739 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
2740 btrfs_set_balance_meta(leaf, item, &disk_bargs);
2741 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
2742 btrfs_set_balance_sys(leaf, item, &disk_bargs);
2743
2744 btrfs_set_balance_flags(leaf, item, bctl->flags);
2745
2746 btrfs_mark_buffer_dirty(leaf);
2747out:
2748 btrfs_free_path(path);
2749 err = btrfs_commit_transaction(trans, root);
2750 if (err && !ret)
2751 ret = err;
2752 return ret;
2753}
2754
2755static int del_balance_item(struct btrfs_root *root)
2756{
2757 struct btrfs_trans_handle *trans;
2758 struct btrfs_path *path;
2759 struct btrfs_key key;
2760 int ret, err;
2761
2762 path = btrfs_alloc_path();
2763 if (!path)
2764 return -ENOMEM;
2765
2766 trans = btrfs_start_transaction(root, 0);
2767 if (IS_ERR(trans)) {
2768 btrfs_free_path(path);
2769 return PTR_ERR(trans);
2770 }
2771
2772 key.objectid = BTRFS_BALANCE_OBJECTID;
2773 key.type = BTRFS_BALANCE_ITEM_KEY;
2774 key.offset = 0;
2775
2776 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2777 if (ret < 0)
2778 goto out;
2779 if (ret > 0) {
2780 ret = -ENOENT;
2781 goto out;
2782 }
2783
2784 ret = btrfs_del_item(trans, root, path);
2785out:
2786 btrfs_free_path(path);
2787 err = btrfs_commit_transaction(trans, root);
2788 if (err && !ret)
2789 ret = err;
2790 return ret;
2791}
2792
2793/*
2794 * This is a heuristic used to reduce the number of chunks balanced on
2795 * resume after balance was interrupted.
2796 */
2797static void update_balance_args(struct btrfs_balance_control *bctl)
2798{
2799 /*
2800 * Turn on soft mode for chunk types that were being converted.
2801 */
2802 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
2803 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
2804 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
2805 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
2806 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
2807 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
2808
2809 /*
2810 * Turn on usage filter if is not already used. The idea is
2811 * that chunks that we have already balanced should be
2812 * reasonably full. Don't do it for chunks that are being
2813 * converted - that will keep us from relocating unconverted
2814 * (albeit full) chunks.
2815 */
2816 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2817 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2818 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
2819 bctl->data.usage = 90;
2820 }
2821 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2822 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2823 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
2824 bctl->sys.usage = 90;
2825 }
2826 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2827 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2828 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
2829 bctl->meta.usage = 90;
2830 }
2831}
2832
2833/*
2834 * Should be called with both balance and volume mutexes held to
2835 * serialize other volume operations (add_dev/rm_dev/resize) with
2836 * restriper. Same goes for unset_balance_control.
2837 */
2838static void set_balance_control(struct btrfs_balance_control *bctl)
2839{
2840 struct btrfs_fs_info *fs_info = bctl->fs_info;
2841
2842 BUG_ON(fs_info->balance_ctl);
2843
2844 spin_lock(&fs_info->balance_lock);
2845 fs_info->balance_ctl = bctl;
2846 spin_unlock(&fs_info->balance_lock);
2847}
2848
2849static void unset_balance_control(struct btrfs_fs_info *fs_info)
2850{
2851 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
2852
2853 BUG_ON(!fs_info->balance_ctl);
2854
2855 spin_lock(&fs_info->balance_lock);
2856 fs_info->balance_ctl = NULL;
2857 spin_unlock(&fs_info->balance_lock);
2858
2859 kfree(bctl);
2860}
2861
2862/*
2863 * Balance filters. Return 1 if chunk should be filtered out
2864 * (should not be balanced).
2865 */
2866static int chunk_profiles_filter(u64 chunk_type,
2867 struct btrfs_balance_args *bargs)
2868{
2869 chunk_type = chunk_to_extended(chunk_type) &
2870 BTRFS_EXTENDED_PROFILE_MASK;
2871
2872 if (bargs->profiles & chunk_type)
2873 return 0;
2874
2875 return 1;
2876}
2877
2878static int chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
2879 struct btrfs_balance_args *bargs)
2880{
2881 struct btrfs_block_group_cache *cache;
2882 u64 chunk_used, user_thresh;
2883 int ret = 1;
2884
2885 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2886 chunk_used = btrfs_block_group_used(&cache->item);
2887
2888 if (bargs->usage == 0)
2889 user_thresh = 1;
2890 else if (bargs->usage > 100)
2891 user_thresh = cache->key.offset;
2892 else
2893 user_thresh = div_factor_fine(cache->key.offset,
2894 bargs->usage);
2895
2896 if (chunk_used < user_thresh)
2897 ret = 0;
2898
2899 btrfs_put_block_group(cache);
2900 return ret;
2901}
2902
2903static int chunk_devid_filter(struct extent_buffer *leaf,
2904 struct btrfs_chunk *chunk,
2905 struct btrfs_balance_args *bargs)
2906{
2907 struct btrfs_stripe *stripe;
2908 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2909 int i;
2910
2911 for (i = 0; i < num_stripes; i++) {
2912 stripe = btrfs_stripe_nr(chunk, i);
2913 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
2914 return 0;
2915 }
2916
2917 return 1;
2918}
2919
2920/* [pstart, pend) */
2921static int chunk_drange_filter(struct extent_buffer *leaf,
2922 struct btrfs_chunk *chunk,
2923 u64 chunk_offset,
2924 struct btrfs_balance_args *bargs)
2925{
2926 struct btrfs_stripe *stripe;
2927 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2928 u64 stripe_offset;
2929 u64 stripe_length;
2930 int factor;
2931 int i;
2932
2933 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
2934 return 0;
2935
2936 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
2937 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
2938 factor = num_stripes / 2;
2939 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
2940 factor = num_stripes - 1;
2941 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
2942 factor = num_stripes - 2;
2943 } else {
2944 factor = num_stripes;
2945 }
2946
2947 for (i = 0; i < num_stripes; i++) {
2948 stripe = btrfs_stripe_nr(chunk, i);
2949 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
2950 continue;
2951
2952 stripe_offset = btrfs_stripe_offset(leaf, stripe);
2953 stripe_length = btrfs_chunk_length(leaf, chunk);
2954 do_div(stripe_length, factor);
2955
2956 if (stripe_offset < bargs->pend &&
2957 stripe_offset + stripe_length > bargs->pstart)
2958 return 0;
2959 }
2960
2961 return 1;
2962}
2963
2964/* [vstart, vend) */
2965static int chunk_vrange_filter(struct extent_buffer *leaf,
2966 struct btrfs_chunk *chunk,
2967 u64 chunk_offset,
2968 struct btrfs_balance_args *bargs)
2969{
2970 if (chunk_offset < bargs->vend &&
2971 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
2972 /* at least part of the chunk is inside this vrange */
2973 return 0;
2974
2975 return 1;
2976}
2977
2978static int chunk_soft_convert_filter(u64 chunk_type,
2979 struct btrfs_balance_args *bargs)
2980{
2981 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
2982 return 0;
2983
2984 chunk_type = chunk_to_extended(chunk_type) &
2985 BTRFS_EXTENDED_PROFILE_MASK;
2986
2987 if (bargs->target == chunk_type)
2988 return 1;
2989
2990 return 0;
2991}
2992
2993static int should_balance_chunk(struct btrfs_root *root,
2994 struct extent_buffer *leaf,
2995 struct btrfs_chunk *chunk, u64 chunk_offset)
2996{
2997 struct btrfs_balance_control *bctl = root->fs_info->balance_ctl;
2998 struct btrfs_balance_args *bargs = NULL;
2999 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3000
3001 /* type filter */
3002 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3003 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3004 return 0;
3005 }
3006
3007 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3008 bargs = &bctl->data;
3009 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3010 bargs = &bctl->sys;
3011 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3012 bargs = &bctl->meta;
3013
3014 /* profiles filter */
3015 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3016 chunk_profiles_filter(chunk_type, bargs)) {
3017 return 0;
3018 }
3019
3020 /* usage filter */
3021 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3022 chunk_usage_filter(bctl->fs_info, chunk_offset, bargs)) {
3023 return 0;
3024 }
3025
3026 /* devid filter */
3027 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3028 chunk_devid_filter(leaf, chunk, bargs)) {
3029 return 0;
3030 }
3031
3032 /* drange filter, makes sense only with devid filter */
3033 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3034 chunk_drange_filter(leaf, chunk, chunk_offset, bargs)) {
3035 return 0;
3036 }
3037
3038 /* vrange filter */
3039 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3040 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3041 return 0;
3042 }
3043
3044 /* soft profile changing mode */
3045 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3046 chunk_soft_convert_filter(chunk_type, bargs)) {
3047 return 0;
3048 }
3049
3050 /*
3051 * limited by count, must be the last filter
3052 */
3053 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3054 if (bargs->limit == 0)
3055 return 0;
3056 else
3057 bargs->limit--;
3058 }
3059
3060 return 1;
3061}
3062
3063static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3064{
3065 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3066 struct btrfs_root *chunk_root = fs_info->chunk_root;
3067 struct btrfs_root *dev_root = fs_info->dev_root;
3068 struct list_head *devices;
3069 struct btrfs_device *device;
3070 u64 old_size;
3071 u64 size_to_free;
3072 struct btrfs_chunk *chunk;
3073 struct btrfs_path *path;
3074 struct btrfs_key key;
3075 struct btrfs_key found_key;
3076 struct btrfs_trans_handle *trans;
3077 struct extent_buffer *leaf;
3078 int slot;
3079 int ret;
3080 int enospc_errors = 0;
3081 bool counting = true;
3082 u64 limit_data = bctl->data.limit;
3083 u64 limit_meta = bctl->meta.limit;
3084 u64 limit_sys = bctl->sys.limit;
3085
3086 /* step one make some room on all the devices */
3087 devices = &fs_info->fs_devices->devices;
3088 list_for_each_entry(device, devices, dev_list) {
3089 old_size = device->total_bytes;
3090 size_to_free = div_factor(old_size, 1);
3091 size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
3092 if (!device->writeable ||
3093 device->total_bytes - device->bytes_used > size_to_free ||
3094 device->is_tgtdev_for_dev_replace)
3095 continue;
3096
3097 ret = btrfs_shrink_device(device, old_size - size_to_free);
3098 if (ret == -ENOSPC)
3099 break;
3100 BUG_ON(ret);
3101
3102 trans = btrfs_start_transaction(dev_root, 0);
3103 BUG_ON(IS_ERR(trans));
3104
3105 ret = btrfs_grow_device(trans, device, old_size);
3106 BUG_ON(ret);
3107
3108 btrfs_end_transaction(trans, dev_root);
3109 }
3110
3111 /* step two, relocate all the chunks */
3112 path = btrfs_alloc_path();
3113 if (!path) {
3114 ret = -ENOMEM;
3115 goto error;
3116 }
3117
3118 /* zero out stat counters */
3119 spin_lock(&fs_info->balance_lock);
3120 memset(&bctl->stat, 0, sizeof(bctl->stat));
3121 spin_unlock(&fs_info->balance_lock);
3122again:
3123 if (!counting) {
3124 bctl->data.limit = limit_data;
3125 bctl->meta.limit = limit_meta;
3126 bctl->sys.limit = limit_sys;
3127 }
3128 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3129 key.offset = (u64)-1;
3130 key.type = BTRFS_CHUNK_ITEM_KEY;
3131
3132 while (1) {
3133 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3134 atomic_read(&fs_info->balance_cancel_req)) {
3135 ret = -ECANCELED;
3136 goto error;
3137 }
3138
3139 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3140 if (ret < 0)
3141 goto error;
3142
3143 /*
3144 * this shouldn't happen, it means the last relocate
3145 * failed
3146 */
3147 if (ret == 0)
3148 BUG(); /* FIXME break ? */
3149
3150 ret = btrfs_previous_item(chunk_root, path, 0,
3151 BTRFS_CHUNK_ITEM_KEY);
3152 if (ret) {
3153 ret = 0;
3154 break;
3155 }
3156
3157 leaf = path->nodes[0];
3158 slot = path->slots[0];
3159 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3160
3161 if (found_key.objectid != key.objectid)
3162 break;
3163
3164 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3165
3166 if (!counting) {
3167 spin_lock(&fs_info->balance_lock);
3168 bctl->stat.considered++;
3169 spin_unlock(&fs_info->balance_lock);
3170 }
3171
3172 ret = should_balance_chunk(chunk_root, leaf, chunk,
3173 found_key.offset);
3174 btrfs_release_path(path);
3175 if (!ret)
3176 goto loop;
3177
3178 if (counting) {
3179 spin_lock(&fs_info->balance_lock);
3180 bctl->stat.expected++;
3181 spin_unlock(&fs_info->balance_lock);
3182 goto loop;
3183 }
3184
3185 ret = btrfs_relocate_chunk(chunk_root,
3186 chunk_root->root_key.objectid,
3187 found_key.objectid,
3188 found_key.offset);
3189 if (ret && ret != -ENOSPC)
3190 goto error;
3191 if (ret == -ENOSPC) {
3192 enospc_errors++;
3193 } else {
3194 spin_lock(&fs_info->balance_lock);
3195 bctl->stat.completed++;
3196 spin_unlock(&fs_info->balance_lock);
3197 }
3198loop:
3199 if (found_key.offset == 0)
3200 break;
3201 key.offset = found_key.offset - 1;
3202 }
3203
3204 if (counting) {
3205 btrfs_release_path(path);
3206 counting = false;
3207 goto again;
3208 }
3209error:
3210 btrfs_free_path(path);
3211 if (enospc_errors) {
3212 btrfs_info(fs_info, "%d enospc errors during balance",
3213 enospc_errors);
3214 if (!ret)
3215 ret = -ENOSPC;
3216 }
3217
3218 return ret;
3219}
3220
3221/**
3222 * alloc_profile_is_valid - see if a given profile is valid and reduced
3223 * @flags: profile to validate
3224 * @extended: if true @flags is treated as an extended profile
3225 */
3226static int alloc_profile_is_valid(u64 flags, int extended)
3227{
3228 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3229 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3230
3231 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3232
3233 /* 1) check that all other bits are zeroed */
3234 if (flags & ~mask)
3235 return 0;
3236
3237 /* 2) see if profile is reduced */
3238 if (flags == 0)
3239 return !extended; /* "0" is valid for usual profiles */
3240
3241 /* true if exactly one bit set */
3242 return (flags & (flags - 1)) == 0;
3243}
3244
3245static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3246{
3247 /* cancel requested || normal exit path */
3248 return atomic_read(&fs_info->balance_cancel_req) ||
3249 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3250 atomic_read(&fs_info->balance_cancel_req) == 0);
3251}
3252
3253static void __cancel_balance(struct btrfs_fs_info *fs_info)
3254{
3255 int ret;
3256
3257 unset_balance_control(fs_info);
3258 ret = del_balance_item(fs_info->tree_root);
3259 if (ret)
3260 btrfs_std_error(fs_info, ret);
3261
3262 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3263}
3264
3265/*
3266 * Should be called with both balance and volume mutexes held
3267 */
3268int btrfs_balance(struct btrfs_balance_control *bctl,
3269 struct btrfs_ioctl_balance_args *bargs)
3270{
3271 struct btrfs_fs_info *fs_info = bctl->fs_info;
3272 u64 allowed;
3273 int mixed = 0;
3274 int ret;
3275 u64 num_devices;
3276 unsigned seq;
3277
3278 if (btrfs_fs_closing(fs_info) ||
3279 atomic_read(&fs_info->balance_pause_req) ||
3280 atomic_read(&fs_info->balance_cancel_req)) {
3281 ret = -EINVAL;
3282 goto out;
3283 }
3284
3285 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3286 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3287 mixed = 1;
3288
3289 /*
3290 * In case of mixed groups both data and meta should be picked,
3291 * and identical options should be given for both of them.
3292 */
3293 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3294 if (mixed && (bctl->flags & allowed)) {
3295 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3296 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3297 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3298 btrfs_err(fs_info, "with mixed groups data and "
3299 "metadata balance options must be the same");
3300 ret = -EINVAL;
3301 goto out;
3302 }
3303 }
3304
3305 num_devices = fs_info->fs_devices->num_devices;
3306 btrfs_dev_replace_lock(&fs_info->dev_replace);
3307 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3308 BUG_ON(num_devices < 1);
3309 num_devices--;
3310 }
3311 btrfs_dev_replace_unlock(&fs_info->dev_replace);
3312 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
3313 if (num_devices == 1)
3314 allowed |= BTRFS_BLOCK_GROUP_DUP;
3315 else if (num_devices > 1)
3316 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3317 if (num_devices > 2)
3318 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3319 if (num_devices > 3)
3320 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3321 BTRFS_BLOCK_GROUP_RAID6);
3322 if ((bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3323 (!alloc_profile_is_valid(bctl->data.target, 1) ||
3324 (bctl->data.target & ~allowed))) {
3325 btrfs_err(fs_info, "unable to start balance with target "
3326 "data profile %llu",
3327 bctl->data.target);
3328 ret = -EINVAL;
3329 goto out;
3330 }
3331 if ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3332 (!alloc_profile_is_valid(bctl->meta.target, 1) ||
3333 (bctl->meta.target & ~allowed))) {
3334 btrfs_err(fs_info,
3335 "unable to start balance with target metadata profile %llu",
3336 bctl->meta.target);
3337 ret = -EINVAL;
3338 goto out;
3339 }
3340 if ((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3341 (!alloc_profile_is_valid(bctl->sys.target, 1) ||
3342 (bctl->sys.target & ~allowed))) {
3343 btrfs_err(fs_info,
3344 "unable to start balance with target system profile %llu",
3345 bctl->sys.target);
3346 ret = -EINVAL;
3347 goto out;
3348 }
3349
3350 /* allow dup'ed data chunks only in mixed mode */
3351 if (!mixed && (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3352 (bctl->data.target & BTRFS_BLOCK_GROUP_DUP)) {
3353 btrfs_err(fs_info, "dup for data is not allowed");
3354 ret = -EINVAL;
3355 goto out;
3356 }
3357
3358 /* allow to reduce meta or sys integrity only if force set */
3359 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3360 BTRFS_BLOCK_GROUP_RAID10 |
3361 BTRFS_BLOCK_GROUP_RAID5 |
3362 BTRFS_BLOCK_GROUP_RAID6;
3363 do {
3364 seq = read_seqbegin(&fs_info->profiles_lock);
3365
3366 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3367 (fs_info->avail_system_alloc_bits & allowed) &&
3368 !(bctl->sys.target & allowed)) ||
3369 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3370 (fs_info->avail_metadata_alloc_bits & allowed) &&
3371 !(bctl->meta.target & allowed))) {
3372 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3373 btrfs_info(fs_info, "force reducing metadata integrity");
3374 } else {
3375 btrfs_err(fs_info, "balance will reduce metadata "
3376 "integrity, use force if you want this");
3377 ret = -EINVAL;
3378 goto out;
3379 }
3380 }
3381 } while (read_seqretry(&fs_info->profiles_lock, seq));
3382
3383 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3384 int num_tolerated_disk_barrier_failures;
3385 u64 target = bctl->sys.target;
3386
3387 num_tolerated_disk_barrier_failures =
3388 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3389 if (num_tolerated_disk_barrier_failures > 0 &&
3390 (target &
3391 (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID0 |
3392 BTRFS_AVAIL_ALLOC_BIT_SINGLE)))
3393 num_tolerated_disk_barrier_failures = 0;
3394 else if (num_tolerated_disk_barrier_failures > 1 &&
3395 (target &
3396 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)))
3397 num_tolerated_disk_barrier_failures = 1;
3398
3399 fs_info->num_tolerated_disk_barrier_failures =
3400 num_tolerated_disk_barrier_failures;
3401 }
3402
3403 ret = insert_balance_item(fs_info->tree_root, bctl);
3404 if (ret && ret != -EEXIST)
3405 goto out;
3406
3407 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3408 BUG_ON(ret == -EEXIST);
3409 set_balance_control(bctl);
3410 } else {
3411 BUG_ON(ret != -EEXIST);
3412 spin_lock(&fs_info->balance_lock);
3413 update_balance_args(bctl);
3414 spin_unlock(&fs_info->balance_lock);
3415 }
3416
3417 atomic_inc(&fs_info->balance_running);
3418 mutex_unlock(&fs_info->balance_mutex);
3419
3420 ret = __btrfs_balance(fs_info);
3421
3422 mutex_lock(&fs_info->balance_mutex);
3423 atomic_dec(&fs_info->balance_running);
3424
3425 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3426 fs_info->num_tolerated_disk_barrier_failures =
3427 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3428 }
3429
3430 if (bargs) {
3431 memset(bargs, 0, sizeof(*bargs));
3432 update_ioctl_balance_args(fs_info, 0, bargs);
3433 }
3434
3435 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3436 balance_need_close(fs_info)) {
3437 __cancel_balance(fs_info);
3438 }
3439
3440 wake_up(&fs_info->balance_wait_q);
3441
3442 return ret;
3443out:
3444 if (bctl->flags & BTRFS_BALANCE_RESUME)
3445 __cancel_balance(fs_info);
3446 else {
3447 kfree(bctl);
3448 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3449 }
3450 return ret;
3451}
3452
3453static int balance_kthread(void *data)
3454{
3455 struct btrfs_fs_info *fs_info = data;
3456 int ret = 0;
3457
3458 mutex_lock(&fs_info->volume_mutex);
3459 mutex_lock(&fs_info->balance_mutex);
3460
3461 if (fs_info->balance_ctl) {
3462 btrfs_info(fs_info, "continuing balance");
3463 ret = btrfs_balance(fs_info->balance_ctl, NULL);
3464 }
3465
3466 mutex_unlock(&fs_info->balance_mutex);
3467 mutex_unlock(&fs_info->volume_mutex);
3468
3469 return ret;
3470}
3471
3472int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3473{
3474 struct task_struct *tsk;
3475
3476 spin_lock(&fs_info->balance_lock);
3477 if (!fs_info->balance_ctl) {
3478 spin_unlock(&fs_info->balance_lock);
3479 return 0;
3480 }
3481 spin_unlock(&fs_info->balance_lock);
3482
3483 if (btrfs_test_opt(fs_info->tree_root, SKIP_BALANCE)) {
3484 btrfs_info(fs_info, "force skipping balance");
3485 return 0;
3486 }
3487
3488 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3489 return PTR_ERR_OR_ZERO(tsk);
3490}
3491
3492int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3493{
3494 struct btrfs_balance_control *bctl;
3495 struct btrfs_balance_item *item;
3496 struct btrfs_disk_balance_args disk_bargs;
3497 struct btrfs_path *path;
3498 struct extent_buffer *leaf;
3499 struct btrfs_key key;
3500 int ret;
3501
3502 path = btrfs_alloc_path();
3503 if (!path)
3504 return -ENOMEM;
3505
3506 key.objectid = BTRFS_BALANCE_OBJECTID;
3507 key.type = BTRFS_BALANCE_ITEM_KEY;
3508 key.offset = 0;
3509
3510 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3511 if (ret < 0)
3512 goto out;
3513 if (ret > 0) { /* ret = -ENOENT; */
3514 ret = 0;
3515 goto out;
3516 }
3517
3518 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3519 if (!bctl) {
3520 ret = -ENOMEM;
3521 goto out;
3522 }
3523
3524 leaf = path->nodes[0];
3525 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3526
3527 bctl->fs_info = fs_info;
3528 bctl->flags = btrfs_balance_flags(leaf, item);
3529 bctl->flags |= BTRFS_BALANCE_RESUME;
3530
3531 btrfs_balance_data(leaf, item, &disk_bargs);
3532 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
3533 btrfs_balance_meta(leaf, item, &disk_bargs);
3534 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
3535 btrfs_balance_sys(leaf, item, &disk_bargs);
3536 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
3537
3538 WARN_ON(atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1));
3539
3540 mutex_lock(&fs_info->volume_mutex);
3541 mutex_lock(&fs_info->balance_mutex);
3542
3543 set_balance_control(bctl);
3544
3545 mutex_unlock(&fs_info->balance_mutex);
3546 mutex_unlock(&fs_info->volume_mutex);
3547out:
3548 btrfs_free_path(path);
3549 return ret;
3550}
3551
3552int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
3553{
3554 int ret = 0;
3555
3556 mutex_lock(&fs_info->balance_mutex);
3557 if (!fs_info->balance_ctl) {
3558 mutex_unlock(&fs_info->balance_mutex);
3559 return -ENOTCONN;
3560 }
3561
3562 if (atomic_read(&fs_info->balance_running)) {
3563 atomic_inc(&fs_info->balance_pause_req);
3564 mutex_unlock(&fs_info->balance_mutex);
3565
3566 wait_event(fs_info->balance_wait_q,
3567 atomic_read(&fs_info->balance_running) == 0);
3568
3569 mutex_lock(&fs_info->balance_mutex);
3570 /* we are good with balance_ctl ripped off from under us */
3571 BUG_ON(atomic_read(&fs_info->balance_running));
3572 atomic_dec(&fs_info->balance_pause_req);
3573 } else {
3574 ret = -ENOTCONN;
3575 }
3576
3577 mutex_unlock(&fs_info->balance_mutex);
3578 return ret;
3579}
3580
3581int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
3582{
3583 if (fs_info->sb->s_flags & MS_RDONLY)
3584 return -EROFS;
3585
3586 mutex_lock(&fs_info->balance_mutex);
3587 if (!fs_info->balance_ctl) {
3588 mutex_unlock(&fs_info->balance_mutex);
3589 return -ENOTCONN;
3590 }
3591
3592 atomic_inc(&fs_info->balance_cancel_req);
3593 /*
3594 * if we are running just wait and return, balance item is
3595 * deleted in btrfs_balance in this case
3596 */
3597 if (atomic_read(&fs_info->balance_running)) {
3598 mutex_unlock(&fs_info->balance_mutex);
3599 wait_event(fs_info->balance_wait_q,
3600 atomic_read(&fs_info->balance_running) == 0);
3601 mutex_lock(&fs_info->balance_mutex);
3602 } else {
3603 /* __cancel_balance needs volume_mutex */
3604 mutex_unlock(&fs_info->balance_mutex);
3605 mutex_lock(&fs_info->volume_mutex);
3606 mutex_lock(&fs_info->balance_mutex);
3607
3608 if (fs_info->balance_ctl)
3609 __cancel_balance(fs_info);
3610
3611 mutex_unlock(&fs_info->volume_mutex);
3612 }
3613
3614 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
3615 atomic_dec(&fs_info->balance_cancel_req);
3616 mutex_unlock(&fs_info->balance_mutex);
3617 return 0;
3618}
3619
3620static int btrfs_uuid_scan_kthread(void *data)
3621{
3622 struct btrfs_fs_info *fs_info = data;
3623 struct btrfs_root *root = fs_info->tree_root;
3624 struct btrfs_key key;
3625 struct btrfs_key max_key;
3626 struct btrfs_path *path = NULL;
3627 int ret = 0;
3628 struct extent_buffer *eb;
3629 int slot;
3630 struct btrfs_root_item root_item;
3631 u32 item_size;
3632 struct btrfs_trans_handle *trans = NULL;
3633
3634 path = btrfs_alloc_path();
3635 if (!path) {
3636 ret = -ENOMEM;
3637 goto out;
3638 }
3639
3640 key.objectid = 0;
3641 key.type = BTRFS_ROOT_ITEM_KEY;
3642 key.offset = 0;
3643
3644 max_key.objectid = (u64)-1;
3645 max_key.type = BTRFS_ROOT_ITEM_KEY;
3646 max_key.offset = (u64)-1;
3647
3648 path->keep_locks = 1;
3649
3650 while (1) {
3651 ret = btrfs_search_forward(root, &key, path, 0);
3652 if (ret) {
3653 if (ret > 0)
3654 ret = 0;
3655 break;
3656 }
3657
3658 if (key.type != BTRFS_ROOT_ITEM_KEY ||
3659 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
3660 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
3661 key.objectid > BTRFS_LAST_FREE_OBJECTID)
3662 goto skip;
3663
3664 eb = path->nodes[0];
3665 slot = path->slots[0];
3666 item_size = btrfs_item_size_nr(eb, slot);
3667 if (item_size < sizeof(root_item))
3668 goto skip;
3669
3670 read_extent_buffer(eb, &root_item,
3671 btrfs_item_ptr_offset(eb, slot),
3672 (int)sizeof(root_item));
3673 if (btrfs_root_refs(&root_item) == 0)
3674 goto skip;
3675
3676 if (!btrfs_is_empty_uuid(root_item.uuid) ||
3677 !btrfs_is_empty_uuid(root_item.received_uuid)) {
3678 if (trans)
3679 goto update_tree;
3680
3681 btrfs_release_path(path);
3682 /*
3683 * 1 - subvol uuid item
3684 * 1 - received_subvol uuid item
3685 */
3686 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
3687 if (IS_ERR(trans)) {
3688 ret = PTR_ERR(trans);
3689 break;
3690 }
3691 continue;
3692 } else {
3693 goto skip;
3694 }
3695update_tree:
3696 if (!btrfs_is_empty_uuid(root_item.uuid)) {
3697 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
3698 root_item.uuid,
3699 BTRFS_UUID_KEY_SUBVOL,
3700 key.objectid);
3701 if (ret < 0) {
3702 btrfs_warn(fs_info, "uuid_tree_add failed %d",
3703 ret);
3704 break;
3705 }
3706 }
3707
3708 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
3709 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
3710 root_item.received_uuid,
3711 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
3712 key.objectid);
3713 if (ret < 0) {
3714 btrfs_warn(fs_info, "uuid_tree_add failed %d",
3715 ret);
3716 break;
3717 }
3718 }
3719
3720skip:
3721 if (trans) {
3722 ret = btrfs_end_transaction(trans, fs_info->uuid_root);
3723 trans = NULL;
3724 if (ret)
3725 break;
3726 }
3727
3728 btrfs_release_path(path);
3729 if (key.offset < (u64)-1) {
3730 key.offset++;
3731 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
3732 key.offset = 0;
3733 key.type = BTRFS_ROOT_ITEM_KEY;
3734 } else if (key.objectid < (u64)-1) {
3735 key.offset = 0;
3736 key.type = BTRFS_ROOT_ITEM_KEY;
3737 key.objectid++;
3738 } else {
3739 break;
3740 }
3741 cond_resched();
3742 }
3743
3744out:
3745 btrfs_free_path(path);
3746 if (trans && !IS_ERR(trans))
3747 btrfs_end_transaction(trans, fs_info->uuid_root);
3748 if (ret)
3749 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
3750 else
3751 fs_info->update_uuid_tree_gen = 1;
3752 up(&fs_info->uuid_tree_rescan_sem);
3753 return 0;
3754}
3755
3756/*
3757 * Callback for btrfs_uuid_tree_iterate().
3758 * returns:
3759 * 0 check succeeded, the entry is not outdated.
3760 * < 0 if an error occured.
3761 * > 0 if the check failed, which means the caller shall remove the entry.
3762 */
3763static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
3764 u8 *uuid, u8 type, u64 subid)
3765{
3766 struct btrfs_key key;
3767 int ret = 0;
3768 struct btrfs_root *subvol_root;
3769
3770 if (type != BTRFS_UUID_KEY_SUBVOL &&
3771 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
3772 goto out;
3773
3774 key.objectid = subid;
3775 key.type = BTRFS_ROOT_ITEM_KEY;
3776 key.offset = (u64)-1;
3777 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
3778 if (IS_ERR(subvol_root)) {
3779 ret = PTR_ERR(subvol_root);
3780 if (ret == -ENOENT)
3781 ret = 1;
3782 goto out;
3783 }
3784
3785 switch (type) {
3786 case BTRFS_UUID_KEY_SUBVOL:
3787 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
3788 ret = 1;
3789 break;
3790 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
3791 if (memcmp(uuid, subvol_root->root_item.received_uuid,
3792 BTRFS_UUID_SIZE))
3793 ret = 1;
3794 break;
3795 }
3796
3797out:
3798 return ret;
3799}
3800
3801static int btrfs_uuid_rescan_kthread(void *data)
3802{
3803 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
3804 int ret;
3805
3806 /*
3807 * 1st step is to iterate through the existing UUID tree and
3808 * to delete all entries that contain outdated data.
3809 * 2nd step is to add all missing entries to the UUID tree.
3810 */
3811 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
3812 if (ret < 0) {
3813 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
3814 up(&fs_info->uuid_tree_rescan_sem);
3815 return ret;
3816 }
3817 return btrfs_uuid_scan_kthread(data);
3818}
3819
3820int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
3821{
3822 struct btrfs_trans_handle *trans;
3823 struct btrfs_root *tree_root = fs_info->tree_root;
3824 struct btrfs_root *uuid_root;
3825 struct task_struct *task;
3826 int ret;
3827
3828 /*
3829 * 1 - root node
3830 * 1 - root item
3831 */
3832 trans = btrfs_start_transaction(tree_root, 2);
3833 if (IS_ERR(trans))
3834 return PTR_ERR(trans);
3835
3836 uuid_root = btrfs_create_tree(trans, fs_info,
3837 BTRFS_UUID_TREE_OBJECTID);
3838 if (IS_ERR(uuid_root)) {
3839 btrfs_abort_transaction(trans, tree_root,
3840 PTR_ERR(uuid_root));
3841 return PTR_ERR(uuid_root);
3842 }
3843
3844 fs_info->uuid_root = uuid_root;
3845
3846 ret = btrfs_commit_transaction(trans, tree_root);
3847 if (ret)
3848 return ret;
3849
3850 down(&fs_info->uuid_tree_rescan_sem);
3851 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
3852 if (IS_ERR(task)) {
3853 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
3854 btrfs_warn(fs_info, "failed to start uuid_scan task");
3855 up(&fs_info->uuid_tree_rescan_sem);
3856 return PTR_ERR(task);
3857 }
3858
3859 return 0;
3860}
3861
3862int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
3863{
3864 struct task_struct *task;
3865
3866 down(&fs_info->uuid_tree_rescan_sem);
3867 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
3868 if (IS_ERR(task)) {
3869 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
3870 btrfs_warn(fs_info, "failed to start uuid_rescan task");
3871 up(&fs_info->uuid_tree_rescan_sem);
3872 return PTR_ERR(task);
3873 }
3874
3875 return 0;
3876}
3877
3878/*
3879 * shrinking a device means finding all of the device extents past
3880 * the new size, and then following the back refs to the chunks.
3881 * The chunk relocation code actually frees the device extent
3882 */
3883int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
3884{
3885 struct btrfs_trans_handle *trans;
3886 struct btrfs_root *root = device->dev_root;
3887 struct btrfs_dev_extent *dev_extent = NULL;
3888 struct btrfs_path *path;
3889 u64 length;
3890 u64 chunk_tree;
3891 u64 chunk_objectid;
3892 u64 chunk_offset;
3893 int ret;
3894 int slot;
3895 int failed = 0;
3896 bool retried = false;
3897 struct extent_buffer *l;
3898 struct btrfs_key key;
3899 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
3900 u64 old_total = btrfs_super_total_bytes(super_copy);
3901 u64 old_size = device->total_bytes;
3902 u64 diff = device->total_bytes - new_size;
3903
3904 if (device->is_tgtdev_for_dev_replace)
3905 return -EINVAL;
3906
3907 path = btrfs_alloc_path();
3908 if (!path)
3909 return -ENOMEM;
3910
3911 path->reada = 2;
3912
3913 lock_chunks(root);
3914
3915 device->total_bytes = new_size;
3916 if (device->writeable) {
3917 device->fs_devices->total_rw_bytes -= diff;
3918 spin_lock(&root->fs_info->free_chunk_lock);
3919 root->fs_info->free_chunk_space -= diff;
3920 spin_unlock(&root->fs_info->free_chunk_lock);
3921 }
3922 unlock_chunks(root);
3923
3924again:
3925 key.objectid = device->devid;
3926 key.offset = (u64)-1;
3927 key.type = BTRFS_DEV_EXTENT_KEY;
3928
3929 do {
3930 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3931 if (ret < 0)
3932 goto done;
3933
3934 ret = btrfs_previous_item(root, path, 0, key.type);
3935 if (ret < 0)
3936 goto done;
3937 if (ret) {
3938 ret = 0;
3939 btrfs_release_path(path);
3940 break;
3941 }
3942
3943 l = path->nodes[0];
3944 slot = path->slots[0];
3945 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
3946
3947 if (key.objectid != device->devid) {
3948 btrfs_release_path(path);
3949 break;
3950 }
3951
3952 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
3953 length = btrfs_dev_extent_length(l, dev_extent);
3954
3955 if (key.offset + length <= new_size) {
3956 btrfs_release_path(path);
3957 break;
3958 }
3959
3960 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
3961 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
3962 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
3963 btrfs_release_path(path);
3964
3965 ret = btrfs_relocate_chunk(root, chunk_tree, chunk_objectid,
3966 chunk_offset);
3967 if (ret && ret != -ENOSPC)
3968 goto done;
3969 if (ret == -ENOSPC)
3970 failed++;
3971 } while (key.offset-- > 0);
3972
3973 if (failed && !retried) {
3974 failed = 0;
3975 retried = true;
3976 goto again;
3977 } else if (failed && retried) {
3978 ret = -ENOSPC;
3979 lock_chunks(root);
3980
3981 device->total_bytes = old_size;
3982 if (device->writeable)
3983 device->fs_devices->total_rw_bytes += diff;
3984 spin_lock(&root->fs_info->free_chunk_lock);
3985 root->fs_info->free_chunk_space += diff;
3986 spin_unlock(&root->fs_info->free_chunk_lock);
3987 unlock_chunks(root);
3988 goto done;
3989 }
3990
3991 /* Shrinking succeeded, else we would be at "done". */
3992 trans = btrfs_start_transaction(root, 0);
3993 if (IS_ERR(trans)) {
3994 ret = PTR_ERR(trans);
3995 goto done;
3996 }
3997
3998 lock_chunks(root);
3999
4000 device->disk_total_bytes = new_size;
4001 /* Now btrfs_update_device() will change the on-disk size. */
4002 ret = btrfs_update_device(trans, device);
4003 if (ret) {
4004 unlock_chunks(root);
4005 btrfs_end_transaction(trans, root);
4006 goto done;
4007 }
4008 WARN_ON(diff > old_total);
4009 btrfs_set_super_total_bytes(super_copy, old_total - diff);
4010 unlock_chunks(root);
4011 btrfs_end_transaction(trans, root);
4012done:
4013 btrfs_free_path(path);
4014 return ret;
4015}
4016
4017static int btrfs_add_system_chunk(struct btrfs_root *root,
4018 struct btrfs_key *key,
4019 struct btrfs_chunk *chunk, int item_size)
4020{
4021 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
4022 struct btrfs_disk_key disk_key;
4023 u32 array_size;
4024 u8 *ptr;
4025
4026 array_size = btrfs_super_sys_array_size(super_copy);
4027 if (array_size + item_size + sizeof(disk_key)
4028 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
4029 return -EFBIG;
4030
4031 ptr = super_copy->sys_chunk_array + array_size;
4032 btrfs_cpu_key_to_disk(&disk_key, key);
4033 memcpy(ptr, &disk_key, sizeof(disk_key));
4034 ptr += sizeof(disk_key);
4035 memcpy(ptr, chunk, item_size);
4036 item_size += sizeof(disk_key);
4037 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4038 return 0;
4039}
4040
4041/*
4042 * sort the devices in descending order by max_avail, total_avail
4043 */
4044static int btrfs_cmp_device_info(const void *a, const void *b)
4045{
4046 const struct btrfs_device_info *di_a = a;
4047 const struct btrfs_device_info *di_b = b;
4048
4049 if (di_a->max_avail > di_b->max_avail)
4050 return -1;
4051 if (di_a->max_avail < di_b->max_avail)
4052 return 1;
4053 if (di_a->total_avail > di_b->total_avail)
4054 return -1;
4055 if (di_a->total_avail < di_b->total_avail)
4056 return 1;
4057 return 0;
4058}
4059
4060static struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
4061 [BTRFS_RAID_RAID10] = {
4062 .sub_stripes = 2,
4063 .dev_stripes = 1,
4064 .devs_max = 0, /* 0 == as many as possible */
4065 .devs_min = 4,
4066 .devs_increment = 2,
4067 .ncopies = 2,
4068 },
4069 [BTRFS_RAID_RAID1] = {
4070 .sub_stripes = 1,
4071 .dev_stripes = 1,
4072 .devs_max = 2,
4073 .devs_min = 2,
4074 .devs_increment = 2,
4075 .ncopies = 2,
4076 },
4077 [BTRFS_RAID_DUP] = {
4078 .sub_stripes = 1,
4079 .dev_stripes = 2,
4080 .devs_max = 1,
4081 .devs_min = 1,
4082 .devs_increment = 1,
4083 .ncopies = 2,
4084 },
4085 [BTRFS_RAID_RAID0] = {
4086 .sub_stripes = 1,
4087 .dev_stripes = 1,
4088 .devs_max = 0,
4089 .devs_min = 2,
4090 .devs_increment = 1,
4091 .ncopies = 1,
4092 },
4093 [BTRFS_RAID_SINGLE] = {
4094 .sub_stripes = 1,
4095 .dev_stripes = 1,
4096 .devs_max = 1,
4097 .devs_min = 1,
4098 .devs_increment = 1,
4099 .ncopies = 1,
4100 },
4101 [BTRFS_RAID_RAID5] = {
4102 .sub_stripes = 1,
4103 .dev_stripes = 1,
4104 .devs_max = 0,
4105 .devs_min = 2,
4106 .devs_increment = 1,
4107 .ncopies = 2,
4108 },
4109 [BTRFS_RAID_RAID6] = {
4110 .sub_stripes = 1,
4111 .dev_stripes = 1,
4112 .devs_max = 0,
4113 .devs_min = 3,
4114 .devs_increment = 1,
4115 .ncopies = 3,
4116 },
4117};
4118
4119static u32 find_raid56_stripe_len(u32 data_devices, u32 dev_stripe_target)
4120{
4121 /* TODO allow them to set a preferred stripe size */
4122 return 64 * 1024;
4123}
4124
4125static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4126{
4127 if (!(type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)))
4128 return;
4129
4130 btrfs_set_fs_incompat(info, RAID56);
4131}
4132
4133#define BTRFS_MAX_DEVS(r) ((BTRFS_LEAF_DATA_SIZE(r) \
4134 - sizeof(struct btrfs_item) \
4135 - sizeof(struct btrfs_chunk)) \
4136 / sizeof(struct btrfs_stripe) + 1)
4137
4138#define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4139 - 2 * sizeof(struct btrfs_disk_key) \
4140 - 2 * sizeof(struct btrfs_chunk)) \
4141 / sizeof(struct btrfs_stripe) + 1)
4142
4143static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4144 struct btrfs_root *extent_root, u64 start,
4145 u64 type)
4146{
4147 struct btrfs_fs_info *info = extent_root->fs_info;
4148 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4149 struct list_head *cur;
4150 struct map_lookup *map = NULL;
4151 struct extent_map_tree *em_tree;
4152 struct extent_map *em;
4153 struct btrfs_device_info *devices_info = NULL;
4154 u64 total_avail;
4155 int num_stripes; /* total number of stripes to allocate */
4156 int data_stripes; /* number of stripes that count for
4157 block group size */
4158 int sub_stripes; /* sub_stripes info for map */
4159 int dev_stripes; /* stripes per dev */
4160 int devs_max; /* max devs to use */
4161 int devs_min; /* min devs needed */
4162 int devs_increment; /* ndevs has to be a multiple of this */
4163 int ncopies; /* how many copies to data has */
4164 int ret;
4165 u64 max_stripe_size;
4166 u64 max_chunk_size;
4167 u64 stripe_size;
4168 u64 num_bytes;
4169 u64 raid_stripe_len = BTRFS_STRIPE_LEN;
4170 int ndevs;
4171 int i;
4172 int j;
4173 int index;
4174
4175 BUG_ON(!alloc_profile_is_valid(type, 0));
4176
4177 if (list_empty(&fs_devices->alloc_list))
4178 return -ENOSPC;
4179
4180 index = __get_raid_index(type);
4181
4182 sub_stripes = btrfs_raid_array[index].sub_stripes;
4183 dev_stripes = btrfs_raid_array[index].dev_stripes;
4184 devs_max = btrfs_raid_array[index].devs_max;
4185 devs_min = btrfs_raid_array[index].devs_min;
4186 devs_increment = btrfs_raid_array[index].devs_increment;
4187 ncopies = btrfs_raid_array[index].ncopies;
4188
4189 if (type & BTRFS_BLOCK_GROUP_DATA) {
4190 max_stripe_size = 1024 * 1024 * 1024;
4191 max_chunk_size = 10 * max_stripe_size;
4192 if (!devs_max)
4193 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4194 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4195 /* for larger filesystems, use larger metadata chunks */
4196 if (fs_devices->total_rw_bytes > 50ULL * 1024 * 1024 * 1024)
4197 max_stripe_size = 1024 * 1024 * 1024;
4198 else
4199 max_stripe_size = 256 * 1024 * 1024;
4200 max_chunk_size = max_stripe_size;
4201 if (!devs_max)
4202 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4203 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4204 max_stripe_size = 32 * 1024 * 1024;
4205 max_chunk_size = 2 * max_stripe_size;
4206 if (!devs_max)
4207 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4208 } else {
4209 btrfs_err(info, "invalid chunk type 0x%llx requested",
4210 type);
4211 BUG_ON(1);
4212 }
4213
4214 /* we don't want a chunk larger than 10% of writeable space */
4215 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4216 max_chunk_size);
4217
4218 devices_info = kzalloc(sizeof(*devices_info) * fs_devices->rw_devices,
4219 GFP_NOFS);
4220 if (!devices_info)
4221 return -ENOMEM;
4222
4223 cur = fs_devices->alloc_list.next;
4224
4225 /*
4226 * in the first pass through the devices list, we gather information
4227 * about the available holes on each device.
4228 */
4229 ndevs = 0;
4230 while (cur != &fs_devices->alloc_list) {
4231 struct btrfs_device *device;
4232 u64 max_avail;
4233 u64 dev_offset;
4234
4235 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
4236
4237 cur = cur->next;
4238
4239 if (!device->writeable) {
4240 WARN(1, KERN_ERR
4241 "BTRFS: read-only device in alloc_list\n");
4242 continue;
4243 }
4244
4245 if (!device->in_fs_metadata ||
4246 device->is_tgtdev_for_dev_replace)
4247 continue;
4248
4249 if (device->total_bytes > device->bytes_used)
4250 total_avail = device->total_bytes - device->bytes_used;
4251 else
4252 total_avail = 0;
4253
4254 /* If there is no space on this device, skip it. */
4255 if (total_avail == 0)
4256 continue;
4257
4258 ret = find_free_dev_extent(trans, device,
4259 max_stripe_size * dev_stripes,
4260 &dev_offset, &max_avail);
4261 if (ret && ret != -ENOSPC)
4262 goto error;
4263
4264 if (ret == 0)
4265 max_avail = max_stripe_size * dev_stripes;
4266
4267 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
4268 continue;
4269
4270 if (ndevs == fs_devices->rw_devices) {
4271 WARN(1, "%s: found more than %llu devices\n",
4272 __func__, fs_devices->rw_devices);
4273 break;
4274 }
4275 devices_info[ndevs].dev_offset = dev_offset;
4276 devices_info[ndevs].max_avail = max_avail;
4277 devices_info[ndevs].total_avail = total_avail;
4278 devices_info[ndevs].dev = device;
4279 ++ndevs;
4280 }
4281
4282 /*
4283 * now sort the devices by hole size / available space
4284 */
4285 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4286 btrfs_cmp_device_info, NULL);
4287
4288 /* round down to number of usable stripes */
4289 ndevs -= ndevs % devs_increment;
4290
4291 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
4292 ret = -ENOSPC;
4293 goto error;
4294 }
4295
4296 if (devs_max && ndevs > devs_max)
4297 ndevs = devs_max;
4298 /*
4299 * the primary goal is to maximize the number of stripes, so use as many
4300 * devices as possible, even if the stripes are not maximum sized.
4301 */
4302 stripe_size = devices_info[ndevs-1].max_avail;
4303 num_stripes = ndevs * dev_stripes;
4304
4305 /*
4306 * this will have to be fixed for RAID1 and RAID10 over
4307 * more drives
4308 */
4309 data_stripes = num_stripes / ncopies;
4310
4311 if (type & BTRFS_BLOCK_GROUP_RAID5) {
4312 raid_stripe_len = find_raid56_stripe_len(ndevs - 1,
4313 btrfs_super_stripesize(info->super_copy));
4314 data_stripes = num_stripes - 1;
4315 }
4316 if (type & BTRFS_BLOCK_GROUP_RAID6) {
4317 raid_stripe_len = find_raid56_stripe_len(ndevs - 2,
4318 btrfs_super_stripesize(info->super_copy));
4319 data_stripes = num_stripes - 2;
4320 }
4321
4322 /*
4323 * Use the number of data stripes to figure out how big this chunk
4324 * is really going to be in terms of logical address space,
4325 * and compare that answer with the max chunk size
4326 */
4327 if (stripe_size * data_stripes > max_chunk_size) {
4328 u64 mask = (1ULL << 24) - 1;
4329 stripe_size = max_chunk_size;
4330 do_div(stripe_size, data_stripes);
4331
4332 /* bump the answer up to a 16MB boundary */
4333 stripe_size = (stripe_size + mask) & ~mask;
4334
4335 /* but don't go higher than the limits we found
4336 * while searching for free extents
4337 */
4338 if (stripe_size > devices_info[ndevs-1].max_avail)
4339 stripe_size = devices_info[ndevs-1].max_avail;
4340 }
4341
4342 do_div(stripe_size, dev_stripes);
4343
4344 /* align to BTRFS_STRIPE_LEN */
4345 do_div(stripe_size, raid_stripe_len);
4346 stripe_size *= raid_stripe_len;
4347
4348 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4349 if (!map) {
4350 ret = -ENOMEM;
4351 goto error;
4352 }
4353 map->num_stripes = num_stripes;
4354
4355 for (i = 0; i < ndevs; ++i) {
4356 for (j = 0; j < dev_stripes; ++j) {
4357 int s = i * dev_stripes + j;
4358 map->stripes[s].dev = devices_info[i].dev;
4359 map->stripes[s].physical = devices_info[i].dev_offset +
4360 j * stripe_size;
4361 }
4362 }
4363 map->sector_size = extent_root->sectorsize;
4364 map->stripe_len = raid_stripe_len;
4365 map->io_align = raid_stripe_len;
4366 map->io_width = raid_stripe_len;
4367 map->type = type;
4368 map->sub_stripes = sub_stripes;
4369
4370 num_bytes = stripe_size * data_stripes;
4371
4372 trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
4373
4374 em = alloc_extent_map();
4375 if (!em) {
4376 kfree(map);
4377 ret = -ENOMEM;
4378 goto error;
4379 }
4380 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4381 em->bdev = (struct block_device *)map;
4382 em->start = start;
4383 em->len = num_bytes;
4384 em->block_start = 0;
4385 em->block_len = em->len;
4386 em->orig_block_len = stripe_size;
4387
4388 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4389 write_lock(&em_tree->lock);
4390 ret = add_extent_mapping(em_tree, em, 0);
4391 if (!ret) {
4392 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4393 atomic_inc(&em->refs);
4394 }
4395 write_unlock(&em_tree->lock);
4396 if (ret) {
4397 free_extent_map(em);
4398 goto error;
4399 }
4400
4401 ret = btrfs_make_block_group(trans, extent_root, 0, type,
4402 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4403 start, num_bytes);
4404 if (ret)
4405 goto error_del_extent;
4406
4407 free_extent_map(em);
4408 check_raid56_incompat_flag(extent_root->fs_info, type);
4409
4410 kfree(devices_info);
4411 return 0;
4412
4413error_del_extent:
4414 write_lock(&em_tree->lock);
4415 remove_extent_mapping(em_tree, em);
4416 write_unlock(&em_tree->lock);
4417
4418 /* One for our allocation */
4419 free_extent_map(em);
4420 /* One for the tree reference */
4421 free_extent_map(em);
4422error:
4423 kfree(devices_info);
4424 return ret;
4425}
4426
4427int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4428 struct btrfs_root *extent_root,
4429 u64 chunk_offset, u64 chunk_size)
4430{
4431 struct btrfs_key key;
4432 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
4433 struct btrfs_device *device;
4434 struct btrfs_chunk *chunk;
4435 struct btrfs_stripe *stripe;
4436 struct extent_map_tree *em_tree;
4437 struct extent_map *em;
4438 struct map_lookup *map;
4439 size_t item_size;
4440 u64 dev_offset;
4441 u64 stripe_size;
4442 int i = 0;
4443 int ret;
4444
4445 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4446 read_lock(&em_tree->lock);
4447 em = lookup_extent_mapping(em_tree, chunk_offset, chunk_size);
4448 read_unlock(&em_tree->lock);
4449
4450 if (!em) {
4451 btrfs_crit(extent_root->fs_info, "unable to find logical "
4452 "%Lu len %Lu", chunk_offset, chunk_size);
4453 return -EINVAL;
4454 }
4455
4456 if (em->start != chunk_offset || em->len != chunk_size) {
4457 btrfs_crit(extent_root->fs_info, "found a bad mapping, wanted"
4458 " %Lu-%Lu, found %Lu-%Lu", chunk_offset,
4459 chunk_size, em->start, em->len);
4460 free_extent_map(em);
4461 return -EINVAL;
4462 }
4463
4464 map = (struct map_lookup *)em->bdev;
4465 item_size = btrfs_chunk_item_size(map->num_stripes);
4466 stripe_size = em->orig_block_len;
4467
4468 chunk = kzalloc(item_size, GFP_NOFS);
4469 if (!chunk) {
4470 ret = -ENOMEM;
4471 goto out;
4472 }
4473
4474 for (i = 0; i < map->num_stripes; i++) {
4475 device = map->stripes[i].dev;
4476 dev_offset = map->stripes[i].physical;
4477
4478 device->bytes_used += stripe_size;
4479 ret = btrfs_update_device(trans, device);
4480 if (ret)
4481 goto out;
4482 ret = btrfs_alloc_dev_extent(trans, device,
4483 chunk_root->root_key.objectid,
4484 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4485 chunk_offset, dev_offset,
4486 stripe_size);
4487 if (ret)
4488 goto out;
4489 }
4490
4491 spin_lock(&extent_root->fs_info->free_chunk_lock);
4492 extent_root->fs_info->free_chunk_space -= (stripe_size *
4493 map->num_stripes);
4494 spin_unlock(&extent_root->fs_info->free_chunk_lock);
4495
4496 stripe = &chunk->stripe;
4497 for (i = 0; i < map->num_stripes; i++) {
4498 device = map->stripes[i].dev;
4499 dev_offset = map->stripes[i].physical;
4500
4501 btrfs_set_stack_stripe_devid(stripe, device->devid);
4502 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4503 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4504 stripe++;
4505 }
4506
4507 btrfs_set_stack_chunk_length(chunk, chunk_size);
4508 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4509 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4510 btrfs_set_stack_chunk_type(chunk, map->type);
4511 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4512 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4513 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4514 btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
4515 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
4516
4517 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4518 key.type = BTRFS_CHUNK_ITEM_KEY;
4519 key.offset = chunk_offset;
4520
4521 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4522 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4523 /*
4524 * TODO: Cleanup of inserted chunk root in case of
4525 * failure.
4526 */
4527 ret = btrfs_add_system_chunk(chunk_root, &key, chunk,
4528 item_size);
4529 }
4530
4531out:
4532 kfree(chunk);
4533 free_extent_map(em);
4534 return ret;
4535}
4536
4537/*
4538 * Chunk allocation falls into two parts. The first part does works
4539 * that make the new allocated chunk useable, but not do any operation
4540 * that modifies the chunk tree. The second part does the works that
4541 * require modifying the chunk tree. This division is important for the
4542 * bootstrap process of adding storage to a seed btrfs.
4543 */
4544int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4545 struct btrfs_root *extent_root, u64 type)
4546{
4547 u64 chunk_offset;
4548
4549 chunk_offset = find_next_chunk(extent_root->fs_info);
4550 return __btrfs_alloc_chunk(trans, extent_root, chunk_offset, type);
4551}
4552
4553static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
4554 struct btrfs_root *root,
4555 struct btrfs_device *device)
4556{
4557 u64 chunk_offset;
4558 u64 sys_chunk_offset;
4559 u64 alloc_profile;
4560 struct btrfs_fs_info *fs_info = root->fs_info;
4561 struct btrfs_root *extent_root = fs_info->extent_root;
4562 int ret;
4563
4564 chunk_offset = find_next_chunk(fs_info);
4565 alloc_profile = btrfs_get_alloc_profile(extent_root, 0);
4566 ret = __btrfs_alloc_chunk(trans, extent_root, chunk_offset,
4567 alloc_profile);
4568 if (ret)
4569 return ret;
4570
4571 sys_chunk_offset = find_next_chunk(root->fs_info);
4572 alloc_profile = btrfs_get_alloc_profile(fs_info->chunk_root, 0);
4573 ret = __btrfs_alloc_chunk(trans, extent_root, sys_chunk_offset,
4574 alloc_profile);
4575 if (ret) {
4576 btrfs_abort_transaction(trans, root, ret);
4577 goto out;
4578 }
4579
4580 ret = btrfs_add_device(trans, fs_info->chunk_root, device);
4581 if (ret)
4582 btrfs_abort_transaction(trans, root, ret);
4583out:
4584 return ret;
4585}
4586
4587static inline int btrfs_chunk_max_errors(struct map_lookup *map)
4588{
4589 int max_errors;
4590
4591 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
4592 BTRFS_BLOCK_GROUP_RAID10 |
4593 BTRFS_BLOCK_GROUP_RAID5 |
4594 BTRFS_BLOCK_GROUP_DUP)) {
4595 max_errors = 1;
4596 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
4597 max_errors = 2;
4598 } else {
4599 max_errors = 0;
4600 }
4601
4602 return max_errors;
4603}
4604
4605int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
4606{
4607 struct extent_map *em;
4608 struct map_lookup *map;
4609 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4610 int readonly = 0;
4611 int miss_ndevs = 0;
4612 int i;
4613
4614 read_lock(&map_tree->map_tree.lock);
4615 em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
4616 read_unlock(&map_tree->map_tree.lock);
4617 if (!em)
4618 return 1;
4619
4620 map = (struct map_lookup *)em->bdev;
4621 for (i = 0; i < map->num_stripes; i++) {
4622 if (map->stripes[i].dev->missing) {
4623 miss_ndevs++;
4624 continue;
4625 }
4626
4627 if (!map->stripes[i].dev->writeable) {
4628 readonly = 1;
4629 goto end;
4630 }
4631 }
4632
4633 /*
4634 * If the number of missing devices is larger than max errors,
4635 * we can not write the data into that chunk successfully, so
4636 * set it readonly.
4637 */
4638 if (miss_ndevs > btrfs_chunk_max_errors(map))
4639 readonly = 1;
4640end:
4641 free_extent_map(em);
4642 return readonly;
4643}
4644
4645void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
4646{
4647 extent_map_tree_init(&tree->map_tree);
4648}
4649
4650void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
4651{
4652 struct extent_map *em;
4653
4654 while (1) {
4655 write_lock(&tree->map_tree.lock);
4656 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
4657 if (em)
4658 remove_extent_mapping(&tree->map_tree, em);
4659 write_unlock(&tree->map_tree.lock);
4660 if (!em)
4661 break;
4662 /* once for us */
4663 free_extent_map(em);
4664 /* once for the tree */
4665 free_extent_map(em);
4666 }
4667}
4668
4669int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
4670{
4671 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
4672 struct extent_map *em;
4673 struct map_lookup *map;
4674 struct extent_map_tree *em_tree = &map_tree->map_tree;
4675 int ret;
4676
4677 read_lock(&em_tree->lock);
4678 em = lookup_extent_mapping(em_tree, logical, len);
4679 read_unlock(&em_tree->lock);
4680
4681 /*
4682 * We could return errors for these cases, but that could get ugly and
4683 * we'd probably do the same thing which is just not do anything else
4684 * and exit, so return 1 so the callers don't try to use other copies.
4685 */
4686 if (!em) {
4687 btrfs_crit(fs_info, "No mapping for %Lu-%Lu", logical,
4688 logical+len);
4689 return 1;
4690 }
4691
4692 if (em->start > logical || em->start + em->len < logical) {
4693 btrfs_crit(fs_info, "Invalid mapping for %Lu-%Lu, got "
4694 "%Lu-%Lu", logical, logical+len, em->start,
4695 em->start + em->len);
4696 free_extent_map(em);
4697 return 1;
4698 }
4699
4700 map = (struct map_lookup *)em->bdev;
4701 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
4702 ret = map->num_stripes;
4703 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
4704 ret = map->sub_stripes;
4705 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
4706 ret = 2;
4707 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
4708 ret = 3;
4709 else
4710 ret = 1;
4711 free_extent_map(em);
4712
4713 btrfs_dev_replace_lock(&fs_info->dev_replace);
4714 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))
4715 ret++;
4716 btrfs_dev_replace_unlock(&fs_info->dev_replace);
4717
4718 return ret;
4719}
4720
4721unsigned long btrfs_full_stripe_len(struct btrfs_root *root,
4722 struct btrfs_mapping_tree *map_tree,
4723 u64 logical)
4724{
4725 struct extent_map *em;
4726 struct map_lookup *map;
4727 struct extent_map_tree *em_tree = &map_tree->map_tree;
4728 unsigned long len = root->sectorsize;
4729
4730 read_lock(&em_tree->lock);
4731 em = lookup_extent_mapping(em_tree, logical, len);
4732 read_unlock(&em_tree->lock);
4733 BUG_ON(!em);
4734
4735 BUG_ON(em->start > logical || em->start + em->len < logical);
4736 map = (struct map_lookup *)em->bdev;
4737 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4738 BTRFS_BLOCK_GROUP_RAID6)) {
4739 len = map->stripe_len * nr_data_stripes(map);
4740 }
4741 free_extent_map(em);
4742 return len;
4743}
4744
4745int btrfs_is_parity_mirror(struct btrfs_mapping_tree *map_tree,
4746 u64 logical, u64 len, int mirror_num)
4747{
4748 struct extent_map *em;
4749 struct map_lookup *map;
4750 struct extent_map_tree *em_tree = &map_tree->map_tree;
4751 int ret = 0;
4752
4753 read_lock(&em_tree->lock);
4754 em = lookup_extent_mapping(em_tree, logical, len);
4755 read_unlock(&em_tree->lock);
4756 BUG_ON(!em);
4757
4758 BUG_ON(em->start > logical || em->start + em->len < logical);
4759 map = (struct map_lookup *)em->bdev;
4760 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4761 BTRFS_BLOCK_GROUP_RAID6))
4762 ret = 1;
4763 free_extent_map(em);
4764 return ret;
4765}
4766
4767static int find_live_mirror(struct btrfs_fs_info *fs_info,
4768 struct map_lookup *map, int first, int num,
4769 int optimal, int dev_replace_is_ongoing)
4770{
4771 int i;
4772 int tolerance;
4773 struct btrfs_device *srcdev;
4774
4775 if (dev_replace_is_ongoing &&
4776 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
4777 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
4778 srcdev = fs_info->dev_replace.srcdev;
4779 else
4780 srcdev = NULL;
4781
4782 /*
4783 * try to avoid the drive that is the source drive for a
4784 * dev-replace procedure, only choose it if no other non-missing
4785 * mirror is available
4786 */
4787 for (tolerance = 0; tolerance < 2; tolerance++) {
4788 if (map->stripes[optimal].dev->bdev &&
4789 (tolerance || map->stripes[optimal].dev != srcdev))
4790 return optimal;
4791 for (i = first; i < first + num; i++) {
4792 if (map->stripes[i].dev->bdev &&
4793 (tolerance || map->stripes[i].dev != srcdev))
4794 return i;
4795 }
4796 }
4797
4798 /* we couldn't find one that doesn't fail. Just return something
4799 * and the io error handling code will clean up eventually
4800 */
4801 return optimal;
4802}
4803
4804static inline int parity_smaller(u64 a, u64 b)
4805{
4806 return a > b;
4807}
4808
4809/* Bubble-sort the stripe set to put the parity/syndrome stripes last */
4810static void sort_parity_stripes(struct btrfs_bio *bbio, u64 *raid_map)
4811{
4812 struct btrfs_bio_stripe s;
4813 int i;
4814 u64 l;
4815 int again = 1;
4816
4817 while (again) {
4818 again = 0;
4819 for (i = 0; i < bbio->num_stripes - 1; i++) {
4820 if (parity_smaller(raid_map[i], raid_map[i+1])) {
4821 s = bbio->stripes[i];
4822 l = raid_map[i];
4823 bbio->stripes[i] = bbio->stripes[i+1];
4824 raid_map[i] = raid_map[i+1];
4825 bbio->stripes[i+1] = s;
4826 raid_map[i+1] = l;
4827 again = 1;
4828 }
4829 }
4830 }
4831}
4832
4833static int __btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
4834 u64 logical, u64 *length,
4835 struct btrfs_bio **bbio_ret,
4836 int mirror_num, u64 **raid_map_ret)
4837{
4838 struct extent_map *em;
4839 struct map_lookup *map;
4840 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
4841 struct extent_map_tree *em_tree = &map_tree->map_tree;
4842 u64 offset;
4843 u64 stripe_offset;
4844 u64 stripe_end_offset;
4845 u64 stripe_nr;
4846 u64 stripe_nr_orig;
4847 u64 stripe_nr_end;
4848 u64 stripe_len;
4849 u64 *raid_map = NULL;
4850 int stripe_index;
4851 int i;
4852 int ret = 0;
4853 int num_stripes;
4854 int max_errors = 0;
4855 struct btrfs_bio *bbio = NULL;
4856 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
4857 int dev_replace_is_ongoing = 0;
4858 int num_alloc_stripes;
4859 int patch_the_first_stripe_for_dev_replace = 0;
4860 u64 physical_to_patch_in_first_stripe = 0;
4861 u64 raid56_full_stripe_start = (u64)-1;
4862
4863 read_lock(&em_tree->lock);
4864 em = lookup_extent_mapping(em_tree, logical, *length);
4865 read_unlock(&em_tree->lock);
4866
4867 if (!em) {
4868 btrfs_crit(fs_info, "unable to find logical %llu len %llu",
4869 logical, *length);
4870 return -EINVAL;
4871 }
4872
4873 if (em->start > logical || em->start + em->len < logical) {
4874 btrfs_crit(fs_info, "found a bad mapping, wanted %Lu, "
4875 "found %Lu-%Lu", logical, em->start,
4876 em->start + em->len);
4877 free_extent_map(em);
4878 return -EINVAL;
4879 }
4880
4881 map = (struct map_lookup *)em->bdev;
4882 offset = logical - em->start;
4883
4884 stripe_len = map->stripe_len;
4885 stripe_nr = offset;
4886 /*
4887 * stripe_nr counts the total number of stripes we have to stride
4888 * to get to this block
4889 */
4890 do_div(stripe_nr, stripe_len);
4891
4892 stripe_offset = stripe_nr * stripe_len;
4893 BUG_ON(offset < stripe_offset);
4894
4895 /* stripe_offset is the offset of this block in its stripe*/
4896 stripe_offset = offset - stripe_offset;
4897
4898 /* if we're here for raid56, we need to know the stripe aligned start */
4899 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
4900 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
4901 raid56_full_stripe_start = offset;
4902
4903 /* allow a write of a full stripe, but make sure we don't
4904 * allow straddling of stripes
4905 */
4906 do_div(raid56_full_stripe_start, full_stripe_len);
4907 raid56_full_stripe_start *= full_stripe_len;
4908 }
4909
4910 if (rw & REQ_DISCARD) {
4911 /* we don't discard raid56 yet */
4912 if (map->type &
4913 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
4914 ret = -EOPNOTSUPP;
4915 goto out;
4916 }
4917 *length = min_t(u64, em->len - offset, *length);
4918 } else if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
4919 u64 max_len;
4920 /* For writes to RAID[56], allow a full stripeset across all disks.
4921 For other RAID types and for RAID[56] reads, just allow a single
4922 stripe (on a single disk). */
4923 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6) &&
4924 (rw & REQ_WRITE)) {
4925 max_len = stripe_len * nr_data_stripes(map) -
4926 (offset - raid56_full_stripe_start);
4927 } else {
4928 /* we limit the length of each bio to what fits in a stripe */
4929 max_len = stripe_len - stripe_offset;
4930 }
4931 *length = min_t(u64, em->len - offset, max_len);
4932 } else {
4933 *length = em->len - offset;
4934 }
4935
4936 /* This is for when we're called from btrfs_merge_bio_hook() and all
4937 it cares about is the length */
4938 if (!bbio_ret)
4939 goto out;
4940
4941 btrfs_dev_replace_lock(dev_replace);
4942 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
4943 if (!dev_replace_is_ongoing)
4944 btrfs_dev_replace_unlock(dev_replace);
4945
4946 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
4947 !(rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) &&
4948 dev_replace->tgtdev != NULL) {
4949 /*
4950 * in dev-replace case, for repair case (that's the only
4951 * case where the mirror is selected explicitly when
4952 * calling btrfs_map_block), blocks left of the left cursor
4953 * can also be read from the target drive.
4954 * For REQ_GET_READ_MIRRORS, the target drive is added as
4955 * the last one to the array of stripes. For READ, it also
4956 * needs to be supported using the same mirror number.
4957 * If the requested block is not left of the left cursor,
4958 * EIO is returned. This can happen because btrfs_num_copies()
4959 * returns one more in the dev-replace case.
4960 */
4961 u64 tmp_length = *length;
4962 struct btrfs_bio *tmp_bbio = NULL;
4963 int tmp_num_stripes;
4964 u64 srcdev_devid = dev_replace->srcdev->devid;
4965 int index_srcdev = 0;
4966 int found = 0;
4967 u64 physical_of_found = 0;
4968
4969 ret = __btrfs_map_block(fs_info, REQ_GET_READ_MIRRORS,
4970 logical, &tmp_length, &tmp_bbio, 0, NULL);
4971 if (ret) {
4972 WARN_ON(tmp_bbio != NULL);
4973 goto out;
4974 }
4975
4976 tmp_num_stripes = tmp_bbio->num_stripes;
4977 if (mirror_num > tmp_num_stripes) {
4978 /*
4979 * REQ_GET_READ_MIRRORS does not contain this
4980 * mirror, that means that the requested area
4981 * is not left of the left cursor
4982 */
4983 ret = -EIO;
4984 kfree(tmp_bbio);
4985 goto out;
4986 }
4987
4988 /*
4989 * process the rest of the function using the mirror_num
4990 * of the source drive. Therefore look it up first.
4991 * At the end, patch the device pointer to the one of the
4992 * target drive.
4993 */
4994 for (i = 0; i < tmp_num_stripes; i++) {
4995 if (tmp_bbio->stripes[i].dev->devid == srcdev_devid) {
4996 /*
4997 * In case of DUP, in order to keep it
4998 * simple, only add the mirror with the
4999 * lowest physical address
5000 */
5001 if (found &&
5002 physical_of_found <=
5003 tmp_bbio->stripes[i].physical)
5004 continue;
5005 index_srcdev = i;
5006 found = 1;
5007 physical_of_found =
5008 tmp_bbio->stripes[i].physical;
5009 }
5010 }
5011
5012 if (found) {
5013 mirror_num = index_srcdev + 1;
5014 patch_the_first_stripe_for_dev_replace = 1;
5015 physical_to_patch_in_first_stripe = physical_of_found;
5016 } else {
5017 WARN_ON(1);
5018 ret = -EIO;
5019 kfree(tmp_bbio);
5020 goto out;
5021 }
5022
5023 kfree(tmp_bbio);
5024 } else if (mirror_num > map->num_stripes) {
5025 mirror_num = 0;
5026 }
5027
5028 num_stripes = 1;
5029 stripe_index = 0;
5030 stripe_nr_orig = stripe_nr;
5031 stripe_nr_end = ALIGN(offset + *length, map->stripe_len);
5032 do_div(stripe_nr_end, map->stripe_len);
5033 stripe_end_offset = stripe_nr_end * map->stripe_len -
5034 (offset + *length);
5035
5036 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5037 if (rw & REQ_DISCARD)
5038 num_stripes = min_t(u64, map->num_stripes,
5039 stripe_nr_end - stripe_nr_orig);
5040 stripe_index = do_div(stripe_nr, map->num_stripes);
5041 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5042 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS))
5043 num_stripes = map->num_stripes;
5044 else if (mirror_num)
5045 stripe_index = mirror_num - 1;
5046 else {
5047 stripe_index = find_live_mirror(fs_info, map, 0,
5048 map->num_stripes,
5049 current->pid % map->num_stripes,
5050 dev_replace_is_ongoing);
5051 mirror_num = stripe_index + 1;
5052 }
5053
5054 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5055 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) {
5056 num_stripes = map->num_stripes;
5057 } else if (mirror_num) {
5058 stripe_index = mirror_num - 1;
5059 } else {
5060 mirror_num = 1;
5061 }
5062
5063 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5064 int factor = map->num_stripes / map->sub_stripes;
5065
5066 stripe_index = do_div(stripe_nr, factor);
5067 stripe_index *= map->sub_stripes;
5068
5069 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
5070 num_stripes = map->sub_stripes;
5071 else if (rw & REQ_DISCARD)
5072 num_stripes = min_t(u64, map->sub_stripes *
5073 (stripe_nr_end - stripe_nr_orig),
5074 map->num_stripes);
5075 else if (mirror_num)
5076 stripe_index += mirror_num - 1;
5077 else {
5078 int old_stripe_index = stripe_index;
5079 stripe_index = find_live_mirror(fs_info, map,
5080 stripe_index,
5081 map->sub_stripes, stripe_index +
5082 current->pid % map->sub_stripes,
5083 dev_replace_is_ongoing);
5084 mirror_num = stripe_index - old_stripe_index + 1;
5085 }
5086
5087 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
5088 BTRFS_BLOCK_GROUP_RAID6)) {
5089 u64 tmp;
5090
5091 if (bbio_ret && ((rw & REQ_WRITE) || mirror_num > 1)
5092 && raid_map_ret) {
5093 int i, rot;
5094
5095 /* push stripe_nr back to the start of the full stripe */
5096 stripe_nr = raid56_full_stripe_start;
5097 do_div(stripe_nr, stripe_len);
5098
5099 stripe_index = do_div(stripe_nr, nr_data_stripes(map));
5100
5101 /* RAID[56] write or recovery. Return all stripes */
5102 num_stripes = map->num_stripes;
5103 max_errors = nr_parity_stripes(map);
5104
5105 raid_map = kmalloc_array(num_stripes, sizeof(u64),
5106 GFP_NOFS);
5107 if (!raid_map) {
5108 ret = -ENOMEM;
5109 goto out;
5110 }
5111
5112 /* Work out the disk rotation on this stripe-set */
5113 tmp = stripe_nr;
5114 rot = do_div(tmp, num_stripes);
5115
5116 /* Fill in the logical address of each stripe */
5117 tmp = stripe_nr * nr_data_stripes(map);
5118 for (i = 0; i < nr_data_stripes(map); i++)
5119 raid_map[(i+rot) % num_stripes] =
5120 em->start + (tmp + i) * map->stripe_len;
5121
5122 raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5123 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5124 raid_map[(i+rot+1) % num_stripes] =
5125 RAID6_Q_STRIPE;
5126
5127 *length = map->stripe_len;
5128 stripe_index = 0;
5129 stripe_offset = 0;
5130 } else {
5131 /*
5132 * Mirror #0 or #1 means the original data block.
5133 * Mirror #2 is RAID5 parity block.
5134 * Mirror #3 is RAID6 Q block.
5135 */
5136 stripe_index = do_div(stripe_nr, nr_data_stripes(map));
5137 if (mirror_num > 1)
5138 stripe_index = nr_data_stripes(map) +
5139 mirror_num - 2;
5140
5141 /* We distribute the parity blocks across stripes */
5142 tmp = stripe_nr + stripe_index;
5143 stripe_index = do_div(tmp, map->num_stripes);
5144 }
5145 } else {
5146 /*
5147 * after this do_div call, stripe_nr is the number of stripes
5148 * on this device we have to walk to find the data, and
5149 * stripe_index is the number of our device in the stripe array
5150 */
5151 stripe_index = do_div(stripe_nr, map->num_stripes);
5152 mirror_num = stripe_index + 1;
5153 }
5154 BUG_ON(stripe_index >= map->num_stripes);
5155
5156 num_alloc_stripes = num_stripes;
5157 if (dev_replace_is_ongoing) {
5158 if (rw & (REQ_WRITE | REQ_DISCARD))
5159 num_alloc_stripes <<= 1;
5160 if (rw & REQ_GET_READ_MIRRORS)
5161 num_alloc_stripes++;
5162 }
5163 bbio = kzalloc(btrfs_bio_size(num_alloc_stripes), GFP_NOFS);
5164 if (!bbio) {
5165 kfree(raid_map);
5166 ret = -ENOMEM;
5167 goto out;
5168 }
5169 atomic_set(&bbio->error, 0);
5170
5171 if (rw & REQ_DISCARD) {
5172 int factor = 0;
5173 int sub_stripes = 0;
5174 u64 stripes_per_dev = 0;
5175 u32 remaining_stripes = 0;
5176 u32 last_stripe = 0;
5177
5178 if (map->type &
5179 (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
5180 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5181 sub_stripes = 1;
5182 else
5183 sub_stripes = map->sub_stripes;
5184
5185 factor = map->num_stripes / sub_stripes;
5186 stripes_per_dev = div_u64_rem(stripe_nr_end -
5187 stripe_nr_orig,
5188 factor,
5189 &remaining_stripes);
5190 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5191 last_stripe *= sub_stripes;
5192 }
5193
5194 for (i = 0; i < num_stripes; i++) {
5195 bbio->stripes[i].physical =
5196 map->stripes[stripe_index].physical +
5197 stripe_offset + stripe_nr * map->stripe_len;
5198 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5199
5200 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5201 BTRFS_BLOCK_GROUP_RAID10)) {
5202 bbio->stripes[i].length = stripes_per_dev *
5203 map->stripe_len;
5204
5205 if (i / sub_stripes < remaining_stripes)
5206 bbio->stripes[i].length +=
5207 map->stripe_len;
5208
5209 /*
5210 * Special for the first stripe and
5211 * the last stripe:
5212 *
5213 * |-------|...|-------|
5214 * |----------|
5215 * off end_off
5216 */
5217 if (i < sub_stripes)
5218 bbio->stripes[i].length -=
5219 stripe_offset;
5220
5221 if (stripe_index >= last_stripe &&
5222 stripe_index <= (last_stripe +
5223 sub_stripes - 1))
5224 bbio->stripes[i].length -=
5225 stripe_end_offset;
5226
5227 if (i == sub_stripes - 1)
5228 stripe_offset = 0;
5229 } else
5230 bbio->stripes[i].length = *length;
5231
5232 stripe_index++;
5233 if (stripe_index == map->num_stripes) {
5234 /* This could only happen for RAID0/10 */
5235 stripe_index = 0;
5236 stripe_nr++;
5237 }
5238 }
5239 } else {
5240 for (i = 0; i < num_stripes; i++) {
5241 bbio->stripes[i].physical =
5242 map->stripes[stripe_index].physical +
5243 stripe_offset +
5244 stripe_nr * map->stripe_len;
5245 bbio->stripes[i].dev =
5246 map->stripes[stripe_index].dev;
5247 stripe_index++;
5248 }
5249 }
5250
5251 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
5252 max_errors = btrfs_chunk_max_errors(map);
5253
5254 if (dev_replace_is_ongoing && (rw & (REQ_WRITE | REQ_DISCARD)) &&
5255 dev_replace->tgtdev != NULL) {
5256 int index_where_to_add;
5257 u64 srcdev_devid = dev_replace->srcdev->devid;
5258
5259 /*
5260 * duplicate the write operations while the dev replace
5261 * procedure is running. Since the copying of the old disk
5262 * to the new disk takes place at run time while the
5263 * filesystem is mounted writable, the regular write
5264 * operations to the old disk have to be duplicated to go
5265 * to the new disk as well.
5266 * Note that device->missing is handled by the caller, and
5267 * that the write to the old disk is already set up in the
5268 * stripes array.
5269 */
5270 index_where_to_add = num_stripes;
5271 for (i = 0; i < num_stripes; i++) {
5272 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5273 /* write to new disk, too */
5274 struct btrfs_bio_stripe *new =
5275 bbio->stripes + index_where_to_add;
5276 struct btrfs_bio_stripe *old =
5277 bbio->stripes + i;
5278
5279 new->physical = old->physical;
5280 new->length = old->length;
5281 new->dev = dev_replace->tgtdev;
5282 index_where_to_add++;
5283 max_errors++;
5284 }
5285 }
5286 num_stripes = index_where_to_add;
5287 } else if (dev_replace_is_ongoing && (rw & REQ_GET_READ_MIRRORS) &&
5288 dev_replace->tgtdev != NULL) {
5289 u64 srcdev_devid = dev_replace->srcdev->devid;
5290 int index_srcdev = 0;
5291 int found = 0;
5292 u64 physical_of_found = 0;
5293
5294 /*
5295 * During the dev-replace procedure, the target drive can
5296 * also be used to read data in case it is needed to repair
5297 * a corrupt block elsewhere. This is possible if the
5298 * requested area is left of the left cursor. In this area,
5299 * the target drive is a full copy of the source drive.
5300 */
5301 for (i = 0; i < num_stripes; i++) {
5302 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5303 /*
5304 * In case of DUP, in order to keep it
5305 * simple, only add the mirror with the
5306 * lowest physical address
5307 */
5308 if (found &&
5309 physical_of_found <=
5310 bbio->stripes[i].physical)
5311 continue;
5312 index_srcdev = i;
5313 found = 1;
5314 physical_of_found = bbio->stripes[i].physical;
5315 }
5316 }
5317 if (found) {
5318 u64 length = map->stripe_len;
5319
5320 if (physical_of_found + length <=
5321 dev_replace->cursor_left) {
5322 struct btrfs_bio_stripe *tgtdev_stripe =
5323 bbio->stripes + num_stripes;
5324
5325 tgtdev_stripe->physical = physical_of_found;
5326 tgtdev_stripe->length =
5327 bbio->stripes[index_srcdev].length;
5328 tgtdev_stripe->dev = dev_replace->tgtdev;
5329
5330 num_stripes++;
5331 }
5332 }
5333 }
5334
5335 *bbio_ret = bbio;
5336 bbio->num_stripes = num_stripes;
5337 bbio->max_errors = max_errors;
5338 bbio->mirror_num = mirror_num;
5339
5340 /*
5341 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5342 * mirror_num == num_stripes + 1 && dev_replace target drive is
5343 * available as a mirror
5344 */
5345 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5346 WARN_ON(num_stripes > 1);
5347 bbio->stripes[0].dev = dev_replace->tgtdev;
5348 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5349 bbio->mirror_num = map->num_stripes + 1;
5350 }
5351 if (raid_map) {
5352 sort_parity_stripes(bbio, raid_map);
5353 *raid_map_ret = raid_map;
5354 }
5355out:
5356 if (dev_replace_is_ongoing)
5357 btrfs_dev_replace_unlock(dev_replace);
5358 free_extent_map(em);
5359 return ret;
5360}
5361
5362int btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
5363 u64 logical, u64 *length,
5364 struct btrfs_bio **bbio_ret, int mirror_num)
5365{
5366 return __btrfs_map_block(fs_info, rw, logical, length, bbio_ret,
5367 mirror_num, NULL);
5368}
5369
5370int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
5371 u64 chunk_start, u64 physical, u64 devid,
5372 u64 **logical, int *naddrs, int *stripe_len)
5373{
5374 struct extent_map_tree *em_tree = &map_tree->map_tree;
5375 struct extent_map *em;
5376 struct map_lookup *map;
5377 u64 *buf;
5378 u64 bytenr;
5379 u64 length;
5380 u64 stripe_nr;
5381 u64 rmap_len;
5382 int i, j, nr = 0;
5383
5384 read_lock(&em_tree->lock);
5385 em = lookup_extent_mapping(em_tree, chunk_start, 1);
5386 read_unlock(&em_tree->lock);
5387
5388 if (!em) {
5389 printk(KERN_ERR "BTRFS: couldn't find em for chunk %Lu\n",
5390 chunk_start);
5391 return -EIO;
5392 }
5393
5394 if (em->start != chunk_start) {
5395 printk(KERN_ERR "BTRFS: bad chunk start, em=%Lu, wanted=%Lu\n",
5396 em->start, chunk_start);
5397 free_extent_map(em);
5398 return -EIO;
5399 }
5400 map = (struct map_lookup *)em->bdev;
5401
5402 length = em->len;
5403 rmap_len = map->stripe_len;
5404
5405 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5406 do_div(length, map->num_stripes / map->sub_stripes);
5407 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5408 do_div(length, map->num_stripes);
5409 else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
5410 BTRFS_BLOCK_GROUP_RAID6)) {
5411 do_div(length, nr_data_stripes(map));
5412 rmap_len = map->stripe_len * nr_data_stripes(map);
5413 }
5414
5415 buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
5416 BUG_ON(!buf); /* -ENOMEM */
5417
5418 for (i = 0; i < map->num_stripes; i++) {
5419 if (devid && map->stripes[i].dev->devid != devid)
5420 continue;
5421 if (map->stripes[i].physical > physical ||
5422 map->stripes[i].physical + length <= physical)
5423 continue;
5424
5425 stripe_nr = physical - map->stripes[i].physical;
5426 do_div(stripe_nr, map->stripe_len);
5427
5428 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5429 stripe_nr = stripe_nr * map->num_stripes + i;
5430 do_div(stripe_nr, map->sub_stripes);
5431 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5432 stripe_nr = stripe_nr * map->num_stripes + i;
5433 } /* else if RAID[56], multiply by nr_data_stripes().
5434 * Alternatively, just use rmap_len below instead of
5435 * map->stripe_len */
5436
5437 bytenr = chunk_start + stripe_nr * rmap_len;
5438 WARN_ON(nr >= map->num_stripes);
5439 for (j = 0; j < nr; j++) {
5440 if (buf[j] == bytenr)
5441 break;
5442 }
5443 if (j == nr) {
5444 WARN_ON(nr >= map->num_stripes);
5445 buf[nr++] = bytenr;
5446 }
5447 }
5448
5449 *logical = buf;
5450 *naddrs = nr;
5451 *stripe_len = rmap_len;
5452
5453 free_extent_map(em);
5454 return 0;
5455}
5456
5457static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio, int err)
5458{
5459 if (likely(bbio->flags & BTRFS_BIO_ORIG_BIO_SUBMITTED))
5460 bio_endio_nodec(bio, err);
5461 else
5462 bio_endio(bio, err);
5463 kfree(bbio);
5464}
5465
5466static void btrfs_end_bio(struct bio *bio, int err)
5467{
5468 struct btrfs_bio *bbio = bio->bi_private;
5469 struct btrfs_device *dev = bbio->stripes[0].dev;
5470 int is_orig_bio = 0;
5471
5472 if (err) {
5473 atomic_inc(&bbio->error);
5474 if (err == -EIO || err == -EREMOTEIO) {
5475 unsigned int stripe_index =
5476 btrfs_io_bio(bio)->stripe_index;
5477
5478 BUG_ON(stripe_index >= bbio->num_stripes);
5479 dev = bbio->stripes[stripe_index].dev;
5480 if (dev->bdev) {
5481 if (bio->bi_rw & WRITE)
5482 btrfs_dev_stat_inc(dev,
5483 BTRFS_DEV_STAT_WRITE_ERRS);
5484 else
5485 btrfs_dev_stat_inc(dev,
5486 BTRFS_DEV_STAT_READ_ERRS);
5487 if ((bio->bi_rw & WRITE_FLUSH) == WRITE_FLUSH)
5488 btrfs_dev_stat_inc(dev,
5489 BTRFS_DEV_STAT_FLUSH_ERRS);
5490 btrfs_dev_stat_print_on_error(dev);
5491 }
5492 }
5493 }
5494
5495 if (bio == bbio->orig_bio)
5496 is_orig_bio = 1;
5497
5498 btrfs_bio_counter_dec(bbio->fs_info);
5499
5500 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5501 if (!is_orig_bio) {
5502 bio_put(bio);
5503 bio = bbio->orig_bio;
5504 }
5505
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 /* only send an error to the higher layers if it is
5510 * beyond the tolerance of the btrfs bio
5511 */
5512 if (atomic_read(&bbio->error) > bbio->max_errors) {
5513 err = -EIO;
5514 } else {
5515 /*
5516 * this bio is actually up to date, we didn't
5517 * go over the max number of errors
5518 */
5519 set_bit(BIO_UPTODATE, &bio->bi_flags);
5520 err = 0;
5521 }
5522
5523 btrfs_end_bbio(bbio, bio, err);
5524 } else if (!is_orig_bio) {
5525 bio_put(bio);
5526 }
5527}
5528
5529/*
5530 * see run_scheduled_bios for a description of why bios are collected for
5531 * async submit.
5532 *
5533 * This will add one bio to the pending list for a device and make sure
5534 * the work struct is scheduled.
5535 */
5536static noinline void btrfs_schedule_bio(struct btrfs_root *root,
5537 struct btrfs_device *device,
5538 int rw, struct bio *bio)
5539{
5540 int should_queue = 1;
5541 struct btrfs_pending_bios *pending_bios;
5542
5543 if (device->missing || !device->bdev) {
5544 bio_endio(bio, -EIO);
5545 return;
5546 }
5547
5548 /* don't bother with additional async steps for reads, right now */
5549 if (!(rw & REQ_WRITE)) {
5550 bio_get(bio);
5551 btrfsic_submit_bio(rw, bio);
5552 bio_put(bio);
5553 return;
5554 }
5555
5556 /*
5557 * nr_async_bios allows us to reliably return congestion to the
5558 * higher layers. Otherwise, the async bio makes it appear we have
5559 * made progress against dirty pages when we've really just put it
5560 * on a queue for later
5561 */
5562 atomic_inc(&root->fs_info->nr_async_bios);
5563 WARN_ON(bio->bi_next);
5564 bio->bi_next = NULL;
5565 bio->bi_rw |= rw;
5566
5567 spin_lock(&device->io_lock);
5568 if (bio->bi_rw & REQ_SYNC)
5569 pending_bios = &device->pending_sync_bios;
5570 else
5571 pending_bios = &device->pending_bios;
5572
5573 if (pending_bios->tail)
5574 pending_bios->tail->bi_next = bio;
5575
5576 pending_bios->tail = bio;
5577 if (!pending_bios->head)
5578 pending_bios->head = bio;
5579 if (device->running_pending)
5580 should_queue = 0;
5581
5582 spin_unlock(&device->io_lock);
5583
5584 if (should_queue)
5585 btrfs_queue_work(root->fs_info->submit_workers,
5586 &device->work);
5587}
5588
5589static int bio_size_ok(struct block_device *bdev, struct bio *bio,
5590 sector_t sector)
5591{
5592 struct bio_vec *prev;
5593 struct request_queue *q = bdev_get_queue(bdev);
5594 unsigned int max_sectors = queue_max_sectors(q);
5595 struct bvec_merge_data bvm = {
5596 .bi_bdev = bdev,
5597 .bi_sector = sector,
5598 .bi_rw = bio->bi_rw,
5599 };
5600
5601 if (WARN_ON(bio->bi_vcnt == 0))
5602 return 1;
5603
5604 prev = &bio->bi_io_vec[bio->bi_vcnt - 1];
5605 if (bio_sectors(bio) > max_sectors)
5606 return 0;
5607
5608 if (!q->merge_bvec_fn)
5609 return 1;
5610
5611 bvm.bi_size = bio->bi_iter.bi_size - prev->bv_len;
5612 if (q->merge_bvec_fn(q, &bvm, prev) < prev->bv_len)
5613 return 0;
5614 return 1;
5615}
5616
5617static void submit_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5618 struct bio *bio, u64 physical, int dev_nr,
5619 int rw, int async)
5620{
5621 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
5622
5623 bio->bi_private = bbio;
5624 btrfs_io_bio(bio)->stripe_index = dev_nr;
5625 bio->bi_end_io = btrfs_end_bio;
5626 bio->bi_iter.bi_sector = physical >> 9;
5627#ifdef DEBUG
5628 {
5629 struct rcu_string *name;
5630
5631 rcu_read_lock();
5632 name = rcu_dereference(dev->name);
5633 pr_debug("btrfs_map_bio: rw %d, sector=%llu, dev=%lu "
5634 "(%s id %llu), size=%u\n", rw,
5635 (u64)bio->bi_sector, (u_long)dev->bdev->bd_dev,
5636 name->str, dev->devid, bio->bi_size);
5637 rcu_read_unlock();
5638 }
5639#endif
5640 bio->bi_bdev = dev->bdev;
5641
5642 btrfs_bio_counter_inc_noblocked(root->fs_info);
5643
5644 if (async)
5645 btrfs_schedule_bio(root, dev, rw, bio);
5646 else
5647 btrfsic_submit_bio(rw, bio);
5648}
5649
5650static int breakup_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5651 struct bio *first_bio, struct btrfs_device *dev,
5652 int dev_nr, int rw, int async)
5653{
5654 struct bio_vec *bvec = first_bio->bi_io_vec;
5655 struct bio *bio;
5656 int nr_vecs = bio_get_nr_vecs(dev->bdev);
5657 u64 physical = bbio->stripes[dev_nr].physical;
5658
5659again:
5660 bio = btrfs_bio_alloc(dev->bdev, physical >> 9, nr_vecs, GFP_NOFS);
5661 if (!bio)
5662 return -ENOMEM;
5663
5664 while (bvec <= (first_bio->bi_io_vec + first_bio->bi_vcnt - 1)) {
5665 if (bio_add_page(bio, bvec->bv_page, bvec->bv_len,
5666 bvec->bv_offset) < bvec->bv_len) {
5667 u64 len = bio->bi_iter.bi_size;
5668
5669 atomic_inc(&bbio->stripes_pending);
5670 submit_stripe_bio(root, bbio, bio, physical, dev_nr,
5671 rw, async);
5672 physical += len;
5673 goto again;
5674 }
5675 bvec++;
5676 }
5677
5678 submit_stripe_bio(root, bbio, bio, physical, dev_nr, rw, async);
5679 return 0;
5680}
5681
5682static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
5683{
5684 atomic_inc(&bbio->error);
5685 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5686 /* Shoud be the original bio. */
5687 WARN_ON(bio != bbio->orig_bio);
5688
5689 bio->bi_private = bbio->private;
5690 bio->bi_end_io = bbio->end_io;
5691 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5692 bio->bi_iter.bi_sector = logical >> 9;
5693
5694 btrfs_end_bbio(bbio, bio, -EIO);
5695 }
5696}
5697
5698int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
5699 int mirror_num, int async_submit)
5700{
5701 struct btrfs_device *dev;
5702 struct bio *first_bio = bio;
5703 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
5704 u64 length = 0;
5705 u64 map_length;
5706 u64 *raid_map = NULL;
5707 int ret;
5708 int dev_nr = 0;
5709 int total_devs = 1;
5710 struct btrfs_bio *bbio = NULL;
5711
5712 length = bio->bi_iter.bi_size;
5713 map_length = length;
5714
5715 btrfs_bio_counter_inc_blocked(root->fs_info);
5716 ret = __btrfs_map_block(root->fs_info, rw, logical, &map_length, &bbio,
5717 mirror_num, &raid_map);
5718 if (ret) {
5719 btrfs_bio_counter_dec(root->fs_info);
5720 return ret;
5721 }
5722
5723 total_devs = bbio->num_stripes;
5724 bbio->orig_bio = first_bio;
5725 bbio->private = first_bio->bi_private;
5726 bbio->end_io = first_bio->bi_end_io;
5727 bbio->fs_info = root->fs_info;
5728 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
5729
5730 if (raid_map) {
5731 /* In this case, map_length has been set to the length of
5732 a single stripe; not the whole write */
5733 if (rw & WRITE) {
5734 ret = raid56_parity_write(root, bio, bbio,
5735 raid_map, map_length);
5736 } else {
5737 ret = raid56_parity_recover(root, bio, bbio,
5738 raid_map, map_length,
5739 mirror_num);
5740 }
5741 /*
5742 * FIXME, replace dosen't support raid56 yet, please fix
5743 * it in the future.
5744 */
5745 btrfs_bio_counter_dec(root->fs_info);
5746 return ret;
5747 }
5748
5749 if (map_length < length) {
5750 btrfs_crit(root->fs_info, "mapping failed logical %llu bio len %llu len %llu",
5751 logical, length, map_length);
5752 BUG();
5753 }
5754
5755 while (dev_nr < total_devs) {
5756 dev = bbio->stripes[dev_nr].dev;
5757 if (!dev || !dev->bdev || (rw & WRITE && !dev->writeable)) {
5758 bbio_error(bbio, first_bio, logical);
5759 dev_nr++;
5760 continue;
5761 }
5762
5763 /*
5764 * Check and see if we're ok with this bio based on it's size
5765 * and offset with the given device.
5766 */
5767 if (!bio_size_ok(dev->bdev, first_bio,
5768 bbio->stripes[dev_nr].physical >> 9)) {
5769 ret = breakup_stripe_bio(root, bbio, first_bio, dev,
5770 dev_nr, rw, async_submit);
5771 BUG_ON(ret);
5772 dev_nr++;
5773 continue;
5774 }
5775
5776 if (dev_nr < total_devs - 1) {
5777 bio = btrfs_bio_clone(first_bio, GFP_NOFS);
5778 BUG_ON(!bio); /* -ENOMEM */
5779 } else {
5780 bio = first_bio;
5781 bbio->flags |= BTRFS_BIO_ORIG_BIO_SUBMITTED;
5782 }
5783
5784 submit_stripe_bio(root, bbio, bio,
5785 bbio->stripes[dev_nr].physical, dev_nr, rw,
5786 async_submit);
5787 dev_nr++;
5788 }
5789 btrfs_bio_counter_dec(root->fs_info);
5790 return 0;
5791}
5792
5793struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
5794 u8 *uuid, u8 *fsid)
5795{
5796 struct btrfs_device *device;
5797 struct btrfs_fs_devices *cur_devices;
5798
5799 cur_devices = fs_info->fs_devices;
5800 while (cur_devices) {
5801 if (!fsid ||
5802 !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
5803 device = __find_device(&cur_devices->devices,
5804 devid, uuid);
5805 if (device)
5806 return device;
5807 }
5808 cur_devices = cur_devices->seed;
5809 }
5810 return NULL;
5811}
5812
5813static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
5814 u64 devid, u8 *dev_uuid)
5815{
5816 struct btrfs_device *device;
5817 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
5818
5819 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
5820 if (IS_ERR(device))
5821 return NULL;
5822
5823 list_add(&device->dev_list, &fs_devices->devices);
5824 device->fs_devices = fs_devices;
5825 fs_devices->num_devices++;
5826
5827 device->missing = 1;
5828 fs_devices->missing_devices++;
5829
5830 return device;
5831}
5832
5833/**
5834 * btrfs_alloc_device - allocate struct btrfs_device
5835 * @fs_info: used only for generating a new devid, can be NULL if
5836 * devid is provided (i.e. @devid != NULL).
5837 * @devid: a pointer to devid for this device. If NULL a new devid
5838 * is generated.
5839 * @uuid: a pointer to UUID for this device. If NULL a new UUID
5840 * is generated.
5841 *
5842 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
5843 * on error. Returned struct is not linked onto any lists and can be
5844 * destroyed with kfree() right away.
5845 */
5846struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
5847 const u64 *devid,
5848 const u8 *uuid)
5849{
5850 struct btrfs_device *dev;
5851 u64 tmp;
5852
5853 if (WARN_ON(!devid && !fs_info))
5854 return ERR_PTR(-EINVAL);
5855
5856 dev = __alloc_device();
5857 if (IS_ERR(dev))
5858 return dev;
5859
5860 if (devid)
5861 tmp = *devid;
5862 else {
5863 int ret;
5864
5865 ret = find_next_devid(fs_info, &tmp);
5866 if (ret) {
5867 kfree(dev);
5868 return ERR_PTR(ret);
5869 }
5870 }
5871 dev->devid = tmp;
5872
5873 if (uuid)
5874 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
5875 else
5876 generate_random_uuid(dev->uuid);
5877
5878 btrfs_init_work(&dev->work, btrfs_submit_helper,
5879 pending_bios_fn, NULL, NULL);
5880
5881 return dev;
5882}
5883
5884static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
5885 struct extent_buffer *leaf,
5886 struct btrfs_chunk *chunk)
5887{
5888 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
5889 struct map_lookup *map;
5890 struct extent_map *em;
5891 u64 logical;
5892 u64 length;
5893 u64 devid;
5894 u8 uuid[BTRFS_UUID_SIZE];
5895 int num_stripes;
5896 int ret;
5897 int i;
5898
5899 logical = key->offset;
5900 length = btrfs_chunk_length(leaf, chunk);
5901
5902 read_lock(&map_tree->map_tree.lock);
5903 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
5904 read_unlock(&map_tree->map_tree.lock);
5905
5906 /* already mapped? */
5907 if (em && em->start <= logical && em->start + em->len > logical) {
5908 free_extent_map(em);
5909 return 0;
5910 } else if (em) {
5911 free_extent_map(em);
5912 }
5913
5914 em = alloc_extent_map();
5915 if (!em)
5916 return -ENOMEM;
5917 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
5918 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
5919 if (!map) {
5920 free_extent_map(em);
5921 return -ENOMEM;
5922 }
5923
5924 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5925 em->bdev = (struct block_device *)map;
5926 em->start = logical;
5927 em->len = length;
5928 em->orig_start = 0;
5929 em->block_start = 0;
5930 em->block_len = em->len;
5931
5932 map->num_stripes = num_stripes;
5933 map->io_width = btrfs_chunk_io_width(leaf, chunk);
5934 map->io_align = btrfs_chunk_io_align(leaf, chunk);
5935 map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
5936 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
5937 map->type = btrfs_chunk_type(leaf, chunk);
5938 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
5939 for (i = 0; i < num_stripes; i++) {
5940 map->stripes[i].physical =
5941 btrfs_stripe_offset_nr(leaf, chunk, i);
5942 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
5943 read_extent_buffer(leaf, uuid, (unsigned long)
5944 btrfs_stripe_dev_uuid_nr(chunk, i),
5945 BTRFS_UUID_SIZE);
5946 map->stripes[i].dev = btrfs_find_device(root->fs_info, devid,
5947 uuid, NULL);
5948 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
5949 free_extent_map(em);
5950 return -EIO;
5951 }
5952 if (!map->stripes[i].dev) {
5953 map->stripes[i].dev =
5954 add_missing_dev(root, devid, uuid);
5955 if (!map->stripes[i].dev) {
5956 free_extent_map(em);
5957 return -EIO;
5958 }
5959 }
5960 map->stripes[i].dev->in_fs_metadata = 1;
5961 }
5962
5963 write_lock(&map_tree->map_tree.lock);
5964 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
5965 write_unlock(&map_tree->map_tree.lock);
5966 BUG_ON(ret); /* Tree corruption */
5967 free_extent_map(em);
5968
5969 return 0;
5970}
5971
5972static void fill_device_from_item(struct extent_buffer *leaf,
5973 struct btrfs_dev_item *dev_item,
5974 struct btrfs_device *device)
5975{
5976 unsigned long ptr;
5977
5978 device->devid = btrfs_device_id(leaf, dev_item);
5979 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
5980 device->total_bytes = device->disk_total_bytes;
5981 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
5982 device->type = btrfs_device_type(leaf, dev_item);
5983 device->io_align = btrfs_device_io_align(leaf, dev_item);
5984 device->io_width = btrfs_device_io_width(leaf, dev_item);
5985 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
5986 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
5987 device->is_tgtdev_for_dev_replace = 0;
5988
5989 ptr = btrfs_device_uuid(dev_item);
5990 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
5991}
5992
5993static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
5994{
5995 struct btrfs_fs_devices *fs_devices;
5996 int ret;
5997
5998 BUG_ON(!mutex_is_locked(&uuid_mutex));
5999
6000 fs_devices = root->fs_info->fs_devices->seed;
6001 while (fs_devices) {
6002 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
6003 ret = 0;
6004 goto out;
6005 }
6006 fs_devices = fs_devices->seed;
6007 }
6008
6009 fs_devices = find_fsid(fsid);
6010 if (!fs_devices) {
6011 ret = -ENOENT;
6012 goto out;
6013 }
6014
6015 fs_devices = clone_fs_devices(fs_devices);
6016 if (IS_ERR(fs_devices)) {
6017 ret = PTR_ERR(fs_devices);
6018 goto out;
6019 }
6020
6021 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
6022 root->fs_info->bdev_holder);
6023 if (ret) {
6024 free_fs_devices(fs_devices);
6025 goto out;
6026 }
6027
6028 if (!fs_devices->seeding) {
6029 __btrfs_close_devices(fs_devices);
6030 free_fs_devices(fs_devices);
6031 ret = -EINVAL;
6032 goto out;
6033 }
6034
6035 fs_devices->seed = root->fs_info->fs_devices->seed;
6036 root->fs_info->fs_devices->seed = fs_devices;
6037out:
6038 return ret;
6039}
6040
6041static int read_one_dev(struct btrfs_root *root,
6042 struct extent_buffer *leaf,
6043 struct btrfs_dev_item *dev_item)
6044{
6045 struct btrfs_device *device;
6046 u64 devid;
6047 int ret;
6048 u8 fs_uuid[BTRFS_UUID_SIZE];
6049 u8 dev_uuid[BTRFS_UUID_SIZE];
6050
6051 devid = btrfs_device_id(leaf, dev_item);
6052 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6053 BTRFS_UUID_SIZE);
6054 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6055 BTRFS_UUID_SIZE);
6056
6057 if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
6058 ret = open_seed_devices(root, fs_uuid);
6059 if (ret && !btrfs_test_opt(root, DEGRADED))
6060 return ret;
6061 }
6062
6063 device = btrfs_find_device(root->fs_info, devid, dev_uuid, fs_uuid);
6064 if (!device || !device->bdev) {
6065 if (!btrfs_test_opt(root, DEGRADED))
6066 return -EIO;
6067
6068 if (!device) {
6069 btrfs_warn(root->fs_info, "devid %llu missing", devid);
6070 device = add_missing_dev(root, devid, dev_uuid);
6071 if (!device)
6072 return -ENOMEM;
6073 } else if (!device->missing) {
6074 /*
6075 * this happens when a device that was properly setup
6076 * in the device info lists suddenly goes bad.
6077 * device->bdev is NULL, and so we have to set
6078 * device->missing to one here
6079 */
6080 root->fs_info->fs_devices->missing_devices++;
6081 device->missing = 1;
6082 }
6083 }
6084
6085 if (device->fs_devices != root->fs_info->fs_devices) {
6086 BUG_ON(device->writeable);
6087 if (device->generation !=
6088 btrfs_device_generation(leaf, dev_item))
6089 return -EINVAL;
6090 }
6091
6092 fill_device_from_item(leaf, dev_item, device);
6093 device->in_fs_metadata = 1;
6094 if (device->writeable && !device->is_tgtdev_for_dev_replace) {
6095 device->fs_devices->total_rw_bytes += device->total_bytes;
6096 spin_lock(&root->fs_info->free_chunk_lock);
6097 root->fs_info->free_chunk_space += device->total_bytes -
6098 device->bytes_used;
6099 spin_unlock(&root->fs_info->free_chunk_lock);
6100 }
6101 ret = 0;
6102 return ret;
6103}
6104
6105int btrfs_read_sys_array(struct btrfs_root *root)
6106{
6107 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
6108 struct extent_buffer *sb;
6109 struct btrfs_disk_key *disk_key;
6110 struct btrfs_chunk *chunk;
6111 u8 *ptr;
6112 unsigned long sb_ptr;
6113 int ret = 0;
6114 u32 num_stripes;
6115 u32 array_size;
6116 u32 len = 0;
6117 u32 cur;
6118 struct btrfs_key key;
6119
6120 sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
6121 BTRFS_SUPER_INFO_SIZE);
6122 if (!sb)
6123 return -ENOMEM;
6124 btrfs_set_buffer_uptodate(sb);
6125 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6126 /*
6127 * The sb extent buffer is artifical and just used to read the system array.
6128 * btrfs_set_buffer_uptodate() call does not properly mark all it's
6129 * pages up-to-date when the page is larger: extent does not cover the
6130 * whole page and consequently check_page_uptodate does not find all
6131 * the page's extents up-to-date (the hole beyond sb),
6132 * write_extent_buffer then triggers a WARN_ON.
6133 *
6134 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6135 * but sb spans only this function. Add an explicit SetPageUptodate call
6136 * to silence the warning eg. on PowerPC 64.
6137 */
6138 if (PAGE_CACHE_SIZE > BTRFS_SUPER_INFO_SIZE)
6139 SetPageUptodate(sb->pages[0]);
6140
6141 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6142 array_size = btrfs_super_sys_array_size(super_copy);
6143
6144 ptr = super_copy->sys_chunk_array;
6145 sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
6146 cur = 0;
6147
6148 while (cur < array_size) {
6149 disk_key = (struct btrfs_disk_key *)ptr;
6150 btrfs_disk_key_to_cpu(&key, disk_key);
6151
6152 len = sizeof(*disk_key); ptr += len;
6153 sb_ptr += len;
6154 cur += len;
6155
6156 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6157 chunk = (struct btrfs_chunk *)sb_ptr;
6158 ret = read_one_chunk(root, &key, sb, chunk);
6159 if (ret)
6160 break;
6161 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6162 len = btrfs_chunk_item_size(num_stripes);
6163 } else {
6164 ret = -EIO;
6165 break;
6166 }
6167 ptr += len;
6168 sb_ptr += len;
6169 cur += len;
6170 }
6171 free_extent_buffer(sb);
6172 return ret;
6173}
6174
6175int btrfs_read_chunk_tree(struct btrfs_root *root)
6176{
6177 struct btrfs_path *path;
6178 struct extent_buffer *leaf;
6179 struct btrfs_key key;
6180 struct btrfs_key found_key;
6181 int ret;
6182 int slot;
6183
6184 root = root->fs_info->chunk_root;
6185
6186 path = btrfs_alloc_path();
6187 if (!path)
6188 return -ENOMEM;
6189
6190 mutex_lock(&uuid_mutex);
6191 lock_chunks(root);
6192
6193 /*
6194 * Read all device items, and then all the chunk items. All
6195 * device items are found before any chunk item (their object id
6196 * is smaller than the lowest possible object id for a chunk
6197 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6198 */
6199 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6200 key.offset = 0;
6201 key.type = 0;
6202 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6203 if (ret < 0)
6204 goto error;
6205 while (1) {
6206 leaf = path->nodes[0];
6207 slot = path->slots[0];
6208 if (slot >= btrfs_header_nritems(leaf)) {
6209 ret = btrfs_next_leaf(root, path);
6210 if (ret == 0)
6211 continue;
6212 if (ret < 0)
6213 goto error;
6214 break;
6215 }
6216 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6217 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6218 struct btrfs_dev_item *dev_item;
6219 dev_item = btrfs_item_ptr(leaf, slot,
6220 struct btrfs_dev_item);
6221 ret = read_one_dev(root, leaf, dev_item);
6222 if (ret)
6223 goto error;
6224 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6225 struct btrfs_chunk *chunk;
6226 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6227 ret = read_one_chunk(root, &found_key, leaf, chunk);
6228 if (ret)
6229 goto error;
6230 }
6231 path->slots[0]++;
6232 }
6233 ret = 0;
6234error:
6235 unlock_chunks(root);
6236 mutex_unlock(&uuid_mutex);
6237
6238 btrfs_free_path(path);
6239 return ret;
6240}
6241
6242void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6243{
6244 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6245 struct btrfs_device *device;
6246
6247 while (fs_devices) {
6248 mutex_lock(&fs_devices->device_list_mutex);
6249 list_for_each_entry(device, &fs_devices->devices, dev_list)
6250 device->dev_root = fs_info->dev_root;
6251 mutex_unlock(&fs_devices->device_list_mutex);
6252
6253 fs_devices = fs_devices->seed;
6254 }
6255}
6256
6257static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
6258{
6259 int i;
6260
6261 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6262 btrfs_dev_stat_reset(dev, i);
6263}
6264
6265int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
6266{
6267 struct btrfs_key key;
6268 struct btrfs_key found_key;
6269 struct btrfs_root *dev_root = fs_info->dev_root;
6270 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6271 struct extent_buffer *eb;
6272 int slot;
6273 int ret = 0;
6274 struct btrfs_device *device;
6275 struct btrfs_path *path = NULL;
6276 int i;
6277
6278 path = btrfs_alloc_path();
6279 if (!path) {
6280 ret = -ENOMEM;
6281 goto out;
6282 }
6283
6284 mutex_lock(&fs_devices->device_list_mutex);
6285 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6286 int item_size;
6287 struct btrfs_dev_stats_item *ptr;
6288
6289 key.objectid = 0;
6290 key.type = BTRFS_DEV_STATS_KEY;
6291 key.offset = device->devid;
6292 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
6293 if (ret) {
6294 __btrfs_reset_dev_stats(device);
6295 device->dev_stats_valid = 1;
6296 btrfs_release_path(path);
6297 continue;
6298 }
6299 slot = path->slots[0];
6300 eb = path->nodes[0];
6301 btrfs_item_key_to_cpu(eb, &found_key, slot);
6302 item_size = btrfs_item_size_nr(eb, slot);
6303
6304 ptr = btrfs_item_ptr(eb, slot,
6305 struct btrfs_dev_stats_item);
6306
6307 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6308 if (item_size >= (1 + i) * sizeof(__le64))
6309 btrfs_dev_stat_set(device, i,
6310 btrfs_dev_stats_value(eb, ptr, i));
6311 else
6312 btrfs_dev_stat_reset(device, i);
6313 }
6314
6315 device->dev_stats_valid = 1;
6316 btrfs_dev_stat_print_on_load(device);
6317 btrfs_release_path(path);
6318 }
6319 mutex_unlock(&fs_devices->device_list_mutex);
6320
6321out:
6322 btrfs_free_path(path);
6323 return ret < 0 ? ret : 0;
6324}
6325
6326static int update_dev_stat_item(struct btrfs_trans_handle *trans,
6327 struct btrfs_root *dev_root,
6328 struct btrfs_device *device)
6329{
6330 struct btrfs_path *path;
6331 struct btrfs_key key;
6332 struct extent_buffer *eb;
6333 struct btrfs_dev_stats_item *ptr;
6334 int ret;
6335 int i;
6336
6337 key.objectid = 0;
6338 key.type = BTRFS_DEV_STATS_KEY;
6339 key.offset = device->devid;
6340
6341 path = btrfs_alloc_path();
6342 BUG_ON(!path);
6343 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
6344 if (ret < 0) {
6345 printk_in_rcu(KERN_WARNING "BTRFS: "
6346 "error %d while searching for dev_stats item for device %s!\n",
6347 ret, rcu_str_deref(device->name));
6348 goto out;
6349 }
6350
6351 if (ret == 0 &&
6352 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
6353 /* need to delete old one and insert a new one */
6354 ret = btrfs_del_item(trans, dev_root, path);
6355 if (ret != 0) {
6356 printk_in_rcu(KERN_WARNING "BTRFS: "
6357 "delete too small dev_stats item for device %s failed %d!\n",
6358 rcu_str_deref(device->name), ret);
6359 goto out;
6360 }
6361 ret = 1;
6362 }
6363
6364 if (ret == 1) {
6365 /* need to insert a new item */
6366 btrfs_release_path(path);
6367 ret = btrfs_insert_empty_item(trans, dev_root, path,
6368 &key, sizeof(*ptr));
6369 if (ret < 0) {
6370 printk_in_rcu(KERN_WARNING "BTRFS: "
6371 "insert dev_stats item for device %s failed %d!\n",
6372 rcu_str_deref(device->name), ret);
6373 goto out;
6374 }
6375 }
6376
6377 eb = path->nodes[0];
6378 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
6379 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6380 btrfs_set_dev_stats_value(eb, ptr, i,
6381 btrfs_dev_stat_read(device, i));
6382 btrfs_mark_buffer_dirty(eb);
6383
6384out:
6385 btrfs_free_path(path);
6386 return ret;
6387}
6388
6389/*
6390 * called from commit_transaction. Writes all changed device stats to disk.
6391 */
6392int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
6393 struct btrfs_fs_info *fs_info)
6394{
6395 struct btrfs_root *dev_root = fs_info->dev_root;
6396 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6397 struct btrfs_device *device;
6398 int stats_cnt;
6399 int ret = 0;
6400
6401 mutex_lock(&fs_devices->device_list_mutex);
6402 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6403 if (!device->dev_stats_valid || !btrfs_dev_stats_dirty(device))
6404 continue;
6405
6406 stats_cnt = atomic_read(&device->dev_stats_ccnt);
6407 ret = update_dev_stat_item(trans, dev_root, device);
6408 if (!ret)
6409 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
6410 }
6411 mutex_unlock(&fs_devices->device_list_mutex);
6412
6413 return ret;
6414}
6415
6416void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
6417{
6418 btrfs_dev_stat_inc(dev, index);
6419 btrfs_dev_stat_print_on_error(dev);
6420}
6421
6422static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
6423{
6424 if (!dev->dev_stats_valid)
6425 return;
6426 printk_ratelimited_in_rcu(KERN_ERR "BTRFS: "
6427 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
6428 rcu_str_deref(dev->name),
6429 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6430 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6431 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6432 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6433 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6434}
6435
6436static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
6437{
6438 int i;
6439
6440 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6441 if (btrfs_dev_stat_read(dev, i) != 0)
6442 break;
6443 if (i == BTRFS_DEV_STAT_VALUES_MAX)
6444 return; /* all values == 0, suppress message */
6445
6446 printk_in_rcu(KERN_INFO "BTRFS: "
6447 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
6448 rcu_str_deref(dev->name),
6449 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6450 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6451 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6452 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6453 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6454}
6455
6456int btrfs_get_dev_stats(struct btrfs_root *root,
6457 struct btrfs_ioctl_get_dev_stats *stats)
6458{
6459 struct btrfs_device *dev;
6460 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
6461 int i;
6462
6463 mutex_lock(&fs_devices->device_list_mutex);
6464 dev = btrfs_find_device(root->fs_info, stats->devid, NULL, NULL);
6465 mutex_unlock(&fs_devices->device_list_mutex);
6466
6467 if (!dev) {
6468 btrfs_warn(root->fs_info, "get dev_stats failed, device not found");
6469 return -ENODEV;
6470 } else if (!dev->dev_stats_valid) {
6471 btrfs_warn(root->fs_info, "get dev_stats failed, not yet valid");
6472 return -ENODEV;
6473 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
6474 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6475 if (stats->nr_items > i)
6476 stats->values[i] =
6477 btrfs_dev_stat_read_and_reset(dev, i);
6478 else
6479 btrfs_dev_stat_reset(dev, i);
6480 }
6481 } else {
6482 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6483 if (stats->nr_items > i)
6484 stats->values[i] = btrfs_dev_stat_read(dev, i);
6485 }
6486 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
6487 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
6488 return 0;
6489}
6490
6491int btrfs_scratch_superblock(struct btrfs_device *device)
6492{
6493 struct buffer_head *bh;
6494 struct btrfs_super_block *disk_super;
6495
6496 bh = btrfs_read_dev_super(device->bdev);
6497 if (!bh)
6498 return -EINVAL;
6499 disk_super = (struct btrfs_super_block *)bh->b_data;
6500
6501 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
6502 set_buffer_dirty(bh);
6503 sync_dirty_buffer(bh);
6504 brelse(bh);
6505
6506 return 0;
6507}
This page took 0.046827 seconds and 5 git commands to generate.