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