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