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