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