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