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