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