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