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