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