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