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