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