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