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