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