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