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