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