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