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