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