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