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