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