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