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