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