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