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