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