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