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