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