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