]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - fs/btrfs/volumes.c
btrfs: Exit gracefully when chunk map cannot be inserted to the tree
[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);
1616 n = rb_last(&em_tree->map);
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
da353f6b
DS
1857int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1858 u64 devid)
f1fa7f26
AJ
1859{
1860 struct btrfs_device *device;
1f78160c 1861 struct btrfs_fs_devices *cur_devices;
b5185197 1862 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2b82032c 1863 u64 num_devices;
a061fc8d
CM
1864 int ret = 0;
1865
a061fc8d
CM
1866 mutex_lock(&uuid_mutex);
1867
b5185197 1868 num_devices = fs_devices->num_devices;
7e79cb86 1869 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
0b246afa 1870 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
8dabb742
SB
1871 WARN_ON(num_devices < 1);
1872 num_devices--;
1873 }
7e79cb86 1874 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
8dabb742 1875
0b246afa 1876 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
f1fa7f26 1877 if (ret)
a061fc8d 1878 goto out;
a061fc8d 1879
2ff7e61e
JM
1880 ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1881 &device);
24fc572f 1882 if (ret)
53b381b3 1883 goto out;
dfe25020 1884
401e29c1 1885 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
183860f6 1886 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
24fc572f 1887 goto out;
63a212ab
SB
1888 }
1889
ebbede42
AJ
1890 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1891 fs_info->fs_devices->rw_devices == 1) {
183860f6 1892 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
24fc572f 1893 goto out;
2b82032c
YZ
1894 }
1895
ebbede42 1896 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
34441361 1897 mutex_lock(&fs_info->chunk_mutex);
2b82032c 1898 list_del_init(&device->dev_alloc_list);
c3929c36 1899 device->fs_devices->rw_devices--;
34441361 1900 mutex_unlock(&fs_info->chunk_mutex);
dfe25020 1901 }
a061fc8d 1902
d7901554 1903 mutex_unlock(&uuid_mutex);
a061fc8d 1904 ret = btrfs_shrink_device(device, 0);
d7901554 1905 mutex_lock(&uuid_mutex);
a061fc8d 1906 if (ret)
9b3517e9 1907 goto error_undo;
a061fc8d 1908
63a212ab
SB
1909 /*
1910 * TODO: the superblock still includes this device in its num_devices
1911 * counter although write_all_supers() is not locked out. This
1912 * could give a filesystem state which requires a degraded mount.
1913 */
0b246afa 1914 ret = btrfs_rm_dev_item(fs_info, device);
a061fc8d 1915 if (ret)
9b3517e9 1916 goto error_undo;
a061fc8d 1917
e12c9621 1918 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
0b246afa 1919 btrfs_scrub_cancel_dev(fs_info, device);
e5e9a520
CM
1920
1921 /*
1922 * the device list mutex makes sure that we don't change
1923 * the device list while someone else is writing out all
d7306801
FDBM
1924 * the device supers. Whoever is writing all supers, should
1925 * lock the device list mutex before getting the number of
1926 * devices in the super block (super_copy). Conversely,
1927 * whoever updates the number of devices in the super block
1928 * (super_copy) should hold the device list mutex.
e5e9a520 1929 */
1f78160c 1930
41a52a0f
AJ
1931 /*
1932 * In normal cases the cur_devices == fs_devices. But in case
1933 * of deleting a seed device, the cur_devices should point to
1934 * its own fs_devices listed under the fs_devices->seed.
1935 */
1f78160c 1936 cur_devices = device->fs_devices;
b5185197 1937 mutex_lock(&fs_devices->device_list_mutex);
1f78160c 1938 list_del_rcu(&device->dev_list);
e5e9a520 1939
41a52a0f
AJ
1940 cur_devices->num_devices--;
1941 cur_devices->total_devices--;
b4993e64
AJ
1942 /* Update total_devices of the parent fs_devices if it's seed */
1943 if (cur_devices != fs_devices)
1944 fs_devices->total_devices--;
2b82032c 1945
e6e674bd 1946 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
41a52a0f 1947 cur_devices->missing_devices--;
cd02dca5 1948
d6507cf1 1949 btrfs_assign_next_active_device(device, NULL);
2b82032c 1950
0bfaa9c5 1951 if (device->bdev) {
41a52a0f 1952 cur_devices->open_devices--;
0bfaa9c5 1953 /* remove sysfs entry */
b5185197 1954 btrfs_sysfs_rm_device_link(fs_devices, device);
0bfaa9c5 1955 }
99994cde 1956
0b246afa
JM
1957 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
1958 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
b5185197 1959 mutex_unlock(&fs_devices->device_list_mutex);
2b82032c 1960
cea67ab9
JM
1961 /*
1962 * at this point, the device is zero sized and detached from
1963 * the devices list. All that's left is to zero out the old
1964 * supers and free the device.
1965 */
ebbede42 1966 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
cea67ab9
JM
1967 btrfs_scratch_superblocks(device->bdev, device->name->str);
1968
1969 btrfs_close_bdev(device);
f06c5965 1970 call_rcu(&device->rcu, free_device_rcu);
cea67ab9 1971
1f78160c 1972 if (cur_devices->open_devices == 0) {
e4404d6e 1973 while (fs_devices) {
8321cf25
RS
1974 if (fs_devices->seed == cur_devices) {
1975 fs_devices->seed = cur_devices->seed;
e4404d6e 1976 break;
8321cf25 1977 }
e4404d6e 1978 fs_devices = fs_devices->seed;
2b82032c 1979 }
1f78160c 1980 cur_devices->seed = NULL;
0226e0eb 1981 close_fs_devices(cur_devices);
1f78160c 1982 free_fs_devices(cur_devices);
2b82032c
YZ
1983 }
1984
a061fc8d
CM
1985out:
1986 mutex_unlock(&uuid_mutex);
a061fc8d 1987 return ret;
24fc572f 1988
9b3517e9 1989error_undo:
ebbede42 1990 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
34441361 1991 mutex_lock(&fs_info->chunk_mutex);
9b3517e9 1992 list_add(&device->dev_alloc_list,
b5185197 1993 &fs_devices->alloc_list);
c3929c36 1994 device->fs_devices->rw_devices++;
34441361 1995 mutex_unlock(&fs_info->chunk_mutex);
9b3517e9 1996 }
24fc572f 1997 goto out;
a061fc8d
CM
1998}
1999
68a9db5f 2000void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
e93c89c1 2001{
d51908ce
AJ
2002 struct btrfs_fs_devices *fs_devices;
2003
68a9db5f 2004 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
1357272f 2005
25e8e911
AJ
2006 /*
2007 * in case of fs with no seed, srcdev->fs_devices will point
2008 * to fs_devices of fs_info. However when the dev being replaced is
2009 * a seed dev it will point to the seed's local fs_devices. In short
2010 * srcdev will have its correct fs_devices in both the cases.
2011 */
2012 fs_devices = srcdev->fs_devices;
d51908ce 2013
e93c89c1 2014 list_del_rcu(&srcdev->dev_list);
619c47f3 2015 list_del(&srcdev->dev_alloc_list);
d51908ce 2016 fs_devices->num_devices--;
e6e674bd 2017 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
d51908ce 2018 fs_devices->missing_devices--;
e93c89c1 2019
ebbede42 2020 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
82372bc8 2021 fs_devices->rw_devices--;
1357272f 2022
82372bc8 2023 if (srcdev->bdev)
d51908ce 2024 fs_devices->open_devices--;
084b6e7c
QW
2025}
2026
2027void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2028 struct btrfs_device *srcdev)
2029{
2030 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
e93c89c1 2031
ebbede42 2032 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
48b3b9d4
AJ
2033 /* zero out the old super if it is writable */
2034 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2035 }
14238819
AJ
2036
2037 btrfs_close_bdev(srcdev);
f06c5965 2038 call_rcu(&srcdev->rcu, free_device_rcu);
94d5f0c2 2039
94d5f0c2
AJ
2040 /* if this is no devs we rather delete the fs_devices */
2041 if (!fs_devices->num_devices) {
2042 struct btrfs_fs_devices *tmp_fs_devices;
2043
6dd38f81
AJ
2044 /*
2045 * On a mounted FS, num_devices can't be zero unless it's a
2046 * seed. In case of a seed device being replaced, the replace
2047 * target added to the sprout FS, so there will be no more
2048 * device left under the seed FS.
2049 */
2050 ASSERT(fs_devices->seeding);
2051
94d5f0c2
AJ
2052 tmp_fs_devices = fs_info->fs_devices;
2053 while (tmp_fs_devices) {
2054 if (tmp_fs_devices->seed == fs_devices) {
2055 tmp_fs_devices->seed = fs_devices->seed;
2056 break;
2057 }
2058 tmp_fs_devices = tmp_fs_devices->seed;
2059 }
2060 fs_devices->seed = NULL;
0226e0eb 2061 close_fs_devices(fs_devices);
8bef8401 2062 free_fs_devices(fs_devices);
94d5f0c2 2063 }
e93c89c1
SB
2064}
2065
4f5ad7bd 2066void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
e93c89c1 2067{
4f5ad7bd 2068 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
d9a071f0 2069
e93c89c1 2070 WARN_ON(!tgtdev);
d9a071f0 2071 mutex_lock(&fs_devices->device_list_mutex);
d2ff1b20 2072
d9a071f0 2073 btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
d2ff1b20 2074
779bf3fe 2075 if (tgtdev->bdev)
d9a071f0 2076 fs_devices->open_devices--;
779bf3fe 2077
d9a071f0 2078 fs_devices->num_devices--;
e93c89c1 2079
d6507cf1 2080 btrfs_assign_next_active_device(tgtdev, NULL);
e93c89c1 2081
e93c89c1 2082 list_del_rcu(&tgtdev->dev_list);
e93c89c1 2083
d9a071f0 2084 mutex_unlock(&fs_devices->device_list_mutex);
779bf3fe
AJ
2085
2086 /*
2087 * The update_dev_time() with in btrfs_scratch_superblocks()
2088 * may lead to a call to btrfs_show_devname() which will try
2089 * to hold device_list_mutex. And here this device
2090 * is already out of device list, so we don't have to hold
2091 * the device_list_mutex lock.
2092 */
2093 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
14238819
AJ
2094
2095 btrfs_close_bdev(tgtdev);
f06c5965 2096 call_rcu(&tgtdev->rcu, free_device_rcu);
e93c89c1
SB
2097}
2098
2ff7e61e 2099static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
da353f6b 2100 const char *device_path,
48a3b636 2101 struct btrfs_device **device)
7ba15b7d
SB
2102{
2103 int ret = 0;
2104 struct btrfs_super_block *disk_super;
2105 u64 devid;
2106 u8 *dev_uuid;
2107 struct block_device *bdev;
2108 struct buffer_head *bh;
2109
2110 *device = NULL;
2111 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
0b246afa 2112 fs_info->bdev_holder, 0, &bdev, &bh);
7ba15b7d
SB
2113 if (ret)
2114 return ret;
2115 disk_super = (struct btrfs_super_block *)bh->b_data;
2116 devid = btrfs_stack_device_id(&disk_super->dev_item);
2117 dev_uuid = disk_super->dev_item.uuid;
0b246afa 2118 *device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
7ba15b7d
SB
2119 brelse(bh);
2120 if (!*device)
2121 ret = -ENOENT;
2122 blkdev_put(bdev, FMODE_READ);
2123 return ret;
2124}
2125
2ff7e61e 2126int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
da353f6b 2127 const char *device_path,
7ba15b7d
SB
2128 struct btrfs_device **device)
2129{
2130 *device = NULL;
2131 if (strcmp(device_path, "missing") == 0) {
2132 struct list_head *devices;
2133 struct btrfs_device *tmp;
2134
0b246afa 2135 devices = &fs_info->fs_devices->devices;
7ba15b7d 2136 list_for_each_entry(tmp, devices, dev_list) {
e12c9621
AJ
2137 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2138 &tmp->dev_state) && !tmp->bdev) {
7ba15b7d
SB
2139 *device = tmp;
2140 break;
2141 }
2142 }
2143
d74a6259
AJ
2144 if (!*device)
2145 return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
7ba15b7d
SB
2146
2147 return 0;
2148 } else {
2ff7e61e 2149 return btrfs_find_device_by_path(fs_info, device_path, device);
7ba15b7d
SB
2150 }
2151}
2152
5c5c0df0
DS
2153/*
2154 * Lookup a device given by device id, or the path if the id is 0.
2155 */
2ff7e61e 2156int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
da353f6b
DS
2157 const char *devpath,
2158 struct btrfs_device **device)
24e0474b
AJ
2159{
2160 int ret;
2161
5c5c0df0 2162 if (devid) {
24e0474b 2163 ret = 0;
0b246afa 2164 *device = btrfs_find_device(fs_info, devid, NULL, NULL);
24e0474b
AJ
2165 if (!*device)
2166 ret = -ENOENT;
2167 } else {
5c5c0df0 2168 if (!devpath || !devpath[0])
b3d1b153
AJ
2169 return -EINVAL;
2170
2ff7e61e 2171 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
24e0474b
AJ
2172 device);
2173 }
2174 return ret;
2175}
2176
2b82032c
YZ
2177/*
2178 * does all the dirty work required for changing file system's UUID.
2179 */
2ff7e61e 2180static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2b82032c 2181{
0b246afa 2182 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2b82032c 2183 struct btrfs_fs_devices *old_devices;
e4404d6e 2184 struct btrfs_fs_devices *seed_devices;
0b246afa 2185 struct btrfs_super_block *disk_super = fs_info->super_copy;
2b82032c
YZ
2186 struct btrfs_device *device;
2187 u64 super_flags;
2188
a32bf9a3 2189 lockdep_assert_held(&uuid_mutex);
e4404d6e 2190 if (!fs_devices->seeding)
2b82032c
YZ
2191 return -EINVAL;
2192
2dfeca9b 2193 seed_devices = alloc_fs_devices(NULL);
2208a378
ID
2194 if (IS_ERR(seed_devices))
2195 return PTR_ERR(seed_devices);
2b82032c 2196
e4404d6e
YZ
2197 old_devices = clone_fs_devices(fs_devices);
2198 if (IS_ERR(old_devices)) {
2199 kfree(seed_devices);
2200 return PTR_ERR(old_devices);
2b82032c 2201 }
e4404d6e 2202
c4babc5e 2203 list_add(&old_devices->fs_list, &fs_uuids);
2b82032c 2204
e4404d6e
YZ
2205 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2206 seed_devices->opened = 1;
2207 INIT_LIST_HEAD(&seed_devices->devices);
2208 INIT_LIST_HEAD(&seed_devices->alloc_list);
e5e9a520 2209 mutex_init(&seed_devices->device_list_mutex);
c9513edb 2210
321a4bf7 2211 mutex_lock(&fs_devices->device_list_mutex);
1f78160c
XG
2212 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2213 synchronize_rcu);
2196d6e8
MX
2214 list_for_each_entry(device, &seed_devices->devices, dev_list)
2215 device->fs_devices = seed_devices;
c9513edb 2216
34441361 2217 mutex_lock(&fs_info->chunk_mutex);
e4404d6e 2218 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
34441361 2219 mutex_unlock(&fs_info->chunk_mutex);
e4404d6e 2220
2b82032c
YZ
2221 fs_devices->seeding = 0;
2222 fs_devices->num_devices = 0;
2223 fs_devices->open_devices = 0;
69611ac8 2224 fs_devices->missing_devices = 0;
69611ac8 2225 fs_devices->rotating = 0;
e4404d6e 2226 fs_devices->seed = seed_devices;
2b82032c
YZ
2227
2228 generate_random_uuid(fs_devices->fsid);
0b246afa 2229 memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2b82032c 2230 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
321a4bf7 2231 mutex_unlock(&fs_devices->device_list_mutex);
f7171750 2232
2b82032c
YZ
2233 super_flags = btrfs_super_flags(disk_super) &
2234 ~BTRFS_SUPER_FLAG_SEEDING;
2235 btrfs_set_super_flags(disk_super, super_flags);
2236
2237 return 0;
2238}
2239
2240/*
01327610 2241 * Store the expected generation for seed devices in device items.
2b82032c
YZ
2242 */
2243static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
5b4aacef 2244 struct btrfs_fs_info *fs_info)
2b82032c 2245{
5b4aacef 2246 struct btrfs_root *root = fs_info->chunk_root;
2b82032c
YZ
2247 struct btrfs_path *path;
2248 struct extent_buffer *leaf;
2249 struct btrfs_dev_item *dev_item;
2250 struct btrfs_device *device;
2251 struct btrfs_key key;
44880fdc 2252 u8 fs_uuid[BTRFS_FSID_SIZE];
2b82032c
YZ
2253 u8 dev_uuid[BTRFS_UUID_SIZE];
2254 u64 devid;
2255 int ret;
2256
2257 path = btrfs_alloc_path();
2258 if (!path)
2259 return -ENOMEM;
2260
2b82032c
YZ
2261 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2262 key.offset = 0;
2263 key.type = BTRFS_DEV_ITEM_KEY;
2264
2265 while (1) {
2266 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2267 if (ret < 0)
2268 goto error;
2269
2270 leaf = path->nodes[0];
2271next_slot:
2272 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2273 ret = btrfs_next_leaf(root, path);
2274 if (ret > 0)
2275 break;
2276 if (ret < 0)
2277 goto error;
2278 leaf = path->nodes[0];
2279 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
b3b4aa74 2280 btrfs_release_path(path);
2b82032c
YZ
2281 continue;
2282 }
2283
2284 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2285 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2286 key.type != BTRFS_DEV_ITEM_KEY)
2287 break;
2288
2289 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2290 struct btrfs_dev_item);
2291 devid = btrfs_device_id(leaf, dev_item);
410ba3a2 2292 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2b82032c 2293 BTRFS_UUID_SIZE);
1473b24e 2294 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
44880fdc 2295 BTRFS_FSID_SIZE);
0b246afa 2296 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
79787eaa 2297 BUG_ON(!device); /* Logic error */
2b82032c
YZ
2298
2299 if (device->fs_devices->seeding) {
2300 btrfs_set_device_generation(leaf, dev_item,
2301 device->generation);
2302 btrfs_mark_buffer_dirty(leaf);
2303 }
2304
2305 path->slots[0]++;
2306 goto next_slot;
2307 }
2308 ret = 0;
2309error:
2310 btrfs_free_path(path);
2311 return ret;
2312}
2313
da353f6b 2314int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
788f20eb 2315{
5112febb 2316 struct btrfs_root *root = fs_info->dev_root;
d5e2003c 2317 struct request_queue *q;
788f20eb
CM
2318 struct btrfs_trans_handle *trans;
2319 struct btrfs_device *device;
2320 struct block_device *bdev;
0b246afa 2321 struct super_block *sb = fs_info->sb;
606686ee 2322 struct rcu_string *name;
5da54bc1 2323 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3c1dbdf5 2324 u64 tmp;
2b82032c 2325 int seeding_dev = 0;
788f20eb 2326 int ret = 0;
7132a262 2327 bool unlocked = false;
788f20eb 2328
5da54bc1 2329 if (sb_rdonly(sb) && !fs_devices->seeding)
f8c5d0b4 2330 return -EROFS;
788f20eb 2331
a5d16333 2332 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
0b246afa 2333 fs_info->bdev_holder);
7f59203a
JB
2334 if (IS_ERR(bdev))
2335 return PTR_ERR(bdev);
a2135011 2336
5da54bc1 2337 if (fs_devices->seeding) {
2b82032c
YZ
2338 seeding_dev = 1;
2339 down_write(&sb->s_umount);
2340 mutex_lock(&uuid_mutex);
2341 }
2342
8c8bee1d 2343 filemap_write_and_wait(bdev->bd_inode->i_mapping);
a2135011 2344
5da54bc1 2345 mutex_lock(&fs_devices->device_list_mutex);
694c51fb 2346 list_for_each_entry(device, &fs_devices->devices, dev_list) {
788f20eb
CM
2347 if (device->bdev == bdev) {
2348 ret = -EEXIST;
d25628bd 2349 mutex_unlock(
5da54bc1 2350 &fs_devices->device_list_mutex);
2b82032c 2351 goto error;
788f20eb
CM
2352 }
2353 }
5da54bc1 2354 mutex_unlock(&fs_devices->device_list_mutex);
788f20eb 2355
0b246afa 2356 device = btrfs_alloc_device(fs_info, NULL, NULL);
12bd2fc0 2357 if (IS_ERR(device)) {
788f20eb 2358 /* we can safely leave the fs_devices entry around */
12bd2fc0 2359 ret = PTR_ERR(device);
2b82032c 2360 goto error;
788f20eb
CM
2361 }
2362
78f2c9e6 2363 name = rcu_string_strdup(device_path, GFP_KERNEL);
606686ee 2364 if (!name) {
2b82032c 2365 ret = -ENOMEM;
5c4cf6c9 2366 goto error_free_device;
788f20eb 2367 }
606686ee 2368 rcu_assign_pointer(device->name, name);
2b82032c 2369
a22285a6 2370 trans = btrfs_start_transaction(root, 0);
98d5dc13 2371 if (IS_ERR(trans)) {
98d5dc13 2372 ret = PTR_ERR(trans);
5c4cf6c9 2373 goto error_free_device;
98d5dc13
TI
2374 }
2375
d5e2003c 2376 q = bdev_get_queue(bdev);
ebbede42 2377 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2b82032c 2378 device->generation = trans->transid;
0b246afa
JM
2379 device->io_width = fs_info->sectorsize;
2380 device->io_align = fs_info->sectorsize;
2381 device->sector_size = fs_info->sectorsize;
7dfb8be1
NB
2382 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2383 fs_info->sectorsize);
2cc3c559 2384 device->disk_total_bytes = device->total_bytes;
935e5cc9 2385 device->commit_total_bytes = device->total_bytes;
fb456252 2386 device->fs_info = fs_info;
788f20eb 2387 device->bdev = bdev;
e12c9621 2388 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
401e29c1 2389 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
fb01aa85 2390 device->mode = FMODE_EXCL;
27087f37 2391 device->dev_stats_valid = 1;
9f6d2510 2392 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
788f20eb 2393
2b82032c 2394 if (seeding_dev) {
1751e8a6 2395 sb->s_flags &= ~SB_RDONLY;
2ff7e61e 2396 ret = btrfs_prepare_sprout(fs_info);
d31c32f6
AJ
2397 if (ret) {
2398 btrfs_abort_transaction(trans, ret);
2399 goto error_trans;
2400 }
2b82032c 2401 }
788f20eb 2402
5da54bc1 2403 device->fs_devices = fs_devices;
e5e9a520 2404
5da54bc1 2405 mutex_lock(&fs_devices->device_list_mutex);
34441361 2406 mutex_lock(&fs_info->chunk_mutex);
5da54bc1
AJ
2407 list_add_rcu(&device->dev_list, &fs_devices->devices);
2408 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2409 fs_devices->num_devices++;
2410 fs_devices->open_devices++;
2411 fs_devices->rw_devices++;
2412 fs_devices->total_devices++;
2413 fs_devices->total_rw_bytes += device->total_bytes;
325cd4ba 2414
a5ed45f8 2415 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2bf64758 2416
e884f4f0 2417 if (!blk_queue_nonrot(q))
5da54bc1 2418 fs_devices->rotating = 1;
c289811c 2419
0b246afa
JM
2420 tmp = btrfs_super_total_bytes(fs_info->super_copy);
2421 btrfs_set_super_total_bytes(fs_info->super_copy,
7dfb8be1 2422 round_down(tmp + device->total_bytes, fs_info->sectorsize));
788f20eb 2423
0b246afa
JM
2424 tmp = btrfs_super_num_devices(fs_info->super_copy);
2425 btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
0d39376a
AJ
2426
2427 /* add sysfs device entry */
5da54bc1 2428 btrfs_sysfs_add_device_link(fs_devices, device);
0d39376a 2429
2196d6e8
MX
2430 /*
2431 * we've got more storage, clear any full flags on the space
2432 * infos
2433 */
0b246afa 2434 btrfs_clear_space_info_full(fs_info);
2196d6e8 2435
34441361 2436 mutex_unlock(&fs_info->chunk_mutex);
5da54bc1 2437 mutex_unlock(&fs_devices->device_list_mutex);
788f20eb 2438
2b82032c 2439 if (seeding_dev) {
34441361 2440 mutex_lock(&fs_info->chunk_mutex);
e4a4dce7 2441 ret = init_first_rw_device(trans, fs_info);
34441361 2442 mutex_unlock(&fs_info->chunk_mutex);
005d6427 2443 if (ret) {
66642832 2444 btrfs_abort_transaction(trans, ret);
d31c32f6 2445 goto error_sysfs;
005d6427 2446 }
2196d6e8
MX
2447 }
2448
8e87e856 2449 ret = btrfs_add_dev_item(trans, device);
2196d6e8 2450 if (ret) {
66642832 2451 btrfs_abort_transaction(trans, ret);
d31c32f6 2452 goto error_sysfs;
2196d6e8
MX
2453 }
2454
2455 if (seeding_dev) {
2456 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2457
0b246afa 2458 ret = btrfs_finish_sprout(trans, fs_info);
005d6427 2459 if (ret) {
66642832 2460 btrfs_abort_transaction(trans, ret);
d31c32f6 2461 goto error_sysfs;
005d6427 2462 }
b2373f25
AJ
2463
2464 /* Sprouting would change fsid of the mounted root,
2465 * so rename the fsid on the sysfs
2466 */
2467 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
0b246afa 2468 fs_info->fsid);
5da54bc1 2469 if (kobject_rename(&fs_devices->fsid_kobj, fsid_buf))
0b246afa
JM
2470 btrfs_warn(fs_info,
2471 "sysfs: failed to create fsid for sprout");
2b82032c
YZ
2472 }
2473
3a45bb20 2474 ret = btrfs_commit_transaction(trans);
a2135011 2475
2b82032c
YZ
2476 if (seeding_dev) {
2477 mutex_unlock(&uuid_mutex);
2478 up_write(&sb->s_umount);
7132a262 2479 unlocked = true;
788f20eb 2480
79787eaa
JM
2481 if (ret) /* transaction commit */
2482 return ret;
2483
2ff7e61e 2484 ret = btrfs_relocate_sys_chunks(fs_info);
79787eaa 2485 if (ret < 0)
0b246afa 2486 btrfs_handle_fs_error(fs_info, ret,
5d163e0e 2487 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
671415b7
MX
2488 trans = btrfs_attach_transaction(root);
2489 if (IS_ERR(trans)) {
2490 if (PTR_ERR(trans) == -ENOENT)
2491 return 0;
7132a262
AJ
2492 ret = PTR_ERR(trans);
2493 trans = NULL;
2494 goto error_sysfs;
671415b7 2495 }
3a45bb20 2496 ret = btrfs_commit_transaction(trans);
2b82032c 2497 }
c9e9f97b 2498
5a1972bd
QW
2499 /* Update ctime/mtime for libblkid */
2500 update_dev_time(device_path);
2b82032c 2501 return ret;
79787eaa 2502
d31c32f6 2503error_sysfs:
5da54bc1 2504 btrfs_sysfs_rm_device_link(fs_devices, device);
79787eaa 2505error_trans:
0af2c4bf 2506 if (seeding_dev)
1751e8a6 2507 sb->s_flags |= SB_RDONLY;
7132a262
AJ
2508 if (trans)
2509 btrfs_end_transaction(trans);
5c4cf6c9 2510error_free_device:
a425f9d4 2511 btrfs_free_device(device);
2b82032c 2512error:
e525fd89 2513 blkdev_put(bdev, FMODE_EXCL);
7132a262 2514 if (seeding_dev && !unlocked) {
2b82032c
YZ
2515 mutex_unlock(&uuid_mutex);
2516 up_write(&sb->s_umount);
2517 }
c9e9f97b 2518 return ret;
788f20eb
CM
2519}
2520
d397712b
CM
2521static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2522 struct btrfs_device *device)
0b86a832
CM
2523{
2524 int ret;
2525 struct btrfs_path *path;
0b246afa 2526 struct btrfs_root *root = device->fs_info->chunk_root;
0b86a832
CM
2527 struct btrfs_dev_item *dev_item;
2528 struct extent_buffer *leaf;
2529 struct btrfs_key key;
2530
0b86a832
CM
2531 path = btrfs_alloc_path();
2532 if (!path)
2533 return -ENOMEM;
2534
2535 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2536 key.type = BTRFS_DEV_ITEM_KEY;
2537 key.offset = device->devid;
2538
2539 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2540 if (ret < 0)
2541 goto out;
2542
2543 if (ret > 0) {
2544 ret = -ENOENT;
2545 goto out;
2546 }
2547
2548 leaf = path->nodes[0];
2549 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2550
2551 btrfs_set_device_id(leaf, dev_item, device->devid);
2552 btrfs_set_device_type(leaf, dev_item, device->type);
2553 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2554 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2555 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
7cc8e58d
MX
2556 btrfs_set_device_total_bytes(leaf, dev_item,
2557 btrfs_device_get_disk_total_bytes(device));
2558 btrfs_set_device_bytes_used(leaf, dev_item,
2559 btrfs_device_get_bytes_used(device));
0b86a832
CM
2560 btrfs_mark_buffer_dirty(leaf);
2561
2562out:
2563 btrfs_free_path(path);
2564 return ret;
2565}
2566
2196d6e8 2567int btrfs_grow_device(struct btrfs_trans_handle *trans,
8f18cf13
CM
2568 struct btrfs_device *device, u64 new_size)
2569{
0b246afa
JM
2570 struct btrfs_fs_info *fs_info = device->fs_info;
2571 struct btrfs_super_block *super_copy = fs_info->super_copy;
935e5cc9 2572 struct btrfs_fs_devices *fs_devices;
2196d6e8
MX
2573 u64 old_total;
2574 u64 diff;
8f18cf13 2575
ebbede42 2576 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2b82032c 2577 return -EACCES;
2196d6e8 2578
7dfb8be1
NB
2579 new_size = round_down(new_size, fs_info->sectorsize);
2580
34441361 2581 mutex_lock(&fs_info->chunk_mutex);
2196d6e8 2582 old_total = btrfs_super_total_bytes(super_copy);
0e4324a4 2583 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2196d6e8 2584
63a212ab 2585 if (new_size <= device->total_bytes ||
401e29c1 2586 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
34441361 2587 mutex_unlock(&fs_info->chunk_mutex);
2b82032c 2588 return -EINVAL;
2196d6e8 2589 }
2b82032c 2590
0b246afa 2591 fs_devices = fs_info->fs_devices;
2b82032c 2592
7dfb8be1
NB
2593 btrfs_set_super_total_bytes(super_copy,
2594 round_down(old_total + diff, fs_info->sectorsize));
2b82032c
YZ
2595 device->fs_devices->total_rw_bytes += diff;
2596
7cc8e58d
MX
2597 btrfs_device_set_total_bytes(device, new_size);
2598 btrfs_device_set_disk_total_bytes(device, new_size);
fb456252 2599 btrfs_clear_space_info_full(device->fs_info);
935e5cc9
MX
2600 if (list_empty(&device->resized_list))
2601 list_add_tail(&device->resized_list,
2602 &fs_devices->resized_devices);
34441361 2603 mutex_unlock(&fs_info->chunk_mutex);
4184ea7f 2604
8f18cf13
CM
2605 return btrfs_update_device(trans, device);
2606}
2607
f4208794 2608static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
8f18cf13 2609{
f4208794 2610 struct btrfs_fs_info *fs_info = trans->fs_info;
5b4aacef 2611 struct btrfs_root *root = fs_info->chunk_root;
8f18cf13
CM
2612 int ret;
2613 struct btrfs_path *path;
2614 struct btrfs_key key;
2615
8f18cf13
CM
2616 path = btrfs_alloc_path();
2617 if (!path)
2618 return -ENOMEM;
2619
408fbf19 2620 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
8f18cf13
CM
2621 key.offset = chunk_offset;
2622 key.type = BTRFS_CHUNK_ITEM_KEY;
2623
2624 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
79787eaa
JM
2625 if (ret < 0)
2626 goto out;
2627 else if (ret > 0) { /* Logic error or corruption */
0b246afa
JM
2628 btrfs_handle_fs_error(fs_info, -ENOENT,
2629 "Failed lookup while freeing chunk.");
79787eaa
JM
2630 ret = -ENOENT;
2631 goto out;
2632 }
8f18cf13
CM
2633
2634 ret = btrfs_del_item(trans, root, path);
79787eaa 2635 if (ret < 0)
0b246afa
JM
2636 btrfs_handle_fs_error(fs_info, ret,
2637 "Failed to delete chunk item.");
79787eaa 2638out:
8f18cf13 2639 btrfs_free_path(path);
65a246c5 2640 return ret;
8f18cf13
CM
2641}
2642
408fbf19 2643static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
8f18cf13 2644{
0b246afa 2645 struct btrfs_super_block *super_copy = fs_info->super_copy;
8f18cf13
CM
2646 struct btrfs_disk_key *disk_key;
2647 struct btrfs_chunk *chunk;
2648 u8 *ptr;
2649 int ret = 0;
2650 u32 num_stripes;
2651 u32 array_size;
2652 u32 len = 0;
2653 u32 cur;
2654 struct btrfs_key key;
2655
34441361 2656 mutex_lock(&fs_info->chunk_mutex);
8f18cf13
CM
2657 array_size = btrfs_super_sys_array_size(super_copy);
2658
2659 ptr = super_copy->sys_chunk_array;
2660 cur = 0;
2661
2662 while (cur < array_size) {
2663 disk_key = (struct btrfs_disk_key *)ptr;
2664 btrfs_disk_key_to_cpu(&key, disk_key);
2665
2666 len = sizeof(*disk_key);
2667
2668 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2669 chunk = (struct btrfs_chunk *)(ptr + len);
2670 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2671 len += btrfs_chunk_item_size(num_stripes);
2672 } else {
2673 ret = -EIO;
2674 break;
2675 }
408fbf19 2676 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
8f18cf13
CM
2677 key.offset == chunk_offset) {
2678 memmove(ptr, ptr + len, array_size - (cur + len));
2679 array_size -= len;
2680 btrfs_set_super_sys_array_size(super_copy, array_size);
2681 } else {
2682 ptr += len;
2683 cur += len;
2684 }
2685 }
34441361 2686 mutex_unlock(&fs_info->chunk_mutex);
8f18cf13
CM
2687 return ret;
2688}
2689
592d92ee
LB
2690static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2691 u64 logical, u64 length)
2692{
2693 struct extent_map_tree *em_tree;
2694 struct extent_map *em;
2695
2696 em_tree = &fs_info->mapping_tree.map_tree;
2697 read_lock(&em_tree->lock);
2698 em = lookup_extent_mapping(em_tree, logical, length);
2699 read_unlock(&em_tree->lock);
2700
2701 if (!em) {
2702 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2703 logical, length);
2704 return ERR_PTR(-EINVAL);
2705 }
2706
2707 if (em->start > logical || em->start + em->len < logical) {
2708 btrfs_crit(fs_info,
2709 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2710 logical, length, em->start, em->start + em->len);
2711 free_extent_map(em);
2712 return ERR_PTR(-EINVAL);
2713 }
2714
2715 /* callers are responsible for dropping em's ref. */
2716 return em;
2717}
2718
97aff912 2719int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
8f18cf13 2720{
97aff912 2721 struct btrfs_fs_info *fs_info = trans->fs_info;
8f18cf13
CM
2722 struct extent_map *em;
2723 struct map_lookup *map;
2196d6e8 2724 u64 dev_extent_len = 0;
47ab2a6c 2725 int i, ret = 0;
0b246afa 2726 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
8f18cf13 2727
592d92ee
LB
2728 em = get_chunk_map(fs_info, chunk_offset, 1);
2729 if (IS_ERR(em)) {
47ab2a6c
JB
2730 /*
2731 * This is a logic error, but we don't want to just rely on the
bb7ab3b9 2732 * user having built with ASSERT enabled, so if ASSERT doesn't
47ab2a6c
JB
2733 * do anything we still error out.
2734 */
2735 ASSERT(0);
592d92ee 2736 return PTR_ERR(em);
47ab2a6c 2737 }
95617d69 2738 map = em->map_lookup;
34441361 2739 mutex_lock(&fs_info->chunk_mutex);
451a2c13 2740 check_system_chunk(trans, map->type);
34441361 2741 mutex_unlock(&fs_info->chunk_mutex);
8f18cf13 2742
57ba4cb8
FM
2743 /*
2744 * Take the device list mutex to prevent races with the final phase of
2745 * a device replace operation that replaces the device object associated
2746 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2747 */
2748 mutex_lock(&fs_devices->device_list_mutex);
8f18cf13 2749 for (i = 0; i < map->num_stripes; i++) {
47ab2a6c 2750 struct btrfs_device *device = map->stripes[i].dev;
2196d6e8
MX
2751 ret = btrfs_free_dev_extent(trans, device,
2752 map->stripes[i].physical,
2753 &dev_extent_len);
47ab2a6c 2754 if (ret) {
57ba4cb8 2755 mutex_unlock(&fs_devices->device_list_mutex);
66642832 2756 btrfs_abort_transaction(trans, ret);
47ab2a6c
JB
2757 goto out;
2758 }
a061fc8d 2759
2196d6e8 2760 if (device->bytes_used > 0) {
34441361 2761 mutex_lock(&fs_info->chunk_mutex);
2196d6e8
MX
2762 btrfs_device_set_bytes_used(device,
2763 device->bytes_used - dev_extent_len);
a5ed45f8 2764 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
0b246afa 2765 btrfs_clear_space_info_full(fs_info);
34441361 2766 mutex_unlock(&fs_info->chunk_mutex);
2196d6e8 2767 }
a061fc8d 2768
dfe25020
CM
2769 if (map->stripes[i].dev) {
2770 ret = btrfs_update_device(trans, map->stripes[i].dev);
47ab2a6c 2771 if (ret) {
57ba4cb8 2772 mutex_unlock(&fs_devices->device_list_mutex);
66642832 2773 btrfs_abort_transaction(trans, ret);
47ab2a6c
JB
2774 goto out;
2775 }
dfe25020 2776 }
8f18cf13 2777 }
57ba4cb8
FM
2778 mutex_unlock(&fs_devices->device_list_mutex);
2779
f4208794 2780 ret = btrfs_free_chunk(trans, chunk_offset);
47ab2a6c 2781 if (ret) {
66642832 2782 btrfs_abort_transaction(trans, ret);
47ab2a6c
JB
2783 goto out;
2784 }
8f18cf13 2785
6bccf3ab 2786 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
1abe9b8a 2787
8f18cf13 2788 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
408fbf19 2789 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
47ab2a6c 2790 if (ret) {
66642832 2791 btrfs_abort_transaction(trans, ret);
47ab2a6c
JB
2792 goto out;
2793 }
8f18cf13
CM
2794 }
2795
5a98ec01 2796 ret = btrfs_remove_block_group(trans, chunk_offset, em);
47ab2a6c 2797 if (ret) {
66642832 2798 btrfs_abort_transaction(trans, ret);
47ab2a6c
JB
2799 goto out;
2800 }
2b82032c 2801
47ab2a6c 2802out:
2b82032c
YZ
2803 /* once for us */
2804 free_extent_map(em);
47ab2a6c
JB
2805 return ret;
2806}
2b82032c 2807
5b4aacef 2808static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
47ab2a6c 2809{
5b4aacef 2810 struct btrfs_root *root = fs_info->chunk_root;
19c4d2f9 2811 struct btrfs_trans_handle *trans;
47ab2a6c 2812 int ret;
2b82032c 2813
67c5e7d4
FM
2814 /*
2815 * Prevent races with automatic removal of unused block groups.
2816 * After we relocate and before we remove the chunk with offset
2817 * chunk_offset, automatic removal of the block group can kick in,
2818 * resulting in a failure when calling btrfs_remove_chunk() below.
2819 *
2820 * Make sure to acquire this mutex before doing a tree search (dev
2821 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2822 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2823 * we release the path used to search the chunk/dev tree and before
2824 * the current task acquires this mutex and calls us.
2825 */
a32bf9a3 2826 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
67c5e7d4 2827
0b246afa 2828 ret = btrfs_can_relocate(fs_info, chunk_offset);
47ab2a6c
JB
2829 if (ret)
2830 return -ENOSPC;
2831
2832 /* step one, relocate all the extents inside this chunk */
2ff7e61e 2833 btrfs_scrub_pause(fs_info);
0b246afa 2834 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2ff7e61e 2835 btrfs_scrub_continue(fs_info);
47ab2a6c
JB
2836 if (ret)
2837 return ret;
2838
75cb379d
JM
2839 /*
2840 * We add the kobjects here (and after forcing data chunk creation)
2841 * since relocation is the only place we'll create chunks of a new
2842 * type at runtime. The only place where we'll remove the last
2843 * chunk of a type is the call immediately below this one. Even
2844 * so, we're protected against races with the cleaner thread since
2845 * we're covered by the delete_unused_bgs_mutex.
2846 */
2847 btrfs_add_raid_kobjects(fs_info);
2848
19c4d2f9
CM
2849 trans = btrfs_start_trans_remove_block_group(root->fs_info,
2850 chunk_offset);
2851 if (IS_ERR(trans)) {
2852 ret = PTR_ERR(trans);
2853 btrfs_handle_fs_error(root->fs_info, ret, NULL);
2854 return ret;
2855 }
2856
47ab2a6c 2857 /*
19c4d2f9
CM
2858 * step two, delete the device extents and the
2859 * chunk tree entries
47ab2a6c 2860 */
97aff912 2861 ret = btrfs_remove_chunk(trans, chunk_offset);
3a45bb20 2862 btrfs_end_transaction(trans);
19c4d2f9 2863 return ret;
2b82032c
YZ
2864}
2865
2ff7e61e 2866static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
2b82032c 2867{
0b246afa 2868 struct btrfs_root *chunk_root = fs_info->chunk_root;
2b82032c
YZ
2869 struct btrfs_path *path;
2870 struct extent_buffer *leaf;
2871 struct btrfs_chunk *chunk;
2872 struct btrfs_key key;
2873 struct btrfs_key found_key;
2b82032c 2874 u64 chunk_type;
ba1bf481
JB
2875 bool retried = false;
2876 int failed = 0;
2b82032c
YZ
2877 int ret;
2878
2879 path = btrfs_alloc_path();
2880 if (!path)
2881 return -ENOMEM;
2882
ba1bf481 2883again:
2b82032c
YZ
2884 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2885 key.offset = (u64)-1;
2886 key.type = BTRFS_CHUNK_ITEM_KEY;
2887
2888 while (1) {
0b246afa 2889 mutex_lock(&fs_info->delete_unused_bgs_mutex);
2b82032c 2890 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
67c5e7d4 2891 if (ret < 0) {
0b246afa 2892 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2b82032c 2893 goto error;
67c5e7d4 2894 }
79787eaa 2895 BUG_ON(ret == 0); /* Corruption */
2b82032c
YZ
2896
2897 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2898 key.type);
67c5e7d4 2899 if (ret)
0b246afa 2900 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2b82032c
YZ
2901 if (ret < 0)
2902 goto error;
2903 if (ret > 0)
2904 break;
1a40e23b 2905
2b82032c
YZ
2906 leaf = path->nodes[0];
2907 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1a40e23b 2908
2b82032c
YZ
2909 chunk = btrfs_item_ptr(leaf, path->slots[0],
2910 struct btrfs_chunk);
2911 chunk_type = btrfs_chunk_type(leaf, chunk);
b3b4aa74 2912 btrfs_release_path(path);
8f18cf13 2913
2b82032c 2914 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
0b246afa 2915 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
ba1bf481
JB
2916 if (ret == -ENOSPC)
2917 failed++;
14586651
HS
2918 else
2919 BUG_ON(ret);
2b82032c 2920 }
0b246afa 2921 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
8f18cf13 2922
2b82032c
YZ
2923 if (found_key.offset == 0)
2924 break;
2925 key.offset = found_key.offset - 1;
2926 }
2927 ret = 0;
ba1bf481
JB
2928 if (failed && !retried) {
2929 failed = 0;
2930 retried = true;
2931 goto again;
fae7f21c 2932 } else if (WARN_ON(failed && retried)) {
ba1bf481
JB
2933 ret = -ENOSPC;
2934 }
2b82032c
YZ
2935error:
2936 btrfs_free_path(path);
2937 return ret;
8f18cf13
CM
2938}
2939
a6f93c71
LB
2940/*
2941 * return 1 : allocate a data chunk successfully,
2942 * return <0: errors during allocating a data chunk,
2943 * return 0 : no need to allocate a data chunk.
2944 */
2945static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
2946 u64 chunk_offset)
2947{
2948 struct btrfs_block_group_cache *cache;
2949 u64 bytes_used;
2950 u64 chunk_type;
2951
2952 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2953 ASSERT(cache);
2954 chunk_type = cache->flags;
2955 btrfs_put_block_group(cache);
2956
2957 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
2958 spin_lock(&fs_info->data_sinfo->lock);
2959 bytes_used = fs_info->data_sinfo->bytes_used;
2960 spin_unlock(&fs_info->data_sinfo->lock);
2961
2962 if (!bytes_used) {
2963 struct btrfs_trans_handle *trans;
2964 int ret;
2965
2966 trans = btrfs_join_transaction(fs_info->tree_root);
2967 if (IS_ERR(trans))
2968 return PTR_ERR(trans);
2969
43a7e99d 2970 ret = btrfs_force_chunk_alloc(trans,
a6f93c71
LB
2971 BTRFS_BLOCK_GROUP_DATA);
2972 btrfs_end_transaction(trans);
2973 if (ret < 0)
2974 return ret;
2975
75cb379d
JM
2976 btrfs_add_raid_kobjects(fs_info);
2977
a6f93c71
LB
2978 return 1;
2979 }
2980 }
2981 return 0;
2982}
2983
6bccf3ab 2984static int insert_balance_item(struct btrfs_fs_info *fs_info,
0940ebf6
ID
2985 struct btrfs_balance_control *bctl)
2986{
6bccf3ab 2987 struct btrfs_root *root = fs_info->tree_root;
0940ebf6
ID
2988 struct btrfs_trans_handle *trans;
2989 struct btrfs_balance_item *item;
2990 struct btrfs_disk_balance_args disk_bargs;
2991 struct btrfs_path *path;
2992 struct extent_buffer *leaf;
2993 struct btrfs_key key;
2994 int ret, err;
2995
2996 path = btrfs_alloc_path();
2997 if (!path)
2998 return -ENOMEM;
2999
3000 trans = btrfs_start_transaction(root, 0);
3001 if (IS_ERR(trans)) {
3002 btrfs_free_path(path);
3003 return PTR_ERR(trans);
3004 }
3005
3006 key.objectid = BTRFS_BALANCE_OBJECTID;
c479cb4f 3007 key.type = BTRFS_TEMPORARY_ITEM_KEY;
0940ebf6
ID
3008 key.offset = 0;
3009
3010 ret = btrfs_insert_empty_item(trans, root, path, &key,
3011 sizeof(*item));
3012 if (ret)
3013 goto out;
3014
3015 leaf = path->nodes[0];
3016 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3017
b159fa28 3018 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
0940ebf6
ID
3019
3020 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3021 btrfs_set_balance_data(leaf, item, &disk_bargs);
3022 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3023 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3024 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3025 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3026
3027 btrfs_set_balance_flags(leaf, item, bctl->flags);
3028
3029 btrfs_mark_buffer_dirty(leaf);
3030out:
3031 btrfs_free_path(path);
3a45bb20 3032 err = btrfs_commit_transaction(trans);
0940ebf6
ID
3033 if (err && !ret)
3034 ret = err;
3035 return ret;
3036}
3037
6bccf3ab 3038static int del_balance_item(struct btrfs_fs_info *fs_info)
0940ebf6 3039{
6bccf3ab 3040 struct btrfs_root *root = fs_info->tree_root;
0940ebf6
ID
3041 struct btrfs_trans_handle *trans;
3042 struct btrfs_path *path;
3043 struct btrfs_key key;
3044 int ret, err;
3045
3046 path = btrfs_alloc_path();
3047 if (!path)
3048 return -ENOMEM;
3049
3050 trans = btrfs_start_transaction(root, 0);
3051 if (IS_ERR(trans)) {
3052 btrfs_free_path(path);
3053 return PTR_ERR(trans);
3054 }
3055
3056 key.objectid = BTRFS_BALANCE_OBJECTID;
c479cb4f 3057 key.type = BTRFS_TEMPORARY_ITEM_KEY;
0940ebf6
ID
3058 key.offset = 0;
3059
3060 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3061 if (ret < 0)
3062 goto out;
3063 if (ret > 0) {
3064 ret = -ENOENT;
3065 goto out;
3066 }
3067
3068 ret = btrfs_del_item(trans, root, path);
3069out:
3070 btrfs_free_path(path);
3a45bb20 3071 err = btrfs_commit_transaction(trans);
0940ebf6
ID
3072 if (err && !ret)
3073 ret = err;
3074 return ret;
3075}
3076
59641015
ID
3077/*
3078 * This is a heuristic used to reduce the number of chunks balanced on
3079 * resume after balance was interrupted.
3080 */
3081static void update_balance_args(struct btrfs_balance_control *bctl)
3082{
3083 /*
3084 * Turn on soft mode for chunk types that were being converted.
3085 */
3086 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3087 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3088 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3089 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3090 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3091 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3092
3093 /*
3094 * Turn on usage filter if is not already used. The idea is
3095 * that chunks that we have already balanced should be
3096 * reasonably full. Don't do it for chunks that are being
3097 * converted - that will keep us from relocating unconverted
3098 * (albeit full) chunks.
3099 */
3100 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
bc309467 3101 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
59641015
ID
3102 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3103 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3104 bctl->data.usage = 90;
3105 }
3106 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
bc309467 3107 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
59641015
ID
3108 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3109 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3110 bctl->sys.usage = 90;
3111 }
3112 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
bc309467 3113 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
59641015
ID
3114 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3115 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3116 bctl->meta.usage = 90;
3117 }
3118}
3119
149196a2
DS
3120/*
3121 * Clear the balance status in fs_info and delete the balance item from disk.
3122 */
3123static void reset_balance_state(struct btrfs_fs_info *fs_info)
c9e9f97b
ID
3124{
3125 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
149196a2 3126 int ret;
c9e9f97b
ID
3127
3128 BUG_ON(!fs_info->balance_ctl);
3129
3130 spin_lock(&fs_info->balance_lock);
3131 fs_info->balance_ctl = NULL;
3132 spin_unlock(&fs_info->balance_lock);
3133
3134 kfree(bctl);
149196a2
DS
3135 ret = del_balance_item(fs_info);
3136 if (ret)
3137 btrfs_handle_fs_error(fs_info, ret, NULL);
c9e9f97b
ID
3138}
3139
ed25e9b2
ID
3140/*
3141 * Balance filters. Return 1 if chunk should be filtered out
3142 * (should not be balanced).
3143 */
899c81ea 3144static int chunk_profiles_filter(u64 chunk_type,
ed25e9b2
ID
3145 struct btrfs_balance_args *bargs)
3146{
899c81ea
ID
3147 chunk_type = chunk_to_extended(chunk_type) &
3148 BTRFS_EXTENDED_PROFILE_MASK;
ed25e9b2 3149
899c81ea 3150 if (bargs->profiles & chunk_type)
ed25e9b2
ID
3151 return 0;
3152
3153 return 1;
3154}
3155
dba72cb3 3156static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
5ce5b3c0 3157 struct btrfs_balance_args *bargs)
bc309467
DS
3158{
3159 struct btrfs_block_group_cache *cache;
3160 u64 chunk_used;
3161 u64 user_thresh_min;
3162 u64 user_thresh_max;
3163 int ret = 1;
3164
3165 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3166 chunk_used = btrfs_block_group_used(&cache->item);
3167
3168 if (bargs->usage_min == 0)
3169 user_thresh_min = 0;
3170 else
3171 user_thresh_min = div_factor_fine(cache->key.offset,
3172 bargs->usage_min);
3173
3174 if (bargs->usage_max == 0)
3175 user_thresh_max = 1;
3176 else if (bargs->usage_max > 100)
3177 user_thresh_max = cache->key.offset;
3178 else
3179 user_thresh_max = div_factor_fine(cache->key.offset,
3180 bargs->usage_max);
3181
3182 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3183 ret = 0;
3184
3185 btrfs_put_block_group(cache);
3186 return ret;
3187}
3188
dba72cb3 3189static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
bc309467 3190 u64 chunk_offset, struct btrfs_balance_args *bargs)
5ce5b3c0
ID
3191{
3192 struct btrfs_block_group_cache *cache;
3193 u64 chunk_used, user_thresh;
3194 int ret = 1;
3195
3196 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3197 chunk_used = btrfs_block_group_used(&cache->item);
3198
bc309467 3199 if (bargs->usage_min == 0)
3e39cea6 3200 user_thresh = 1;
a105bb88
ID
3201 else if (bargs->usage > 100)
3202 user_thresh = cache->key.offset;
3203 else
3204 user_thresh = div_factor_fine(cache->key.offset,
3205 bargs->usage);
3206
5ce5b3c0
ID
3207 if (chunk_used < user_thresh)
3208 ret = 0;
3209
3210 btrfs_put_block_group(cache);
3211 return ret;
3212}
3213
409d404b
ID
3214static int chunk_devid_filter(struct extent_buffer *leaf,
3215 struct btrfs_chunk *chunk,
3216 struct btrfs_balance_args *bargs)
3217{
3218 struct btrfs_stripe *stripe;
3219 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3220 int i;
3221
3222 for (i = 0; i < num_stripes; i++) {
3223 stripe = btrfs_stripe_nr(chunk, i);
3224 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3225 return 0;
3226 }
3227
3228 return 1;
3229}
3230
94e60d5a
ID
3231/* [pstart, pend) */
3232static int chunk_drange_filter(struct extent_buffer *leaf,
3233 struct btrfs_chunk *chunk,
94e60d5a
ID
3234 struct btrfs_balance_args *bargs)
3235{
3236 struct btrfs_stripe *stripe;
3237 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3238 u64 stripe_offset;
3239 u64 stripe_length;
3240 int factor;
3241 int i;
3242
3243 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3244 return 0;
3245
3246 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
53b381b3
DW
3247 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3248 factor = num_stripes / 2;
3249 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3250 factor = num_stripes - 1;
3251 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3252 factor = num_stripes - 2;
3253 } else {
3254 factor = num_stripes;
3255 }
94e60d5a
ID
3256
3257 for (i = 0; i < num_stripes; i++) {
3258 stripe = btrfs_stripe_nr(chunk, i);
3259 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3260 continue;
3261
3262 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3263 stripe_length = btrfs_chunk_length(leaf, chunk);
b8b93add 3264 stripe_length = div_u64(stripe_length, factor);
94e60d5a
ID
3265
3266 if (stripe_offset < bargs->pend &&
3267 stripe_offset + stripe_length > bargs->pstart)
3268 return 0;
3269 }
3270
3271 return 1;
3272}
3273
ea67176a
ID
3274/* [vstart, vend) */
3275static int chunk_vrange_filter(struct extent_buffer *leaf,
3276 struct btrfs_chunk *chunk,
3277 u64 chunk_offset,
3278 struct btrfs_balance_args *bargs)
3279{
3280 if (chunk_offset < bargs->vend &&
3281 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3282 /* at least part of the chunk is inside this vrange */
3283 return 0;
3284
3285 return 1;
3286}
3287
dee32d0a
GAP
3288static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3289 struct btrfs_chunk *chunk,
3290 struct btrfs_balance_args *bargs)
3291{
3292 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3293
3294 if (bargs->stripes_min <= num_stripes
3295 && num_stripes <= bargs->stripes_max)
3296 return 0;
3297
3298 return 1;
3299}
3300
899c81ea 3301static int chunk_soft_convert_filter(u64 chunk_type,
cfa4c961
ID
3302 struct btrfs_balance_args *bargs)
3303{
3304 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3305 return 0;
3306
899c81ea
ID
3307 chunk_type = chunk_to_extended(chunk_type) &
3308 BTRFS_EXTENDED_PROFILE_MASK;
cfa4c961 3309
899c81ea 3310 if (bargs->target == chunk_type)
cfa4c961
ID
3311 return 1;
3312
3313 return 0;
3314}
3315
2ff7e61e 3316static int should_balance_chunk(struct btrfs_fs_info *fs_info,
f43ffb60
ID
3317 struct extent_buffer *leaf,
3318 struct btrfs_chunk *chunk, u64 chunk_offset)
3319{
0b246afa 3320 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
f43ffb60
ID
3321 struct btrfs_balance_args *bargs = NULL;
3322 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3323
3324 /* type filter */
3325 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3326 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3327 return 0;
3328 }
3329
3330 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3331 bargs = &bctl->data;
3332 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3333 bargs = &bctl->sys;
3334 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3335 bargs = &bctl->meta;
3336
ed25e9b2
ID
3337 /* profiles filter */
3338 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3339 chunk_profiles_filter(chunk_type, bargs)) {
3340 return 0;
5ce5b3c0
ID
3341 }
3342
3343 /* usage filter */
3344 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
0b246afa 3345 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
5ce5b3c0 3346 return 0;
bc309467 3347 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
0b246afa 3348 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
bc309467 3349 return 0;
409d404b
ID
3350 }
3351
3352 /* devid filter */
3353 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3354 chunk_devid_filter(leaf, chunk, bargs)) {
3355 return 0;
94e60d5a
ID
3356 }
3357
3358 /* drange filter, makes sense only with devid filter */
3359 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
e4ff5fb5 3360 chunk_drange_filter(leaf, chunk, bargs)) {
94e60d5a 3361 return 0;
ea67176a
ID
3362 }
3363
3364 /* vrange filter */
3365 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3366 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3367 return 0;
ed25e9b2
ID
3368 }
3369
dee32d0a
GAP
3370 /* stripes filter */
3371 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3372 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3373 return 0;
3374 }
3375
cfa4c961
ID
3376 /* soft profile changing mode */
3377 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3378 chunk_soft_convert_filter(chunk_type, bargs)) {
3379 return 0;
3380 }
3381
7d824b6f
DS
3382 /*
3383 * limited by count, must be the last filter
3384 */
3385 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3386 if (bargs->limit == 0)
3387 return 0;
3388 else
3389 bargs->limit--;
12907fc7
DS
3390 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3391 /*
3392 * Same logic as the 'limit' filter; the minimum cannot be
01327610 3393 * determined here because we do not have the global information
12907fc7
DS
3394 * about the count of all chunks that satisfy the filters.
3395 */
3396 if (bargs->limit_max == 0)
3397 return 0;
3398 else
3399 bargs->limit_max--;
7d824b6f
DS
3400 }
3401
f43ffb60
ID
3402 return 1;
3403}
3404
c9e9f97b 3405static int __btrfs_balance(struct btrfs_fs_info *fs_info)
ec44a35c 3406{
19a39dce 3407 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
c9e9f97b
ID
3408 struct btrfs_root *chunk_root = fs_info->chunk_root;
3409 struct btrfs_root *dev_root = fs_info->dev_root;
3410 struct list_head *devices;
ec44a35c
CM
3411 struct btrfs_device *device;
3412 u64 old_size;
3413 u64 size_to_free;
12907fc7 3414 u64 chunk_type;
f43ffb60 3415 struct btrfs_chunk *chunk;
5a488b9d 3416 struct btrfs_path *path = NULL;
ec44a35c 3417 struct btrfs_key key;
ec44a35c 3418 struct btrfs_key found_key;
c9e9f97b 3419 struct btrfs_trans_handle *trans;
f43ffb60
ID
3420 struct extent_buffer *leaf;
3421 int slot;
c9e9f97b
ID
3422 int ret;
3423 int enospc_errors = 0;
19a39dce 3424 bool counting = true;
12907fc7 3425 /* The single value limit and min/max limits use the same bytes in the */
7d824b6f
DS
3426 u64 limit_data = bctl->data.limit;
3427 u64 limit_meta = bctl->meta.limit;
3428 u64 limit_sys = bctl->sys.limit;
12907fc7
DS
3429 u32 count_data = 0;
3430 u32 count_meta = 0;
3431 u32 count_sys = 0;
2c9fe835 3432 int chunk_reserved = 0;
ec44a35c 3433
ec44a35c 3434 /* step one make some room on all the devices */
c9e9f97b 3435 devices = &fs_info->fs_devices->devices;
c6e30871 3436 list_for_each_entry(device, devices, dev_list) {
7cc8e58d 3437 old_size = btrfs_device_get_total_bytes(device);
ec44a35c 3438 size_to_free = div_factor(old_size, 1);
ee22184b 3439 size_to_free = min_t(u64, size_to_free, SZ_1M);
ebbede42 3440 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
7cc8e58d
MX
3441 btrfs_device_get_total_bytes(device) -
3442 btrfs_device_get_bytes_used(device) > size_to_free ||
401e29c1 3443 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
ec44a35c
CM
3444 continue;
3445
3446 ret = btrfs_shrink_device(device, old_size - size_to_free);
ba1bf481
JB
3447 if (ret == -ENOSPC)
3448 break;
5a488b9d
LB
3449 if (ret) {
3450 /* btrfs_shrink_device never returns ret > 0 */
3451 WARN_ON(ret > 0);
3452 goto error;
3453 }
ec44a35c 3454
a22285a6 3455 trans = btrfs_start_transaction(dev_root, 0);
5a488b9d
LB
3456 if (IS_ERR(trans)) {
3457 ret = PTR_ERR(trans);
3458 btrfs_info_in_rcu(fs_info,
3459 "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3460 rcu_str_deref(device->name), ret,
3461 old_size, old_size - size_to_free);
3462 goto error;
3463 }
ec44a35c
CM
3464
3465 ret = btrfs_grow_device(trans, device, old_size);
5a488b9d 3466 if (ret) {
3a45bb20 3467 btrfs_end_transaction(trans);
5a488b9d
LB
3468 /* btrfs_grow_device never returns ret > 0 */
3469 WARN_ON(ret > 0);
3470 btrfs_info_in_rcu(fs_info,
3471 "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3472 rcu_str_deref(device->name), ret,
3473 old_size, old_size - size_to_free);
3474 goto error;
3475 }
ec44a35c 3476
3a45bb20 3477 btrfs_end_transaction(trans);
ec44a35c
CM
3478 }
3479
3480 /* step two, relocate all the chunks */
3481 path = btrfs_alloc_path();
17e9f796
MF
3482 if (!path) {
3483 ret = -ENOMEM;
3484 goto error;
3485 }
19a39dce
ID
3486
3487 /* zero out stat counters */
3488 spin_lock(&fs_info->balance_lock);
3489 memset(&bctl->stat, 0, sizeof(bctl->stat));
3490 spin_unlock(&fs_info->balance_lock);
3491again:
7d824b6f 3492 if (!counting) {
12907fc7
DS
3493 /*
3494 * The single value limit and min/max limits use the same bytes
3495 * in the
3496 */
7d824b6f
DS
3497 bctl->data.limit = limit_data;
3498 bctl->meta.limit = limit_meta;
3499 bctl->sys.limit = limit_sys;
3500 }
ec44a35c
CM
3501 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3502 key.offset = (u64)-1;
3503 key.type = BTRFS_CHUNK_ITEM_KEY;
3504
d397712b 3505 while (1) {
19a39dce 3506 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
a7e99c69 3507 atomic_read(&fs_info->balance_cancel_req)) {
837d5b6e
ID
3508 ret = -ECANCELED;
3509 goto error;
3510 }
3511
67c5e7d4 3512 mutex_lock(&fs_info->delete_unused_bgs_mutex);
ec44a35c 3513 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
67c5e7d4
FM
3514 if (ret < 0) {
3515 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
ec44a35c 3516 goto error;
67c5e7d4 3517 }
ec44a35c
CM
3518
3519 /*
3520 * this shouldn't happen, it means the last relocate
3521 * failed
3522 */
3523 if (ret == 0)
c9e9f97b 3524 BUG(); /* FIXME break ? */
ec44a35c
CM
3525
3526 ret = btrfs_previous_item(chunk_root, path, 0,
3527 BTRFS_CHUNK_ITEM_KEY);
c9e9f97b 3528 if (ret) {
67c5e7d4 3529 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
c9e9f97b 3530 ret = 0;
ec44a35c 3531 break;
c9e9f97b 3532 }
7d9eb12c 3533
f43ffb60
ID
3534 leaf = path->nodes[0];
3535 slot = path->slots[0];
3536 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7d9eb12c 3537
67c5e7d4
FM
3538 if (found_key.objectid != key.objectid) {
3539 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
ec44a35c 3540 break;
67c5e7d4 3541 }
7d9eb12c 3542
f43ffb60 3543 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
12907fc7 3544 chunk_type = btrfs_chunk_type(leaf, chunk);
f43ffb60 3545
19a39dce
ID
3546 if (!counting) {
3547 spin_lock(&fs_info->balance_lock);
3548 bctl->stat.considered++;
3549 spin_unlock(&fs_info->balance_lock);
3550 }
3551
2ff7e61e 3552 ret = should_balance_chunk(fs_info, leaf, chunk,
f43ffb60 3553 found_key.offset);
2c9fe835 3554
b3b4aa74 3555 btrfs_release_path(path);
67c5e7d4
FM
3556 if (!ret) {
3557 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
f43ffb60 3558 goto loop;
67c5e7d4 3559 }
f43ffb60 3560
19a39dce 3561 if (counting) {
67c5e7d4 3562 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
19a39dce
ID
3563 spin_lock(&fs_info->balance_lock);
3564 bctl->stat.expected++;
3565 spin_unlock(&fs_info->balance_lock);
12907fc7
DS
3566
3567 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3568 count_data++;
3569 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3570 count_sys++;
3571 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3572 count_meta++;
3573
3574 goto loop;
3575 }
3576
3577 /*
3578 * Apply limit_min filter, no need to check if the LIMITS
3579 * filter is used, limit_min is 0 by default
3580 */
3581 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3582 count_data < bctl->data.limit_min)
3583 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3584 count_meta < bctl->meta.limit_min)
3585 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3586 count_sys < bctl->sys.limit_min)) {
3587 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
19a39dce
ID
3588 goto loop;
3589 }
3590
a6f93c71
LB
3591 if (!chunk_reserved) {
3592 /*
3593 * We may be relocating the only data chunk we have,
3594 * which could potentially end up with losing data's
3595 * raid profile, so lets allocate an empty one in
3596 * advance.
3597 */
3598 ret = btrfs_may_alloc_data_chunk(fs_info,
3599 found_key.offset);
2c9fe835
ZL
3600 if (ret < 0) {
3601 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3602 goto error;
a6f93c71
LB
3603 } else if (ret == 1) {
3604 chunk_reserved = 1;
2c9fe835 3605 }
2c9fe835
ZL
3606 }
3607
5b4aacef 3608 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
67c5e7d4 3609 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
508794eb
JB
3610 if (ret && ret != -ENOSPC)
3611 goto error;
19a39dce 3612 if (ret == -ENOSPC) {
c9e9f97b 3613 enospc_errors++;
19a39dce
ID
3614 } else {
3615 spin_lock(&fs_info->balance_lock);
3616 bctl->stat.completed++;
3617 spin_unlock(&fs_info->balance_lock);
3618 }
f43ffb60 3619loop:
795a3321
ID
3620 if (found_key.offset == 0)
3621 break;
ba1bf481 3622 key.offset = found_key.offset - 1;
ec44a35c 3623 }
c9e9f97b 3624
19a39dce
ID
3625 if (counting) {
3626 btrfs_release_path(path);
3627 counting = false;
3628 goto again;
3629 }
ec44a35c
CM
3630error:
3631 btrfs_free_path(path);
c9e9f97b 3632 if (enospc_errors) {
efe120a0 3633 btrfs_info(fs_info, "%d enospc errors during balance",
5d163e0e 3634 enospc_errors);
c9e9f97b
ID
3635 if (!ret)
3636 ret = -ENOSPC;
3637 }
3638
ec44a35c
CM
3639 return ret;
3640}
3641
0c460c0d
ID
3642/**
3643 * alloc_profile_is_valid - see if a given profile is valid and reduced
3644 * @flags: profile to validate
3645 * @extended: if true @flags is treated as an extended profile
3646 */
3647static int alloc_profile_is_valid(u64 flags, int extended)
3648{
3649 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3650 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3651
3652 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3653
3654 /* 1) check that all other bits are zeroed */
3655 if (flags & ~mask)
3656 return 0;
3657
3658 /* 2) see if profile is reduced */
3659 if (flags == 0)
3660 return !extended; /* "0" is valid for usual profiles */
3661
3662 /* true if exactly one bit set */
3663 return (flags & (flags - 1)) == 0;
3664}
3665
837d5b6e
ID
3666static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3667{
a7e99c69
ID
3668 /* cancel requested || normal exit path */
3669 return atomic_read(&fs_info->balance_cancel_req) ||
3670 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3671 atomic_read(&fs_info->balance_cancel_req) == 0);
837d5b6e
ID
3672}
3673
bdcd3c97
AM
3674/* Non-zero return value signifies invalidity */
3675static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3676 u64 allowed)
3677{
3678 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3679 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3680 (bctl_arg->target & ~allowed)));
3681}
3682
c9e9f97b 3683/*
dccdb07b 3684 * Should be called with balance mutexe held
c9e9f97b 3685 */
6fcf6e2b
DS
3686int btrfs_balance(struct btrfs_fs_info *fs_info,
3687 struct btrfs_balance_control *bctl,
c9e9f97b
ID
3688 struct btrfs_ioctl_balance_args *bargs)
3689{
14506127 3690 u64 meta_target, data_target;
f43ffb60 3691 u64 allowed;
e4837f8f 3692 int mixed = 0;
c9e9f97b 3693 int ret;
8dabb742 3694 u64 num_devices;
de98ced9 3695 unsigned seq;
c9e9f97b 3696
837d5b6e 3697 if (btrfs_fs_closing(fs_info) ||
a7e99c69
ID
3698 atomic_read(&fs_info->balance_pause_req) ||
3699 atomic_read(&fs_info->balance_cancel_req)) {
c9e9f97b
ID
3700 ret = -EINVAL;
3701 goto out;
3702 }
3703
e4837f8f
ID
3704 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3705 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3706 mixed = 1;
3707
f43ffb60
ID
3708 /*
3709 * In case of mixed groups both data and meta should be picked,
3710 * and identical options should be given for both of them.
3711 */
e4837f8f
ID
3712 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3713 if (mixed && (bctl->flags & allowed)) {
f43ffb60
ID
3714 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3715 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3716 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
5d163e0e 3717 btrfs_err(fs_info,
6dac13f8 3718 "balance: mixed groups data and metadata options must be the same");
f43ffb60
ID
3719 ret = -EINVAL;
3720 goto out;
3721 }
3722 }
3723
8dabb742 3724 num_devices = fs_info->fs_devices->num_devices;
7e79cb86 3725 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
8dabb742
SB
3726 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3727 BUG_ON(num_devices < 1);
3728 num_devices--;
3729 }
7e79cb86 3730 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
88be159c
AH
3731 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3732 if (num_devices > 1)
e4d8ec0f 3733 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
8250dabe
AP
3734 if (num_devices > 2)
3735 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3736 if (num_devices > 3)
3737 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3738 BTRFS_BLOCK_GROUP_RAID6);
bdcd3c97 3739 if (validate_convert_profile(&bctl->data, allowed)) {
6dac13f8
AJ
3740 int index = btrfs_bg_flags_to_raid_index(bctl->data.target);
3741
5d163e0e 3742 btrfs_err(fs_info,
6dac13f8
AJ
3743 "balance: invalid convert data profile %s",
3744 get_raid_name(index));
e4d8ec0f
ID
3745 ret = -EINVAL;
3746 goto out;
3747 }
bdcd3c97 3748 if (validate_convert_profile(&bctl->meta, allowed)) {
6dac13f8
AJ
3749 int index = btrfs_bg_flags_to_raid_index(bctl->meta.target);
3750
efe120a0 3751 btrfs_err(fs_info,
6dac13f8
AJ
3752 "balance: invalid convert metadata profile %s",
3753 get_raid_name(index));
e4d8ec0f
ID
3754 ret = -EINVAL;
3755 goto out;
3756 }
bdcd3c97 3757 if (validate_convert_profile(&bctl->sys, allowed)) {
6dac13f8
AJ
3758 int index = btrfs_bg_flags_to_raid_index(bctl->sys.target);
3759
efe120a0 3760 btrfs_err(fs_info,
6dac13f8
AJ
3761 "balance: invalid convert system profile %s",
3762 get_raid_name(index));
e4d8ec0f
ID
3763 ret = -EINVAL;
3764 goto out;
3765 }
3766
e4d8ec0f
ID
3767 /* allow to reduce meta or sys integrity only if force set */
3768 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
53b381b3
DW
3769 BTRFS_BLOCK_GROUP_RAID10 |
3770 BTRFS_BLOCK_GROUP_RAID5 |
3771 BTRFS_BLOCK_GROUP_RAID6;
de98ced9
MX
3772 do {
3773 seq = read_seqbegin(&fs_info->profiles_lock);
3774
3775 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3776 (fs_info->avail_system_alloc_bits & allowed) &&
3777 !(bctl->sys.target & allowed)) ||
3778 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3779 (fs_info->avail_metadata_alloc_bits & allowed) &&
3780 !(bctl->meta.target & allowed))) {
3781 if (bctl->flags & BTRFS_BALANCE_FORCE) {
5d163e0e 3782 btrfs_info(fs_info,
6dac13f8 3783 "balance: force reducing metadata integrity");
de98ced9 3784 } else {
5d163e0e 3785 btrfs_err(fs_info,
6dac13f8 3786 "balance: reduces metadata integrity, use --force if you want this");
de98ced9
MX
3787 ret = -EINVAL;
3788 goto out;
3789 }
e4d8ec0f 3790 }
de98ced9 3791 } while (read_seqretry(&fs_info->profiles_lock, seq));
e4d8ec0f 3792
14506127
AB
3793 /* if we're not converting, the target field is uninitialized */
3794 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3795 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
3796 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3797 bctl->data.target : fs_info->avail_data_alloc_bits;
3798 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
3799 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
6dac13f8
AJ
3800 int meta_index = btrfs_bg_flags_to_raid_index(meta_target);
3801 int data_index = btrfs_bg_flags_to_raid_index(data_target);
3802
ee592d07 3803 btrfs_warn(fs_info,
6dac13f8
AJ
3804 "balance: metadata profile %s has lower redundancy than data profile %s",
3805 get_raid_name(meta_index), get_raid_name(data_index));
ee592d07
ST
3806 }
3807
6bccf3ab 3808 ret = insert_balance_item(fs_info, bctl);
59641015 3809 if (ret && ret != -EEXIST)
0940ebf6
ID
3810 goto out;
3811
59641015
ID
3812 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3813 BUG_ON(ret == -EEXIST);
833aae18
DS
3814 BUG_ON(fs_info->balance_ctl);
3815 spin_lock(&fs_info->balance_lock);
3816 fs_info->balance_ctl = bctl;
3817 spin_unlock(&fs_info->balance_lock);
59641015
ID
3818 } else {
3819 BUG_ON(ret != -EEXIST);
3820 spin_lock(&fs_info->balance_lock);
3821 update_balance_args(bctl);
3822 spin_unlock(&fs_info->balance_lock);
3823 }
c9e9f97b 3824
3009a62f
DS
3825 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
3826 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
c9e9f97b
ID
3827 mutex_unlock(&fs_info->balance_mutex);
3828
3829 ret = __btrfs_balance(fs_info);
3830
3831 mutex_lock(&fs_info->balance_mutex);
3009a62f 3832 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
c9e9f97b
ID
3833
3834 if (bargs) {
3835 memset(bargs, 0, sizeof(*bargs));
008ef096 3836 btrfs_update_ioctl_balance_args(fs_info, bargs);
c9e9f97b
ID
3837 }
3838
3a01aa7a
ID
3839 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3840 balance_need_close(fs_info)) {
149196a2 3841 reset_balance_state(fs_info);
a17c95df 3842 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3a01aa7a
ID
3843 }
3844
837d5b6e 3845 wake_up(&fs_info->balance_wait_q);
c9e9f97b
ID
3846
3847 return ret;
3848out:
59641015 3849 if (bctl->flags & BTRFS_BALANCE_RESUME)
149196a2 3850 reset_balance_state(fs_info);
a17c95df 3851 else
59641015 3852 kfree(bctl);
a17c95df
DS
3853 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3854
59641015
ID
3855 return ret;
3856}
3857
3858static int balance_kthread(void *data)
3859{
2b6ba629 3860 struct btrfs_fs_info *fs_info = data;
9555c6c1 3861 int ret = 0;
59641015 3862
59641015 3863 mutex_lock(&fs_info->balance_mutex);
2b6ba629 3864 if (fs_info->balance_ctl) {
6dac13f8 3865 btrfs_info(fs_info, "balance: resuming");
6fcf6e2b 3866 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
9555c6c1 3867 }
59641015 3868 mutex_unlock(&fs_info->balance_mutex);
2b6ba629 3869
59641015
ID
3870 return ret;
3871}
3872
2b6ba629
ID
3873int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3874{
3875 struct task_struct *tsk;
3876
1354e1a1 3877 mutex_lock(&fs_info->balance_mutex);
2b6ba629 3878 if (!fs_info->balance_ctl) {
1354e1a1 3879 mutex_unlock(&fs_info->balance_mutex);
2b6ba629
ID
3880 return 0;
3881 }
1354e1a1 3882 mutex_unlock(&fs_info->balance_mutex);
2b6ba629 3883
3cdde224 3884 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
6dac13f8 3885 btrfs_info(fs_info, "balance: resume skipped");
2b6ba629
ID
3886 return 0;
3887 }
3888
02ee654d
AJ
3889 /*
3890 * A ro->rw remount sequence should continue with the paused balance
3891 * regardless of who pauses it, system or the user as of now, so set
3892 * the resume flag.
3893 */
3894 spin_lock(&fs_info->balance_lock);
3895 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
3896 spin_unlock(&fs_info->balance_lock);
3897
2b6ba629 3898 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
cd633972 3899 return PTR_ERR_OR_ZERO(tsk);
2b6ba629
ID
3900}
3901
68310a5e 3902int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
59641015 3903{
59641015
ID
3904 struct btrfs_balance_control *bctl;
3905 struct btrfs_balance_item *item;
3906 struct btrfs_disk_balance_args disk_bargs;
3907 struct btrfs_path *path;
3908 struct extent_buffer *leaf;
3909 struct btrfs_key key;
3910 int ret;
3911
3912 path = btrfs_alloc_path();
3913 if (!path)
3914 return -ENOMEM;
3915
59641015 3916 key.objectid = BTRFS_BALANCE_OBJECTID;
c479cb4f 3917 key.type = BTRFS_TEMPORARY_ITEM_KEY;
59641015
ID
3918 key.offset = 0;
3919
68310a5e 3920 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
59641015 3921 if (ret < 0)
68310a5e 3922 goto out;
59641015
ID
3923 if (ret > 0) { /* ret = -ENOENT; */
3924 ret = 0;
68310a5e
ID
3925 goto out;
3926 }
3927
3928 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3929 if (!bctl) {
3930 ret = -ENOMEM;
3931 goto out;
59641015
ID
3932 }
3933
3934 leaf = path->nodes[0];
3935 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3936
68310a5e
ID
3937 bctl->flags = btrfs_balance_flags(leaf, item);
3938 bctl->flags |= BTRFS_BALANCE_RESUME;
59641015
ID
3939
3940 btrfs_balance_data(leaf, item, &disk_bargs);
3941 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
3942 btrfs_balance_meta(leaf, item, &disk_bargs);
3943 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
3944 btrfs_balance_sys(leaf, item, &disk_bargs);
3945 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
3946
eee95e3f
DS
3947 /*
3948 * This should never happen, as the paused balance state is recovered
3949 * during mount without any chance of other exclusive ops to collide.
3950 *
3951 * This gives the exclusive op status to balance and keeps in paused
3952 * state until user intervention (cancel or umount). If the ownership
3953 * cannot be assigned, show a message but do not fail. The balance
3954 * is in a paused state and must have fs_info::balance_ctl properly
3955 * set up.
3956 */
3957 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
3958 btrfs_warn(fs_info,
6dac13f8 3959 "balance: cannot set exclusive op status, resume manually");
ed0fb78f 3960
68310a5e 3961 mutex_lock(&fs_info->balance_mutex);
833aae18
DS
3962 BUG_ON(fs_info->balance_ctl);
3963 spin_lock(&fs_info->balance_lock);
3964 fs_info->balance_ctl = bctl;
3965 spin_unlock(&fs_info->balance_lock);
68310a5e 3966 mutex_unlock(&fs_info->balance_mutex);
59641015
ID
3967out:
3968 btrfs_free_path(path);
ec44a35c
CM
3969 return ret;
3970}
3971
837d5b6e
ID
3972int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
3973{
3974 int ret = 0;
3975
3976 mutex_lock(&fs_info->balance_mutex);
3977 if (!fs_info->balance_ctl) {
3978 mutex_unlock(&fs_info->balance_mutex);
3979 return -ENOTCONN;
3980 }
3981
3009a62f 3982 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
837d5b6e
ID
3983 atomic_inc(&fs_info->balance_pause_req);
3984 mutex_unlock(&fs_info->balance_mutex);
3985
3986 wait_event(fs_info->balance_wait_q,
3009a62f 3987 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
837d5b6e
ID
3988
3989 mutex_lock(&fs_info->balance_mutex);
3990 /* we are good with balance_ctl ripped off from under us */
3009a62f 3991 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
837d5b6e
ID
3992 atomic_dec(&fs_info->balance_pause_req);
3993 } else {
3994 ret = -ENOTCONN;
3995 }
3996
3997 mutex_unlock(&fs_info->balance_mutex);
3998 return ret;
3999}
4000
a7e99c69
ID
4001int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4002{
4003 mutex_lock(&fs_info->balance_mutex);
4004 if (!fs_info->balance_ctl) {
4005 mutex_unlock(&fs_info->balance_mutex);
4006 return -ENOTCONN;
4007 }
4008
cf7d20f4
DS
4009 /*
4010 * A paused balance with the item stored on disk can be resumed at
4011 * mount time if the mount is read-write. Otherwise it's still paused
4012 * and we must not allow cancelling as it deletes the item.
4013 */
4014 if (sb_rdonly(fs_info->sb)) {
4015 mutex_unlock(&fs_info->balance_mutex);
4016 return -EROFS;
4017 }
4018
a7e99c69
ID
4019 atomic_inc(&fs_info->balance_cancel_req);
4020 /*
4021 * if we are running just wait and return, balance item is
4022 * deleted in btrfs_balance in this case
4023 */
3009a62f 4024 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
a7e99c69
ID
4025 mutex_unlock(&fs_info->balance_mutex);
4026 wait_event(fs_info->balance_wait_q,
3009a62f 4027 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
a7e99c69
ID
4028 mutex_lock(&fs_info->balance_mutex);
4029 } else {
a7e99c69 4030 mutex_unlock(&fs_info->balance_mutex);
dccdb07b
DS
4031 /*
4032 * Lock released to allow other waiters to continue, we'll
4033 * reexamine the status again.
4034 */
a7e99c69
ID
4035 mutex_lock(&fs_info->balance_mutex);
4036
a17c95df 4037 if (fs_info->balance_ctl) {
149196a2 4038 reset_balance_state(fs_info);
a17c95df 4039 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
6dac13f8 4040 btrfs_info(fs_info, "balance: canceled");
a17c95df 4041 }
a7e99c69
ID
4042 }
4043
3009a62f
DS
4044 BUG_ON(fs_info->balance_ctl ||
4045 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
a7e99c69
ID
4046 atomic_dec(&fs_info->balance_cancel_req);
4047 mutex_unlock(&fs_info->balance_mutex);
4048 return 0;
4049}
4050
803b2f54
SB
4051static int btrfs_uuid_scan_kthread(void *data)
4052{
4053 struct btrfs_fs_info *fs_info = data;
4054 struct btrfs_root *root = fs_info->tree_root;
4055 struct btrfs_key key;
803b2f54
SB
4056 struct btrfs_path *path = NULL;
4057 int ret = 0;
4058 struct extent_buffer *eb;
4059 int slot;
4060 struct btrfs_root_item root_item;
4061 u32 item_size;
f45388f3 4062 struct btrfs_trans_handle *trans = NULL;
803b2f54
SB
4063
4064 path = btrfs_alloc_path();
4065 if (!path) {
4066 ret = -ENOMEM;
4067 goto out;
4068 }
4069
4070 key.objectid = 0;
4071 key.type = BTRFS_ROOT_ITEM_KEY;
4072 key.offset = 0;
4073
803b2f54 4074 while (1) {
7c829b72
AJ
4075 ret = btrfs_search_forward(root, &key, path,
4076 BTRFS_OLDEST_GENERATION);
803b2f54
SB
4077 if (ret) {
4078 if (ret > 0)
4079 ret = 0;
4080 break;
4081 }
4082
4083 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4084 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4085 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4086 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4087 goto skip;
4088
4089 eb = path->nodes[0];
4090 slot = path->slots[0];
4091 item_size = btrfs_item_size_nr(eb, slot);
4092 if (item_size < sizeof(root_item))
4093 goto skip;
4094
803b2f54
SB
4095 read_extent_buffer(eb, &root_item,
4096 btrfs_item_ptr_offset(eb, slot),
4097 (int)sizeof(root_item));
4098 if (btrfs_root_refs(&root_item) == 0)
4099 goto skip;
f45388f3
FDBM
4100
4101 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4102 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4103 if (trans)
4104 goto update_tree;
4105
4106 btrfs_release_path(path);
803b2f54
SB
4107 /*
4108 * 1 - subvol uuid item
4109 * 1 - received_subvol uuid item
4110 */
4111 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4112 if (IS_ERR(trans)) {
4113 ret = PTR_ERR(trans);
4114 break;
4115 }
f45388f3
FDBM
4116 continue;
4117 } else {
4118 goto skip;
4119 }
4120update_tree:
4121 if (!btrfs_is_empty_uuid(root_item.uuid)) {
cdb345a8 4122 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
803b2f54
SB
4123 BTRFS_UUID_KEY_SUBVOL,
4124 key.objectid);
4125 if (ret < 0) {
efe120a0 4126 btrfs_warn(fs_info, "uuid_tree_add failed %d",
803b2f54 4127 ret);
803b2f54
SB
4128 break;
4129 }
4130 }
4131
4132 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
cdb345a8 4133 ret = btrfs_uuid_tree_add(trans,
803b2f54
SB
4134 root_item.received_uuid,
4135 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4136 key.objectid);
4137 if (ret < 0) {
efe120a0 4138 btrfs_warn(fs_info, "uuid_tree_add failed %d",
803b2f54 4139 ret);
803b2f54
SB
4140 break;
4141 }
4142 }
4143
f45388f3 4144skip:
803b2f54 4145 if (trans) {
3a45bb20 4146 ret = btrfs_end_transaction(trans);
f45388f3 4147 trans = NULL;
803b2f54
SB
4148 if (ret)
4149 break;
4150 }
4151
803b2f54
SB
4152 btrfs_release_path(path);
4153 if (key.offset < (u64)-1) {
4154 key.offset++;
4155 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4156 key.offset = 0;
4157 key.type = BTRFS_ROOT_ITEM_KEY;
4158 } else if (key.objectid < (u64)-1) {
4159 key.offset = 0;
4160 key.type = BTRFS_ROOT_ITEM_KEY;
4161 key.objectid++;
4162 } else {
4163 break;
4164 }
4165 cond_resched();
4166 }
4167
4168out:
4169 btrfs_free_path(path);
f45388f3 4170 if (trans && !IS_ERR(trans))
3a45bb20 4171 btrfs_end_transaction(trans);
803b2f54 4172 if (ret)
efe120a0 4173 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
70f80175 4174 else
afcdd129 4175 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
803b2f54
SB
4176 up(&fs_info->uuid_tree_rescan_sem);
4177 return 0;
4178}
4179
70f80175
SB
4180/*
4181 * Callback for btrfs_uuid_tree_iterate().
4182 * returns:
4183 * 0 check succeeded, the entry is not outdated.
bb7ab3b9 4184 * < 0 if an error occurred.
70f80175
SB
4185 * > 0 if the check failed, which means the caller shall remove the entry.
4186 */
4187static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4188 u8 *uuid, u8 type, u64 subid)
4189{
4190 struct btrfs_key key;
4191 int ret = 0;
4192 struct btrfs_root *subvol_root;
4193
4194 if (type != BTRFS_UUID_KEY_SUBVOL &&
4195 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4196 goto out;
4197
4198 key.objectid = subid;
4199 key.type = BTRFS_ROOT_ITEM_KEY;
4200 key.offset = (u64)-1;
4201 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4202 if (IS_ERR(subvol_root)) {
4203 ret = PTR_ERR(subvol_root);
4204 if (ret == -ENOENT)
4205 ret = 1;
4206 goto out;
4207 }
4208
4209 switch (type) {
4210 case BTRFS_UUID_KEY_SUBVOL:
4211 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4212 ret = 1;
4213 break;
4214 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4215 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4216 BTRFS_UUID_SIZE))
4217 ret = 1;
4218 break;
4219 }
4220
4221out:
4222 return ret;
4223}
4224
4225static int btrfs_uuid_rescan_kthread(void *data)
4226{
4227 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4228 int ret;
4229
4230 /*
4231 * 1st step is to iterate through the existing UUID tree and
4232 * to delete all entries that contain outdated data.
4233 * 2nd step is to add all missing entries to the UUID tree.
4234 */
4235 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4236 if (ret < 0) {
efe120a0 4237 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
70f80175
SB
4238 up(&fs_info->uuid_tree_rescan_sem);
4239 return ret;
4240 }
4241 return btrfs_uuid_scan_kthread(data);
4242}
4243
f7a81ea4
SB
4244int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4245{
4246 struct btrfs_trans_handle *trans;
4247 struct btrfs_root *tree_root = fs_info->tree_root;
4248 struct btrfs_root *uuid_root;
803b2f54
SB
4249 struct task_struct *task;
4250 int ret;
f7a81ea4
SB
4251
4252 /*
4253 * 1 - root node
4254 * 1 - root item
4255 */
4256 trans = btrfs_start_transaction(tree_root, 2);
4257 if (IS_ERR(trans))
4258 return PTR_ERR(trans);
4259
4260 uuid_root = btrfs_create_tree(trans, fs_info,
4261 BTRFS_UUID_TREE_OBJECTID);
4262 if (IS_ERR(uuid_root)) {
6d13f549 4263 ret = PTR_ERR(uuid_root);
66642832 4264 btrfs_abort_transaction(trans, ret);
3a45bb20 4265 btrfs_end_transaction(trans);
6d13f549 4266 return ret;
f7a81ea4
SB
4267 }
4268
4269 fs_info->uuid_root = uuid_root;
4270
3a45bb20 4271 ret = btrfs_commit_transaction(trans);
803b2f54
SB
4272 if (ret)
4273 return ret;
4274
4275 down(&fs_info->uuid_tree_rescan_sem);
4276 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4277 if (IS_ERR(task)) {
70f80175 4278 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
efe120a0 4279 btrfs_warn(fs_info, "failed to start uuid_scan task");
803b2f54
SB
4280 up(&fs_info->uuid_tree_rescan_sem);
4281 return PTR_ERR(task);
4282 }
4283
4284 return 0;
f7a81ea4 4285}
803b2f54 4286
70f80175
SB
4287int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4288{
4289 struct task_struct *task;
4290
4291 down(&fs_info->uuid_tree_rescan_sem);
4292 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4293 if (IS_ERR(task)) {
4294 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
efe120a0 4295 btrfs_warn(fs_info, "failed to start uuid_rescan task");
70f80175
SB
4296 up(&fs_info->uuid_tree_rescan_sem);
4297 return PTR_ERR(task);
4298 }
4299
4300 return 0;
4301}
4302
8f18cf13
CM
4303/*
4304 * shrinking a device means finding all of the device extents past
4305 * the new size, and then following the back refs to the chunks.
4306 * The chunk relocation code actually frees the device extent
4307 */
4308int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4309{
0b246afa
JM
4310 struct btrfs_fs_info *fs_info = device->fs_info;
4311 struct btrfs_root *root = fs_info->dev_root;
8f18cf13 4312 struct btrfs_trans_handle *trans;
8f18cf13
CM
4313 struct btrfs_dev_extent *dev_extent = NULL;
4314 struct btrfs_path *path;
4315 u64 length;
8f18cf13
CM
4316 u64 chunk_offset;
4317 int ret;
4318 int slot;
ba1bf481
JB
4319 int failed = 0;
4320 bool retried = false;
53e489bc 4321 bool checked_pending_chunks = false;
8f18cf13
CM
4322 struct extent_buffer *l;
4323 struct btrfs_key key;
0b246afa 4324 struct btrfs_super_block *super_copy = fs_info->super_copy;
8f18cf13 4325 u64 old_total = btrfs_super_total_bytes(super_copy);
7cc8e58d 4326 u64 old_size = btrfs_device_get_total_bytes(device);
7dfb8be1
NB
4327 u64 diff;
4328
4329 new_size = round_down(new_size, fs_info->sectorsize);
0e4324a4 4330 diff = round_down(old_size - new_size, fs_info->sectorsize);
8f18cf13 4331
401e29c1 4332 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
63a212ab
SB
4333 return -EINVAL;
4334
8f18cf13
CM
4335 path = btrfs_alloc_path();
4336 if (!path)
4337 return -ENOMEM;
4338
0338dff6 4339 path->reada = READA_BACK;
8f18cf13 4340
34441361 4341 mutex_lock(&fs_info->chunk_mutex);
7d9eb12c 4342
7cc8e58d 4343 btrfs_device_set_total_bytes(device, new_size);
ebbede42 4344 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2b82032c 4345 device->fs_devices->total_rw_bytes -= diff;
a5ed45f8 4346 atomic64_sub(diff, &fs_info->free_chunk_space);
2bf64758 4347 }
34441361 4348 mutex_unlock(&fs_info->chunk_mutex);
8f18cf13 4349
ba1bf481 4350again:
8f18cf13
CM
4351 key.objectid = device->devid;
4352 key.offset = (u64)-1;
4353 key.type = BTRFS_DEV_EXTENT_KEY;
4354
213e64da 4355 do {
0b246afa 4356 mutex_lock(&fs_info->delete_unused_bgs_mutex);
8f18cf13 4357 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
67c5e7d4 4358 if (ret < 0) {
0b246afa 4359 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
8f18cf13 4360 goto done;
67c5e7d4 4361 }
8f18cf13
CM
4362
4363 ret = btrfs_previous_item(root, path, 0, key.type);
67c5e7d4 4364 if (ret)
0b246afa 4365 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
8f18cf13
CM
4366 if (ret < 0)
4367 goto done;
4368 if (ret) {
4369 ret = 0;
b3b4aa74 4370 btrfs_release_path(path);
bf1fb512 4371 break;
8f18cf13
CM
4372 }
4373
4374 l = path->nodes[0];
4375 slot = path->slots[0];
4376 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4377
ba1bf481 4378 if (key.objectid != device->devid) {
0b246afa 4379 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
b3b4aa74 4380 btrfs_release_path(path);
bf1fb512 4381 break;
ba1bf481 4382 }
8f18cf13
CM
4383
4384 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4385 length = btrfs_dev_extent_length(l, dev_extent);
4386
ba1bf481 4387 if (key.offset + length <= new_size) {
0b246afa 4388 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
b3b4aa74 4389 btrfs_release_path(path);
d6397bae 4390 break;
ba1bf481 4391 }
8f18cf13 4392
8f18cf13 4393 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
b3b4aa74 4394 btrfs_release_path(path);
8f18cf13 4395
a6f93c71
LB
4396 /*
4397 * We may be relocating the only data chunk we have,
4398 * which could potentially end up with losing data's
4399 * raid profile, so lets allocate an empty one in
4400 * advance.
4401 */
4402 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4403 if (ret < 0) {
4404 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4405 goto done;
4406 }
4407
0b246afa
JM
4408 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4409 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
ba1bf481 4410 if (ret && ret != -ENOSPC)
8f18cf13 4411 goto done;
ba1bf481
JB
4412 if (ret == -ENOSPC)
4413 failed++;
213e64da 4414 } while (key.offset-- > 0);
ba1bf481
JB
4415
4416 if (failed && !retried) {
4417 failed = 0;
4418 retried = true;
4419 goto again;
4420 } else if (failed && retried) {
4421 ret = -ENOSPC;
ba1bf481 4422 goto done;
8f18cf13
CM
4423 }
4424
d6397bae 4425 /* Shrinking succeeded, else we would be at "done". */
a22285a6 4426 trans = btrfs_start_transaction(root, 0);
98d5dc13
TI
4427 if (IS_ERR(trans)) {
4428 ret = PTR_ERR(trans);
4429 goto done;
4430 }
4431
34441361 4432 mutex_lock(&fs_info->chunk_mutex);
53e489bc
FM
4433
4434 /*
4435 * We checked in the above loop all device extents that were already in
4436 * the device tree. However before we have updated the device's
4437 * total_bytes to the new size, we might have had chunk allocations that
4438 * have not complete yet (new block groups attached to transaction
4439 * handles), and therefore their device extents were not yet in the
4440 * device tree and we missed them in the loop above. So if we have any
4441 * pending chunk using a device extent that overlaps the device range
4442 * that we can not use anymore, commit the current transaction and
4443 * repeat the search on the device tree - this way we guarantee we will
4444 * not have chunks using device extents that end beyond 'new_size'.
4445 */
4446 if (!checked_pending_chunks) {
4447 u64 start = new_size;
4448 u64 len = old_size - new_size;
4449
499f377f
JM
4450 if (contains_pending_extent(trans->transaction, device,
4451 &start, len)) {
34441361 4452 mutex_unlock(&fs_info->chunk_mutex);
53e489bc
FM
4453 checked_pending_chunks = true;
4454 failed = 0;
4455 retried = false;
3a45bb20 4456 ret = btrfs_commit_transaction(trans);
53e489bc
FM
4457 if (ret)
4458 goto done;
4459 goto again;
4460 }
4461 }
4462
7cc8e58d 4463 btrfs_device_set_disk_total_bytes(device, new_size);
935e5cc9
MX
4464 if (list_empty(&device->resized_list))
4465 list_add_tail(&device->resized_list,
0b246afa 4466 &fs_info->fs_devices->resized_devices);
d6397bae 4467
d6397bae 4468 WARN_ON(diff > old_total);
7dfb8be1
NB
4469 btrfs_set_super_total_bytes(super_copy,
4470 round_down(old_total - diff, fs_info->sectorsize));
34441361 4471 mutex_unlock(&fs_info->chunk_mutex);
2196d6e8
MX
4472
4473 /* Now btrfs_update_device() will change the on-disk size. */
4474 ret = btrfs_update_device(trans, device);
3a45bb20 4475 btrfs_end_transaction(trans);
8f18cf13
CM
4476done:
4477 btrfs_free_path(path);
53e489bc 4478 if (ret) {
34441361 4479 mutex_lock(&fs_info->chunk_mutex);
53e489bc 4480 btrfs_device_set_total_bytes(device, old_size);
ebbede42 4481 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
53e489bc 4482 device->fs_devices->total_rw_bytes += diff;
a5ed45f8 4483 atomic64_add(diff, &fs_info->free_chunk_space);
34441361 4484 mutex_unlock(&fs_info->chunk_mutex);
53e489bc 4485 }
8f18cf13
CM
4486 return ret;
4487}
4488
2ff7e61e 4489static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
0b86a832
CM
4490 struct btrfs_key *key,
4491 struct btrfs_chunk *chunk, int item_size)
4492{
0b246afa 4493 struct btrfs_super_block *super_copy = fs_info->super_copy;
0b86a832
CM
4494 struct btrfs_disk_key disk_key;
4495 u32 array_size;
4496 u8 *ptr;
4497
34441361 4498 mutex_lock(&fs_info->chunk_mutex);
0b86a832 4499 array_size = btrfs_super_sys_array_size(super_copy);
5f43f86e 4500 if (array_size + item_size + sizeof(disk_key)
fe48a5c0 4501 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
34441361 4502 mutex_unlock(&fs_info->chunk_mutex);
0b86a832 4503 return -EFBIG;
fe48a5c0 4504 }
0b86a832
CM
4505
4506 ptr = super_copy->sys_chunk_array + array_size;
4507 btrfs_cpu_key_to_disk(&disk_key, key);
4508 memcpy(ptr, &disk_key, sizeof(disk_key));
4509 ptr += sizeof(disk_key);
4510 memcpy(ptr, chunk, item_size);
4511 item_size += sizeof(disk_key);
4512 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
34441361 4513 mutex_unlock(&fs_info->chunk_mutex);
fe48a5c0 4514
0b86a832
CM
4515 return 0;
4516}
4517
73c5de00
AJ
4518/*
4519 * sort the devices in descending order by max_avail, total_avail
4520 */
4521static int btrfs_cmp_device_info(const void *a, const void *b)
9b3f68b9 4522{
73c5de00
AJ
4523 const struct btrfs_device_info *di_a = a;
4524 const struct btrfs_device_info *di_b = b;
9b3f68b9 4525
73c5de00 4526 if (di_a->max_avail > di_b->max_avail)
b2117a39 4527 return -1;
73c5de00 4528 if (di_a->max_avail < di_b->max_avail)
b2117a39 4529 return 1;
73c5de00
AJ
4530 if (di_a->total_avail > di_b->total_avail)
4531 return -1;
4532 if (di_a->total_avail < di_b->total_avail)
4533 return 1;
4534 return 0;
b2117a39 4535}
0b86a832 4536
53b381b3
DW
4537static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4538{
ffe2d203 4539 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
53b381b3
DW
4540 return;
4541
ceda0864 4542 btrfs_set_fs_incompat(info, RAID56);
53b381b3
DW
4543}
4544
062d4d1f 4545#define BTRFS_MAX_DEVS(info) ((BTRFS_MAX_ITEM_SIZE(info) \
23f8f9b7
GH
4546 - sizeof(struct btrfs_chunk)) \
4547 / sizeof(struct btrfs_stripe) + 1)
4548
4549#define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4550 - 2 * sizeof(struct btrfs_disk_key) \
4551 - 2 * sizeof(struct btrfs_chunk)) \
4552 / sizeof(struct btrfs_stripe) + 1)
4553
73c5de00 4554static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
72b468c8 4555 u64 start, u64 type)
b2117a39 4556{
2ff7e61e 4557 struct btrfs_fs_info *info = trans->fs_info;
73c5de00 4558 struct btrfs_fs_devices *fs_devices = info->fs_devices;
ebcc9301 4559 struct btrfs_device *device;
73c5de00
AJ
4560 struct map_lookup *map = NULL;
4561 struct extent_map_tree *em_tree;
4562 struct extent_map *em;
4563 struct btrfs_device_info *devices_info = NULL;
4564 u64 total_avail;
4565 int num_stripes; /* total number of stripes to allocate */
53b381b3
DW
4566 int data_stripes; /* number of stripes that count for
4567 block group size */
73c5de00
AJ
4568 int sub_stripes; /* sub_stripes info for map */
4569 int dev_stripes; /* stripes per dev */
4570 int devs_max; /* max devs to use */
4571 int devs_min; /* min devs needed */
4572 int devs_increment; /* ndevs has to be a multiple of this */
4573 int ncopies; /* how many copies to data has */
4574 int ret;
4575 u64 max_stripe_size;
4576 u64 max_chunk_size;
4577 u64 stripe_size;
4578 u64 num_bytes;
4579 int ndevs;
4580 int i;
4581 int j;
31e50229 4582 int index;
593060d7 4583
0c460c0d 4584 BUG_ON(!alloc_profile_is_valid(type, 0));
9b3f68b9 4585
4117f207
QW
4586 if (list_empty(&fs_devices->alloc_list)) {
4587 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4588 btrfs_debug(info, "%s: no writable device", __func__);
73c5de00 4589 return -ENOSPC;
4117f207 4590 }
b2117a39 4591
3e72ee88 4592 index = btrfs_bg_flags_to_raid_index(type);
73c5de00 4593
31e50229
LB
4594 sub_stripes = btrfs_raid_array[index].sub_stripes;
4595 dev_stripes = btrfs_raid_array[index].dev_stripes;
4596 devs_max = btrfs_raid_array[index].devs_max;
4597 devs_min = btrfs_raid_array[index].devs_min;
4598 devs_increment = btrfs_raid_array[index].devs_increment;
4599 ncopies = btrfs_raid_array[index].ncopies;
b2117a39 4600
9b3f68b9 4601 if (type & BTRFS_BLOCK_GROUP_DATA) {
ee22184b 4602 max_stripe_size = SZ_1G;
fce466ea 4603 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
23f8f9b7 4604 if (!devs_max)
062d4d1f 4605 devs_max = BTRFS_MAX_DEVS(info);
9b3f68b9 4606 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
1100373f 4607 /* for larger filesystems, use larger metadata chunks */
ee22184b
BL
4608 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4609 max_stripe_size = SZ_1G;
1100373f 4610 else
ee22184b 4611 max_stripe_size = SZ_256M;
73c5de00 4612 max_chunk_size = max_stripe_size;
23f8f9b7 4613 if (!devs_max)
062d4d1f 4614 devs_max = BTRFS_MAX_DEVS(info);
a40a90a0 4615 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
ee22184b 4616 max_stripe_size = SZ_32M;
73c5de00 4617 max_chunk_size = 2 * max_stripe_size;
23f8f9b7
GH
4618 if (!devs_max)
4619 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
73c5de00 4620 } else {
351fd353 4621 btrfs_err(info, "invalid chunk type 0x%llx requested",
73c5de00
AJ
4622 type);
4623 BUG_ON(1);
9b3f68b9
CM
4624 }
4625
2b82032c
YZ
4626 /* we don't want a chunk larger than 10% of writeable space */
4627 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4628 max_chunk_size);
9b3f68b9 4629
31e818fe 4630 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
73c5de00
AJ
4631 GFP_NOFS);
4632 if (!devices_info)
4633 return -ENOMEM;
0cad8a11 4634
9f680ce0 4635 /*
73c5de00
AJ
4636 * in the first pass through the devices list, we gather information
4637 * about the available holes on each device.
9f680ce0 4638 */
73c5de00 4639 ndevs = 0;
ebcc9301 4640 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
73c5de00
AJ
4641 u64 max_avail;
4642 u64 dev_offset;
b2117a39 4643
ebbede42 4644 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
31b1a2bd 4645 WARN(1, KERN_ERR
efe120a0 4646 "BTRFS: read-only device in alloc_list\n");
73c5de00
AJ
4647 continue;
4648 }
b2117a39 4649
e12c9621
AJ
4650 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4651 &device->dev_state) ||
401e29c1 4652 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
73c5de00 4653 continue;
b2117a39 4654
73c5de00
AJ
4655 if (device->total_bytes > device->bytes_used)
4656 total_avail = device->total_bytes - device->bytes_used;
4657 else
4658 total_avail = 0;
38c01b96 4659
4660 /* If there is no space on this device, skip it. */
4661 if (total_avail == 0)
4662 continue;
b2117a39 4663
6df9a95e 4664 ret = find_free_dev_extent(trans, device,
73c5de00
AJ
4665 max_stripe_size * dev_stripes,
4666 &dev_offset, &max_avail);
4667 if (ret && ret != -ENOSPC)
4668 goto error;
b2117a39 4669
73c5de00
AJ
4670 if (ret == 0)
4671 max_avail = max_stripe_size * dev_stripes;
b2117a39 4672
4117f207
QW
4673 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
4674 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4675 btrfs_debug(info,
4676 "%s: devid %llu has no free space, have=%llu want=%u",
4677 __func__, device->devid, max_avail,
4678 BTRFS_STRIPE_LEN * dev_stripes);
73c5de00 4679 continue;
4117f207 4680 }
b2117a39 4681
063d006f
ES
4682 if (ndevs == fs_devices->rw_devices) {
4683 WARN(1, "%s: found more than %llu devices\n",
4684 __func__, fs_devices->rw_devices);
4685 break;
4686 }
73c5de00
AJ
4687 devices_info[ndevs].dev_offset = dev_offset;
4688 devices_info[ndevs].max_avail = max_avail;
4689 devices_info[ndevs].total_avail = total_avail;
4690 devices_info[ndevs].dev = device;
4691 ++ndevs;
4692 }
b2117a39 4693
73c5de00
AJ
4694 /*
4695 * now sort the devices by hole size / available space
4696 */
4697 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4698 btrfs_cmp_device_info, NULL);
b2117a39 4699
73c5de00 4700 /* round down to number of usable stripes */
e5600fd6 4701 ndevs = round_down(ndevs, devs_increment);
b2117a39 4702
ba89b802 4703 if (ndevs < devs_min) {
73c5de00 4704 ret = -ENOSPC;
4117f207
QW
4705 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
4706 btrfs_debug(info,
4707 "%s: not enough devices with free space: have=%d minimum required=%d",
ba89b802 4708 __func__, ndevs, devs_min);
4117f207 4709 }
73c5de00 4710 goto error;
b2117a39 4711 }
9f680ce0 4712
f148ef4d
NB
4713 ndevs = min(ndevs, devs_max);
4714
73c5de00 4715 /*
92e222df
HK
4716 * The primary goal is to maximize the number of stripes, so use as
4717 * many devices as possible, even if the stripes are not maximum sized.
4718 *
4719 * The DUP profile stores more than one stripe per device, the
4720 * max_avail is the total size so we have to adjust.
73c5de00 4721 */
92e222df 4722 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
73c5de00 4723 num_stripes = ndevs * dev_stripes;
b2117a39 4724
53b381b3
DW
4725 /*
4726 * this will have to be fixed for RAID1 and RAID10 over
4727 * more drives
4728 */
4729 data_stripes = num_stripes / ncopies;
4730
500ceed8 4731 if (type & BTRFS_BLOCK_GROUP_RAID5)
53b381b3 4732 data_stripes = num_stripes - 1;
500ceed8
NB
4733
4734 if (type & BTRFS_BLOCK_GROUP_RAID6)
53b381b3 4735 data_stripes = num_stripes - 2;
86db2578
CM
4736
4737 /*
4738 * Use the number of data stripes to figure out how big this chunk
4739 * is really going to be in terms of logical address space,
4740 * and compare that answer with the max chunk size
4741 */
4742 if (stripe_size * data_stripes > max_chunk_size) {
b8b93add 4743 stripe_size = div_u64(max_chunk_size, data_stripes);
86db2578
CM
4744
4745 /* bump the answer up to a 16MB boundary */
793ff2c8 4746 stripe_size = round_up(stripe_size, SZ_16M);
86db2578 4747
793ff2c8
QW
4748 /*
4749 * But don't go higher than the limits we found while searching
4750 * for free extents
86db2578 4751 */
793ff2c8
QW
4752 stripe_size = min(devices_info[ndevs - 1].max_avail,
4753 stripe_size);
86db2578
CM
4754 }
4755
37db63a4 4756 /* align to BTRFS_STRIPE_LEN */
500ceed8 4757 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
b2117a39
MX
4758
4759 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4760 if (!map) {
4761 ret = -ENOMEM;
4762 goto error;
4763 }
4764 map->num_stripes = num_stripes;
9b3f68b9 4765
73c5de00
AJ
4766 for (i = 0; i < ndevs; ++i) {
4767 for (j = 0; j < dev_stripes; ++j) {
4768 int s = i * dev_stripes + j;
4769 map->stripes[s].dev = devices_info[i].dev;
4770 map->stripes[s].physical = devices_info[i].dev_offset +
4771 j * stripe_size;
6324fbf3 4772 }
6324fbf3 4773 }
500ceed8
NB
4774 map->stripe_len = BTRFS_STRIPE_LEN;
4775 map->io_align = BTRFS_STRIPE_LEN;
4776 map->io_width = BTRFS_STRIPE_LEN;
2b82032c 4777 map->type = type;
2b82032c 4778 map->sub_stripes = sub_stripes;
0b86a832 4779
53b381b3 4780 num_bytes = stripe_size * data_stripes;
0b86a832 4781
6bccf3ab 4782 trace_btrfs_chunk_alloc(info, map, start, num_bytes);
1abe9b8a 4783
172ddd60 4784 em = alloc_extent_map();
2b82032c 4785 if (!em) {
298a8f9c 4786 kfree(map);
b2117a39
MX
4787 ret = -ENOMEM;
4788 goto error;
593060d7 4789 }
298a8f9c 4790 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
95617d69 4791 em->map_lookup = map;
2b82032c 4792 em->start = start;
73c5de00 4793 em->len = num_bytes;
2b82032c
YZ
4794 em->block_start = 0;
4795 em->block_len = em->len;
6df9a95e 4796 em->orig_block_len = stripe_size;
593060d7 4797
0b246afa 4798 em_tree = &info->mapping_tree.map_tree;
890871be 4799 write_lock(&em_tree->lock);
09a2a8f9 4800 ret = add_extent_mapping(em_tree, em, 0);
0f5d42b2 4801 if (ret) {
1efb72a3 4802 write_unlock(&em_tree->lock);
0f5d42b2 4803 free_extent_map(em);
1dd4602f 4804 goto error;
0f5d42b2 4805 }
0b86a832 4806
1efb72a3
NB
4807 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4808 refcount_inc(&em->refs);
4809 write_unlock(&em_tree->lock);
4810
e7e02096 4811 ret = btrfs_make_block_group(trans, 0, type, start, num_bytes);
6df9a95e
JB
4812 if (ret)
4813 goto error_del_extent;
2b82032c 4814
7cc8e58d
MX
4815 for (i = 0; i < map->num_stripes; i++) {
4816 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4817 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4818 }
43530c46 4819
a5ed45f8 4820 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
1c116187 4821
0f5d42b2 4822 free_extent_map(em);
0b246afa 4823 check_raid56_incompat_flag(info, type);
53b381b3 4824
b2117a39 4825 kfree(devices_info);
2b82032c 4826 return 0;
b2117a39 4827
6df9a95e 4828error_del_extent:
0f5d42b2
JB
4829 write_lock(&em_tree->lock);
4830 remove_extent_mapping(em_tree, em);
4831 write_unlock(&em_tree->lock);
4832
4833 /* One for our allocation */
4834 free_extent_map(em);
4835 /* One for the tree reference */
4836 free_extent_map(em);
495e64f4
FM
4837 /* One for the pending_chunks list reference */
4838 free_extent_map(em);
b2117a39 4839error:
b2117a39
MX
4840 kfree(devices_info);
4841 return ret;
2b82032c
YZ
4842}
4843
6df9a95e 4844int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
97aff912 4845 u64 chunk_offset, u64 chunk_size)
2b82032c 4846{
97aff912 4847 struct btrfs_fs_info *fs_info = trans->fs_info;
6bccf3ab
JM
4848 struct btrfs_root *extent_root = fs_info->extent_root;
4849 struct btrfs_root *chunk_root = fs_info->chunk_root;
2b82032c 4850 struct btrfs_key key;
2b82032c
YZ
4851 struct btrfs_device *device;
4852 struct btrfs_chunk *chunk;
4853 struct btrfs_stripe *stripe;
6df9a95e
JB
4854 struct extent_map *em;
4855 struct map_lookup *map;
4856 size_t item_size;
4857 u64 dev_offset;
4858 u64 stripe_size;
4859 int i = 0;
140e639f 4860 int ret = 0;
2b82032c 4861
592d92ee
LB
4862 em = get_chunk_map(fs_info, chunk_offset, chunk_size);
4863 if (IS_ERR(em))
4864 return PTR_ERR(em);
6df9a95e 4865
95617d69 4866 map = em->map_lookup;
6df9a95e
JB
4867 item_size = btrfs_chunk_item_size(map->num_stripes);
4868 stripe_size = em->orig_block_len;
4869
2b82032c 4870 chunk = kzalloc(item_size, GFP_NOFS);
6df9a95e
JB
4871 if (!chunk) {
4872 ret = -ENOMEM;
4873 goto out;
4874 }
4875
50460e37
FM
4876 /*
4877 * Take the device list mutex to prevent races with the final phase of
4878 * a device replace operation that replaces the device object associated
4879 * with the map's stripes, because the device object's id can change
4880 * at any time during that final phase of the device replace operation
4881 * (dev-replace.c:btrfs_dev_replace_finishing()).
4882 */
0b246afa 4883 mutex_lock(&fs_info->fs_devices->device_list_mutex);
6df9a95e
JB
4884 for (i = 0; i < map->num_stripes; i++) {
4885 device = map->stripes[i].dev;
4886 dev_offset = map->stripes[i].physical;
2b82032c 4887
0b86a832 4888 ret = btrfs_update_device(trans, device);
3acd3953 4889 if (ret)
50460e37 4890 break;
b5d9071c
NB
4891 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
4892 dev_offset, stripe_size);
6df9a95e 4893 if (ret)
50460e37
FM
4894 break;
4895 }
4896 if (ret) {
0b246afa 4897 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
50460e37 4898 goto out;
2b82032c
YZ
4899 }
4900
2b82032c 4901 stripe = &chunk->stripe;
6df9a95e
JB
4902 for (i = 0; i < map->num_stripes; i++) {
4903 device = map->stripes[i].dev;
4904 dev_offset = map->stripes[i].physical;
0b86a832 4905
e17cade2
CM
4906 btrfs_set_stack_stripe_devid(stripe, device->devid);
4907 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4908 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
2b82032c 4909 stripe++;
0b86a832 4910 }
0b246afa 4911 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
0b86a832 4912
2b82032c 4913 btrfs_set_stack_chunk_length(chunk, chunk_size);
0b86a832 4914 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
2b82032c
YZ
4915 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4916 btrfs_set_stack_chunk_type(chunk, map->type);
4917 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4918 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4919 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
0b246afa 4920 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
2b82032c 4921 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
0b86a832 4922
2b82032c
YZ
4923 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4924 key.type = BTRFS_CHUNK_ITEM_KEY;
4925 key.offset = chunk_offset;
0b86a832 4926
2b82032c 4927 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4ed1d16e
MF
4928 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4929 /*
4930 * TODO: Cleanup of inserted chunk root in case of
4931 * failure.
4932 */
2ff7e61e 4933 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
8f18cf13 4934 }
1abe9b8a 4935
6df9a95e 4936out:
0b86a832 4937 kfree(chunk);
6df9a95e 4938 free_extent_map(em);
4ed1d16e 4939 return ret;
2b82032c 4940}
0b86a832 4941
2b82032c
YZ
4942/*
4943 * Chunk allocation falls into two parts. The first part does works
4944 * that make the new allocated chunk useable, but not do any operation
4945 * that modifies the chunk tree. The second part does the works that
4946 * require modifying the chunk tree. This division is important for the
4947 * bootstrap process of adding storage to a seed btrfs.
4948 */
c216b203 4949int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
2b82032c
YZ
4950{
4951 u64 chunk_offset;
2b82032c 4952
c216b203
NB
4953 lockdep_assert_held(&trans->fs_info->chunk_mutex);
4954 chunk_offset = find_next_chunk(trans->fs_info);
72b468c8 4955 return __btrfs_alloc_chunk(trans, chunk_offset, type);
2b82032c
YZ
4956}
4957
d397712b 4958static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
e4a4dce7 4959 struct btrfs_fs_info *fs_info)
2b82032c
YZ
4960{
4961 u64 chunk_offset;
4962 u64 sys_chunk_offset;
2b82032c 4963 u64 alloc_profile;
2b82032c
YZ
4964 int ret;
4965
6df9a95e 4966 chunk_offset = find_next_chunk(fs_info);
1b86826d 4967 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
72b468c8 4968 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
79787eaa
JM
4969 if (ret)
4970 return ret;
2b82032c 4971
0b246afa 4972 sys_chunk_offset = find_next_chunk(fs_info);
1b86826d 4973 alloc_profile = btrfs_system_alloc_profile(fs_info);
72b468c8 4974 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
79787eaa 4975 return ret;
2b82032c
YZ
4976}
4977
d20983b4
MX
4978static inline int btrfs_chunk_max_errors(struct map_lookup *map)
4979{
4980 int max_errors;
4981
4982 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
4983 BTRFS_BLOCK_GROUP_RAID10 |
4984 BTRFS_BLOCK_GROUP_RAID5 |
4985 BTRFS_BLOCK_GROUP_DUP)) {
4986 max_errors = 1;
4987 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
4988 max_errors = 2;
4989 } else {
4990 max_errors = 0;
005d6427 4991 }
2b82032c 4992
d20983b4 4993 return max_errors;
2b82032c
YZ
4994}
4995
2ff7e61e 4996int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2b82032c
YZ
4997{
4998 struct extent_map *em;
4999 struct map_lookup *map;
2b82032c 5000 int readonly = 0;
d20983b4 5001 int miss_ndevs = 0;
2b82032c
YZ
5002 int i;
5003
592d92ee
LB
5004 em = get_chunk_map(fs_info, chunk_offset, 1);
5005 if (IS_ERR(em))
2b82032c
YZ
5006 return 1;
5007
95617d69 5008 map = em->map_lookup;
2b82032c 5009 for (i = 0; i < map->num_stripes; i++) {
e6e674bd
AJ
5010 if (test_bit(BTRFS_DEV_STATE_MISSING,
5011 &map->stripes[i].dev->dev_state)) {
d20983b4
MX
5012 miss_ndevs++;
5013 continue;
5014 }
ebbede42
AJ
5015 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5016 &map->stripes[i].dev->dev_state)) {
2b82032c 5017 readonly = 1;
d20983b4 5018 goto end;
2b82032c
YZ
5019 }
5020 }
d20983b4
MX
5021
5022 /*
5023 * If the number of missing devices is larger than max errors,
5024 * we can not write the data into that chunk successfully, so
5025 * set it readonly.
5026 */
5027 if (miss_ndevs > btrfs_chunk_max_errors(map))
5028 readonly = 1;
5029end:
0b86a832 5030 free_extent_map(em);
2b82032c 5031 return readonly;
0b86a832
CM
5032}
5033
5034void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5035{
a8067e02 5036 extent_map_tree_init(&tree->map_tree);
0b86a832
CM
5037}
5038
5039void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5040{
5041 struct extent_map *em;
5042
d397712b 5043 while (1) {
890871be 5044 write_lock(&tree->map_tree.lock);
0b86a832
CM
5045 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5046 if (em)
5047 remove_extent_mapping(&tree->map_tree, em);
890871be 5048 write_unlock(&tree->map_tree.lock);
0b86a832
CM
5049 if (!em)
5050 break;
0b86a832
CM
5051 /* once for us */
5052 free_extent_map(em);
5053 /* once for the tree */
5054 free_extent_map(em);
5055 }
5056}
5057
5d964051 5058int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
f188591e
CM
5059{
5060 struct extent_map *em;
5061 struct map_lookup *map;
f188591e
CM
5062 int ret;
5063
592d92ee
LB
5064 em = get_chunk_map(fs_info, logical, len);
5065 if (IS_ERR(em))
5066 /*
5067 * We could return errors for these cases, but that could get
5068 * ugly and we'd probably do the same thing which is just not do
5069 * anything else and exit, so return 1 so the callers don't try
5070 * to use other copies.
5071 */
fb7669b5 5072 return 1;
fb7669b5 5073
95617d69 5074 map = em->map_lookup;
f188591e
CM
5075 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5076 ret = map->num_stripes;
321aecc6
CM
5077 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5078 ret = map->sub_stripes;
53b381b3
DW
5079 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5080 ret = 2;
5081 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
8810f751
LB
5082 /*
5083 * There could be two corrupted data stripes, we need
5084 * to loop retry in order to rebuild the correct data.
e7e02096 5085 *
8810f751
LB
5086 * Fail a stripe at a time on every retry except the
5087 * stripe under reconstruction.
5088 */
5089 ret = map->num_stripes;
f188591e
CM
5090 else
5091 ret = 1;
5092 free_extent_map(em);
ad6d620e 5093
7e79cb86 5094 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
6fad823f
LB
5095 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5096 fs_info->dev_replace.tgtdev)
ad6d620e 5097 ret++;
7e79cb86 5098 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
ad6d620e 5099
f188591e
CM
5100 return ret;
5101}
5102
2ff7e61e 5103unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
53b381b3
DW
5104 u64 logical)
5105{
5106 struct extent_map *em;
5107 struct map_lookup *map;
0b246afa 5108 unsigned long len = fs_info->sectorsize;
53b381b3 5109
592d92ee 5110 em = get_chunk_map(fs_info, logical, len);
53b381b3 5111
69f03f13
NB
5112 if (!WARN_ON(IS_ERR(em))) {
5113 map = em->map_lookup;
5114 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5115 len = map->stripe_len * nr_data_stripes(map);
5116 free_extent_map(em);
5117 }
53b381b3
DW
5118 return len;
5119}
5120
e4ff5fb5 5121int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
53b381b3
DW
5122{
5123 struct extent_map *em;
5124 struct map_lookup *map;
53b381b3
DW
5125 int ret = 0;
5126
592d92ee 5127 em = get_chunk_map(fs_info, logical, len);
53b381b3 5128
69f03f13
NB
5129 if(!WARN_ON(IS_ERR(em))) {
5130 map = em->map_lookup;
5131 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5132 ret = 1;
5133 free_extent_map(em);
5134 }
53b381b3
DW
5135 return ret;
5136}
5137
30d9861f 5138static int find_live_mirror(struct btrfs_fs_info *fs_info,
99f92a7c 5139 struct map_lookup *map, int first,
8ba0ae78 5140 int dev_replace_is_ongoing)
dfe25020
CM
5141{
5142 int i;
99f92a7c 5143 int num_stripes;
8ba0ae78 5144 int preferred_mirror;
30d9861f
SB
5145 int tolerance;
5146 struct btrfs_device *srcdev;
5147
99f92a7c
AJ
5148 ASSERT((map->type &
5149 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)));
5150
5151 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5152 num_stripes = map->sub_stripes;
5153 else
5154 num_stripes = map->num_stripes;
5155
8ba0ae78
AJ
5156 preferred_mirror = first + current->pid % num_stripes;
5157
30d9861f
SB
5158 if (dev_replace_is_ongoing &&
5159 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5160 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5161 srcdev = fs_info->dev_replace.srcdev;
5162 else
5163 srcdev = NULL;
5164
5165 /*
5166 * try to avoid the drive that is the source drive for a
5167 * dev-replace procedure, only choose it if no other non-missing
5168 * mirror is available
5169 */
5170 for (tolerance = 0; tolerance < 2; tolerance++) {
8ba0ae78
AJ
5171 if (map->stripes[preferred_mirror].dev->bdev &&
5172 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5173 return preferred_mirror;
99f92a7c 5174 for (i = first; i < first + num_stripes; i++) {
30d9861f
SB
5175 if (map->stripes[i].dev->bdev &&
5176 (tolerance || map->stripes[i].dev != srcdev))
5177 return i;
5178 }
dfe25020 5179 }
30d9861f 5180
dfe25020
CM
5181 /* we couldn't find one that doesn't fail. Just return something
5182 * and the io error handling code will clean up eventually
5183 */
8ba0ae78 5184 return preferred_mirror;
dfe25020
CM
5185}
5186
53b381b3
DW
5187static inline int parity_smaller(u64 a, u64 b)
5188{
5189 return a > b;
5190}
5191
5192/* Bubble-sort the stripe set to put the parity/syndrome stripes last */
8e5cfb55 5193static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
53b381b3
DW
5194{
5195 struct btrfs_bio_stripe s;
5196 int i;
5197 u64 l;
5198 int again = 1;
5199
5200 while (again) {
5201 again = 0;
cc7539ed 5202 for (i = 0; i < num_stripes - 1; i++) {
8e5cfb55
ZL
5203 if (parity_smaller(bbio->raid_map[i],
5204 bbio->raid_map[i+1])) {
53b381b3 5205 s = bbio->stripes[i];
8e5cfb55 5206 l = bbio->raid_map[i];
53b381b3 5207 bbio->stripes[i] = bbio->stripes[i+1];
8e5cfb55 5208 bbio->raid_map[i] = bbio->raid_map[i+1];
53b381b3 5209 bbio->stripes[i+1] = s;
8e5cfb55 5210 bbio->raid_map[i+1] = l;
2c8cdd6e 5211
53b381b3
DW
5212 again = 1;
5213 }
5214 }
5215 }
5216}
5217
6e9606d2
ZL
5218static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5219{
5220 struct btrfs_bio *bbio = kzalloc(
e57cf21e 5221 /* the size of the btrfs_bio */
6e9606d2 5222 sizeof(struct btrfs_bio) +
e57cf21e 5223 /* plus the variable array for the stripes */
6e9606d2 5224 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
e57cf21e 5225 /* plus the variable array for the tgt dev */
6e9606d2 5226 sizeof(int) * (real_stripes) +
e57cf21e
CM
5227 /*
5228 * plus the raid_map, which includes both the tgt dev
5229 * and the stripes
5230 */
5231 sizeof(u64) * (total_stripes),
277fb5fc 5232 GFP_NOFS|__GFP_NOFAIL);
6e9606d2
ZL
5233
5234 atomic_set(&bbio->error, 0);
140475ae 5235 refcount_set(&bbio->refs, 1);
6e9606d2
ZL
5236
5237 return bbio;
5238}
5239
5240void btrfs_get_bbio(struct btrfs_bio *bbio)
5241{
140475ae
ER
5242 WARN_ON(!refcount_read(&bbio->refs));
5243 refcount_inc(&bbio->refs);
6e9606d2
ZL
5244}
5245
5246void btrfs_put_bbio(struct btrfs_bio *bbio)
5247{
5248 if (!bbio)
5249 return;
140475ae 5250 if (refcount_dec_and_test(&bbio->refs))
6e9606d2
ZL
5251 kfree(bbio);
5252}
5253
0b3d4cd3
LB
5254/* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5255/*
5256 * Please note that, discard won't be sent to target device of device
5257 * replace.
5258 */
5259static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5260 u64 logical, u64 length,
5261 struct btrfs_bio **bbio_ret)
5262{
5263 struct extent_map *em;
5264 struct map_lookup *map;
5265 struct btrfs_bio *bbio;
5266 u64 offset;
5267 u64 stripe_nr;
5268 u64 stripe_nr_end;
5269 u64 stripe_end_offset;
5270 u64 stripe_cnt;
5271 u64 stripe_len;
5272 u64 stripe_offset;
5273 u64 num_stripes;
5274 u32 stripe_index;
5275 u32 factor = 0;
5276 u32 sub_stripes = 0;
5277 u64 stripes_per_dev = 0;
5278 u32 remaining_stripes = 0;
5279 u32 last_stripe = 0;
5280 int ret = 0;
5281 int i;
5282
5283 /* discard always return a bbio */
5284 ASSERT(bbio_ret);
5285
5286 em = get_chunk_map(fs_info, logical, length);
5287 if (IS_ERR(em))
5288 return PTR_ERR(em);
5289
5290 map = em->map_lookup;
5291 /* we don't discard raid56 yet */
5292 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5293 ret = -EOPNOTSUPP;
5294 goto out;
5295 }
5296
5297 offset = logical - em->start;
5298 length = min_t(u64, em->len - offset, length);
5299
5300 stripe_len = map->stripe_len;
5301 /*
5302 * stripe_nr counts the total number of stripes we have to stride
5303 * to get to this block
5304 */
5305 stripe_nr = div64_u64(offset, stripe_len);
5306
5307 /* stripe_offset is the offset of this block in its stripe */
5308 stripe_offset = offset - stripe_nr * stripe_len;
5309
5310 stripe_nr_end = round_up(offset + length, map->stripe_len);
42c61ab6 5311 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
0b3d4cd3
LB
5312 stripe_cnt = stripe_nr_end - stripe_nr;
5313 stripe_end_offset = stripe_nr_end * map->stripe_len -
5314 (offset + length);
5315 /*
5316 * after this, stripe_nr is the number of stripes on this
5317 * device we have to walk to find the data, and stripe_index is
5318 * the number of our device in the stripe array
5319 */
5320 num_stripes = 1;
5321 stripe_index = 0;
5322 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5323 BTRFS_BLOCK_GROUP_RAID10)) {
5324 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5325 sub_stripes = 1;
5326 else
5327 sub_stripes = map->sub_stripes;
5328
5329 factor = map->num_stripes / sub_stripes;
5330 num_stripes = min_t(u64, map->num_stripes,
5331 sub_stripes * stripe_cnt);
5332 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5333 stripe_index *= sub_stripes;
5334 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5335 &remaining_stripes);
5336 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5337 last_stripe *= sub_stripes;
5338 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5339 BTRFS_BLOCK_GROUP_DUP)) {
5340 num_stripes = map->num_stripes;
5341 } else {
5342 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5343 &stripe_index);
5344 }
5345
5346 bbio = alloc_btrfs_bio(num_stripes, 0);
5347 if (!bbio) {
5348 ret = -ENOMEM;
5349 goto out;
5350 }
5351
5352 for (i = 0; i < num_stripes; i++) {
5353 bbio->stripes[i].physical =
5354 map->stripes[stripe_index].physical +
5355 stripe_offset + stripe_nr * map->stripe_len;
5356 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5357
5358 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5359 BTRFS_BLOCK_GROUP_RAID10)) {
5360 bbio->stripes[i].length = stripes_per_dev *
5361 map->stripe_len;
5362
5363 if (i / sub_stripes < remaining_stripes)
5364 bbio->stripes[i].length +=
5365 map->stripe_len;
5366
5367 /*
5368 * Special for the first stripe and
5369 * the last stripe:
5370 *
5371 * |-------|...|-------|
5372 * |----------|
5373 * off end_off
5374 */
5375 if (i < sub_stripes)
5376 bbio->stripes[i].length -=
5377 stripe_offset;
5378
5379 if (stripe_index >= last_stripe &&
5380 stripe_index <= (last_stripe +
5381 sub_stripes - 1))
5382 bbio->stripes[i].length -=
5383 stripe_end_offset;
5384
5385 if (i == sub_stripes - 1)
5386 stripe_offset = 0;
5387 } else {
5388 bbio->stripes[i].length = length;
5389 }
5390
5391 stripe_index++;
5392 if (stripe_index == map->num_stripes) {
5393 stripe_index = 0;
5394 stripe_nr++;
5395 }
5396 }
5397
5398 *bbio_ret = bbio;
5399 bbio->map_type = map->type;
5400 bbio->num_stripes = num_stripes;
5401out:
5402 free_extent_map(em);
5403 return ret;
5404}
5405
5ab56090
LB
5406/*
5407 * In dev-replace case, for repair case (that's the only case where the mirror
5408 * is selected explicitly when calling btrfs_map_block), blocks left of the
5409 * left cursor can also be read from the target drive.
5410 *
5411 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5412 * array of stripes.
5413 * For READ, it also needs to be supported using the same mirror number.
5414 *
5415 * If the requested block is not left of the left cursor, EIO is returned. This
5416 * can happen because btrfs_num_copies() returns one more in the dev-replace
5417 * case.
5418 */
5419static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5420 u64 logical, u64 length,
5421 u64 srcdev_devid, int *mirror_num,
5422 u64 *physical)
5423{
5424 struct btrfs_bio *bbio = NULL;
5425 int num_stripes;
5426 int index_srcdev = 0;
5427 int found = 0;
5428 u64 physical_of_found = 0;
5429 int i;
5430 int ret = 0;
5431
5432 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5433 logical, &length, &bbio, 0, 0);
5434 if (ret) {
5435 ASSERT(bbio == NULL);
5436 return ret;
5437 }
5438
5439 num_stripes = bbio->num_stripes;
5440 if (*mirror_num > num_stripes) {
5441 /*
5442 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5443 * that means that the requested area is not left of the left
5444 * cursor
5445 */
5446 btrfs_put_bbio(bbio);
5447 return -EIO;
5448 }
5449
5450 /*
5451 * process the rest of the function using the mirror_num of the source
5452 * drive. Therefore look it up first. At the end, patch the device
5453 * pointer to the one of the target drive.
5454 */
5455 for (i = 0; i < num_stripes; i++) {
5456 if (bbio->stripes[i].dev->devid != srcdev_devid)
5457 continue;
5458
5459 /*
5460 * In case of DUP, in order to keep it simple, only add the
5461 * mirror with the lowest physical address
5462 */
5463 if (found &&
5464 physical_of_found <= bbio->stripes[i].physical)
5465 continue;
5466
5467 index_srcdev = i;
5468 found = 1;
5469 physical_of_found = bbio->stripes[i].physical;
5470 }
5471
5472 btrfs_put_bbio(bbio);
5473
5474 ASSERT(found);
5475 if (!found)
5476 return -EIO;
5477
5478 *mirror_num = index_srcdev + 1;
5479 *physical = physical_of_found;
5480 return ret;
5481}
5482
73c0f228
LB
5483static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5484 struct btrfs_bio **bbio_ret,
5485 struct btrfs_dev_replace *dev_replace,
5486 int *num_stripes_ret, int *max_errors_ret)
5487{
5488 struct btrfs_bio *bbio = *bbio_ret;
5489 u64 srcdev_devid = dev_replace->srcdev->devid;
5490 int tgtdev_indexes = 0;
5491 int num_stripes = *num_stripes_ret;
5492 int max_errors = *max_errors_ret;
5493 int i;
5494
5495 if (op == BTRFS_MAP_WRITE) {
5496 int index_where_to_add;
5497
5498 /*
5499 * duplicate the write operations while the dev replace
5500 * procedure is running. Since the copying of the old disk to
5501 * the new disk takes place at run time while the filesystem is
5502 * mounted writable, the regular write operations to the old
5503 * disk have to be duplicated to go to the new disk as well.
5504 *
5505 * Note that device->missing is handled by the caller, and that
5506 * the write to the old disk is already set up in the stripes
5507 * array.
5508 */
5509 index_where_to_add = num_stripes;
5510 for (i = 0; i < num_stripes; i++) {
5511 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5512 /* write to new disk, too */
5513 struct btrfs_bio_stripe *new =
5514 bbio->stripes + index_where_to_add;
5515 struct btrfs_bio_stripe *old =
5516 bbio->stripes + i;
5517
5518 new->physical = old->physical;
5519 new->length = old->length;
5520 new->dev = dev_replace->tgtdev;
5521 bbio->tgtdev_map[i] = index_where_to_add;
5522 index_where_to_add++;
5523 max_errors++;
5524 tgtdev_indexes++;
5525 }
5526 }
5527 num_stripes = index_where_to_add;
5528 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5529 int index_srcdev = 0;
5530 int found = 0;
5531 u64 physical_of_found = 0;
5532
5533 /*
5534 * During the dev-replace procedure, the target drive can also
5535 * be used to read data in case it is needed to repair a corrupt
5536 * block elsewhere. This is possible if the requested area is
5537 * left of the left cursor. In this area, the target drive is a
5538 * full copy of the source drive.
5539 */
5540 for (i = 0; i < num_stripes; i++) {
5541 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5542 /*
5543 * In case of DUP, in order to keep it simple,
5544 * only add the mirror with the lowest physical
5545 * address
5546 */
5547 if (found &&
5548 physical_of_found <=
5549 bbio->stripes[i].physical)
5550 continue;
5551 index_srcdev = i;
5552 found = 1;
5553 physical_of_found = bbio->stripes[i].physical;
5554 }
5555 }
5556 if (found) {
5557 struct btrfs_bio_stripe *tgtdev_stripe =
5558 bbio->stripes + num_stripes;
5559
5560 tgtdev_stripe->physical = physical_of_found;
5561 tgtdev_stripe->length =
5562 bbio->stripes[index_srcdev].length;
5563 tgtdev_stripe->dev = dev_replace->tgtdev;
5564 bbio->tgtdev_map[index_srcdev] = num_stripes;
5565
5566 tgtdev_indexes++;
5567 num_stripes++;
5568 }
5569 }
5570
5571 *num_stripes_ret = num_stripes;
5572 *max_errors_ret = max_errors;
5573 bbio->num_tgtdevs = tgtdev_indexes;
5574 *bbio_ret = bbio;
5575}
5576
2b19a1fe
LB
5577static bool need_full_stripe(enum btrfs_map_op op)
5578{
5579 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5580}
5581
cf8cddd3
CH
5582static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5583 enum btrfs_map_op op,
f2d8d74d 5584 u64 logical, u64 *length,
a1d3c478 5585 struct btrfs_bio **bbio_ret,
8e5cfb55 5586 int mirror_num, int need_raid_map)
0b86a832
CM
5587{
5588 struct extent_map *em;
5589 struct map_lookup *map;
0b86a832 5590 u64 offset;
593060d7
CM
5591 u64 stripe_offset;
5592 u64 stripe_nr;
53b381b3 5593 u64 stripe_len;
9d644a62 5594 u32 stripe_index;
cea9e445 5595 int i;
de11cc12 5596 int ret = 0;
f2d8d74d 5597 int num_stripes;
a236aed1 5598 int max_errors = 0;
2c8cdd6e 5599 int tgtdev_indexes = 0;
a1d3c478 5600 struct btrfs_bio *bbio = NULL;
472262f3
SB
5601 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5602 int dev_replace_is_ongoing = 0;
5603 int num_alloc_stripes;
ad6d620e
SB
5604 int patch_the_first_stripe_for_dev_replace = 0;
5605 u64 physical_to_patch_in_first_stripe = 0;
53b381b3 5606 u64 raid56_full_stripe_start = (u64)-1;
0b86a832 5607
0b3d4cd3
LB
5608 if (op == BTRFS_MAP_DISCARD)
5609 return __btrfs_map_block_for_discard(fs_info, logical,
5610 *length, bbio_ret);
5611
592d92ee
LB
5612 em = get_chunk_map(fs_info, logical, *length);
5613 if (IS_ERR(em))
5614 return PTR_ERR(em);
0b86a832 5615
95617d69 5616 map = em->map_lookup;
0b86a832 5617 offset = logical - em->start;
593060d7 5618
53b381b3 5619 stripe_len = map->stripe_len;
593060d7
CM
5620 stripe_nr = offset;
5621 /*
5622 * stripe_nr counts the total number of stripes we have to stride
5623 * to get to this block
5624 */
47c5713f 5625 stripe_nr = div64_u64(stripe_nr, stripe_len);
593060d7 5626
53b381b3 5627 stripe_offset = stripe_nr * stripe_len;
e042d1ec 5628 if (offset < stripe_offset) {
5d163e0e
JM
5629 btrfs_crit(fs_info,
5630 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
e042d1ec
JB
5631 stripe_offset, offset, em->start, logical,
5632 stripe_len);
5633 free_extent_map(em);
5634 return -EINVAL;
5635 }
593060d7
CM
5636
5637 /* stripe_offset is the offset of this block in its stripe*/
5638 stripe_offset = offset - stripe_offset;
5639
53b381b3 5640 /* if we're here for raid56, we need to know the stripe aligned start */
ffe2d203 5641 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
53b381b3
DW
5642 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5643 raid56_full_stripe_start = offset;
5644
5645 /* allow a write of a full stripe, but make sure we don't
5646 * allow straddling of stripes
5647 */
47c5713f
DS
5648 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5649 full_stripe_len);
53b381b3
DW
5650 raid56_full_stripe_start *= full_stripe_len;
5651 }
5652
0b3d4cd3 5653 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
53b381b3
DW
5654 u64 max_len;
5655 /* For writes to RAID[56], allow a full stripeset across all disks.
5656 For other RAID types and for RAID[56] reads, just allow a single
5657 stripe (on a single disk). */
ffe2d203 5658 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
cf8cddd3 5659 (op == BTRFS_MAP_WRITE)) {
53b381b3
DW
5660 max_len = stripe_len * nr_data_stripes(map) -
5661 (offset - raid56_full_stripe_start);
5662 } else {
5663 /* we limit the length of each bio to what fits in a stripe */
5664 max_len = stripe_len - stripe_offset;
5665 }
5666 *length = min_t(u64, em->len - offset, max_len);
cea9e445
CM
5667 } else {
5668 *length = em->len - offset;
5669 }
f2d8d74d 5670
53b381b3
DW
5671 /* This is for when we're called from btrfs_merge_bio_hook() and all
5672 it cares about is the length */
a1d3c478 5673 if (!bbio_ret)
cea9e445
CM
5674 goto out;
5675
7e79cb86 5676 btrfs_dev_replace_read_lock(dev_replace);
472262f3
SB
5677 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5678 if (!dev_replace_is_ongoing)
7e79cb86 5679 btrfs_dev_replace_read_unlock(dev_replace);
73beece9
LB
5680 else
5681 btrfs_dev_replace_set_lock_blocking(dev_replace);
472262f3 5682
ad6d620e 5683 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
2b19a1fe 5684 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
5ab56090
LB
5685 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
5686 dev_replace->srcdev->devid,
5687 &mirror_num,
5688 &physical_to_patch_in_first_stripe);
5689 if (ret)
ad6d620e 5690 goto out;
5ab56090
LB
5691 else
5692 patch_the_first_stripe_for_dev_replace = 1;
ad6d620e
SB
5693 } else if (mirror_num > map->num_stripes) {
5694 mirror_num = 0;
5695 }
5696
f2d8d74d 5697 num_stripes = 1;
cea9e445 5698 stripe_index = 0;
fce3bb9a 5699 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
47c5713f
DS
5700 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5701 &stripe_index);
de483734 5702 if (!need_full_stripe(op))
28e1cc7d 5703 mirror_num = 1;
fce3bb9a 5704 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
de483734 5705 if (need_full_stripe(op))
f2d8d74d 5706 num_stripes = map->num_stripes;
2fff734f 5707 else if (mirror_num)
f188591e 5708 stripe_index = mirror_num - 1;
dfe25020 5709 else {
30d9861f 5710 stripe_index = find_live_mirror(fs_info, map, 0,
30d9861f 5711 dev_replace_is_ongoing);
a1d3c478 5712 mirror_num = stripe_index + 1;
dfe25020 5713 }
2fff734f 5714
611f0e00 5715 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
de483734 5716 if (need_full_stripe(op)) {
f2d8d74d 5717 num_stripes = map->num_stripes;
a1d3c478 5718 } else if (mirror_num) {
f188591e 5719 stripe_index = mirror_num - 1;
a1d3c478
JS
5720 } else {
5721 mirror_num = 1;
5722 }
2fff734f 5723
321aecc6 5724 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
9d644a62 5725 u32 factor = map->num_stripes / map->sub_stripes;
321aecc6 5726
47c5713f 5727 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
321aecc6
CM
5728 stripe_index *= map->sub_stripes;
5729
de483734 5730 if (need_full_stripe(op))
f2d8d74d 5731 num_stripes = map->sub_stripes;
321aecc6
CM
5732 else if (mirror_num)
5733 stripe_index += mirror_num - 1;
dfe25020 5734 else {
3e74317a 5735 int old_stripe_index = stripe_index;
30d9861f
SB
5736 stripe_index = find_live_mirror(fs_info, map,
5737 stripe_index,
30d9861f 5738 dev_replace_is_ongoing);
3e74317a 5739 mirror_num = stripe_index - old_stripe_index + 1;
dfe25020 5740 }
53b381b3 5741
ffe2d203 5742 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
de483734 5743 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
53b381b3 5744 /* push stripe_nr back to the start of the full stripe */
42c61ab6 5745 stripe_nr = div64_u64(raid56_full_stripe_start,
b8b93add 5746 stripe_len * nr_data_stripes(map));
53b381b3
DW
5747
5748 /* RAID[56] write or recovery. Return all stripes */
5749 num_stripes = map->num_stripes;
5750 max_errors = nr_parity_stripes(map);
5751
53b381b3
DW
5752 *length = map->stripe_len;
5753 stripe_index = 0;
5754 stripe_offset = 0;
5755 } else {
5756 /*
5757 * Mirror #0 or #1 means the original data block.
5758 * Mirror #2 is RAID5 parity block.
5759 * Mirror #3 is RAID6 Q block.
5760 */
47c5713f
DS
5761 stripe_nr = div_u64_rem(stripe_nr,
5762 nr_data_stripes(map), &stripe_index);
53b381b3
DW
5763 if (mirror_num > 1)
5764 stripe_index = nr_data_stripes(map) +
5765 mirror_num - 2;
5766
5767 /* We distribute the parity blocks across stripes */
47c5713f
DS
5768 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5769 &stripe_index);
de483734 5770 if (!need_full_stripe(op) && mirror_num <= 1)
28e1cc7d 5771 mirror_num = 1;
53b381b3 5772 }
8790d502
CM
5773 } else {
5774 /*
47c5713f
DS
5775 * after this, stripe_nr is the number of stripes on this
5776 * device we have to walk to find the data, and stripe_index is
5777 * the number of our device in the stripe array
8790d502 5778 */
47c5713f
DS
5779 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5780 &stripe_index);
a1d3c478 5781 mirror_num = stripe_index + 1;
8790d502 5782 }
e042d1ec 5783 if (stripe_index >= map->num_stripes) {
5d163e0e
JM
5784 btrfs_crit(fs_info,
5785 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
e042d1ec
JB
5786 stripe_index, map->num_stripes);
5787 ret = -EINVAL;
5788 goto out;
5789 }
cea9e445 5790
472262f3 5791 num_alloc_stripes = num_stripes;
6fad823f 5792 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
0b3d4cd3 5793 if (op == BTRFS_MAP_WRITE)
ad6d620e 5794 num_alloc_stripes <<= 1;
cf8cddd3 5795 if (op == BTRFS_MAP_GET_READ_MIRRORS)
ad6d620e 5796 num_alloc_stripes++;
2c8cdd6e 5797 tgtdev_indexes = num_stripes;
ad6d620e 5798 }
2c8cdd6e 5799
6e9606d2 5800 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
de11cc12
LZ
5801 if (!bbio) {
5802 ret = -ENOMEM;
5803 goto out;
5804 }
6fad823f 5805 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
2c8cdd6e 5806 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
de11cc12 5807
8e5cfb55 5808 /* build raid_map */
2b19a1fe
LB
5809 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
5810 (need_full_stripe(op) || mirror_num > 1)) {
8e5cfb55 5811 u64 tmp;
9d644a62 5812 unsigned rot;
8e5cfb55
ZL
5813
5814 bbio->raid_map = (u64 *)((void *)bbio->stripes +
5815 sizeof(struct btrfs_bio_stripe) *
5816 num_alloc_stripes +
5817 sizeof(int) * tgtdev_indexes);
5818
5819 /* Work out the disk rotation on this stripe-set */
47c5713f 5820 div_u64_rem(stripe_nr, num_stripes, &rot);
8e5cfb55
ZL
5821
5822 /* Fill in the logical address of each stripe */
5823 tmp = stripe_nr * nr_data_stripes(map);
5824 for (i = 0; i < nr_data_stripes(map); i++)
5825 bbio->raid_map[(i+rot) % num_stripes] =
5826 em->start + (tmp + i) * map->stripe_len;
5827
5828 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5829 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5830 bbio->raid_map[(i+rot+1) % num_stripes] =
5831 RAID6_Q_STRIPE;
5832 }
5833
b89203f7 5834
0b3d4cd3
LB
5835 for (i = 0; i < num_stripes; i++) {
5836 bbio->stripes[i].physical =
5837 map->stripes[stripe_index].physical +
5838 stripe_offset +
5839 stripe_nr * map->stripe_len;
5840 bbio->stripes[i].dev =
5841 map->stripes[stripe_index].dev;
5842 stripe_index++;
593060d7 5843 }
de11cc12 5844
2b19a1fe 5845 if (need_full_stripe(op))
d20983b4 5846 max_errors = btrfs_chunk_max_errors(map);
de11cc12 5847
8e5cfb55
ZL
5848 if (bbio->raid_map)
5849 sort_parity_stripes(bbio, num_stripes);
cc7539ed 5850
73c0f228 5851 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
2b19a1fe 5852 need_full_stripe(op)) {
73c0f228
LB
5853 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
5854 &max_errors);
472262f3
SB
5855 }
5856
de11cc12 5857 *bbio_ret = bbio;
10f11900 5858 bbio->map_type = map->type;
de11cc12
LZ
5859 bbio->num_stripes = num_stripes;
5860 bbio->max_errors = max_errors;
5861 bbio->mirror_num = mirror_num;
ad6d620e
SB
5862
5863 /*
5864 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5865 * mirror_num == num_stripes + 1 && dev_replace target drive is
5866 * available as a mirror
5867 */
5868 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5869 WARN_ON(num_stripes > 1);
5870 bbio->stripes[0].dev = dev_replace->tgtdev;
5871 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5872 bbio->mirror_num = map->num_stripes + 1;
5873 }
cea9e445 5874out:
73beece9
LB
5875 if (dev_replace_is_ongoing) {
5876 btrfs_dev_replace_clear_lock_blocking(dev_replace);
7e79cb86 5877 btrfs_dev_replace_read_unlock(dev_replace);
73beece9 5878 }
0b86a832 5879 free_extent_map(em);
de11cc12 5880 return ret;
0b86a832
CM
5881}
5882
cf8cddd3 5883int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
f2d8d74d 5884 u64 logical, u64 *length,
a1d3c478 5885 struct btrfs_bio **bbio_ret, int mirror_num)
f2d8d74d 5886{
b3d3fa51 5887 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
8e5cfb55 5888 mirror_num, 0);
f2d8d74d
CM
5889}
5890
af8e2d1d 5891/* For Scrub/replace */
cf8cddd3 5892int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
af8e2d1d 5893 u64 logical, u64 *length,
825ad4c9 5894 struct btrfs_bio **bbio_ret)
af8e2d1d 5895{
825ad4c9 5896 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
af8e2d1d
MX
5897}
5898
63a9c7b9
NB
5899int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
5900 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
a512bbf8 5901{
a512bbf8
YZ
5902 struct extent_map *em;
5903 struct map_lookup *map;
5904 u64 *buf;
5905 u64 bytenr;
5906 u64 length;
5907 u64 stripe_nr;
53b381b3 5908 u64 rmap_len;
a512bbf8
YZ
5909 int i, j, nr = 0;
5910
592d92ee
LB
5911 em = get_chunk_map(fs_info, chunk_start, 1);
5912 if (IS_ERR(em))
835d974f 5913 return -EIO;
835d974f 5914
95617d69 5915 map = em->map_lookup;
a512bbf8 5916 length = em->len;
53b381b3
DW
5917 rmap_len = map->stripe_len;
5918
a512bbf8 5919 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
b8b93add 5920 length = div_u64(length, map->num_stripes / map->sub_stripes);
a512bbf8 5921 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
b8b93add 5922 length = div_u64(length, map->num_stripes);
ffe2d203 5923 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
b8b93add 5924 length = div_u64(length, nr_data_stripes(map));
53b381b3
DW
5925 rmap_len = map->stripe_len * nr_data_stripes(map);
5926 }
a512bbf8 5927
31e818fe 5928 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
79787eaa 5929 BUG_ON(!buf); /* -ENOMEM */
a512bbf8
YZ
5930
5931 for (i = 0; i < map->num_stripes; i++) {
a512bbf8
YZ
5932 if (map->stripes[i].physical > physical ||
5933 map->stripes[i].physical + length <= physical)
5934 continue;
5935
5936 stripe_nr = physical - map->stripes[i].physical;
42c61ab6 5937 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
a512bbf8
YZ
5938
5939 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5940 stripe_nr = stripe_nr * map->num_stripes + i;
b8b93add 5941 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
a512bbf8
YZ
5942 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5943 stripe_nr = stripe_nr * map->num_stripes + i;
53b381b3
DW
5944 } /* else if RAID[56], multiply by nr_data_stripes().
5945 * Alternatively, just use rmap_len below instead of
5946 * map->stripe_len */
5947
5948 bytenr = chunk_start + stripe_nr * rmap_len;
934d375b 5949 WARN_ON(nr >= map->num_stripes);
a512bbf8
YZ
5950 for (j = 0; j < nr; j++) {
5951 if (buf[j] == bytenr)
5952 break;
5953 }
934d375b
CM
5954 if (j == nr) {
5955 WARN_ON(nr >= map->num_stripes);
a512bbf8 5956 buf[nr++] = bytenr;
934d375b 5957 }
a512bbf8
YZ
5958 }
5959
a512bbf8
YZ
5960 *logical = buf;
5961 *naddrs = nr;
53b381b3 5962 *stripe_len = rmap_len;
a512bbf8
YZ
5963
5964 free_extent_map(em);
5965 return 0;
f2d8d74d
CM
5966}
5967
4246a0b6 5968static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
8408c716 5969{
326e1dbb
MS
5970 bio->bi_private = bbio->private;
5971 bio->bi_end_io = bbio->end_io;
4246a0b6 5972 bio_endio(bio);
326e1dbb 5973
6e9606d2 5974 btrfs_put_bbio(bbio);
8408c716
MX
5975}
5976
4246a0b6 5977static void btrfs_end_bio(struct bio *bio)
8790d502 5978{
9be3395b 5979 struct btrfs_bio *bbio = bio->bi_private;
7d2b4daa 5980 int is_orig_bio = 0;
8790d502 5981
4e4cbee9 5982 if (bio->bi_status) {
a1d3c478 5983 atomic_inc(&bbio->error);
4e4cbee9
CH
5984 if (bio->bi_status == BLK_STS_IOERR ||
5985 bio->bi_status == BLK_STS_TARGET) {
442a4f63 5986 unsigned int stripe_index =
9be3395b 5987 btrfs_io_bio(bio)->stripe_index;
65f53338 5988 struct btrfs_device *dev;
442a4f63
SB
5989
5990 BUG_ON(stripe_index >= bbio->num_stripes);
5991 dev = bbio->stripes[stripe_index].dev;
597a60fa 5992 if (dev->bdev) {
37226b21 5993 if (bio_op(bio) == REQ_OP_WRITE)
1cb34c8e 5994 btrfs_dev_stat_inc_and_print(dev,
597a60fa
SB
5995 BTRFS_DEV_STAT_WRITE_ERRS);
5996 else
1cb34c8e 5997 btrfs_dev_stat_inc_and_print(dev,
597a60fa 5998 BTRFS_DEV_STAT_READ_ERRS);
70fd7614 5999 if (bio->bi_opf & REQ_PREFLUSH)
1cb34c8e 6000 btrfs_dev_stat_inc_and_print(dev,
597a60fa 6001 BTRFS_DEV_STAT_FLUSH_ERRS);
597a60fa 6002 }
442a4f63
SB
6003 }
6004 }
8790d502 6005
a1d3c478 6006 if (bio == bbio->orig_bio)
7d2b4daa
CM
6007 is_orig_bio = 1;
6008
c404e0dc
MX
6009 btrfs_bio_counter_dec(bbio->fs_info);
6010
a1d3c478 6011 if (atomic_dec_and_test(&bbio->stripes_pending)) {
7d2b4daa
CM
6012 if (!is_orig_bio) {
6013 bio_put(bio);
a1d3c478 6014 bio = bbio->orig_bio;
7d2b4daa 6015 }
c7b22bb1 6016
9be3395b 6017 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
a236aed1 6018 /* only send an error to the higher layers if it is
53b381b3 6019 * beyond the tolerance of the btrfs bio
a236aed1 6020 */
a1d3c478 6021 if (atomic_read(&bbio->error) > bbio->max_errors) {
4e4cbee9 6022 bio->bi_status = BLK_STS_IOERR;
5dbc8fca 6023 } else {
1259ab75
CM
6024 /*
6025 * this bio is actually up to date, we didn't
6026 * go over the max number of errors
6027 */
2dbe0c77 6028 bio->bi_status = BLK_STS_OK;
1259ab75 6029 }
c55f1396 6030
4246a0b6 6031 btrfs_end_bbio(bbio, bio);
7d2b4daa 6032 } else if (!is_orig_bio) {
8790d502
CM
6033 bio_put(bio);
6034 }
8790d502
CM
6035}
6036
8b712842
CM
6037/*
6038 * see run_scheduled_bios for a description of why bios are collected for
6039 * async submit.
6040 *
6041 * This will add one bio to the pending list for a device and make sure
6042 * the work struct is scheduled.
6043 */
2ff7e61e 6044static noinline void btrfs_schedule_bio(struct btrfs_device *device,
4e49ea4a 6045 struct bio *bio)
8b712842 6046{
0b246afa 6047 struct btrfs_fs_info *fs_info = device->fs_info;
8b712842 6048 int should_queue = 1;
ffbd517d 6049 struct btrfs_pending_bios *pending_bios;
8b712842 6050
e6e674bd
AJ
6051 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state) ||
6052 !device->bdev) {
4246a0b6 6053 bio_io_error(bio);
53b381b3
DW
6054 return;
6055 }
6056
8b712842 6057 /* don't bother with additional async steps for reads, right now */
37226b21 6058 if (bio_op(bio) == REQ_OP_READ) {
4e49ea4a 6059 btrfsic_submit_bio(bio);
143bede5 6060 return;
8b712842
CM
6061 }
6062
492bb6de 6063 WARN_ON(bio->bi_next);
8b712842 6064 bio->bi_next = NULL;
8b712842
CM
6065
6066 spin_lock(&device->io_lock);
67f055c7 6067 if (op_is_sync(bio->bi_opf))
ffbd517d
CM
6068 pending_bios = &device->pending_sync_bios;
6069 else
6070 pending_bios = &device->pending_bios;
8b712842 6071
ffbd517d
CM
6072 if (pending_bios->tail)
6073 pending_bios->tail->bi_next = bio;
8b712842 6074
ffbd517d
CM
6075 pending_bios->tail = bio;
6076 if (!pending_bios->head)
6077 pending_bios->head = bio;
8b712842
CM
6078 if (device->running_pending)
6079 should_queue = 0;
6080
6081 spin_unlock(&device->io_lock);
6082
6083 if (should_queue)
0b246afa 6084 btrfs_queue_work(fs_info->submit_workers, &device->work);
8b712842
CM
6085}
6086
2ff7e61e
JM
6087static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6088 u64 physical, int dev_nr, int async)
de1ee92a
JB
6089{
6090 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
2ff7e61e 6091 struct btrfs_fs_info *fs_info = bbio->fs_info;
de1ee92a
JB
6092
6093 bio->bi_private = bbio;
9be3395b 6094 btrfs_io_bio(bio)->stripe_index = dev_nr;
de1ee92a 6095 bio->bi_end_io = btrfs_end_bio;
4f024f37 6096 bio->bi_iter.bi_sector = physical >> 9;
672d5990
MT
6097 btrfs_debug_in_rcu(fs_info,
6098 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6099 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6100 (u_long)dev->bdev->bd_dev, rcu_str_deref(dev->name), dev->devid,
6101 bio->bi_iter.bi_size);
74d46992 6102 bio_set_dev(bio, dev->bdev);
c404e0dc 6103
2ff7e61e 6104 btrfs_bio_counter_inc_noblocked(fs_info);
c404e0dc 6105
de1ee92a 6106 if (async)
2ff7e61e 6107 btrfs_schedule_bio(dev, bio);
de1ee92a 6108 else
4e49ea4a 6109 btrfsic_submit_bio(bio);
de1ee92a
JB
6110}
6111
de1ee92a
JB
6112static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6113{
6114 atomic_inc(&bbio->error);
6115 if (atomic_dec_and_test(&bbio->stripes_pending)) {
01327610 6116 /* Should be the original bio. */
8408c716
MX
6117 WARN_ON(bio != bbio->orig_bio);
6118
9be3395b 6119 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
4f024f37 6120 bio->bi_iter.bi_sector = logical >> 9;
102ed2c5
AJ
6121 if (atomic_read(&bbio->error) > bbio->max_errors)
6122 bio->bi_status = BLK_STS_IOERR;
6123 else
6124 bio->bi_status = BLK_STS_OK;
4246a0b6 6125 btrfs_end_bbio(bbio, bio);
de1ee92a
JB
6126 }
6127}
6128
58efbc9f
OS
6129blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6130 int mirror_num, int async_submit)
0b86a832 6131{
0b86a832 6132 struct btrfs_device *dev;
8790d502 6133 struct bio *first_bio = bio;
4f024f37 6134 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
0b86a832
CM
6135 u64 length = 0;
6136 u64 map_length;
0b86a832 6137 int ret;
08da757d
ZL
6138 int dev_nr;
6139 int total_devs;
a1d3c478 6140 struct btrfs_bio *bbio = NULL;
0b86a832 6141
4f024f37 6142 length = bio->bi_iter.bi_size;
0b86a832 6143 map_length = length;
cea9e445 6144
0b246afa 6145 btrfs_bio_counter_inc_blocked(fs_info);
bd7d63c2 6146 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
37226b21 6147 &map_length, &bbio, mirror_num, 1);
c404e0dc 6148 if (ret) {
0b246afa 6149 btrfs_bio_counter_dec(fs_info);
58efbc9f 6150 return errno_to_blk_status(ret);
c404e0dc 6151 }
cea9e445 6152
a1d3c478 6153 total_devs = bbio->num_stripes;
53b381b3
DW
6154 bbio->orig_bio = first_bio;
6155 bbio->private = first_bio->bi_private;
6156 bbio->end_io = first_bio->bi_end_io;
0b246afa 6157 bbio->fs_info = fs_info;
53b381b3
DW
6158 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6159
ad1ba2a0 6160 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
37226b21 6161 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
53b381b3
DW
6162 /* In this case, map_length has been set to the length of
6163 a single stripe; not the whole write */
37226b21 6164 if (bio_op(bio) == REQ_OP_WRITE) {
2ff7e61e
JM
6165 ret = raid56_parity_write(fs_info, bio, bbio,
6166 map_length);
53b381b3 6167 } else {
2ff7e61e
JM
6168 ret = raid56_parity_recover(fs_info, bio, bbio,
6169 map_length, mirror_num, 1);
53b381b3 6170 }
4245215d 6171
0b246afa 6172 btrfs_bio_counter_dec(fs_info);
58efbc9f 6173 return errno_to_blk_status(ret);
53b381b3
DW
6174 }
6175
cea9e445 6176 if (map_length < length) {
0b246afa 6177 btrfs_crit(fs_info,
5d163e0e
JM
6178 "mapping failed logical %llu bio len %llu len %llu",
6179 logical, length, map_length);
cea9e445
CM
6180 BUG();
6181 }
a1d3c478 6182
08da757d 6183 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
de1ee92a 6184 dev = bbio->stripes[dev_nr].dev;
37226b21 6185 if (!dev || !dev->bdev ||
ebbede42
AJ
6186 (bio_op(first_bio) == REQ_OP_WRITE &&
6187 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
de1ee92a 6188 bbio_error(bbio, first_bio, logical);
de1ee92a
JB
6189 continue;
6190 }
6191
3aa8e074 6192 if (dev_nr < total_devs - 1)
8b6c1d56 6193 bio = btrfs_bio_clone(first_bio);
3aa8e074 6194 else
a1d3c478 6195 bio = first_bio;
de1ee92a 6196
2ff7e61e
JM
6197 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6198 dev_nr, async_submit);
8790d502 6199 }
0b246afa 6200 btrfs_bio_counter_dec(fs_info);
58efbc9f 6201 return BLK_STS_OK;
0b86a832
CM
6202}
6203
aa1b8cd4 6204struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
2b82032c 6205 u8 *uuid, u8 *fsid)
0b86a832 6206{
2b82032c
YZ
6207 struct btrfs_device *device;
6208 struct btrfs_fs_devices *cur_devices;
6209
aa1b8cd4 6210 cur_devices = fs_info->fs_devices;
2b82032c
YZ
6211 while (cur_devices) {
6212 if (!fsid ||
44880fdc 6213 !memcmp(cur_devices->fsid, fsid, BTRFS_FSID_SIZE)) {
35c70103 6214 device = find_device(cur_devices, devid, uuid);
2b82032c
YZ
6215 if (device)
6216 return device;
6217 }
6218 cur_devices = cur_devices->seed;
6219 }
6220 return NULL;
0b86a832
CM
6221}
6222
2ff7e61e 6223static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
dfe25020
CM
6224 u64 devid, u8 *dev_uuid)
6225{
6226 struct btrfs_device *device;
dfe25020 6227
12bd2fc0
ID
6228 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6229 if (IS_ERR(device))
adfb69af 6230 return device;
12bd2fc0
ID
6231
6232 list_add(&device->dev_list, &fs_devices->devices);
e4404d6e 6233 device->fs_devices = fs_devices;
dfe25020 6234 fs_devices->num_devices++;
12bd2fc0 6235
e6e674bd 6236 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
cd02dca5 6237 fs_devices->missing_devices++;
12bd2fc0 6238
dfe25020
CM
6239 return device;
6240}
6241
12bd2fc0
ID
6242/**
6243 * btrfs_alloc_device - allocate struct btrfs_device
6244 * @fs_info: used only for generating a new devid, can be NULL if
6245 * devid is provided (i.e. @devid != NULL).
6246 * @devid: a pointer to devid for this device. If NULL a new devid
6247 * is generated.
6248 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6249 * is generated.
6250 *
6251 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
48dae9cf 6252 * on error. Returned struct is not linked onto any lists and must be
a425f9d4 6253 * destroyed with btrfs_free_device.
12bd2fc0
ID
6254 */
6255struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6256 const u64 *devid,
6257 const u8 *uuid)
6258{
6259 struct btrfs_device *dev;
6260 u64 tmp;
6261
fae7f21c 6262 if (WARN_ON(!devid && !fs_info))
12bd2fc0 6263 return ERR_PTR(-EINVAL);
12bd2fc0
ID
6264
6265 dev = __alloc_device();
6266 if (IS_ERR(dev))
6267 return dev;
6268
6269 if (devid)
6270 tmp = *devid;
6271 else {
6272 int ret;
6273
6274 ret = find_next_devid(fs_info, &tmp);
6275 if (ret) {
a425f9d4 6276 btrfs_free_device(dev);
12bd2fc0
ID
6277 return ERR_PTR(ret);
6278 }
6279 }
6280 dev->devid = tmp;
6281
6282 if (uuid)
6283 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6284 else
6285 generate_random_uuid(dev->uuid);
6286
9e0af237
LB
6287 btrfs_init_work(&dev->work, btrfs_submit_helper,
6288 pending_bios_fn, NULL, NULL);
12bd2fc0
ID
6289
6290 return dev;
6291}
6292
e06cd3dd 6293/* Return -EIO if any error, otherwise return 0. */
2ff7e61e 6294static int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info,
e06cd3dd
LB
6295 struct extent_buffer *leaf,
6296 struct btrfs_chunk *chunk, u64 logical)
0b86a832 6297{
0b86a832 6298 u64 length;
f04b772b 6299 u64 stripe_len;
e06cd3dd
LB
6300 u16 num_stripes;
6301 u16 sub_stripes;
6302 u64 type;
315409b0
GJ
6303 u64 features;
6304 bool mixed = false;
0b86a832 6305
e17cade2 6306 length = btrfs_chunk_length(leaf, chunk);
f04b772b
QW
6307 stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6308 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
e06cd3dd
LB
6309 sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6310 type = btrfs_chunk_type(leaf, chunk);
6311
f04b772b 6312 if (!num_stripes) {
0b246afa 6313 btrfs_err(fs_info, "invalid chunk num_stripes: %u",
f04b772b
QW
6314 num_stripes);
6315 return -EIO;
6316 }
0b246afa
JM
6317 if (!IS_ALIGNED(logical, fs_info->sectorsize)) {
6318 btrfs_err(fs_info, "invalid chunk logical %llu", logical);
f04b772b
QW
6319 return -EIO;
6320 }
0b246afa
JM
6321 if (btrfs_chunk_sector_size(leaf, chunk) != fs_info->sectorsize) {
6322 btrfs_err(fs_info, "invalid chunk sectorsize %u",
e06cd3dd
LB
6323 btrfs_chunk_sector_size(leaf, chunk));
6324 return -EIO;
6325 }
0b246afa
JM
6326 if (!length || !IS_ALIGNED(length, fs_info->sectorsize)) {
6327 btrfs_err(fs_info, "invalid chunk length %llu", length);
f04b772b
QW
6328 return -EIO;
6329 }
3d8da678 6330 if (!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN) {
0b246afa 6331 btrfs_err(fs_info, "invalid chunk stripe length: %llu",
f04b772b
QW
6332 stripe_len);
6333 return -EIO;
6334 }
6335 if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
e06cd3dd 6336 type) {
0b246afa 6337 btrfs_err(fs_info, "unrecognized chunk type: %llu",
f04b772b
QW
6338 ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
6339 BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6340 btrfs_chunk_type(leaf, chunk));
6341 return -EIO;
6342 }
315409b0
GJ
6343
6344 if ((type & BTRFS_BLOCK_GROUP_TYPE_MASK) == 0) {
6345 btrfs_err(fs_info, "missing chunk type flag: 0x%llx", type);
6346 return -EIO;
6347 }
6348
6349 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) &&
6350 (type & (BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA))) {
6351 btrfs_err(fs_info,
6352 "system chunk with data or metadata type: 0x%llx", type);
6353 return -EIO;
6354 }
6355
6356 features = btrfs_super_incompat_flags(fs_info->super_copy);
6357 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
6358 mixed = true;
6359
6360 if (!mixed) {
6361 if ((type & BTRFS_BLOCK_GROUP_METADATA) &&
6362 (type & BTRFS_BLOCK_GROUP_DATA)) {
6363 btrfs_err(fs_info,
6364 "mixed chunk type in non-mixed mode: 0x%llx", type);
6365 return -EIO;
6366 }
6367 }
6368
e06cd3dd
LB
6369 if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes != 2) ||
6370 (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes < 1) ||
6371 (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
6372 (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
6373 (type & BTRFS_BLOCK_GROUP_DUP && num_stripes > 2) ||
6374 ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
6375 num_stripes != 1)) {
0b246afa 6376 btrfs_err(fs_info,
e06cd3dd
LB
6377 "invalid num_stripes:sub_stripes %u:%u for profile %llu",
6378 num_stripes, sub_stripes,
6379 type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
6380 return -EIO;
6381 }
6382
6383 return 0;
6384}
6385
5a2b8e60 6386static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
2b902dfc 6387 u64 devid, u8 *uuid, bool error)
5a2b8e60 6388{
2b902dfc
AJ
6389 if (error)
6390 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6391 devid, uuid);
6392 else
6393 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6394 devid, uuid);
5a2b8e60
AJ
6395}
6396
2ff7e61e 6397static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
e06cd3dd
LB
6398 struct extent_buffer *leaf,
6399 struct btrfs_chunk *chunk)
6400{
0b246afa 6401 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
e06cd3dd
LB
6402 struct map_lookup *map;
6403 struct extent_map *em;
6404 u64 logical;
6405 u64 length;
e06cd3dd
LB
6406 u64 devid;
6407 u8 uuid[BTRFS_UUID_SIZE];
6408 int num_stripes;
6409 int ret;
6410 int i;
6411
6412 logical = key->offset;
6413 length = btrfs_chunk_length(leaf, chunk);
e06cd3dd
LB
6414 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6415
2ff7e61e 6416 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
e06cd3dd
LB
6417 if (ret)
6418 return ret;
a061fc8d 6419
890871be 6420 read_lock(&map_tree->map_tree.lock);
0b86a832 6421 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
890871be 6422 read_unlock(&map_tree->map_tree.lock);
0b86a832
CM
6423
6424 /* already mapped? */
6425 if (em && em->start <= logical && em->start + em->len > logical) {
6426 free_extent_map(em);
0b86a832
CM
6427 return 0;
6428 } else if (em) {
6429 free_extent_map(em);
6430 }
0b86a832 6431
172ddd60 6432 em = alloc_extent_map();
0b86a832
CM
6433 if (!em)
6434 return -ENOMEM;
593060d7 6435 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
0b86a832
CM
6436 if (!map) {
6437 free_extent_map(em);
6438 return -ENOMEM;
6439 }
6440
298a8f9c 6441 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
95617d69 6442 em->map_lookup = map;
0b86a832
CM
6443 em->start = logical;
6444 em->len = length;
70c8a91c 6445 em->orig_start = 0;
0b86a832 6446 em->block_start = 0;
c8b97818 6447 em->block_len = em->len;
0b86a832 6448
593060d7
CM
6449 map->num_stripes = num_stripes;
6450 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6451 map->io_align = btrfs_chunk_io_align(leaf, chunk);
593060d7
CM
6452 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6453 map->type = btrfs_chunk_type(leaf, chunk);
321aecc6 6454 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
cf90d884 6455 map->verified_stripes = 0;
593060d7
CM
6456 for (i = 0; i < num_stripes; i++) {
6457 map->stripes[i].physical =
6458 btrfs_stripe_offset_nr(leaf, chunk, i);
6459 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
a443755f
CM
6460 read_extent_buffer(leaf, uuid, (unsigned long)
6461 btrfs_stripe_dev_uuid_nr(chunk, i),
6462 BTRFS_UUID_SIZE);
0b246afa 6463 map->stripes[i].dev = btrfs_find_device(fs_info, devid,
aa1b8cd4 6464 uuid, NULL);
3cdde224 6465 if (!map->stripes[i].dev &&
0b246afa 6466 !btrfs_test_opt(fs_info, DEGRADED)) {
593060d7 6467 free_extent_map(em);
2b902dfc 6468 btrfs_report_missing_device(fs_info, devid, uuid, true);
45dbdbc9 6469 return -ENOENT;
593060d7 6470 }
dfe25020
CM
6471 if (!map->stripes[i].dev) {
6472 map->stripes[i].dev =
2ff7e61e
JM
6473 add_missing_dev(fs_info->fs_devices, devid,
6474 uuid);
adfb69af 6475 if (IS_ERR(map->stripes[i].dev)) {
dfe25020 6476 free_extent_map(em);
adfb69af
AJ
6477 btrfs_err(fs_info,
6478 "failed to init missing dev %llu: %ld",
6479 devid, PTR_ERR(map->stripes[i].dev));
6480 return PTR_ERR(map->stripes[i].dev);
dfe25020 6481 }
2b902dfc 6482 btrfs_report_missing_device(fs_info, devid, uuid, false);
dfe25020 6483 }
e12c9621
AJ
6484 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6485 &(map->stripes[i].dev->dev_state));
6486
0b86a832
CM
6487 }
6488
890871be 6489 write_lock(&map_tree->map_tree.lock);
09a2a8f9 6490 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
890871be 6491 write_unlock(&map_tree->map_tree.lock);
64f64f43
QW
6492 if (ret < 0) {
6493 btrfs_err(fs_info,
6494 "failed to add chunk map, start=%llu len=%llu: %d",
6495 em->start, em->len, ret);
6496 }
0b86a832
CM
6497 free_extent_map(em);
6498
64f64f43 6499 return ret;
0b86a832
CM
6500}
6501
143bede5 6502static void fill_device_from_item(struct extent_buffer *leaf,
0b86a832
CM
6503 struct btrfs_dev_item *dev_item,
6504 struct btrfs_device *device)
6505{
6506 unsigned long ptr;
0b86a832
CM
6507
6508 device->devid = btrfs_device_id(leaf, dev_item);
d6397bae
CB
6509 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6510 device->total_bytes = device->disk_total_bytes;
935e5cc9 6511 device->commit_total_bytes = device->disk_total_bytes;
0b86a832 6512 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
ce7213c7 6513 device->commit_bytes_used = device->bytes_used;
0b86a832
CM
6514 device->type = btrfs_device_type(leaf, dev_item);
6515 device->io_align = btrfs_device_io_align(leaf, dev_item);
6516 device->io_width = btrfs_device_io_width(leaf, dev_item);
6517 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
8dabb742 6518 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
401e29c1 6519 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
0b86a832 6520
410ba3a2 6521 ptr = btrfs_device_uuid(dev_item);
e17cade2 6522 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
0b86a832
CM
6523}
6524
2ff7e61e 6525static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
5f375835 6526 u8 *fsid)
2b82032c
YZ
6527{
6528 struct btrfs_fs_devices *fs_devices;
6529 int ret;
6530
a32bf9a3 6531 lockdep_assert_held(&uuid_mutex);
2dfeca9b 6532 ASSERT(fsid);
2b82032c 6533
0b246afa 6534 fs_devices = fs_info->fs_devices->seed;
2b82032c 6535 while (fs_devices) {
44880fdc 6536 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
5f375835
MX
6537 return fs_devices;
6538
2b82032c
YZ
6539 fs_devices = fs_devices->seed;
6540 }
6541
6542 fs_devices = find_fsid(fsid);
6543 if (!fs_devices) {
0b246afa 6544 if (!btrfs_test_opt(fs_info, DEGRADED))
5f375835
MX
6545 return ERR_PTR(-ENOENT);
6546
6547 fs_devices = alloc_fs_devices(fsid);
6548 if (IS_ERR(fs_devices))
6549 return fs_devices;
6550
6551 fs_devices->seeding = 1;
6552 fs_devices->opened = 1;
6553 return fs_devices;
2b82032c 6554 }
e4404d6e
YZ
6555
6556 fs_devices = clone_fs_devices(fs_devices);
5f375835
MX
6557 if (IS_ERR(fs_devices))
6558 return fs_devices;
2b82032c 6559
897fb573 6560 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
48d28232
JL
6561 if (ret) {
6562 free_fs_devices(fs_devices);
5f375835 6563 fs_devices = ERR_PTR(ret);
2b82032c 6564 goto out;
48d28232 6565 }
2b82032c
YZ
6566
6567 if (!fs_devices->seeding) {
0226e0eb 6568 close_fs_devices(fs_devices);
e4404d6e 6569 free_fs_devices(fs_devices);
5f375835 6570 fs_devices = ERR_PTR(-EINVAL);
2b82032c
YZ
6571 goto out;
6572 }
6573
0b246afa
JM
6574 fs_devices->seed = fs_info->fs_devices->seed;
6575 fs_info->fs_devices->seed = fs_devices;
2b82032c 6576out:
5f375835 6577 return fs_devices;
2b82032c
YZ
6578}
6579
2ff7e61e 6580static int read_one_dev(struct btrfs_fs_info *fs_info,
0b86a832
CM
6581 struct extent_buffer *leaf,
6582 struct btrfs_dev_item *dev_item)
6583{
0b246afa 6584 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
0b86a832
CM
6585 struct btrfs_device *device;
6586 u64 devid;
6587 int ret;
44880fdc 6588 u8 fs_uuid[BTRFS_FSID_SIZE];
a443755f
CM
6589 u8 dev_uuid[BTRFS_UUID_SIZE];
6590
0b86a832 6591 devid = btrfs_device_id(leaf, dev_item);
410ba3a2 6592 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
a443755f 6593 BTRFS_UUID_SIZE);
1473b24e 6594 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
44880fdc 6595 BTRFS_FSID_SIZE);
2b82032c 6596
44880fdc 6597 if (memcmp(fs_uuid, fs_info->fsid, BTRFS_FSID_SIZE)) {
2ff7e61e 6598 fs_devices = open_seed_devices(fs_info, fs_uuid);
5f375835
MX
6599 if (IS_ERR(fs_devices))
6600 return PTR_ERR(fs_devices);
2b82032c
YZ
6601 }
6602
0b246afa 6603 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
5f375835 6604 if (!device) {
c5502451 6605 if (!btrfs_test_opt(fs_info, DEGRADED)) {
2b902dfc
AJ
6606 btrfs_report_missing_device(fs_info, devid,
6607 dev_uuid, true);
45dbdbc9 6608 return -ENOENT;
c5502451 6609 }
2b82032c 6610
2ff7e61e 6611 device = add_missing_dev(fs_devices, devid, dev_uuid);
adfb69af
AJ
6612 if (IS_ERR(device)) {
6613 btrfs_err(fs_info,
6614 "failed to add missing dev %llu: %ld",
6615 devid, PTR_ERR(device));
6616 return PTR_ERR(device);
6617 }
2b902dfc 6618 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
5f375835 6619 } else {
c5502451 6620 if (!device->bdev) {
2b902dfc
AJ
6621 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6622 btrfs_report_missing_device(fs_info,
6623 devid, dev_uuid, true);
45dbdbc9 6624 return -ENOENT;
2b902dfc
AJ
6625 }
6626 btrfs_report_missing_device(fs_info, devid,
6627 dev_uuid, false);
c5502451 6628 }
5f375835 6629
e6e674bd
AJ
6630 if (!device->bdev &&
6631 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
cd02dca5
CM
6632 /*
6633 * this happens when a device that was properly setup
6634 * in the device info lists suddenly goes bad.
6635 * device->bdev is NULL, and so we have to set
6636 * device->missing to one here
6637 */
5f375835 6638 device->fs_devices->missing_devices++;
e6e674bd 6639 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
2b82032c 6640 }
5f375835
MX
6641
6642 /* Move the device to its own fs_devices */
6643 if (device->fs_devices != fs_devices) {
e6e674bd
AJ
6644 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6645 &device->dev_state));
5f375835
MX
6646
6647 list_move(&device->dev_list, &fs_devices->devices);
6648 device->fs_devices->num_devices--;
6649 fs_devices->num_devices++;
6650
6651 device->fs_devices->missing_devices--;
6652 fs_devices->missing_devices++;
6653
6654 device->fs_devices = fs_devices;
6655 }
2b82032c
YZ
6656 }
6657
0b246afa 6658 if (device->fs_devices != fs_info->fs_devices) {
ebbede42 6659 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
2b82032c
YZ
6660 if (device->generation !=
6661 btrfs_device_generation(leaf, dev_item))
6662 return -EINVAL;
6324fbf3 6663 }
0b86a832
CM
6664
6665 fill_device_from_item(leaf, dev_item, device);
e12c9621 6666 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
ebbede42 6667 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
401e29c1 6668 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2b82032c 6669 device->fs_devices->total_rw_bytes += device->total_bytes;
a5ed45f8
NB
6670 atomic64_add(device->total_bytes - device->bytes_used,
6671 &fs_info->free_chunk_space);
2bf64758 6672 }
0b86a832 6673 ret = 0;
0b86a832
CM
6674 return ret;
6675}
6676
6bccf3ab 6677int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
0b86a832 6678{
6bccf3ab 6679 struct btrfs_root *root = fs_info->tree_root;
ab8d0fc4 6680 struct btrfs_super_block *super_copy = fs_info->super_copy;
a061fc8d 6681 struct extent_buffer *sb;
0b86a832 6682 struct btrfs_disk_key *disk_key;
0b86a832 6683 struct btrfs_chunk *chunk;
1ffb22cf
DS
6684 u8 *array_ptr;
6685 unsigned long sb_array_offset;
84eed90f 6686 int ret = 0;
0b86a832
CM
6687 u32 num_stripes;
6688 u32 array_size;
6689 u32 len = 0;
1ffb22cf 6690 u32 cur_offset;
e06cd3dd 6691 u64 type;
84eed90f 6692 struct btrfs_key key;
0b86a832 6693
0b246afa 6694 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
a83fffb7
DS
6695 /*
6696 * This will create extent buffer of nodesize, superblock size is
6697 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6698 * overallocate but we can keep it as-is, only the first page is used.
6699 */
2ff7e61e 6700 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
c871b0f2
LB
6701 if (IS_ERR(sb))
6702 return PTR_ERR(sb);
4db8c528 6703 set_extent_buffer_uptodate(sb);
85d4e461 6704 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
8a334426 6705 /*
01327610 6706 * The sb extent buffer is artificial and just used to read the system array.
4db8c528 6707 * set_extent_buffer_uptodate() call does not properly mark all it's
8a334426
DS
6708 * pages up-to-date when the page is larger: extent does not cover the
6709 * whole page and consequently check_page_uptodate does not find all
6710 * the page's extents up-to-date (the hole beyond sb),
6711 * write_extent_buffer then triggers a WARN_ON.
6712 *
6713 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6714 * but sb spans only this function. Add an explicit SetPageUptodate call
6715 * to silence the warning eg. on PowerPC 64.
6716 */
09cbfeaf 6717 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
727011e0 6718 SetPageUptodate(sb->pages[0]);
4008c04a 6719
a061fc8d 6720 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
0b86a832
CM
6721 array_size = btrfs_super_sys_array_size(super_copy);
6722
1ffb22cf
DS
6723 array_ptr = super_copy->sys_chunk_array;
6724 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6725 cur_offset = 0;
0b86a832 6726
1ffb22cf
DS
6727 while (cur_offset < array_size) {
6728 disk_key = (struct btrfs_disk_key *)array_ptr;
e3540eab
DS
6729 len = sizeof(*disk_key);
6730 if (cur_offset + len > array_size)
6731 goto out_short_read;
6732
0b86a832
CM
6733 btrfs_disk_key_to_cpu(&key, disk_key);
6734
1ffb22cf
DS
6735 array_ptr += len;
6736 sb_array_offset += len;
6737 cur_offset += len;
0b86a832 6738
0d81ba5d 6739 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1ffb22cf 6740 chunk = (struct btrfs_chunk *)sb_array_offset;
e3540eab
DS
6741 /*
6742 * At least one btrfs_chunk with one stripe must be
6743 * present, exact stripe count check comes afterwards
6744 */
6745 len = btrfs_chunk_item_size(1);
6746 if (cur_offset + len > array_size)
6747 goto out_short_read;
6748
6749 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
f5cdedd7 6750 if (!num_stripes) {
ab8d0fc4
JM
6751 btrfs_err(fs_info,
6752 "invalid number of stripes %u in sys_array at offset %u",
f5cdedd7
DS
6753 num_stripes, cur_offset);
6754 ret = -EIO;
6755 break;
6756 }
6757
e06cd3dd
LB
6758 type = btrfs_chunk_type(sb, chunk);
6759 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
ab8d0fc4 6760 btrfs_err(fs_info,
e06cd3dd
LB
6761 "invalid chunk type %llu in sys_array at offset %u",
6762 type, cur_offset);
6763 ret = -EIO;
6764 break;
6765 }
6766
e3540eab
DS
6767 len = btrfs_chunk_item_size(num_stripes);
6768 if (cur_offset + len > array_size)
6769 goto out_short_read;
6770
2ff7e61e 6771 ret = read_one_chunk(fs_info, &key, sb, chunk);
84eed90f
CM
6772 if (ret)
6773 break;
0b86a832 6774 } else {
ab8d0fc4
JM
6775 btrfs_err(fs_info,
6776 "unexpected item type %u in sys_array at offset %u",
6777 (u32)key.type, cur_offset);
84eed90f
CM
6778 ret = -EIO;
6779 break;
0b86a832 6780 }
1ffb22cf
DS
6781 array_ptr += len;
6782 sb_array_offset += len;
6783 cur_offset += len;
0b86a832 6784 }
d865177a 6785 clear_extent_buffer_uptodate(sb);
1c8b5b6e 6786 free_extent_buffer_stale(sb);
84eed90f 6787 return ret;
e3540eab
DS
6788
6789out_short_read:
ab8d0fc4 6790 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
e3540eab 6791 len, cur_offset);
d865177a 6792 clear_extent_buffer_uptodate(sb);
1c8b5b6e 6793 free_extent_buffer_stale(sb);
e3540eab 6794 return -EIO;
0b86a832
CM
6795}
6796
21634a19
QW
6797/*
6798 * Check if all chunks in the fs are OK for read-write degraded mount
6799 *
6528b99d
AJ
6800 * If the @failing_dev is specified, it's accounted as missing.
6801 *
21634a19
QW
6802 * Return true if all chunks meet the minimal RW mount requirements.
6803 * Return false if any chunk doesn't meet the minimal RW mount requirements.
6804 */
6528b99d
AJ
6805bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
6806 struct btrfs_device *failing_dev)
21634a19
QW
6807{
6808 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6809 struct extent_map *em;
6810 u64 next_start = 0;
6811 bool ret = true;
6812
6813 read_lock(&map_tree->map_tree.lock);
6814 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
6815 read_unlock(&map_tree->map_tree.lock);
6816 /* No chunk at all? Return false anyway */
6817 if (!em) {
6818 ret = false;
6819 goto out;
6820 }
6821 while (em) {
6822 struct map_lookup *map;
6823 int missing = 0;
6824 int max_tolerated;
6825 int i;
6826
6827 map = em->map_lookup;
6828 max_tolerated =
6829 btrfs_get_num_tolerated_disk_barrier_failures(
6830 map->type);
6831 for (i = 0; i < map->num_stripes; i++) {
6832 struct btrfs_device *dev = map->stripes[i].dev;
6833
e6e674bd
AJ
6834 if (!dev || !dev->bdev ||
6835 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
21634a19
QW
6836 dev->last_flush_error)
6837 missing++;
6528b99d
AJ
6838 else if (failing_dev && failing_dev == dev)
6839 missing++;
21634a19
QW
6840 }
6841 if (missing > max_tolerated) {
6528b99d
AJ
6842 if (!failing_dev)
6843 btrfs_warn(fs_info,
21634a19
QW
6844 "chunk %llu missing %d devices, max tolerance is %d for writeable mount",
6845 em->start, missing, max_tolerated);
6846 free_extent_map(em);
6847 ret = false;
6848 goto out;
6849 }
6850 next_start = extent_map_end(em);
6851 free_extent_map(em);
6852
6853 read_lock(&map_tree->map_tree.lock);
6854 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
6855 (u64)(-1) - next_start);
6856 read_unlock(&map_tree->map_tree.lock);
6857 }
6858out:
6859 return ret;
6860}
6861
5b4aacef 6862int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
0b86a832 6863{
5b4aacef 6864 struct btrfs_root *root = fs_info->chunk_root;
0b86a832
CM
6865 struct btrfs_path *path;
6866 struct extent_buffer *leaf;
6867 struct btrfs_key key;
6868 struct btrfs_key found_key;
6869 int ret;
6870 int slot;
99e3ecfc 6871 u64 total_dev = 0;
0b86a832 6872
0b86a832
CM
6873 path = btrfs_alloc_path();
6874 if (!path)
6875 return -ENOMEM;
6876
3dd0f7a3
AJ
6877 /*
6878 * uuid_mutex is needed only if we are mounting a sprout FS
6879 * otherwise we don't need it.
6880 */
b367e47f 6881 mutex_lock(&uuid_mutex);
34441361 6882 mutex_lock(&fs_info->chunk_mutex);
b367e47f 6883
395927a9
FDBM
6884 /*
6885 * Read all device items, and then all the chunk items. All
6886 * device items are found before any chunk item (their object id
6887 * is smaller than the lowest possible object id for a chunk
6888 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
0b86a832
CM
6889 */
6890 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6891 key.offset = 0;
6892 key.type = 0;
0b86a832 6893 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
ab59381e
ZL
6894 if (ret < 0)
6895 goto error;
d397712b 6896 while (1) {
0b86a832
CM
6897 leaf = path->nodes[0];
6898 slot = path->slots[0];
6899 if (slot >= btrfs_header_nritems(leaf)) {
6900 ret = btrfs_next_leaf(root, path);
6901 if (ret == 0)
6902 continue;
6903 if (ret < 0)
6904 goto error;
6905 break;
6906 }
6907 btrfs_item_key_to_cpu(leaf, &found_key, slot);
395927a9
FDBM
6908 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6909 struct btrfs_dev_item *dev_item;
6910 dev_item = btrfs_item_ptr(leaf, slot,
0b86a832 6911 struct btrfs_dev_item);
2ff7e61e 6912 ret = read_one_dev(fs_info, leaf, dev_item);
395927a9
FDBM
6913 if (ret)
6914 goto error;
99e3ecfc 6915 total_dev++;
0b86a832
CM
6916 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6917 struct btrfs_chunk *chunk;
6918 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
2ff7e61e 6919 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
2b82032c
YZ
6920 if (ret)
6921 goto error;
0b86a832
CM
6922 }
6923 path->slots[0]++;
6924 }
99e3ecfc
LB
6925
6926 /*
6927 * After loading chunk tree, we've got all device information,
6928 * do another round of validation checks.
6929 */
0b246afa
JM
6930 if (total_dev != fs_info->fs_devices->total_devices) {
6931 btrfs_err(fs_info,
99e3ecfc 6932 "super_num_devices %llu mismatch with num_devices %llu found here",
0b246afa 6933 btrfs_super_num_devices(fs_info->super_copy),
99e3ecfc
LB
6934 total_dev);
6935 ret = -EINVAL;
6936 goto error;
6937 }
0b246afa
JM
6938 if (btrfs_super_total_bytes(fs_info->super_copy) <
6939 fs_info->fs_devices->total_rw_bytes) {
6940 btrfs_err(fs_info,
99e3ecfc 6941 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
0b246afa
JM
6942 btrfs_super_total_bytes(fs_info->super_copy),
6943 fs_info->fs_devices->total_rw_bytes);
99e3ecfc
LB
6944 ret = -EINVAL;
6945 goto error;
6946 }
0b86a832
CM
6947 ret = 0;
6948error:
34441361 6949 mutex_unlock(&fs_info->chunk_mutex);
b367e47f
LZ
6950 mutex_unlock(&uuid_mutex);
6951
2b82032c 6952 btrfs_free_path(path);
0b86a832
CM
6953 return ret;
6954}
442a4f63 6955
cb517eab
MX
6956void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6957{
6958 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6959 struct btrfs_device *device;
6960
29cc83f6
LB
6961 while (fs_devices) {
6962 mutex_lock(&fs_devices->device_list_mutex);
6963 list_for_each_entry(device, &fs_devices->devices, dev_list)
fb456252 6964 device->fs_info = fs_info;
29cc83f6
LB
6965 mutex_unlock(&fs_devices->device_list_mutex);
6966
6967 fs_devices = fs_devices->seed;
6968 }
cb517eab
MX
6969}
6970
733f4fbb
SB
6971static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
6972{
6973 int i;
6974
6975 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6976 btrfs_dev_stat_reset(dev, i);
6977}
6978
6979int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
6980{
6981 struct btrfs_key key;
6982 struct btrfs_key found_key;
6983 struct btrfs_root *dev_root = fs_info->dev_root;
6984 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6985 struct extent_buffer *eb;
6986 int slot;
6987 int ret = 0;
6988 struct btrfs_device *device;
6989 struct btrfs_path *path = NULL;
6990 int i;
6991
6992 path = btrfs_alloc_path();
6993 if (!path) {
6994 ret = -ENOMEM;
6995 goto out;
6996 }
6997
6998 mutex_lock(&fs_devices->device_list_mutex);
6999 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7000 int item_size;
7001 struct btrfs_dev_stats_item *ptr;
7002
242e2956
DS
7003 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7004 key.type = BTRFS_PERSISTENT_ITEM_KEY;
733f4fbb
SB
7005 key.offset = device->devid;
7006 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7007 if (ret) {
733f4fbb
SB
7008 __btrfs_reset_dev_stats(device);
7009 device->dev_stats_valid = 1;
7010 btrfs_release_path(path);
7011 continue;
7012 }
7013 slot = path->slots[0];
7014 eb = path->nodes[0];
7015 btrfs_item_key_to_cpu(eb, &found_key, slot);
7016 item_size = btrfs_item_size_nr(eb, slot);
7017
7018 ptr = btrfs_item_ptr(eb, slot,
7019 struct btrfs_dev_stats_item);
7020
7021 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7022 if (item_size >= (1 + i) * sizeof(__le64))
7023 btrfs_dev_stat_set(device, i,
7024 btrfs_dev_stats_value(eb, ptr, i));
7025 else
7026 btrfs_dev_stat_reset(device, i);
7027 }
7028
7029 device->dev_stats_valid = 1;
7030 btrfs_dev_stat_print_on_load(device);
7031 btrfs_release_path(path);
7032 }
7033 mutex_unlock(&fs_devices->device_list_mutex);
7034
7035out:
7036 btrfs_free_path(path);
7037 return ret < 0 ? ret : 0;
7038}
7039
7040static int update_dev_stat_item(struct btrfs_trans_handle *trans,
733f4fbb
SB
7041 struct btrfs_device *device)
7042{
5495f195 7043 struct btrfs_fs_info *fs_info = trans->fs_info;
6bccf3ab 7044 struct btrfs_root *dev_root = fs_info->dev_root;
733f4fbb
SB
7045 struct btrfs_path *path;
7046 struct btrfs_key key;
7047 struct extent_buffer *eb;
7048 struct btrfs_dev_stats_item *ptr;
7049 int ret;
7050 int i;
7051
242e2956
DS
7052 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7053 key.type = BTRFS_PERSISTENT_ITEM_KEY;
733f4fbb
SB
7054 key.offset = device->devid;
7055
7056 path = btrfs_alloc_path();
fa252992
DS
7057 if (!path)
7058 return -ENOMEM;
733f4fbb
SB
7059 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7060 if (ret < 0) {
0b246afa 7061 btrfs_warn_in_rcu(fs_info,
ecaeb14b 7062 "error %d while searching for dev_stats item for device %s",
606686ee 7063 ret, rcu_str_deref(device->name));
733f4fbb
SB
7064 goto out;
7065 }
7066
7067 if (ret == 0 &&
7068 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7069 /* need to delete old one and insert a new one */
7070 ret = btrfs_del_item(trans, dev_root, path);
7071 if (ret != 0) {
0b246afa 7072 btrfs_warn_in_rcu(fs_info,
ecaeb14b 7073 "delete too small dev_stats item for device %s failed %d",
606686ee 7074 rcu_str_deref(device->name), ret);
733f4fbb
SB
7075 goto out;
7076 }
7077 ret = 1;
7078 }
7079
7080 if (ret == 1) {
7081 /* need to insert a new item */
7082 btrfs_release_path(path);
7083 ret = btrfs_insert_empty_item(trans, dev_root, path,
7084 &key, sizeof(*ptr));
7085 if (ret < 0) {
0b246afa 7086 btrfs_warn_in_rcu(fs_info,
ecaeb14b
DS
7087 "insert dev_stats item for device %s failed %d",
7088 rcu_str_deref(device->name), ret);
733f4fbb
SB
7089 goto out;
7090 }
7091 }
7092
7093 eb = path->nodes[0];
7094 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7095 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7096 btrfs_set_dev_stats_value(eb, ptr, i,
7097 btrfs_dev_stat_read(device, i));
7098 btrfs_mark_buffer_dirty(eb);
7099
7100out:
7101 btrfs_free_path(path);
7102 return ret;
7103}
7104
7105/*
7106 * called from commit_transaction. Writes all changed device stats to disk.
7107 */
7108int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7109 struct btrfs_fs_info *fs_info)
7110{
733f4fbb
SB
7111 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7112 struct btrfs_device *device;
addc3fa7 7113 int stats_cnt;
733f4fbb
SB
7114 int ret = 0;
7115
7116 mutex_lock(&fs_devices->device_list_mutex);
7117 list_for_each_entry(device, &fs_devices->devices, dev_list) {
9deae968
NB
7118 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7119 if (!device->dev_stats_valid || stats_cnt == 0)
733f4fbb
SB
7120 continue;
7121
9deae968
NB
7122
7123 /*
7124 * There is a LOAD-LOAD control dependency between the value of
7125 * dev_stats_ccnt and updating the on-disk values which requires
7126 * reading the in-memory counters. Such control dependencies
7127 * require explicit read memory barriers.
7128 *
7129 * This memory barriers pairs with smp_mb__before_atomic in
7130 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7131 * barrier implied by atomic_xchg in
7132 * btrfs_dev_stats_read_and_reset
7133 */
7134 smp_rmb();
7135
5495f195 7136 ret = update_dev_stat_item(trans, device);
733f4fbb 7137 if (!ret)
addc3fa7 7138 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
733f4fbb
SB
7139 }
7140 mutex_unlock(&fs_devices->device_list_mutex);
7141
7142 return ret;
7143}
7144
442a4f63
SB
7145void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7146{
7147 btrfs_dev_stat_inc(dev, index);
7148 btrfs_dev_stat_print_on_error(dev);
7149}
7150
48a3b636 7151static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
442a4f63 7152{
733f4fbb
SB
7153 if (!dev->dev_stats_valid)
7154 return;
fb456252 7155 btrfs_err_rl_in_rcu(dev->fs_info,
b14af3b4 7156 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
606686ee 7157 rcu_str_deref(dev->name),
442a4f63
SB
7158 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7159 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7160 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
efe120a0
FH
7161 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7162 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
442a4f63 7163}
c11d2c23 7164
733f4fbb
SB
7165static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7166{
a98cdb85
SB
7167 int i;
7168
7169 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7170 if (btrfs_dev_stat_read(dev, i) != 0)
7171 break;
7172 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7173 return; /* all values == 0, suppress message */
7174
fb456252 7175 btrfs_info_in_rcu(dev->fs_info,
ecaeb14b 7176 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
606686ee 7177 rcu_str_deref(dev->name),
733f4fbb
SB
7178 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7179 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7180 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7181 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7182 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7183}
7184
2ff7e61e 7185int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
b27f7c0c 7186 struct btrfs_ioctl_get_dev_stats *stats)
c11d2c23
SB
7187{
7188 struct btrfs_device *dev;
0b246afa 7189 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
c11d2c23
SB
7190 int i;
7191
7192 mutex_lock(&fs_devices->device_list_mutex);
0b246afa 7193 dev = btrfs_find_device(fs_info, stats->devid, NULL, NULL);
c11d2c23
SB
7194 mutex_unlock(&fs_devices->device_list_mutex);
7195
7196 if (!dev) {
0b246afa 7197 btrfs_warn(fs_info, "get dev_stats failed, device not found");
c11d2c23 7198 return -ENODEV;
733f4fbb 7199 } else if (!dev->dev_stats_valid) {
0b246afa 7200 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
733f4fbb 7201 return -ENODEV;
b27f7c0c 7202 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
c11d2c23
SB
7203 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7204 if (stats->nr_items > i)
7205 stats->values[i] =
7206 btrfs_dev_stat_read_and_reset(dev, i);
7207 else
7208 btrfs_dev_stat_reset(dev, i);
7209 }
7210 } else {
7211 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7212 if (stats->nr_items > i)
7213 stats->values[i] = btrfs_dev_stat_read(dev, i);
7214 }
7215 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7216 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7217 return 0;
7218}
a8a6dab7 7219
da353f6b 7220void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
a8a6dab7
SB
7221{
7222 struct buffer_head *bh;
7223 struct btrfs_super_block *disk_super;
12b1c263 7224 int copy_num;
a8a6dab7 7225
12b1c263
AJ
7226 if (!bdev)
7227 return;
a8a6dab7 7228
12b1c263
AJ
7229 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7230 copy_num++) {
a8a6dab7 7231
12b1c263
AJ
7232 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7233 continue;
7234
7235 disk_super = (struct btrfs_super_block *)bh->b_data;
7236
7237 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7238 set_buffer_dirty(bh);
7239 sync_dirty_buffer(bh);
7240 brelse(bh);
7241 }
7242
7243 /* Notify udev that device has changed */
7244 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7245
7246 /* Update ctime/mtime for device path for libblkid */
7247 update_dev_time(device_path);
a8a6dab7 7248}
935e5cc9
MX
7249
7250/*
7251 * Update the size of all devices, which is used for writing out the
7252 * super blocks.
7253 */
7254void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7255{
7256 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7257 struct btrfs_device *curr, *next;
7258
7259 if (list_empty(&fs_devices->resized_devices))
7260 return;
7261
7262 mutex_lock(&fs_devices->device_list_mutex);
34441361 7263 mutex_lock(&fs_info->chunk_mutex);
935e5cc9
MX
7264 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7265 resized_list) {
7266 list_del_init(&curr->resized_list);
7267 curr->commit_total_bytes = curr->disk_total_bytes;
7268 }
34441361 7269 mutex_unlock(&fs_info->chunk_mutex);
935e5cc9
MX
7270 mutex_unlock(&fs_devices->device_list_mutex);
7271}
ce7213c7
MX
7272
7273/* Must be invoked during the transaction commit */
e9b919b1 7274void btrfs_update_commit_device_bytes_used(struct btrfs_transaction *trans)
ce7213c7 7275{
e9b919b1 7276 struct btrfs_fs_info *fs_info = trans->fs_info;
ce7213c7
MX
7277 struct extent_map *em;
7278 struct map_lookup *map;
7279 struct btrfs_device *dev;
7280 int i;
7281
e9b919b1 7282 if (list_empty(&trans->pending_chunks))
ce7213c7
MX
7283 return;
7284
7285 /* In order to kick the device replace finish process */
34441361 7286 mutex_lock(&fs_info->chunk_mutex);
e9b919b1 7287 list_for_each_entry(em, &trans->pending_chunks, list) {
95617d69 7288 map = em->map_lookup;
ce7213c7
MX
7289
7290 for (i = 0; i < map->num_stripes; i++) {
7291 dev = map->stripes[i].dev;
7292 dev->commit_bytes_used = dev->bytes_used;
7293 }
7294 }
34441361 7295 mutex_unlock(&fs_info->chunk_mutex);
ce7213c7 7296}
5a13f430
AJ
7297
7298void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7299{
7300 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7301 while (fs_devices) {
7302 fs_devices->fs_info = fs_info;
7303 fs_devices = fs_devices->seed;
7304 }
7305}
7306
7307void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7308{
7309 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7310 while (fs_devices) {
7311 fs_devices->fs_info = NULL;
7312 fs_devices = fs_devices->seed;
7313 }
7314}
46df06b8
DS
7315
7316/*
7317 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7318 */
7319int btrfs_bg_type_to_factor(u64 flags)
7320{
7321 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
7322 BTRFS_BLOCK_GROUP_RAID10))
7323 return 2;
7324 return 1;
7325}
cf90d884
QW
7326
7327
7328static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
7329{
7330 int index = btrfs_bg_flags_to_raid_index(type);
7331 int ncopies = btrfs_raid_array[index].ncopies;
7332 int data_stripes;
7333
7334 switch (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
7335 case BTRFS_BLOCK_GROUP_RAID5:
7336 data_stripes = num_stripes - 1;
7337 break;
7338 case BTRFS_BLOCK_GROUP_RAID6:
7339 data_stripes = num_stripes - 2;
7340 break;
7341 default:
7342 data_stripes = num_stripes / ncopies;
7343 break;
7344 }
7345 return div_u64(chunk_len, data_stripes);
7346}
7347
7348static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7349 u64 chunk_offset, u64 devid,
7350 u64 physical_offset, u64 physical_len)
7351{
7352 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7353 struct extent_map *em;
7354 struct map_lookup *map;
7355 u64 stripe_len;
7356 bool found = false;
7357 int ret = 0;
7358 int i;
7359
7360 read_lock(&em_tree->lock);
7361 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7362 read_unlock(&em_tree->lock);
7363
7364 if (!em) {
7365 btrfs_err(fs_info,
7366"dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7367 physical_offset, devid);
7368 ret = -EUCLEAN;
7369 goto out;
7370 }
7371
7372 map = em->map_lookup;
7373 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7374 if (physical_len != stripe_len) {
7375 btrfs_err(fs_info,
7376"dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7377 physical_offset, devid, em->start, physical_len,
7378 stripe_len);
7379 ret = -EUCLEAN;
7380 goto out;
7381 }
7382
7383 for (i = 0; i < map->num_stripes; i++) {
7384 if (map->stripes[i].dev->devid == devid &&
7385 map->stripes[i].physical == physical_offset) {
7386 found = true;
7387 if (map->verified_stripes >= map->num_stripes) {
7388 btrfs_err(fs_info,
7389 "too many dev extents for chunk %llu found",
7390 em->start);
7391 ret = -EUCLEAN;
7392 goto out;
7393 }
7394 map->verified_stripes++;
7395 break;
7396 }
7397 }
7398 if (!found) {
7399 btrfs_err(fs_info,
7400 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7401 physical_offset, devid);
7402 ret = -EUCLEAN;
7403 }
7404out:
7405 free_extent_map(em);
7406 return ret;
7407}
7408
7409static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7410{
7411 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7412 struct extent_map *em;
7413 struct rb_node *node;
7414 int ret = 0;
7415
7416 read_lock(&em_tree->lock);
7417 for (node = rb_first(&em_tree->map); node; node = rb_next(node)) {
7418 em = rb_entry(node, struct extent_map, rb_node);
7419 if (em->map_lookup->num_stripes !=
7420 em->map_lookup->verified_stripes) {
7421 btrfs_err(fs_info,
7422 "chunk %llu has missing dev extent, have %d expect %d",
7423 em->start, em->map_lookup->verified_stripes,
7424 em->map_lookup->num_stripes);
7425 ret = -EUCLEAN;
7426 goto out;
7427 }
7428 }
7429out:
7430 read_unlock(&em_tree->lock);
7431 return ret;
7432}
7433
7434/*
7435 * Ensure that all dev extents are mapped to correct chunk, otherwise
7436 * later chunk allocation/free would cause unexpected behavior.
7437 *
7438 * NOTE: This will iterate through the whole device tree, which should be of
7439 * the same size level as the chunk tree. This slightly increases mount time.
7440 */
7441int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7442{
7443 struct btrfs_path *path;
7444 struct btrfs_root *root = fs_info->dev_root;
7445 struct btrfs_key key;
7446 int ret = 0;
7447
7448 key.objectid = 1;
7449 key.type = BTRFS_DEV_EXTENT_KEY;
7450 key.offset = 0;
7451
7452 path = btrfs_alloc_path();
7453 if (!path)
7454 return -ENOMEM;
7455
7456 path->reada = READA_FORWARD;
7457 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7458 if (ret < 0)
7459 goto out;
7460
7461 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7462 ret = btrfs_next_item(root, path);
7463 if (ret < 0)
7464 goto out;
7465 /* No dev extents at all? Not good */
7466 if (ret > 0) {
7467 ret = -EUCLEAN;
7468 goto out;
7469 }
7470 }
7471 while (1) {
7472 struct extent_buffer *leaf = path->nodes[0];
7473 struct btrfs_dev_extent *dext;
7474 int slot = path->slots[0];
7475 u64 chunk_offset;
7476 u64 physical_offset;
7477 u64 physical_len;
7478 u64 devid;
7479
7480 btrfs_item_key_to_cpu(leaf, &key, slot);
7481 if (key.type != BTRFS_DEV_EXTENT_KEY)
7482 break;
7483 devid = key.objectid;
7484 physical_offset = key.offset;
7485
7486 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7487 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7488 physical_len = btrfs_dev_extent_length(leaf, dext);
7489
7490 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7491 physical_offset, physical_len);
7492 if (ret < 0)
7493 goto out;
7494 ret = btrfs_next_item(root, path);
7495 if (ret < 0)
7496 goto out;
7497 if (ret > 0) {
7498 ret = 0;
7499 break;
7500 }
7501 }
7502
7503 /* Ensure all chunks have corresponding dev extents */
7504 ret = verify_chunk_dev_extent_mapping(fs_info);
7505out:
7506 btrfs_free_path(path);
7507 return ret;
7508}