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