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