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