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