btrfs: Don't BUG_ON kzalloc error in btrfs_lookup_csums_range()
[linux-block.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));
1078 BUG_ON(ret);
1079
1080 leaf = path->nodes[0];
1081 extent = btrfs_item_ptr(leaf, path->slots[0],
1082 struct btrfs_dev_extent);
e17cade2
CM
1083 btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1084 btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1085 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1086
1087 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1088 (unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
1089 BTRFS_UUID_SIZE);
1090
0b86a832
CM
1091 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1092 btrfs_mark_buffer_dirty(leaf);
0b86a832
CM
1093 btrfs_free_path(path);
1094 return ret;
1095}
1096
a1b32a59
CM
1097static noinline int find_next_chunk(struct btrfs_root *root,
1098 u64 objectid, u64 *offset)
0b86a832
CM
1099{
1100 struct btrfs_path *path;
1101 int ret;
1102 struct btrfs_key key;
e17cade2 1103 struct btrfs_chunk *chunk;
0b86a832
CM
1104 struct btrfs_key found_key;
1105
1106 path = btrfs_alloc_path();
92b8e897
MF
1107 if (!path)
1108 return -ENOMEM;
0b86a832 1109
e17cade2 1110 key.objectid = objectid;
0b86a832
CM
1111 key.offset = (u64)-1;
1112 key.type = BTRFS_CHUNK_ITEM_KEY;
1113
1114 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1115 if (ret < 0)
1116 goto error;
1117
1118 BUG_ON(ret == 0);
1119
1120 ret = btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY);
1121 if (ret) {
e17cade2 1122 *offset = 0;
0b86a832
CM
1123 } else {
1124 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1125 path->slots[0]);
e17cade2
CM
1126 if (found_key.objectid != objectid)
1127 *offset = 0;
1128 else {
1129 chunk = btrfs_item_ptr(path->nodes[0], path->slots[0],
1130 struct btrfs_chunk);
1131 *offset = found_key.offset +
1132 btrfs_chunk_length(path->nodes[0], chunk);
1133 }
0b86a832
CM
1134 }
1135 ret = 0;
1136error:
1137 btrfs_free_path(path);
1138 return ret;
1139}
1140
2b82032c 1141static noinline int find_next_devid(struct btrfs_root *root, u64 *objectid)
0b86a832
CM
1142{
1143 int ret;
1144 struct btrfs_key key;
1145 struct btrfs_key found_key;
2b82032c
YZ
1146 struct btrfs_path *path;
1147
1148 root = root->fs_info->chunk_root;
1149
1150 path = btrfs_alloc_path();
1151 if (!path)
1152 return -ENOMEM;
0b86a832
CM
1153
1154 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1155 key.type = BTRFS_DEV_ITEM_KEY;
1156 key.offset = (u64)-1;
1157
1158 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1159 if (ret < 0)
1160 goto error;
1161
1162 BUG_ON(ret == 0);
1163
1164 ret = btrfs_previous_item(root, path, BTRFS_DEV_ITEMS_OBJECTID,
1165 BTRFS_DEV_ITEM_KEY);
1166 if (ret) {
1167 *objectid = 1;
1168 } else {
1169 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1170 path->slots[0]);
1171 *objectid = found_key.offset + 1;
1172 }
1173 ret = 0;
1174error:
2b82032c 1175 btrfs_free_path(path);
0b86a832
CM
1176 return ret;
1177}
1178
1179/*
1180 * the device information is stored in the chunk root
1181 * the btrfs_device struct should be fully filled in
1182 */
1183int btrfs_add_device(struct btrfs_trans_handle *trans,
1184 struct btrfs_root *root,
1185 struct btrfs_device *device)
1186{
1187 int ret;
1188 struct btrfs_path *path;
1189 struct btrfs_dev_item *dev_item;
1190 struct extent_buffer *leaf;
1191 struct btrfs_key key;
1192 unsigned long ptr;
0b86a832
CM
1193
1194 root = root->fs_info->chunk_root;
1195
1196 path = btrfs_alloc_path();
1197 if (!path)
1198 return -ENOMEM;
1199
0b86a832
CM
1200 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1201 key.type = BTRFS_DEV_ITEM_KEY;
2b82032c 1202 key.offset = device->devid;
0b86a832
CM
1203
1204 ret = btrfs_insert_empty_item(trans, root, path, &key,
0d81ba5d 1205 sizeof(*dev_item));
0b86a832
CM
1206 if (ret)
1207 goto out;
1208
1209 leaf = path->nodes[0];
1210 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1211
1212 btrfs_set_device_id(leaf, dev_item, device->devid);
2b82032c 1213 btrfs_set_device_generation(leaf, dev_item, 0);
0b86a832
CM
1214 btrfs_set_device_type(leaf, dev_item, device->type);
1215 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1216 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1217 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
0b86a832
CM
1218 btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
1219 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
e17cade2
CM
1220 btrfs_set_device_group(leaf, dev_item, 0);
1221 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1222 btrfs_set_device_bandwidth(leaf, dev_item, 0);
c3027eb5 1223 btrfs_set_device_start_offset(leaf, dev_item, 0);
0b86a832 1224
0b86a832 1225 ptr = (unsigned long)btrfs_device_uuid(dev_item);
e17cade2 1226 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
2b82032c
YZ
1227 ptr = (unsigned long)btrfs_device_fsid(dev_item);
1228 write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
0b86a832 1229 btrfs_mark_buffer_dirty(leaf);
0b86a832 1230
2b82032c 1231 ret = 0;
0b86a832
CM
1232out:
1233 btrfs_free_path(path);
1234 return ret;
1235}
8f18cf13 1236
a061fc8d
CM
1237static int btrfs_rm_dev_item(struct btrfs_root *root,
1238 struct btrfs_device *device)
1239{
1240 int ret;
1241 struct btrfs_path *path;
a061fc8d 1242 struct btrfs_key key;
a061fc8d
CM
1243 struct btrfs_trans_handle *trans;
1244
1245 root = root->fs_info->chunk_root;
1246
1247 path = btrfs_alloc_path();
1248 if (!path)
1249 return -ENOMEM;
1250
a22285a6 1251 trans = btrfs_start_transaction(root, 0);
98d5dc13
TI
1252 if (IS_ERR(trans)) {
1253 btrfs_free_path(path);
1254 return PTR_ERR(trans);
1255 }
a061fc8d
CM
1256 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1257 key.type = BTRFS_DEV_ITEM_KEY;
1258 key.offset = device->devid;
7d9eb12c 1259 lock_chunks(root);
a061fc8d
CM
1260
1261 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1262 if (ret < 0)
1263 goto out;
1264
1265 if (ret > 0) {
1266 ret = -ENOENT;
1267 goto out;
1268 }
1269
1270 ret = btrfs_del_item(trans, root, path);
1271 if (ret)
1272 goto out;
a061fc8d
CM
1273out:
1274 btrfs_free_path(path);
7d9eb12c 1275 unlock_chunks(root);
a061fc8d
CM
1276 btrfs_commit_transaction(trans, root);
1277 return ret;
1278}
1279
1280int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1281{
1282 struct btrfs_device *device;
2b82032c 1283 struct btrfs_device *next_device;
a061fc8d 1284 struct block_device *bdev;
dfe25020 1285 struct buffer_head *bh = NULL;
a061fc8d 1286 struct btrfs_super_block *disk_super;
1f78160c 1287 struct btrfs_fs_devices *cur_devices;
a061fc8d
CM
1288 u64 all_avail;
1289 u64 devid;
2b82032c
YZ
1290 u64 num_devices;
1291 u8 *dev_uuid;
a061fc8d 1292 int ret = 0;
1f78160c 1293 bool clear_super = false;
a061fc8d 1294
a061fc8d
CM
1295 mutex_lock(&uuid_mutex);
1296
1297 all_avail = root->fs_info->avail_data_alloc_bits |
1298 root->fs_info->avail_system_alloc_bits |
1299 root->fs_info->avail_metadata_alloc_bits;
1300
1301 if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) &&
035fe03a 1302 root->fs_info->fs_devices->num_devices <= 4) {
d397712b
CM
1303 printk(KERN_ERR "btrfs: unable to go below four devices "
1304 "on raid10\n");
a061fc8d
CM
1305 ret = -EINVAL;
1306 goto out;
1307 }
1308
1309 if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) &&
035fe03a 1310 root->fs_info->fs_devices->num_devices <= 2) {
d397712b
CM
1311 printk(KERN_ERR "btrfs: unable to go below two "
1312 "devices on raid1\n");
a061fc8d
CM
1313 ret = -EINVAL;
1314 goto out;
1315 }
1316
dfe25020 1317 if (strcmp(device_path, "missing") == 0) {
dfe25020
CM
1318 struct list_head *devices;
1319 struct btrfs_device *tmp;
a061fc8d 1320
dfe25020
CM
1321 device = NULL;
1322 devices = &root->fs_info->fs_devices->devices;
46224705
XG
1323 /*
1324 * It is safe to read the devices since the volume_mutex
1325 * is held.
1326 */
c6e30871 1327 list_for_each_entry(tmp, devices, dev_list) {
dfe25020
CM
1328 if (tmp->in_fs_metadata && !tmp->bdev) {
1329 device = tmp;
1330 break;
1331 }
1332 }
1333 bdev = NULL;
1334 bh = NULL;
1335 disk_super = NULL;
1336 if (!device) {
d397712b
CM
1337 printk(KERN_ERR "btrfs: no missing devices found to "
1338 "remove\n");
dfe25020
CM
1339 goto out;
1340 }
dfe25020 1341 } else {
d4d77629
TH
1342 bdev = blkdev_get_by_path(device_path, FMODE_READ | FMODE_EXCL,
1343 root->fs_info->bdev_holder);
dfe25020
CM
1344 if (IS_ERR(bdev)) {
1345 ret = PTR_ERR(bdev);
1346 goto out;
1347 }
a061fc8d 1348
2b82032c 1349 set_blocksize(bdev, 4096);
a512bbf8 1350 bh = btrfs_read_dev_super(bdev);
dfe25020 1351 if (!bh) {
20b45077 1352 ret = -EINVAL;
dfe25020
CM
1353 goto error_close;
1354 }
1355 disk_super = (struct btrfs_super_block *)bh->b_data;
a343832f 1356 devid = btrfs_stack_device_id(&disk_super->dev_item);
2b82032c
YZ
1357 dev_uuid = disk_super->dev_item.uuid;
1358 device = btrfs_find_device(root, devid, dev_uuid,
1359 disk_super->fsid);
dfe25020
CM
1360 if (!device) {
1361 ret = -ENOENT;
1362 goto error_brelse;
1363 }
2b82032c 1364 }
dfe25020 1365
2b82032c 1366 if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
d397712b
CM
1367 printk(KERN_ERR "btrfs: unable to remove the only writeable "
1368 "device\n");
2b82032c
YZ
1369 ret = -EINVAL;
1370 goto error_brelse;
1371 }
1372
1373 if (device->writeable) {
0c1daee0 1374 lock_chunks(root);
2b82032c 1375 list_del_init(&device->dev_alloc_list);
0c1daee0 1376 unlock_chunks(root);
2b82032c 1377 root->fs_info->fs_devices->rw_devices--;
1f78160c 1378 clear_super = true;
dfe25020 1379 }
a061fc8d
CM
1380
1381 ret = btrfs_shrink_device(device, 0);
1382 if (ret)
9b3517e9 1383 goto error_undo;
a061fc8d 1384
a061fc8d
CM
1385 ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1386 if (ret)
9b3517e9 1387 goto error_undo;
a061fc8d 1388
2bf64758
JB
1389 spin_lock(&root->fs_info->free_chunk_lock);
1390 root->fs_info->free_chunk_space = device->total_bytes -
1391 device->bytes_used;
1392 spin_unlock(&root->fs_info->free_chunk_lock);
1393
2b82032c 1394 device->in_fs_metadata = 0;
a2de733c 1395 btrfs_scrub_cancel_dev(root, device);
e5e9a520
CM
1396
1397 /*
1398 * the device list mutex makes sure that we don't change
1399 * the device list while someone else is writing out all
1400 * the device supers.
1401 */
1f78160c
XG
1402
1403 cur_devices = device->fs_devices;
e5e9a520 1404 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1f78160c 1405 list_del_rcu(&device->dev_list);
e5e9a520 1406
e4404d6e 1407 device->fs_devices->num_devices--;
2b82032c 1408
cd02dca5
CM
1409 if (device->missing)
1410 root->fs_info->fs_devices->missing_devices--;
1411
2b82032c
YZ
1412 next_device = list_entry(root->fs_info->fs_devices->devices.next,
1413 struct btrfs_device, dev_list);
1414 if (device->bdev == root->fs_info->sb->s_bdev)
1415 root->fs_info->sb->s_bdev = next_device->bdev;
1416 if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1417 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1418
1f78160c 1419 if (device->bdev)
e4404d6e 1420 device->fs_devices->open_devices--;
1f78160c
XG
1421
1422 call_rcu(&device->rcu, free_device);
1423 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
e4404d6e 1424
6c41761f
DS
1425 num_devices = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
1426 btrfs_set_super_num_devices(root->fs_info->super_copy, num_devices);
2b82032c 1427
1f78160c 1428 if (cur_devices->open_devices == 0) {
e4404d6e
YZ
1429 struct btrfs_fs_devices *fs_devices;
1430 fs_devices = root->fs_info->fs_devices;
1431 while (fs_devices) {
1f78160c 1432 if (fs_devices->seed == cur_devices)
e4404d6e
YZ
1433 break;
1434 fs_devices = fs_devices->seed;
2b82032c 1435 }
1f78160c
XG
1436 fs_devices->seed = cur_devices->seed;
1437 cur_devices->seed = NULL;
0c1daee0 1438 lock_chunks(root);
1f78160c 1439 __btrfs_close_devices(cur_devices);
0c1daee0 1440 unlock_chunks(root);
1f78160c 1441 free_fs_devices(cur_devices);
2b82032c
YZ
1442 }
1443
1444 /*
1445 * at this point, the device is zero sized. We want to
1446 * remove it from the devices list and zero out the old super
1447 */
1f78160c 1448 if (clear_super) {
dfe25020
CM
1449 /* make sure this device isn't detected as part of
1450 * the FS anymore
1451 */
1452 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1453 set_buffer_dirty(bh);
1454 sync_dirty_buffer(bh);
dfe25020 1455 }
a061fc8d 1456
a061fc8d 1457 ret = 0;
a061fc8d
CM
1458
1459error_brelse:
1460 brelse(bh);
1461error_close:
dfe25020 1462 if (bdev)
e525fd89 1463 blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
a061fc8d
CM
1464out:
1465 mutex_unlock(&uuid_mutex);
a061fc8d 1466 return ret;
9b3517e9
ID
1467error_undo:
1468 if (device->writeable) {
0c1daee0 1469 lock_chunks(root);
9b3517e9
ID
1470 list_add(&device->dev_alloc_list,
1471 &root->fs_info->fs_devices->alloc_list);
0c1daee0 1472 unlock_chunks(root);
9b3517e9
ID
1473 root->fs_info->fs_devices->rw_devices++;
1474 }
1475 goto error_brelse;
a061fc8d
CM
1476}
1477
2b82032c
YZ
1478/*
1479 * does all the dirty work required for changing file system's UUID.
1480 */
125ccb0a 1481static int btrfs_prepare_sprout(struct btrfs_root *root)
2b82032c
YZ
1482{
1483 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
1484 struct btrfs_fs_devices *old_devices;
e4404d6e 1485 struct btrfs_fs_devices *seed_devices;
6c41761f 1486 struct btrfs_super_block *disk_super = root->fs_info->super_copy;
2b82032c
YZ
1487 struct btrfs_device *device;
1488 u64 super_flags;
1489
1490 BUG_ON(!mutex_is_locked(&uuid_mutex));
e4404d6e 1491 if (!fs_devices->seeding)
2b82032c
YZ
1492 return -EINVAL;
1493
e4404d6e
YZ
1494 seed_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
1495 if (!seed_devices)
2b82032c
YZ
1496 return -ENOMEM;
1497
e4404d6e
YZ
1498 old_devices = clone_fs_devices(fs_devices);
1499 if (IS_ERR(old_devices)) {
1500 kfree(seed_devices);
1501 return PTR_ERR(old_devices);
2b82032c 1502 }
e4404d6e 1503
2b82032c
YZ
1504 list_add(&old_devices->list, &fs_uuids);
1505
e4404d6e
YZ
1506 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
1507 seed_devices->opened = 1;
1508 INIT_LIST_HEAD(&seed_devices->devices);
1509 INIT_LIST_HEAD(&seed_devices->alloc_list);
e5e9a520 1510 mutex_init(&seed_devices->device_list_mutex);
c9513edb
XG
1511
1512 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1f78160c
XG
1513 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
1514 synchronize_rcu);
c9513edb
XG
1515 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1516
e4404d6e
YZ
1517 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
1518 list_for_each_entry(device, &seed_devices->devices, dev_list) {
1519 device->fs_devices = seed_devices;
1520 }
1521
2b82032c
YZ
1522 fs_devices->seeding = 0;
1523 fs_devices->num_devices = 0;
1524 fs_devices->open_devices = 0;
e4404d6e 1525 fs_devices->seed = seed_devices;
2b82032c
YZ
1526
1527 generate_random_uuid(fs_devices->fsid);
1528 memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1529 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1530 super_flags = btrfs_super_flags(disk_super) &
1531 ~BTRFS_SUPER_FLAG_SEEDING;
1532 btrfs_set_super_flags(disk_super, super_flags);
1533
1534 return 0;
1535}
1536
1537/*
1538 * strore the expected generation for seed devices in device items.
1539 */
1540static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
1541 struct btrfs_root *root)
1542{
1543 struct btrfs_path *path;
1544 struct extent_buffer *leaf;
1545 struct btrfs_dev_item *dev_item;
1546 struct btrfs_device *device;
1547 struct btrfs_key key;
1548 u8 fs_uuid[BTRFS_UUID_SIZE];
1549 u8 dev_uuid[BTRFS_UUID_SIZE];
1550 u64 devid;
1551 int ret;
1552
1553 path = btrfs_alloc_path();
1554 if (!path)
1555 return -ENOMEM;
1556
1557 root = root->fs_info->chunk_root;
1558 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1559 key.offset = 0;
1560 key.type = BTRFS_DEV_ITEM_KEY;
1561
1562 while (1) {
1563 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1564 if (ret < 0)
1565 goto error;
1566
1567 leaf = path->nodes[0];
1568next_slot:
1569 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1570 ret = btrfs_next_leaf(root, path);
1571 if (ret > 0)
1572 break;
1573 if (ret < 0)
1574 goto error;
1575 leaf = path->nodes[0];
1576 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
b3b4aa74 1577 btrfs_release_path(path);
2b82032c
YZ
1578 continue;
1579 }
1580
1581 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1582 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
1583 key.type != BTRFS_DEV_ITEM_KEY)
1584 break;
1585
1586 dev_item = btrfs_item_ptr(leaf, path->slots[0],
1587 struct btrfs_dev_item);
1588 devid = btrfs_device_id(leaf, dev_item);
1589 read_extent_buffer(leaf, dev_uuid,
1590 (unsigned long)btrfs_device_uuid(dev_item),
1591 BTRFS_UUID_SIZE);
1592 read_extent_buffer(leaf, fs_uuid,
1593 (unsigned long)btrfs_device_fsid(dev_item),
1594 BTRFS_UUID_SIZE);
1595 device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
1596 BUG_ON(!device);
1597
1598 if (device->fs_devices->seeding) {
1599 btrfs_set_device_generation(leaf, dev_item,
1600 device->generation);
1601 btrfs_mark_buffer_dirty(leaf);
1602 }
1603
1604 path->slots[0]++;
1605 goto next_slot;
1606 }
1607 ret = 0;
1608error:
1609 btrfs_free_path(path);
1610 return ret;
1611}
1612
788f20eb
CM
1613int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
1614{
d5e2003c 1615 struct request_queue *q;
788f20eb
CM
1616 struct btrfs_trans_handle *trans;
1617 struct btrfs_device *device;
1618 struct block_device *bdev;
788f20eb 1619 struct list_head *devices;
2b82032c 1620 struct super_block *sb = root->fs_info->sb;
788f20eb 1621 u64 total_bytes;
2b82032c 1622 int seeding_dev = 0;
788f20eb
CM
1623 int ret = 0;
1624
2b82032c
YZ
1625 if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
1626 return -EINVAL;
788f20eb 1627
a5d16333 1628 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
d4d77629 1629 root->fs_info->bdev_holder);
7f59203a
JB
1630 if (IS_ERR(bdev))
1631 return PTR_ERR(bdev);
a2135011 1632
2b82032c
YZ
1633 if (root->fs_info->fs_devices->seeding) {
1634 seeding_dev = 1;
1635 down_write(&sb->s_umount);
1636 mutex_lock(&uuid_mutex);
1637 }
1638
8c8bee1d 1639 filemap_write_and_wait(bdev->bd_inode->i_mapping);
a2135011 1640
788f20eb 1641 devices = &root->fs_info->fs_devices->devices;
e5e9a520
CM
1642 /*
1643 * we have the volume lock, so we don't need the extra
1644 * device list mutex while reading the list here.
1645 */
c6e30871 1646 list_for_each_entry(device, devices, dev_list) {
788f20eb
CM
1647 if (device->bdev == bdev) {
1648 ret = -EEXIST;
2b82032c 1649 goto error;
788f20eb
CM
1650 }
1651 }
1652
1653 device = kzalloc(sizeof(*device), GFP_NOFS);
1654 if (!device) {
1655 /* we can safely leave the fs_devices entry around */
1656 ret = -ENOMEM;
2b82032c 1657 goto error;
788f20eb
CM
1658 }
1659
788f20eb
CM
1660 device->name = kstrdup(device_path, GFP_NOFS);
1661 if (!device->name) {
1662 kfree(device);
2b82032c
YZ
1663 ret = -ENOMEM;
1664 goto error;
788f20eb 1665 }
2b82032c
YZ
1666
1667 ret = find_next_devid(root, &device->devid);
1668 if (ret) {
67100f25 1669 kfree(device->name);
2b82032c
YZ
1670 kfree(device);
1671 goto error;
1672 }
1673
a22285a6 1674 trans = btrfs_start_transaction(root, 0);
98d5dc13 1675 if (IS_ERR(trans)) {
67100f25 1676 kfree(device->name);
98d5dc13
TI
1677 kfree(device);
1678 ret = PTR_ERR(trans);
1679 goto error;
1680 }
1681
2b82032c
YZ
1682 lock_chunks(root);
1683
d5e2003c
JB
1684 q = bdev_get_queue(bdev);
1685 if (blk_queue_discard(q))
1686 device->can_discard = 1;
2b82032c
YZ
1687 device->writeable = 1;
1688 device->work.func = pending_bios_fn;
1689 generate_random_uuid(device->uuid);
1690 spin_lock_init(&device->io_lock);
1691 device->generation = trans->transid;
788f20eb
CM
1692 device->io_width = root->sectorsize;
1693 device->io_align = root->sectorsize;
1694 device->sector_size = root->sectorsize;
1695 device->total_bytes = i_size_read(bdev->bd_inode);
2cc3c559 1696 device->disk_total_bytes = device->total_bytes;
788f20eb
CM
1697 device->dev_root = root->fs_info->dev_root;
1698 device->bdev = bdev;
dfe25020 1699 device->in_fs_metadata = 1;
fb01aa85 1700 device->mode = FMODE_EXCL;
2b82032c 1701 set_blocksize(device->bdev, 4096);
788f20eb 1702
2b82032c
YZ
1703 if (seeding_dev) {
1704 sb->s_flags &= ~MS_RDONLY;
125ccb0a 1705 ret = btrfs_prepare_sprout(root);
2b82032c
YZ
1706 BUG_ON(ret);
1707 }
788f20eb 1708
2b82032c 1709 device->fs_devices = root->fs_info->fs_devices;
e5e9a520
CM
1710
1711 /*
1712 * we don't want write_supers to jump in here with our device
1713 * half setup
1714 */
1715 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1f78160c 1716 list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
2b82032c
YZ
1717 list_add(&device->dev_alloc_list,
1718 &root->fs_info->fs_devices->alloc_list);
1719 root->fs_info->fs_devices->num_devices++;
1720 root->fs_info->fs_devices->open_devices++;
1721 root->fs_info->fs_devices->rw_devices++;
d5e2003c
JB
1722 if (device->can_discard)
1723 root->fs_info->fs_devices->num_can_discard++;
2b82032c 1724 root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
325cd4ba 1725
2bf64758
JB
1726 spin_lock(&root->fs_info->free_chunk_lock);
1727 root->fs_info->free_chunk_space += device->total_bytes;
1728 spin_unlock(&root->fs_info->free_chunk_lock);
1729
c289811c
CM
1730 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
1731 root->fs_info->fs_devices->rotating = 1;
1732
6c41761f
DS
1733 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
1734 btrfs_set_super_total_bytes(root->fs_info->super_copy,
788f20eb
CM
1735 total_bytes + device->total_bytes);
1736
6c41761f
DS
1737 total_bytes = btrfs_super_num_devices(root->fs_info->super_copy);
1738 btrfs_set_super_num_devices(root->fs_info->super_copy,
788f20eb 1739 total_bytes + 1);
e5e9a520 1740 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
788f20eb 1741
2b82032c
YZ
1742 if (seeding_dev) {
1743 ret = init_first_rw_device(trans, root, device);
1744 BUG_ON(ret);
1745 ret = btrfs_finish_sprout(trans, root);
1746 BUG_ON(ret);
1747 } else {
1748 ret = btrfs_add_device(trans, root, device);
1749 }
1750
913d952e
CM
1751 /*
1752 * we've got more storage, clear any full flags on the space
1753 * infos
1754 */
1755 btrfs_clear_space_info_full(root->fs_info);
1756
7d9eb12c 1757 unlock_chunks(root);
2b82032c 1758 btrfs_commit_transaction(trans, root);
a2135011 1759
2b82032c
YZ
1760 if (seeding_dev) {
1761 mutex_unlock(&uuid_mutex);
1762 up_write(&sb->s_umount);
788f20eb 1763
2b82032c
YZ
1764 ret = btrfs_relocate_sys_chunks(root);
1765 BUG_ON(ret);
1766 }
c9e9f97b 1767
2b82032c
YZ
1768 return ret;
1769error:
e525fd89 1770 blkdev_put(bdev, FMODE_EXCL);
2b82032c
YZ
1771 if (seeding_dev) {
1772 mutex_unlock(&uuid_mutex);
1773 up_write(&sb->s_umount);
1774 }
c9e9f97b 1775 return ret;
788f20eb
CM
1776}
1777
d397712b
CM
1778static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
1779 struct btrfs_device *device)
0b86a832
CM
1780{
1781 int ret;
1782 struct btrfs_path *path;
1783 struct btrfs_root *root;
1784 struct btrfs_dev_item *dev_item;
1785 struct extent_buffer *leaf;
1786 struct btrfs_key key;
1787
1788 root = device->dev_root->fs_info->chunk_root;
1789
1790 path = btrfs_alloc_path();
1791 if (!path)
1792 return -ENOMEM;
1793
1794 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1795 key.type = BTRFS_DEV_ITEM_KEY;
1796 key.offset = device->devid;
1797
1798 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1799 if (ret < 0)
1800 goto out;
1801
1802 if (ret > 0) {
1803 ret = -ENOENT;
1804 goto out;
1805 }
1806
1807 leaf = path->nodes[0];
1808 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1809
1810 btrfs_set_device_id(leaf, dev_item, device->devid);
1811 btrfs_set_device_type(leaf, dev_item, device->type);
1812 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1813 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1814 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
d6397bae 1815 btrfs_set_device_total_bytes(leaf, dev_item, device->disk_total_bytes);
0b86a832
CM
1816 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1817 btrfs_mark_buffer_dirty(leaf);
1818
1819out:
1820 btrfs_free_path(path);
1821 return ret;
1822}
1823
7d9eb12c 1824static int __btrfs_grow_device(struct btrfs_trans_handle *trans,
8f18cf13
CM
1825 struct btrfs_device *device, u64 new_size)
1826{
1827 struct btrfs_super_block *super_copy =
6c41761f 1828 device->dev_root->fs_info->super_copy;
8f18cf13
CM
1829 u64 old_total = btrfs_super_total_bytes(super_copy);
1830 u64 diff = new_size - device->total_bytes;
1831
2b82032c
YZ
1832 if (!device->writeable)
1833 return -EACCES;
1834 if (new_size <= device->total_bytes)
1835 return -EINVAL;
1836
8f18cf13 1837 btrfs_set_super_total_bytes(super_copy, old_total + diff);
2b82032c
YZ
1838 device->fs_devices->total_rw_bytes += diff;
1839
1840 device->total_bytes = new_size;
9779b72f 1841 device->disk_total_bytes = new_size;
4184ea7f
CM
1842 btrfs_clear_space_info_full(device->dev_root->fs_info);
1843
8f18cf13
CM
1844 return btrfs_update_device(trans, device);
1845}
1846
7d9eb12c
CM
1847int btrfs_grow_device(struct btrfs_trans_handle *trans,
1848 struct btrfs_device *device, u64 new_size)
1849{
1850 int ret;
1851 lock_chunks(device->dev_root);
1852 ret = __btrfs_grow_device(trans, device, new_size);
1853 unlock_chunks(device->dev_root);
1854 return ret;
1855}
1856
8f18cf13
CM
1857static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
1858 struct btrfs_root *root,
1859 u64 chunk_tree, u64 chunk_objectid,
1860 u64 chunk_offset)
1861{
1862 int ret;
1863 struct btrfs_path *path;
1864 struct btrfs_key key;
1865
1866 root = root->fs_info->chunk_root;
1867 path = btrfs_alloc_path();
1868 if (!path)
1869 return -ENOMEM;
1870
1871 key.objectid = chunk_objectid;
1872 key.offset = chunk_offset;
1873 key.type = BTRFS_CHUNK_ITEM_KEY;
1874
1875 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1876 BUG_ON(ret);
1877
1878 ret = btrfs_del_item(trans, root, path);
8f18cf13
CM
1879
1880 btrfs_free_path(path);
65a246c5 1881 return ret;
8f18cf13
CM
1882}
1883
b2950863 1884static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
8f18cf13
CM
1885 chunk_offset)
1886{
6c41761f 1887 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
8f18cf13
CM
1888 struct btrfs_disk_key *disk_key;
1889 struct btrfs_chunk *chunk;
1890 u8 *ptr;
1891 int ret = 0;
1892 u32 num_stripes;
1893 u32 array_size;
1894 u32 len = 0;
1895 u32 cur;
1896 struct btrfs_key key;
1897
1898 array_size = btrfs_super_sys_array_size(super_copy);
1899
1900 ptr = super_copy->sys_chunk_array;
1901 cur = 0;
1902
1903 while (cur < array_size) {
1904 disk_key = (struct btrfs_disk_key *)ptr;
1905 btrfs_disk_key_to_cpu(&key, disk_key);
1906
1907 len = sizeof(*disk_key);
1908
1909 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1910 chunk = (struct btrfs_chunk *)(ptr + len);
1911 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
1912 len += btrfs_chunk_item_size(num_stripes);
1913 } else {
1914 ret = -EIO;
1915 break;
1916 }
1917 if (key.objectid == chunk_objectid &&
1918 key.offset == chunk_offset) {
1919 memmove(ptr, ptr + len, array_size - (cur + len));
1920 array_size -= len;
1921 btrfs_set_super_sys_array_size(super_copy, array_size);
1922 } else {
1923 ptr += len;
1924 cur += len;
1925 }
1926 }
1927 return ret;
1928}
1929
b2950863 1930static int btrfs_relocate_chunk(struct btrfs_root *root,
8f18cf13
CM
1931 u64 chunk_tree, u64 chunk_objectid,
1932 u64 chunk_offset)
1933{
1934 struct extent_map_tree *em_tree;
1935 struct btrfs_root *extent_root;
1936 struct btrfs_trans_handle *trans;
1937 struct extent_map *em;
1938 struct map_lookup *map;
1939 int ret;
1940 int i;
1941
1942 root = root->fs_info->chunk_root;
1943 extent_root = root->fs_info->extent_root;
1944 em_tree = &root->fs_info->mapping_tree.map_tree;
1945
ba1bf481
JB
1946 ret = btrfs_can_relocate(extent_root, chunk_offset);
1947 if (ret)
1948 return -ENOSPC;
1949
8f18cf13 1950 /* step one, relocate all the extents inside this chunk */
1a40e23b 1951 ret = btrfs_relocate_block_group(extent_root, chunk_offset);
a22285a6
YZ
1952 if (ret)
1953 return ret;
8f18cf13 1954
a22285a6 1955 trans = btrfs_start_transaction(root, 0);
98d5dc13 1956 BUG_ON(IS_ERR(trans));
8f18cf13 1957
7d9eb12c
CM
1958 lock_chunks(root);
1959
8f18cf13
CM
1960 /*
1961 * step two, delete the device extents and the
1962 * chunk tree entries
1963 */
890871be 1964 read_lock(&em_tree->lock);
8f18cf13 1965 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
890871be 1966 read_unlock(&em_tree->lock);
8f18cf13 1967
285190d9 1968 BUG_ON(!em || em->start > chunk_offset ||
a061fc8d 1969 em->start + em->len < chunk_offset);
8f18cf13
CM
1970 map = (struct map_lookup *)em->bdev;
1971
1972 for (i = 0; i < map->num_stripes; i++) {
1973 ret = btrfs_free_dev_extent(trans, map->stripes[i].dev,
1974 map->stripes[i].physical);
1975 BUG_ON(ret);
a061fc8d 1976
dfe25020
CM
1977 if (map->stripes[i].dev) {
1978 ret = btrfs_update_device(trans, map->stripes[i].dev);
1979 BUG_ON(ret);
1980 }
8f18cf13
CM
1981 }
1982 ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
1983 chunk_offset);
1984
1985 BUG_ON(ret);
1986
1abe9b8a 1987 trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
1988
8f18cf13
CM
1989 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
1990 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
1991 BUG_ON(ret);
8f18cf13
CM
1992 }
1993
2b82032c
YZ
1994 ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
1995 BUG_ON(ret);
1996
890871be 1997 write_lock(&em_tree->lock);
2b82032c 1998 remove_extent_mapping(em_tree, em);
890871be 1999 write_unlock(&em_tree->lock);
2b82032c
YZ
2000
2001 kfree(map);
2002 em->bdev = NULL;
2003
2004 /* once for the tree */
2005 free_extent_map(em);
2006 /* once for us */
2007 free_extent_map(em);
2008
2009 unlock_chunks(root);
2010 btrfs_end_transaction(trans, root);
2011 return 0;
2012}
2013
2014static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
2015{
2016 struct btrfs_root *chunk_root = root->fs_info->chunk_root;
2017 struct btrfs_path *path;
2018 struct extent_buffer *leaf;
2019 struct btrfs_chunk *chunk;
2020 struct btrfs_key key;
2021 struct btrfs_key found_key;
2022 u64 chunk_tree = chunk_root->root_key.objectid;
2023 u64 chunk_type;
ba1bf481
JB
2024 bool retried = false;
2025 int failed = 0;
2b82032c
YZ
2026 int ret;
2027
2028 path = btrfs_alloc_path();
2029 if (!path)
2030 return -ENOMEM;
2031
ba1bf481 2032again:
2b82032c
YZ
2033 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2034 key.offset = (u64)-1;
2035 key.type = BTRFS_CHUNK_ITEM_KEY;
2036
2037 while (1) {
2038 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2039 if (ret < 0)
2040 goto error;
2041 BUG_ON(ret == 0);
2042
2043 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2044 key.type);
2045 if (ret < 0)
2046 goto error;
2047 if (ret > 0)
2048 break;
1a40e23b 2049
2b82032c
YZ
2050 leaf = path->nodes[0];
2051 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1a40e23b 2052
2b82032c
YZ
2053 chunk = btrfs_item_ptr(leaf, path->slots[0],
2054 struct btrfs_chunk);
2055 chunk_type = btrfs_chunk_type(leaf, chunk);
b3b4aa74 2056 btrfs_release_path(path);
8f18cf13 2057
2b82032c
YZ
2058 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2059 ret = btrfs_relocate_chunk(chunk_root, chunk_tree,
2060 found_key.objectid,
2061 found_key.offset);
ba1bf481
JB
2062 if (ret == -ENOSPC)
2063 failed++;
2064 else if (ret)
2065 BUG();
2b82032c 2066 }
8f18cf13 2067
2b82032c
YZ
2068 if (found_key.offset == 0)
2069 break;
2070 key.offset = found_key.offset - 1;
2071 }
2072 ret = 0;
ba1bf481
JB
2073 if (failed && !retried) {
2074 failed = 0;
2075 retried = true;
2076 goto again;
2077 } else if (failed && retried) {
2078 WARN_ON(1);
2079 ret = -ENOSPC;
2080 }
2b82032c
YZ
2081error:
2082 btrfs_free_path(path);
2083 return ret;
8f18cf13
CM
2084}
2085
0940ebf6
ID
2086static int insert_balance_item(struct btrfs_root *root,
2087 struct btrfs_balance_control *bctl)
2088{
2089 struct btrfs_trans_handle *trans;
2090 struct btrfs_balance_item *item;
2091 struct btrfs_disk_balance_args disk_bargs;
2092 struct btrfs_path *path;
2093 struct extent_buffer *leaf;
2094 struct btrfs_key key;
2095 int ret, err;
2096
2097 path = btrfs_alloc_path();
2098 if (!path)
2099 return -ENOMEM;
2100
2101 trans = btrfs_start_transaction(root, 0);
2102 if (IS_ERR(trans)) {
2103 btrfs_free_path(path);
2104 return PTR_ERR(trans);
2105 }
2106
2107 key.objectid = BTRFS_BALANCE_OBJECTID;
2108 key.type = BTRFS_BALANCE_ITEM_KEY;
2109 key.offset = 0;
2110
2111 ret = btrfs_insert_empty_item(trans, root, path, &key,
2112 sizeof(*item));
2113 if (ret)
2114 goto out;
2115
2116 leaf = path->nodes[0];
2117 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2118
2119 memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
2120
2121 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
2122 btrfs_set_balance_data(leaf, item, &disk_bargs);
2123 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
2124 btrfs_set_balance_meta(leaf, item, &disk_bargs);
2125 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
2126 btrfs_set_balance_sys(leaf, item, &disk_bargs);
2127
2128 btrfs_set_balance_flags(leaf, item, bctl->flags);
2129
2130 btrfs_mark_buffer_dirty(leaf);
2131out:
2132 btrfs_free_path(path);
2133 err = btrfs_commit_transaction(trans, root);
2134 if (err && !ret)
2135 ret = err;
2136 return ret;
2137}
2138
2139static int del_balance_item(struct btrfs_root *root)
2140{
2141 struct btrfs_trans_handle *trans;
2142 struct btrfs_path *path;
2143 struct btrfs_key key;
2144 int ret, err;
2145
2146 path = btrfs_alloc_path();
2147 if (!path)
2148 return -ENOMEM;
2149
2150 trans = btrfs_start_transaction(root, 0);
2151 if (IS_ERR(trans)) {
2152 btrfs_free_path(path);
2153 return PTR_ERR(trans);
2154 }
2155
2156 key.objectid = BTRFS_BALANCE_OBJECTID;
2157 key.type = BTRFS_BALANCE_ITEM_KEY;
2158 key.offset = 0;
2159
2160 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2161 if (ret < 0)
2162 goto out;
2163 if (ret > 0) {
2164 ret = -ENOENT;
2165 goto out;
2166 }
2167
2168 ret = btrfs_del_item(trans, root, path);
2169out:
2170 btrfs_free_path(path);
2171 err = btrfs_commit_transaction(trans, root);
2172 if (err && !ret)
2173 ret = err;
2174 return ret;
2175}
2176
59641015
ID
2177/*
2178 * This is a heuristic used to reduce the number of chunks balanced on
2179 * resume after balance was interrupted.
2180 */
2181static void update_balance_args(struct btrfs_balance_control *bctl)
2182{
2183 /*
2184 * Turn on soft mode for chunk types that were being converted.
2185 */
2186 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
2187 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
2188 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
2189 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
2190 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
2191 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
2192
2193 /*
2194 * Turn on usage filter if is not already used. The idea is
2195 * that chunks that we have already balanced should be
2196 * reasonably full. Don't do it for chunks that are being
2197 * converted - that will keep us from relocating unconverted
2198 * (albeit full) chunks.
2199 */
2200 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2201 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2202 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
2203 bctl->data.usage = 90;
2204 }
2205 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2206 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2207 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
2208 bctl->sys.usage = 90;
2209 }
2210 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2211 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2212 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
2213 bctl->meta.usage = 90;
2214 }
2215}
2216
c9e9f97b
ID
2217/*
2218 * Should be called with both balance and volume mutexes held to
2219 * serialize other volume operations (add_dev/rm_dev/resize) with
2220 * restriper. Same goes for unset_balance_control.
2221 */
2222static void set_balance_control(struct btrfs_balance_control *bctl)
2223{
2224 struct btrfs_fs_info *fs_info = bctl->fs_info;
2225
2226 BUG_ON(fs_info->balance_ctl);
2227
2228 spin_lock(&fs_info->balance_lock);
2229 fs_info->balance_ctl = bctl;
2230 spin_unlock(&fs_info->balance_lock);
2231}
2232
2233static void unset_balance_control(struct btrfs_fs_info *fs_info)
2234{
2235 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
2236
2237 BUG_ON(!fs_info->balance_ctl);
2238
2239 spin_lock(&fs_info->balance_lock);
2240 fs_info->balance_ctl = NULL;
2241 spin_unlock(&fs_info->balance_lock);
2242
2243 kfree(bctl);
2244}
2245
ed25e9b2
ID
2246/*
2247 * Balance filters. Return 1 if chunk should be filtered out
2248 * (should not be balanced).
2249 */
2250static int chunk_profiles_filter(u64 chunk_profile,
2251 struct btrfs_balance_args *bargs)
2252{
2253 chunk_profile &= BTRFS_BLOCK_GROUP_PROFILE_MASK;
2254
2255 if (chunk_profile == 0)
2256 chunk_profile = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
2257
2258 if (bargs->profiles & chunk_profile)
2259 return 0;
2260
2261 return 1;
2262}
2263
5ce5b3c0
ID
2264static u64 div_factor_fine(u64 num, int factor)
2265{
2266 if (factor <= 0)
2267 return 0;
2268 if (factor >= 100)
2269 return num;
2270
2271 num *= factor;
2272 do_div(num, 100);
2273 return num;
2274}
2275
2276static int chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
2277 struct btrfs_balance_args *bargs)
2278{
2279 struct btrfs_block_group_cache *cache;
2280 u64 chunk_used, user_thresh;
2281 int ret = 1;
2282
2283 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2284 chunk_used = btrfs_block_group_used(&cache->item);
2285
2286 user_thresh = div_factor_fine(cache->key.offset, bargs->usage);
2287 if (chunk_used < user_thresh)
2288 ret = 0;
2289
2290 btrfs_put_block_group(cache);
2291 return ret;
2292}
2293
409d404b
ID
2294static int chunk_devid_filter(struct extent_buffer *leaf,
2295 struct btrfs_chunk *chunk,
2296 struct btrfs_balance_args *bargs)
2297{
2298 struct btrfs_stripe *stripe;
2299 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2300 int i;
2301
2302 for (i = 0; i < num_stripes; i++) {
2303 stripe = btrfs_stripe_nr(chunk, i);
2304 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
2305 return 0;
2306 }
2307
2308 return 1;
2309}
2310
94e60d5a
ID
2311/* [pstart, pend) */
2312static int chunk_drange_filter(struct extent_buffer *leaf,
2313 struct btrfs_chunk *chunk,
2314 u64 chunk_offset,
2315 struct btrfs_balance_args *bargs)
2316{
2317 struct btrfs_stripe *stripe;
2318 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2319 u64 stripe_offset;
2320 u64 stripe_length;
2321 int factor;
2322 int i;
2323
2324 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
2325 return 0;
2326
2327 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
2328 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10))
2329 factor = 2;
2330 else
2331 factor = 1;
2332 factor = num_stripes / factor;
2333
2334 for (i = 0; i < num_stripes; i++) {
2335 stripe = btrfs_stripe_nr(chunk, i);
2336 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
2337 continue;
2338
2339 stripe_offset = btrfs_stripe_offset(leaf, stripe);
2340 stripe_length = btrfs_chunk_length(leaf, chunk);
2341 do_div(stripe_length, factor);
2342
2343 if (stripe_offset < bargs->pend &&
2344 stripe_offset + stripe_length > bargs->pstart)
2345 return 0;
2346 }
2347
2348 return 1;
2349}
2350
ea67176a
ID
2351/* [vstart, vend) */
2352static int chunk_vrange_filter(struct extent_buffer *leaf,
2353 struct btrfs_chunk *chunk,
2354 u64 chunk_offset,
2355 struct btrfs_balance_args *bargs)
2356{
2357 if (chunk_offset < bargs->vend &&
2358 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
2359 /* at least part of the chunk is inside this vrange */
2360 return 0;
2361
2362 return 1;
2363}
2364
cfa4c961
ID
2365static int chunk_soft_convert_filter(u64 chunk_profile,
2366 struct btrfs_balance_args *bargs)
2367{
2368 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
2369 return 0;
2370
2371 chunk_profile &= BTRFS_BLOCK_GROUP_PROFILE_MASK;
2372
2373 if (chunk_profile == 0)
2374 chunk_profile = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
2375
2376 if (bargs->target & chunk_profile)
2377 return 1;
2378
2379 return 0;
2380}
2381
f43ffb60
ID
2382static int should_balance_chunk(struct btrfs_root *root,
2383 struct extent_buffer *leaf,
2384 struct btrfs_chunk *chunk, u64 chunk_offset)
2385{
2386 struct btrfs_balance_control *bctl = root->fs_info->balance_ctl;
2387 struct btrfs_balance_args *bargs = NULL;
2388 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
2389
2390 /* type filter */
2391 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
2392 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
2393 return 0;
2394 }
2395
2396 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
2397 bargs = &bctl->data;
2398 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
2399 bargs = &bctl->sys;
2400 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
2401 bargs = &bctl->meta;
2402
ed25e9b2
ID
2403 /* profiles filter */
2404 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
2405 chunk_profiles_filter(chunk_type, bargs)) {
2406 return 0;
5ce5b3c0
ID
2407 }
2408
2409 /* usage filter */
2410 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
2411 chunk_usage_filter(bctl->fs_info, chunk_offset, bargs)) {
2412 return 0;
409d404b
ID
2413 }
2414
2415 /* devid filter */
2416 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
2417 chunk_devid_filter(leaf, chunk, bargs)) {
2418 return 0;
94e60d5a
ID
2419 }
2420
2421 /* drange filter, makes sense only with devid filter */
2422 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
2423 chunk_drange_filter(leaf, chunk, chunk_offset, bargs)) {
2424 return 0;
ea67176a
ID
2425 }
2426
2427 /* vrange filter */
2428 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
2429 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
2430 return 0;
ed25e9b2
ID
2431 }
2432
cfa4c961
ID
2433 /* soft profile changing mode */
2434 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
2435 chunk_soft_convert_filter(chunk_type, bargs)) {
2436 return 0;
2437 }
2438
f43ffb60
ID
2439 return 1;
2440}
2441
ec44a35c
CM
2442static u64 div_factor(u64 num, int factor)
2443{
2444 if (factor == 10)
2445 return num;
2446 num *= factor;
2447 do_div(num, 10);
2448 return num;
2449}
2450
c9e9f97b 2451static int __btrfs_balance(struct btrfs_fs_info *fs_info)
ec44a35c 2452{
19a39dce 2453 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
c9e9f97b
ID
2454 struct btrfs_root *chunk_root = fs_info->chunk_root;
2455 struct btrfs_root *dev_root = fs_info->dev_root;
2456 struct list_head *devices;
ec44a35c
CM
2457 struct btrfs_device *device;
2458 u64 old_size;
2459 u64 size_to_free;
f43ffb60 2460 struct btrfs_chunk *chunk;
ec44a35c
CM
2461 struct btrfs_path *path;
2462 struct btrfs_key key;
ec44a35c 2463 struct btrfs_key found_key;
c9e9f97b 2464 struct btrfs_trans_handle *trans;
f43ffb60
ID
2465 struct extent_buffer *leaf;
2466 int slot;
c9e9f97b
ID
2467 int ret;
2468 int enospc_errors = 0;
19a39dce 2469 bool counting = true;
ec44a35c 2470
ec44a35c 2471 /* step one make some room on all the devices */
c9e9f97b 2472 devices = &fs_info->fs_devices->devices;
c6e30871 2473 list_for_each_entry(device, devices, dev_list) {
ec44a35c
CM
2474 old_size = device->total_bytes;
2475 size_to_free = div_factor(old_size, 1);
2476 size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
2b82032c
YZ
2477 if (!device->writeable ||
2478 device->total_bytes - device->bytes_used > size_to_free)
ec44a35c
CM
2479 continue;
2480
2481 ret = btrfs_shrink_device(device, old_size - size_to_free);
ba1bf481
JB
2482 if (ret == -ENOSPC)
2483 break;
ec44a35c
CM
2484 BUG_ON(ret);
2485
a22285a6 2486 trans = btrfs_start_transaction(dev_root, 0);
98d5dc13 2487 BUG_ON(IS_ERR(trans));
ec44a35c
CM
2488
2489 ret = btrfs_grow_device(trans, device, old_size);
2490 BUG_ON(ret);
2491
2492 btrfs_end_transaction(trans, dev_root);
2493 }
2494
2495 /* step two, relocate all the chunks */
2496 path = btrfs_alloc_path();
17e9f796
MF
2497 if (!path) {
2498 ret = -ENOMEM;
2499 goto error;
2500 }
19a39dce
ID
2501
2502 /* zero out stat counters */
2503 spin_lock(&fs_info->balance_lock);
2504 memset(&bctl->stat, 0, sizeof(bctl->stat));
2505 spin_unlock(&fs_info->balance_lock);
2506again:
ec44a35c
CM
2507 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2508 key.offset = (u64)-1;
2509 key.type = BTRFS_CHUNK_ITEM_KEY;
2510
d397712b 2511 while (1) {
19a39dce 2512 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
a7e99c69 2513 atomic_read(&fs_info->balance_cancel_req)) {
837d5b6e
ID
2514 ret = -ECANCELED;
2515 goto error;
2516 }
2517
ec44a35c
CM
2518 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2519 if (ret < 0)
2520 goto error;
2521
2522 /*
2523 * this shouldn't happen, it means the last relocate
2524 * failed
2525 */
2526 if (ret == 0)
c9e9f97b 2527 BUG(); /* FIXME break ? */
ec44a35c
CM
2528
2529 ret = btrfs_previous_item(chunk_root, path, 0,
2530 BTRFS_CHUNK_ITEM_KEY);
c9e9f97b
ID
2531 if (ret) {
2532 ret = 0;
ec44a35c 2533 break;
c9e9f97b 2534 }
7d9eb12c 2535
f43ffb60
ID
2536 leaf = path->nodes[0];
2537 slot = path->slots[0];
2538 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7d9eb12c 2539
ec44a35c
CM
2540 if (found_key.objectid != key.objectid)
2541 break;
7d9eb12c 2542
ec44a35c 2543 /* chunk zero is special */
ba1bf481 2544 if (found_key.offset == 0)
ec44a35c
CM
2545 break;
2546
f43ffb60
ID
2547 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
2548
19a39dce
ID
2549 if (!counting) {
2550 spin_lock(&fs_info->balance_lock);
2551 bctl->stat.considered++;
2552 spin_unlock(&fs_info->balance_lock);
2553 }
2554
f43ffb60
ID
2555 ret = should_balance_chunk(chunk_root, leaf, chunk,
2556 found_key.offset);
b3b4aa74 2557 btrfs_release_path(path);
f43ffb60
ID
2558 if (!ret)
2559 goto loop;
2560
19a39dce
ID
2561 if (counting) {
2562 spin_lock(&fs_info->balance_lock);
2563 bctl->stat.expected++;
2564 spin_unlock(&fs_info->balance_lock);
2565 goto loop;
2566 }
2567
ec44a35c
CM
2568 ret = btrfs_relocate_chunk(chunk_root,
2569 chunk_root->root_key.objectid,
2570 found_key.objectid,
2571 found_key.offset);
508794eb
JB
2572 if (ret && ret != -ENOSPC)
2573 goto error;
19a39dce 2574 if (ret == -ENOSPC) {
c9e9f97b 2575 enospc_errors++;
19a39dce
ID
2576 } else {
2577 spin_lock(&fs_info->balance_lock);
2578 bctl->stat.completed++;
2579 spin_unlock(&fs_info->balance_lock);
2580 }
f43ffb60 2581loop:
ba1bf481 2582 key.offset = found_key.offset - 1;
ec44a35c 2583 }
c9e9f97b 2584
19a39dce
ID
2585 if (counting) {
2586 btrfs_release_path(path);
2587 counting = false;
2588 goto again;
2589 }
ec44a35c
CM
2590error:
2591 btrfs_free_path(path);
c9e9f97b
ID
2592 if (enospc_errors) {
2593 printk(KERN_INFO "btrfs: %d enospc errors during balance\n",
2594 enospc_errors);
2595 if (!ret)
2596 ret = -ENOSPC;
2597 }
2598
ec44a35c
CM
2599 return ret;
2600}
2601
837d5b6e
ID
2602static inline int balance_need_close(struct btrfs_fs_info *fs_info)
2603{
a7e99c69
ID
2604 /* cancel requested || normal exit path */
2605 return atomic_read(&fs_info->balance_cancel_req) ||
2606 (atomic_read(&fs_info->balance_pause_req) == 0 &&
2607 atomic_read(&fs_info->balance_cancel_req) == 0);
837d5b6e
ID
2608}
2609
c9e9f97b
ID
2610static void __cancel_balance(struct btrfs_fs_info *fs_info)
2611{
0940ebf6
ID
2612 int ret;
2613
c9e9f97b 2614 unset_balance_control(fs_info);
0940ebf6
ID
2615 ret = del_balance_item(fs_info->tree_root);
2616 BUG_ON(ret);
c9e9f97b
ID
2617}
2618
19a39dce 2619void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
c9e9f97b
ID
2620 struct btrfs_ioctl_balance_args *bargs);
2621
2622/*
2623 * Should be called with both balance and volume mutexes held
2624 */
2625int btrfs_balance(struct btrfs_balance_control *bctl,
2626 struct btrfs_ioctl_balance_args *bargs)
2627{
2628 struct btrfs_fs_info *fs_info = bctl->fs_info;
f43ffb60 2629 u64 allowed;
c9e9f97b
ID
2630 int ret;
2631
837d5b6e 2632 if (btrfs_fs_closing(fs_info) ||
a7e99c69
ID
2633 atomic_read(&fs_info->balance_pause_req) ||
2634 atomic_read(&fs_info->balance_cancel_req)) {
c9e9f97b
ID
2635 ret = -EINVAL;
2636 goto out;
2637 }
2638
f43ffb60
ID
2639 /*
2640 * In case of mixed groups both data and meta should be picked,
2641 * and identical options should be given for both of them.
2642 */
2643 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
2644 if ((allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
2645 (bctl->flags & (BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA))) {
2646 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
2647 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
2648 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
2649 printk(KERN_ERR "btrfs: with mixed groups data and "
2650 "metadata balance options must be the same\n");
2651 ret = -EINVAL;
2652 goto out;
2653 }
2654 }
2655
e4d8ec0f
ID
2656 /*
2657 * Profile changing sanity checks. Skip them if a simple
2658 * balance is requested.
2659 */
2660 if (!((bctl->data.flags | bctl->sys.flags | bctl->meta.flags) &
2661 BTRFS_BALANCE_ARGS_CONVERT))
2662 goto do_balance;
2663
2664 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
2665 if (fs_info->fs_devices->num_devices == 1)
2666 allowed |= BTRFS_BLOCK_GROUP_DUP;
2667 else if (fs_info->fs_devices->num_devices < 4)
2668 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
2669 else
2670 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
2671 BTRFS_BLOCK_GROUP_RAID10);
2672
2673 if (!profile_is_valid(bctl->data.target, 1) ||
2674 bctl->data.target & ~allowed) {
2675 printk(KERN_ERR "btrfs: unable to start balance with target "
2676 "data profile %llu\n",
2677 (unsigned long long)bctl->data.target);
2678 ret = -EINVAL;
2679 goto out;
2680 }
2681 if (!profile_is_valid(bctl->meta.target, 1) ||
2682 bctl->meta.target & ~allowed) {
2683 printk(KERN_ERR "btrfs: unable to start balance with target "
2684 "metadata profile %llu\n",
2685 (unsigned long long)bctl->meta.target);
2686 ret = -EINVAL;
2687 goto out;
2688 }
2689 if (!profile_is_valid(bctl->sys.target, 1) ||
2690 bctl->sys.target & ~allowed) {
2691 printk(KERN_ERR "btrfs: unable to start balance with target "
2692 "system profile %llu\n",
2693 (unsigned long long)bctl->sys.target);
2694 ret = -EINVAL;
2695 goto out;
2696 }
2697
2698 if (bctl->data.target & BTRFS_BLOCK_GROUP_DUP) {
2699 printk(KERN_ERR "btrfs: dup for data is not allowed\n");
2700 ret = -EINVAL;
2701 goto out;
2702 }
2703
2704 /* allow to reduce meta or sys integrity only if force set */
2705 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
2706 BTRFS_BLOCK_GROUP_RAID10;
2707 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
2708 (fs_info->avail_system_alloc_bits & allowed) &&
2709 !(bctl->sys.target & allowed)) ||
2710 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
2711 (fs_info->avail_metadata_alloc_bits & allowed) &&
2712 !(bctl->meta.target & allowed))) {
2713 if (bctl->flags & BTRFS_BALANCE_FORCE) {
2714 printk(KERN_INFO "btrfs: force reducing metadata "
2715 "integrity\n");
2716 } else {
2717 printk(KERN_ERR "btrfs: balance will reduce metadata "
2718 "integrity, use force if you want this\n");
2719 ret = -EINVAL;
2720 goto out;
2721 }
2722 }
2723
2724do_balance:
0940ebf6 2725 ret = insert_balance_item(fs_info->tree_root, bctl);
59641015 2726 if (ret && ret != -EEXIST)
0940ebf6
ID
2727 goto out;
2728
59641015
ID
2729 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
2730 BUG_ON(ret == -EEXIST);
2731 set_balance_control(bctl);
2732 } else {
2733 BUG_ON(ret != -EEXIST);
2734 spin_lock(&fs_info->balance_lock);
2735 update_balance_args(bctl);
2736 spin_unlock(&fs_info->balance_lock);
2737 }
c9e9f97b 2738
837d5b6e 2739 atomic_inc(&fs_info->balance_running);
c9e9f97b
ID
2740 mutex_unlock(&fs_info->balance_mutex);
2741
2742 ret = __btrfs_balance(fs_info);
2743
2744 mutex_lock(&fs_info->balance_mutex);
837d5b6e 2745 atomic_dec(&fs_info->balance_running);
c9e9f97b
ID
2746
2747 if (bargs) {
2748 memset(bargs, 0, sizeof(*bargs));
19a39dce 2749 update_ioctl_balance_args(fs_info, 0, bargs);
c9e9f97b
ID
2750 }
2751
837d5b6e
ID
2752 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
2753 balance_need_close(fs_info)) {
2754 __cancel_balance(fs_info);
2755 }
2756
2757 wake_up(&fs_info->balance_wait_q);
c9e9f97b
ID
2758
2759 return ret;
2760out:
59641015
ID
2761 if (bctl->flags & BTRFS_BALANCE_RESUME)
2762 __cancel_balance(fs_info);
2763 else
2764 kfree(bctl);
2765 return ret;
2766}
2767
2768static int balance_kthread(void *data)
2769{
2770 struct btrfs_balance_control *bctl =
2771 (struct btrfs_balance_control *)data;
2772 struct btrfs_fs_info *fs_info = bctl->fs_info;
9555c6c1 2773 int ret = 0;
59641015
ID
2774
2775 mutex_lock(&fs_info->volume_mutex);
2776 mutex_lock(&fs_info->balance_mutex);
2777
2778 set_balance_control(bctl);
2779
9555c6c1
ID
2780 if (btrfs_test_opt(fs_info->tree_root, SKIP_BALANCE)) {
2781 printk(KERN_INFO "btrfs: force skipping balance\n");
2782 } else {
2783 printk(KERN_INFO "btrfs: continuing balance\n");
2784 ret = btrfs_balance(bctl, NULL);
2785 }
59641015
ID
2786
2787 mutex_unlock(&fs_info->balance_mutex);
2788 mutex_unlock(&fs_info->volume_mutex);
2789 return ret;
2790}
2791
2792int btrfs_recover_balance(struct btrfs_root *tree_root)
2793{
2794 struct task_struct *tsk;
2795 struct btrfs_balance_control *bctl;
2796 struct btrfs_balance_item *item;
2797 struct btrfs_disk_balance_args disk_bargs;
2798 struct btrfs_path *path;
2799 struct extent_buffer *leaf;
2800 struct btrfs_key key;
2801 int ret;
2802
2803 path = btrfs_alloc_path();
2804 if (!path)
2805 return -ENOMEM;
2806
2807 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
2808 if (!bctl) {
2809 ret = -ENOMEM;
2810 goto out;
2811 }
2812
2813 key.objectid = BTRFS_BALANCE_OBJECTID;
2814 key.type = BTRFS_BALANCE_ITEM_KEY;
2815 key.offset = 0;
2816
2817 ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
2818 if (ret < 0)
2819 goto out_bctl;
2820 if (ret > 0) { /* ret = -ENOENT; */
2821 ret = 0;
2822 goto out_bctl;
2823 }
2824
2825 leaf = path->nodes[0];
2826 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2827
2828 bctl->fs_info = tree_root->fs_info;
2829 bctl->flags = btrfs_balance_flags(leaf, item) | BTRFS_BALANCE_RESUME;
2830
2831 btrfs_balance_data(leaf, item, &disk_bargs);
2832 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
2833 btrfs_balance_meta(leaf, item, &disk_bargs);
2834 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
2835 btrfs_balance_sys(leaf, item, &disk_bargs);
2836 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
2837
2838 tsk = kthread_run(balance_kthread, bctl, "btrfs-balance");
2839 if (IS_ERR(tsk))
2840 ret = PTR_ERR(tsk);
2841 else
2842 goto out;
2843
2844out_bctl:
c9e9f97b 2845 kfree(bctl);
59641015
ID
2846out:
2847 btrfs_free_path(path);
ec44a35c
CM
2848 return ret;
2849}
2850
837d5b6e
ID
2851int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
2852{
2853 int ret = 0;
2854
2855 mutex_lock(&fs_info->balance_mutex);
2856 if (!fs_info->balance_ctl) {
2857 mutex_unlock(&fs_info->balance_mutex);
2858 return -ENOTCONN;
2859 }
2860
2861 if (atomic_read(&fs_info->balance_running)) {
2862 atomic_inc(&fs_info->balance_pause_req);
2863 mutex_unlock(&fs_info->balance_mutex);
2864
2865 wait_event(fs_info->balance_wait_q,
2866 atomic_read(&fs_info->balance_running) == 0);
2867
2868 mutex_lock(&fs_info->balance_mutex);
2869 /* we are good with balance_ctl ripped off from under us */
2870 BUG_ON(atomic_read(&fs_info->balance_running));
2871 atomic_dec(&fs_info->balance_pause_req);
2872 } else {
2873 ret = -ENOTCONN;
2874 }
2875
2876 mutex_unlock(&fs_info->balance_mutex);
2877 return ret;
2878}
2879
a7e99c69
ID
2880int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
2881{
2882 mutex_lock(&fs_info->balance_mutex);
2883 if (!fs_info->balance_ctl) {
2884 mutex_unlock(&fs_info->balance_mutex);
2885 return -ENOTCONN;
2886 }
2887
2888 atomic_inc(&fs_info->balance_cancel_req);
2889 /*
2890 * if we are running just wait and return, balance item is
2891 * deleted in btrfs_balance in this case
2892 */
2893 if (atomic_read(&fs_info->balance_running)) {
2894 mutex_unlock(&fs_info->balance_mutex);
2895 wait_event(fs_info->balance_wait_q,
2896 atomic_read(&fs_info->balance_running) == 0);
2897 mutex_lock(&fs_info->balance_mutex);
2898 } else {
2899 /* __cancel_balance needs volume_mutex */
2900 mutex_unlock(&fs_info->balance_mutex);
2901 mutex_lock(&fs_info->volume_mutex);
2902 mutex_lock(&fs_info->balance_mutex);
2903
2904 if (fs_info->balance_ctl)
2905 __cancel_balance(fs_info);
2906
2907 mutex_unlock(&fs_info->volume_mutex);
2908 }
2909
2910 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
2911 atomic_dec(&fs_info->balance_cancel_req);
2912 mutex_unlock(&fs_info->balance_mutex);
2913 return 0;
2914}
2915
8f18cf13
CM
2916/*
2917 * shrinking a device means finding all of the device extents past
2918 * the new size, and then following the back refs to the chunks.
2919 * The chunk relocation code actually frees the device extent
2920 */
2921int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
2922{
2923 struct btrfs_trans_handle *trans;
2924 struct btrfs_root *root = device->dev_root;
2925 struct btrfs_dev_extent *dev_extent = NULL;
2926 struct btrfs_path *path;
2927 u64 length;
2928 u64 chunk_tree;
2929 u64 chunk_objectid;
2930 u64 chunk_offset;
2931 int ret;
2932 int slot;
ba1bf481
JB
2933 int failed = 0;
2934 bool retried = false;
8f18cf13
CM
2935 struct extent_buffer *l;
2936 struct btrfs_key key;
6c41761f 2937 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
8f18cf13 2938 u64 old_total = btrfs_super_total_bytes(super_copy);
ba1bf481 2939 u64 old_size = device->total_bytes;
8f18cf13
CM
2940 u64 diff = device->total_bytes - new_size;
2941
2b82032c
YZ
2942 if (new_size >= device->total_bytes)
2943 return -EINVAL;
8f18cf13
CM
2944
2945 path = btrfs_alloc_path();
2946 if (!path)
2947 return -ENOMEM;
2948
8f18cf13
CM
2949 path->reada = 2;
2950
7d9eb12c
CM
2951 lock_chunks(root);
2952
8f18cf13 2953 device->total_bytes = new_size;
2bf64758 2954 if (device->writeable) {
2b82032c 2955 device->fs_devices->total_rw_bytes -= diff;
2bf64758
JB
2956 spin_lock(&root->fs_info->free_chunk_lock);
2957 root->fs_info->free_chunk_space -= diff;
2958 spin_unlock(&root->fs_info->free_chunk_lock);
2959 }
7d9eb12c 2960 unlock_chunks(root);
8f18cf13 2961
ba1bf481 2962again:
8f18cf13
CM
2963 key.objectid = device->devid;
2964 key.offset = (u64)-1;
2965 key.type = BTRFS_DEV_EXTENT_KEY;
2966
2967 while (1) {
2968 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2969 if (ret < 0)
2970 goto done;
2971
2972 ret = btrfs_previous_item(root, path, 0, key.type);
2973 if (ret < 0)
2974 goto done;
2975 if (ret) {
2976 ret = 0;
b3b4aa74 2977 btrfs_release_path(path);
bf1fb512 2978 break;
8f18cf13
CM
2979 }
2980
2981 l = path->nodes[0];
2982 slot = path->slots[0];
2983 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
2984
ba1bf481 2985 if (key.objectid != device->devid) {
b3b4aa74 2986 btrfs_release_path(path);
bf1fb512 2987 break;
ba1bf481 2988 }
8f18cf13
CM
2989
2990 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
2991 length = btrfs_dev_extent_length(l, dev_extent);
2992
ba1bf481 2993 if (key.offset + length <= new_size) {
b3b4aa74 2994 btrfs_release_path(path);
d6397bae 2995 break;
ba1bf481 2996 }
8f18cf13
CM
2997
2998 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
2999 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
3000 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
b3b4aa74 3001 btrfs_release_path(path);
8f18cf13
CM
3002
3003 ret = btrfs_relocate_chunk(root, chunk_tree, chunk_objectid,
3004 chunk_offset);
ba1bf481 3005 if (ret && ret != -ENOSPC)
8f18cf13 3006 goto done;
ba1bf481
JB
3007 if (ret == -ENOSPC)
3008 failed++;
3009 key.offset -= 1;
3010 }
3011
3012 if (failed && !retried) {
3013 failed = 0;
3014 retried = true;
3015 goto again;
3016 } else if (failed && retried) {
3017 ret = -ENOSPC;
3018 lock_chunks(root);
3019
3020 device->total_bytes = old_size;
3021 if (device->writeable)
3022 device->fs_devices->total_rw_bytes += diff;
2bf64758
JB
3023 spin_lock(&root->fs_info->free_chunk_lock);
3024 root->fs_info->free_chunk_space += diff;
3025 spin_unlock(&root->fs_info->free_chunk_lock);
ba1bf481
JB
3026 unlock_chunks(root);
3027 goto done;
8f18cf13
CM
3028 }
3029
d6397bae 3030 /* Shrinking succeeded, else we would be at "done". */
a22285a6 3031 trans = btrfs_start_transaction(root, 0);
98d5dc13
TI
3032 if (IS_ERR(trans)) {
3033 ret = PTR_ERR(trans);
3034 goto done;
3035 }
3036
d6397bae
CB
3037 lock_chunks(root);
3038
3039 device->disk_total_bytes = new_size;
3040 /* Now btrfs_update_device() will change the on-disk size. */
3041 ret = btrfs_update_device(trans, device);
3042 if (ret) {
3043 unlock_chunks(root);
3044 btrfs_end_transaction(trans, root);
3045 goto done;
3046 }
3047 WARN_ON(diff > old_total);
3048 btrfs_set_super_total_bytes(super_copy, old_total - diff);
3049 unlock_chunks(root);
3050 btrfs_end_transaction(trans, root);
8f18cf13
CM
3051done:
3052 btrfs_free_path(path);
3053 return ret;
3054}
3055
125ccb0a 3056static int btrfs_add_system_chunk(struct btrfs_root *root,
0b86a832
CM
3057 struct btrfs_key *key,
3058 struct btrfs_chunk *chunk, int item_size)
3059{
6c41761f 3060 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
0b86a832
CM
3061 struct btrfs_disk_key disk_key;
3062 u32 array_size;
3063 u8 *ptr;
3064
3065 array_size = btrfs_super_sys_array_size(super_copy);
3066 if (array_size + item_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
3067 return -EFBIG;
3068
3069 ptr = super_copy->sys_chunk_array + array_size;
3070 btrfs_cpu_key_to_disk(&disk_key, key);
3071 memcpy(ptr, &disk_key, sizeof(disk_key));
3072 ptr += sizeof(disk_key);
3073 memcpy(ptr, chunk, item_size);
3074 item_size += sizeof(disk_key);
3075 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
3076 return 0;
3077}
3078
73c5de00
AJ
3079/*
3080 * sort the devices in descending order by max_avail, total_avail
3081 */
3082static int btrfs_cmp_device_info(const void *a, const void *b)
9b3f68b9 3083{
73c5de00
AJ
3084 const struct btrfs_device_info *di_a = a;
3085 const struct btrfs_device_info *di_b = b;
9b3f68b9 3086
73c5de00 3087 if (di_a->max_avail > di_b->max_avail)
b2117a39 3088 return -1;
73c5de00 3089 if (di_a->max_avail < di_b->max_avail)
b2117a39 3090 return 1;
73c5de00
AJ
3091 if (di_a->total_avail > di_b->total_avail)
3092 return -1;
3093 if (di_a->total_avail < di_b->total_avail)
3094 return 1;
3095 return 0;
b2117a39 3096}
0b86a832 3097
73c5de00
AJ
3098static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
3099 struct btrfs_root *extent_root,
3100 struct map_lookup **map_ret,
3101 u64 *num_bytes_out, u64 *stripe_size_out,
3102 u64 start, u64 type)
b2117a39 3103{
73c5de00
AJ
3104 struct btrfs_fs_info *info = extent_root->fs_info;
3105 struct btrfs_fs_devices *fs_devices = info->fs_devices;
3106 struct list_head *cur;
3107 struct map_lookup *map = NULL;
3108 struct extent_map_tree *em_tree;
3109 struct extent_map *em;
3110 struct btrfs_device_info *devices_info = NULL;
3111 u64 total_avail;
3112 int num_stripes; /* total number of stripes to allocate */
3113 int sub_stripes; /* sub_stripes info for map */
3114 int dev_stripes; /* stripes per dev */
3115 int devs_max; /* max devs to use */
3116 int devs_min; /* min devs needed */
3117 int devs_increment; /* ndevs has to be a multiple of this */
3118 int ncopies; /* how many copies to data has */
3119 int ret;
3120 u64 max_stripe_size;
3121 u64 max_chunk_size;
3122 u64 stripe_size;
3123 u64 num_bytes;
3124 int ndevs;
3125 int i;
3126 int j;
593060d7 3127
73c5de00
AJ
3128 if ((type & BTRFS_BLOCK_GROUP_RAID1) &&
3129 (type & BTRFS_BLOCK_GROUP_DUP)) {
3130 WARN_ON(1);
3131 type &= ~BTRFS_BLOCK_GROUP_DUP;
321aecc6 3132 }
9b3f68b9 3133
73c5de00
AJ
3134 if (list_empty(&fs_devices->alloc_list))
3135 return -ENOSPC;
b2117a39 3136
73c5de00
AJ
3137 sub_stripes = 1;
3138 dev_stripes = 1;
3139 devs_increment = 1;
3140 ncopies = 1;
3141 devs_max = 0; /* 0 == as many as possible */
3142 devs_min = 1;
3143
3144 /*
3145 * define the properties of each RAID type.
3146 * FIXME: move this to a global table and use it in all RAID
3147 * calculation code
3148 */
3149 if (type & (BTRFS_BLOCK_GROUP_DUP)) {
3150 dev_stripes = 2;
b2117a39 3151 ncopies = 2;
73c5de00
AJ
3152 devs_max = 1;
3153 } else if (type & (BTRFS_BLOCK_GROUP_RAID0)) {
3154 devs_min = 2;
3155 } else if (type & (BTRFS_BLOCK_GROUP_RAID1)) {
3156 devs_increment = 2;
b2117a39 3157 ncopies = 2;
73c5de00
AJ
3158 devs_max = 2;
3159 devs_min = 2;
3160 } else if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
3161 sub_stripes = 2;
3162 devs_increment = 2;
3163 ncopies = 2;
3164 devs_min = 4;
3165 } else {
3166 devs_max = 1;
3167 }
b2117a39 3168
9b3f68b9 3169 if (type & BTRFS_BLOCK_GROUP_DATA) {
73c5de00
AJ
3170 max_stripe_size = 1024 * 1024 * 1024;
3171 max_chunk_size = 10 * max_stripe_size;
9b3f68b9 3172 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
1100373f
CM
3173 /* for larger filesystems, use larger metadata chunks */
3174 if (fs_devices->total_rw_bytes > 50ULL * 1024 * 1024 * 1024)
3175 max_stripe_size = 1024 * 1024 * 1024;
3176 else
3177 max_stripe_size = 256 * 1024 * 1024;
73c5de00 3178 max_chunk_size = max_stripe_size;
a40a90a0 3179 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
96bdc7dc 3180 max_stripe_size = 32 * 1024 * 1024;
73c5de00
AJ
3181 max_chunk_size = 2 * max_stripe_size;
3182 } else {
3183 printk(KERN_ERR "btrfs: invalid chunk type 0x%llx requested\n",
3184 type);
3185 BUG_ON(1);
9b3f68b9
CM
3186 }
3187
2b82032c
YZ
3188 /* we don't want a chunk larger than 10% of writeable space */
3189 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
3190 max_chunk_size);
9b3f68b9 3191
73c5de00
AJ
3192 devices_info = kzalloc(sizeof(*devices_info) * fs_devices->rw_devices,
3193 GFP_NOFS);
3194 if (!devices_info)
3195 return -ENOMEM;
0cad8a11 3196
73c5de00 3197 cur = fs_devices->alloc_list.next;
9b3f68b9 3198
9f680ce0 3199 /*
73c5de00
AJ
3200 * in the first pass through the devices list, we gather information
3201 * about the available holes on each device.
9f680ce0 3202 */
73c5de00
AJ
3203 ndevs = 0;
3204 while (cur != &fs_devices->alloc_list) {
3205 struct btrfs_device *device;
3206 u64 max_avail;
3207 u64 dev_offset;
b2117a39 3208
73c5de00 3209 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
9f680ce0 3210
73c5de00 3211 cur = cur->next;
b2117a39 3212
73c5de00
AJ
3213 if (!device->writeable) {
3214 printk(KERN_ERR
3215 "btrfs: read-only device in alloc_list\n");
3216 WARN_ON(1);
3217 continue;
3218 }
b2117a39 3219
73c5de00
AJ
3220 if (!device->in_fs_metadata)
3221 continue;
b2117a39 3222
73c5de00
AJ
3223 if (device->total_bytes > device->bytes_used)
3224 total_avail = device->total_bytes - device->bytes_used;
3225 else
3226 total_avail = 0;
38c01b96 3227
3228 /* If there is no space on this device, skip it. */
3229 if (total_avail == 0)
3230 continue;
b2117a39 3231
125ccb0a 3232 ret = find_free_dev_extent(device,
73c5de00
AJ
3233 max_stripe_size * dev_stripes,
3234 &dev_offset, &max_avail);
3235 if (ret && ret != -ENOSPC)
3236 goto error;
b2117a39 3237
73c5de00
AJ
3238 if (ret == 0)
3239 max_avail = max_stripe_size * dev_stripes;
b2117a39 3240
73c5de00
AJ
3241 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
3242 continue;
b2117a39 3243
73c5de00
AJ
3244 devices_info[ndevs].dev_offset = dev_offset;
3245 devices_info[ndevs].max_avail = max_avail;
3246 devices_info[ndevs].total_avail = total_avail;
3247 devices_info[ndevs].dev = device;
3248 ++ndevs;
3249 }
b2117a39 3250
73c5de00
AJ
3251 /*
3252 * now sort the devices by hole size / available space
3253 */
3254 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
3255 btrfs_cmp_device_info, NULL);
b2117a39 3256
73c5de00
AJ
3257 /* round down to number of usable stripes */
3258 ndevs -= ndevs % devs_increment;
b2117a39 3259
73c5de00
AJ
3260 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
3261 ret = -ENOSPC;
3262 goto error;
b2117a39 3263 }
9f680ce0 3264
73c5de00
AJ
3265 if (devs_max && ndevs > devs_max)
3266 ndevs = devs_max;
3267 /*
3268 * the primary goal is to maximize the number of stripes, so use as many
3269 * devices as possible, even if the stripes are not maximum sized.
3270 */
3271 stripe_size = devices_info[ndevs-1].max_avail;
3272 num_stripes = ndevs * dev_stripes;
b2117a39 3273
73c5de00
AJ
3274 if (stripe_size * num_stripes > max_chunk_size * ncopies) {
3275 stripe_size = max_chunk_size * ncopies;
3276 do_div(stripe_size, num_stripes);
b2117a39 3277 }
b2117a39 3278
73c5de00
AJ
3279 do_div(stripe_size, dev_stripes);
3280 do_div(stripe_size, BTRFS_STRIPE_LEN);
3281 stripe_size *= BTRFS_STRIPE_LEN;
b2117a39
MX
3282
3283 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
3284 if (!map) {
3285 ret = -ENOMEM;
3286 goto error;
3287 }
3288 map->num_stripes = num_stripes;
9b3f68b9 3289
73c5de00
AJ
3290 for (i = 0; i < ndevs; ++i) {
3291 for (j = 0; j < dev_stripes; ++j) {
3292 int s = i * dev_stripes + j;
3293 map->stripes[s].dev = devices_info[i].dev;
3294 map->stripes[s].physical = devices_info[i].dev_offset +
3295 j * stripe_size;
6324fbf3 3296 }
6324fbf3 3297 }
2b82032c 3298 map->sector_size = extent_root->sectorsize;
b2117a39
MX
3299 map->stripe_len = BTRFS_STRIPE_LEN;
3300 map->io_align = BTRFS_STRIPE_LEN;
3301 map->io_width = BTRFS_STRIPE_LEN;
2b82032c 3302 map->type = type;
2b82032c 3303 map->sub_stripes = sub_stripes;
0b86a832 3304
2b82032c 3305 *map_ret = map;
73c5de00 3306 num_bytes = stripe_size * (num_stripes / ncopies);
0b86a832 3307
73c5de00
AJ
3308 *stripe_size_out = stripe_size;
3309 *num_bytes_out = num_bytes;
0b86a832 3310
73c5de00 3311 trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
1abe9b8a 3312
172ddd60 3313 em = alloc_extent_map();
2b82032c 3314 if (!em) {
b2117a39
MX
3315 ret = -ENOMEM;
3316 goto error;
593060d7 3317 }
2b82032c
YZ
3318 em->bdev = (struct block_device *)map;
3319 em->start = start;
73c5de00 3320 em->len = num_bytes;
2b82032c
YZ
3321 em->block_start = 0;
3322 em->block_len = em->len;
593060d7 3323
2b82032c 3324 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
890871be 3325 write_lock(&em_tree->lock);
2b82032c 3326 ret = add_extent_mapping(em_tree, em);
890871be 3327 write_unlock(&em_tree->lock);
2b82032c
YZ
3328 BUG_ON(ret);
3329 free_extent_map(em);
0b86a832 3330
2b82032c
YZ
3331 ret = btrfs_make_block_group(trans, extent_root, 0, type,
3332 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
73c5de00 3333 start, num_bytes);
2b82032c 3334 BUG_ON(ret);
611f0e00 3335
73c5de00
AJ
3336 for (i = 0; i < map->num_stripes; ++i) {
3337 struct btrfs_device *device;
3338 u64 dev_offset;
3339
3340 device = map->stripes[i].dev;
3341 dev_offset = map->stripes[i].physical;
0b86a832
CM
3342
3343 ret = btrfs_alloc_dev_extent(trans, device,
2b82032c
YZ
3344 info->chunk_root->root_key.objectid,
3345 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
73c5de00 3346 start, dev_offset, stripe_size);
0b86a832 3347 BUG_ON(ret);
2b82032c
YZ
3348 }
3349
b2117a39 3350 kfree(devices_info);
2b82032c 3351 return 0;
b2117a39
MX
3352
3353error:
3354 kfree(map);
3355 kfree(devices_info);
3356 return ret;
2b82032c
YZ
3357}
3358
3359static int __finish_chunk_alloc(struct btrfs_trans_handle *trans,
3360 struct btrfs_root *extent_root,
3361 struct map_lookup *map, u64 chunk_offset,
3362 u64 chunk_size, u64 stripe_size)
3363{
3364 u64 dev_offset;
3365 struct btrfs_key key;
3366 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
3367 struct btrfs_device *device;
3368 struct btrfs_chunk *chunk;
3369 struct btrfs_stripe *stripe;
3370 size_t item_size = btrfs_chunk_item_size(map->num_stripes);
3371 int index = 0;
3372 int ret;
3373
3374 chunk = kzalloc(item_size, GFP_NOFS);
3375 if (!chunk)
3376 return -ENOMEM;
3377
3378 index = 0;
3379 while (index < map->num_stripes) {
3380 device = map->stripes[index].dev;
3381 device->bytes_used += stripe_size;
0b86a832
CM
3382 ret = btrfs_update_device(trans, device);
3383 BUG_ON(ret);
2b82032c
YZ
3384 index++;
3385 }
3386
2bf64758
JB
3387 spin_lock(&extent_root->fs_info->free_chunk_lock);
3388 extent_root->fs_info->free_chunk_space -= (stripe_size *
3389 map->num_stripes);
3390 spin_unlock(&extent_root->fs_info->free_chunk_lock);
3391
2b82032c
YZ
3392 index = 0;
3393 stripe = &chunk->stripe;
3394 while (index < map->num_stripes) {
3395 device = map->stripes[index].dev;
3396 dev_offset = map->stripes[index].physical;
0b86a832 3397
e17cade2
CM
3398 btrfs_set_stack_stripe_devid(stripe, device->devid);
3399 btrfs_set_stack_stripe_offset(stripe, dev_offset);
3400 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
2b82032c 3401 stripe++;
0b86a832
CM
3402 index++;
3403 }
3404
2b82032c 3405 btrfs_set_stack_chunk_length(chunk, chunk_size);
0b86a832 3406 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
2b82032c
YZ
3407 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
3408 btrfs_set_stack_chunk_type(chunk, map->type);
3409 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
3410 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
3411 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
0b86a832 3412 btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
2b82032c 3413 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
0b86a832 3414
2b82032c
YZ
3415 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3416 key.type = BTRFS_CHUNK_ITEM_KEY;
3417 key.offset = chunk_offset;
0b86a832 3418
2b82032c
YZ
3419 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
3420 BUG_ON(ret);
0b86a832 3421
2b82032c 3422 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
125ccb0a 3423 ret = btrfs_add_system_chunk(chunk_root, &key, chunk,
2b82032c 3424 item_size);
8f18cf13
CM
3425 BUG_ON(ret);
3426 }
1abe9b8a 3427
0b86a832 3428 kfree(chunk);
2b82032c
YZ
3429 return 0;
3430}
0b86a832 3431
2b82032c
YZ
3432/*
3433 * Chunk allocation falls into two parts. The first part does works
3434 * that make the new allocated chunk useable, but not do any operation
3435 * that modifies the chunk tree. The second part does the works that
3436 * require modifying the chunk tree. This division is important for the
3437 * bootstrap process of adding storage to a seed btrfs.
3438 */
3439int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
3440 struct btrfs_root *extent_root, u64 type)
3441{
3442 u64 chunk_offset;
3443 u64 chunk_size;
3444 u64 stripe_size;
3445 struct map_lookup *map;
3446 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
3447 int ret;
3448
3449 ret = find_next_chunk(chunk_root, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
3450 &chunk_offset);
3451 if (ret)
3452 return ret;
3453
3454 ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
3455 &stripe_size, chunk_offset, type);
3456 if (ret)
3457 return ret;
3458
3459 ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
3460 chunk_size, stripe_size);
3461 BUG_ON(ret);
3462 return 0;
3463}
3464
d397712b 3465static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
2b82032c
YZ
3466 struct btrfs_root *root,
3467 struct btrfs_device *device)
3468{
3469 u64 chunk_offset;
3470 u64 sys_chunk_offset;
3471 u64 chunk_size;
3472 u64 sys_chunk_size;
3473 u64 stripe_size;
3474 u64 sys_stripe_size;
3475 u64 alloc_profile;
3476 struct map_lookup *map;
3477 struct map_lookup *sys_map;
3478 struct btrfs_fs_info *fs_info = root->fs_info;
3479 struct btrfs_root *extent_root = fs_info->extent_root;
3480 int ret;
3481
3482 ret = find_next_chunk(fs_info->chunk_root,
3483 BTRFS_FIRST_CHUNK_TREE_OBJECTID, &chunk_offset);
92b8e897
MF
3484 if (ret)
3485 return ret;
2b82032c
YZ
3486
3487 alloc_profile = BTRFS_BLOCK_GROUP_METADATA |
6fef8df1 3488 fs_info->avail_metadata_alloc_bits;
2b82032c
YZ
3489 alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
3490
3491 ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
3492 &stripe_size, chunk_offset, alloc_profile);
3493 BUG_ON(ret);
3494
3495 sys_chunk_offset = chunk_offset + chunk_size;
3496
3497 alloc_profile = BTRFS_BLOCK_GROUP_SYSTEM |
6fef8df1 3498 fs_info->avail_system_alloc_bits;
2b82032c
YZ
3499 alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
3500
3501 ret = __btrfs_alloc_chunk(trans, extent_root, &sys_map,
3502 &sys_chunk_size, &sys_stripe_size,
3503 sys_chunk_offset, alloc_profile);
3504 BUG_ON(ret);
3505
3506 ret = btrfs_add_device(trans, fs_info->chunk_root, device);
3507 BUG_ON(ret);
3508
3509 /*
3510 * Modifying chunk tree needs allocating new blocks from both
3511 * system block group and metadata block group. So we only can
3512 * do operations require modifying the chunk tree after both
3513 * block groups were created.
3514 */
3515 ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
3516 chunk_size, stripe_size);
3517 BUG_ON(ret);
3518
3519 ret = __finish_chunk_alloc(trans, extent_root, sys_map,
3520 sys_chunk_offset, sys_chunk_size,
3521 sys_stripe_size);
b248a415 3522 BUG_ON(ret);
2b82032c
YZ
3523 return 0;
3524}
3525
3526int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
3527{
3528 struct extent_map *em;
3529 struct map_lookup *map;
3530 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
3531 int readonly = 0;
3532 int i;
3533
890871be 3534 read_lock(&map_tree->map_tree.lock);
2b82032c 3535 em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
890871be 3536 read_unlock(&map_tree->map_tree.lock);
2b82032c
YZ
3537 if (!em)
3538 return 1;
3539
f48b9075
JB
3540 if (btrfs_test_opt(root, DEGRADED)) {
3541 free_extent_map(em);
3542 return 0;
3543 }
3544
2b82032c
YZ
3545 map = (struct map_lookup *)em->bdev;
3546 for (i = 0; i < map->num_stripes; i++) {
3547 if (!map->stripes[i].dev->writeable) {
3548 readonly = 1;
3549 break;
3550 }
3551 }
0b86a832 3552 free_extent_map(em);
2b82032c 3553 return readonly;
0b86a832
CM
3554}
3555
3556void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
3557{
a8067e02 3558 extent_map_tree_init(&tree->map_tree);
0b86a832
CM
3559}
3560
3561void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
3562{
3563 struct extent_map *em;
3564
d397712b 3565 while (1) {
890871be 3566 write_lock(&tree->map_tree.lock);
0b86a832
CM
3567 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
3568 if (em)
3569 remove_extent_mapping(&tree->map_tree, em);
890871be 3570 write_unlock(&tree->map_tree.lock);
0b86a832
CM
3571 if (!em)
3572 break;
3573 kfree(em->bdev);
3574 /* once for us */
3575 free_extent_map(em);
3576 /* once for the tree */
3577 free_extent_map(em);
3578 }
3579}
3580
f188591e
CM
3581int btrfs_num_copies(struct btrfs_mapping_tree *map_tree, u64 logical, u64 len)
3582{
3583 struct extent_map *em;
3584 struct map_lookup *map;
3585 struct extent_map_tree *em_tree = &map_tree->map_tree;
3586 int ret;
3587
890871be 3588 read_lock(&em_tree->lock);
f188591e 3589 em = lookup_extent_mapping(em_tree, logical, len);
890871be 3590 read_unlock(&em_tree->lock);
f188591e
CM
3591 BUG_ON(!em);
3592
3593 BUG_ON(em->start > logical || em->start + em->len < logical);
3594 map = (struct map_lookup *)em->bdev;
3595 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
3596 ret = map->num_stripes;
321aecc6
CM
3597 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
3598 ret = map->sub_stripes;
f188591e
CM
3599 else
3600 ret = 1;
3601 free_extent_map(em);
f188591e
CM
3602 return ret;
3603}
3604
dfe25020
CM
3605static int find_live_mirror(struct map_lookup *map, int first, int num,
3606 int optimal)
3607{
3608 int i;
3609 if (map->stripes[optimal].dev->bdev)
3610 return optimal;
3611 for (i = first; i < first + num; i++) {
3612 if (map->stripes[i].dev->bdev)
3613 return i;
3614 }
3615 /* we couldn't find one that doesn't fail. Just return something
3616 * and the io error handling code will clean up eventually
3617 */
3618 return optimal;
3619}
3620
f2d8d74d
CM
3621static int __btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
3622 u64 logical, u64 *length,
a1d3c478 3623 struct btrfs_bio **bbio_ret,
7eaceacc 3624 int mirror_num)
0b86a832
CM
3625{
3626 struct extent_map *em;
3627 struct map_lookup *map;
3628 struct extent_map_tree *em_tree = &map_tree->map_tree;
3629 u64 offset;
593060d7 3630 u64 stripe_offset;
fce3bb9a 3631 u64 stripe_end_offset;
593060d7 3632 u64 stripe_nr;
fce3bb9a
LD
3633 u64 stripe_nr_orig;
3634 u64 stripe_nr_end;
593060d7 3635 int stripe_index;
cea9e445 3636 int i;
de11cc12 3637 int ret = 0;
f2d8d74d 3638 int num_stripes;
a236aed1 3639 int max_errors = 0;
a1d3c478 3640 struct btrfs_bio *bbio = NULL;
0b86a832 3641
890871be 3642 read_lock(&em_tree->lock);
0b86a832 3643 em = lookup_extent_mapping(em_tree, logical, *length);
890871be 3644 read_unlock(&em_tree->lock);
f2d8d74d 3645
3b951516 3646 if (!em) {
d397712b
CM
3647 printk(KERN_CRIT "unable to find logical %llu len %llu\n",
3648 (unsigned long long)logical,
3649 (unsigned long long)*length);
f2d8d74d 3650 BUG();
3b951516 3651 }
0b86a832
CM
3652
3653 BUG_ON(em->start > logical || em->start + em->len < logical);
3654 map = (struct map_lookup *)em->bdev;
3655 offset = logical - em->start;
593060d7 3656
f188591e
CM
3657 if (mirror_num > map->num_stripes)
3658 mirror_num = 0;
3659
593060d7
CM
3660 stripe_nr = offset;
3661 /*
3662 * stripe_nr counts the total number of stripes we have to stride
3663 * to get to this block
3664 */
3665 do_div(stripe_nr, map->stripe_len);
3666
3667 stripe_offset = stripe_nr * map->stripe_len;
3668 BUG_ON(offset < stripe_offset);
3669
3670 /* stripe_offset is the offset of this block in its stripe*/
3671 stripe_offset = offset - stripe_offset;
3672
fce3bb9a
LD
3673 if (rw & REQ_DISCARD)
3674 *length = min_t(u64, em->len - offset, *length);
52ba6929 3675 else if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
cea9e445
CM
3676 /* we limit the length of each bio to what fits in a stripe */
3677 *length = min_t(u64, em->len - offset,
fce3bb9a 3678 map->stripe_len - stripe_offset);
cea9e445
CM
3679 } else {
3680 *length = em->len - offset;
3681 }
f2d8d74d 3682
a1d3c478 3683 if (!bbio_ret)
cea9e445
CM
3684 goto out;
3685
f2d8d74d 3686 num_stripes = 1;
cea9e445 3687 stripe_index = 0;
fce3bb9a
LD
3688 stripe_nr_orig = stripe_nr;
3689 stripe_nr_end = (offset + *length + map->stripe_len - 1) &
3690 (~(map->stripe_len - 1));
3691 do_div(stripe_nr_end, map->stripe_len);
3692 stripe_end_offset = stripe_nr_end * map->stripe_len -
3693 (offset + *length);
3694 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
3695 if (rw & REQ_DISCARD)
3696 num_stripes = min_t(u64, map->num_stripes,
3697 stripe_nr_end - stripe_nr_orig);
3698 stripe_index = do_div(stripe_nr, map->num_stripes);
3699 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
212a17ab 3700 if (rw & (REQ_WRITE | REQ_DISCARD))
f2d8d74d 3701 num_stripes = map->num_stripes;
2fff734f 3702 else if (mirror_num)
f188591e 3703 stripe_index = mirror_num - 1;
dfe25020
CM
3704 else {
3705 stripe_index = find_live_mirror(map, 0,
3706 map->num_stripes,
3707 current->pid % map->num_stripes);
a1d3c478 3708 mirror_num = stripe_index + 1;
dfe25020 3709 }
2fff734f 3710
611f0e00 3711 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
a1d3c478 3712 if (rw & (REQ_WRITE | REQ_DISCARD)) {
f2d8d74d 3713 num_stripes = map->num_stripes;
a1d3c478 3714 } else if (mirror_num) {
f188591e 3715 stripe_index = mirror_num - 1;
a1d3c478
JS
3716 } else {
3717 mirror_num = 1;
3718 }
2fff734f 3719
321aecc6
CM
3720 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
3721 int factor = map->num_stripes / map->sub_stripes;
321aecc6
CM
3722
3723 stripe_index = do_div(stripe_nr, factor);
3724 stripe_index *= map->sub_stripes;
3725
7eaceacc 3726 if (rw & REQ_WRITE)
f2d8d74d 3727 num_stripes = map->sub_stripes;
fce3bb9a
LD
3728 else if (rw & REQ_DISCARD)
3729 num_stripes = min_t(u64, map->sub_stripes *
3730 (stripe_nr_end - stripe_nr_orig),
3731 map->num_stripes);
321aecc6
CM
3732 else if (mirror_num)
3733 stripe_index += mirror_num - 1;
dfe25020
CM
3734 else {
3735 stripe_index = find_live_mirror(map, stripe_index,
3736 map->sub_stripes, stripe_index +
3737 current->pid % map->sub_stripes);
a1d3c478 3738 mirror_num = stripe_index + 1;
dfe25020 3739 }
8790d502
CM
3740 } else {
3741 /*
3742 * after this do_div call, stripe_nr is the number of stripes
3743 * on this device we have to walk to find the data, and
3744 * stripe_index is the number of our device in the stripe array
3745 */
3746 stripe_index = do_div(stripe_nr, map->num_stripes);
a1d3c478 3747 mirror_num = stripe_index + 1;
8790d502 3748 }
593060d7 3749 BUG_ON(stripe_index >= map->num_stripes);
cea9e445 3750
de11cc12
LZ
3751 bbio = kzalloc(btrfs_bio_size(num_stripes), GFP_NOFS);
3752 if (!bbio) {
3753 ret = -ENOMEM;
3754 goto out;
3755 }
3756 atomic_set(&bbio->error, 0);
3757
fce3bb9a 3758 if (rw & REQ_DISCARD) {
ec9ef7a1
LZ
3759 int factor = 0;
3760 int sub_stripes = 0;
3761 u64 stripes_per_dev = 0;
3762 u32 remaining_stripes = 0;
3763
3764 if (map->type &
3765 (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
3766 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
3767 sub_stripes = 1;
3768 else
3769 sub_stripes = map->sub_stripes;
3770
3771 factor = map->num_stripes / sub_stripes;
3772 stripes_per_dev = div_u64_rem(stripe_nr_end -
3773 stripe_nr_orig,
3774 factor,
3775 &remaining_stripes);
3776 }
3777
fce3bb9a 3778 for (i = 0; i < num_stripes; i++) {
a1d3c478 3779 bbio->stripes[i].physical =
f2d8d74d
CM
3780 map->stripes[stripe_index].physical +
3781 stripe_offset + stripe_nr * map->stripe_len;
a1d3c478 3782 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
fce3bb9a 3783
ec9ef7a1
LZ
3784 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
3785 BTRFS_BLOCK_GROUP_RAID10)) {
3786 bbio->stripes[i].length = stripes_per_dev *
3787 map->stripe_len;
3788 if (i / sub_stripes < remaining_stripes)
3789 bbio->stripes[i].length +=
3790 map->stripe_len;
3791 if (i < sub_stripes)
a1d3c478 3792 bbio->stripes[i].length -=
fce3bb9a 3793 stripe_offset;
ec9ef7a1
LZ
3794 if ((i / sub_stripes + 1) %
3795 sub_stripes == remaining_stripes)
a1d3c478 3796 bbio->stripes[i].length -=
fce3bb9a 3797 stripe_end_offset;
ec9ef7a1
LZ
3798 if (i == sub_stripes - 1)
3799 stripe_offset = 0;
fce3bb9a 3800 } else
a1d3c478 3801 bbio->stripes[i].length = *length;
fce3bb9a
LD
3802
3803 stripe_index++;
3804 if (stripe_index == map->num_stripes) {
3805 /* This could only happen for RAID0/10 */
3806 stripe_index = 0;
3807 stripe_nr++;
3808 }
3809 }
3810 } else {
3811 for (i = 0; i < num_stripes; i++) {
a1d3c478 3812 bbio->stripes[i].physical =
212a17ab
LT
3813 map->stripes[stripe_index].physical +
3814 stripe_offset +
3815 stripe_nr * map->stripe_len;
a1d3c478 3816 bbio->stripes[i].dev =
212a17ab 3817 map->stripes[stripe_index].dev;
fce3bb9a 3818 stripe_index++;
f2d8d74d 3819 }
593060d7 3820 }
de11cc12
LZ
3821
3822 if (rw & REQ_WRITE) {
3823 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
3824 BTRFS_BLOCK_GROUP_RAID10 |
3825 BTRFS_BLOCK_GROUP_DUP)) {
3826 max_errors = 1;
3827 }
f2d8d74d 3828 }
de11cc12
LZ
3829
3830 *bbio_ret = bbio;
3831 bbio->num_stripes = num_stripes;
3832 bbio->max_errors = max_errors;
3833 bbio->mirror_num = mirror_num;
cea9e445 3834out:
0b86a832 3835 free_extent_map(em);
de11cc12 3836 return ret;
0b86a832
CM
3837}
3838
f2d8d74d
CM
3839int btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
3840 u64 logical, u64 *length,
a1d3c478 3841 struct btrfs_bio **bbio_ret, int mirror_num)
f2d8d74d 3842{
a1d3c478 3843 return __btrfs_map_block(map_tree, rw, logical, length, bbio_ret,
7eaceacc 3844 mirror_num);
f2d8d74d
CM
3845}
3846
a512bbf8
YZ
3847int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
3848 u64 chunk_start, u64 physical, u64 devid,
3849 u64 **logical, int *naddrs, int *stripe_len)
3850{
3851 struct extent_map_tree *em_tree = &map_tree->map_tree;
3852 struct extent_map *em;
3853 struct map_lookup *map;
3854 u64 *buf;
3855 u64 bytenr;
3856 u64 length;
3857 u64 stripe_nr;
3858 int i, j, nr = 0;
3859
890871be 3860 read_lock(&em_tree->lock);
a512bbf8 3861 em = lookup_extent_mapping(em_tree, chunk_start, 1);
890871be 3862 read_unlock(&em_tree->lock);
a512bbf8
YZ
3863
3864 BUG_ON(!em || em->start != chunk_start);
3865 map = (struct map_lookup *)em->bdev;
3866
3867 length = em->len;
3868 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
3869 do_div(length, map->num_stripes / map->sub_stripes);
3870 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
3871 do_div(length, map->num_stripes);
3872
3873 buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
3874 BUG_ON(!buf);
3875
3876 for (i = 0; i < map->num_stripes; i++) {
3877 if (devid && map->stripes[i].dev->devid != devid)
3878 continue;
3879 if (map->stripes[i].physical > physical ||
3880 map->stripes[i].physical + length <= physical)
3881 continue;
3882
3883 stripe_nr = physical - map->stripes[i].physical;
3884 do_div(stripe_nr, map->stripe_len);
3885
3886 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
3887 stripe_nr = stripe_nr * map->num_stripes + i;
3888 do_div(stripe_nr, map->sub_stripes);
3889 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
3890 stripe_nr = stripe_nr * map->num_stripes + i;
3891 }
3892 bytenr = chunk_start + stripe_nr * map->stripe_len;
934d375b 3893 WARN_ON(nr >= map->num_stripes);
a512bbf8
YZ
3894 for (j = 0; j < nr; j++) {
3895 if (buf[j] == bytenr)
3896 break;
3897 }
934d375b
CM
3898 if (j == nr) {
3899 WARN_ON(nr >= map->num_stripes);
a512bbf8 3900 buf[nr++] = bytenr;
934d375b 3901 }
a512bbf8
YZ
3902 }
3903
a512bbf8
YZ
3904 *logical = buf;
3905 *naddrs = nr;
3906 *stripe_len = map->stripe_len;
3907
3908 free_extent_map(em);
3909 return 0;
f2d8d74d
CM
3910}
3911
a1d3c478 3912static void btrfs_end_bio(struct bio *bio, int err)
8790d502 3913{
a1d3c478 3914 struct btrfs_bio *bbio = bio->bi_private;
7d2b4daa 3915 int is_orig_bio = 0;
8790d502 3916
8790d502 3917 if (err)
a1d3c478 3918 atomic_inc(&bbio->error);
8790d502 3919
a1d3c478 3920 if (bio == bbio->orig_bio)
7d2b4daa
CM
3921 is_orig_bio = 1;
3922
a1d3c478 3923 if (atomic_dec_and_test(&bbio->stripes_pending)) {
7d2b4daa
CM
3924 if (!is_orig_bio) {
3925 bio_put(bio);
a1d3c478 3926 bio = bbio->orig_bio;
7d2b4daa 3927 }
a1d3c478
JS
3928 bio->bi_private = bbio->private;
3929 bio->bi_end_io = bbio->end_io;
2774b2ca
JS
3930 bio->bi_bdev = (struct block_device *)
3931 (unsigned long)bbio->mirror_num;
a236aed1
CM
3932 /* only send an error to the higher layers if it is
3933 * beyond the tolerance of the multi-bio
3934 */
a1d3c478 3935 if (atomic_read(&bbio->error) > bbio->max_errors) {
a236aed1 3936 err = -EIO;
5dbc8fca 3937 } else {
1259ab75
CM
3938 /*
3939 * this bio is actually up to date, we didn't
3940 * go over the max number of errors
3941 */
3942 set_bit(BIO_UPTODATE, &bio->bi_flags);
a236aed1 3943 err = 0;
1259ab75 3944 }
a1d3c478 3945 kfree(bbio);
8790d502
CM
3946
3947 bio_endio(bio, err);
7d2b4daa 3948 } else if (!is_orig_bio) {
8790d502
CM
3949 bio_put(bio);
3950 }
8790d502
CM
3951}
3952
8b712842
CM
3953struct async_sched {
3954 struct bio *bio;
3955 int rw;
3956 struct btrfs_fs_info *info;
3957 struct btrfs_work work;
3958};
3959
3960/*
3961 * see run_scheduled_bios for a description of why bios are collected for
3962 * async submit.
3963 *
3964 * This will add one bio to the pending list for a device and make sure
3965 * the work struct is scheduled.
3966 */
143bede5 3967static noinline void schedule_bio(struct btrfs_root *root,
a1b32a59
CM
3968 struct btrfs_device *device,
3969 int rw, struct bio *bio)
8b712842
CM
3970{
3971 int should_queue = 1;
ffbd517d 3972 struct btrfs_pending_bios *pending_bios;
8b712842
CM
3973
3974 /* don't bother with additional async steps for reads, right now */
7b6d91da 3975 if (!(rw & REQ_WRITE)) {
492bb6de 3976 bio_get(bio);
21adbd5c 3977 btrfsic_submit_bio(rw, bio);
492bb6de 3978 bio_put(bio);
143bede5 3979 return;
8b712842
CM
3980 }
3981
3982 /*
0986fe9e 3983 * nr_async_bios allows us to reliably return congestion to the
8b712842
CM
3984 * higher layers. Otherwise, the async bio makes it appear we have
3985 * made progress against dirty pages when we've really just put it
3986 * on a queue for later
3987 */
0986fe9e 3988 atomic_inc(&root->fs_info->nr_async_bios);
492bb6de 3989 WARN_ON(bio->bi_next);
8b712842
CM
3990 bio->bi_next = NULL;
3991 bio->bi_rw |= rw;
3992
3993 spin_lock(&device->io_lock);
7b6d91da 3994 if (bio->bi_rw & REQ_SYNC)
ffbd517d
CM
3995 pending_bios = &device->pending_sync_bios;
3996 else
3997 pending_bios = &device->pending_bios;
8b712842 3998
ffbd517d
CM
3999 if (pending_bios->tail)
4000 pending_bios->tail->bi_next = bio;
8b712842 4001
ffbd517d
CM
4002 pending_bios->tail = bio;
4003 if (!pending_bios->head)
4004 pending_bios->head = bio;
8b712842
CM
4005 if (device->running_pending)
4006 should_queue = 0;
4007
4008 spin_unlock(&device->io_lock);
4009
4010 if (should_queue)
1cc127b5
CM
4011 btrfs_queue_worker(&root->fs_info->submit_workers,
4012 &device->work);
8b712842
CM
4013}
4014
f188591e 4015int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
8b712842 4016 int mirror_num, int async_submit)
0b86a832
CM
4017{
4018 struct btrfs_mapping_tree *map_tree;
4019 struct btrfs_device *dev;
8790d502 4020 struct bio *first_bio = bio;
a62b9401 4021 u64 logical = (u64)bio->bi_sector << 9;
0b86a832
CM
4022 u64 length = 0;
4023 u64 map_length;
0b86a832 4024 int ret;
8790d502
CM
4025 int dev_nr = 0;
4026 int total_devs = 1;
a1d3c478 4027 struct btrfs_bio *bbio = NULL;
0b86a832 4028
f2d8d74d 4029 length = bio->bi_size;
0b86a832
CM
4030 map_tree = &root->fs_info->mapping_tree;
4031 map_length = length;
cea9e445 4032
a1d3c478 4033 ret = btrfs_map_block(map_tree, rw, logical, &map_length, &bbio,
f188591e 4034 mirror_num);
cea9e445
CM
4035 BUG_ON(ret);
4036
a1d3c478 4037 total_devs = bbio->num_stripes;
cea9e445 4038 if (map_length < length) {
d397712b
CM
4039 printk(KERN_CRIT "mapping failed logical %llu bio len %llu "
4040 "len %llu\n", (unsigned long long)logical,
4041 (unsigned long long)length,
4042 (unsigned long long)map_length);
cea9e445
CM
4043 BUG();
4044 }
a1d3c478
JS
4045
4046 bbio->orig_bio = first_bio;
4047 bbio->private = first_bio->bi_private;
4048 bbio->end_io = first_bio->bi_end_io;
4049 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
cea9e445 4050
d397712b 4051 while (dev_nr < total_devs) {
a1d3c478
JS
4052 if (dev_nr < total_devs - 1) {
4053 bio = bio_clone(first_bio, GFP_NOFS);
4054 BUG_ON(!bio);
4055 } else {
4056 bio = first_bio;
8790d502 4057 }
a1d3c478
JS
4058 bio->bi_private = bbio;
4059 bio->bi_end_io = btrfs_end_bio;
4060 bio->bi_sector = bbio->stripes[dev_nr].physical >> 9;
4061 dev = bbio->stripes[dev_nr].dev;
18e503d6 4062 if (dev && dev->bdev && (rw != WRITE || dev->writeable)) {
a1d3c478
JS
4063 pr_debug("btrfs_map_bio: rw %d, secor=%llu, dev=%lu "
4064 "(%s id %llu), size=%u\n", rw,
4065 (u64)bio->bi_sector, (u_long)dev->bdev->bd_dev,
4066 dev->name, dev->devid, bio->bi_size);
dfe25020 4067 bio->bi_bdev = dev->bdev;
8b712842
CM
4068 if (async_submit)
4069 schedule_bio(root, dev, rw, bio);
4070 else
21adbd5c 4071 btrfsic_submit_bio(rw, bio);
dfe25020
CM
4072 } else {
4073 bio->bi_bdev = root->fs_info->fs_devices->latest_bdev;
4074 bio->bi_sector = logical >> 9;
dfe25020 4075 bio_endio(bio, -EIO);
dfe25020 4076 }
8790d502
CM
4077 dev_nr++;
4078 }
0b86a832
CM
4079 return 0;
4080}
4081
a443755f 4082struct btrfs_device *btrfs_find_device(struct btrfs_root *root, u64 devid,
2b82032c 4083 u8 *uuid, u8 *fsid)
0b86a832 4084{
2b82032c
YZ
4085 struct btrfs_device *device;
4086 struct btrfs_fs_devices *cur_devices;
4087
4088 cur_devices = root->fs_info->fs_devices;
4089 while (cur_devices) {
4090 if (!fsid ||
4091 !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
4092 device = __find_device(&cur_devices->devices,
4093 devid, uuid);
4094 if (device)
4095 return device;
4096 }
4097 cur_devices = cur_devices->seed;
4098 }
4099 return NULL;
0b86a832
CM
4100}
4101
dfe25020
CM
4102static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
4103 u64 devid, u8 *dev_uuid)
4104{
4105 struct btrfs_device *device;
4106 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
4107
4108 device = kzalloc(sizeof(*device), GFP_NOFS);
7cbd8a83 4109 if (!device)
4110 return NULL;
dfe25020
CM
4111 list_add(&device->dev_list,
4112 &fs_devices->devices);
dfe25020
CM
4113 device->dev_root = root->fs_info->dev_root;
4114 device->devid = devid;
8b712842 4115 device->work.func = pending_bios_fn;
e4404d6e 4116 device->fs_devices = fs_devices;
cd02dca5 4117 device->missing = 1;
dfe25020 4118 fs_devices->num_devices++;
cd02dca5 4119 fs_devices->missing_devices++;
dfe25020 4120 spin_lock_init(&device->io_lock);
d20f7043 4121 INIT_LIST_HEAD(&device->dev_alloc_list);
dfe25020
CM
4122 memcpy(device->uuid, dev_uuid, BTRFS_UUID_SIZE);
4123 return device;
4124}
4125
0b86a832
CM
4126static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
4127 struct extent_buffer *leaf,
4128 struct btrfs_chunk *chunk)
4129{
4130 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4131 struct map_lookup *map;
4132 struct extent_map *em;
4133 u64 logical;
4134 u64 length;
4135 u64 devid;
a443755f 4136 u8 uuid[BTRFS_UUID_SIZE];
593060d7 4137 int num_stripes;
0b86a832 4138 int ret;
593060d7 4139 int i;
0b86a832 4140
e17cade2
CM
4141 logical = key->offset;
4142 length = btrfs_chunk_length(leaf, chunk);
a061fc8d 4143
890871be 4144 read_lock(&map_tree->map_tree.lock);
0b86a832 4145 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
890871be 4146 read_unlock(&map_tree->map_tree.lock);
0b86a832
CM
4147
4148 /* already mapped? */
4149 if (em && em->start <= logical && em->start + em->len > logical) {
4150 free_extent_map(em);
0b86a832
CM
4151 return 0;
4152 } else if (em) {
4153 free_extent_map(em);
4154 }
0b86a832 4155
172ddd60 4156 em = alloc_extent_map();
0b86a832
CM
4157 if (!em)
4158 return -ENOMEM;
593060d7
CM
4159 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
4160 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
0b86a832
CM
4161 if (!map) {
4162 free_extent_map(em);
4163 return -ENOMEM;
4164 }
4165
4166 em->bdev = (struct block_device *)map;
4167 em->start = logical;
4168 em->len = length;
4169 em->block_start = 0;
c8b97818 4170 em->block_len = em->len;
0b86a832 4171
593060d7
CM
4172 map->num_stripes = num_stripes;
4173 map->io_width = btrfs_chunk_io_width(leaf, chunk);
4174 map->io_align = btrfs_chunk_io_align(leaf, chunk);
4175 map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
4176 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
4177 map->type = btrfs_chunk_type(leaf, chunk);
321aecc6 4178 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
593060d7
CM
4179 for (i = 0; i < num_stripes; i++) {
4180 map->stripes[i].physical =
4181 btrfs_stripe_offset_nr(leaf, chunk, i);
4182 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
a443755f
CM
4183 read_extent_buffer(leaf, uuid, (unsigned long)
4184 btrfs_stripe_dev_uuid_nr(chunk, i),
4185 BTRFS_UUID_SIZE);
2b82032c
YZ
4186 map->stripes[i].dev = btrfs_find_device(root, devid, uuid,
4187 NULL);
dfe25020 4188 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
593060d7
CM
4189 kfree(map);
4190 free_extent_map(em);
4191 return -EIO;
4192 }
dfe25020
CM
4193 if (!map->stripes[i].dev) {
4194 map->stripes[i].dev =
4195 add_missing_dev(root, devid, uuid);
4196 if (!map->stripes[i].dev) {
4197 kfree(map);
4198 free_extent_map(em);
4199 return -EIO;
4200 }
4201 }
4202 map->stripes[i].dev->in_fs_metadata = 1;
0b86a832
CM
4203 }
4204
890871be 4205 write_lock(&map_tree->map_tree.lock);
0b86a832 4206 ret = add_extent_mapping(&map_tree->map_tree, em);
890871be 4207 write_unlock(&map_tree->map_tree.lock);
b248a415 4208 BUG_ON(ret);
0b86a832
CM
4209 free_extent_map(em);
4210
4211 return 0;
4212}
4213
143bede5 4214static void fill_device_from_item(struct extent_buffer *leaf,
0b86a832
CM
4215 struct btrfs_dev_item *dev_item,
4216 struct btrfs_device *device)
4217{
4218 unsigned long ptr;
0b86a832
CM
4219
4220 device->devid = btrfs_device_id(leaf, dev_item);
d6397bae
CB
4221 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
4222 device->total_bytes = device->disk_total_bytes;
0b86a832
CM
4223 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
4224 device->type = btrfs_device_type(leaf, dev_item);
4225 device->io_align = btrfs_device_io_align(leaf, dev_item);
4226 device->io_width = btrfs_device_io_width(leaf, dev_item);
4227 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
0b86a832
CM
4228
4229 ptr = (unsigned long)btrfs_device_uuid(dev_item);
e17cade2 4230 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
0b86a832
CM
4231}
4232
2b82032c
YZ
4233static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
4234{
4235 struct btrfs_fs_devices *fs_devices;
4236 int ret;
4237
b367e47f 4238 BUG_ON(!mutex_is_locked(&uuid_mutex));
2b82032c
YZ
4239
4240 fs_devices = root->fs_info->fs_devices->seed;
4241 while (fs_devices) {
4242 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
4243 ret = 0;
4244 goto out;
4245 }
4246 fs_devices = fs_devices->seed;
4247 }
4248
4249 fs_devices = find_fsid(fsid);
4250 if (!fs_devices) {
4251 ret = -ENOENT;
4252 goto out;
4253 }
e4404d6e
YZ
4254
4255 fs_devices = clone_fs_devices(fs_devices);
4256 if (IS_ERR(fs_devices)) {
4257 ret = PTR_ERR(fs_devices);
2b82032c
YZ
4258 goto out;
4259 }
4260
97288f2c 4261 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
15916de8 4262 root->fs_info->bdev_holder);
2b82032c
YZ
4263 if (ret)
4264 goto out;
4265
4266 if (!fs_devices->seeding) {
4267 __btrfs_close_devices(fs_devices);
e4404d6e 4268 free_fs_devices(fs_devices);
2b82032c
YZ
4269 ret = -EINVAL;
4270 goto out;
4271 }
4272
4273 fs_devices->seed = root->fs_info->fs_devices->seed;
4274 root->fs_info->fs_devices->seed = fs_devices;
2b82032c 4275out:
2b82032c
YZ
4276 return ret;
4277}
4278
0d81ba5d 4279static int read_one_dev(struct btrfs_root *root,
0b86a832
CM
4280 struct extent_buffer *leaf,
4281 struct btrfs_dev_item *dev_item)
4282{
4283 struct btrfs_device *device;
4284 u64 devid;
4285 int ret;
2b82032c 4286 u8 fs_uuid[BTRFS_UUID_SIZE];
a443755f
CM
4287 u8 dev_uuid[BTRFS_UUID_SIZE];
4288
0b86a832 4289 devid = btrfs_device_id(leaf, dev_item);
a443755f
CM
4290 read_extent_buffer(leaf, dev_uuid,
4291 (unsigned long)btrfs_device_uuid(dev_item),
4292 BTRFS_UUID_SIZE);
2b82032c
YZ
4293 read_extent_buffer(leaf, fs_uuid,
4294 (unsigned long)btrfs_device_fsid(dev_item),
4295 BTRFS_UUID_SIZE);
4296
4297 if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
4298 ret = open_seed_devices(root, fs_uuid);
e4404d6e 4299 if (ret && !btrfs_test_opt(root, DEGRADED))
2b82032c 4300 return ret;
2b82032c
YZ
4301 }
4302
4303 device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
4304 if (!device || !device->bdev) {
e4404d6e 4305 if (!btrfs_test_opt(root, DEGRADED))
2b82032c
YZ
4306 return -EIO;
4307
4308 if (!device) {
d397712b
CM
4309 printk(KERN_WARNING "warning devid %llu missing\n",
4310 (unsigned long long)devid);
2b82032c
YZ
4311 device = add_missing_dev(root, devid, dev_uuid);
4312 if (!device)
4313 return -ENOMEM;
cd02dca5
CM
4314 } else if (!device->missing) {
4315 /*
4316 * this happens when a device that was properly setup
4317 * in the device info lists suddenly goes bad.
4318 * device->bdev is NULL, and so we have to set
4319 * device->missing to one here
4320 */
4321 root->fs_info->fs_devices->missing_devices++;
4322 device->missing = 1;
2b82032c
YZ
4323 }
4324 }
4325
4326 if (device->fs_devices != root->fs_info->fs_devices) {
4327 BUG_ON(device->writeable);
4328 if (device->generation !=
4329 btrfs_device_generation(leaf, dev_item))
4330 return -EINVAL;
6324fbf3 4331 }
0b86a832
CM
4332
4333 fill_device_from_item(leaf, dev_item, device);
4334 device->dev_root = root->fs_info->dev_root;
dfe25020 4335 device->in_fs_metadata = 1;
2bf64758 4336 if (device->writeable) {
2b82032c 4337 device->fs_devices->total_rw_bytes += device->total_bytes;
2bf64758
JB
4338 spin_lock(&root->fs_info->free_chunk_lock);
4339 root->fs_info->free_chunk_space += device->total_bytes -
4340 device->bytes_used;
4341 spin_unlock(&root->fs_info->free_chunk_lock);
4342 }
0b86a832 4343 ret = 0;
0b86a832
CM
4344 return ret;
4345}
4346
e4404d6e 4347int btrfs_read_sys_array(struct btrfs_root *root)
0b86a832 4348{
6c41761f 4349 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
a061fc8d 4350 struct extent_buffer *sb;
0b86a832 4351 struct btrfs_disk_key *disk_key;
0b86a832 4352 struct btrfs_chunk *chunk;
84eed90f
CM
4353 u8 *ptr;
4354 unsigned long sb_ptr;
4355 int ret = 0;
0b86a832
CM
4356 u32 num_stripes;
4357 u32 array_size;
4358 u32 len = 0;
0b86a832 4359 u32 cur;
84eed90f 4360 struct btrfs_key key;
0b86a832 4361
e4404d6e 4362 sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
a061fc8d
CM
4363 BTRFS_SUPER_INFO_SIZE);
4364 if (!sb)
4365 return -ENOMEM;
4366 btrfs_set_buffer_uptodate(sb);
85d4e461 4367 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
8a334426
DS
4368 /*
4369 * The sb extent buffer is artifical and just used to read the system array.
4370 * btrfs_set_buffer_uptodate() call does not properly mark all it's
4371 * pages up-to-date when the page is larger: extent does not cover the
4372 * whole page and consequently check_page_uptodate does not find all
4373 * the page's extents up-to-date (the hole beyond sb),
4374 * write_extent_buffer then triggers a WARN_ON.
4375 *
4376 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
4377 * but sb spans only this function. Add an explicit SetPageUptodate call
4378 * to silence the warning eg. on PowerPC 64.
4379 */
4380 if (PAGE_CACHE_SIZE > BTRFS_SUPER_INFO_SIZE)
4381 SetPageUptodate(sb->first_page);
4008c04a 4382
a061fc8d 4383 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
0b86a832
CM
4384 array_size = btrfs_super_sys_array_size(super_copy);
4385
0b86a832
CM
4386 ptr = super_copy->sys_chunk_array;
4387 sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
4388 cur = 0;
4389
4390 while (cur < array_size) {
4391 disk_key = (struct btrfs_disk_key *)ptr;
4392 btrfs_disk_key_to_cpu(&key, disk_key);
4393
a061fc8d 4394 len = sizeof(*disk_key); ptr += len;
0b86a832
CM
4395 sb_ptr += len;
4396 cur += len;
4397
0d81ba5d 4398 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
0b86a832 4399 chunk = (struct btrfs_chunk *)sb_ptr;
0d81ba5d 4400 ret = read_one_chunk(root, &key, sb, chunk);
84eed90f
CM
4401 if (ret)
4402 break;
0b86a832
CM
4403 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
4404 len = btrfs_chunk_item_size(num_stripes);
4405 } else {
84eed90f
CM
4406 ret = -EIO;
4407 break;
0b86a832
CM
4408 }
4409 ptr += len;
4410 sb_ptr += len;
4411 cur += len;
4412 }
a061fc8d 4413 free_extent_buffer(sb);
84eed90f 4414 return ret;
0b86a832
CM
4415}
4416
4417int btrfs_read_chunk_tree(struct btrfs_root *root)
4418{
4419 struct btrfs_path *path;
4420 struct extent_buffer *leaf;
4421 struct btrfs_key key;
4422 struct btrfs_key found_key;
4423 int ret;
4424 int slot;
4425
4426 root = root->fs_info->chunk_root;
4427
4428 path = btrfs_alloc_path();
4429 if (!path)
4430 return -ENOMEM;
4431
b367e47f
LZ
4432 mutex_lock(&uuid_mutex);
4433 lock_chunks(root);
4434
0b86a832
CM
4435 /* first we search for all of the device items, and then we
4436 * read in all of the chunk items. This way we can create chunk
4437 * mappings that reference all of the devices that are afound
4438 */
4439 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
4440 key.offset = 0;
4441 key.type = 0;
4442again:
4443 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
ab59381e
ZL
4444 if (ret < 0)
4445 goto error;
d397712b 4446 while (1) {
0b86a832
CM
4447 leaf = path->nodes[0];
4448 slot = path->slots[0];
4449 if (slot >= btrfs_header_nritems(leaf)) {
4450 ret = btrfs_next_leaf(root, path);
4451 if (ret == 0)
4452 continue;
4453 if (ret < 0)
4454 goto error;
4455 break;
4456 }
4457 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4458 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
4459 if (found_key.objectid != BTRFS_DEV_ITEMS_OBJECTID)
4460 break;
4461 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
4462 struct btrfs_dev_item *dev_item;
4463 dev_item = btrfs_item_ptr(leaf, slot,
4464 struct btrfs_dev_item);
0d81ba5d 4465 ret = read_one_dev(root, leaf, dev_item);
2b82032c
YZ
4466 if (ret)
4467 goto error;
0b86a832
CM
4468 }
4469 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
4470 struct btrfs_chunk *chunk;
4471 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4472 ret = read_one_chunk(root, &found_key, leaf, chunk);
2b82032c
YZ
4473 if (ret)
4474 goto error;
0b86a832
CM
4475 }
4476 path->slots[0]++;
4477 }
4478 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
4479 key.objectid = 0;
b3b4aa74 4480 btrfs_release_path(path);
0b86a832
CM
4481 goto again;
4482 }
0b86a832
CM
4483 ret = 0;
4484error:
b367e47f
LZ
4485 unlock_chunks(root);
4486 mutex_unlock(&uuid_mutex);
4487
2b82032c 4488 btrfs_free_path(path);
0b86a832
CM
4489 return ret;
4490}