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