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