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