]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - fs/btrfs/volumes.c
btrfs: Don't BUG_ON insert errors in btrfs_alloc_dev_extent()
[mirror_ubuntu-jammy-kernel.git] / fs / btrfs / volumes.c
CommitLineData
0b86a832
CM
1/*
2 * Copyright (C) 2007 Oracle. All rights reserved.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
17 */
18#include <linux/sched.h>
19#include <linux/bio.h>
5a0e3ad6 20#include <linux/slab.h>
8a4b83cc 21#include <linux/buffer_head.h>
f2d8d74d 22#include <linux/blkdev.h>
788f20eb 23#include <linux/random.h>
b765ead5 24#include <linux/iocontext.h>
6f88a440 25#include <linux/capability.h>
59641015 26#include <linux/kthread.h>
593060d7 27#include <asm/div64.h>
4b4e25f2 28#include "compat.h"
0b86a832
CM
29#include "ctree.h"
30#include "extent_map.h"
31#include "disk-io.h"
32#include "transaction.h"
33#include "print-tree.h"
34#include "volumes.h"
8b712842 35#include "async-thread.h"
21adbd5c 36#include "check-integrity.h"
0b86a832 37
2b82032c
YZ
38static int init_first_rw_device(struct btrfs_trans_handle *trans,
39 struct btrfs_root *root,
40 struct btrfs_device *device);
41static int btrfs_relocate_sys_chunks(struct btrfs_root *root);
42
8a4b83cc
CM
43static DEFINE_MUTEX(uuid_mutex);
44static LIST_HEAD(fs_uuids);
45
7d9eb12c
CM
46static void lock_chunks(struct btrfs_root *root)
47{
7d9eb12c
CM
48 mutex_lock(&root->fs_info->chunk_mutex);
49}
50
51static void unlock_chunks(struct btrfs_root *root)
52{
7d9eb12c
CM
53 mutex_unlock(&root->fs_info->chunk_mutex);
54}
55
e4404d6e
YZ
56static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
57{
58 struct btrfs_device *device;
59 WARN_ON(fs_devices->opened);
60 while (!list_empty(&fs_devices->devices)) {
61 device = list_entry(fs_devices->devices.next,
62 struct btrfs_device, dev_list);
63 list_del(&device->dev_list);
64 kfree(device->name);
65 kfree(device);
66 }
67 kfree(fs_devices);
68}
69
143bede5 70void btrfs_cleanup_fs_uuids(void)
8a4b83cc
CM
71{
72 struct btrfs_fs_devices *fs_devices;
8a4b83cc 73
2b82032c
YZ
74 while (!list_empty(&fs_uuids)) {
75 fs_devices = list_entry(fs_uuids.next,
76 struct btrfs_fs_devices, list);
77 list_del(&fs_devices->list);
e4404d6e 78 free_fs_devices(fs_devices);
8a4b83cc 79 }
8a4b83cc
CM
80}
81
a1b32a59
CM
82static noinline struct btrfs_device *__find_device(struct list_head *head,
83 u64 devid, u8 *uuid)
8a4b83cc
CM
84{
85 struct btrfs_device *dev;
8a4b83cc 86
c6e30871 87 list_for_each_entry(dev, head, dev_list) {
a443755f 88 if (dev->devid == devid &&
8f18cf13 89 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
8a4b83cc 90 return dev;
a443755f 91 }
8a4b83cc
CM
92 }
93 return NULL;
94}
95
a1b32a59 96static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
8a4b83cc 97{
8a4b83cc
CM
98 struct btrfs_fs_devices *fs_devices;
99
c6e30871 100 list_for_each_entry(fs_devices, &fs_uuids, list) {
8a4b83cc
CM
101 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
102 return fs_devices;
103 }
104 return NULL;
105}
106
ffbd517d
CM
107static void requeue_list(struct btrfs_pending_bios *pending_bios,
108 struct bio *head, struct bio *tail)
109{
110
111 struct bio *old_head;
112
113 old_head = pending_bios->head;
114 pending_bios->head = head;
115 if (pending_bios->tail)
116 tail->bi_next = old_head;
117 else
118 pending_bios->tail = tail;
119}
120
8b712842
CM
121/*
122 * we try to collect pending bios for a device so we don't get a large
123 * number of procs sending bios down to the same device. This greatly
124 * improves the schedulers ability to collect and merge the bios.
125 *
126 * But, it also turns into a long list of bios to process and that is sure
127 * to eventually make the worker thread block. The solution here is to
128 * make some progress and then put this work struct back at the end of
129 * the list if the block device is congested. This way, multiple devices
130 * can make progress from a single worker thread.
131 */
143bede5 132static noinline void run_scheduled_bios(struct btrfs_device *device)
8b712842
CM
133{
134 struct bio *pending;
135 struct backing_dev_info *bdi;
b64a2851 136 struct btrfs_fs_info *fs_info;
ffbd517d 137 struct btrfs_pending_bios *pending_bios;
8b712842
CM
138 struct bio *tail;
139 struct bio *cur;
140 int again = 0;
ffbd517d 141 unsigned long num_run;
d644d8a1 142 unsigned long batch_run = 0;
b64a2851 143 unsigned long limit;
b765ead5 144 unsigned long last_waited = 0;
d84275c9 145 int force_reg = 0;
0e588859 146 int sync_pending = 0;
211588ad
CM
147 struct blk_plug plug;
148
149 /*
150 * this function runs all the bios we've collected for
151 * a particular device. We don't want to wander off to
152 * another device without first sending all of these down.
153 * So, setup a plug here and finish it off before we return
154 */
155 blk_start_plug(&plug);
8b712842 156
bedf762b 157 bdi = blk_get_backing_dev_info(device->bdev);
b64a2851
CM
158 fs_info = device->dev_root->fs_info;
159 limit = btrfs_async_submit_limit(fs_info);
160 limit = limit * 2 / 3;
161
8b712842
CM
162loop:
163 spin_lock(&device->io_lock);
164
a6837051 165loop_lock:
d84275c9 166 num_run = 0;
ffbd517d 167
8b712842
CM
168 /* take all the bios off the list at once and process them
169 * later on (without the lock held). But, remember the
170 * tail and other pointers so the bios can be properly reinserted
171 * into the list if we hit congestion
172 */
d84275c9 173 if (!force_reg && device->pending_sync_bios.head) {
ffbd517d 174 pending_bios = &device->pending_sync_bios;
d84275c9
CM
175 force_reg = 1;
176 } else {
ffbd517d 177 pending_bios = &device->pending_bios;
d84275c9
CM
178 force_reg = 0;
179 }
ffbd517d
CM
180
181 pending = pending_bios->head;
182 tail = pending_bios->tail;
8b712842 183 WARN_ON(pending && !tail);
8b712842
CM
184
185 /*
186 * if pending was null this time around, no bios need processing
187 * at all and we can stop. Otherwise it'll loop back up again
188 * and do an additional check so no bios are missed.
189 *
190 * device->running_pending is used to synchronize with the
191 * schedule_bio code.
192 */
ffbd517d
CM
193 if (device->pending_sync_bios.head == NULL &&
194 device->pending_bios.head == NULL) {
8b712842
CM
195 again = 0;
196 device->running_pending = 0;
ffbd517d
CM
197 } else {
198 again = 1;
199 device->running_pending = 1;
8b712842 200 }
ffbd517d
CM
201
202 pending_bios->head = NULL;
203 pending_bios->tail = NULL;
204
8b712842
CM
205 spin_unlock(&device->io_lock);
206
d397712b 207 while (pending) {
ffbd517d
CM
208
209 rmb();
d84275c9
CM
210 /* we want to work on both lists, but do more bios on the
211 * sync list than the regular list
212 */
213 if ((num_run > 32 &&
214 pending_bios != &device->pending_sync_bios &&
215 device->pending_sync_bios.head) ||
216 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
217 device->pending_bios.head)) {
ffbd517d
CM
218 spin_lock(&device->io_lock);
219 requeue_list(pending_bios, pending, tail);
220 goto loop_lock;
221 }
222
8b712842
CM
223 cur = pending;
224 pending = pending->bi_next;
225 cur->bi_next = NULL;
b64a2851
CM
226 atomic_dec(&fs_info->nr_async_bios);
227
228 if (atomic_read(&fs_info->nr_async_bios) < limit &&
229 waitqueue_active(&fs_info->async_submit_wait))
230 wake_up(&fs_info->async_submit_wait);
492bb6de
CM
231
232 BUG_ON(atomic_read(&cur->bi_cnt) == 0);
d644d8a1 233
2ab1ba68
CM
234 /*
235 * if we're doing the sync list, record that our
236 * plug has some sync requests on it
237 *
238 * If we're doing the regular list and there are
239 * sync requests sitting around, unplug before
240 * we add more
241 */
242 if (pending_bios == &device->pending_sync_bios) {
243 sync_pending = 1;
244 } else if (sync_pending) {
245 blk_finish_plug(&plug);
246 blk_start_plug(&plug);
247 sync_pending = 0;
248 }
249
21adbd5c 250 btrfsic_submit_bio(cur->bi_rw, cur);
5ff7ba3a
CM
251 num_run++;
252 batch_run++;
7eaceacc 253 if (need_resched())
ffbd517d 254 cond_resched();
8b712842
CM
255
256 /*
257 * we made progress, there is more work to do and the bdi
258 * is now congested. Back off and let other work structs
259 * run instead
260 */
57fd5a5f 261 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
5f2cc086 262 fs_info->fs_devices->open_devices > 1) {
b765ead5 263 struct io_context *ioc;
8b712842 264
b765ead5
CM
265 ioc = current->io_context;
266
267 /*
268 * the main goal here is that we don't want to
269 * block if we're going to be able to submit
270 * more requests without blocking.
271 *
272 * This code does two great things, it pokes into
273 * the elevator code from a filesystem _and_
274 * it makes assumptions about how batching works.
275 */
276 if (ioc && ioc->nr_batch_requests > 0 &&
277 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
278 (last_waited == 0 ||
279 ioc->last_waited == last_waited)) {
280 /*
281 * we want to go through our batch of
282 * requests and stop. So, we copy out
283 * the ioc->last_waited time and test
284 * against it before looping
285 */
286 last_waited = ioc->last_waited;
7eaceacc 287 if (need_resched())
ffbd517d 288 cond_resched();
b765ead5
CM
289 continue;
290 }
8b712842 291 spin_lock(&device->io_lock);
ffbd517d 292 requeue_list(pending_bios, pending, tail);
a6837051 293 device->running_pending = 1;
8b712842
CM
294
295 spin_unlock(&device->io_lock);
296 btrfs_requeue_work(&device->work);
297 goto done;
298 }
d85c8a6f
CM
299 /* unplug every 64 requests just for good measure */
300 if (batch_run % 64 == 0) {
301 blk_finish_plug(&plug);
302 blk_start_plug(&plug);
303 sync_pending = 0;
304 }
8b712842 305 }
ffbd517d 306
51684082
CM
307 cond_resched();
308 if (again)
309 goto loop;
310
311 spin_lock(&device->io_lock);
312 if (device->pending_bios.head || device->pending_sync_bios.head)
313 goto loop_lock;
314 spin_unlock(&device->io_lock);
315
8b712842 316done:
211588ad 317 blk_finish_plug(&plug);
8b712842
CM
318}
319
b2950863 320static void pending_bios_fn(struct btrfs_work *work)
8b712842
CM
321{
322 struct btrfs_device *device;
323
324 device = container_of(work, struct btrfs_device, work);
325 run_scheduled_bios(device);
326}
327
a1b32a59 328static noinline int device_list_add(const char *path,
8a4b83cc
CM
329 struct btrfs_super_block *disk_super,
330 u64 devid, struct btrfs_fs_devices **fs_devices_ret)
331{
332 struct btrfs_device *device;
333 struct btrfs_fs_devices *fs_devices;
334 u64 found_transid = btrfs_super_generation(disk_super);
3a0524dc 335 char *name;
8a4b83cc
CM
336
337 fs_devices = find_fsid(disk_super->fsid);
338 if (!fs_devices) {
515dc322 339 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
8a4b83cc
CM
340 if (!fs_devices)
341 return -ENOMEM;
342 INIT_LIST_HEAD(&fs_devices->devices);
b3075717 343 INIT_LIST_HEAD(&fs_devices->alloc_list);
8a4b83cc
CM
344 list_add(&fs_devices->list, &fs_uuids);
345 memcpy(fs_devices->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
346 fs_devices->latest_devid = devid;
347 fs_devices->latest_trans = found_transid;
e5e9a520 348 mutex_init(&fs_devices->device_list_mutex);
8a4b83cc
CM
349 device = NULL;
350 } else {
a443755f
CM
351 device = __find_device(&fs_devices->devices, devid,
352 disk_super->dev_item.uuid);
8a4b83cc
CM
353 }
354 if (!device) {
2b82032c
YZ
355 if (fs_devices->opened)
356 return -EBUSY;
357
8a4b83cc
CM
358 device = kzalloc(sizeof(*device), GFP_NOFS);
359 if (!device) {
360 /* we can safely leave the fs_devices entry around */
361 return -ENOMEM;
362 }
363 device->devid = devid;
8b712842 364 device->work.func = pending_bios_fn;
a443755f
CM
365 memcpy(device->uuid, disk_super->dev_item.uuid,
366 BTRFS_UUID_SIZE);
b248a415 367 spin_lock_init(&device->io_lock);
8a4b83cc
CM
368 device->name = kstrdup(path, GFP_NOFS);
369 if (!device->name) {
370 kfree(device);
371 return -ENOMEM;
372 }
2b82032c 373 INIT_LIST_HEAD(&device->dev_alloc_list);
e5e9a520 374
90519d66
AJ
375 /* init readahead state */
376 spin_lock_init(&device->reada_lock);
377 device->reada_curr_zone = NULL;
378 atomic_set(&device->reada_in_flight, 0);
379 device->reada_next = 0;
380 INIT_RADIX_TREE(&device->reada_zones, GFP_NOFS & ~__GFP_WAIT);
381 INIT_RADIX_TREE(&device->reada_extents, GFP_NOFS & ~__GFP_WAIT);
382
e5e9a520 383 mutex_lock(&fs_devices->device_list_mutex);
1f78160c 384 list_add_rcu(&device->dev_list, &fs_devices->devices);
e5e9a520
CM
385 mutex_unlock(&fs_devices->device_list_mutex);
386
2b82032c 387 device->fs_devices = fs_devices;
8a4b83cc 388 fs_devices->num_devices++;
cd02dca5 389 } else if (!device->name || strcmp(device->name, path)) {
3a0524dc
TH
390 name = kstrdup(path, GFP_NOFS);
391 if (!name)
392 return -ENOMEM;
393 kfree(device->name);
394 device->name = name;
cd02dca5
CM
395 if (device->missing) {
396 fs_devices->missing_devices--;
397 device->missing = 0;
398 }
8a4b83cc
CM
399 }
400
401 if (found_transid > fs_devices->latest_trans) {
402 fs_devices->latest_devid = devid;
403 fs_devices->latest_trans = found_transid;
404 }
8a4b83cc
CM
405 *fs_devices_ret = fs_devices;
406 return 0;
407}
408
e4404d6e
YZ
409static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
410{
411 struct btrfs_fs_devices *fs_devices;
412 struct btrfs_device *device;
413 struct btrfs_device *orig_dev;
414
415 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
416 if (!fs_devices)
417 return ERR_PTR(-ENOMEM);
418
419 INIT_LIST_HEAD(&fs_devices->devices);
420 INIT_LIST_HEAD(&fs_devices->alloc_list);
421 INIT_LIST_HEAD(&fs_devices->list);
e5e9a520 422 mutex_init(&fs_devices->device_list_mutex);
e4404d6e
YZ
423 fs_devices->latest_devid = orig->latest_devid;
424 fs_devices->latest_trans = orig->latest_trans;
425 memcpy(fs_devices->fsid, orig->fsid, sizeof(fs_devices->fsid));
426
46224705 427 /* We have held the volume lock, it is safe to get the devices. */
e4404d6e
YZ
428 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
429 device = kzalloc(sizeof(*device), GFP_NOFS);
430 if (!device)
431 goto error;
432
433 device->name = kstrdup(orig_dev->name, GFP_NOFS);
fd2696f3
JL
434 if (!device->name) {
435 kfree(device);
e4404d6e 436 goto error;
fd2696f3 437 }
e4404d6e
YZ
438
439 device->devid = orig_dev->devid;
440 device->work.func = pending_bios_fn;
441 memcpy(device->uuid, orig_dev->uuid, sizeof(device->uuid));
e4404d6e
YZ
442 spin_lock_init(&device->io_lock);
443 INIT_LIST_HEAD(&device->dev_list);
444 INIT_LIST_HEAD(&device->dev_alloc_list);
445
446 list_add(&device->dev_list, &fs_devices->devices);
447 device->fs_devices = fs_devices;
448 fs_devices->num_devices++;
449 }
450 return fs_devices;
451error:
452 free_fs_devices(fs_devices);
453 return ERR_PTR(-ENOMEM);
454}
455
143bede5 456void btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices)
dfe25020 457{
c6e30871 458 struct btrfs_device *device, *next;
dfe25020 459
a6b0d5c8
CM
460 struct block_device *latest_bdev = NULL;
461 u64 latest_devid = 0;
462 u64 latest_transid = 0;
463
dfe25020
CM
464 mutex_lock(&uuid_mutex);
465again:
46224705 466 /* This is the initialized path, it is safe to release the devices. */
c6e30871 467 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
a6b0d5c8
CM
468 if (device->in_fs_metadata) {
469 if (!latest_transid ||
470 device->generation > latest_transid) {
471 latest_devid = device->devid;
472 latest_transid = device->generation;
473 latest_bdev = device->bdev;
474 }
2b82032c 475 continue;
a6b0d5c8 476 }
2b82032c
YZ
477
478 if (device->bdev) {
d4d77629 479 blkdev_put(device->bdev, device->mode);
2b82032c
YZ
480 device->bdev = NULL;
481 fs_devices->open_devices--;
482 }
483 if (device->writeable) {
484 list_del_init(&device->dev_alloc_list);
485 device->writeable = 0;
486 fs_devices->rw_devices--;
487 }
e4404d6e
YZ
488 list_del_init(&device->dev_list);
489 fs_devices->num_devices--;
490 kfree(device->name);
491 kfree(device);
dfe25020 492 }
2b82032c
YZ
493
494 if (fs_devices->seed) {
495 fs_devices = fs_devices->seed;
2b82032c
YZ
496 goto again;
497 }
498
a6b0d5c8
CM
499 fs_devices->latest_bdev = latest_bdev;
500 fs_devices->latest_devid = latest_devid;
501 fs_devices->latest_trans = latest_transid;
502
dfe25020 503 mutex_unlock(&uuid_mutex);
dfe25020 504}
a0af469b 505
1f78160c
XG
506static void __free_device(struct work_struct *work)
507{
508 struct btrfs_device *device;
509
510 device = container_of(work, struct btrfs_device, rcu_work);
511
512 if (device->bdev)
513 blkdev_put(device->bdev, device->mode);
514
515 kfree(device->name);
516 kfree(device);
517}
518
519static void free_device(struct rcu_head *head)
520{
521 struct btrfs_device *device;
522
523 device = container_of(head, struct btrfs_device, rcu);
524
525 INIT_WORK(&device->rcu_work, __free_device);
526 schedule_work(&device->rcu_work);
527}
528
2b82032c 529static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
8a4b83cc 530{
8a4b83cc 531 struct btrfs_device *device;
e4404d6e 532
2b82032c
YZ
533 if (--fs_devices->opened > 0)
534 return 0;
8a4b83cc 535
c9513edb 536 mutex_lock(&fs_devices->device_list_mutex);
c6e30871 537 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1f78160c
XG
538 struct btrfs_device *new_device;
539
540 if (device->bdev)
a0af469b 541 fs_devices->open_devices--;
1f78160c 542
2b82032c
YZ
543 if (device->writeable) {
544 list_del_init(&device->dev_alloc_list);
545 fs_devices->rw_devices--;
546 }
547
d5e2003c
JB
548 if (device->can_discard)
549 fs_devices->num_can_discard--;
550
1f78160c
XG
551 new_device = kmalloc(sizeof(*new_device), GFP_NOFS);
552 BUG_ON(!new_device);
553 memcpy(new_device, device, sizeof(*new_device));
554 new_device->name = kstrdup(device->name, GFP_NOFS);
5f3f302a 555 BUG_ON(device->name && !new_device->name);
1f78160c
XG
556 new_device->bdev = NULL;
557 new_device->writeable = 0;
558 new_device->in_fs_metadata = 0;
d5e2003c 559 new_device->can_discard = 0;
1f78160c
XG
560 list_replace_rcu(&device->dev_list, &new_device->dev_list);
561
562 call_rcu(&device->rcu, free_device);
8a4b83cc 563 }
c9513edb
XG
564 mutex_unlock(&fs_devices->device_list_mutex);
565
e4404d6e
YZ
566 WARN_ON(fs_devices->open_devices);
567 WARN_ON(fs_devices->rw_devices);
2b82032c
YZ
568 fs_devices->opened = 0;
569 fs_devices->seeding = 0;
2b82032c 570
8a4b83cc
CM
571 return 0;
572}
573
2b82032c
YZ
574int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
575{
e4404d6e 576 struct btrfs_fs_devices *seed_devices = NULL;
2b82032c
YZ
577 int ret;
578
579 mutex_lock(&uuid_mutex);
580 ret = __btrfs_close_devices(fs_devices);
e4404d6e
YZ
581 if (!fs_devices->opened) {
582 seed_devices = fs_devices->seed;
583 fs_devices->seed = NULL;
584 }
2b82032c 585 mutex_unlock(&uuid_mutex);
e4404d6e
YZ
586
587 while (seed_devices) {
588 fs_devices = seed_devices;
589 seed_devices = fs_devices->seed;
590 __btrfs_close_devices(fs_devices);
591 free_fs_devices(fs_devices);
592 }
2b82032c
YZ
593 return ret;
594}
595
e4404d6e
YZ
596static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
597 fmode_t flags, void *holder)
8a4b83cc 598{
d5e2003c 599 struct request_queue *q;
8a4b83cc
CM
600 struct block_device *bdev;
601 struct list_head *head = &fs_devices->devices;
8a4b83cc 602 struct btrfs_device *device;
a0af469b
CM
603 struct block_device *latest_bdev = NULL;
604 struct buffer_head *bh;
605 struct btrfs_super_block *disk_super;
606 u64 latest_devid = 0;
607 u64 latest_transid = 0;
a0af469b 608 u64 devid;
2b82032c 609 int seeding = 1;
a0af469b 610 int ret = 0;
8a4b83cc 611
d4d77629
TH
612 flags |= FMODE_EXCL;
613
c6e30871 614 list_for_each_entry(device, head, dev_list) {
c1c4d91c
CM
615 if (device->bdev)
616 continue;
dfe25020
CM
617 if (!device->name)
618 continue;
619
d4d77629 620 bdev = blkdev_get_by_path(device->name, flags, holder);
8a4b83cc 621 if (IS_ERR(bdev)) {
d397712b 622 printk(KERN_INFO "open %s failed\n", device->name);
a0af469b 623 goto error;
8a4b83cc 624 }
a061fc8d 625 set_blocksize(bdev, 4096);
a0af469b 626
a512bbf8 627 bh = btrfs_read_dev_super(bdev);
20bcd649 628 if (!bh)
a0af469b
CM
629 goto error_close;
630
631 disk_super = (struct btrfs_super_block *)bh->b_data;
a343832f 632 devid = btrfs_stack_device_id(&disk_super->dev_item);
a0af469b
CM
633 if (devid != device->devid)
634 goto error_brelse;
635
2b82032c
YZ
636 if (memcmp(device->uuid, disk_super->dev_item.uuid,
637 BTRFS_UUID_SIZE))
638 goto error_brelse;
639
640 device->generation = btrfs_super_generation(disk_super);
641 if (!latest_transid || device->generation > latest_transid) {
a0af469b 642 latest_devid = devid;
2b82032c 643 latest_transid = device->generation;
a0af469b
CM
644 latest_bdev = bdev;
645 }
646
2b82032c
YZ
647 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
648 device->writeable = 0;
649 } else {
650 device->writeable = !bdev_read_only(bdev);
651 seeding = 0;
652 }
653
d5e2003c
JB
654 q = bdev_get_queue(bdev);
655 if (blk_queue_discard(q)) {
656 device->can_discard = 1;
657 fs_devices->num_can_discard++;
658 }
659
8a4b83cc 660 device->bdev = bdev;
dfe25020 661 device->in_fs_metadata = 0;
15916de8
CM
662 device->mode = flags;
663
c289811c
CM
664 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
665 fs_devices->rotating = 1;
666
a0af469b 667 fs_devices->open_devices++;
2b82032c
YZ
668 if (device->writeable) {
669 fs_devices->rw_devices++;
670 list_add(&device->dev_alloc_list,
671 &fs_devices->alloc_list);
672 }
4f6c9328 673 brelse(bh);
a0af469b 674 continue;
a061fc8d 675
a0af469b
CM
676error_brelse:
677 brelse(bh);
678error_close:
d4d77629 679 blkdev_put(bdev, flags);
a0af469b
CM
680error:
681 continue;
8a4b83cc 682 }
a0af469b 683 if (fs_devices->open_devices == 0) {
20bcd649 684 ret = -EINVAL;
a0af469b
CM
685 goto out;
686 }
2b82032c
YZ
687 fs_devices->seeding = seeding;
688 fs_devices->opened = 1;
a0af469b
CM
689 fs_devices->latest_bdev = latest_bdev;
690 fs_devices->latest_devid = latest_devid;
691 fs_devices->latest_trans = latest_transid;
2b82032c 692 fs_devices->total_rw_bytes = 0;
a0af469b 693out:
2b82032c
YZ
694 return ret;
695}
696
697int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
97288f2c 698 fmode_t flags, void *holder)
2b82032c
YZ
699{
700 int ret;
701
702 mutex_lock(&uuid_mutex);
703 if (fs_devices->opened) {
e4404d6e
YZ
704 fs_devices->opened++;
705 ret = 0;
2b82032c 706 } else {
15916de8 707 ret = __btrfs_open_devices(fs_devices, flags, holder);
2b82032c 708 }
8a4b83cc 709 mutex_unlock(&uuid_mutex);
8a4b83cc
CM
710 return ret;
711}
712
97288f2c 713int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
8a4b83cc
CM
714 struct btrfs_fs_devices **fs_devices_ret)
715{
716 struct btrfs_super_block *disk_super;
717 struct block_device *bdev;
718 struct buffer_head *bh;
719 int ret;
720 u64 devid;
f2984462 721 u64 transid;
8a4b83cc 722
d4d77629
TH
723 flags |= FMODE_EXCL;
724 bdev = blkdev_get_by_path(path, flags, holder);
8a4b83cc
CM
725
726 if (IS_ERR(bdev)) {
8a4b83cc
CM
727 ret = PTR_ERR(bdev);
728 goto error;
729 }
730
10f6327b 731 mutex_lock(&uuid_mutex);
8a4b83cc
CM
732 ret = set_blocksize(bdev, 4096);
733 if (ret)
734 goto error_close;
a512bbf8 735 bh = btrfs_read_dev_super(bdev);
8a4b83cc 736 if (!bh) {
20b45077 737 ret = -EINVAL;
8a4b83cc
CM
738 goto error_close;
739 }
740 disk_super = (struct btrfs_super_block *)bh->b_data;
a343832f 741 devid = btrfs_stack_device_id(&disk_super->dev_item);
f2984462 742 transid = btrfs_super_generation(disk_super);
7ae9c09d 743 if (disk_super->label[0])
d397712b 744 printk(KERN_INFO "device label %s ", disk_super->label);
22b63a29
ID
745 else
746 printk(KERN_INFO "device fsid %pU ", disk_super->fsid);
119e10cf 747 printk(KERN_CONT "devid %llu transid %llu %s\n",
d397712b 748 (unsigned long long)devid, (unsigned long long)transid, path);
8a4b83cc
CM
749 ret = device_list_add(path, disk_super, devid, fs_devices_ret);
750
8a4b83cc
CM
751 brelse(bh);
752error_close:
10f6327b 753 mutex_unlock(&uuid_mutex);
d4d77629 754 blkdev_put(bdev, flags);
8a4b83cc 755error:
8a4b83cc
CM
756 return ret;
757}
0b86a832 758
6d07bcec
MX
759/* helper to account the used device space in the range */
760int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
761 u64 end, u64 *length)
762{
763 struct btrfs_key key;
764 struct btrfs_root *root = device->dev_root;
765 struct btrfs_dev_extent *dev_extent;
766 struct btrfs_path *path;
767 u64 extent_end;
768 int ret;
769 int slot;
770 struct extent_buffer *l;
771
772 *length = 0;
773
774 if (start >= device->total_bytes)
775 return 0;
776
777 path = btrfs_alloc_path();
778 if (!path)
779 return -ENOMEM;
780 path->reada = 2;
781
782 key.objectid = device->devid;
783 key.offset = start;
784 key.type = BTRFS_DEV_EXTENT_KEY;
785
786 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
787 if (ret < 0)
788 goto out;
789 if (ret > 0) {
790 ret = btrfs_previous_item(root, path, key.objectid, key.type);
791 if (ret < 0)
792 goto out;
793 }
794
795 while (1) {
796 l = path->nodes[0];
797 slot = path->slots[0];
798 if (slot >= btrfs_header_nritems(l)) {
799 ret = btrfs_next_leaf(root, path);
800 if (ret == 0)
801 continue;
802 if (ret < 0)
803 goto out;
804
805 break;
806 }
807 btrfs_item_key_to_cpu(l, &key, slot);
808
809 if (key.objectid < device->devid)
810 goto next;
811
812 if (key.objectid > device->devid)
813 break;
814
815 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
816 goto next;
817
818 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
819 extent_end = key.offset + btrfs_dev_extent_length(l,
820 dev_extent);
821 if (key.offset <= start && extent_end > end) {
822 *length = end - start + 1;
823 break;
824 } else if (key.offset <= start && extent_end > start)
825 *length += extent_end - start;
826 else if (key.offset > start && extent_end <= end)
827 *length += extent_end - key.offset;
828 else if (key.offset > start && key.offset <= end) {
829 *length += end - key.offset + 1;
830 break;
831 } else if (key.offset > end)
832 break;
833
834next:
835 path->slots[0]++;
836 }
837 ret = 0;
838out:
839 btrfs_free_path(path);
840 return ret;
841}
842
0b86a832 843/*
7bfc837d 844 * find_free_dev_extent - find free space in the specified device
7bfc837d
MX
845 * @device: the device which we search the free space in
846 * @num_bytes: the size of the free space that we need
847 * @start: store the start of the free space.
848 * @len: the size of the free space. that we find, or the size of the max
849 * free space if we don't find suitable free space
850 *
0b86a832
CM
851 * this uses a pretty simple search, the expectation is that it is
852 * called very infrequently and that a given device has a small number
853 * of extents
7bfc837d
MX
854 *
855 * @start is used to store the start of the free space if we find. But if we
856 * don't find suitable free space, it will be used to store the start position
857 * of the max free space.
858 *
859 * @len is used to store the size of the free space that we find.
860 * But if we don't find suitable free space, it is used to store the size of
861 * the max free space.
0b86a832 862 */
125ccb0a 863int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
7bfc837d 864 u64 *start, u64 *len)
0b86a832
CM
865{
866 struct btrfs_key key;
867 struct btrfs_root *root = device->dev_root;
7bfc837d 868 struct btrfs_dev_extent *dev_extent;
2b82032c 869 struct btrfs_path *path;
7bfc837d
MX
870 u64 hole_size;
871 u64 max_hole_start;
872 u64 max_hole_size;
873 u64 extent_end;
874 u64 search_start;
0b86a832
CM
875 u64 search_end = device->total_bytes;
876 int ret;
7bfc837d 877 int slot;
0b86a832
CM
878 struct extent_buffer *l;
879
0b86a832
CM
880 /* FIXME use last free of some kind */
881
8a4b83cc
CM
882 /* we don't want to overwrite the superblock on the drive,
883 * so we make sure to start at an offset of at least 1MB
884 */
a9c9bf68 885 search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
8f18cf13 886
7bfc837d
MX
887 max_hole_start = search_start;
888 max_hole_size = 0;
38c01b96 889 hole_size = 0;
7bfc837d
MX
890
891 if (search_start >= search_end) {
892 ret = -ENOSPC;
893 goto error;
894 }
895
896 path = btrfs_alloc_path();
897 if (!path) {
898 ret = -ENOMEM;
899 goto error;
900 }
901 path->reada = 2;
902
0b86a832
CM
903 key.objectid = device->devid;
904 key.offset = search_start;
905 key.type = BTRFS_DEV_EXTENT_KEY;
7bfc837d 906
125ccb0a 907 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
0b86a832 908 if (ret < 0)
7bfc837d 909 goto out;
1fcbac58
YZ
910 if (ret > 0) {
911 ret = btrfs_previous_item(root, path, key.objectid, key.type);
912 if (ret < 0)
7bfc837d 913 goto out;
1fcbac58 914 }
7bfc837d 915
0b86a832
CM
916 while (1) {
917 l = path->nodes[0];
918 slot = path->slots[0];
919 if (slot >= btrfs_header_nritems(l)) {
920 ret = btrfs_next_leaf(root, path);
921 if (ret == 0)
922 continue;
923 if (ret < 0)
7bfc837d
MX
924 goto out;
925
926 break;
0b86a832
CM
927 }
928 btrfs_item_key_to_cpu(l, &key, slot);
929
930 if (key.objectid < device->devid)
931 goto next;
932
933 if (key.objectid > device->devid)
7bfc837d 934 break;
0b86a832 935
7bfc837d
MX
936 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
937 goto next;
9779b72f 938
7bfc837d
MX
939 if (key.offset > search_start) {
940 hole_size = key.offset - search_start;
9779b72f 941
7bfc837d
MX
942 if (hole_size > max_hole_size) {
943 max_hole_start = search_start;
944 max_hole_size = hole_size;
945 }
9779b72f 946
7bfc837d
MX
947 /*
948 * If this free space is greater than which we need,
949 * it must be the max free space that we have found
950 * until now, so max_hole_start must point to the start
951 * of this free space and the length of this free space
952 * is stored in max_hole_size. Thus, we return
953 * max_hole_start and max_hole_size and go back to the
954 * caller.
955 */
956 if (hole_size >= num_bytes) {
957 ret = 0;
958 goto out;
0b86a832
CM
959 }
960 }
0b86a832 961
0b86a832 962 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
7bfc837d
MX
963 extent_end = key.offset + btrfs_dev_extent_length(l,
964 dev_extent);
965 if (extent_end > search_start)
966 search_start = extent_end;
0b86a832
CM
967next:
968 path->slots[0]++;
969 cond_resched();
970 }
0b86a832 971
38c01b96 972 /*
973 * At this point, search_start should be the end of
974 * allocated dev extents, and when shrinking the device,
975 * search_end may be smaller than search_start.
976 */
977 if (search_end > search_start)
978 hole_size = search_end - search_start;
979
7bfc837d
MX
980 if (hole_size > max_hole_size) {
981 max_hole_start = search_start;
982 max_hole_size = hole_size;
0b86a832 983 }
0b86a832 984
7bfc837d
MX
985 /* See above. */
986 if (hole_size < num_bytes)
987 ret = -ENOSPC;
988 else
989 ret = 0;
990
991out:
2b82032c 992 btrfs_free_path(path);
7bfc837d
MX
993error:
994 *start = max_hole_start;
b2117a39 995 if (len)
7bfc837d 996 *len = max_hole_size;
0b86a832
CM
997 return ret;
998}
999
b2950863 1000static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
8f18cf13
CM
1001 struct btrfs_device *device,
1002 u64 start)
1003{
1004 int ret;
1005 struct btrfs_path *path;
1006 struct btrfs_root *root = device->dev_root;
1007 struct btrfs_key key;
a061fc8d
CM
1008 struct btrfs_key found_key;
1009 struct extent_buffer *leaf = NULL;
1010 struct btrfs_dev_extent *extent = NULL;
8f18cf13
CM
1011
1012 path = btrfs_alloc_path();
1013 if (!path)
1014 return -ENOMEM;
1015
1016 key.objectid = device->devid;
1017 key.offset = start;
1018 key.type = BTRFS_DEV_EXTENT_KEY;
924cd8fb 1019again:
8f18cf13 1020 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
a061fc8d
CM
1021 if (ret > 0) {
1022 ret = btrfs_previous_item(root, path, key.objectid,
1023 BTRFS_DEV_EXTENT_KEY);
b0b802d7
TI
1024 if (ret)
1025 goto out;
a061fc8d
CM
1026 leaf = path->nodes[0];
1027 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1028 extent = btrfs_item_ptr(leaf, path->slots[0],
1029 struct btrfs_dev_extent);
1030 BUG_ON(found_key.offset > start || found_key.offset +
1031 btrfs_dev_extent_length(leaf, extent) < start);
924cd8fb
MX
1032 key = found_key;
1033 btrfs_release_path(path);
1034 goto again;
a061fc8d
CM
1035 } else if (ret == 0) {
1036 leaf = path->nodes[0];
1037 extent = btrfs_item_ptr(leaf, path->slots[0],
1038 struct btrfs_dev_extent);
1039 }
8f18cf13
CM
1040 BUG_ON(ret);
1041
2bf64758
JB
1042 if (device->bytes_used > 0) {
1043 u64 len = btrfs_dev_extent_length(leaf, extent);
1044 device->bytes_used -= len;
1045 spin_lock(&root->fs_info->free_chunk_lock);
1046 root->fs_info->free_chunk_space += len;
1047 spin_unlock(&root->fs_info->free_chunk_lock);
1048 }
8f18cf13 1049 ret = btrfs_del_item(trans, root, path);
8f18cf13 1050
b0b802d7 1051out:
8f18cf13
CM
1052 btrfs_free_path(path);
1053 return ret;
1054}
1055
2b82032c 1056int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
0b86a832 1057 struct btrfs_device *device,
e17cade2 1058 u64 chunk_tree, u64 chunk_objectid,
2b82032c 1059 u64 chunk_offset, u64 start, u64 num_bytes)
0b86a832
CM
1060{
1061 int ret;
1062 struct btrfs_path *path;
1063 struct btrfs_root *root = device->dev_root;
1064 struct btrfs_dev_extent *extent;
1065 struct extent_buffer *leaf;
1066 struct btrfs_key key;
1067
dfe25020 1068 WARN_ON(!device->in_fs_metadata);
0b86a832
CM
1069 path = btrfs_alloc_path();
1070 if (!path)
1071 return -ENOMEM;
1072
0b86a832 1073 key.objectid = device->devid;
2b82032c 1074 key.offset = start;
0b86a832
CM
1075 key.type = BTRFS_DEV_EXTENT_KEY;
1076 ret = btrfs_insert_empty_item(trans, root, path, &key,
1077 sizeof(*extent));
2cdcecbc
MF
1078 if (ret)
1079 goto out;
0b86a832
CM
1080
1081 leaf = path->nodes[0];
1082 extent = btrfs_item_ptr(leaf, path->slots[0],
1083 struct btrfs_dev_extent);
e17cade2
CM
1084 btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1085 btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1086 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1087
1088 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1089 (unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
1090 BTRFS_UUID_SIZE);
1091
0b86a832
CM
1092 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1093 btrfs_mark_buffer_dirty(leaf);
2cdcecbc 1094out:
0b86a832
CM
1095 btrfs_free_path(path);
1096 return ret;
1097}
1098
a1b32a59
CM
1099static noinline int find_next_chunk(struct btrfs_root *root,
1100 u64 objectid, u64 *offset)
0b86a832
CM
1101{
1102 struct btrfs_path *path;
1103 int ret;
1104 struct btrfs_key key;
e17cade2 1105 struct btrfs_chunk *chunk;
0b86a832
CM
1106 struct btrfs_key found_key;
1107
1108 path = btrfs_alloc_path();
92b8e897
MF
1109 if (!path)
1110 return -ENOMEM;
0b86a832 1111
e17cade2 1112 key.objectid = objectid;
0b86a832
CM
1113 key.offset = (u64)-1;
1114 key.type = BTRFS_CHUNK_ITEM_KEY;
1115
1116 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1117 if (ret < 0)
1118 goto error;
1119
1120 BUG_ON(ret == 0);
1121
1122 ret = btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY);
1123 if (ret) {
e17cade2 1124 *offset = 0;
0b86a832
CM
1125 } else {
1126 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1127 path->slots[0]);
e17cade2
CM
1128 if (found_key.objectid != objectid)
1129 *offset = 0;
1130 else {
1131 chunk = btrfs_item_ptr(path->nodes[0], path->slots[0],
1132 struct btrfs_chunk);
1133 *offset = found_key.offset +
1134 btrfs_chunk_length(path->nodes[0], chunk);
1135 }
0b86a832
CM
1136 }
1137 ret = 0;
1138error:
1139 btrfs_free_path(path);
1140 return ret;
1141}
1142
2b82032c 1143static noinline int find_next_devid(struct btrfs_root *root, u64 *objectid)
0b86a832
CM
1144{
1145 int ret;
1146 struct btrfs_key key;
1147 struct btrfs_key found_key;
2b82032c
YZ
1148 struct btrfs_path *path;
1149
1150 root = root->fs_info->chunk_root;
1151
1152 path = btrfs_alloc_path();
1153 if (!path)
1154 return -ENOMEM;
0b86a832
CM
1155
1156 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1157 key.type = BTRFS_DEV_ITEM_KEY;
1158 key.offset = (u64)-1;
1159
1160 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1161 if (ret < 0)
1162 goto error;
1163
1164 BUG_ON(ret == 0);
1165
1166 ret = btrfs_previous_item(root, path, BTRFS_DEV_ITEMS_OBJECTID,
1167 BTRFS_DEV_ITEM_KEY);
1168 if (ret) {
1169 *objectid = 1;
1170 } else {
1171 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1172 path->slots[0]);
1173 *objectid = found_key.offset + 1;
1174 }
1175 ret = 0;
1176error:
2b82032c 1177 btrfs_free_path(path);
0b86a832
CM
1178 return ret;
1179}
1180
1181/*
1182 * the device information is stored in the chunk root
1183 * the btrfs_device struct should be fully filled in
1184 */
1185int btrfs_add_device(struct btrfs_trans_handle *trans,
1186 struct btrfs_root *root,
1187 struct btrfs_device *device)
1188{
1189 int ret;
1190 struct btrfs_path *path;
1191 struct btrfs_dev_item *dev_item;
1192 struct extent_buffer *leaf;
1193 struct btrfs_key key;
1194 unsigned long ptr;
0b86a832
CM
1195
1196 root = root->fs_info->chunk_root;
1197
1198 path = btrfs_alloc_path();
1199 if (!path)
1200 return -ENOMEM;
1201
0b86a832
CM
1202 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1203 key.type = BTRFS_DEV_ITEM_KEY;
2b82032c 1204 key.offset = device->devid;
0b86a832
CM
1205
1206 ret = btrfs_insert_empty_item(trans, root, path, &key,
0d81ba5d 1207 sizeof(*dev_item));
0b86a832
CM
1208 if (ret)
1209 goto out;
1210
1211 leaf = path->nodes[0];
1212 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1213
1214 btrfs_set_device_id(leaf, dev_item, device->devid);
2b82032c 1215 btrfs_set_device_generation(leaf, dev_item, 0);
0b86a832
CM
1216 btrfs_set_device_type(leaf, dev_item, device->type);
1217 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1218 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1219 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
0b86a832
CM
1220 btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
1221 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
e17cade2
CM
1222 btrfs_set_device_group(leaf, dev_item, 0);
1223 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1224 btrfs_set_device_bandwidth(leaf, dev_item, 0);
c3027eb5 1225 btrfs_set_device_start_offset(leaf, dev_item, 0);
0b86a832 1226
0b86a832 1227 ptr = (unsigned long)btrfs_device_uuid(dev_item);
e17cade2 1228 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
2b82032c
YZ
1229 ptr = (unsigned long)btrfs_device_fsid(dev_item);
1230 write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
0b86a832 1231 btrfs_mark_buffer_dirty(leaf);
0b86a832 1232
2b82032c 1233 ret = 0;
0b86a832
CM
1234out:
1235 btrfs_free_path(path);
1236 return ret;
1237}
8f18cf13 1238
a061fc8d
CM
1239static int btrfs_rm_dev_item(struct btrfs_root *root,
1240 struct btrfs_device *device)
1241{
1242 int ret;
1243 struct btrfs_path *path;
a061fc8d 1244 struct btrfs_key key;
a061fc8d
CM
1245 struct btrfs_trans_handle *trans;
1246
1247 root = root->fs_info->chunk_root;
1248
1249 path = btrfs_alloc_path();
1250 if (!path)
1251 return -ENOMEM;
1252
a22285a6 1253 trans = btrfs_start_transaction(root, 0);
98d5dc13
TI
1254 if (IS_ERR(trans)) {
1255 btrfs_free_path(path);
1256 return PTR_ERR(trans);
1257 }
a061fc8d
CM
1258 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1259 key.type = BTRFS_DEV_ITEM_KEY;
1260 key.offset = device->devid;
7d9eb12c 1261 lock_chunks(root);
a061fc8d
CM
1262
1263 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1264 if (ret < 0)
1265 goto out;
1266
1267 if (ret > 0) {
1268 ret = -ENOENT;
1269 goto out;
1270 }
1271
1272 ret = btrfs_del_item(trans, root, path);
1273 if (ret)
1274 goto out;
a061fc8d
CM
1275out:
1276 btrfs_free_path(path);
7d9eb12c 1277 unlock_chunks(root);
a061fc8d
CM
1278 btrfs_commit_transaction(trans, root);
1279 return ret;
1280}
1281
1282int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1283{
1284 struct btrfs_device *device;
2b82032c 1285 struct btrfs_device *next_device;
a061fc8d 1286 struct block_device *bdev;
dfe25020 1287 struct buffer_head *bh = NULL;
a061fc8d 1288 struct btrfs_super_block *disk_super;
1f78160c 1289 struct btrfs_fs_devices *cur_devices;
a061fc8d
CM
1290 u64 all_avail;
1291 u64 devid;
2b82032c
YZ
1292 u64 num_devices;
1293 u8 *dev_uuid;
a061fc8d 1294 int ret = 0;
1f78160c 1295 bool clear_super = false;
a061fc8d 1296
a061fc8d
CM
1297 mutex_lock(&uuid_mutex);
1298
1299 all_avail = root->fs_info->avail_data_alloc_bits |
1300 root->fs_info->avail_system_alloc_bits |
1301 root->fs_info->avail_metadata_alloc_bits;
1302
1303 if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) &&
035fe03a 1304 root->fs_info->fs_devices->num_devices <= 4) {
d397712b
CM
1305 printk(KERN_ERR "btrfs: unable to go below four devices "
1306 "on raid10\n");
a061fc8d
CM
1307 ret = -EINVAL;
1308 goto out;
1309 }
1310
1311 if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) &&
035fe03a 1312 root->fs_info->fs_devices->num_devices <= 2) {
d397712b
CM
1313 printk(KERN_ERR "btrfs: unable to go below two "
1314 "devices on raid1\n");
a061fc8d
CM
1315 ret = -EINVAL;
1316 goto out;
1317 }
1318
dfe25020 1319 if (strcmp(device_path, "missing") == 0) {
dfe25020
CM
1320 struct list_head *devices;
1321 struct btrfs_device *tmp;
a061fc8d 1322
dfe25020
CM
1323 device = NULL;
1324 devices = &root->fs_info->fs_devices->devices;
46224705
XG
1325 /*
1326 * It is safe to read the devices since the volume_mutex
1327 * is held.
1328 */
c6e30871 1329 list_for_each_entry(tmp, devices, dev_list) {
dfe25020
CM
1330 if (tmp->in_fs_metadata && !tmp->bdev) {
1331 device = tmp;
1332 break;
1333 }
1334 }
1335 bdev = NULL;
1336 bh = NULL;
1337 disk_super = NULL;
1338 if (!device) {
d397712b
CM
1339 printk(KERN_ERR "btrfs: no missing devices found to "
1340 "remove\n");
dfe25020
CM
1341 goto out;
1342 }
dfe25020 1343 } else {
d4d77629
TH
1344 bdev = blkdev_get_by_path(device_path, FMODE_READ | FMODE_EXCL,
1345 root->fs_info->bdev_holder);
dfe25020
CM
1346 if (IS_ERR(bdev)) {
1347 ret = PTR_ERR(bdev);
1348 goto out;
1349 }
a061fc8d 1350
2b82032c 1351 set_blocksize(bdev, 4096);
a512bbf8 1352 bh = btrfs_read_dev_super(bdev);
dfe25020 1353 if (!bh) {
20b45077 1354 ret = -EINVAL;
dfe25020
CM
1355 goto error_close;
1356 }
1357 disk_super = (struct btrfs_super_block *)bh->b_data;
a343832f 1358 devid = btrfs_stack_device_id(&disk_super->dev_item);
2b82032c
YZ
1359 dev_uuid = disk_super->dev_item.uuid;
1360 device = btrfs_find_device(root, devid, dev_uuid,
1361 disk_super->fsid);
dfe25020
CM
1362 if (!device) {
1363 ret = -ENOENT;
1364 goto error_brelse;
1365 }
2b82032c 1366 }
dfe25020 1367
2b82032c 1368 if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
d397712b
CM
1369 printk(KERN_ERR "btrfs: unable to remove the only writeable "
1370 "device\n");
2b82032c
YZ
1371 ret = -EINVAL;
1372 goto error_brelse;
1373 }
1374
1375 if (device->writeable) {
0c1daee0 1376 lock_chunks(root);
2b82032c 1377 list_del_init(&device->dev_alloc_list);
0c1daee0 1378 unlock_chunks(root);
2b82032c 1379 root->fs_info->fs_devices->rw_devices--;
1f78160c 1380 clear_super = true;
dfe25020 1381 }
a061fc8d
CM
1382
1383 ret = btrfs_shrink_device(device, 0);
1384 if (ret)
9b3517e9 1385 goto error_undo;
a061fc8d 1386
a061fc8d
CM
1387 ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1388 if (ret)
9b3517e9 1389 goto error_undo;
a061fc8d 1390
2bf64758
JB
1391 spin_lock(&root->fs_info->free_chunk_lock);
1392 root->fs_info->free_chunk_space = device->total_bytes -
1393 device->bytes_used;
1394 spin_unlock(&root->fs_info->free_chunk_lock);
1395
2b82032c 1396 device->in_fs_metadata = 0;
a2de733c 1397 btrfs_scrub_cancel_dev(root, device);
e5e9a520
CM
1398
1399 /*
1400 * the device list mutex makes sure that we don't change
1401 * the device list while someone else is writing out all
1402 * the device supers.
1403 */
1f78160c
XG
1404
1405 cur_devices = device->fs_devices;
e5e9a520 1406 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1f78160c 1407 list_del_rcu(&device->dev_list);
e5e9a520 1408
e4404d6e 1409 device->fs_devices->num_devices--;
2b82032c 1410
cd02dca5
CM
1411 if (device->missing)
1412 root->fs_info->fs_devices->missing_devices--;
1413
2b82032c
YZ
1414 next_device = list_entry(root->fs_info->fs_devices->devices.next,
1415 struct btrfs_device, dev_list);
1416 if (device->bdev == root->fs_info->sb->s_bdev)
1417 root->fs_info->sb->s_bdev = next_device->bdev;
1418 if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1419 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1420
1f78160c 1421 if (device->bdev)
e4404d6e 1422 device->fs_devices->open_devices--;
1f78160c
XG
1423
1424 call_rcu(&device->rcu, free_device);
1425 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
e4404d6e 1426
6c41761f
DS
1427 num_devices = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
1428 btrfs_set_super_num_devices(root->fs_info->super_copy, num_devices);
2b82032c 1429
1f78160c 1430 if (cur_devices->open_devices == 0) {
e4404d6e
YZ
1431 struct btrfs_fs_devices *fs_devices;
1432 fs_devices = root->fs_info->fs_devices;
1433 while (fs_devices) {
1f78160c 1434 if (fs_devices->seed == cur_devices)
e4404d6e
YZ
1435 break;
1436 fs_devices = fs_devices->seed;
2b82032c 1437 }
1f78160c
XG
1438 fs_devices->seed = cur_devices->seed;
1439 cur_devices->seed = NULL;
0c1daee0 1440 lock_chunks(root);
1f78160c 1441 __btrfs_close_devices(cur_devices);
0c1daee0 1442 unlock_chunks(root);
1f78160c 1443 free_fs_devices(cur_devices);
2b82032c
YZ
1444 }
1445
1446 /*
1447 * at this point, the device is zero sized. We want to
1448 * remove it from the devices list and zero out the old super
1449 */
1f78160c 1450 if (clear_super) {
dfe25020
CM
1451 /* make sure this device isn't detected as part of
1452 * the FS anymore
1453 */
1454 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1455 set_buffer_dirty(bh);
1456 sync_dirty_buffer(bh);
dfe25020 1457 }
a061fc8d 1458
a061fc8d 1459 ret = 0;
a061fc8d
CM
1460
1461error_brelse:
1462 brelse(bh);
1463error_close:
dfe25020 1464 if (bdev)
e525fd89 1465 blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
a061fc8d
CM
1466out:
1467 mutex_unlock(&uuid_mutex);
a061fc8d 1468 return ret;
9b3517e9
ID
1469error_undo:
1470 if (device->writeable) {
0c1daee0 1471 lock_chunks(root);
9b3517e9
ID
1472 list_add(&device->dev_alloc_list,
1473 &root->fs_info->fs_devices->alloc_list);
0c1daee0 1474 unlock_chunks(root);
9b3517e9
ID
1475 root->fs_info->fs_devices->rw_devices++;
1476 }
1477 goto error_brelse;
a061fc8d
CM
1478}
1479
2b82032c
YZ
1480/*
1481 * does all the dirty work required for changing file system's UUID.
1482 */
125ccb0a 1483static int btrfs_prepare_sprout(struct btrfs_root *root)
2b82032c
YZ
1484{
1485 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
1486 struct btrfs_fs_devices *old_devices;
e4404d6e 1487 struct btrfs_fs_devices *seed_devices;
6c41761f 1488 struct btrfs_super_block *disk_super = root->fs_info->super_copy;
2b82032c
YZ
1489 struct btrfs_device *device;
1490 u64 super_flags;
1491
1492 BUG_ON(!mutex_is_locked(&uuid_mutex));
e4404d6e 1493 if (!fs_devices->seeding)
2b82032c
YZ
1494 return -EINVAL;
1495
e4404d6e
YZ
1496 seed_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
1497 if (!seed_devices)
2b82032c
YZ
1498 return -ENOMEM;
1499
e4404d6e
YZ
1500 old_devices = clone_fs_devices(fs_devices);
1501 if (IS_ERR(old_devices)) {
1502 kfree(seed_devices);
1503 return PTR_ERR(old_devices);
2b82032c 1504 }
e4404d6e 1505
2b82032c
YZ
1506 list_add(&old_devices->list, &fs_uuids);
1507
e4404d6e
YZ
1508 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
1509 seed_devices->opened = 1;
1510 INIT_LIST_HEAD(&seed_devices->devices);
1511 INIT_LIST_HEAD(&seed_devices->alloc_list);
e5e9a520 1512 mutex_init(&seed_devices->device_list_mutex);
c9513edb
XG
1513
1514 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1f78160c
XG
1515 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
1516 synchronize_rcu);
c9513edb
XG
1517 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1518
e4404d6e
YZ
1519 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
1520 list_for_each_entry(device, &seed_devices->devices, dev_list) {
1521 device->fs_devices = seed_devices;
1522 }
1523
2b82032c
YZ
1524 fs_devices->seeding = 0;
1525 fs_devices->num_devices = 0;
1526 fs_devices->open_devices = 0;
e4404d6e 1527 fs_devices->seed = seed_devices;
2b82032c
YZ
1528
1529 generate_random_uuid(fs_devices->fsid);
1530 memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1531 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1532 super_flags = btrfs_super_flags(disk_super) &
1533 ~BTRFS_SUPER_FLAG_SEEDING;
1534 btrfs_set_super_flags(disk_super, super_flags);
1535
1536 return 0;
1537}
1538
1539/*
1540 * strore the expected generation for seed devices in device items.
1541 */
1542static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
1543 struct btrfs_root *root)
1544{
1545 struct btrfs_path *path;
1546 struct extent_buffer *leaf;
1547 struct btrfs_dev_item *dev_item;
1548 struct btrfs_device *device;
1549 struct btrfs_key key;
1550 u8 fs_uuid[BTRFS_UUID_SIZE];
1551 u8 dev_uuid[BTRFS_UUID_SIZE];
1552 u64 devid;
1553 int ret;
1554
1555 path = btrfs_alloc_path();
1556 if (!path)
1557 return -ENOMEM;
1558
1559 root = root->fs_info->chunk_root;
1560 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1561 key.offset = 0;
1562 key.type = BTRFS_DEV_ITEM_KEY;
1563
1564 while (1) {
1565 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1566 if (ret < 0)
1567 goto error;
1568
1569 leaf = path->nodes[0];
1570next_slot:
1571 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1572 ret = btrfs_next_leaf(root, path);
1573 if (ret > 0)
1574 break;
1575 if (ret < 0)
1576 goto error;
1577 leaf = path->nodes[0];
1578 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
b3b4aa74 1579 btrfs_release_path(path);
2b82032c
YZ
1580 continue;
1581 }
1582
1583 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1584 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
1585 key.type != BTRFS_DEV_ITEM_KEY)
1586 break;
1587
1588 dev_item = btrfs_item_ptr(leaf, path->slots[0],
1589 struct btrfs_dev_item);
1590 devid = btrfs_device_id(leaf, dev_item);
1591 read_extent_buffer(leaf, dev_uuid,
1592 (unsigned long)btrfs_device_uuid(dev_item),
1593 BTRFS_UUID_SIZE);
1594 read_extent_buffer(leaf, fs_uuid,
1595 (unsigned long)btrfs_device_fsid(dev_item),
1596 BTRFS_UUID_SIZE);
1597 device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
1598 BUG_ON(!device);
1599
1600 if (device->fs_devices->seeding) {
1601 btrfs_set_device_generation(leaf, dev_item,
1602 device->generation);
1603 btrfs_mark_buffer_dirty(leaf);
1604 }
1605
1606 path->slots[0]++;
1607 goto next_slot;
1608 }
1609 ret = 0;
1610error:
1611 btrfs_free_path(path);
1612 return ret;
1613}
1614
788f20eb
CM
1615int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
1616{
d5e2003c 1617 struct request_queue *q;
788f20eb
CM
1618 struct btrfs_trans_handle *trans;
1619 struct btrfs_device *device;
1620 struct block_device *bdev;
788f20eb 1621 struct list_head *devices;
2b82032c 1622 struct super_block *sb = root->fs_info->sb;
788f20eb 1623 u64 total_bytes;
2b82032c 1624 int seeding_dev = 0;
788f20eb
CM
1625 int ret = 0;
1626
2b82032c
YZ
1627 if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
1628 return -EINVAL;
788f20eb 1629
a5d16333 1630 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
d4d77629 1631 root->fs_info->bdev_holder);
7f59203a
JB
1632 if (IS_ERR(bdev))
1633 return PTR_ERR(bdev);
a2135011 1634
2b82032c
YZ
1635 if (root->fs_info->fs_devices->seeding) {
1636 seeding_dev = 1;
1637 down_write(&sb->s_umount);
1638 mutex_lock(&uuid_mutex);
1639 }
1640
8c8bee1d 1641 filemap_write_and_wait(bdev->bd_inode->i_mapping);
a2135011 1642
788f20eb 1643 devices = &root->fs_info->fs_devices->devices;
e5e9a520
CM
1644 /*
1645 * we have the volume lock, so we don't need the extra
1646 * device list mutex while reading the list here.
1647 */
c6e30871 1648 list_for_each_entry(device, devices, dev_list) {
788f20eb
CM
1649 if (device->bdev == bdev) {
1650 ret = -EEXIST;
2b82032c 1651 goto error;
788f20eb
CM
1652 }
1653 }
1654
1655 device = kzalloc(sizeof(*device), GFP_NOFS);
1656 if (!device) {
1657 /* we can safely leave the fs_devices entry around */
1658 ret = -ENOMEM;
2b82032c 1659 goto error;
788f20eb
CM
1660 }
1661
788f20eb
CM
1662 device->name = kstrdup(device_path, GFP_NOFS);
1663 if (!device->name) {
1664 kfree(device);
2b82032c
YZ
1665 ret = -ENOMEM;
1666 goto error;
788f20eb 1667 }
2b82032c
YZ
1668
1669 ret = find_next_devid(root, &device->devid);
1670 if (ret) {
67100f25 1671 kfree(device->name);
2b82032c
YZ
1672 kfree(device);
1673 goto error;
1674 }
1675
a22285a6 1676 trans = btrfs_start_transaction(root, 0);
98d5dc13 1677 if (IS_ERR(trans)) {
67100f25 1678 kfree(device->name);
98d5dc13
TI
1679 kfree(device);
1680 ret = PTR_ERR(trans);
1681 goto error;
1682 }
1683
2b82032c
YZ
1684 lock_chunks(root);
1685
d5e2003c
JB
1686 q = bdev_get_queue(bdev);
1687 if (blk_queue_discard(q))
1688 device->can_discard = 1;
2b82032c
YZ
1689 device->writeable = 1;
1690 device->work.func = pending_bios_fn;
1691 generate_random_uuid(device->uuid);
1692 spin_lock_init(&device->io_lock);
1693 device->generation = trans->transid;
788f20eb
CM
1694 device->io_width = root->sectorsize;
1695 device->io_align = root->sectorsize;
1696 device->sector_size = root->sectorsize;
1697 device->total_bytes = i_size_read(bdev->bd_inode);
2cc3c559 1698 device->disk_total_bytes = device->total_bytes;
788f20eb
CM
1699 device->dev_root = root->fs_info->dev_root;
1700 device->bdev = bdev;
dfe25020 1701 device->in_fs_metadata = 1;
fb01aa85 1702 device->mode = FMODE_EXCL;
2b82032c 1703 set_blocksize(device->bdev, 4096);
788f20eb 1704
2b82032c
YZ
1705 if (seeding_dev) {
1706 sb->s_flags &= ~MS_RDONLY;
125ccb0a 1707 ret = btrfs_prepare_sprout(root);
2b82032c
YZ
1708 BUG_ON(ret);
1709 }
788f20eb 1710
2b82032c 1711 device->fs_devices = root->fs_info->fs_devices;
e5e9a520
CM
1712
1713 /*
1714 * we don't want write_supers to jump in here with our device
1715 * half setup
1716 */
1717 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1f78160c 1718 list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
2b82032c
YZ
1719 list_add(&device->dev_alloc_list,
1720 &root->fs_info->fs_devices->alloc_list);
1721 root->fs_info->fs_devices->num_devices++;
1722 root->fs_info->fs_devices->open_devices++;
1723 root->fs_info->fs_devices->rw_devices++;
d5e2003c
JB
1724 if (device->can_discard)
1725 root->fs_info->fs_devices->num_can_discard++;
2b82032c 1726 root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
325cd4ba 1727
2bf64758
JB
1728 spin_lock(&root->fs_info->free_chunk_lock);
1729 root->fs_info->free_chunk_space += device->total_bytes;
1730 spin_unlock(&root->fs_info->free_chunk_lock);
1731
c289811c
CM
1732 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
1733 root->fs_info->fs_devices->rotating = 1;
1734
6c41761f
DS
1735 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
1736 btrfs_set_super_total_bytes(root->fs_info->super_copy,
788f20eb
CM
1737 total_bytes + device->total_bytes);
1738
6c41761f
DS
1739 total_bytes = btrfs_super_num_devices(root->fs_info->super_copy);
1740 btrfs_set_super_num_devices(root->fs_info->super_copy,
788f20eb 1741 total_bytes + 1);
e5e9a520 1742 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
788f20eb 1743
2b82032c
YZ
1744 if (seeding_dev) {
1745 ret = init_first_rw_device(trans, root, device);
1746 BUG_ON(ret);
1747 ret = btrfs_finish_sprout(trans, root);
1748 BUG_ON(ret);
1749 } else {
1750 ret = btrfs_add_device(trans, root, device);
1751 }
1752
913d952e
CM
1753 /*
1754 * we've got more storage, clear any full flags on the space
1755 * infos
1756 */
1757 btrfs_clear_space_info_full(root->fs_info);
1758
7d9eb12c 1759 unlock_chunks(root);
2b82032c 1760 btrfs_commit_transaction(trans, root);
a2135011 1761
2b82032c
YZ
1762 if (seeding_dev) {
1763 mutex_unlock(&uuid_mutex);
1764 up_write(&sb->s_umount);
788f20eb 1765
2b82032c
YZ
1766 ret = btrfs_relocate_sys_chunks(root);
1767 BUG_ON(ret);
1768 }
c9e9f97b 1769
2b82032c
YZ
1770 return ret;
1771error:
e525fd89 1772 blkdev_put(bdev, FMODE_EXCL);
2b82032c
YZ
1773 if (seeding_dev) {
1774 mutex_unlock(&uuid_mutex);
1775 up_write(&sb->s_umount);
1776 }
c9e9f97b 1777 return ret;
788f20eb
CM
1778}
1779
d397712b
CM
1780static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
1781 struct btrfs_device *device)
0b86a832
CM
1782{
1783 int ret;
1784 struct btrfs_path *path;
1785 struct btrfs_root *root;
1786 struct btrfs_dev_item *dev_item;
1787 struct extent_buffer *leaf;
1788 struct btrfs_key key;
1789
1790 root = device->dev_root->fs_info->chunk_root;
1791
1792 path = btrfs_alloc_path();
1793 if (!path)
1794 return -ENOMEM;
1795
1796 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1797 key.type = BTRFS_DEV_ITEM_KEY;
1798 key.offset = device->devid;
1799
1800 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1801 if (ret < 0)
1802 goto out;
1803
1804 if (ret > 0) {
1805 ret = -ENOENT;
1806 goto out;
1807 }
1808
1809 leaf = path->nodes[0];
1810 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1811
1812 btrfs_set_device_id(leaf, dev_item, device->devid);
1813 btrfs_set_device_type(leaf, dev_item, device->type);
1814 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1815 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1816 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
d6397bae 1817 btrfs_set_device_total_bytes(leaf, dev_item, device->disk_total_bytes);
0b86a832
CM
1818 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1819 btrfs_mark_buffer_dirty(leaf);
1820
1821out:
1822 btrfs_free_path(path);
1823 return ret;
1824}
1825
7d9eb12c 1826static int __btrfs_grow_device(struct btrfs_trans_handle *trans,
8f18cf13
CM
1827 struct btrfs_device *device, u64 new_size)
1828{
1829 struct btrfs_super_block *super_copy =
6c41761f 1830 device->dev_root->fs_info->super_copy;
8f18cf13
CM
1831 u64 old_total = btrfs_super_total_bytes(super_copy);
1832 u64 diff = new_size - device->total_bytes;
1833
2b82032c
YZ
1834 if (!device->writeable)
1835 return -EACCES;
1836 if (new_size <= device->total_bytes)
1837 return -EINVAL;
1838
8f18cf13 1839 btrfs_set_super_total_bytes(super_copy, old_total + diff);
2b82032c
YZ
1840 device->fs_devices->total_rw_bytes += diff;
1841
1842 device->total_bytes = new_size;
9779b72f 1843 device->disk_total_bytes = new_size;
4184ea7f
CM
1844 btrfs_clear_space_info_full(device->dev_root->fs_info);
1845
8f18cf13
CM
1846 return btrfs_update_device(trans, device);
1847}
1848
7d9eb12c
CM
1849int btrfs_grow_device(struct btrfs_trans_handle *trans,
1850 struct btrfs_device *device, u64 new_size)
1851{
1852 int ret;
1853 lock_chunks(device->dev_root);
1854 ret = __btrfs_grow_device(trans, device, new_size);
1855 unlock_chunks(device->dev_root);
1856 return ret;
1857}
1858
8f18cf13
CM
1859static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
1860 struct btrfs_root *root,
1861 u64 chunk_tree, u64 chunk_objectid,
1862 u64 chunk_offset)
1863{
1864 int ret;
1865 struct btrfs_path *path;
1866 struct btrfs_key key;
1867
1868 root = root->fs_info->chunk_root;
1869 path = btrfs_alloc_path();
1870 if (!path)
1871 return -ENOMEM;
1872
1873 key.objectid = chunk_objectid;
1874 key.offset = chunk_offset;
1875 key.type = BTRFS_CHUNK_ITEM_KEY;
1876
1877 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1878 BUG_ON(ret);
1879
1880 ret = btrfs_del_item(trans, root, path);
8f18cf13
CM
1881
1882 btrfs_free_path(path);
65a246c5 1883 return ret;
8f18cf13
CM
1884}
1885
b2950863 1886static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
8f18cf13
CM
1887 chunk_offset)
1888{
6c41761f 1889 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
8f18cf13
CM
1890 struct btrfs_disk_key *disk_key;
1891 struct btrfs_chunk *chunk;
1892 u8 *ptr;
1893 int ret = 0;
1894 u32 num_stripes;
1895 u32 array_size;
1896 u32 len = 0;
1897 u32 cur;
1898 struct btrfs_key key;
1899
1900 array_size = btrfs_super_sys_array_size(super_copy);
1901
1902 ptr = super_copy->sys_chunk_array;
1903 cur = 0;
1904
1905 while (cur < array_size) {
1906 disk_key = (struct btrfs_disk_key *)ptr;
1907 btrfs_disk_key_to_cpu(&key, disk_key);
1908
1909 len = sizeof(*disk_key);
1910
1911 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1912 chunk = (struct btrfs_chunk *)(ptr + len);
1913 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
1914 len += btrfs_chunk_item_size(num_stripes);
1915 } else {
1916 ret = -EIO;
1917 break;
1918 }
1919 if (key.objectid == chunk_objectid &&
1920 key.offset == chunk_offset) {
1921 memmove(ptr, ptr + len, array_size - (cur + len));
1922 array_size -= len;
1923 btrfs_set_super_sys_array_size(super_copy, array_size);
1924 } else {
1925 ptr += len;
1926 cur += len;
1927 }
1928 }
1929 return ret;
1930}
1931
b2950863 1932static int btrfs_relocate_chunk(struct btrfs_root *root,
8f18cf13
CM
1933 u64 chunk_tree, u64 chunk_objectid,
1934 u64 chunk_offset)
1935{
1936 struct extent_map_tree *em_tree;
1937 struct btrfs_root *extent_root;
1938 struct btrfs_trans_handle *trans;
1939 struct extent_map *em;
1940 struct map_lookup *map;
1941 int ret;
1942 int i;
1943
1944 root = root->fs_info->chunk_root;
1945 extent_root = root->fs_info->extent_root;
1946 em_tree = &root->fs_info->mapping_tree.map_tree;
1947
ba1bf481
JB
1948 ret = btrfs_can_relocate(extent_root, chunk_offset);
1949 if (ret)
1950 return -ENOSPC;
1951
8f18cf13 1952 /* step one, relocate all the extents inside this chunk */
1a40e23b 1953 ret = btrfs_relocate_block_group(extent_root, chunk_offset);
a22285a6
YZ
1954 if (ret)
1955 return ret;
8f18cf13 1956
a22285a6 1957 trans = btrfs_start_transaction(root, 0);
98d5dc13 1958 BUG_ON(IS_ERR(trans));
8f18cf13 1959
7d9eb12c
CM
1960 lock_chunks(root);
1961
8f18cf13
CM
1962 /*
1963 * step two, delete the device extents and the
1964 * chunk tree entries
1965 */
890871be 1966 read_lock(&em_tree->lock);
8f18cf13 1967 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
890871be 1968 read_unlock(&em_tree->lock);
8f18cf13 1969
285190d9 1970 BUG_ON(!em || em->start > chunk_offset ||
a061fc8d 1971 em->start + em->len < chunk_offset);
8f18cf13
CM
1972 map = (struct map_lookup *)em->bdev;
1973
1974 for (i = 0; i < map->num_stripes; i++) {
1975 ret = btrfs_free_dev_extent(trans, map->stripes[i].dev,
1976 map->stripes[i].physical);
1977 BUG_ON(ret);
a061fc8d 1978
dfe25020
CM
1979 if (map->stripes[i].dev) {
1980 ret = btrfs_update_device(trans, map->stripes[i].dev);
1981 BUG_ON(ret);
1982 }
8f18cf13
CM
1983 }
1984 ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
1985 chunk_offset);
1986
1987 BUG_ON(ret);
1988
1abe9b8a 1989 trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
1990
8f18cf13
CM
1991 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
1992 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
1993 BUG_ON(ret);
8f18cf13
CM
1994 }
1995
2b82032c
YZ
1996 ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
1997 BUG_ON(ret);
1998
890871be 1999 write_lock(&em_tree->lock);
2b82032c 2000 remove_extent_mapping(em_tree, em);
890871be 2001 write_unlock(&em_tree->lock);
2b82032c
YZ
2002
2003 kfree(map);
2004 em->bdev = NULL;
2005
2006 /* once for the tree */
2007 free_extent_map(em);
2008 /* once for us */
2009 free_extent_map(em);
2010
2011 unlock_chunks(root);
2012 btrfs_end_transaction(trans, root);
2013 return 0;
2014}
2015
2016static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
2017{
2018 struct btrfs_root *chunk_root = root->fs_info->chunk_root;
2019 struct btrfs_path *path;
2020 struct extent_buffer *leaf;
2021 struct btrfs_chunk *chunk;
2022 struct btrfs_key key;
2023 struct btrfs_key found_key;
2024 u64 chunk_tree = chunk_root->root_key.objectid;
2025 u64 chunk_type;
ba1bf481
JB
2026 bool retried = false;
2027 int failed = 0;
2b82032c
YZ
2028 int ret;
2029
2030 path = btrfs_alloc_path();
2031 if (!path)
2032 return -ENOMEM;
2033
ba1bf481 2034again:
2b82032c
YZ
2035 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2036 key.offset = (u64)-1;
2037 key.type = BTRFS_CHUNK_ITEM_KEY;
2038
2039 while (1) {
2040 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2041 if (ret < 0)
2042 goto error;
2043 BUG_ON(ret == 0);
2044
2045 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2046 key.type);
2047 if (ret < 0)
2048 goto error;
2049 if (ret > 0)
2050 break;
1a40e23b 2051
2b82032c
YZ
2052 leaf = path->nodes[0];
2053 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1a40e23b 2054
2b82032c
YZ
2055 chunk = btrfs_item_ptr(leaf, path->slots[0],
2056 struct btrfs_chunk);
2057 chunk_type = btrfs_chunk_type(leaf, chunk);
b3b4aa74 2058 btrfs_release_path(path);
8f18cf13 2059
2b82032c
YZ
2060 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2061 ret = btrfs_relocate_chunk(chunk_root, chunk_tree,
2062 found_key.objectid,
2063 found_key.offset);
ba1bf481
JB
2064 if (ret == -ENOSPC)
2065 failed++;
2066 else if (ret)
2067 BUG();
2b82032c 2068 }
8f18cf13 2069
2b82032c
YZ
2070 if (found_key.offset == 0)
2071 break;
2072 key.offset = found_key.offset - 1;
2073 }
2074 ret = 0;
ba1bf481
JB
2075 if (failed && !retried) {
2076 failed = 0;
2077 retried = true;
2078 goto again;
2079 } else if (failed && retried) {
2080 WARN_ON(1);
2081 ret = -ENOSPC;
2082 }
2b82032c
YZ
2083error:
2084 btrfs_free_path(path);
2085 return ret;
8f18cf13
CM
2086}
2087
0940ebf6
ID
2088static int insert_balance_item(struct btrfs_root *root,
2089 struct btrfs_balance_control *bctl)
2090{
2091 struct btrfs_trans_handle *trans;
2092 struct btrfs_balance_item *item;
2093 struct btrfs_disk_balance_args disk_bargs;
2094 struct btrfs_path *path;
2095 struct extent_buffer *leaf;
2096 struct btrfs_key key;
2097 int ret, err;
2098
2099 path = btrfs_alloc_path();
2100 if (!path)
2101 return -ENOMEM;
2102
2103 trans = btrfs_start_transaction(root, 0);
2104 if (IS_ERR(trans)) {
2105 btrfs_free_path(path);
2106 return PTR_ERR(trans);
2107 }
2108
2109 key.objectid = BTRFS_BALANCE_OBJECTID;
2110 key.type = BTRFS_BALANCE_ITEM_KEY;
2111 key.offset = 0;
2112
2113 ret = btrfs_insert_empty_item(trans, root, path, &key,
2114 sizeof(*item));
2115 if (ret)
2116 goto out;
2117
2118 leaf = path->nodes[0];
2119 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2120
2121 memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
2122
2123 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
2124 btrfs_set_balance_data(leaf, item, &disk_bargs);
2125 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
2126 btrfs_set_balance_meta(leaf, item, &disk_bargs);
2127 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
2128 btrfs_set_balance_sys(leaf, item, &disk_bargs);
2129
2130 btrfs_set_balance_flags(leaf, item, bctl->flags);
2131
2132 btrfs_mark_buffer_dirty(leaf);
2133out:
2134 btrfs_free_path(path);
2135 err = btrfs_commit_transaction(trans, root);
2136 if (err && !ret)
2137 ret = err;
2138 return ret;
2139}
2140
2141static int del_balance_item(struct btrfs_root *root)
2142{
2143 struct btrfs_trans_handle *trans;
2144 struct btrfs_path *path;
2145 struct btrfs_key key;
2146 int ret, err;
2147
2148 path = btrfs_alloc_path();
2149 if (!path)
2150 return -ENOMEM;
2151
2152 trans = btrfs_start_transaction(root, 0);
2153 if (IS_ERR(trans)) {
2154 btrfs_free_path(path);
2155 return PTR_ERR(trans);
2156 }
2157
2158 key.objectid = BTRFS_BALANCE_OBJECTID;
2159 key.type = BTRFS_BALANCE_ITEM_KEY;
2160 key.offset = 0;
2161
2162 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2163 if (ret < 0)
2164 goto out;
2165 if (ret > 0) {
2166 ret = -ENOENT;
2167 goto out;
2168 }
2169
2170 ret = btrfs_del_item(trans, root, path);
2171out:
2172 btrfs_free_path(path);
2173 err = btrfs_commit_transaction(trans, root);
2174 if (err && !ret)
2175 ret = err;
2176 return ret;
2177}
2178
59641015
ID
2179/*
2180 * This is a heuristic used to reduce the number of chunks balanced on
2181 * resume after balance was interrupted.
2182 */
2183static void update_balance_args(struct btrfs_balance_control *bctl)
2184{
2185 /*
2186 * Turn on soft mode for chunk types that were being converted.
2187 */
2188 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
2189 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
2190 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
2191 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
2192 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
2193 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
2194
2195 /*
2196 * Turn on usage filter if is not already used. The idea is
2197 * that chunks that we have already balanced should be
2198 * reasonably full. Don't do it for chunks that are being
2199 * converted - that will keep us from relocating unconverted
2200 * (albeit full) chunks.
2201 */
2202 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2203 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2204 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
2205 bctl->data.usage = 90;
2206 }
2207 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2208 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2209 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
2210 bctl->sys.usage = 90;
2211 }
2212 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2213 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2214 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
2215 bctl->meta.usage = 90;
2216 }
2217}
2218
c9e9f97b
ID
2219/*
2220 * Should be called with both balance and volume mutexes held to
2221 * serialize other volume operations (add_dev/rm_dev/resize) with
2222 * restriper. Same goes for unset_balance_control.
2223 */
2224static void set_balance_control(struct btrfs_balance_control *bctl)
2225{
2226 struct btrfs_fs_info *fs_info = bctl->fs_info;
2227
2228 BUG_ON(fs_info->balance_ctl);
2229
2230 spin_lock(&fs_info->balance_lock);
2231 fs_info->balance_ctl = bctl;
2232 spin_unlock(&fs_info->balance_lock);
2233}
2234
2235static void unset_balance_control(struct btrfs_fs_info *fs_info)
2236{
2237 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
2238
2239 BUG_ON(!fs_info->balance_ctl);
2240
2241 spin_lock(&fs_info->balance_lock);
2242 fs_info->balance_ctl = NULL;
2243 spin_unlock(&fs_info->balance_lock);
2244
2245 kfree(bctl);
2246}
2247
ed25e9b2
ID
2248/*
2249 * Balance filters. Return 1 if chunk should be filtered out
2250 * (should not be balanced).
2251 */
2252static int chunk_profiles_filter(u64 chunk_profile,
2253 struct btrfs_balance_args *bargs)
2254{
2255 chunk_profile &= BTRFS_BLOCK_GROUP_PROFILE_MASK;
2256
2257 if (chunk_profile == 0)
2258 chunk_profile = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
2259
2260 if (bargs->profiles & chunk_profile)
2261 return 0;
2262
2263 return 1;
2264}
2265
5ce5b3c0
ID
2266static u64 div_factor_fine(u64 num, int factor)
2267{
2268 if (factor <= 0)
2269 return 0;
2270 if (factor >= 100)
2271 return num;
2272
2273 num *= factor;
2274 do_div(num, 100);
2275 return num;
2276}
2277
2278static int chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
2279 struct btrfs_balance_args *bargs)
2280{
2281 struct btrfs_block_group_cache *cache;
2282 u64 chunk_used, user_thresh;
2283 int ret = 1;
2284
2285 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2286 chunk_used = btrfs_block_group_used(&cache->item);
2287
2288 user_thresh = div_factor_fine(cache->key.offset, bargs->usage);
2289 if (chunk_used < user_thresh)
2290 ret = 0;
2291
2292 btrfs_put_block_group(cache);
2293 return ret;
2294}
2295
409d404b
ID
2296static int chunk_devid_filter(struct extent_buffer *leaf,
2297 struct btrfs_chunk *chunk,
2298 struct btrfs_balance_args *bargs)
2299{
2300 struct btrfs_stripe *stripe;
2301 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2302 int i;
2303
2304 for (i = 0; i < num_stripes; i++) {
2305 stripe = btrfs_stripe_nr(chunk, i);
2306 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
2307 return 0;
2308 }
2309
2310 return 1;
2311}
2312
94e60d5a
ID
2313/* [pstart, pend) */
2314static int chunk_drange_filter(struct extent_buffer *leaf,
2315 struct btrfs_chunk *chunk,
2316 u64 chunk_offset,
2317 struct btrfs_balance_args *bargs)
2318{
2319 struct btrfs_stripe *stripe;
2320 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2321 u64 stripe_offset;
2322 u64 stripe_length;
2323 int factor;
2324 int i;
2325
2326 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
2327 return 0;
2328
2329 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
2330 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10))
2331 factor = 2;
2332 else
2333 factor = 1;
2334 factor = num_stripes / factor;
2335
2336 for (i = 0; i < num_stripes; i++) {
2337 stripe = btrfs_stripe_nr(chunk, i);
2338 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
2339 continue;
2340
2341 stripe_offset = btrfs_stripe_offset(leaf, stripe);
2342 stripe_length = btrfs_chunk_length(leaf, chunk);
2343 do_div(stripe_length, factor);
2344
2345 if (stripe_offset < bargs->pend &&
2346 stripe_offset + stripe_length > bargs->pstart)
2347 return 0;
2348 }
2349
2350 return 1;
2351}
2352
ea67176a
ID
2353/* [vstart, vend) */
2354static int chunk_vrange_filter(struct extent_buffer *leaf,
2355 struct btrfs_chunk *chunk,
2356 u64 chunk_offset,
2357 struct btrfs_balance_args *bargs)
2358{
2359 if (chunk_offset < bargs->vend &&
2360 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
2361 /* at least part of the chunk is inside this vrange */
2362 return 0;
2363
2364 return 1;
2365}
2366
cfa4c961
ID
2367static int chunk_soft_convert_filter(u64 chunk_profile,
2368 struct btrfs_balance_args *bargs)
2369{
2370 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
2371 return 0;
2372
2373 chunk_profile &= BTRFS_BLOCK_GROUP_PROFILE_MASK;
2374
2375 if (chunk_profile == 0)
2376 chunk_profile = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
2377
2378 if (bargs->target & chunk_profile)
2379 return 1;
2380
2381 return 0;
2382}
2383
f43ffb60
ID
2384static int should_balance_chunk(struct btrfs_root *root,
2385 struct extent_buffer *leaf,
2386 struct btrfs_chunk *chunk, u64 chunk_offset)
2387{
2388 struct btrfs_balance_control *bctl = root->fs_info->balance_ctl;
2389 struct btrfs_balance_args *bargs = NULL;
2390 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
2391
2392 /* type filter */
2393 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
2394 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
2395 return 0;
2396 }
2397
2398 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
2399 bargs = &bctl->data;
2400 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
2401 bargs = &bctl->sys;
2402 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
2403 bargs = &bctl->meta;
2404
ed25e9b2
ID
2405 /* profiles filter */
2406 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
2407 chunk_profiles_filter(chunk_type, bargs)) {
2408 return 0;
5ce5b3c0
ID
2409 }
2410
2411 /* usage filter */
2412 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
2413 chunk_usage_filter(bctl->fs_info, chunk_offset, bargs)) {
2414 return 0;
409d404b
ID
2415 }
2416
2417 /* devid filter */
2418 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
2419 chunk_devid_filter(leaf, chunk, bargs)) {
2420 return 0;
94e60d5a
ID
2421 }
2422
2423 /* drange filter, makes sense only with devid filter */
2424 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
2425 chunk_drange_filter(leaf, chunk, chunk_offset, bargs)) {
2426 return 0;
ea67176a
ID
2427 }
2428
2429 /* vrange filter */
2430 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
2431 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
2432 return 0;
ed25e9b2
ID
2433 }
2434
cfa4c961
ID
2435 /* soft profile changing mode */
2436 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
2437 chunk_soft_convert_filter(chunk_type, bargs)) {
2438 return 0;
2439 }
2440
f43ffb60
ID
2441 return 1;
2442}
2443
ec44a35c
CM
2444static u64 div_factor(u64 num, int factor)
2445{
2446 if (factor == 10)
2447 return num;
2448 num *= factor;
2449 do_div(num, 10);
2450 return num;
2451}
2452
c9e9f97b 2453static int __btrfs_balance(struct btrfs_fs_info *fs_info)
ec44a35c 2454{
19a39dce 2455 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
c9e9f97b
ID
2456 struct btrfs_root *chunk_root = fs_info->chunk_root;
2457 struct btrfs_root *dev_root = fs_info->dev_root;
2458 struct list_head *devices;
ec44a35c
CM
2459 struct btrfs_device *device;
2460 u64 old_size;
2461 u64 size_to_free;
f43ffb60 2462 struct btrfs_chunk *chunk;
ec44a35c
CM
2463 struct btrfs_path *path;
2464 struct btrfs_key key;
ec44a35c 2465 struct btrfs_key found_key;
c9e9f97b 2466 struct btrfs_trans_handle *trans;
f43ffb60
ID
2467 struct extent_buffer *leaf;
2468 int slot;
c9e9f97b
ID
2469 int ret;
2470 int enospc_errors = 0;
19a39dce 2471 bool counting = true;
ec44a35c 2472
ec44a35c 2473 /* step one make some room on all the devices */
c9e9f97b 2474 devices = &fs_info->fs_devices->devices;
c6e30871 2475 list_for_each_entry(device, devices, dev_list) {
ec44a35c
CM
2476 old_size = device->total_bytes;
2477 size_to_free = div_factor(old_size, 1);
2478 size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
2b82032c
YZ
2479 if (!device->writeable ||
2480 device->total_bytes - device->bytes_used > size_to_free)
ec44a35c
CM
2481 continue;
2482
2483 ret = btrfs_shrink_device(device, old_size - size_to_free);
ba1bf481
JB
2484 if (ret == -ENOSPC)
2485 break;
ec44a35c
CM
2486 BUG_ON(ret);
2487
a22285a6 2488 trans = btrfs_start_transaction(dev_root, 0);
98d5dc13 2489 BUG_ON(IS_ERR(trans));
ec44a35c
CM
2490
2491 ret = btrfs_grow_device(trans, device, old_size);
2492 BUG_ON(ret);
2493
2494 btrfs_end_transaction(trans, dev_root);
2495 }
2496
2497 /* step two, relocate all the chunks */
2498 path = btrfs_alloc_path();
17e9f796
MF
2499 if (!path) {
2500 ret = -ENOMEM;
2501 goto error;
2502 }
19a39dce
ID
2503
2504 /* zero out stat counters */
2505 spin_lock(&fs_info->balance_lock);
2506 memset(&bctl->stat, 0, sizeof(bctl->stat));
2507 spin_unlock(&fs_info->balance_lock);
2508again:
ec44a35c
CM
2509 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2510 key.offset = (u64)-1;
2511 key.type = BTRFS_CHUNK_ITEM_KEY;
2512
d397712b 2513 while (1) {
19a39dce 2514 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
a7e99c69 2515 atomic_read(&fs_info->balance_cancel_req)) {
837d5b6e
ID
2516 ret = -ECANCELED;
2517 goto error;
2518 }
2519
ec44a35c
CM
2520 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2521 if (ret < 0)
2522 goto error;
2523
2524 /*
2525 * this shouldn't happen, it means the last relocate
2526 * failed
2527 */
2528 if (ret == 0)
c9e9f97b 2529 BUG(); /* FIXME break ? */
ec44a35c
CM
2530
2531 ret = btrfs_previous_item(chunk_root, path, 0,
2532 BTRFS_CHUNK_ITEM_KEY);
c9e9f97b
ID
2533 if (ret) {
2534 ret = 0;
ec44a35c 2535 break;
c9e9f97b 2536 }
7d9eb12c 2537
f43ffb60
ID
2538 leaf = path->nodes[0];
2539 slot = path->slots[0];
2540 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7d9eb12c 2541
ec44a35c
CM
2542 if (found_key.objectid != key.objectid)
2543 break;
7d9eb12c 2544
ec44a35c 2545 /* chunk zero is special */
ba1bf481 2546 if (found_key.offset == 0)
ec44a35c
CM
2547 break;
2548
f43ffb60
ID
2549 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
2550
19a39dce
ID
2551 if (!counting) {
2552 spin_lock(&fs_info->balance_lock);
2553 bctl->stat.considered++;
2554 spin_unlock(&fs_info->balance_lock);
2555 }
2556
f43ffb60
ID
2557 ret = should_balance_chunk(chunk_root, leaf, chunk,
2558 found_key.offset);
b3b4aa74 2559 btrfs_release_path(path);
f43ffb60
ID
2560 if (!ret)
2561 goto loop;
2562
19a39dce
ID
2563 if (counting) {
2564 spin_lock(&fs_info->balance_lock);
2565 bctl->stat.expected++;
2566 spin_unlock(&fs_info->balance_lock);
2567 goto loop;
2568 }
2569
ec44a35c
CM
2570 ret = btrfs_relocate_chunk(chunk_root,
2571 chunk_root->root_key.objectid,
2572 found_key.objectid,
2573 found_key.offset);
508794eb
JB
2574 if (ret && ret != -ENOSPC)
2575 goto error;
19a39dce 2576 if (ret == -ENOSPC) {
c9e9f97b 2577 enospc_errors++;
19a39dce
ID
2578 } else {
2579 spin_lock(&fs_info->balance_lock);
2580 bctl->stat.completed++;
2581 spin_unlock(&fs_info->balance_lock);
2582 }
f43ffb60 2583loop:
ba1bf481 2584 key.offset = found_key.offset - 1;
ec44a35c 2585 }
c9e9f97b 2586
19a39dce
ID
2587 if (counting) {
2588 btrfs_release_path(path);
2589 counting = false;
2590 goto again;
2591 }
ec44a35c
CM
2592error:
2593 btrfs_free_path(path);
c9e9f97b
ID
2594 if (enospc_errors) {
2595 printk(KERN_INFO "btrfs: %d enospc errors during balance\n",
2596 enospc_errors);
2597 if (!ret)
2598 ret = -ENOSPC;
2599 }
2600
ec44a35c
CM
2601 return ret;
2602}
2603
837d5b6e
ID
2604static inline int balance_need_close(struct btrfs_fs_info *fs_info)
2605{
a7e99c69
ID
2606 /* cancel requested || normal exit path */
2607 return atomic_read(&fs_info->balance_cancel_req) ||
2608 (atomic_read(&fs_info->balance_pause_req) == 0 &&
2609 atomic_read(&fs_info->balance_cancel_req) == 0);
837d5b6e
ID
2610}
2611
c9e9f97b
ID
2612static void __cancel_balance(struct btrfs_fs_info *fs_info)
2613{
0940ebf6
ID
2614 int ret;
2615
c9e9f97b 2616 unset_balance_control(fs_info);
0940ebf6
ID
2617 ret = del_balance_item(fs_info->tree_root);
2618 BUG_ON(ret);
c9e9f97b
ID
2619}
2620
19a39dce 2621void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
c9e9f97b
ID
2622 struct btrfs_ioctl_balance_args *bargs);
2623
2624/*
2625 * Should be called with both balance and volume mutexes held
2626 */
2627int btrfs_balance(struct btrfs_balance_control *bctl,
2628 struct btrfs_ioctl_balance_args *bargs)
2629{
2630 struct btrfs_fs_info *fs_info = bctl->fs_info;
f43ffb60 2631 u64 allowed;
c9e9f97b
ID
2632 int ret;
2633
837d5b6e 2634 if (btrfs_fs_closing(fs_info) ||
a7e99c69
ID
2635 atomic_read(&fs_info->balance_pause_req) ||
2636 atomic_read(&fs_info->balance_cancel_req)) {
c9e9f97b
ID
2637 ret = -EINVAL;
2638 goto out;
2639 }
2640
f43ffb60
ID
2641 /*
2642 * In case of mixed groups both data and meta should be picked,
2643 * and identical options should be given for both of them.
2644 */
2645 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
2646 if ((allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
2647 (bctl->flags & (BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA))) {
2648 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
2649 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
2650 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
2651 printk(KERN_ERR "btrfs: with mixed groups data and "
2652 "metadata balance options must be the same\n");
2653 ret = -EINVAL;
2654 goto out;
2655 }
2656 }
2657
e4d8ec0f
ID
2658 /*
2659 * Profile changing sanity checks. Skip them if a simple
2660 * balance is requested.
2661 */
2662 if (!((bctl->data.flags | bctl->sys.flags | bctl->meta.flags) &
2663 BTRFS_BALANCE_ARGS_CONVERT))
2664 goto do_balance;
2665
2666 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
2667 if (fs_info->fs_devices->num_devices == 1)
2668 allowed |= BTRFS_BLOCK_GROUP_DUP;
2669 else if (fs_info->fs_devices->num_devices < 4)
2670 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
2671 else
2672 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
2673 BTRFS_BLOCK_GROUP_RAID10);
2674
2675 if (!profile_is_valid(bctl->data.target, 1) ||
2676 bctl->data.target & ~allowed) {
2677 printk(KERN_ERR "btrfs: unable to start balance with target "
2678 "data profile %llu\n",
2679 (unsigned long long)bctl->data.target);
2680 ret = -EINVAL;
2681 goto out;
2682 }
2683 if (!profile_is_valid(bctl->meta.target, 1) ||
2684 bctl->meta.target & ~allowed) {
2685 printk(KERN_ERR "btrfs: unable to start balance with target "
2686 "metadata profile %llu\n",
2687 (unsigned long long)bctl->meta.target);
2688 ret = -EINVAL;
2689 goto out;
2690 }
2691 if (!profile_is_valid(bctl->sys.target, 1) ||
2692 bctl->sys.target & ~allowed) {
2693 printk(KERN_ERR "btrfs: unable to start balance with target "
2694 "system profile %llu\n",
2695 (unsigned long long)bctl->sys.target);
2696 ret = -EINVAL;
2697 goto out;
2698 }
2699
2700 if (bctl->data.target & BTRFS_BLOCK_GROUP_DUP) {
2701 printk(KERN_ERR "btrfs: dup for data is not allowed\n");
2702 ret = -EINVAL;
2703 goto out;
2704 }
2705
2706 /* allow to reduce meta or sys integrity only if force set */
2707 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
2708 BTRFS_BLOCK_GROUP_RAID10;
2709 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
2710 (fs_info->avail_system_alloc_bits & allowed) &&
2711 !(bctl->sys.target & allowed)) ||
2712 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
2713 (fs_info->avail_metadata_alloc_bits & allowed) &&
2714 !(bctl->meta.target & allowed))) {
2715 if (bctl->flags & BTRFS_BALANCE_FORCE) {
2716 printk(KERN_INFO "btrfs: force reducing metadata "
2717 "integrity\n");
2718 } else {
2719 printk(KERN_ERR "btrfs: balance will reduce metadata "
2720 "integrity, use force if you want this\n");
2721 ret = -EINVAL;
2722 goto out;
2723 }
2724 }
2725
2726do_balance:
0940ebf6 2727 ret = insert_balance_item(fs_info->tree_root, bctl);
59641015 2728 if (ret && ret != -EEXIST)
0940ebf6
ID
2729 goto out;
2730
59641015
ID
2731 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
2732 BUG_ON(ret == -EEXIST);
2733 set_balance_control(bctl);
2734 } else {
2735 BUG_ON(ret != -EEXIST);
2736 spin_lock(&fs_info->balance_lock);
2737 update_balance_args(bctl);
2738 spin_unlock(&fs_info->balance_lock);
2739 }
c9e9f97b 2740
837d5b6e 2741 atomic_inc(&fs_info->balance_running);
c9e9f97b
ID
2742 mutex_unlock(&fs_info->balance_mutex);
2743
2744 ret = __btrfs_balance(fs_info);
2745
2746 mutex_lock(&fs_info->balance_mutex);
837d5b6e 2747 atomic_dec(&fs_info->balance_running);
c9e9f97b
ID
2748
2749 if (bargs) {
2750 memset(bargs, 0, sizeof(*bargs));
19a39dce 2751 update_ioctl_balance_args(fs_info, 0, bargs);
c9e9f97b
ID
2752 }
2753
837d5b6e
ID
2754 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
2755 balance_need_close(fs_info)) {
2756 __cancel_balance(fs_info);
2757 }
2758
2759 wake_up(&fs_info->balance_wait_q);
c9e9f97b
ID
2760
2761 return ret;
2762out:
59641015
ID
2763 if (bctl->flags & BTRFS_BALANCE_RESUME)
2764 __cancel_balance(fs_info);
2765 else
2766 kfree(bctl);
2767 return ret;
2768}
2769
2770static int balance_kthread(void *data)
2771{
2772 struct btrfs_balance_control *bctl =
2773 (struct btrfs_balance_control *)data;
2774 struct btrfs_fs_info *fs_info = bctl->fs_info;
9555c6c1 2775 int ret = 0;
59641015
ID
2776
2777 mutex_lock(&fs_info->volume_mutex);
2778 mutex_lock(&fs_info->balance_mutex);
2779
2780 set_balance_control(bctl);
2781
9555c6c1
ID
2782 if (btrfs_test_opt(fs_info->tree_root, SKIP_BALANCE)) {
2783 printk(KERN_INFO "btrfs: force skipping balance\n");
2784 } else {
2785 printk(KERN_INFO "btrfs: continuing balance\n");
2786 ret = btrfs_balance(bctl, NULL);
2787 }
59641015
ID
2788
2789 mutex_unlock(&fs_info->balance_mutex);
2790 mutex_unlock(&fs_info->volume_mutex);
2791 return ret;
2792}
2793
2794int btrfs_recover_balance(struct btrfs_root *tree_root)
2795{
2796 struct task_struct *tsk;
2797 struct btrfs_balance_control *bctl;
2798 struct btrfs_balance_item *item;
2799 struct btrfs_disk_balance_args disk_bargs;
2800 struct btrfs_path *path;
2801 struct extent_buffer *leaf;
2802 struct btrfs_key key;
2803 int ret;
2804
2805 path = btrfs_alloc_path();
2806 if (!path)
2807 return -ENOMEM;
2808
2809 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
2810 if (!bctl) {
2811 ret = -ENOMEM;
2812 goto out;
2813 }
2814
2815 key.objectid = BTRFS_BALANCE_OBJECTID;
2816 key.type = BTRFS_BALANCE_ITEM_KEY;
2817 key.offset = 0;
2818
2819 ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
2820 if (ret < 0)
2821 goto out_bctl;
2822 if (ret > 0) { /* ret = -ENOENT; */
2823 ret = 0;
2824 goto out_bctl;
2825 }
2826
2827 leaf = path->nodes[0];
2828 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2829
2830 bctl->fs_info = tree_root->fs_info;
2831 bctl->flags = btrfs_balance_flags(leaf, item) | BTRFS_BALANCE_RESUME;
2832
2833 btrfs_balance_data(leaf, item, &disk_bargs);
2834 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
2835 btrfs_balance_meta(leaf, item, &disk_bargs);
2836 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
2837 btrfs_balance_sys(leaf, item, &disk_bargs);
2838 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
2839
2840 tsk = kthread_run(balance_kthread, bctl, "btrfs-balance");
2841 if (IS_ERR(tsk))
2842 ret = PTR_ERR(tsk);
2843 else
2844 goto out;
2845
2846out_bctl:
c9e9f97b 2847 kfree(bctl);
59641015
ID
2848out:
2849 btrfs_free_path(path);
ec44a35c
CM
2850 return ret;
2851}
2852
837d5b6e
ID
2853int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
2854{
2855 int ret = 0;
2856
2857 mutex_lock(&fs_info->balance_mutex);
2858 if (!fs_info->balance_ctl) {
2859 mutex_unlock(&fs_info->balance_mutex);
2860 return -ENOTCONN;
2861 }
2862
2863 if (atomic_read(&fs_info->balance_running)) {
2864 atomic_inc(&fs_info->balance_pause_req);
2865 mutex_unlock(&fs_info->balance_mutex);
2866
2867 wait_event(fs_info->balance_wait_q,
2868 atomic_read(&fs_info->balance_running) == 0);
2869
2870 mutex_lock(&fs_info->balance_mutex);
2871 /* we are good with balance_ctl ripped off from under us */
2872 BUG_ON(atomic_read(&fs_info->balance_running));
2873 atomic_dec(&fs_info->balance_pause_req);
2874 } else {
2875 ret = -ENOTCONN;
2876 }
2877
2878 mutex_unlock(&fs_info->balance_mutex);
2879 return ret;
2880}
2881
a7e99c69
ID
2882int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
2883{
2884 mutex_lock(&fs_info->balance_mutex);
2885 if (!fs_info->balance_ctl) {
2886 mutex_unlock(&fs_info->balance_mutex);
2887 return -ENOTCONN;
2888 }
2889
2890 atomic_inc(&fs_info->balance_cancel_req);
2891 /*
2892 * if we are running just wait and return, balance item is
2893 * deleted in btrfs_balance in this case
2894 */
2895 if (atomic_read(&fs_info->balance_running)) {
2896 mutex_unlock(&fs_info->balance_mutex);
2897 wait_event(fs_info->balance_wait_q,
2898 atomic_read(&fs_info->balance_running) == 0);
2899 mutex_lock(&fs_info->balance_mutex);
2900 } else {
2901 /* __cancel_balance needs volume_mutex */
2902 mutex_unlock(&fs_info->balance_mutex);
2903 mutex_lock(&fs_info->volume_mutex);
2904 mutex_lock(&fs_info->balance_mutex);
2905
2906 if (fs_info->balance_ctl)
2907 __cancel_balance(fs_info);
2908
2909 mutex_unlock(&fs_info->volume_mutex);
2910 }
2911
2912 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
2913 atomic_dec(&fs_info->balance_cancel_req);
2914 mutex_unlock(&fs_info->balance_mutex);
2915 return 0;
2916}
2917
8f18cf13
CM
2918/*
2919 * shrinking a device means finding all of the device extents past
2920 * the new size, and then following the back refs to the chunks.
2921 * The chunk relocation code actually frees the device extent
2922 */
2923int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
2924{
2925 struct btrfs_trans_handle *trans;
2926 struct btrfs_root *root = device->dev_root;
2927 struct btrfs_dev_extent *dev_extent = NULL;
2928 struct btrfs_path *path;
2929 u64 length;
2930 u64 chunk_tree;
2931 u64 chunk_objectid;
2932 u64 chunk_offset;
2933 int ret;
2934 int slot;
ba1bf481
JB
2935 int failed = 0;
2936 bool retried = false;
8f18cf13
CM
2937 struct extent_buffer *l;
2938 struct btrfs_key key;
6c41761f 2939 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
8f18cf13 2940 u64 old_total = btrfs_super_total_bytes(super_copy);
ba1bf481 2941 u64 old_size = device->total_bytes;
8f18cf13
CM
2942 u64 diff = device->total_bytes - new_size;
2943
2b82032c
YZ
2944 if (new_size >= device->total_bytes)
2945 return -EINVAL;
8f18cf13
CM
2946
2947 path = btrfs_alloc_path();
2948 if (!path)
2949 return -ENOMEM;
2950
8f18cf13
CM
2951 path->reada = 2;
2952
7d9eb12c
CM
2953 lock_chunks(root);
2954
8f18cf13 2955 device->total_bytes = new_size;
2bf64758 2956 if (device->writeable) {
2b82032c 2957 device->fs_devices->total_rw_bytes -= diff;
2bf64758
JB
2958 spin_lock(&root->fs_info->free_chunk_lock);
2959 root->fs_info->free_chunk_space -= diff;
2960 spin_unlock(&root->fs_info->free_chunk_lock);
2961 }
7d9eb12c 2962 unlock_chunks(root);
8f18cf13 2963
ba1bf481 2964again:
8f18cf13
CM
2965 key.objectid = device->devid;
2966 key.offset = (u64)-1;
2967 key.type = BTRFS_DEV_EXTENT_KEY;
2968
2969 while (1) {
2970 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2971 if (ret < 0)
2972 goto done;
2973
2974 ret = btrfs_previous_item(root, path, 0, key.type);
2975 if (ret < 0)
2976 goto done;
2977 if (ret) {
2978 ret = 0;
b3b4aa74 2979 btrfs_release_path(path);
bf1fb512 2980 break;
8f18cf13
CM
2981 }
2982
2983 l = path->nodes[0];
2984 slot = path->slots[0];
2985 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
2986
ba1bf481 2987 if (key.objectid != device->devid) {
b3b4aa74 2988 btrfs_release_path(path);
bf1fb512 2989 break;
ba1bf481 2990 }
8f18cf13
CM
2991
2992 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
2993 length = btrfs_dev_extent_length(l, dev_extent);
2994
ba1bf481 2995 if (key.offset + length <= new_size) {
b3b4aa74 2996 btrfs_release_path(path);
d6397bae 2997 break;
ba1bf481 2998 }
8f18cf13
CM
2999
3000 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
3001 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
3002 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
b3b4aa74 3003 btrfs_release_path(path);
8f18cf13
CM
3004
3005 ret = btrfs_relocate_chunk(root, chunk_tree, chunk_objectid,
3006 chunk_offset);
ba1bf481 3007 if (ret && ret != -ENOSPC)
8f18cf13 3008 goto done;
ba1bf481
JB
3009 if (ret == -ENOSPC)
3010 failed++;
3011 key.offset -= 1;
3012 }
3013
3014 if (failed && !retried) {
3015 failed = 0;
3016 retried = true;
3017 goto again;
3018 } else if (failed && retried) {
3019 ret = -ENOSPC;
3020 lock_chunks(root);
3021
3022 device->total_bytes = old_size;
3023 if (device->writeable)
3024 device->fs_devices->total_rw_bytes += diff;
2bf64758
JB
3025 spin_lock(&root->fs_info->free_chunk_lock);
3026 root->fs_info->free_chunk_space += diff;
3027 spin_unlock(&root->fs_info->free_chunk_lock);
ba1bf481
JB
3028 unlock_chunks(root);
3029 goto done;
8f18cf13
CM
3030 }
3031
d6397bae 3032 /* Shrinking succeeded, else we would be at "done". */
a22285a6 3033 trans = btrfs_start_transaction(root, 0);
98d5dc13
TI
3034 if (IS_ERR(trans)) {
3035 ret = PTR_ERR(trans);
3036 goto done;
3037 }
3038
d6397bae
CB
3039 lock_chunks(root);
3040
3041 device->disk_total_bytes = new_size;
3042 /* Now btrfs_update_device() will change the on-disk size. */
3043 ret = btrfs_update_device(trans, device);
3044 if (ret) {
3045 unlock_chunks(root);
3046 btrfs_end_transaction(trans, root);
3047 goto done;
3048 }
3049 WARN_ON(diff > old_total);
3050 btrfs_set_super_total_bytes(super_copy, old_total - diff);
3051 unlock_chunks(root);
3052 btrfs_end_transaction(trans, root);
8f18cf13
CM
3053done:
3054 btrfs_free_path(path);
3055 return ret;
3056}
3057
125ccb0a 3058static int btrfs_add_system_chunk(struct btrfs_root *root,
0b86a832
CM
3059 struct btrfs_key *key,
3060 struct btrfs_chunk *chunk, int item_size)
3061{
6c41761f 3062 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
0b86a832
CM
3063 struct btrfs_disk_key disk_key;
3064 u32 array_size;
3065 u8 *ptr;
3066
3067 array_size = btrfs_super_sys_array_size(super_copy);
3068 if (array_size + item_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
3069 return -EFBIG;
3070
3071 ptr = super_copy->sys_chunk_array + array_size;
3072 btrfs_cpu_key_to_disk(&disk_key, key);
3073 memcpy(ptr, &disk_key, sizeof(disk_key));
3074 ptr += sizeof(disk_key);
3075 memcpy(ptr, chunk, item_size);
3076 item_size += sizeof(disk_key);
3077 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
3078 return 0;
3079}
3080
73c5de00
AJ
3081/*
3082 * sort the devices in descending order by max_avail, total_avail
3083 */
3084static int btrfs_cmp_device_info(const void *a, const void *b)
9b3f68b9 3085{
73c5de00
AJ
3086 const struct btrfs_device_info *di_a = a;
3087 const struct btrfs_device_info *di_b = b;
9b3f68b9 3088
73c5de00 3089 if (di_a->max_avail > di_b->max_avail)
b2117a39 3090 return -1;
73c5de00 3091 if (di_a->max_avail < di_b->max_avail)
b2117a39 3092 return 1;
73c5de00
AJ
3093 if (di_a->total_avail > di_b->total_avail)
3094 return -1;
3095 if (di_a->total_avail < di_b->total_avail)
3096 return 1;
3097 return 0;
b2117a39 3098}
0b86a832 3099
73c5de00
AJ
3100static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
3101 struct btrfs_root *extent_root,
3102 struct map_lookup **map_ret,
3103 u64 *num_bytes_out, u64 *stripe_size_out,
3104 u64 start, u64 type)
b2117a39 3105{
73c5de00
AJ
3106 struct btrfs_fs_info *info = extent_root->fs_info;
3107 struct btrfs_fs_devices *fs_devices = info->fs_devices;
3108 struct list_head *cur;
3109 struct map_lookup *map = NULL;
3110 struct extent_map_tree *em_tree;
3111 struct extent_map *em;
3112 struct btrfs_device_info *devices_info = NULL;
3113 u64 total_avail;
3114 int num_stripes; /* total number of stripes to allocate */
3115 int sub_stripes; /* sub_stripes info for map */
3116 int dev_stripes; /* stripes per dev */
3117 int devs_max; /* max devs to use */
3118 int devs_min; /* min devs needed */
3119 int devs_increment; /* ndevs has to be a multiple of this */
3120 int ncopies; /* how many copies to data has */
3121 int ret;
3122 u64 max_stripe_size;
3123 u64 max_chunk_size;
3124 u64 stripe_size;
3125 u64 num_bytes;
3126 int ndevs;
3127 int i;
3128 int j;
593060d7 3129
73c5de00
AJ
3130 if ((type & BTRFS_BLOCK_GROUP_RAID1) &&
3131 (type & BTRFS_BLOCK_GROUP_DUP)) {
3132 WARN_ON(1);
3133 type &= ~BTRFS_BLOCK_GROUP_DUP;
321aecc6 3134 }
9b3f68b9 3135
73c5de00
AJ
3136 if (list_empty(&fs_devices->alloc_list))
3137 return -ENOSPC;
b2117a39 3138
73c5de00
AJ
3139 sub_stripes = 1;
3140 dev_stripes = 1;
3141 devs_increment = 1;
3142 ncopies = 1;
3143 devs_max = 0; /* 0 == as many as possible */
3144 devs_min = 1;
3145
3146 /*
3147 * define the properties of each RAID type.
3148 * FIXME: move this to a global table and use it in all RAID
3149 * calculation code
3150 */
3151 if (type & (BTRFS_BLOCK_GROUP_DUP)) {
3152 dev_stripes = 2;
b2117a39 3153 ncopies = 2;
73c5de00
AJ
3154 devs_max = 1;
3155 } else if (type & (BTRFS_BLOCK_GROUP_RAID0)) {
3156 devs_min = 2;
3157 } else if (type & (BTRFS_BLOCK_GROUP_RAID1)) {
3158 devs_increment = 2;
b2117a39 3159 ncopies = 2;
73c5de00
AJ
3160 devs_max = 2;
3161 devs_min = 2;
3162 } else if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
3163 sub_stripes = 2;
3164 devs_increment = 2;
3165 ncopies = 2;
3166 devs_min = 4;
3167 } else {
3168 devs_max = 1;
3169 }
b2117a39 3170
9b3f68b9 3171 if (type & BTRFS_BLOCK_GROUP_DATA) {
73c5de00
AJ
3172 max_stripe_size = 1024 * 1024 * 1024;
3173 max_chunk_size = 10 * max_stripe_size;
9b3f68b9 3174 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
1100373f
CM
3175 /* for larger filesystems, use larger metadata chunks */
3176 if (fs_devices->total_rw_bytes > 50ULL * 1024 * 1024 * 1024)
3177 max_stripe_size = 1024 * 1024 * 1024;
3178 else
3179 max_stripe_size = 256 * 1024 * 1024;
73c5de00 3180 max_chunk_size = max_stripe_size;
a40a90a0 3181 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
96bdc7dc 3182 max_stripe_size = 32 * 1024 * 1024;
73c5de00
AJ
3183 max_chunk_size = 2 * max_stripe_size;
3184 } else {
3185 printk(KERN_ERR "btrfs: invalid chunk type 0x%llx requested\n",
3186 type);
3187 BUG_ON(1);
9b3f68b9
CM
3188 }
3189
2b82032c
YZ
3190 /* we don't want a chunk larger than 10% of writeable space */
3191 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
3192 max_chunk_size);
9b3f68b9 3193
73c5de00
AJ
3194 devices_info = kzalloc(sizeof(*devices_info) * fs_devices->rw_devices,
3195 GFP_NOFS);
3196 if (!devices_info)
3197 return -ENOMEM;
0cad8a11 3198
73c5de00 3199 cur = fs_devices->alloc_list.next;
9b3f68b9 3200
9f680ce0 3201 /*
73c5de00
AJ
3202 * in the first pass through the devices list, we gather information
3203 * about the available holes on each device.
9f680ce0 3204 */
73c5de00
AJ
3205 ndevs = 0;
3206 while (cur != &fs_devices->alloc_list) {
3207 struct btrfs_device *device;
3208 u64 max_avail;
3209 u64 dev_offset;
b2117a39 3210
73c5de00 3211 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
9f680ce0 3212
73c5de00 3213 cur = cur->next;
b2117a39 3214
73c5de00
AJ
3215 if (!device->writeable) {
3216 printk(KERN_ERR
3217 "btrfs: read-only device in alloc_list\n");
3218 WARN_ON(1);
3219 continue;
3220 }
b2117a39 3221
73c5de00
AJ
3222 if (!device->in_fs_metadata)
3223 continue;
b2117a39 3224
73c5de00
AJ
3225 if (device->total_bytes > device->bytes_used)
3226 total_avail = device->total_bytes - device->bytes_used;
3227 else
3228 total_avail = 0;
38c01b96 3229
3230 /* If there is no space on this device, skip it. */
3231 if (total_avail == 0)
3232 continue;
b2117a39 3233
125ccb0a 3234 ret = find_free_dev_extent(device,
73c5de00
AJ
3235 max_stripe_size * dev_stripes,
3236 &dev_offset, &max_avail);
3237 if (ret && ret != -ENOSPC)
3238 goto error;
b2117a39 3239
73c5de00
AJ
3240 if (ret == 0)
3241 max_avail = max_stripe_size * dev_stripes;
b2117a39 3242
73c5de00
AJ
3243 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
3244 continue;
b2117a39 3245
73c5de00
AJ
3246 devices_info[ndevs].dev_offset = dev_offset;
3247 devices_info[ndevs].max_avail = max_avail;
3248 devices_info[ndevs].total_avail = total_avail;
3249 devices_info[ndevs].dev = device;
3250 ++ndevs;
3251 }
b2117a39 3252
73c5de00
AJ
3253 /*
3254 * now sort the devices by hole size / available space
3255 */
3256 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
3257 btrfs_cmp_device_info, NULL);
b2117a39 3258
73c5de00
AJ
3259 /* round down to number of usable stripes */
3260 ndevs -= ndevs % devs_increment;
b2117a39 3261
73c5de00
AJ
3262 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
3263 ret = -ENOSPC;
3264 goto error;
b2117a39 3265 }
9f680ce0 3266
73c5de00
AJ
3267 if (devs_max && ndevs > devs_max)
3268 ndevs = devs_max;
3269 /*
3270 * the primary goal is to maximize the number of stripes, so use as many
3271 * devices as possible, even if the stripes are not maximum sized.
3272 */
3273 stripe_size = devices_info[ndevs-1].max_avail;
3274 num_stripes = ndevs * dev_stripes;
b2117a39 3275
73c5de00
AJ
3276 if (stripe_size * num_stripes > max_chunk_size * ncopies) {
3277 stripe_size = max_chunk_size * ncopies;
3278 do_div(stripe_size, num_stripes);
b2117a39 3279 }
b2117a39 3280
73c5de00
AJ
3281 do_div(stripe_size, dev_stripes);
3282 do_div(stripe_size, BTRFS_STRIPE_LEN);
3283 stripe_size *= BTRFS_STRIPE_LEN;
b2117a39
MX
3284
3285 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
3286 if (!map) {
3287 ret = -ENOMEM;
3288 goto error;
3289 }
3290 map->num_stripes = num_stripes;
9b3f68b9 3291
73c5de00
AJ
3292 for (i = 0; i < ndevs; ++i) {
3293 for (j = 0; j < dev_stripes; ++j) {
3294 int s = i * dev_stripes + j;
3295 map->stripes[s].dev = devices_info[i].dev;
3296 map->stripes[s].physical = devices_info[i].dev_offset +
3297 j * stripe_size;
6324fbf3 3298 }
6324fbf3 3299 }
2b82032c 3300 map->sector_size = extent_root->sectorsize;
b2117a39
MX
3301 map->stripe_len = BTRFS_STRIPE_LEN;
3302 map->io_align = BTRFS_STRIPE_LEN;
3303 map->io_width = BTRFS_STRIPE_LEN;
2b82032c 3304 map->type = type;
2b82032c 3305 map->sub_stripes = sub_stripes;
0b86a832 3306
2b82032c 3307 *map_ret = map;
73c5de00 3308 num_bytes = stripe_size * (num_stripes / ncopies);
0b86a832 3309
73c5de00
AJ
3310 *stripe_size_out = stripe_size;
3311 *num_bytes_out = num_bytes;
0b86a832 3312
73c5de00 3313 trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
1abe9b8a 3314
172ddd60 3315 em = alloc_extent_map();
2b82032c 3316 if (!em) {
b2117a39
MX
3317 ret = -ENOMEM;
3318 goto error;
593060d7 3319 }
2b82032c
YZ
3320 em->bdev = (struct block_device *)map;
3321 em->start = start;
73c5de00 3322 em->len = num_bytes;
2b82032c
YZ
3323 em->block_start = 0;
3324 em->block_len = em->len;
593060d7 3325
2b82032c 3326 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
890871be 3327 write_lock(&em_tree->lock);
2b82032c 3328 ret = add_extent_mapping(em_tree, em);
890871be 3329 write_unlock(&em_tree->lock);
2b82032c
YZ
3330 BUG_ON(ret);
3331 free_extent_map(em);
0b86a832 3332
2b82032c
YZ
3333 ret = btrfs_make_block_group(trans, extent_root, 0, type,
3334 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
73c5de00 3335 start, num_bytes);
2b82032c 3336 BUG_ON(ret);
611f0e00 3337
73c5de00
AJ
3338 for (i = 0; i < map->num_stripes; ++i) {
3339 struct btrfs_device *device;
3340 u64 dev_offset;
3341
3342 device = map->stripes[i].dev;
3343 dev_offset = map->stripes[i].physical;
0b86a832
CM
3344
3345 ret = btrfs_alloc_dev_extent(trans, device,
2b82032c
YZ
3346 info->chunk_root->root_key.objectid,
3347 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
73c5de00 3348 start, dev_offset, stripe_size);
0b86a832 3349 BUG_ON(ret);
2b82032c
YZ
3350 }
3351
b2117a39 3352 kfree(devices_info);
2b82032c 3353 return 0;
b2117a39
MX
3354
3355error:
3356 kfree(map);
3357 kfree(devices_info);
3358 return ret;
2b82032c
YZ
3359}
3360
3361static int __finish_chunk_alloc(struct btrfs_trans_handle *trans,
3362 struct btrfs_root *extent_root,
3363 struct map_lookup *map, u64 chunk_offset,
3364 u64 chunk_size, u64 stripe_size)
3365{
3366 u64 dev_offset;
3367 struct btrfs_key key;
3368 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
3369 struct btrfs_device *device;
3370 struct btrfs_chunk *chunk;
3371 struct btrfs_stripe *stripe;
3372 size_t item_size = btrfs_chunk_item_size(map->num_stripes);
3373 int index = 0;
3374 int ret;
3375
3376 chunk = kzalloc(item_size, GFP_NOFS);
3377 if (!chunk)
3378 return -ENOMEM;
3379
3380 index = 0;
3381 while (index < map->num_stripes) {
3382 device = map->stripes[index].dev;
3383 device->bytes_used += stripe_size;
0b86a832
CM
3384 ret = btrfs_update_device(trans, device);
3385 BUG_ON(ret);
2b82032c
YZ
3386 index++;
3387 }
3388
2bf64758
JB
3389 spin_lock(&extent_root->fs_info->free_chunk_lock);
3390 extent_root->fs_info->free_chunk_space -= (stripe_size *
3391 map->num_stripes);
3392 spin_unlock(&extent_root->fs_info->free_chunk_lock);
3393
2b82032c
YZ
3394 index = 0;
3395 stripe = &chunk->stripe;
3396 while (index < map->num_stripes) {
3397 device = map->stripes[index].dev;
3398 dev_offset = map->stripes[index].physical;
0b86a832 3399
e17cade2
CM
3400 btrfs_set_stack_stripe_devid(stripe, device->devid);
3401 btrfs_set_stack_stripe_offset(stripe, dev_offset);
3402 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
2b82032c 3403 stripe++;
0b86a832
CM
3404 index++;
3405 }
3406
2b82032c 3407 btrfs_set_stack_chunk_length(chunk, chunk_size);
0b86a832 3408 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
2b82032c
YZ
3409 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
3410 btrfs_set_stack_chunk_type(chunk, map->type);
3411 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
3412 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
3413 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
0b86a832 3414 btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
2b82032c 3415 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
0b86a832 3416
2b82032c
YZ
3417 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3418 key.type = BTRFS_CHUNK_ITEM_KEY;
3419 key.offset = chunk_offset;
0b86a832 3420
2b82032c 3421 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
0b86a832 3422
4ed1d16e
MF
3423 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3424 /*
3425 * TODO: Cleanup of inserted chunk root in case of
3426 * failure.
3427 */
125ccb0a 3428 ret = btrfs_add_system_chunk(chunk_root, &key, chunk,
2b82032c 3429 item_size);
8f18cf13 3430 }
1abe9b8a 3431
0b86a832 3432 kfree(chunk);
4ed1d16e 3433 return ret;
2b82032c 3434}
0b86a832 3435
2b82032c
YZ
3436/*
3437 * Chunk allocation falls into two parts. The first part does works
3438 * that make the new allocated chunk useable, but not do any operation
3439 * that modifies the chunk tree. The second part does the works that
3440 * require modifying the chunk tree. This division is important for the
3441 * bootstrap process of adding storage to a seed btrfs.
3442 */
3443int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
3444 struct btrfs_root *extent_root, u64 type)
3445{
3446 u64 chunk_offset;
3447 u64 chunk_size;
3448 u64 stripe_size;
3449 struct map_lookup *map;
3450 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
3451 int ret;
3452
3453 ret = find_next_chunk(chunk_root, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
3454 &chunk_offset);
3455 if (ret)
3456 return ret;
3457
3458 ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
3459 &stripe_size, chunk_offset, type);
3460 if (ret)
3461 return ret;
3462
3463 ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
3464 chunk_size, stripe_size);
3465 BUG_ON(ret);
3466 return 0;
3467}
3468
d397712b 3469static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
2b82032c
YZ
3470 struct btrfs_root *root,
3471 struct btrfs_device *device)
3472{
3473 u64 chunk_offset;
3474 u64 sys_chunk_offset;
3475 u64 chunk_size;
3476 u64 sys_chunk_size;
3477 u64 stripe_size;
3478 u64 sys_stripe_size;
3479 u64 alloc_profile;
3480 struct map_lookup *map;
3481 struct map_lookup *sys_map;
3482 struct btrfs_fs_info *fs_info = root->fs_info;
3483 struct btrfs_root *extent_root = fs_info->extent_root;
3484 int ret;
3485
3486 ret = find_next_chunk(fs_info->chunk_root,
3487 BTRFS_FIRST_CHUNK_TREE_OBJECTID, &chunk_offset);
92b8e897
MF
3488 if (ret)
3489 return ret;
2b82032c
YZ
3490
3491 alloc_profile = BTRFS_BLOCK_GROUP_METADATA |
6fef8df1 3492 fs_info->avail_metadata_alloc_bits;
2b82032c
YZ
3493 alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
3494
3495 ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
3496 &stripe_size, chunk_offset, alloc_profile);
3497 BUG_ON(ret);
3498
3499 sys_chunk_offset = chunk_offset + chunk_size;
3500
3501 alloc_profile = BTRFS_BLOCK_GROUP_SYSTEM |
6fef8df1 3502 fs_info->avail_system_alloc_bits;
2b82032c
YZ
3503 alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
3504
3505 ret = __btrfs_alloc_chunk(trans, extent_root, &sys_map,
3506 &sys_chunk_size, &sys_stripe_size,
3507 sys_chunk_offset, alloc_profile);
3508 BUG_ON(ret);
3509
3510 ret = btrfs_add_device(trans, fs_info->chunk_root, device);
3511 BUG_ON(ret);
3512
3513 /*
3514 * Modifying chunk tree needs allocating new blocks from both
3515 * system block group and metadata block group. So we only can
3516 * do operations require modifying the chunk tree after both
3517 * block groups were created.
3518 */
3519 ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
3520 chunk_size, stripe_size);
3521 BUG_ON(ret);
3522
3523 ret = __finish_chunk_alloc(trans, extent_root, sys_map,
3524 sys_chunk_offset, sys_chunk_size,
3525 sys_stripe_size);
b248a415 3526 BUG_ON(ret);
2b82032c
YZ
3527 return 0;
3528}
3529
3530int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
3531{
3532 struct extent_map *em;
3533 struct map_lookup *map;
3534 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
3535 int readonly = 0;
3536 int i;
3537
890871be 3538 read_lock(&map_tree->map_tree.lock);
2b82032c 3539 em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
890871be 3540 read_unlock(&map_tree->map_tree.lock);
2b82032c
YZ
3541 if (!em)
3542 return 1;
3543
f48b9075
JB
3544 if (btrfs_test_opt(root, DEGRADED)) {
3545 free_extent_map(em);
3546 return 0;
3547 }
3548
2b82032c
YZ
3549 map = (struct map_lookup *)em->bdev;
3550 for (i = 0; i < map->num_stripes; i++) {
3551 if (!map->stripes[i].dev->writeable) {
3552 readonly = 1;
3553 break;
3554 }
3555 }
0b86a832 3556 free_extent_map(em);
2b82032c 3557 return readonly;
0b86a832
CM
3558}
3559
3560void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
3561{
a8067e02 3562 extent_map_tree_init(&tree->map_tree);
0b86a832
CM
3563}
3564
3565void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
3566{
3567 struct extent_map *em;
3568
d397712b 3569 while (1) {
890871be 3570 write_lock(&tree->map_tree.lock);
0b86a832
CM
3571 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
3572 if (em)
3573 remove_extent_mapping(&tree->map_tree, em);
890871be 3574 write_unlock(&tree->map_tree.lock);
0b86a832
CM
3575 if (!em)
3576 break;
3577 kfree(em->bdev);
3578 /* once for us */
3579 free_extent_map(em);
3580 /* once for the tree */
3581 free_extent_map(em);
3582 }
3583}
3584
f188591e
CM
3585int btrfs_num_copies(struct btrfs_mapping_tree *map_tree, u64 logical, u64 len)
3586{
3587 struct extent_map *em;
3588 struct map_lookup *map;
3589 struct extent_map_tree *em_tree = &map_tree->map_tree;
3590 int ret;
3591
890871be 3592 read_lock(&em_tree->lock);
f188591e 3593 em = lookup_extent_mapping(em_tree, logical, len);
890871be 3594 read_unlock(&em_tree->lock);
f188591e
CM
3595 BUG_ON(!em);
3596
3597 BUG_ON(em->start > logical || em->start + em->len < logical);
3598 map = (struct map_lookup *)em->bdev;
3599 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
3600 ret = map->num_stripes;
321aecc6
CM
3601 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
3602 ret = map->sub_stripes;
f188591e
CM
3603 else
3604 ret = 1;
3605 free_extent_map(em);
f188591e
CM
3606 return ret;
3607}
3608
dfe25020
CM
3609static int find_live_mirror(struct map_lookup *map, int first, int num,
3610 int optimal)
3611{
3612 int i;
3613 if (map->stripes[optimal].dev->bdev)
3614 return optimal;
3615 for (i = first; i < first + num; i++) {
3616 if (map->stripes[i].dev->bdev)
3617 return i;
3618 }
3619 /* we couldn't find one that doesn't fail. Just return something
3620 * and the io error handling code will clean up eventually
3621 */
3622 return optimal;
3623}
3624
f2d8d74d
CM
3625static int __btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
3626 u64 logical, u64 *length,
a1d3c478 3627 struct btrfs_bio **bbio_ret,
7eaceacc 3628 int mirror_num)
0b86a832
CM
3629{
3630 struct extent_map *em;
3631 struct map_lookup *map;
3632 struct extent_map_tree *em_tree = &map_tree->map_tree;
3633 u64 offset;
593060d7 3634 u64 stripe_offset;
fce3bb9a 3635 u64 stripe_end_offset;
593060d7 3636 u64 stripe_nr;
fce3bb9a
LD
3637 u64 stripe_nr_orig;
3638 u64 stripe_nr_end;
593060d7 3639 int stripe_index;
cea9e445 3640 int i;
de11cc12 3641 int ret = 0;
f2d8d74d 3642 int num_stripes;
a236aed1 3643 int max_errors = 0;
a1d3c478 3644 struct btrfs_bio *bbio = NULL;
0b86a832 3645
890871be 3646 read_lock(&em_tree->lock);
0b86a832 3647 em = lookup_extent_mapping(em_tree, logical, *length);
890871be 3648 read_unlock(&em_tree->lock);
f2d8d74d 3649
3b951516 3650 if (!em) {
d397712b
CM
3651 printk(KERN_CRIT "unable to find logical %llu len %llu\n",
3652 (unsigned long long)logical,
3653 (unsigned long long)*length);
f2d8d74d 3654 BUG();
3b951516 3655 }
0b86a832
CM
3656
3657 BUG_ON(em->start > logical || em->start + em->len < logical);
3658 map = (struct map_lookup *)em->bdev;
3659 offset = logical - em->start;
593060d7 3660
f188591e
CM
3661 if (mirror_num > map->num_stripes)
3662 mirror_num = 0;
3663
593060d7
CM
3664 stripe_nr = offset;
3665 /*
3666 * stripe_nr counts the total number of stripes we have to stride
3667 * to get to this block
3668 */
3669 do_div(stripe_nr, map->stripe_len);
3670
3671 stripe_offset = stripe_nr * map->stripe_len;
3672 BUG_ON(offset < stripe_offset);
3673
3674 /* stripe_offset is the offset of this block in its stripe*/
3675 stripe_offset = offset - stripe_offset;
3676
fce3bb9a
LD
3677 if (rw & REQ_DISCARD)
3678 *length = min_t(u64, em->len - offset, *length);
52ba6929 3679 else if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
cea9e445
CM
3680 /* we limit the length of each bio to what fits in a stripe */
3681 *length = min_t(u64, em->len - offset,
fce3bb9a 3682 map->stripe_len - stripe_offset);
cea9e445
CM
3683 } else {
3684 *length = em->len - offset;
3685 }
f2d8d74d 3686
a1d3c478 3687 if (!bbio_ret)
cea9e445
CM
3688 goto out;
3689
f2d8d74d 3690 num_stripes = 1;
cea9e445 3691 stripe_index = 0;
fce3bb9a
LD
3692 stripe_nr_orig = stripe_nr;
3693 stripe_nr_end = (offset + *length + map->stripe_len - 1) &
3694 (~(map->stripe_len - 1));
3695 do_div(stripe_nr_end, map->stripe_len);
3696 stripe_end_offset = stripe_nr_end * map->stripe_len -
3697 (offset + *length);
3698 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
3699 if (rw & REQ_DISCARD)
3700 num_stripes = min_t(u64, map->num_stripes,
3701 stripe_nr_end - stripe_nr_orig);
3702 stripe_index = do_div(stripe_nr, map->num_stripes);
3703 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
212a17ab 3704 if (rw & (REQ_WRITE | REQ_DISCARD))
f2d8d74d 3705 num_stripes = map->num_stripes;
2fff734f 3706 else if (mirror_num)
f188591e 3707 stripe_index = mirror_num - 1;
dfe25020
CM
3708 else {
3709 stripe_index = find_live_mirror(map, 0,
3710 map->num_stripes,
3711 current->pid % map->num_stripes);
a1d3c478 3712 mirror_num = stripe_index + 1;
dfe25020 3713 }
2fff734f 3714
611f0e00 3715 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
a1d3c478 3716 if (rw & (REQ_WRITE | REQ_DISCARD)) {
f2d8d74d 3717 num_stripes = map->num_stripes;
a1d3c478 3718 } else if (mirror_num) {
f188591e 3719 stripe_index = mirror_num - 1;
a1d3c478
JS
3720 } else {
3721 mirror_num = 1;
3722 }
2fff734f 3723
321aecc6
CM
3724 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
3725 int factor = map->num_stripes / map->sub_stripes;
321aecc6
CM
3726
3727 stripe_index = do_div(stripe_nr, factor);
3728 stripe_index *= map->sub_stripes;
3729
7eaceacc 3730 if (rw & REQ_WRITE)
f2d8d74d 3731 num_stripes = map->sub_stripes;
fce3bb9a
LD
3732 else if (rw & REQ_DISCARD)
3733 num_stripes = min_t(u64, map->sub_stripes *
3734 (stripe_nr_end - stripe_nr_orig),
3735 map->num_stripes);
321aecc6
CM
3736 else if (mirror_num)
3737 stripe_index += mirror_num - 1;
dfe25020
CM
3738 else {
3739 stripe_index = find_live_mirror(map, stripe_index,
3740 map->sub_stripes, stripe_index +
3741 current->pid % map->sub_stripes);
a1d3c478 3742 mirror_num = stripe_index + 1;
dfe25020 3743 }
8790d502
CM
3744 } else {
3745 /*
3746 * after this do_div call, stripe_nr is the number of stripes
3747 * on this device we have to walk to find the data, and
3748 * stripe_index is the number of our device in the stripe array
3749 */
3750 stripe_index = do_div(stripe_nr, map->num_stripes);
a1d3c478 3751 mirror_num = stripe_index + 1;
8790d502 3752 }
593060d7 3753 BUG_ON(stripe_index >= map->num_stripes);
cea9e445 3754
de11cc12
LZ
3755 bbio = kzalloc(btrfs_bio_size(num_stripes), GFP_NOFS);
3756 if (!bbio) {
3757 ret = -ENOMEM;
3758 goto out;
3759 }
3760 atomic_set(&bbio->error, 0);
3761
fce3bb9a 3762 if (rw & REQ_DISCARD) {
ec9ef7a1
LZ
3763 int factor = 0;
3764 int sub_stripes = 0;
3765 u64 stripes_per_dev = 0;
3766 u32 remaining_stripes = 0;
3767
3768 if (map->type &
3769 (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
3770 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
3771 sub_stripes = 1;
3772 else
3773 sub_stripes = map->sub_stripes;
3774
3775 factor = map->num_stripes / sub_stripes;
3776 stripes_per_dev = div_u64_rem(stripe_nr_end -
3777 stripe_nr_orig,
3778 factor,
3779 &remaining_stripes);
3780 }
3781
fce3bb9a 3782 for (i = 0; i < num_stripes; i++) {
a1d3c478 3783 bbio->stripes[i].physical =
f2d8d74d
CM
3784 map->stripes[stripe_index].physical +
3785 stripe_offset + stripe_nr * map->stripe_len;
a1d3c478 3786 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
fce3bb9a 3787
ec9ef7a1
LZ
3788 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
3789 BTRFS_BLOCK_GROUP_RAID10)) {
3790 bbio->stripes[i].length = stripes_per_dev *
3791 map->stripe_len;
3792 if (i / sub_stripes < remaining_stripes)
3793 bbio->stripes[i].length +=
3794 map->stripe_len;
3795 if (i < sub_stripes)
a1d3c478 3796 bbio->stripes[i].length -=
fce3bb9a 3797 stripe_offset;
ec9ef7a1
LZ
3798 if ((i / sub_stripes + 1) %
3799 sub_stripes == remaining_stripes)
a1d3c478 3800 bbio->stripes[i].length -=
fce3bb9a 3801 stripe_end_offset;
ec9ef7a1
LZ
3802 if (i == sub_stripes - 1)
3803 stripe_offset = 0;
fce3bb9a 3804 } else
a1d3c478 3805 bbio->stripes[i].length = *length;
fce3bb9a
LD
3806
3807 stripe_index++;
3808 if (stripe_index == map->num_stripes) {
3809 /* This could only happen for RAID0/10 */
3810 stripe_index = 0;
3811 stripe_nr++;
3812 }
3813 }
3814 } else {
3815 for (i = 0; i < num_stripes; i++) {
a1d3c478 3816 bbio->stripes[i].physical =
212a17ab
LT
3817 map->stripes[stripe_index].physical +
3818 stripe_offset +
3819 stripe_nr * map->stripe_len;
a1d3c478 3820 bbio->stripes[i].dev =
212a17ab 3821 map->stripes[stripe_index].dev;
fce3bb9a 3822 stripe_index++;
f2d8d74d 3823 }
593060d7 3824 }
de11cc12
LZ
3825
3826 if (rw & REQ_WRITE) {
3827 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
3828 BTRFS_BLOCK_GROUP_RAID10 |
3829 BTRFS_BLOCK_GROUP_DUP)) {
3830 max_errors = 1;
3831 }
f2d8d74d 3832 }
de11cc12
LZ
3833
3834 *bbio_ret = bbio;
3835 bbio->num_stripes = num_stripes;
3836 bbio->max_errors = max_errors;
3837 bbio->mirror_num = mirror_num;
cea9e445 3838out:
0b86a832 3839 free_extent_map(em);
de11cc12 3840 return ret;
0b86a832
CM
3841}
3842
f2d8d74d
CM
3843int btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
3844 u64 logical, u64 *length,
a1d3c478 3845 struct btrfs_bio **bbio_ret, int mirror_num)
f2d8d74d 3846{
a1d3c478 3847 return __btrfs_map_block(map_tree, rw, logical, length, bbio_ret,
7eaceacc 3848 mirror_num);
f2d8d74d
CM
3849}
3850
a512bbf8
YZ
3851int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
3852 u64 chunk_start, u64 physical, u64 devid,
3853 u64 **logical, int *naddrs, int *stripe_len)
3854{
3855 struct extent_map_tree *em_tree = &map_tree->map_tree;
3856 struct extent_map *em;
3857 struct map_lookup *map;
3858 u64 *buf;
3859 u64 bytenr;
3860 u64 length;
3861 u64 stripe_nr;
3862 int i, j, nr = 0;
3863
890871be 3864 read_lock(&em_tree->lock);
a512bbf8 3865 em = lookup_extent_mapping(em_tree, chunk_start, 1);
890871be 3866 read_unlock(&em_tree->lock);
a512bbf8
YZ
3867
3868 BUG_ON(!em || em->start != chunk_start);
3869 map = (struct map_lookup *)em->bdev;
3870
3871 length = em->len;
3872 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
3873 do_div(length, map->num_stripes / map->sub_stripes);
3874 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
3875 do_div(length, map->num_stripes);
3876
3877 buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
3878 BUG_ON(!buf);
3879
3880 for (i = 0; i < map->num_stripes; i++) {
3881 if (devid && map->stripes[i].dev->devid != devid)
3882 continue;
3883 if (map->stripes[i].physical > physical ||
3884 map->stripes[i].physical + length <= physical)
3885 continue;
3886
3887 stripe_nr = physical - map->stripes[i].physical;
3888 do_div(stripe_nr, map->stripe_len);
3889
3890 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
3891 stripe_nr = stripe_nr * map->num_stripes + i;
3892 do_div(stripe_nr, map->sub_stripes);
3893 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
3894 stripe_nr = stripe_nr * map->num_stripes + i;
3895 }
3896 bytenr = chunk_start + stripe_nr * map->stripe_len;
934d375b 3897 WARN_ON(nr >= map->num_stripes);
a512bbf8
YZ
3898 for (j = 0; j < nr; j++) {
3899 if (buf[j] == bytenr)
3900 break;
3901 }
934d375b
CM
3902 if (j == nr) {
3903 WARN_ON(nr >= map->num_stripes);
a512bbf8 3904 buf[nr++] = bytenr;
934d375b 3905 }
a512bbf8
YZ
3906 }
3907
a512bbf8
YZ
3908 *logical = buf;
3909 *naddrs = nr;
3910 *stripe_len = map->stripe_len;
3911
3912 free_extent_map(em);
3913 return 0;
f2d8d74d
CM
3914}
3915
a1d3c478 3916static void btrfs_end_bio(struct bio *bio, int err)
8790d502 3917{
a1d3c478 3918 struct btrfs_bio *bbio = bio->bi_private;
7d2b4daa 3919 int is_orig_bio = 0;
8790d502 3920
8790d502 3921 if (err)
a1d3c478 3922 atomic_inc(&bbio->error);
8790d502 3923
a1d3c478 3924 if (bio == bbio->orig_bio)
7d2b4daa
CM
3925 is_orig_bio = 1;
3926
a1d3c478 3927 if (atomic_dec_and_test(&bbio->stripes_pending)) {
7d2b4daa
CM
3928 if (!is_orig_bio) {
3929 bio_put(bio);
a1d3c478 3930 bio = bbio->orig_bio;
7d2b4daa 3931 }
a1d3c478
JS
3932 bio->bi_private = bbio->private;
3933 bio->bi_end_io = bbio->end_io;
2774b2ca
JS
3934 bio->bi_bdev = (struct block_device *)
3935 (unsigned long)bbio->mirror_num;
a236aed1
CM
3936 /* only send an error to the higher layers if it is
3937 * beyond the tolerance of the multi-bio
3938 */
a1d3c478 3939 if (atomic_read(&bbio->error) > bbio->max_errors) {
a236aed1 3940 err = -EIO;
5dbc8fca 3941 } else {
1259ab75
CM
3942 /*
3943 * this bio is actually up to date, we didn't
3944 * go over the max number of errors
3945 */
3946 set_bit(BIO_UPTODATE, &bio->bi_flags);
a236aed1 3947 err = 0;
1259ab75 3948 }
a1d3c478 3949 kfree(bbio);
8790d502
CM
3950
3951 bio_endio(bio, err);
7d2b4daa 3952 } else if (!is_orig_bio) {
8790d502
CM
3953 bio_put(bio);
3954 }
8790d502
CM
3955}
3956
8b712842
CM
3957struct async_sched {
3958 struct bio *bio;
3959 int rw;
3960 struct btrfs_fs_info *info;
3961 struct btrfs_work work;
3962};
3963
3964/*
3965 * see run_scheduled_bios for a description of why bios are collected for
3966 * async submit.
3967 *
3968 * This will add one bio to the pending list for a device and make sure
3969 * the work struct is scheduled.
3970 */
143bede5 3971static noinline void schedule_bio(struct btrfs_root *root,
a1b32a59
CM
3972 struct btrfs_device *device,
3973 int rw, struct bio *bio)
8b712842
CM
3974{
3975 int should_queue = 1;
ffbd517d 3976 struct btrfs_pending_bios *pending_bios;
8b712842
CM
3977
3978 /* don't bother with additional async steps for reads, right now */
7b6d91da 3979 if (!(rw & REQ_WRITE)) {
492bb6de 3980 bio_get(bio);
21adbd5c 3981 btrfsic_submit_bio(rw, bio);
492bb6de 3982 bio_put(bio);
143bede5 3983 return;
8b712842
CM
3984 }
3985
3986 /*
0986fe9e 3987 * nr_async_bios allows us to reliably return congestion to the
8b712842
CM
3988 * higher layers. Otherwise, the async bio makes it appear we have
3989 * made progress against dirty pages when we've really just put it
3990 * on a queue for later
3991 */
0986fe9e 3992 atomic_inc(&root->fs_info->nr_async_bios);
492bb6de 3993 WARN_ON(bio->bi_next);
8b712842
CM
3994 bio->bi_next = NULL;
3995 bio->bi_rw |= rw;
3996
3997 spin_lock(&device->io_lock);
7b6d91da 3998 if (bio->bi_rw & REQ_SYNC)
ffbd517d
CM
3999 pending_bios = &device->pending_sync_bios;
4000 else
4001 pending_bios = &device->pending_bios;
8b712842 4002
ffbd517d
CM
4003 if (pending_bios->tail)
4004 pending_bios->tail->bi_next = bio;
8b712842 4005
ffbd517d
CM
4006 pending_bios->tail = bio;
4007 if (!pending_bios->head)
4008 pending_bios->head = bio;
8b712842
CM
4009 if (device->running_pending)
4010 should_queue = 0;
4011
4012 spin_unlock(&device->io_lock);
4013
4014 if (should_queue)
1cc127b5
CM
4015 btrfs_queue_worker(&root->fs_info->submit_workers,
4016 &device->work);
8b712842
CM
4017}
4018
f188591e 4019int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
8b712842 4020 int mirror_num, int async_submit)
0b86a832
CM
4021{
4022 struct btrfs_mapping_tree *map_tree;
4023 struct btrfs_device *dev;
8790d502 4024 struct bio *first_bio = bio;
a62b9401 4025 u64 logical = (u64)bio->bi_sector << 9;
0b86a832
CM
4026 u64 length = 0;
4027 u64 map_length;
0b86a832 4028 int ret;
8790d502
CM
4029 int dev_nr = 0;
4030 int total_devs = 1;
a1d3c478 4031 struct btrfs_bio *bbio = NULL;
0b86a832 4032
f2d8d74d 4033 length = bio->bi_size;
0b86a832
CM
4034 map_tree = &root->fs_info->mapping_tree;
4035 map_length = length;
cea9e445 4036
a1d3c478 4037 ret = btrfs_map_block(map_tree, rw, logical, &map_length, &bbio,
f188591e 4038 mirror_num);
cea9e445
CM
4039 BUG_ON(ret);
4040
a1d3c478 4041 total_devs = bbio->num_stripes;
cea9e445 4042 if (map_length < length) {
d397712b
CM
4043 printk(KERN_CRIT "mapping failed logical %llu bio len %llu "
4044 "len %llu\n", (unsigned long long)logical,
4045 (unsigned long long)length,
4046 (unsigned long long)map_length);
cea9e445
CM
4047 BUG();
4048 }
a1d3c478
JS
4049
4050 bbio->orig_bio = first_bio;
4051 bbio->private = first_bio->bi_private;
4052 bbio->end_io = first_bio->bi_end_io;
4053 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
cea9e445 4054
d397712b 4055 while (dev_nr < total_devs) {
a1d3c478
JS
4056 if (dev_nr < total_devs - 1) {
4057 bio = bio_clone(first_bio, GFP_NOFS);
4058 BUG_ON(!bio);
4059 } else {
4060 bio = first_bio;
8790d502 4061 }
a1d3c478
JS
4062 bio->bi_private = bbio;
4063 bio->bi_end_io = btrfs_end_bio;
4064 bio->bi_sector = bbio->stripes[dev_nr].physical >> 9;
4065 dev = bbio->stripes[dev_nr].dev;
18e503d6 4066 if (dev && dev->bdev && (rw != WRITE || dev->writeable)) {
a1d3c478
JS
4067 pr_debug("btrfs_map_bio: rw %d, secor=%llu, dev=%lu "
4068 "(%s id %llu), size=%u\n", rw,
4069 (u64)bio->bi_sector, (u_long)dev->bdev->bd_dev,
4070 dev->name, dev->devid, bio->bi_size);
dfe25020 4071 bio->bi_bdev = dev->bdev;
8b712842
CM
4072 if (async_submit)
4073 schedule_bio(root, dev, rw, bio);
4074 else
21adbd5c 4075 btrfsic_submit_bio(rw, bio);
dfe25020
CM
4076 } else {
4077 bio->bi_bdev = root->fs_info->fs_devices->latest_bdev;
4078 bio->bi_sector = logical >> 9;
dfe25020 4079 bio_endio(bio, -EIO);
dfe25020 4080 }
8790d502
CM
4081 dev_nr++;
4082 }
0b86a832
CM
4083 return 0;
4084}
4085
a443755f 4086struct btrfs_device *btrfs_find_device(struct btrfs_root *root, u64 devid,
2b82032c 4087 u8 *uuid, u8 *fsid)
0b86a832 4088{
2b82032c
YZ
4089 struct btrfs_device *device;
4090 struct btrfs_fs_devices *cur_devices;
4091
4092 cur_devices = root->fs_info->fs_devices;
4093 while (cur_devices) {
4094 if (!fsid ||
4095 !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
4096 device = __find_device(&cur_devices->devices,
4097 devid, uuid);
4098 if (device)
4099 return device;
4100 }
4101 cur_devices = cur_devices->seed;
4102 }
4103 return NULL;
0b86a832
CM
4104}
4105
dfe25020
CM
4106static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
4107 u64 devid, u8 *dev_uuid)
4108{
4109 struct btrfs_device *device;
4110 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
4111
4112 device = kzalloc(sizeof(*device), GFP_NOFS);
7cbd8a83 4113 if (!device)
4114 return NULL;
dfe25020
CM
4115 list_add(&device->dev_list,
4116 &fs_devices->devices);
dfe25020
CM
4117 device->dev_root = root->fs_info->dev_root;
4118 device->devid = devid;
8b712842 4119 device->work.func = pending_bios_fn;
e4404d6e 4120 device->fs_devices = fs_devices;
cd02dca5 4121 device->missing = 1;
dfe25020 4122 fs_devices->num_devices++;
cd02dca5 4123 fs_devices->missing_devices++;
dfe25020 4124 spin_lock_init(&device->io_lock);
d20f7043 4125 INIT_LIST_HEAD(&device->dev_alloc_list);
dfe25020
CM
4126 memcpy(device->uuid, dev_uuid, BTRFS_UUID_SIZE);
4127 return device;
4128}
4129
0b86a832
CM
4130static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
4131 struct extent_buffer *leaf,
4132 struct btrfs_chunk *chunk)
4133{
4134 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4135 struct map_lookup *map;
4136 struct extent_map *em;
4137 u64 logical;
4138 u64 length;
4139 u64 devid;
a443755f 4140 u8 uuid[BTRFS_UUID_SIZE];
593060d7 4141 int num_stripes;
0b86a832 4142 int ret;
593060d7 4143 int i;
0b86a832 4144
e17cade2
CM
4145 logical = key->offset;
4146 length = btrfs_chunk_length(leaf, chunk);
a061fc8d 4147
890871be 4148 read_lock(&map_tree->map_tree.lock);
0b86a832 4149 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
890871be 4150 read_unlock(&map_tree->map_tree.lock);
0b86a832
CM
4151
4152 /* already mapped? */
4153 if (em && em->start <= logical && em->start + em->len > logical) {
4154 free_extent_map(em);
0b86a832
CM
4155 return 0;
4156 } else if (em) {
4157 free_extent_map(em);
4158 }
0b86a832 4159
172ddd60 4160 em = alloc_extent_map();
0b86a832
CM
4161 if (!em)
4162 return -ENOMEM;
593060d7
CM
4163 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
4164 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
0b86a832
CM
4165 if (!map) {
4166 free_extent_map(em);
4167 return -ENOMEM;
4168 }
4169
4170 em->bdev = (struct block_device *)map;
4171 em->start = logical;
4172 em->len = length;
4173 em->block_start = 0;
c8b97818 4174 em->block_len = em->len;
0b86a832 4175
593060d7
CM
4176 map->num_stripes = num_stripes;
4177 map->io_width = btrfs_chunk_io_width(leaf, chunk);
4178 map->io_align = btrfs_chunk_io_align(leaf, chunk);
4179 map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
4180 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
4181 map->type = btrfs_chunk_type(leaf, chunk);
321aecc6 4182 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
593060d7
CM
4183 for (i = 0; i < num_stripes; i++) {
4184 map->stripes[i].physical =
4185 btrfs_stripe_offset_nr(leaf, chunk, i);
4186 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
a443755f
CM
4187 read_extent_buffer(leaf, uuid, (unsigned long)
4188 btrfs_stripe_dev_uuid_nr(chunk, i),
4189 BTRFS_UUID_SIZE);
2b82032c
YZ
4190 map->stripes[i].dev = btrfs_find_device(root, devid, uuid,
4191 NULL);
dfe25020 4192 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
593060d7
CM
4193 kfree(map);
4194 free_extent_map(em);
4195 return -EIO;
4196 }
dfe25020
CM
4197 if (!map->stripes[i].dev) {
4198 map->stripes[i].dev =
4199 add_missing_dev(root, devid, uuid);
4200 if (!map->stripes[i].dev) {
4201 kfree(map);
4202 free_extent_map(em);
4203 return -EIO;
4204 }
4205 }
4206 map->stripes[i].dev->in_fs_metadata = 1;
0b86a832
CM
4207 }
4208
890871be 4209 write_lock(&map_tree->map_tree.lock);
0b86a832 4210 ret = add_extent_mapping(&map_tree->map_tree, em);
890871be 4211 write_unlock(&map_tree->map_tree.lock);
b248a415 4212 BUG_ON(ret);
0b86a832
CM
4213 free_extent_map(em);
4214
4215 return 0;
4216}
4217
143bede5 4218static void fill_device_from_item(struct extent_buffer *leaf,
0b86a832
CM
4219 struct btrfs_dev_item *dev_item,
4220 struct btrfs_device *device)
4221{
4222 unsigned long ptr;
0b86a832
CM
4223
4224 device->devid = btrfs_device_id(leaf, dev_item);
d6397bae
CB
4225 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
4226 device->total_bytes = device->disk_total_bytes;
0b86a832
CM
4227 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
4228 device->type = btrfs_device_type(leaf, dev_item);
4229 device->io_align = btrfs_device_io_align(leaf, dev_item);
4230 device->io_width = btrfs_device_io_width(leaf, dev_item);
4231 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
0b86a832
CM
4232
4233 ptr = (unsigned long)btrfs_device_uuid(dev_item);
e17cade2 4234 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
0b86a832
CM
4235}
4236
2b82032c
YZ
4237static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
4238{
4239 struct btrfs_fs_devices *fs_devices;
4240 int ret;
4241
b367e47f 4242 BUG_ON(!mutex_is_locked(&uuid_mutex));
2b82032c
YZ
4243
4244 fs_devices = root->fs_info->fs_devices->seed;
4245 while (fs_devices) {
4246 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
4247 ret = 0;
4248 goto out;
4249 }
4250 fs_devices = fs_devices->seed;
4251 }
4252
4253 fs_devices = find_fsid(fsid);
4254 if (!fs_devices) {
4255 ret = -ENOENT;
4256 goto out;
4257 }
e4404d6e
YZ
4258
4259 fs_devices = clone_fs_devices(fs_devices);
4260 if (IS_ERR(fs_devices)) {
4261 ret = PTR_ERR(fs_devices);
2b82032c
YZ
4262 goto out;
4263 }
4264
97288f2c 4265 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
15916de8 4266 root->fs_info->bdev_holder);
2b82032c
YZ
4267 if (ret)
4268 goto out;
4269
4270 if (!fs_devices->seeding) {
4271 __btrfs_close_devices(fs_devices);
e4404d6e 4272 free_fs_devices(fs_devices);
2b82032c
YZ
4273 ret = -EINVAL;
4274 goto out;
4275 }
4276
4277 fs_devices->seed = root->fs_info->fs_devices->seed;
4278 root->fs_info->fs_devices->seed = fs_devices;
2b82032c 4279out:
2b82032c
YZ
4280 return ret;
4281}
4282
0d81ba5d 4283static int read_one_dev(struct btrfs_root *root,
0b86a832
CM
4284 struct extent_buffer *leaf,
4285 struct btrfs_dev_item *dev_item)
4286{
4287 struct btrfs_device *device;
4288 u64 devid;
4289 int ret;
2b82032c 4290 u8 fs_uuid[BTRFS_UUID_SIZE];
a443755f
CM
4291 u8 dev_uuid[BTRFS_UUID_SIZE];
4292
0b86a832 4293 devid = btrfs_device_id(leaf, dev_item);
a443755f
CM
4294 read_extent_buffer(leaf, dev_uuid,
4295 (unsigned long)btrfs_device_uuid(dev_item),
4296 BTRFS_UUID_SIZE);
2b82032c
YZ
4297 read_extent_buffer(leaf, fs_uuid,
4298 (unsigned long)btrfs_device_fsid(dev_item),
4299 BTRFS_UUID_SIZE);
4300
4301 if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
4302 ret = open_seed_devices(root, fs_uuid);
e4404d6e 4303 if (ret && !btrfs_test_opt(root, DEGRADED))
2b82032c 4304 return ret;
2b82032c
YZ
4305 }
4306
4307 device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
4308 if (!device || !device->bdev) {
e4404d6e 4309 if (!btrfs_test_opt(root, DEGRADED))
2b82032c
YZ
4310 return -EIO;
4311
4312 if (!device) {
d397712b
CM
4313 printk(KERN_WARNING "warning devid %llu missing\n",
4314 (unsigned long long)devid);
2b82032c
YZ
4315 device = add_missing_dev(root, devid, dev_uuid);
4316 if (!device)
4317 return -ENOMEM;
cd02dca5
CM
4318 } else if (!device->missing) {
4319 /*
4320 * this happens when a device that was properly setup
4321 * in the device info lists suddenly goes bad.
4322 * device->bdev is NULL, and so we have to set
4323 * device->missing to one here
4324 */
4325 root->fs_info->fs_devices->missing_devices++;
4326 device->missing = 1;
2b82032c
YZ
4327 }
4328 }
4329
4330 if (device->fs_devices != root->fs_info->fs_devices) {
4331 BUG_ON(device->writeable);
4332 if (device->generation !=
4333 btrfs_device_generation(leaf, dev_item))
4334 return -EINVAL;
6324fbf3 4335 }
0b86a832
CM
4336
4337 fill_device_from_item(leaf, dev_item, device);
4338 device->dev_root = root->fs_info->dev_root;
dfe25020 4339 device->in_fs_metadata = 1;
2bf64758 4340 if (device->writeable) {
2b82032c 4341 device->fs_devices->total_rw_bytes += device->total_bytes;
2bf64758
JB
4342 spin_lock(&root->fs_info->free_chunk_lock);
4343 root->fs_info->free_chunk_space += device->total_bytes -
4344 device->bytes_used;
4345 spin_unlock(&root->fs_info->free_chunk_lock);
4346 }
0b86a832 4347 ret = 0;
0b86a832
CM
4348 return ret;
4349}
4350
e4404d6e 4351int btrfs_read_sys_array(struct btrfs_root *root)
0b86a832 4352{
6c41761f 4353 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
a061fc8d 4354 struct extent_buffer *sb;
0b86a832 4355 struct btrfs_disk_key *disk_key;
0b86a832 4356 struct btrfs_chunk *chunk;
84eed90f
CM
4357 u8 *ptr;
4358 unsigned long sb_ptr;
4359 int ret = 0;
0b86a832
CM
4360 u32 num_stripes;
4361 u32 array_size;
4362 u32 len = 0;
0b86a832 4363 u32 cur;
84eed90f 4364 struct btrfs_key key;
0b86a832 4365
e4404d6e 4366 sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
a061fc8d
CM
4367 BTRFS_SUPER_INFO_SIZE);
4368 if (!sb)
4369 return -ENOMEM;
4370 btrfs_set_buffer_uptodate(sb);
85d4e461 4371 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
8a334426
DS
4372 /*
4373 * The sb extent buffer is artifical and just used to read the system array.
4374 * btrfs_set_buffer_uptodate() call does not properly mark all it's
4375 * pages up-to-date when the page is larger: extent does not cover the
4376 * whole page and consequently check_page_uptodate does not find all
4377 * the page's extents up-to-date (the hole beyond sb),
4378 * write_extent_buffer then triggers a WARN_ON.
4379 *
4380 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
4381 * but sb spans only this function. Add an explicit SetPageUptodate call
4382 * to silence the warning eg. on PowerPC 64.
4383 */
4384 if (PAGE_CACHE_SIZE > BTRFS_SUPER_INFO_SIZE)
4385 SetPageUptodate(sb->first_page);
4008c04a 4386
a061fc8d 4387 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
0b86a832
CM
4388 array_size = btrfs_super_sys_array_size(super_copy);
4389
0b86a832
CM
4390 ptr = super_copy->sys_chunk_array;
4391 sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
4392 cur = 0;
4393
4394 while (cur < array_size) {
4395 disk_key = (struct btrfs_disk_key *)ptr;
4396 btrfs_disk_key_to_cpu(&key, disk_key);
4397
a061fc8d 4398 len = sizeof(*disk_key); ptr += len;
0b86a832
CM
4399 sb_ptr += len;
4400 cur += len;
4401
0d81ba5d 4402 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
0b86a832 4403 chunk = (struct btrfs_chunk *)sb_ptr;
0d81ba5d 4404 ret = read_one_chunk(root, &key, sb, chunk);
84eed90f
CM
4405 if (ret)
4406 break;
0b86a832
CM
4407 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
4408 len = btrfs_chunk_item_size(num_stripes);
4409 } else {
84eed90f
CM
4410 ret = -EIO;
4411 break;
0b86a832
CM
4412 }
4413 ptr += len;
4414 sb_ptr += len;
4415 cur += len;
4416 }
a061fc8d 4417 free_extent_buffer(sb);
84eed90f 4418 return ret;
0b86a832
CM
4419}
4420
4421int btrfs_read_chunk_tree(struct btrfs_root *root)
4422{
4423 struct btrfs_path *path;
4424 struct extent_buffer *leaf;
4425 struct btrfs_key key;
4426 struct btrfs_key found_key;
4427 int ret;
4428 int slot;
4429
4430 root = root->fs_info->chunk_root;
4431
4432 path = btrfs_alloc_path();
4433 if (!path)
4434 return -ENOMEM;
4435
b367e47f
LZ
4436 mutex_lock(&uuid_mutex);
4437 lock_chunks(root);
4438
0b86a832
CM
4439 /* first we search for all of the device items, and then we
4440 * read in all of the chunk items. This way we can create chunk
4441 * mappings that reference all of the devices that are afound
4442 */
4443 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
4444 key.offset = 0;
4445 key.type = 0;
4446again:
4447 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
ab59381e
ZL
4448 if (ret < 0)
4449 goto error;
d397712b 4450 while (1) {
0b86a832
CM
4451 leaf = path->nodes[0];
4452 slot = path->slots[0];
4453 if (slot >= btrfs_header_nritems(leaf)) {
4454 ret = btrfs_next_leaf(root, path);
4455 if (ret == 0)
4456 continue;
4457 if (ret < 0)
4458 goto error;
4459 break;
4460 }
4461 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4462 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
4463 if (found_key.objectid != BTRFS_DEV_ITEMS_OBJECTID)
4464 break;
4465 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
4466 struct btrfs_dev_item *dev_item;
4467 dev_item = btrfs_item_ptr(leaf, slot,
4468 struct btrfs_dev_item);
0d81ba5d 4469 ret = read_one_dev(root, leaf, dev_item);
2b82032c
YZ
4470 if (ret)
4471 goto error;
0b86a832
CM
4472 }
4473 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
4474 struct btrfs_chunk *chunk;
4475 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4476 ret = read_one_chunk(root, &found_key, leaf, chunk);
2b82032c
YZ
4477 if (ret)
4478 goto error;
0b86a832
CM
4479 }
4480 path->slots[0]++;
4481 }
4482 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
4483 key.objectid = 0;
b3b4aa74 4484 btrfs_release_path(path);
0b86a832
CM
4485 goto again;
4486 }
0b86a832
CM
4487 ret = 0;
4488error:
b367e47f
LZ
4489 unlock_chunks(root);
4490 mutex_unlock(&uuid_mutex);
4491
2b82032c 4492 btrfs_free_path(path);
0b86a832
CM
4493 return ret;
4494}