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