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