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