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