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