Btrfs: profiles filter
[firefly-linux-kernel-4.4.55.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 <asm/div64.h>
27 #include "compat.h"
28 #include "ctree.h"
29 #include "extent_map.h"
30 #include "disk-io.h"
31 #include "transaction.h"
32 #include "print-tree.h"
33 #include "volumes.h"
34 #include "async-thread.h"
35
36 static int init_first_rw_device(struct btrfs_trans_handle *trans,
37                                 struct btrfs_root *root,
38                                 struct btrfs_device *device);
39 static int btrfs_relocate_sys_chunks(struct btrfs_root *root);
40
41 static DEFINE_MUTEX(uuid_mutex);
42 static LIST_HEAD(fs_uuids);
43
44 static void lock_chunks(struct btrfs_root *root)
45 {
46         mutex_lock(&root->fs_info->chunk_mutex);
47 }
48
49 static void unlock_chunks(struct btrfs_root *root)
50 {
51         mutex_unlock(&root->fs_info->chunk_mutex);
52 }
53
54 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
55 {
56         struct btrfs_device *device;
57         WARN_ON(fs_devices->opened);
58         while (!list_empty(&fs_devices->devices)) {
59                 device = list_entry(fs_devices->devices.next,
60                                     struct btrfs_device, dev_list);
61                 list_del(&device->dev_list);
62                 kfree(device->name);
63                 kfree(device);
64         }
65         kfree(fs_devices);
66 }
67
68 int btrfs_cleanup_fs_uuids(void)
69 {
70         struct btrfs_fs_devices *fs_devices;
71
72         while (!list_empty(&fs_uuids)) {
73                 fs_devices = list_entry(fs_uuids.next,
74                                         struct btrfs_fs_devices, list);
75                 list_del(&fs_devices->list);
76                 free_fs_devices(fs_devices);
77         }
78         return 0;
79 }
80
81 static noinline struct btrfs_device *__find_device(struct list_head *head,
82                                                    u64 devid, u8 *uuid)
83 {
84         struct btrfs_device *dev;
85
86         list_for_each_entry(dev, head, dev_list) {
87                 if (dev->devid == devid &&
88                     (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
89                         return dev;
90                 }
91         }
92         return NULL;
93 }
94
95 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
96 {
97         struct btrfs_fs_devices *fs_devices;
98
99         list_for_each_entry(fs_devices, &fs_uuids, list) {
100                 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
101                         return fs_devices;
102         }
103         return NULL;
104 }
105
106 static void requeue_list(struct btrfs_pending_bios *pending_bios,
107                         struct bio *head, struct bio *tail)
108 {
109
110         struct bio *old_head;
111
112         old_head = pending_bios->head;
113         pending_bios->head = head;
114         if (pending_bios->tail)
115                 tail->bi_next = old_head;
116         else
117                 pending_bios->tail = tail;
118 }
119
120 /*
121  * we try to collect pending bios for a device so we don't get a large
122  * number of procs sending bios down to the same device.  This greatly
123  * improves the schedulers ability to collect and merge the bios.
124  *
125  * But, it also turns into a long list of bios to process and that is sure
126  * to eventually make the worker thread block.  The solution here is to
127  * make some progress and then put this work struct back at the end of
128  * the list if the block device is congested.  This way, multiple devices
129  * can make progress from a single worker thread.
130  */
131 static noinline int run_scheduled_bios(struct btrfs_device *device)
132 {
133         struct bio *pending;
134         struct backing_dev_info *bdi;
135         struct btrfs_fs_info *fs_info;
136         struct btrfs_pending_bios *pending_bios;
137         struct bio *tail;
138         struct bio *cur;
139         int again = 0;
140         unsigned long num_run;
141         unsigned long batch_run = 0;
142         unsigned long limit;
143         unsigned long last_waited = 0;
144         int force_reg = 0;
145         int sync_pending = 0;
146         struct blk_plug plug;
147
148         /*
149          * this function runs all the bios we've collected for
150          * a particular device.  We don't want to wander off to
151          * another device without first sending all of these down.
152          * So, setup a plug here and finish it off before we return
153          */
154         blk_start_plug(&plug);
155
156         bdi = blk_get_backing_dev_info(device->bdev);
157         fs_info = device->dev_root->fs_info;
158         limit = btrfs_async_submit_limit(fs_info);
159         limit = limit * 2 / 3;
160
161 loop:
162         spin_lock(&device->io_lock);
163
164 loop_lock:
165         num_run = 0;
166
167         /* take all the bios off the list at once and process them
168          * later on (without the lock held).  But, remember the
169          * tail and other pointers so the bios can be properly reinserted
170          * into the list if we hit congestion
171          */
172         if (!force_reg && device->pending_sync_bios.head) {
173                 pending_bios = &device->pending_sync_bios;
174                 force_reg = 1;
175         } else {
176                 pending_bios = &device->pending_bios;
177                 force_reg = 0;
178         }
179
180         pending = pending_bios->head;
181         tail = pending_bios->tail;
182         WARN_ON(pending && !tail);
183
184         /*
185          * if pending was null this time around, no bios need processing
186          * at all and we can stop.  Otherwise it'll loop back up again
187          * and do an additional check so no bios are missed.
188          *
189          * device->running_pending is used to synchronize with the
190          * schedule_bio code.
191          */
192         if (device->pending_sync_bios.head == NULL &&
193             device->pending_bios.head == NULL) {
194                 again = 0;
195                 device->running_pending = 0;
196         } else {
197                 again = 1;
198                 device->running_pending = 1;
199         }
200
201         pending_bios->head = NULL;
202         pending_bios->tail = NULL;
203
204         spin_unlock(&device->io_lock);
205
206         while (pending) {
207
208                 rmb();
209                 /* we want to work on both lists, but do more bios on the
210                  * sync list than the regular list
211                  */
212                 if ((num_run > 32 &&
213                     pending_bios != &device->pending_sync_bios &&
214                     device->pending_sync_bios.head) ||
215                    (num_run > 64 && pending_bios == &device->pending_sync_bios &&
216                     device->pending_bios.head)) {
217                         spin_lock(&device->io_lock);
218                         requeue_list(pending_bios, pending, tail);
219                         goto loop_lock;
220                 }
221
222                 cur = pending;
223                 pending = pending->bi_next;
224                 cur->bi_next = NULL;
225                 atomic_dec(&fs_info->nr_async_bios);
226
227                 if (atomic_read(&fs_info->nr_async_bios) < limit &&
228                     waitqueue_active(&fs_info->async_submit_wait))
229                         wake_up(&fs_info->async_submit_wait);
230
231                 BUG_ON(atomic_read(&cur->bi_cnt) == 0);
232
233                 /*
234                  * if we're doing the sync list, record that our
235                  * plug has some sync requests on it
236                  *
237                  * If we're doing the regular list and there are
238                  * sync requests sitting around, unplug before
239                  * we add more
240                  */
241                 if (pending_bios == &device->pending_sync_bios) {
242                         sync_pending = 1;
243                 } else if (sync_pending) {
244                         blk_finish_plug(&plug);
245                         blk_start_plug(&plug);
246                         sync_pending = 0;
247                 }
248
249                 submit_bio(cur->bi_rw, cur);
250                 num_run++;
251                 batch_run++;
252                 if (need_resched())
253                         cond_resched();
254
255                 /*
256                  * we made progress, there is more work to do and the bdi
257                  * is now congested.  Back off and let other work structs
258                  * run instead
259                  */
260                 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
261                     fs_info->fs_devices->open_devices > 1) {
262                         struct io_context *ioc;
263
264                         ioc = current->io_context;
265
266                         /*
267                          * the main goal here is that we don't want to
268                          * block if we're going to be able to submit
269                          * more requests without blocking.
270                          *
271                          * This code does two great things, it pokes into
272                          * the elevator code from a filesystem _and_
273                          * it makes assumptions about how batching works.
274                          */
275                         if (ioc && ioc->nr_batch_requests > 0 &&
276                             time_before(jiffies, ioc->last_waited + HZ/50UL) &&
277                             (last_waited == 0 ||
278                              ioc->last_waited == last_waited)) {
279                                 /*
280                                  * we want to go through our batch of
281                                  * requests and stop.  So, we copy out
282                                  * the ioc->last_waited time and test
283                                  * against it before looping
284                                  */
285                                 last_waited = ioc->last_waited;
286                                 if (need_resched())
287                                         cond_resched();
288                                 continue;
289                         }
290                         spin_lock(&device->io_lock);
291                         requeue_list(pending_bios, pending, tail);
292                         device->running_pending = 1;
293
294                         spin_unlock(&device->io_lock);
295                         btrfs_requeue_work(&device->work);
296                         goto done;
297                 }
298                 /* unplug every 64 requests just for good measure */
299                 if (batch_run % 64 == 0) {
300                         blk_finish_plug(&plug);
301                         blk_start_plug(&plug);
302                         sync_pending = 0;
303                 }
304         }
305
306         cond_resched();
307         if (again)
308                 goto loop;
309
310         spin_lock(&device->io_lock);
311         if (device->pending_bios.head || device->pending_sync_bios.head)
312                 goto loop_lock;
313         spin_unlock(&device->io_lock);
314
315 done:
316         blk_finish_plug(&plug);
317         return 0;
318 }
319
320 static void pending_bios_fn(struct btrfs_work *work)
321 {
322         struct btrfs_device *device;
323
324         device = container_of(work, struct btrfs_device, work);
325         run_scheduled_bios(device);
326 }
327
328 static noinline int device_list_add(const char *path,
329                            struct btrfs_super_block *disk_super,
330                            u64 devid, struct btrfs_fs_devices **fs_devices_ret)
331 {
332         struct btrfs_device *device;
333         struct btrfs_fs_devices *fs_devices;
334         u64 found_transid = btrfs_super_generation(disk_super);
335         char *name;
336
337         fs_devices = find_fsid(disk_super->fsid);
338         if (!fs_devices) {
339                 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
340                 if (!fs_devices)
341                         return -ENOMEM;
342                 INIT_LIST_HEAD(&fs_devices->devices);
343                 INIT_LIST_HEAD(&fs_devices->alloc_list);
344                 list_add(&fs_devices->list, &fs_uuids);
345                 memcpy(fs_devices->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
346                 fs_devices->latest_devid = devid;
347                 fs_devices->latest_trans = found_transid;
348                 mutex_init(&fs_devices->device_list_mutex);
349                 device = NULL;
350         } else {
351                 device = __find_device(&fs_devices->devices, devid,
352                                        disk_super->dev_item.uuid);
353         }
354         if (!device) {
355                 if (fs_devices->opened)
356                         return -EBUSY;
357
358                 device = kzalloc(sizeof(*device), GFP_NOFS);
359                 if (!device) {
360                         /* we can safely leave the fs_devices entry around */
361                         return -ENOMEM;
362                 }
363                 device->devid = devid;
364                 device->work.func = pending_bios_fn;
365                 memcpy(device->uuid, disk_super->dev_item.uuid,
366                        BTRFS_UUID_SIZE);
367                 spin_lock_init(&device->io_lock);
368                 device->name = kstrdup(path, GFP_NOFS);
369                 if (!device->name) {
370                         kfree(device);
371                         return -ENOMEM;
372                 }
373                 INIT_LIST_HEAD(&device->dev_alloc_list);
374
375                 /* init readahead state */
376                 spin_lock_init(&device->reada_lock);
377                 device->reada_curr_zone = NULL;
378                 atomic_set(&device->reada_in_flight, 0);
379                 device->reada_next = 0;
380                 INIT_RADIX_TREE(&device->reada_zones, GFP_NOFS & ~__GFP_WAIT);
381                 INIT_RADIX_TREE(&device->reada_extents, GFP_NOFS & ~__GFP_WAIT);
382
383                 mutex_lock(&fs_devices->device_list_mutex);
384                 list_add_rcu(&device->dev_list, &fs_devices->devices);
385                 mutex_unlock(&fs_devices->device_list_mutex);
386
387                 device->fs_devices = fs_devices;
388                 fs_devices->num_devices++;
389         } else if (!device->name || strcmp(device->name, path)) {
390                 name = kstrdup(path, GFP_NOFS);
391                 if (!name)
392                         return -ENOMEM;
393                 kfree(device->name);
394                 device->name = name;
395                 if (device->missing) {
396                         fs_devices->missing_devices--;
397                         device->missing = 0;
398                 }
399         }
400
401         if (found_transid > fs_devices->latest_trans) {
402                 fs_devices->latest_devid = devid;
403                 fs_devices->latest_trans = found_transid;
404         }
405         *fs_devices_ret = fs_devices;
406         return 0;
407 }
408
409 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
410 {
411         struct btrfs_fs_devices *fs_devices;
412         struct btrfs_device *device;
413         struct btrfs_device *orig_dev;
414
415         fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
416         if (!fs_devices)
417                 return ERR_PTR(-ENOMEM);
418
419         INIT_LIST_HEAD(&fs_devices->devices);
420         INIT_LIST_HEAD(&fs_devices->alloc_list);
421         INIT_LIST_HEAD(&fs_devices->list);
422         mutex_init(&fs_devices->device_list_mutex);
423         fs_devices->latest_devid = orig->latest_devid;
424         fs_devices->latest_trans = orig->latest_trans;
425         memcpy(fs_devices->fsid, orig->fsid, sizeof(fs_devices->fsid));
426
427         /* We have held the volume lock, it is safe to get the devices. */
428         list_for_each_entry(orig_dev, &orig->devices, dev_list) {
429                 device = kzalloc(sizeof(*device), GFP_NOFS);
430                 if (!device)
431                         goto error;
432
433                 device->name = kstrdup(orig_dev->name, GFP_NOFS);
434                 if (!device->name) {
435                         kfree(device);
436                         goto error;
437                 }
438
439                 device->devid = orig_dev->devid;
440                 device->work.func = pending_bios_fn;
441                 memcpy(device->uuid, orig_dev->uuid, sizeof(device->uuid));
442                 spin_lock_init(&device->io_lock);
443                 INIT_LIST_HEAD(&device->dev_list);
444                 INIT_LIST_HEAD(&device->dev_alloc_list);
445
446                 list_add(&device->dev_list, &fs_devices->devices);
447                 device->fs_devices = fs_devices;
448                 fs_devices->num_devices++;
449         }
450         return fs_devices;
451 error:
452         free_fs_devices(fs_devices);
453         return ERR_PTR(-ENOMEM);
454 }
455
456 int btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices)
457 {
458         struct btrfs_device *device, *next;
459
460         mutex_lock(&uuid_mutex);
461 again:
462         /* This is the initialized path, it is safe to release the devices. */
463         list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
464                 if (device->in_fs_metadata)
465                         continue;
466
467                 if (device->bdev) {
468                         blkdev_put(device->bdev, device->mode);
469                         device->bdev = NULL;
470                         fs_devices->open_devices--;
471                 }
472                 if (device->writeable) {
473                         list_del_init(&device->dev_alloc_list);
474                         device->writeable = 0;
475                         fs_devices->rw_devices--;
476                 }
477                 list_del_init(&device->dev_list);
478                 fs_devices->num_devices--;
479                 kfree(device->name);
480                 kfree(device);
481         }
482
483         if (fs_devices->seed) {
484                 fs_devices = fs_devices->seed;
485                 goto again;
486         }
487
488         mutex_unlock(&uuid_mutex);
489         return 0;
490 }
491
492 static void __free_device(struct work_struct *work)
493 {
494         struct btrfs_device *device;
495
496         device = container_of(work, struct btrfs_device, rcu_work);
497
498         if (device->bdev)
499                 blkdev_put(device->bdev, device->mode);
500
501         kfree(device->name);
502         kfree(device);
503 }
504
505 static void free_device(struct rcu_head *head)
506 {
507         struct btrfs_device *device;
508
509         device = container_of(head, struct btrfs_device, rcu);
510
511         INIT_WORK(&device->rcu_work, __free_device);
512         schedule_work(&device->rcu_work);
513 }
514
515 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
516 {
517         struct btrfs_device *device;
518
519         if (--fs_devices->opened > 0)
520                 return 0;
521
522         mutex_lock(&fs_devices->device_list_mutex);
523         list_for_each_entry(device, &fs_devices->devices, dev_list) {
524                 struct btrfs_device *new_device;
525
526                 if (device->bdev)
527                         fs_devices->open_devices--;
528
529                 if (device->writeable) {
530                         list_del_init(&device->dev_alloc_list);
531                         fs_devices->rw_devices--;
532                 }
533
534                 if (device->can_discard)
535                         fs_devices->num_can_discard--;
536
537                 new_device = kmalloc(sizeof(*new_device), GFP_NOFS);
538                 BUG_ON(!new_device);
539                 memcpy(new_device, device, sizeof(*new_device));
540                 new_device->name = kstrdup(device->name, GFP_NOFS);
541                 BUG_ON(device->name && !new_device->name);
542                 new_device->bdev = NULL;
543                 new_device->writeable = 0;
544                 new_device->in_fs_metadata = 0;
545                 new_device->can_discard = 0;
546                 list_replace_rcu(&device->dev_list, &new_device->dev_list);
547
548                 call_rcu(&device->rcu, free_device);
549         }
550         mutex_unlock(&fs_devices->device_list_mutex);
551
552         WARN_ON(fs_devices->open_devices);
553         WARN_ON(fs_devices->rw_devices);
554         fs_devices->opened = 0;
555         fs_devices->seeding = 0;
556
557         return 0;
558 }
559
560 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
561 {
562         struct btrfs_fs_devices *seed_devices = NULL;
563         int ret;
564
565         mutex_lock(&uuid_mutex);
566         ret = __btrfs_close_devices(fs_devices);
567         if (!fs_devices->opened) {
568                 seed_devices = fs_devices->seed;
569                 fs_devices->seed = NULL;
570         }
571         mutex_unlock(&uuid_mutex);
572
573         while (seed_devices) {
574                 fs_devices = seed_devices;
575                 seed_devices = fs_devices->seed;
576                 __btrfs_close_devices(fs_devices);
577                 free_fs_devices(fs_devices);
578         }
579         return ret;
580 }
581
582 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
583                                 fmode_t flags, void *holder)
584 {
585         struct request_queue *q;
586         struct block_device *bdev;
587         struct list_head *head = &fs_devices->devices;
588         struct btrfs_device *device;
589         struct block_device *latest_bdev = NULL;
590         struct buffer_head *bh;
591         struct btrfs_super_block *disk_super;
592         u64 latest_devid = 0;
593         u64 latest_transid = 0;
594         u64 devid;
595         int seeding = 1;
596         int ret = 0;
597
598         flags |= FMODE_EXCL;
599
600         list_for_each_entry(device, head, dev_list) {
601                 if (device->bdev)
602                         continue;
603                 if (!device->name)
604                         continue;
605
606                 bdev = blkdev_get_by_path(device->name, flags, holder);
607                 if (IS_ERR(bdev)) {
608                         printk(KERN_INFO "open %s failed\n", device->name);
609                         goto error;
610                 }
611                 set_blocksize(bdev, 4096);
612
613                 bh = btrfs_read_dev_super(bdev);
614                 if (!bh)
615                         goto error_close;
616
617                 disk_super = (struct btrfs_super_block *)bh->b_data;
618                 devid = btrfs_stack_device_id(&disk_super->dev_item);
619                 if (devid != device->devid)
620                         goto error_brelse;
621
622                 if (memcmp(device->uuid, disk_super->dev_item.uuid,
623                            BTRFS_UUID_SIZE))
624                         goto error_brelse;
625
626                 device->generation = btrfs_super_generation(disk_super);
627                 if (!latest_transid || device->generation > latest_transid) {
628                         latest_devid = devid;
629                         latest_transid = device->generation;
630                         latest_bdev = bdev;
631                 }
632
633                 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
634                         device->writeable = 0;
635                 } else {
636                         device->writeable = !bdev_read_only(bdev);
637                         seeding = 0;
638                 }
639
640                 q = bdev_get_queue(bdev);
641                 if (blk_queue_discard(q)) {
642                         device->can_discard = 1;
643                         fs_devices->num_can_discard++;
644                 }
645
646                 device->bdev = bdev;
647                 device->in_fs_metadata = 0;
648                 device->mode = flags;
649
650                 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
651                         fs_devices->rotating = 1;
652
653                 fs_devices->open_devices++;
654                 if (device->writeable) {
655                         fs_devices->rw_devices++;
656                         list_add(&device->dev_alloc_list,
657                                  &fs_devices->alloc_list);
658                 }
659                 brelse(bh);
660                 continue;
661
662 error_brelse:
663                 brelse(bh);
664 error_close:
665                 blkdev_put(bdev, flags);
666 error:
667                 continue;
668         }
669         if (fs_devices->open_devices == 0) {
670                 ret = -EINVAL;
671                 goto out;
672         }
673         fs_devices->seeding = seeding;
674         fs_devices->opened = 1;
675         fs_devices->latest_bdev = latest_bdev;
676         fs_devices->latest_devid = latest_devid;
677         fs_devices->latest_trans = latest_transid;
678         fs_devices->total_rw_bytes = 0;
679 out:
680         return ret;
681 }
682
683 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
684                        fmode_t flags, void *holder)
685 {
686         int ret;
687
688         mutex_lock(&uuid_mutex);
689         if (fs_devices->opened) {
690                 fs_devices->opened++;
691                 ret = 0;
692         } else {
693                 ret = __btrfs_open_devices(fs_devices, flags, holder);
694         }
695         mutex_unlock(&uuid_mutex);
696         return ret;
697 }
698
699 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
700                           struct btrfs_fs_devices **fs_devices_ret)
701 {
702         struct btrfs_super_block *disk_super;
703         struct block_device *bdev;
704         struct buffer_head *bh;
705         int ret;
706         u64 devid;
707         u64 transid;
708
709         mutex_lock(&uuid_mutex);
710
711         flags |= FMODE_EXCL;
712         bdev = blkdev_get_by_path(path, flags, holder);
713
714         if (IS_ERR(bdev)) {
715                 ret = PTR_ERR(bdev);
716                 goto error;
717         }
718
719         ret = set_blocksize(bdev, 4096);
720         if (ret)
721                 goto error_close;
722         bh = btrfs_read_dev_super(bdev);
723         if (!bh) {
724                 ret = -EINVAL;
725                 goto error_close;
726         }
727         disk_super = (struct btrfs_super_block *)bh->b_data;
728         devid = btrfs_stack_device_id(&disk_super->dev_item);
729         transid = btrfs_super_generation(disk_super);
730         if (disk_super->label[0])
731                 printk(KERN_INFO "device label %s ", disk_super->label);
732         else
733                 printk(KERN_INFO "device fsid %pU ", disk_super->fsid);
734         printk(KERN_CONT "devid %llu transid %llu %s\n",
735                (unsigned long long)devid, (unsigned long long)transid, path);
736         ret = device_list_add(path, disk_super, devid, fs_devices_ret);
737
738         brelse(bh);
739 error_close:
740         blkdev_put(bdev, flags);
741 error:
742         mutex_unlock(&uuid_mutex);
743         return ret;
744 }
745
746 /* helper to account the used device space in the range */
747 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
748                                    u64 end, u64 *length)
749 {
750         struct btrfs_key key;
751         struct btrfs_root *root = device->dev_root;
752         struct btrfs_dev_extent *dev_extent;
753         struct btrfs_path *path;
754         u64 extent_end;
755         int ret;
756         int slot;
757         struct extent_buffer *l;
758
759         *length = 0;
760
761         if (start >= device->total_bytes)
762                 return 0;
763
764         path = btrfs_alloc_path();
765         if (!path)
766                 return -ENOMEM;
767         path->reada = 2;
768
769         key.objectid = device->devid;
770         key.offset = start;
771         key.type = BTRFS_DEV_EXTENT_KEY;
772
773         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
774         if (ret < 0)
775                 goto out;
776         if (ret > 0) {
777                 ret = btrfs_previous_item(root, path, key.objectid, key.type);
778                 if (ret < 0)
779                         goto out;
780         }
781
782         while (1) {
783                 l = path->nodes[0];
784                 slot = path->slots[0];
785                 if (slot >= btrfs_header_nritems(l)) {
786                         ret = btrfs_next_leaf(root, path);
787                         if (ret == 0)
788                                 continue;
789                         if (ret < 0)
790                                 goto out;
791
792                         break;
793                 }
794                 btrfs_item_key_to_cpu(l, &key, slot);
795
796                 if (key.objectid < device->devid)
797                         goto next;
798
799                 if (key.objectid > device->devid)
800                         break;
801
802                 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
803                         goto next;
804
805                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
806                 extent_end = key.offset + btrfs_dev_extent_length(l,
807                                                                   dev_extent);
808                 if (key.offset <= start && extent_end > end) {
809                         *length = end - start + 1;
810                         break;
811                 } else if (key.offset <= start && extent_end > start)
812                         *length += extent_end - start;
813                 else if (key.offset > start && extent_end <= end)
814                         *length += extent_end - key.offset;
815                 else if (key.offset > start && key.offset <= end) {
816                         *length += end - key.offset + 1;
817                         break;
818                 } else if (key.offset > end)
819                         break;
820
821 next:
822                 path->slots[0]++;
823         }
824         ret = 0;
825 out:
826         btrfs_free_path(path);
827         return ret;
828 }
829
830 /*
831  * find_free_dev_extent - find free space in the specified device
832  * @trans:      transaction handler
833  * @device:     the device which we search the free space in
834  * @num_bytes:  the size of the free space that we need
835  * @start:      store the start of the free space.
836  * @len:        the size of the free space. that we find, or the size of the max
837  *              free space if we don't find suitable free space
838  *
839  * this uses a pretty simple search, the expectation is that it is
840  * called very infrequently and that a given device has a small number
841  * of extents
842  *
843  * @start is used to store the start of the free space if we find. But if we
844  * don't find suitable free space, it will be used to store the start position
845  * of the max free space.
846  *
847  * @len is used to store the size of the free space that we find.
848  * But if we don't find suitable free space, it is used to store the size of
849  * the max free space.
850  */
851 int find_free_dev_extent(struct btrfs_trans_handle *trans,
852                          struct btrfs_device *device, u64 num_bytes,
853                          u64 *start, u64 *len)
854 {
855         struct btrfs_key key;
856         struct btrfs_root *root = device->dev_root;
857         struct btrfs_dev_extent *dev_extent;
858         struct btrfs_path *path;
859         u64 hole_size;
860         u64 max_hole_start;
861         u64 max_hole_size;
862         u64 extent_end;
863         u64 search_start;
864         u64 search_end = device->total_bytes;
865         int ret;
866         int slot;
867         struct extent_buffer *l;
868
869         /* FIXME use last free of some kind */
870
871         /* we don't want to overwrite the superblock on the drive,
872          * so we make sure to start at an offset of at least 1MB
873          */
874         search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
875
876         max_hole_start = search_start;
877         max_hole_size = 0;
878         hole_size = 0;
879
880         if (search_start >= search_end) {
881                 ret = -ENOSPC;
882                 goto error;
883         }
884
885         path = btrfs_alloc_path();
886         if (!path) {
887                 ret = -ENOMEM;
888                 goto error;
889         }
890         path->reada = 2;
891
892         key.objectid = device->devid;
893         key.offset = search_start;
894         key.type = BTRFS_DEV_EXTENT_KEY;
895
896         ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
897         if (ret < 0)
898                 goto out;
899         if (ret > 0) {
900                 ret = btrfs_previous_item(root, path, key.objectid, key.type);
901                 if (ret < 0)
902                         goto out;
903         }
904
905         while (1) {
906                 l = path->nodes[0];
907                 slot = path->slots[0];
908                 if (slot >= btrfs_header_nritems(l)) {
909                         ret = btrfs_next_leaf(root, path);
910                         if (ret == 0)
911                                 continue;
912                         if (ret < 0)
913                                 goto out;
914
915                         break;
916                 }
917                 btrfs_item_key_to_cpu(l, &key, slot);
918
919                 if (key.objectid < device->devid)
920                         goto next;
921
922                 if (key.objectid > device->devid)
923                         break;
924
925                 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
926                         goto next;
927
928                 if (key.offset > search_start) {
929                         hole_size = key.offset - search_start;
930
931                         if (hole_size > max_hole_size) {
932                                 max_hole_start = search_start;
933                                 max_hole_size = hole_size;
934                         }
935
936                         /*
937                          * If this free space is greater than which we need,
938                          * it must be the max free space that we have found
939                          * until now, so max_hole_start must point to the start
940                          * of this free space and the length of this free space
941                          * is stored in max_hole_size. Thus, we return
942                          * max_hole_start and max_hole_size and go back to the
943                          * caller.
944                          */
945                         if (hole_size >= num_bytes) {
946                                 ret = 0;
947                                 goto out;
948                         }
949                 }
950
951                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
952                 extent_end = key.offset + btrfs_dev_extent_length(l,
953                                                                   dev_extent);
954                 if (extent_end > search_start)
955                         search_start = extent_end;
956 next:
957                 path->slots[0]++;
958                 cond_resched();
959         }
960
961         /*
962          * At this point, search_start should be the end of
963          * allocated dev extents, and when shrinking the device,
964          * search_end may be smaller than search_start.
965          */
966         if (search_end > search_start)
967                 hole_size = search_end - search_start;
968
969         if (hole_size > max_hole_size) {
970                 max_hole_start = search_start;
971                 max_hole_size = hole_size;
972         }
973
974         /* See above. */
975         if (hole_size < num_bytes)
976                 ret = -ENOSPC;
977         else
978                 ret = 0;
979
980 out:
981         btrfs_free_path(path);
982 error:
983         *start = max_hole_start;
984         if (len)
985                 *len = max_hole_size;
986         return ret;
987 }
988
989 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
990                           struct btrfs_device *device,
991                           u64 start)
992 {
993         int ret;
994         struct btrfs_path *path;
995         struct btrfs_root *root = device->dev_root;
996         struct btrfs_key key;
997         struct btrfs_key found_key;
998         struct extent_buffer *leaf = NULL;
999         struct btrfs_dev_extent *extent = NULL;
1000
1001         path = btrfs_alloc_path();
1002         if (!path)
1003                 return -ENOMEM;
1004
1005         key.objectid = device->devid;
1006         key.offset = start;
1007         key.type = BTRFS_DEV_EXTENT_KEY;
1008 again:
1009         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1010         if (ret > 0) {
1011                 ret = btrfs_previous_item(root, path, key.objectid,
1012                                           BTRFS_DEV_EXTENT_KEY);
1013                 if (ret)
1014                         goto out;
1015                 leaf = path->nodes[0];
1016                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1017                 extent = btrfs_item_ptr(leaf, path->slots[0],
1018                                         struct btrfs_dev_extent);
1019                 BUG_ON(found_key.offset > start || found_key.offset +
1020                        btrfs_dev_extent_length(leaf, extent) < start);
1021                 key = found_key;
1022                 btrfs_release_path(path);
1023                 goto again;
1024         } else if (ret == 0) {
1025                 leaf = path->nodes[0];
1026                 extent = btrfs_item_ptr(leaf, path->slots[0],
1027                                         struct btrfs_dev_extent);
1028         }
1029         BUG_ON(ret);
1030
1031         if (device->bytes_used > 0) {
1032                 u64 len = btrfs_dev_extent_length(leaf, extent);
1033                 device->bytes_used -= len;
1034                 spin_lock(&root->fs_info->free_chunk_lock);
1035                 root->fs_info->free_chunk_space += len;
1036                 spin_unlock(&root->fs_info->free_chunk_lock);
1037         }
1038         ret = btrfs_del_item(trans, root, path);
1039
1040 out:
1041         btrfs_free_path(path);
1042         return ret;
1043 }
1044
1045 int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1046                            struct btrfs_device *device,
1047                            u64 chunk_tree, u64 chunk_objectid,
1048                            u64 chunk_offset, u64 start, u64 num_bytes)
1049 {
1050         int ret;
1051         struct btrfs_path *path;
1052         struct btrfs_root *root = device->dev_root;
1053         struct btrfs_dev_extent *extent;
1054         struct extent_buffer *leaf;
1055         struct btrfs_key key;
1056
1057         WARN_ON(!device->in_fs_metadata);
1058         path = btrfs_alloc_path();
1059         if (!path)
1060                 return -ENOMEM;
1061
1062         key.objectid = device->devid;
1063         key.offset = start;
1064         key.type = BTRFS_DEV_EXTENT_KEY;
1065         ret = btrfs_insert_empty_item(trans, root, path, &key,
1066                                       sizeof(*extent));
1067         BUG_ON(ret);
1068
1069         leaf = path->nodes[0];
1070         extent = btrfs_item_ptr(leaf, path->slots[0],
1071                                 struct btrfs_dev_extent);
1072         btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1073         btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1074         btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1075
1076         write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1077                     (unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
1078                     BTRFS_UUID_SIZE);
1079
1080         btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1081         btrfs_mark_buffer_dirty(leaf);
1082         btrfs_free_path(path);
1083         return ret;
1084 }
1085
1086 static noinline int find_next_chunk(struct btrfs_root *root,
1087                                     u64 objectid, u64 *offset)
1088 {
1089         struct btrfs_path *path;
1090         int ret;
1091         struct btrfs_key key;
1092         struct btrfs_chunk *chunk;
1093         struct btrfs_key found_key;
1094
1095         path = btrfs_alloc_path();
1096         if (!path)
1097                 return -ENOMEM;
1098
1099         key.objectid = objectid;
1100         key.offset = (u64)-1;
1101         key.type = BTRFS_CHUNK_ITEM_KEY;
1102
1103         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1104         if (ret < 0)
1105                 goto error;
1106
1107         BUG_ON(ret == 0);
1108
1109         ret = btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY);
1110         if (ret) {
1111                 *offset = 0;
1112         } else {
1113                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1114                                       path->slots[0]);
1115                 if (found_key.objectid != objectid)
1116                         *offset = 0;
1117                 else {
1118                         chunk = btrfs_item_ptr(path->nodes[0], path->slots[0],
1119                                                struct btrfs_chunk);
1120                         *offset = found_key.offset +
1121                                 btrfs_chunk_length(path->nodes[0], chunk);
1122                 }
1123         }
1124         ret = 0;
1125 error:
1126         btrfs_free_path(path);
1127         return ret;
1128 }
1129
1130 static noinline int find_next_devid(struct btrfs_root *root, u64 *objectid)
1131 {
1132         int ret;
1133         struct btrfs_key key;
1134         struct btrfs_key found_key;
1135         struct btrfs_path *path;
1136
1137         root = root->fs_info->chunk_root;
1138
1139         path = btrfs_alloc_path();
1140         if (!path)
1141                 return -ENOMEM;
1142
1143         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1144         key.type = BTRFS_DEV_ITEM_KEY;
1145         key.offset = (u64)-1;
1146
1147         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1148         if (ret < 0)
1149                 goto error;
1150
1151         BUG_ON(ret == 0);
1152
1153         ret = btrfs_previous_item(root, path, BTRFS_DEV_ITEMS_OBJECTID,
1154                                   BTRFS_DEV_ITEM_KEY);
1155         if (ret) {
1156                 *objectid = 1;
1157         } else {
1158                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1159                                       path->slots[0]);
1160                 *objectid = found_key.offset + 1;
1161         }
1162         ret = 0;
1163 error:
1164         btrfs_free_path(path);
1165         return ret;
1166 }
1167
1168 /*
1169  * the device information is stored in the chunk root
1170  * the btrfs_device struct should be fully filled in
1171  */
1172 int btrfs_add_device(struct btrfs_trans_handle *trans,
1173                      struct btrfs_root *root,
1174                      struct btrfs_device *device)
1175 {
1176         int ret;
1177         struct btrfs_path *path;
1178         struct btrfs_dev_item *dev_item;
1179         struct extent_buffer *leaf;
1180         struct btrfs_key key;
1181         unsigned long ptr;
1182
1183         root = root->fs_info->chunk_root;
1184
1185         path = btrfs_alloc_path();
1186         if (!path)
1187                 return -ENOMEM;
1188
1189         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1190         key.type = BTRFS_DEV_ITEM_KEY;
1191         key.offset = device->devid;
1192
1193         ret = btrfs_insert_empty_item(trans, root, path, &key,
1194                                       sizeof(*dev_item));
1195         if (ret)
1196                 goto out;
1197
1198         leaf = path->nodes[0];
1199         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1200
1201         btrfs_set_device_id(leaf, dev_item, device->devid);
1202         btrfs_set_device_generation(leaf, dev_item, 0);
1203         btrfs_set_device_type(leaf, dev_item, device->type);
1204         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1205         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1206         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1207         btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
1208         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1209         btrfs_set_device_group(leaf, dev_item, 0);
1210         btrfs_set_device_seek_speed(leaf, dev_item, 0);
1211         btrfs_set_device_bandwidth(leaf, dev_item, 0);
1212         btrfs_set_device_start_offset(leaf, dev_item, 0);
1213
1214         ptr = (unsigned long)btrfs_device_uuid(dev_item);
1215         write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1216         ptr = (unsigned long)btrfs_device_fsid(dev_item);
1217         write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
1218         btrfs_mark_buffer_dirty(leaf);
1219
1220         ret = 0;
1221 out:
1222         btrfs_free_path(path);
1223         return ret;
1224 }
1225
1226 static int btrfs_rm_dev_item(struct btrfs_root *root,
1227                              struct btrfs_device *device)
1228 {
1229         int ret;
1230         struct btrfs_path *path;
1231         struct btrfs_key key;
1232         struct btrfs_trans_handle *trans;
1233
1234         root = root->fs_info->chunk_root;
1235
1236         path = btrfs_alloc_path();
1237         if (!path)
1238                 return -ENOMEM;
1239
1240         trans = btrfs_start_transaction(root, 0);
1241         if (IS_ERR(trans)) {
1242                 btrfs_free_path(path);
1243                 return PTR_ERR(trans);
1244         }
1245         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1246         key.type = BTRFS_DEV_ITEM_KEY;
1247         key.offset = device->devid;
1248         lock_chunks(root);
1249
1250         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1251         if (ret < 0)
1252                 goto out;
1253
1254         if (ret > 0) {
1255                 ret = -ENOENT;
1256                 goto out;
1257         }
1258
1259         ret = btrfs_del_item(trans, root, path);
1260         if (ret)
1261                 goto out;
1262 out:
1263         btrfs_free_path(path);
1264         unlock_chunks(root);
1265         btrfs_commit_transaction(trans, root);
1266         return ret;
1267 }
1268
1269 int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1270 {
1271         struct btrfs_device *device;
1272         struct btrfs_device *next_device;
1273         struct block_device *bdev;
1274         struct buffer_head *bh = NULL;
1275         struct btrfs_super_block *disk_super;
1276         struct btrfs_fs_devices *cur_devices;
1277         u64 all_avail;
1278         u64 devid;
1279         u64 num_devices;
1280         u8 *dev_uuid;
1281         int ret = 0;
1282         bool clear_super = false;
1283
1284         mutex_lock(&uuid_mutex);
1285
1286         all_avail = root->fs_info->avail_data_alloc_bits |
1287                 root->fs_info->avail_system_alloc_bits |
1288                 root->fs_info->avail_metadata_alloc_bits;
1289
1290         if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) &&
1291             root->fs_info->fs_devices->num_devices <= 4) {
1292                 printk(KERN_ERR "btrfs: unable to go below four devices "
1293                        "on raid10\n");
1294                 ret = -EINVAL;
1295                 goto out;
1296         }
1297
1298         if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) &&
1299             root->fs_info->fs_devices->num_devices <= 2) {
1300                 printk(KERN_ERR "btrfs: unable to go below two "
1301                        "devices on raid1\n");
1302                 ret = -EINVAL;
1303                 goto out;
1304         }
1305
1306         if (strcmp(device_path, "missing") == 0) {
1307                 struct list_head *devices;
1308                 struct btrfs_device *tmp;
1309
1310                 device = NULL;
1311                 devices = &root->fs_info->fs_devices->devices;
1312                 /*
1313                  * It is safe to read the devices since the volume_mutex
1314                  * is held.
1315                  */
1316                 list_for_each_entry(tmp, devices, dev_list) {
1317                         if (tmp->in_fs_metadata && !tmp->bdev) {
1318                                 device = tmp;
1319                                 break;
1320                         }
1321                 }
1322                 bdev = NULL;
1323                 bh = NULL;
1324                 disk_super = NULL;
1325                 if (!device) {
1326                         printk(KERN_ERR "btrfs: no missing devices found to "
1327                                "remove\n");
1328                         goto out;
1329                 }
1330         } else {
1331                 bdev = blkdev_get_by_path(device_path, FMODE_READ | FMODE_EXCL,
1332                                           root->fs_info->bdev_holder);
1333                 if (IS_ERR(bdev)) {
1334                         ret = PTR_ERR(bdev);
1335                         goto out;
1336                 }
1337
1338                 set_blocksize(bdev, 4096);
1339                 bh = btrfs_read_dev_super(bdev);
1340                 if (!bh) {
1341                         ret = -EINVAL;
1342                         goto error_close;
1343                 }
1344                 disk_super = (struct btrfs_super_block *)bh->b_data;
1345                 devid = btrfs_stack_device_id(&disk_super->dev_item);
1346                 dev_uuid = disk_super->dev_item.uuid;
1347                 device = btrfs_find_device(root, devid, dev_uuid,
1348                                            disk_super->fsid);
1349                 if (!device) {
1350                         ret = -ENOENT;
1351                         goto error_brelse;
1352                 }
1353         }
1354
1355         if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
1356                 printk(KERN_ERR "btrfs: unable to remove the only writeable "
1357                        "device\n");
1358                 ret = -EINVAL;
1359                 goto error_brelse;
1360         }
1361
1362         if (device->writeable) {
1363                 lock_chunks(root);
1364                 list_del_init(&device->dev_alloc_list);
1365                 unlock_chunks(root);
1366                 root->fs_info->fs_devices->rw_devices--;
1367                 clear_super = true;
1368         }
1369
1370         ret = btrfs_shrink_device(device, 0);
1371         if (ret)
1372                 goto error_undo;
1373
1374         ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1375         if (ret)
1376                 goto error_undo;
1377
1378         spin_lock(&root->fs_info->free_chunk_lock);
1379         root->fs_info->free_chunk_space = device->total_bytes -
1380                 device->bytes_used;
1381         spin_unlock(&root->fs_info->free_chunk_lock);
1382
1383         device->in_fs_metadata = 0;
1384         btrfs_scrub_cancel_dev(root, device);
1385
1386         /*
1387          * the device list mutex makes sure that we don't change
1388          * the device list while someone else is writing out all
1389          * the device supers.
1390          */
1391
1392         cur_devices = device->fs_devices;
1393         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1394         list_del_rcu(&device->dev_list);
1395
1396         device->fs_devices->num_devices--;
1397
1398         if (device->missing)
1399                 root->fs_info->fs_devices->missing_devices--;
1400
1401         next_device = list_entry(root->fs_info->fs_devices->devices.next,
1402                                  struct btrfs_device, dev_list);
1403         if (device->bdev == root->fs_info->sb->s_bdev)
1404                 root->fs_info->sb->s_bdev = next_device->bdev;
1405         if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1406                 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1407
1408         if (device->bdev)
1409                 device->fs_devices->open_devices--;
1410
1411         call_rcu(&device->rcu, free_device);
1412         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1413
1414         num_devices = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
1415         btrfs_set_super_num_devices(root->fs_info->super_copy, num_devices);
1416
1417         if (cur_devices->open_devices == 0) {
1418                 struct btrfs_fs_devices *fs_devices;
1419                 fs_devices = root->fs_info->fs_devices;
1420                 while (fs_devices) {
1421                         if (fs_devices->seed == cur_devices)
1422                                 break;
1423                         fs_devices = fs_devices->seed;
1424                 }
1425                 fs_devices->seed = cur_devices->seed;
1426                 cur_devices->seed = NULL;
1427                 lock_chunks(root);
1428                 __btrfs_close_devices(cur_devices);
1429                 unlock_chunks(root);
1430                 free_fs_devices(cur_devices);
1431         }
1432
1433         /*
1434          * at this point, the device is zero sized.  We want to
1435          * remove it from the devices list and zero out the old super
1436          */
1437         if (clear_super) {
1438                 /* make sure this device isn't detected as part of
1439                  * the FS anymore
1440                  */
1441                 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1442                 set_buffer_dirty(bh);
1443                 sync_dirty_buffer(bh);
1444         }
1445
1446         ret = 0;
1447
1448 error_brelse:
1449         brelse(bh);
1450 error_close:
1451         if (bdev)
1452                 blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
1453 out:
1454         mutex_unlock(&uuid_mutex);
1455         return ret;
1456 error_undo:
1457         if (device->writeable) {
1458                 lock_chunks(root);
1459                 list_add(&device->dev_alloc_list,
1460                          &root->fs_info->fs_devices->alloc_list);
1461                 unlock_chunks(root);
1462                 root->fs_info->fs_devices->rw_devices++;
1463         }
1464         goto error_brelse;
1465 }
1466
1467 /*
1468  * does all the dirty work required for changing file system's UUID.
1469  */
1470 static int btrfs_prepare_sprout(struct btrfs_trans_handle *trans,
1471                                 struct btrfs_root *root)
1472 {
1473         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
1474         struct btrfs_fs_devices *old_devices;
1475         struct btrfs_fs_devices *seed_devices;
1476         struct btrfs_super_block *disk_super = root->fs_info->super_copy;
1477         struct btrfs_device *device;
1478         u64 super_flags;
1479
1480         BUG_ON(!mutex_is_locked(&uuid_mutex));
1481         if (!fs_devices->seeding)
1482                 return -EINVAL;
1483
1484         seed_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
1485         if (!seed_devices)
1486                 return -ENOMEM;
1487
1488         old_devices = clone_fs_devices(fs_devices);
1489         if (IS_ERR(old_devices)) {
1490                 kfree(seed_devices);
1491                 return PTR_ERR(old_devices);
1492         }
1493
1494         list_add(&old_devices->list, &fs_uuids);
1495
1496         memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
1497         seed_devices->opened = 1;
1498         INIT_LIST_HEAD(&seed_devices->devices);
1499         INIT_LIST_HEAD(&seed_devices->alloc_list);
1500         mutex_init(&seed_devices->device_list_mutex);
1501
1502         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1503         list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
1504                               synchronize_rcu);
1505         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1506
1507         list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
1508         list_for_each_entry(device, &seed_devices->devices, dev_list) {
1509                 device->fs_devices = seed_devices;
1510         }
1511
1512         fs_devices->seeding = 0;
1513         fs_devices->num_devices = 0;
1514         fs_devices->open_devices = 0;
1515         fs_devices->seed = seed_devices;
1516
1517         generate_random_uuid(fs_devices->fsid);
1518         memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1519         memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1520         super_flags = btrfs_super_flags(disk_super) &
1521                       ~BTRFS_SUPER_FLAG_SEEDING;
1522         btrfs_set_super_flags(disk_super, super_flags);
1523
1524         return 0;
1525 }
1526
1527 /*
1528  * strore the expected generation for seed devices in device items.
1529  */
1530 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
1531                                struct btrfs_root *root)
1532 {
1533         struct btrfs_path *path;
1534         struct extent_buffer *leaf;
1535         struct btrfs_dev_item *dev_item;
1536         struct btrfs_device *device;
1537         struct btrfs_key key;
1538         u8 fs_uuid[BTRFS_UUID_SIZE];
1539         u8 dev_uuid[BTRFS_UUID_SIZE];
1540         u64 devid;
1541         int ret;
1542
1543         path = btrfs_alloc_path();
1544         if (!path)
1545                 return -ENOMEM;
1546
1547         root = root->fs_info->chunk_root;
1548         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1549         key.offset = 0;
1550         key.type = BTRFS_DEV_ITEM_KEY;
1551
1552         while (1) {
1553                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1554                 if (ret < 0)
1555                         goto error;
1556
1557                 leaf = path->nodes[0];
1558 next_slot:
1559                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1560                         ret = btrfs_next_leaf(root, path);
1561                         if (ret > 0)
1562                                 break;
1563                         if (ret < 0)
1564                                 goto error;
1565                         leaf = path->nodes[0];
1566                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1567                         btrfs_release_path(path);
1568                         continue;
1569                 }
1570
1571                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1572                 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
1573                     key.type != BTRFS_DEV_ITEM_KEY)
1574                         break;
1575
1576                 dev_item = btrfs_item_ptr(leaf, path->slots[0],
1577                                           struct btrfs_dev_item);
1578                 devid = btrfs_device_id(leaf, dev_item);
1579                 read_extent_buffer(leaf, dev_uuid,
1580                                    (unsigned long)btrfs_device_uuid(dev_item),
1581                                    BTRFS_UUID_SIZE);
1582                 read_extent_buffer(leaf, fs_uuid,
1583                                    (unsigned long)btrfs_device_fsid(dev_item),
1584                                    BTRFS_UUID_SIZE);
1585                 device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
1586                 BUG_ON(!device);
1587
1588                 if (device->fs_devices->seeding) {
1589                         btrfs_set_device_generation(leaf, dev_item,
1590                                                     device->generation);
1591                         btrfs_mark_buffer_dirty(leaf);
1592                 }
1593
1594                 path->slots[0]++;
1595                 goto next_slot;
1596         }
1597         ret = 0;
1598 error:
1599         btrfs_free_path(path);
1600         return ret;
1601 }
1602
1603 int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
1604 {
1605         struct request_queue *q;
1606         struct btrfs_trans_handle *trans;
1607         struct btrfs_device *device;
1608         struct block_device *bdev;
1609         struct list_head *devices;
1610         struct super_block *sb = root->fs_info->sb;
1611         u64 total_bytes;
1612         int seeding_dev = 0;
1613         int ret = 0;
1614
1615         if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
1616                 return -EINVAL;
1617
1618         bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
1619                                   root->fs_info->bdev_holder);
1620         if (IS_ERR(bdev))
1621                 return PTR_ERR(bdev);
1622
1623         if (root->fs_info->fs_devices->seeding) {
1624                 seeding_dev = 1;
1625                 down_write(&sb->s_umount);
1626                 mutex_lock(&uuid_mutex);
1627         }
1628
1629         filemap_write_and_wait(bdev->bd_inode->i_mapping);
1630
1631         devices = &root->fs_info->fs_devices->devices;
1632         /*
1633          * we have the volume lock, so we don't need the extra
1634          * device list mutex while reading the list here.
1635          */
1636         list_for_each_entry(device, devices, dev_list) {
1637                 if (device->bdev == bdev) {
1638                         ret = -EEXIST;
1639                         goto error;
1640                 }
1641         }
1642
1643         device = kzalloc(sizeof(*device), GFP_NOFS);
1644         if (!device) {
1645                 /* we can safely leave the fs_devices entry around */
1646                 ret = -ENOMEM;
1647                 goto error;
1648         }
1649
1650         device->name = kstrdup(device_path, GFP_NOFS);
1651         if (!device->name) {
1652                 kfree(device);
1653                 ret = -ENOMEM;
1654                 goto error;
1655         }
1656
1657         ret = find_next_devid(root, &device->devid);
1658         if (ret) {
1659                 kfree(device->name);
1660                 kfree(device);
1661                 goto error;
1662         }
1663
1664         trans = btrfs_start_transaction(root, 0);
1665         if (IS_ERR(trans)) {
1666                 kfree(device->name);
1667                 kfree(device);
1668                 ret = PTR_ERR(trans);
1669                 goto error;
1670         }
1671
1672         lock_chunks(root);
1673
1674         q = bdev_get_queue(bdev);
1675         if (blk_queue_discard(q))
1676                 device->can_discard = 1;
1677         device->writeable = 1;
1678         device->work.func = pending_bios_fn;
1679         generate_random_uuid(device->uuid);
1680         spin_lock_init(&device->io_lock);
1681         device->generation = trans->transid;
1682         device->io_width = root->sectorsize;
1683         device->io_align = root->sectorsize;
1684         device->sector_size = root->sectorsize;
1685         device->total_bytes = i_size_read(bdev->bd_inode);
1686         device->disk_total_bytes = device->total_bytes;
1687         device->dev_root = root->fs_info->dev_root;
1688         device->bdev = bdev;
1689         device->in_fs_metadata = 1;
1690         device->mode = FMODE_EXCL;
1691         set_blocksize(device->bdev, 4096);
1692
1693         if (seeding_dev) {
1694                 sb->s_flags &= ~MS_RDONLY;
1695                 ret = btrfs_prepare_sprout(trans, root);
1696                 BUG_ON(ret);
1697         }
1698
1699         device->fs_devices = root->fs_info->fs_devices;
1700
1701         /*
1702          * we don't want write_supers to jump in here with our device
1703          * half setup
1704          */
1705         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1706         list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
1707         list_add(&device->dev_alloc_list,
1708                  &root->fs_info->fs_devices->alloc_list);
1709         root->fs_info->fs_devices->num_devices++;
1710         root->fs_info->fs_devices->open_devices++;
1711         root->fs_info->fs_devices->rw_devices++;
1712         if (device->can_discard)
1713                 root->fs_info->fs_devices->num_can_discard++;
1714         root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
1715
1716         spin_lock(&root->fs_info->free_chunk_lock);
1717         root->fs_info->free_chunk_space += device->total_bytes;
1718         spin_unlock(&root->fs_info->free_chunk_lock);
1719
1720         if (!blk_queue_nonrot(bdev_get_queue(bdev)))
1721                 root->fs_info->fs_devices->rotating = 1;
1722
1723         total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
1724         btrfs_set_super_total_bytes(root->fs_info->super_copy,
1725                                     total_bytes + device->total_bytes);
1726
1727         total_bytes = btrfs_super_num_devices(root->fs_info->super_copy);
1728         btrfs_set_super_num_devices(root->fs_info->super_copy,
1729                                     total_bytes + 1);
1730         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1731
1732         if (seeding_dev) {
1733                 ret = init_first_rw_device(trans, root, device);
1734                 BUG_ON(ret);
1735                 ret = btrfs_finish_sprout(trans, root);
1736                 BUG_ON(ret);
1737         } else {
1738                 ret = btrfs_add_device(trans, root, device);
1739         }
1740
1741         /*
1742          * we've got more storage, clear any full flags on the space
1743          * infos
1744          */
1745         btrfs_clear_space_info_full(root->fs_info);
1746
1747         unlock_chunks(root);
1748         btrfs_commit_transaction(trans, root);
1749
1750         if (seeding_dev) {
1751                 mutex_unlock(&uuid_mutex);
1752                 up_write(&sb->s_umount);
1753
1754                 ret = btrfs_relocate_sys_chunks(root);
1755                 BUG_ON(ret);
1756         }
1757
1758         return ret;
1759 error:
1760         blkdev_put(bdev, FMODE_EXCL);
1761         if (seeding_dev) {
1762                 mutex_unlock(&uuid_mutex);
1763                 up_write(&sb->s_umount);
1764         }
1765         return ret;
1766 }
1767
1768 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
1769                                         struct btrfs_device *device)
1770 {
1771         int ret;
1772         struct btrfs_path *path;
1773         struct btrfs_root *root;
1774         struct btrfs_dev_item *dev_item;
1775         struct extent_buffer *leaf;
1776         struct btrfs_key key;
1777
1778         root = device->dev_root->fs_info->chunk_root;
1779
1780         path = btrfs_alloc_path();
1781         if (!path)
1782                 return -ENOMEM;
1783
1784         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1785         key.type = BTRFS_DEV_ITEM_KEY;
1786         key.offset = device->devid;
1787
1788         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1789         if (ret < 0)
1790                 goto out;
1791
1792         if (ret > 0) {
1793                 ret = -ENOENT;
1794                 goto out;
1795         }
1796
1797         leaf = path->nodes[0];
1798         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1799
1800         btrfs_set_device_id(leaf, dev_item, device->devid);
1801         btrfs_set_device_type(leaf, dev_item, device->type);
1802         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1803         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1804         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1805         btrfs_set_device_total_bytes(leaf, dev_item, device->disk_total_bytes);
1806         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1807         btrfs_mark_buffer_dirty(leaf);
1808
1809 out:
1810         btrfs_free_path(path);
1811         return ret;
1812 }
1813
1814 static int __btrfs_grow_device(struct btrfs_trans_handle *trans,
1815                       struct btrfs_device *device, u64 new_size)
1816 {
1817         struct btrfs_super_block *super_copy =
1818                 device->dev_root->fs_info->super_copy;
1819         u64 old_total = btrfs_super_total_bytes(super_copy);
1820         u64 diff = new_size - device->total_bytes;
1821
1822         if (!device->writeable)
1823                 return -EACCES;
1824         if (new_size <= device->total_bytes)
1825                 return -EINVAL;
1826
1827         btrfs_set_super_total_bytes(super_copy, old_total + diff);
1828         device->fs_devices->total_rw_bytes += diff;
1829
1830         device->total_bytes = new_size;
1831         device->disk_total_bytes = new_size;
1832         btrfs_clear_space_info_full(device->dev_root->fs_info);
1833
1834         return btrfs_update_device(trans, device);
1835 }
1836
1837 int btrfs_grow_device(struct btrfs_trans_handle *trans,
1838                       struct btrfs_device *device, u64 new_size)
1839 {
1840         int ret;
1841         lock_chunks(device->dev_root);
1842         ret = __btrfs_grow_device(trans, device, new_size);
1843         unlock_chunks(device->dev_root);
1844         return ret;
1845 }
1846
1847 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
1848                             struct btrfs_root *root,
1849                             u64 chunk_tree, u64 chunk_objectid,
1850                             u64 chunk_offset)
1851 {
1852         int ret;
1853         struct btrfs_path *path;
1854         struct btrfs_key key;
1855
1856         root = root->fs_info->chunk_root;
1857         path = btrfs_alloc_path();
1858         if (!path)
1859                 return -ENOMEM;
1860
1861         key.objectid = chunk_objectid;
1862         key.offset = chunk_offset;
1863         key.type = BTRFS_CHUNK_ITEM_KEY;
1864
1865         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1866         BUG_ON(ret);
1867
1868         ret = btrfs_del_item(trans, root, path);
1869
1870         btrfs_free_path(path);
1871         return ret;
1872 }
1873
1874 static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
1875                         chunk_offset)
1876 {
1877         struct btrfs_super_block *super_copy = root->fs_info->super_copy;
1878         struct btrfs_disk_key *disk_key;
1879         struct btrfs_chunk *chunk;
1880         u8 *ptr;
1881         int ret = 0;
1882         u32 num_stripes;
1883         u32 array_size;
1884         u32 len = 0;
1885         u32 cur;
1886         struct btrfs_key key;
1887
1888         array_size = btrfs_super_sys_array_size(super_copy);
1889
1890         ptr = super_copy->sys_chunk_array;
1891         cur = 0;
1892
1893         while (cur < array_size) {
1894                 disk_key = (struct btrfs_disk_key *)ptr;
1895                 btrfs_disk_key_to_cpu(&key, disk_key);
1896
1897                 len = sizeof(*disk_key);
1898
1899                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1900                         chunk = (struct btrfs_chunk *)(ptr + len);
1901                         num_stripes = btrfs_stack_chunk_num_stripes(chunk);
1902                         len += btrfs_chunk_item_size(num_stripes);
1903                 } else {
1904                         ret = -EIO;
1905                         break;
1906                 }
1907                 if (key.objectid == chunk_objectid &&
1908                     key.offset == chunk_offset) {
1909                         memmove(ptr, ptr + len, array_size - (cur + len));
1910                         array_size -= len;
1911                         btrfs_set_super_sys_array_size(super_copy, array_size);
1912                 } else {
1913                         ptr += len;
1914                         cur += len;
1915                 }
1916         }
1917         return ret;
1918 }
1919
1920 static int btrfs_relocate_chunk(struct btrfs_root *root,
1921                          u64 chunk_tree, u64 chunk_objectid,
1922                          u64 chunk_offset)
1923 {
1924         struct extent_map_tree *em_tree;
1925         struct btrfs_root *extent_root;
1926         struct btrfs_trans_handle *trans;
1927         struct extent_map *em;
1928         struct map_lookup *map;
1929         int ret;
1930         int i;
1931
1932         root = root->fs_info->chunk_root;
1933         extent_root = root->fs_info->extent_root;
1934         em_tree = &root->fs_info->mapping_tree.map_tree;
1935
1936         ret = btrfs_can_relocate(extent_root, chunk_offset);
1937         if (ret)
1938                 return -ENOSPC;
1939
1940         /* step one, relocate all the extents inside this chunk */
1941         ret = btrfs_relocate_block_group(extent_root, chunk_offset);
1942         if (ret)
1943                 return ret;
1944
1945         trans = btrfs_start_transaction(root, 0);
1946         BUG_ON(IS_ERR(trans));
1947
1948         lock_chunks(root);
1949
1950         /*
1951          * step two, delete the device extents and the
1952          * chunk tree entries
1953          */
1954         read_lock(&em_tree->lock);
1955         em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1956         read_unlock(&em_tree->lock);
1957
1958         BUG_ON(em->start > chunk_offset ||
1959                em->start + em->len < chunk_offset);
1960         map = (struct map_lookup *)em->bdev;
1961
1962         for (i = 0; i < map->num_stripes; i++) {
1963                 ret = btrfs_free_dev_extent(trans, map->stripes[i].dev,
1964                                             map->stripes[i].physical);
1965                 BUG_ON(ret);
1966
1967                 if (map->stripes[i].dev) {
1968                         ret = btrfs_update_device(trans, map->stripes[i].dev);
1969                         BUG_ON(ret);
1970                 }
1971         }
1972         ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
1973                                chunk_offset);
1974
1975         BUG_ON(ret);
1976
1977         trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
1978
1979         if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
1980                 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
1981                 BUG_ON(ret);
1982         }
1983
1984         ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
1985         BUG_ON(ret);
1986
1987         write_lock(&em_tree->lock);
1988         remove_extent_mapping(em_tree, em);
1989         write_unlock(&em_tree->lock);
1990
1991         kfree(map);
1992         em->bdev = NULL;
1993
1994         /* once for the tree */
1995         free_extent_map(em);
1996         /* once for us */
1997         free_extent_map(em);
1998
1999         unlock_chunks(root);
2000         btrfs_end_transaction(trans, root);
2001         return 0;
2002 }
2003
2004 static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
2005 {
2006         struct btrfs_root *chunk_root = root->fs_info->chunk_root;
2007         struct btrfs_path *path;
2008         struct extent_buffer *leaf;
2009         struct btrfs_chunk *chunk;
2010         struct btrfs_key key;
2011         struct btrfs_key found_key;
2012         u64 chunk_tree = chunk_root->root_key.objectid;
2013         u64 chunk_type;
2014         bool retried = false;
2015         int failed = 0;
2016         int ret;
2017
2018         path = btrfs_alloc_path();
2019         if (!path)
2020                 return -ENOMEM;
2021
2022 again:
2023         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2024         key.offset = (u64)-1;
2025         key.type = BTRFS_CHUNK_ITEM_KEY;
2026
2027         while (1) {
2028                 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2029                 if (ret < 0)
2030                         goto error;
2031                 BUG_ON(ret == 0);
2032
2033                 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2034                                           key.type);
2035                 if (ret < 0)
2036                         goto error;
2037                 if (ret > 0)
2038                         break;
2039
2040                 leaf = path->nodes[0];
2041                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2042
2043                 chunk = btrfs_item_ptr(leaf, path->slots[0],
2044                                        struct btrfs_chunk);
2045                 chunk_type = btrfs_chunk_type(leaf, chunk);
2046                 btrfs_release_path(path);
2047
2048                 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2049                         ret = btrfs_relocate_chunk(chunk_root, chunk_tree,
2050                                                    found_key.objectid,
2051                                                    found_key.offset);
2052                         if (ret == -ENOSPC)
2053                                 failed++;
2054                         else if (ret)
2055                                 BUG();
2056                 }
2057
2058                 if (found_key.offset == 0)
2059                         break;
2060                 key.offset = found_key.offset - 1;
2061         }
2062         ret = 0;
2063         if (failed && !retried) {
2064                 failed = 0;
2065                 retried = true;
2066                 goto again;
2067         } else if (failed && retried) {
2068                 WARN_ON(1);
2069                 ret = -ENOSPC;
2070         }
2071 error:
2072         btrfs_free_path(path);
2073         return ret;
2074 }
2075
2076 /*
2077  * Should be called with both balance and volume mutexes held to
2078  * serialize other volume operations (add_dev/rm_dev/resize) with
2079  * restriper.  Same goes for unset_balance_control.
2080  */
2081 static void set_balance_control(struct btrfs_balance_control *bctl)
2082 {
2083         struct btrfs_fs_info *fs_info = bctl->fs_info;
2084
2085         BUG_ON(fs_info->balance_ctl);
2086
2087         spin_lock(&fs_info->balance_lock);
2088         fs_info->balance_ctl = bctl;
2089         spin_unlock(&fs_info->balance_lock);
2090 }
2091
2092 static void unset_balance_control(struct btrfs_fs_info *fs_info)
2093 {
2094         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
2095
2096         BUG_ON(!fs_info->balance_ctl);
2097
2098         spin_lock(&fs_info->balance_lock);
2099         fs_info->balance_ctl = NULL;
2100         spin_unlock(&fs_info->balance_lock);
2101
2102         kfree(bctl);
2103 }
2104
2105 /*
2106  * Balance filters.  Return 1 if chunk should be filtered out
2107  * (should not be balanced).
2108  */
2109 static int chunk_profiles_filter(u64 chunk_profile,
2110                                  struct btrfs_balance_args *bargs)
2111 {
2112         chunk_profile &= BTRFS_BLOCK_GROUP_PROFILE_MASK;
2113
2114         if (chunk_profile == 0)
2115                 chunk_profile = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
2116
2117         if (bargs->profiles & chunk_profile)
2118                 return 0;
2119
2120         return 1;
2121 }
2122
2123 static int should_balance_chunk(struct btrfs_root *root,
2124                                 struct extent_buffer *leaf,
2125                                 struct btrfs_chunk *chunk, u64 chunk_offset)
2126 {
2127         struct btrfs_balance_control *bctl = root->fs_info->balance_ctl;
2128         struct btrfs_balance_args *bargs = NULL;
2129         u64 chunk_type = btrfs_chunk_type(leaf, chunk);
2130
2131         /* type filter */
2132         if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
2133               (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
2134                 return 0;
2135         }
2136
2137         if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
2138                 bargs = &bctl->data;
2139         else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
2140                 bargs = &bctl->sys;
2141         else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
2142                 bargs = &bctl->meta;
2143
2144         /* profiles filter */
2145         if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
2146             chunk_profiles_filter(chunk_type, bargs)) {
2147                 return 0;
2148         }
2149
2150         return 1;
2151 }
2152
2153 static u64 div_factor(u64 num, int factor)
2154 {
2155         if (factor == 10)
2156                 return num;
2157         num *= factor;
2158         do_div(num, 10);
2159         return num;
2160 }
2161
2162 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
2163 {
2164         struct btrfs_root *chunk_root = fs_info->chunk_root;
2165         struct btrfs_root *dev_root = fs_info->dev_root;
2166         struct list_head *devices;
2167         struct btrfs_device *device;
2168         u64 old_size;
2169         u64 size_to_free;
2170         struct btrfs_chunk *chunk;
2171         struct btrfs_path *path;
2172         struct btrfs_key key;
2173         struct btrfs_key found_key;
2174         struct btrfs_trans_handle *trans;
2175         struct extent_buffer *leaf;
2176         int slot;
2177         int ret;
2178         int enospc_errors = 0;
2179
2180         /* step one make some room on all the devices */
2181         devices = &fs_info->fs_devices->devices;
2182         list_for_each_entry(device, devices, dev_list) {
2183                 old_size = device->total_bytes;
2184                 size_to_free = div_factor(old_size, 1);
2185                 size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
2186                 if (!device->writeable ||
2187                     device->total_bytes - device->bytes_used > size_to_free)
2188                         continue;
2189
2190                 ret = btrfs_shrink_device(device, old_size - size_to_free);
2191                 if (ret == -ENOSPC)
2192                         break;
2193                 BUG_ON(ret);
2194
2195                 trans = btrfs_start_transaction(dev_root, 0);
2196                 BUG_ON(IS_ERR(trans));
2197
2198                 ret = btrfs_grow_device(trans, device, old_size);
2199                 BUG_ON(ret);
2200
2201                 btrfs_end_transaction(trans, dev_root);
2202         }
2203
2204         /* step two, relocate all the chunks */
2205         path = btrfs_alloc_path();
2206         if (!path) {
2207                 ret = -ENOMEM;
2208                 goto error;
2209         }
2210         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2211         key.offset = (u64)-1;
2212         key.type = BTRFS_CHUNK_ITEM_KEY;
2213
2214         while (1) {
2215                 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2216                 if (ret < 0)
2217                         goto error;
2218
2219                 /*
2220                  * this shouldn't happen, it means the last relocate
2221                  * failed
2222                  */
2223                 if (ret == 0)
2224                         BUG(); /* FIXME break ? */
2225
2226                 ret = btrfs_previous_item(chunk_root, path, 0,
2227                                           BTRFS_CHUNK_ITEM_KEY);
2228                 if (ret) {
2229                         ret = 0;
2230                         break;
2231                 }
2232
2233                 leaf = path->nodes[0];
2234                 slot = path->slots[0];
2235                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2236
2237                 if (found_key.objectid != key.objectid)
2238                         break;
2239
2240                 /* chunk zero is special */
2241                 if (found_key.offset == 0)
2242                         break;
2243
2244                 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
2245
2246                 ret = should_balance_chunk(chunk_root, leaf, chunk,
2247                                            found_key.offset);
2248                 btrfs_release_path(path);
2249                 if (!ret)
2250                         goto loop;
2251
2252                 ret = btrfs_relocate_chunk(chunk_root,
2253                                            chunk_root->root_key.objectid,
2254                                            found_key.objectid,
2255                                            found_key.offset);
2256                 if (ret && ret != -ENOSPC)
2257                         goto error;
2258                 if (ret == -ENOSPC)
2259                         enospc_errors++;
2260 loop:
2261                 key.offset = found_key.offset - 1;
2262         }
2263
2264 error:
2265         btrfs_free_path(path);
2266         if (enospc_errors) {
2267                 printk(KERN_INFO "btrfs: %d enospc errors during balance\n",
2268                        enospc_errors);
2269                 if (!ret)
2270                         ret = -ENOSPC;
2271         }
2272
2273         return ret;
2274 }
2275
2276 static void __cancel_balance(struct btrfs_fs_info *fs_info)
2277 {
2278         unset_balance_control(fs_info);
2279 }
2280
2281 void update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
2282                                struct btrfs_ioctl_balance_args *bargs);
2283
2284 /*
2285  * Should be called with both balance and volume mutexes held
2286  */
2287 int btrfs_balance(struct btrfs_balance_control *bctl,
2288                   struct btrfs_ioctl_balance_args *bargs)
2289 {
2290         struct btrfs_fs_info *fs_info = bctl->fs_info;
2291         u64 allowed;
2292         int ret;
2293
2294         if (btrfs_fs_closing(fs_info)) {
2295                 ret = -EINVAL;
2296                 goto out;
2297         }
2298
2299         /*
2300          * In case of mixed groups both data and meta should be picked,
2301          * and identical options should be given for both of them.
2302          */
2303         allowed = btrfs_super_incompat_flags(fs_info->super_copy);
2304         if ((allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
2305             (bctl->flags & (BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA))) {
2306                 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
2307                     !(bctl->flags & BTRFS_BALANCE_METADATA) ||
2308                     memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
2309                         printk(KERN_ERR "btrfs: with mixed groups data and "
2310                                "metadata balance options must be the same\n");
2311                         ret = -EINVAL;
2312                         goto out;
2313                 }
2314         }
2315
2316         set_balance_control(bctl);
2317
2318         mutex_unlock(&fs_info->balance_mutex);
2319
2320         ret = __btrfs_balance(fs_info);
2321
2322         mutex_lock(&fs_info->balance_mutex);
2323
2324         if (bargs) {
2325                 memset(bargs, 0, sizeof(*bargs));
2326                 update_ioctl_balance_args(fs_info, bargs);
2327         }
2328
2329         __cancel_balance(fs_info);
2330
2331         return ret;
2332 out:
2333         kfree(bctl);
2334         return ret;
2335 }
2336
2337 /*
2338  * shrinking a device means finding all of the device extents past
2339  * the new size, and then following the back refs to the chunks.
2340  * The chunk relocation code actually frees the device extent
2341  */
2342 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
2343 {
2344         struct btrfs_trans_handle *trans;
2345         struct btrfs_root *root = device->dev_root;
2346         struct btrfs_dev_extent *dev_extent = NULL;
2347         struct btrfs_path *path;
2348         u64 length;
2349         u64 chunk_tree;
2350         u64 chunk_objectid;
2351         u64 chunk_offset;
2352         int ret;
2353         int slot;
2354         int failed = 0;
2355         bool retried = false;
2356         struct extent_buffer *l;
2357         struct btrfs_key key;
2358         struct btrfs_super_block *super_copy = root->fs_info->super_copy;
2359         u64 old_total = btrfs_super_total_bytes(super_copy);
2360         u64 old_size = device->total_bytes;
2361         u64 diff = device->total_bytes - new_size;
2362
2363         if (new_size >= device->total_bytes)
2364                 return -EINVAL;
2365
2366         path = btrfs_alloc_path();
2367         if (!path)
2368                 return -ENOMEM;
2369
2370         path->reada = 2;
2371
2372         lock_chunks(root);
2373
2374         device->total_bytes = new_size;
2375         if (device->writeable) {
2376                 device->fs_devices->total_rw_bytes -= diff;
2377                 spin_lock(&root->fs_info->free_chunk_lock);
2378                 root->fs_info->free_chunk_space -= diff;
2379                 spin_unlock(&root->fs_info->free_chunk_lock);
2380         }
2381         unlock_chunks(root);
2382
2383 again:
2384         key.objectid = device->devid;
2385         key.offset = (u64)-1;
2386         key.type = BTRFS_DEV_EXTENT_KEY;
2387
2388         while (1) {
2389                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2390                 if (ret < 0)
2391                         goto done;
2392
2393                 ret = btrfs_previous_item(root, path, 0, key.type);
2394                 if (ret < 0)
2395                         goto done;
2396                 if (ret) {
2397                         ret = 0;
2398                         btrfs_release_path(path);
2399                         break;
2400                 }
2401
2402                 l = path->nodes[0];
2403                 slot = path->slots[0];
2404                 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
2405
2406                 if (key.objectid != device->devid) {
2407                         btrfs_release_path(path);
2408                         break;
2409                 }
2410
2411                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
2412                 length = btrfs_dev_extent_length(l, dev_extent);
2413
2414                 if (key.offset + length <= new_size) {
2415                         btrfs_release_path(path);
2416                         break;
2417                 }
2418
2419                 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
2420                 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
2421                 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
2422                 btrfs_release_path(path);
2423
2424                 ret = btrfs_relocate_chunk(root, chunk_tree, chunk_objectid,
2425                                            chunk_offset);
2426                 if (ret && ret != -ENOSPC)
2427                         goto done;
2428                 if (ret == -ENOSPC)
2429                         failed++;
2430                 key.offset -= 1;
2431         }
2432
2433         if (failed && !retried) {
2434                 failed = 0;
2435                 retried = true;
2436                 goto again;
2437         } else if (failed && retried) {
2438                 ret = -ENOSPC;
2439                 lock_chunks(root);
2440
2441                 device->total_bytes = old_size;
2442                 if (device->writeable)
2443                         device->fs_devices->total_rw_bytes += diff;
2444                 spin_lock(&root->fs_info->free_chunk_lock);
2445                 root->fs_info->free_chunk_space += diff;
2446                 spin_unlock(&root->fs_info->free_chunk_lock);
2447                 unlock_chunks(root);
2448                 goto done;
2449         }
2450
2451         /* Shrinking succeeded, else we would be at "done". */
2452         trans = btrfs_start_transaction(root, 0);
2453         if (IS_ERR(trans)) {
2454                 ret = PTR_ERR(trans);
2455                 goto done;
2456         }
2457
2458         lock_chunks(root);
2459
2460         device->disk_total_bytes = new_size;
2461         /* Now btrfs_update_device() will change the on-disk size. */
2462         ret = btrfs_update_device(trans, device);
2463         if (ret) {
2464                 unlock_chunks(root);
2465                 btrfs_end_transaction(trans, root);
2466                 goto done;
2467         }
2468         WARN_ON(diff > old_total);
2469         btrfs_set_super_total_bytes(super_copy, old_total - diff);
2470         unlock_chunks(root);
2471         btrfs_end_transaction(trans, root);
2472 done:
2473         btrfs_free_path(path);
2474         return ret;
2475 }
2476
2477 static int btrfs_add_system_chunk(struct btrfs_trans_handle *trans,
2478                            struct btrfs_root *root,
2479                            struct btrfs_key *key,
2480                            struct btrfs_chunk *chunk, int item_size)
2481 {
2482         struct btrfs_super_block *super_copy = root->fs_info->super_copy;
2483         struct btrfs_disk_key disk_key;
2484         u32 array_size;
2485         u8 *ptr;
2486
2487         array_size = btrfs_super_sys_array_size(super_copy);
2488         if (array_size + item_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
2489                 return -EFBIG;
2490
2491         ptr = super_copy->sys_chunk_array + array_size;
2492         btrfs_cpu_key_to_disk(&disk_key, key);
2493         memcpy(ptr, &disk_key, sizeof(disk_key));
2494         ptr += sizeof(disk_key);
2495         memcpy(ptr, chunk, item_size);
2496         item_size += sizeof(disk_key);
2497         btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
2498         return 0;
2499 }
2500
2501 /*
2502  * sort the devices in descending order by max_avail, total_avail
2503  */
2504 static int btrfs_cmp_device_info(const void *a, const void *b)
2505 {
2506         const struct btrfs_device_info *di_a = a;
2507         const struct btrfs_device_info *di_b = b;
2508
2509         if (di_a->max_avail > di_b->max_avail)
2510                 return -1;
2511         if (di_a->max_avail < di_b->max_avail)
2512                 return 1;
2513         if (di_a->total_avail > di_b->total_avail)
2514                 return -1;
2515         if (di_a->total_avail < di_b->total_avail)
2516                 return 1;
2517         return 0;
2518 }
2519
2520 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
2521                                struct btrfs_root *extent_root,
2522                                struct map_lookup **map_ret,
2523                                u64 *num_bytes_out, u64 *stripe_size_out,
2524                                u64 start, u64 type)
2525 {
2526         struct btrfs_fs_info *info = extent_root->fs_info;
2527         struct btrfs_fs_devices *fs_devices = info->fs_devices;
2528         struct list_head *cur;
2529         struct map_lookup *map = NULL;
2530         struct extent_map_tree *em_tree;
2531         struct extent_map *em;
2532         struct btrfs_device_info *devices_info = NULL;
2533         u64 total_avail;
2534         int num_stripes;        /* total number of stripes to allocate */
2535         int sub_stripes;        /* sub_stripes info for map */
2536         int dev_stripes;        /* stripes per dev */
2537         int devs_max;           /* max devs to use */
2538         int devs_min;           /* min devs needed */
2539         int devs_increment;     /* ndevs has to be a multiple of this */
2540         int ncopies;            /* how many copies to data has */
2541         int ret;
2542         u64 max_stripe_size;
2543         u64 max_chunk_size;
2544         u64 stripe_size;
2545         u64 num_bytes;
2546         int ndevs;
2547         int i;
2548         int j;
2549
2550         if ((type & BTRFS_BLOCK_GROUP_RAID1) &&
2551             (type & BTRFS_BLOCK_GROUP_DUP)) {
2552                 WARN_ON(1);
2553                 type &= ~BTRFS_BLOCK_GROUP_DUP;
2554         }
2555
2556         if (list_empty(&fs_devices->alloc_list))
2557                 return -ENOSPC;
2558
2559         sub_stripes = 1;
2560         dev_stripes = 1;
2561         devs_increment = 1;
2562         ncopies = 1;
2563         devs_max = 0;   /* 0 == as many as possible */
2564         devs_min = 1;
2565
2566         /*
2567          * define the properties of each RAID type.
2568          * FIXME: move this to a global table and use it in all RAID
2569          * calculation code
2570          */
2571         if (type & (BTRFS_BLOCK_GROUP_DUP)) {
2572                 dev_stripes = 2;
2573                 ncopies = 2;
2574                 devs_max = 1;
2575         } else if (type & (BTRFS_BLOCK_GROUP_RAID0)) {
2576                 devs_min = 2;
2577         } else if (type & (BTRFS_BLOCK_GROUP_RAID1)) {
2578                 devs_increment = 2;
2579                 ncopies = 2;
2580                 devs_max = 2;
2581                 devs_min = 2;
2582         } else if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
2583                 sub_stripes = 2;
2584                 devs_increment = 2;
2585                 ncopies = 2;
2586                 devs_min = 4;
2587         } else {
2588                 devs_max = 1;
2589         }
2590
2591         if (type & BTRFS_BLOCK_GROUP_DATA) {
2592                 max_stripe_size = 1024 * 1024 * 1024;
2593                 max_chunk_size = 10 * max_stripe_size;
2594         } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
2595                 max_stripe_size = 256 * 1024 * 1024;
2596                 max_chunk_size = max_stripe_size;
2597         } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
2598                 max_stripe_size = 8 * 1024 * 1024;
2599                 max_chunk_size = 2 * max_stripe_size;
2600         } else {
2601                 printk(KERN_ERR "btrfs: invalid chunk type 0x%llx requested\n",
2602                        type);
2603                 BUG_ON(1);
2604         }
2605
2606         /* we don't want a chunk larger than 10% of writeable space */
2607         max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
2608                              max_chunk_size);
2609
2610         devices_info = kzalloc(sizeof(*devices_info) * fs_devices->rw_devices,
2611                                GFP_NOFS);
2612         if (!devices_info)
2613                 return -ENOMEM;
2614
2615         cur = fs_devices->alloc_list.next;
2616
2617         /*
2618          * in the first pass through the devices list, we gather information
2619          * about the available holes on each device.
2620          */
2621         ndevs = 0;
2622         while (cur != &fs_devices->alloc_list) {
2623                 struct btrfs_device *device;
2624                 u64 max_avail;
2625                 u64 dev_offset;
2626
2627                 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
2628
2629                 cur = cur->next;
2630
2631                 if (!device->writeable) {
2632                         printk(KERN_ERR
2633                                "btrfs: read-only device in alloc_list\n");
2634                         WARN_ON(1);
2635                         continue;
2636                 }
2637
2638                 if (!device->in_fs_metadata)
2639                         continue;
2640
2641                 if (device->total_bytes > device->bytes_used)
2642                         total_avail = device->total_bytes - device->bytes_used;
2643                 else
2644                         total_avail = 0;
2645
2646                 /* If there is no space on this device, skip it. */
2647                 if (total_avail == 0)
2648                         continue;
2649
2650                 ret = find_free_dev_extent(trans, device,
2651                                            max_stripe_size * dev_stripes,
2652                                            &dev_offset, &max_avail);
2653                 if (ret && ret != -ENOSPC)
2654                         goto error;
2655
2656                 if (ret == 0)
2657                         max_avail = max_stripe_size * dev_stripes;
2658
2659                 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
2660                         continue;
2661
2662                 devices_info[ndevs].dev_offset = dev_offset;
2663                 devices_info[ndevs].max_avail = max_avail;
2664                 devices_info[ndevs].total_avail = total_avail;
2665                 devices_info[ndevs].dev = device;
2666                 ++ndevs;
2667         }
2668
2669         /*
2670          * now sort the devices by hole size / available space
2671          */
2672         sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
2673              btrfs_cmp_device_info, NULL);
2674
2675         /* round down to number of usable stripes */
2676         ndevs -= ndevs % devs_increment;
2677
2678         if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
2679                 ret = -ENOSPC;
2680                 goto error;
2681         }
2682
2683         if (devs_max && ndevs > devs_max)
2684                 ndevs = devs_max;
2685         /*
2686          * the primary goal is to maximize the number of stripes, so use as many
2687          * devices as possible, even if the stripes are not maximum sized.
2688          */
2689         stripe_size = devices_info[ndevs-1].max_avail;
2690         num_stripes = ndevs * dev_stripes;
2691
2692         if (stripe_size * num_stripes > max_chunk_size * ncopies) {
2693                 stripe_size = max_chunk_size * ncopies;
2694                 do_div(stripe_size, num_stripes);
2695         }
2696
2697         do_div(stripe_size, dev_stripes);
2698         do_div(stripe_size, BTRFS_STRIPE_LEN);
2699         stripe_size *= BTRFS_STRIPE_LEN;
2700
2701         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
2702         if (!map) {
2703                 ret = -ENOMEM;
2704                 goto error;
2705         }
2706         map->num_stripes = num_stripes;
2707
2708         for (i = 0; i < ndevs; ++i) {
2709                 for (j = 0; j < dev_stripes; ++j) {
2710                         int s = i * dev_stripes + j;
2711                         map->stripes[s].dev = devices_info[i].dev;
2712                         map->stripes[s].physical = devices_info[i].dev_offset +
2713                                                    j * stripe_size;
2714                 }
2715         }
2716         map->sector_size = extent_root->sectorsize;
2717         map->stripe_len = BTRFS_STRIPE_LEN;
2718         map->io_align = BTRFS_STRIPE_LEN;
2719         map->io_width = BTRFS_STRIPE_LEN;
2720         map->type = type;
2721         map->sub_stripes = sub_stripes;
2722
2723         *map_ret = map;
2724         num_bytes = stripe_size * (num_stripes / ncopies);
2725
2726         *stripe_size_out = stripe_size;
2727         *num_bytes_out = num_bytes;
2728
2729         trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
2730
2731         em = alloc_extent_map();
2732         if (!em) {
2733                 ret = -ENOMEM;
2734                 goto error;
2735         }
2736         em->bdev = (struct block_device *)map;
2737         em->start = start;
2738         em->len = num_bytes;
2739         em->block_start = 0;
2740         em->block_len = em->len;
2741
2742         em_tree = &extent_root->fs_info->mapping_tree.map_tree;
2743         write_lock(&em_tree->lock);
2744         ret = add_extent_mapping(em_tree, em);
2745         write_unlock(&em_tree->lock);
2746         BUG_ON(ret);
2747         free_extent_map(em);
2748
2749         ret = btrfs_make_block_group(trans, extent_root, 0, type,
2750                                      BTRFS_FIRST_CHUNK_TREE_OBJECTID,
2751                                      start, num_bytes);
2752         BUG_ON(ret);
2753
2754         for (i = 0; i < map->num_stripes; ++i) {
2755                 struct btrfs_device *device;
2756                 u64 dev_offset;
2757
2758                 device = map->stripes[i].dev;
2759                 dev_offset = map->stripes[i].physical;
2760
2761                 ret = btrfs_alloc_dev_extent(trans, device,
2762                                 info->chunk_root->root_key.objectid,
2763                                 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
2764                                 start, dev_offset, stripe_size);
2765                 BUG_ON(ret);
2766         }
2767
2768         kfree(devices_info);
2769         return 0;
2770
2771 error:
2772         kfree(map);
2773         kfree(devices_info);
2774         return ret;
2775 }
2776
2777 static int __finish_chunk_alloc(struct btrfs_trans_handle *trans,
2778                                 struct btrfs_root *extent_root,
2779                                 struct map_lookup *map, u64 chunk_offset,
2780                                 u64 chunk_size, u64 stripe_size)
2781 {
2782         u64 dev_offset;
2783         struct btrfs_key key;
2784         struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
2785         struct btrfs_device *device;
2786         struct btrfs_chunk *chunk;
2787         struct btrfs_stripe *stripe;
2788         size_t item_size = btrfs_chunk_item_size(map->num_stripes);
2789         int index = 0;
2790         int ret;
2791
2792         chunk = kzalloc(item_size, GFP_NOFS);
2793         if (!chunk)
2794                 return -ENOMEM;
2795
2796         index = 0;
2797         while (index < map->num_stripes) {
2798                 device = map->stripes[index].dev;
2799                 device->bytes_used += stripe_size;
2800                 ret = btrfs_update_device(trans, device);
2801                 BUG_ON(ret);
2802                 index++;
2803         }
2804
2805         spin_lock(&extent_root->fs_info->free_chunk_lock);
2806         extent_root->fs_info->free_chunk_space -= (stripe_size *
2807                                                    map->num_stripes);
2808         spin_unlock(&extent_root->fs_info->free_chunk_lock);
2809
2810         index = 0;
2811         stripe = &chunk->stripe;
2812         while (index < map->num_stripes) {
2813                 device = map->stripes[index].dev;
2814                 dev_offset = map->stripes[index].physical;
2815
2816                 btrfs_set_stack_stripe_devid(stripe, device->devid);
2817                 btrfs_set_stack_stripe_offset(stripe, dev_offset);
2818                 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
2819                 stripe++;
2820                 index++;
2821         }
2822
2823         btrfs_set_stack_chunk_length(chunk, chunk_size);
2824         btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
2825         btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
2826         btrfs_set_stack_chunk_type(chunk, map->type);
2827         btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
2828         btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
2829         btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
2830         btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
2831         btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
2832
2833         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2834         key.type = BTRFS_CHUNK_ITEM_KEY;
2835         key.offset = chunk_offset;
2836
2837         ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
2838         BUG_ON(ret);
2839
2840         if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2841                 ret = btrfs_add_system_chunk(trans, chunk_root, &key, chunk,
2842                                              item_size);
2843                 BUG_ON(ret);
2844         }
2845
2846         kfree(chunk);
2847         return 0;
2848 }
2849
2850 /*
2851  * Chunk allocation falls into two parts. The first part does works
2852  * that make the new allocated chunk useable, but not do any operation
2853  * that modifies the chunk tree. The second part does the works that
2854  * require modifying the chunk tree. This division is important for the
2855  * bootstrap process of adding storage to a seed btrfs.
2856  */
2857 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
2858                       struct btrfs_root *extent_root, u64 type)
2859 {
2860         u64 chunk_offset;
2861         u64 chunk_size;
2862         u64 stripe_size;
2863         struct map_lookup *map;
2864         struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
2865         int ret;
2866
2867         ret = find_next_chunk(chunk_root, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
2868                               &chunk_offset);
2869         if (ret)
2870                 return ret;
2871
2872         ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
2873                                   &stripe_size, chunk_offset, type);
2874         if (ret)
2875                 return ret;
2876
2877         ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
2878                                    chunk_size, stripe_size);
2879         BUG_ON(ret);
2880         return 0;
2881 }
2882
2883 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
2884                                          struct btrfs_root *root,
2885                                          struct btrfs_device *device)
2886 {
2887         u64 chunk_offset;
2888         u64 sys_chunk_offset;
2889         u64 chunk_size;
2890         u64 sys_chunk_size;
2891         u64 stripe_size;
2892         u64 sys_stripe_size;
2893         u64 alloc_profile;
2894         struct map_lookup *map;
2895         struct map_lookup *sys_map;
2896         struct btrfs_fs_info *fs_info = root->fs_info;
2897         struct btrfs_root *extent_root = fs_info->extent_root;
2898         int ret;
2899
2900         ret = find_next_chunk(fs_info->chunk_root,
2901                               BTRFS_FIRST_CHUNK_TREE_OBJECTID, &chunk_offset);
2902         if (ret)
2903                 return ret;
2904
2905         alloc_profile = BTRFS_BLOCK_GROUP_METADATA |
2906                                 fs_info->avail_metadata_alloc_bits;
2907         alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
2908
2909         ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
2910                                   &stripe_size, chunk_offset, alloc_profile);
2911         BUG_ON(ret);
2912
2913         sys_chunk_offset = chunk_offset + chunk_size;
2914
2915         alloc_profile = BTRFS_BLOCK_GROUP_SYSTEM |
2916                                 fs_info->avail_system_alloc_bits;
2917         alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
2918
2919         ret = __btrfs_alloc_chunk(trans, extent_root, &sys_map,
2920                                   &sys_chunk_size, &sys_stripe_size,
2921                                   sys_chunk_offset, alloc_profile);
2922         BUG_ON(ret);
2923
2924         ret = btrfs_add_device(trans, fs_info->chunk_root, device);
2925         BUG_ON(ret);
2926
2927         /*
2928          * Modifying chunk tree needs allocating new blocks from both
2929          * system block group and metadata block group. So we only can
2930          * do operations require modifying the chunk tree after both
2931          * block groups were created.
2932          */
2933         ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
2934                                    chunk_size, stripe_size);
2935         BUG_ON(ret);
2936
2937         ret = __finish_chunk_alloc(trans, extent_root, sys_map,
2938                                    sys_chunk_offset, sys_chunk_size,
2939                                    sys_stripe_size);
2940         BUG_ON(ret);
2941         return 0;
2942 }
2943
2944 int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
2945 {
2946         struct extent_map *em;
2947         struct map_lookup *map;
2948         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
2949         int readonly = 0;
2950         int i;
2951
2952         read_lock(&map_tree->map_tree.lock);
2953         em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
2954         read_unlock(&map_tree->map_tree.lock);
2955         if (!em)
2956                 return 1;
2957
2958         if (btrfs_test_opt(root, DEGRADED)) {
2959                 free_extent_map(em);
2960                 return 0;
2961         }
2962
2963         map = (struct map_lookup *)em->bdev;
2964         for (i = 0; i < map->num_stripes; i++) {
2965                 if (!map->stripes[i].dev->writeable) {
2966                         readonly = 1;
2967                         break;
2968                 }
2969         }
2970         free_extent_map(em);
2971         return readonly;
2972 }
2973
2974 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
2975 {
2976         extent_map_tree_init(&tree->map_tree);
2977 }
2978
2979 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
2980 {
2981         struct extent_map *em;
2982
2983         while (1) {
2984                 write_lock(&tree->map_tree.lock);
2985                 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
2986                 if (em)
2987                         remove_extent_mapping(&tree->map_tree, em);
2988                 write_unlock(&tree->map_tree.lock);
2989                 if (!em)
2990                         break;
2991                 kfree(em->bdev);
2992                 /* once for us */
2993                 free_extent_map(em);
2994                 /* once for the tree */
2995                 free_extent_map(em);
2996         }
2997 }
2998
2999 int btrfs_num_copies(struct btrfs_mapping_tree *map_tree, u64 logical, u64 len)
3000 {
3001         struct extent_map *em;
3002         struct map_lookup *map;
3003         struct extent_map_tree *em_tree = &map_tree->map_tree;
3004         int ret;
3005
3006         read_lock(&em_tree->lock);
3007         em = lookup_extent_mapping(em_tree, logical, len);
3008         read_unlock(&em_tree->lock);
3009         BUG_ON(!em);
3010
3011         BUG_ON(em->start > logical || em->start + em->len < logical);
3012         map = (struct map_lookup *)em->bdev;
3013         if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
3014                 ret = map->num_stripes;
3015         else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
3016                 ret = map->sub_stripes;
3017         else
3018                 ret = 1;
3019         free_extent_map(em);
3020         return ret;
3021 }
3022
3023 static int find_live_mirror(struct map_lookup *map, int first, int num,
3024                             int optimal)
3025 {
3026         int i;
3027         if (map->stripes[optimal].dev->bdev)
3028                 return optimal;
3029         for (i = first; i < first + num; i++) {
3030                 if (map->stripes[i].dev->bdev)
3031                         return i;
3032         }
3033         /* we couldn't find one that doesn't fail.  Just return something
3034          * and the io error handling code will clean up eventually
3035          */
3036         return optimal;
3037 }
3038
3039 static int __btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
3040                              u64 logical, u64 *length,
3041                              struct btrfs_bio **bbio_ret,
3042                              int mirror_num)
3043 {
3044         struct extent_map *em;
3045         struct map_lookup *map;
3046         struct extent_map_tree *em_tree = &map_tree->map_tree;
3047         u64 offset;
3048         u64 stripe_offset;
3049         u64 stripe_end_offset;
3050         u64 stripe_nr;
3051         u64 stripe_nr_orig;
3052         u64 stripe_nr_end;
3053         int stripes_allocated = 8;
3054         int stripes_required = 1;
3055         int stripe_index;
3056         int i;
3057         int num_stripes;
3058         int max_errors = 0;
3059         struct btrfs_bio *bbio = NULL;
3060
3061         if (bbio_ret && !(rw & (REQ_WRITE | REQ_DISCARD)))
3062                 stripes_allocated = 1;
3063 again:
3064         if (bbio_ret) {
3065                 bbio = kzalloc(btrfs_bio_size(stripes_allocated),
3066                                 GFP_NOFS);
3067                 if (!bbio)
3068                         return -ENOMEM;
3069
3070                 atomic_set(&bbio->error, 0);
3071         }
3072
3073         read_lock(&em_tree->lock);
3074         em = lookup_extent_mapping(em_tree, logical, *length);
3075         read_unlock(&em_tree->lock);
3076
3077         if (!em) {
3078                 printk(KERN_CRIT "unable to find logical %llu len %llu\n",
3079                        (unsigned long long)logical,
3080                        (unsigned long long)*length);
3081                 BUG();
3082         }
3083
3084         BUG_ON(em->start > logical || em->start + em->len < logical);
3085         map = (struct map_lookup *)em->bdev;
3086         offset = logical - em->start;
3087
3088         if (mirror_num > map->num_stripes)
3089                 mirror_num = 0;
3090
3091         /* if our btrfs_bio struct is too small, back off and try again */
3092         if (rw & REQ_WRITE) {
3093                 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
3094                                  BTRFS_BLOCK_GROUP_DUP)) {
3095                         stripes_required = map->num_stripes;
3096                         max_errors = 1;
3097                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
3098                         stripes_required = map->sub_stripes;
3099                         max_errors = 1;
3100                 }
3101         }
3102         if (rw & REQ_DISCARD) {
3103                 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK)
3104                         stripes_required = map->num_stripes;
3105         }
3106         if (bbio_ret && (rw & (REQ_WRITE | REQ_DISCARD)) &&
3107             stripes_allocated < stripes_required) {
3108                 stripes_allocated = map->num_stripes;
3109                 free_extent_map(em);
3110                 kfree(bbio);
3111                 goto again;
3112         }
3113         stripe_nr = offset;
3114         /*
3115          * stripe_nr counts the total number of stripes we have to stride
3116          * to get to this block
3117          */
3118         do_div(stripe_nr, map->stripe_len);
3119
3120         stripe_offset = stripe_nr * map->stripe_len;
3121         BUG_ON(offset < stripe_offset);
3122
3123         /* stripe_offset is the offset of this block in its stripe*/
3124         stripe_offset = offset - stripe_offset;
3125
3126         if (rw & REQ_DISCARD)
3127                 *length = min_t(u64, em->len - offset, *length);
3128         else if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
3129                 /* we limit the length of each bio to what fits in a stripe */
3130                 *length = min_t(u64, em->len - offset,
3131                                 map->stripe_len - stripe_offset);
3132         } else {
3133                 *length = em->len - offset;
3134         }
3135
3136         if (!bbio_ret)
3137                 goto out;
3138
3139         num_stripes = 1;
3140         stripe_index = 0;
3141         stripe_nr_orig = stripe_nr;
3142         stripe_nr_end = (offset + *length + map->stripe_len - 1) &
3143                         (~(map->stripe_len - 1));
3144         do_div(stripe_nr_end, map->stripe_len);
3145         stripe_end_offset = stripe_nr_end * map->stripe_len -
3146                             (offset + *length);
3147         if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
3148                 if (rw & REQ_DISCARD)
3149                         num_stripes = min_t(u64, map->num_stripes,
3150                                             stripe_nr_end - stripe_nr_orig);
3151                 stripe_index = do_div(stripe_nr, map->num_stripes);
3152         } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
3153                 if (rw & (REQ_WRITE | REQ_DISCARD))
3154                         num_stripes = map->num_stripes;
3155                 else if (mirror_num)
3156                         stripe_index = mirror_num - 1;
3157                 else {
3158                         stripe_index = find_live_mirror(map, 0,
3159                                             map->num_stripes,
3160                                             current->pid % map->num_stripes);
3161                         mirror_num = stripe_index + 1;
3162                 }
3163
3164         } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
3165                 if (rw & (REQ_WRITE | REQ_DISCARD)) {
3166                         num_stripes = map->num_stripes;
3167                 } else if (mirror_num) {
3168                         stripe_index = mirror_num - 1;
3169                 } else {
3170                         mirror_num = 1;
3171                 }
3172
3173         } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
3174                 int factor = map->num_stripes / map->sub_stripes;
3175
3176                 stripe_index = do_div(stripe_nr, factor);
3177                 stripe_index *= map->sub_stripes;
3178
3179                 if (rw & REQ_WRITE)
3180                         num_stripes = map->sub_stripes;
3181                 else if (rw & REQ_DISCARD)
3182                         num_stripes = min_t(u64, map->sub_stripes *
3183                                             (stripe_nr_end - stripe_nr_orig),
3184                                             map->num_stripes);
3185                 else if (mirror_num)
3186                         stripe_index += mirror_num - 1;
3187                 else {
3188                         stripe_index = find_live_mirror(map, stripe_index,
3189                                               map->sub_stripes, stripe_index +
3190                                               current->pid % map->sub_stripes);
3191                         mirror_num = stripe_index + 1;
3192                 }
3193         } else {
3194                 /*
3195                  * after this do_div call, stripe_nr is the number of stripes
3196                  * on this device we have to walk to find the data, and
3197                  * stripe_index is the number of our device in the stripe array
3198                  */
3199                 stripe_index = do_div(stripe_nr, map->num_stripes);
3200                 mirror_num = stripe_index + 1;
3201         }
3202         BUG_ON(stripe_index >= map->num_stripes);
3203
3204         if (rw & REQ_DISCARD) {
3205                 for (i = 0; i < num_stripes; i++) {
3206                         bbio->stripes[i].physical =
3207                                 map->stripes[stripe_index].physical +
3208                                 stripe_offset + stripe_nr * map->stripe_len;
3209                         bbio->stripes[i].dev = map->stripes[stripe_index].dev;
3210
3211                         if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
3212                                 u64 stripes;
3213                                 u32 last_stripe = 0;
3214                                 int j;
3215
3216                                 div_u64_rem(stripe_nr_end - 1,
3217                                             map->num_stripes,
3218                                             &last_stripe);
3219
3220                                 for (j = 0; j < map->num_stripes; j++) {
3221                                         u32 test;
3222
3223                                         div_u64_rem(stripe_nr_end - 1 - j,
3224                                                     map->num_stripes, &test);
3225                                         if (test == stripe_index)
3226                                                 break;
3227                                 }
3228                                 stripes = stripe_nr_end - 1 - j;
3229                                 do_div(stripes, map->num_stripes);
3230                                 bbio->stripes[i].length = map->stripe_len *
3231                                         (stripes - stripe_nr + 1);
3232
3233                                 if (i == 0) {
3234                                         bbio->stripes[i].length -=
3235                                                 stripe_offset;
3236                                         stripe_offset = 0;
3237                                 }
3238                                 if (stripe_index == last_stripe)
3239                                         bbio->stripes[i].length -=
3240                                                 stripe_end_offset;
3241                         } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
3242                                 u64 stripes;
3243                                 int j;
3244                                 int factor = map->num_stripes /
3245                                              map->sub_stripes;
3246                                 u32 last_stripe = 0;
3247
3248                                 div_u64_rem(stripe_nr_end - 1,
3249                                             factor, &last_stripe);
3250                                 last_stripe *= map->sub_stripes;
3251
3252                                 for (j = 0; j < factor; j++) {
3253                                         u32 test;
3254
3255                                         div_u64_rem(stripe_nr_end - 1 - j,
3256                                                     factor, &test);
3257
3258                                         if (test ==
3259                                             stripe_index / map->sub_stripes)
3260                                                 break;
3261                                 }
3262                                 stripes = stripe_nr_end - 1 - j;
3263                                 do_div(stripes, factor);
3264                                 bbio->stripes[i].length = map->stripe_len *
3265                                         (stripes - stripe_nr + 1);
3266
3267                                 if (i < map->sub_stripes) {
3268                                         bbio->stripes[i].length -=
3269                                                 stripe_offset;
3270                                         if (i == map->sub_stripes - 1)
3271                                                 stripe_offset = 0;
3272                                 }
3273                                 if (stripe_index >= last_stripe &&
3274                                     stripe_index <= (last_stripe +
3275                                                      map->sub_stripes - 1)) {
3276                                         bbio->stripes[i].length -=
3277                                                 stripe_end_offset;
3278                                 }
3279                         } else
3280                                 bbio->stripes[i].length = *length;
3281
3282                         stripe_index++;
3283                         if (stripe_index == map->num_stripes) {
3284                                 /* This could only happen for RAID0/10 */
3285                                 stripe_index = 0;
3286                                 stripe_nr++;
3287                         }
3288                 }
3289         } else {
3290                 for (i = 0; i < num_stripes; i++) {
3291                         bbio->stripes[i].physical =
3292                                 map->stripes[stripe_index].physical +
3293                                 stripe_offset +
3294                                 stripe_nr * map->stripe_len;
3295                         bbio->stripes[i].dev =
3296                                 map->stripes[stripe_index].dev;
3297                         stripe_index++;
3298                 }
3299         }
3300         if (bbio_ret) {
3301                 *bbio_ret = bbio;
3302                 bbio->num_stripes = num_stripes;
3303                 bbio->max_errors = max_errors;
3304                 bbio->mirror_num = mirror_num;
3305         }
3306 out:
3307         free_extent_map(em);
3308         return 0;
3309 }
3310
3311 int btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
3312                       u64 logical, u64 *length,
3313                       struct btrfs_bio **bbio_ret, int mirror_num)
3314 {
3315         return __btrfs_map_block(map_tree, rw, logical, length, bbio_ret,
3316                                  mirror_num);
3317 }
3318
3319 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
3320                      u64 chunk_start, u64 physical, u64 devid,
3321                      u64 **logical, int *naddrs, int *stripe_len)
3322 {
3323         struct extent_map_tree *em_tree = &map_tree->map_tree;
3324         struct extent_map *em;
3325         struct map_lookup *map;
3326         u64 *buf;
3327         u64 bytenr;
3328         u64 length;
3329         u64 stripe_nr;
3330         int i, j, nr = 0;
3331
3332         read_lock(&em_tree->lock);
3333         em = lookup_extent_mapping(em_tree, chunk_start, 1);
3334         read_unlock(&em_tree->lock);
3335
3336         BUG_ON(!em || em->start != chunk_start);
3337         map = (struct map_lookup *)em->bdev;
3338
3339         length = em->len;
3340         if (map->type & BTRFS_BLOCK_GROUP_RAID10)
3341                 do_div(length, map->num_stripes / map->sub_stripes);
3342         else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
3343                 do_div(length, map->num_stripes);
3344
3345         buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
3346         BUG_ON(!buf);
3347
3348         for (i = 0; i < map->num_stripes; i++) {
3349                 if (devid && map->stripes[i].dev->devid != devid)
3350                         continue;
3351                 if (map->stripes[i].physical > physical ||
3352                     map->stripes[i].physical + length <= physical)
3353                         continue;
3354
3355                 stripe_nr = physical - map->stripes[i].physical;
3356                 do_div(stripe_nr, map->stripe_len);
3357
3358                 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
3359                         stripe_nr = stripe_nr * map->num_stripes + i;
3360                         do_div(stripe_nr, map->sub_stripes);
3361                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
3362                         stripe_nr = stripe_nr * map->num_stripes + i;
3363                 }
3364                 bytenr = chunk_start + stripe_nr * map->stripe_len;
3365                 WARN_ON(nr >= map->num_stripes);
3366                 for (j = 0; j < nr; j++) {
3367                         if (buf[j] == bytenr)
3368                                 break;
3369                 }
3370                 if (j == nr) {
3371                         WARN_ON(nr >= map->num_stripes);
3372                         buf[nr++] = bytenr;
3373                 }
3374         }
3375
3376         *logical = buf;
3377         *naddrs = nr;
3378         *stripe_len = map->stripe_len;
3379
3380         free_extent_map(em);
3381         return 0;
3382 }
3383
3384 static void btrfs_end_bio(struct bio *bio, int err)
3385 {
3386         struct btrfs_bio *bbio = bio->bi_private;
3387         int is_orig_bio = 0;
3388
3389         if (err)
3390                 atomic_inc(&bbio->error);
3391
3392         if (bio == bbio->orig_bio)
3393                 is_orig_bio = 1;
3394
3395         if (atomic_dec_and_test(&bbio->stripes_pending)) {
3396                 if (!is_orig_bio) {
3397                         bio_put(bio);
3398                         bio = bbio->orig_bio;
3399                 }
3400                 bio->bi_private = bbio->private;
3401                 bio->bi_end_io = bbio->end_io;
3402                 bio->bi_bdev = (struct block_device *)
3403                                         (unsigned long)bbio->mirror_num;
3404                 /* only send an error to the higher layers if it is
3405                  * beyond the tolerance of the multi-bio
3406                  */
3407                 if (atomic_read(&bbio->error) > bbio->max_errors) {
3408                         err = -EIO;
3409                 } else {
3410                         /*
3411                          * this bio is actually up to date, we didn't
3412                          * go over the max number of errors
3413                          */
3414                         set_bit(BIO_UPTODATE, &bio->bi_flags);
3415                         err = 0;
3416                 }
3417                 kfree(bbio);
3418
3419                 bio_endio(bio, err);
3420         } else if (!is_orig_bio) {
3421                 bio_put(bio);
3422         }
3423 }
3424
3425 struct async_sched {
3426         struct bio *bio;
3427         int rw;
3428         struct btrfs_fs_info *info;
3429         struct btrfs_work work;
3430 };
3431
3432 /*
3433  * see run_scheduled_bios for a description of why bios are collected for
3434  * async submit.
3435  *
3436  * This will add one bio to the pending list for a device and make sure
3437  * the work struct is scheduled.
3438  */
3439 static noinline int schedule_bio(struct btrfs_root *root,
3440                                  struct btrfs_device *device,
3441                                  int rw, struct bio *bio)
3442 {
3443         int should_queue = 1;
3444         struct btrfs_pending_bios *pending_bios;
3445
3446         /* don't bother with additional async steps for reads, right now */
3447         if (!(rw & REQ_WRITE)) {
3448                 bio_get(bio);
3449                 submit_bio(rw, bio);
3450                 bio_put(bio);
3451                 return 0;
3452         }
3453
3454         /*
3455          * nr_async_bios allows us to reliably return congestion to the
3456          * higher layers.  Otherwise, the async bio makes it appear we have
3457          * made progress against dirty pages when we've really just put it
3458          * on a queue for later
3459          */
3460         atomic_inc(&root->fs_info->nr_async_bios);
3461         WARN_ON(bio->bi_next);
3462         bio->bi_next = NULL;
3463         bio->bi_rw |= rw;
3464
3465         spin_lock(&device->io_lock);
3466         if (bio->bi_rw & REQ_SYNC)
3467                 pending_bios = &device->pending_sync_bios;
3468         else
3469                 pending_bios = &device->pending_bios;
3470
3471         if (pending_bios->tail)
3472                 pending_bios->tail->bi_next = bio;
3473
3474         pending_bios->tail = bio;
3475         if (!pending_bios->head)
3476                 pending_bios->head = bio;
3477         if (device->running_pending)
3478                 should_queue = 0;
3479
3480         spin_unlock(&device->io_lock);
3481
3482         if (should_queue)
3483                 btrfs_queue_worker(&root->fs_info->submit_workers,
3484                                    &device->work);
3485         return 0;
3486 }
3487
3488 int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
3489                   int mirror_num, int async_submit)
3490 {
3491         struct btrfs_mapping_tree *map_tree;
3492         struct btrfs_device *dev;
3493         struct bio *first_bio = bio;
3494         u64 logical = (u64)bio->bi_sector << 9;
3495         u64 length = 0;
3496         u64 map_length;
3497         int ret;
3498         int dev_nr = 0;
3499         int total_devs = 1;
3500         struct btrfs_bio *bbio = NULL;
3501
3502         length = bio->bi_size;
3503         map_tree = &root->fs_info->mapping_tree;
3504         map_length = length;
3505
3506         ret = btrfs_map_block(map_tree, rw, logical, &map_length, &bbio,
3507                               mirror_num);
3508         BUG_ON(ret);
3509
3510         total_devs = bbio->num_stripes;
3511         if (map_length < length) {
3512                 printk(KERN_CRIT "mapping failed logical %llu bio len %llu "
3513                        "len %llu\n", (unsigned long long)logical,
3514                        (unsigned long long)length,
3515                        (unsigned long long)map_length);
3516                 BUG();
3517         }
3518
3519         bbio->orig_bio = first_bio;
3520         bbio->private = first_bio->bi_private;
3521         bbio->end_io = first_bio->bi_end_io;
3522         atomic_set(&bbio->stripes_pending, bbio->num_stripes);
3523
3524         while (dev_nr < total_devs) {
3525                 if (dev_nr < total_devs - 1) {
3526                         bio = bio_clone(first_bio, GFP_NOFS);
3527                         BUG_ON(!bio);
3528                 } else {
3529                         bio = first_bio;
3530                 }
3531                 bio->bi_private = bbio;
3532                 bio->bi_end_io = btrfs_end_bio;
3533                 bio->bi_sector = bbio->stripes[dev_nr].physical >> 9;
3534                 dev = bbio->stripes[dev_nr].dev;
3535                 if (dev && dev->bdev && (rw != WRITE || dev->writeable)) {
3536                         pr_debug("btrfs_map_bio: rw %d, secor=%llu, dev=%lu "
3537                                  "(%s id %llu), size=%u\n", rw,
3538                                  (u64)bio->bi_sector, (u_long)dev->bdev->bd_dev,
3539                                  dev->name, dev->devid, bio->bi_size);
3540                         bio->bi_bdev = dev->bdev;
3541                         if (async_submit)
3542                                 schedule_bio(root, dev, rw, bio);
3543                         else
3544                                 submit_bio(rw, bio);
3545                 } else {
3546                         bio->bi_bdev = root->fs_info->fs_devices->latest_bdev;
3547                         bio->bi_sector = logical >> 9;
3548                         bio_endio(bio, -EIO);
3549                 }
3550                 dev_nr++;
3551         }
3552         return 0;
3553 }
3554
3555 struct btrfs_device *btrfs_find_device(struct btrfs_root *root, u64 devid,
3556                                        u8 *uuid, u8 *fsid)
3557 {
3558         struct btrfs_device *device;
3559         struct btrfs_fs_devices *cur_devices;
3560
3561         cur_devices = root->fs_info->fs_devices;
3562         while (cur_devices) {
3563                 if (!fsid ||
3564                     !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
3565                         device = __find_device(&cur_devices->devices,
3566                                                devid, uuid);
3567                         if (device)
3568                                 return device;
3569                 }
3570                 cur_devices = cur_devices->seed;
3571         }
3572         return NULL;
3573 }
3574
3575 static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
3576                                             u64 devid, u8 *dev_uuid)
3577 {
3578         struct btrfs_device *device;
3579         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
3580
3581         device = kzalloc(sizeof(*device), GFP_NOFS);
3582         if (!device)
3583                 return NULL;
3584         list_add(&device->dev_list,
3585                  &fs_devices->devices);
3586         device->dev_root = root->fs_info->dev_root;
3587         device->devid = devid;
3588         device->work.func = pending_bios_fn;
3589         device->fs_devices = fs_devices;
3590         device->missing = 1;
3591         fs_devices->num_devices++;
3592         fs_devices->missing_devices++;
3593         spin_lock_init(&device->io_lock);
3594         INIT_LIST_HEAD(&device->dev_alloc_list);
3595         memcpy(device->uuid, dev_uuid, BTRFS_UUID_SIZE);
3596         return device;
3597 }
3598
3599 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
3600                           struct extent_buffer *leaf,
3601                           struct btrfs_chunk *chunk)
3602 {
3603         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
3604         struct map_lookup *map;
3605         struct extent_map *em;
3606         u64 logical;
3607         u64 length;
3608         u64 devid;
3609         u8 uuid[BTRFS_UUID_SIZE];
3610         int num_stripes;
3611         int ret;
3612         int i;
3613
3614         logical = key->offset;
3615         length = btrfs_chunk_length(leaf, chunk);
3616
3617         read_lock(&map_tree->map_tree.lock);
3618         em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
3619         read_unlock(&map_tree->map_tree.lock);
3620
3621         /* already mapped? */
3622         if (em && em->start <= logical && em->start + em->len > logical) {
3623                 free_extent_map(em);
3624                 return 0;
3625         } else if (em) {
3626                 free_extent_map(em);
3627         }
3628
3629         em = alloc_extent_map();
3630         if (!em)
3631                 return -ENOMEM;
3632         num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3633         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
3634         if (!map) {
3635                 free_extent_map(em);
3636                 return -ENOMEM;
3637         }
3638
3639         em->bdev = (struct block_device *)map;
3640         em->start = logical;
3641         em->len = length;
3642         em->block_start = 0;
3643         em->block_len = em->len;
3644
3645         map->num_stripes = num_stripes;
3646         map->io_width = btrfs_chunk_io_width(leaf, chunk);
3647         map->io_align = btrfs_chunk_io_align(leaf, chunk);
3648         map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
3649         map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
3650         map->type = btrfs_chunk_type(leaf, chunk);
3651         map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
3652         for (i = 0; i < num_stripes; i++) {
3653                 map->stripes[i].physical =
3654                         btrfs_stripe_offset_nr(leaf, chunk, i);
3655                 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
3656                 read_extent_buffer(leaf, uuid, (unsigned long)
3657                                    btrfs_stripe_dev_uuid_nr(chunk, i),
3658                                    BTRFS_UUID_SIZE);
3659                 map->stripes[i].dev = btrfs_find_device(root, devid, uuid,
3660                                                         NULL);
3661                 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
3662                         kfree(map);
3663                         free_extent_map(em);
3664                         return -EIO;
3665                 }
3666                 if (!map->stripes[i].dev) {
3667                         map->stripes[i].dev =
3668                                 add_missing_dev(root, devid, uuid);
3669                         if (!map->stripes[i].dev) {
3670                                 kfree(map);
3671                                 free_extent_map(em);
3672                                 return -EIO;
3673                         }
3674                 }
3675                 map->stripes[i].dev->in_fs_metadata = 1;
3676         }
3677
3678         write_lock(&map_tree->map_tree.lock);
3679         ret = add_extent_mapping(&map_tree->map_tree, em);
3680         write_unlock(&map_tree->map_tree.lock);
3681         BUG_ON(ret);
3682         free_extent_map(em);
3683
3684         return 0;
3685 }
3686
3687 static int fill_device_from_item(struct extent_buffer *leaf,
3688                                  struct btrfs_dev_item *dev_item,
3689                                  struct btrfs_device *device)
3690 {
3691         unsigned long ptr;
3692
3693         device->devid = btrfs_device_id(leaf, dev_item);
3694         device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
3695         device->total_bytes = device->disk_total_bytes;
3696         device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
3697         device->type = btrfs_device_type(leaf, dev_item);
3698         device->io_align = btrfs_device_io_align(leaf, dev_item);
3699         device->io_width = btrfs_device_io_width(leaf, dev_item);
3700         device->sector_size = btrfs_device_sector_size(leaf, dev_item);
3701
3702         ptr = (unsigned long)btrfs_device_uuid(dev_item);
3703         read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
3704
3705         return 0;
3706 }
3707
3708 static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
3709 {
3710         struct btrfs_fs_devices *fs_devices;
3711         int ret;
3712
3713         mutex_lock(&uuid_mutex);
3714
3715         fs_devices = root->fs_info->fs_devices->seed;
3716         while (fs_devices) {
3717                 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
3718                         ret = 0;
3719                         goto out;
3720                 }
3721                 fs_devices = fs_devices->seed;
3722         }
3723
3724         fs_devices = find_fsid(fsid);
3725         if (!fs_devices) {
3726                 ret = -ENOENT;
3727                 goto out;
3728         }
3729
3730         fs_devices = clone_fs_devices(fs_devices);
3731         if (IS_ERR(fs_devices)) {
3732                 ret = PTR_ERR(fs_devices);
3733                 goto out;
3734         }
3735
3736         ret = __btrfs_open_devices(fs_devices, FMODE_READ,
3737                                    root->fs_info->bdev_holder);
3738         if (ret)
3739                 goto out;
3740
3741         if (!fs_devices->seeding) {
3742                 __btrfs_close_devices(fs_devices);
3743                 free_fs_devices(fs_devices);
3744                 ret = -EINVAL;
3745                 goto out;
3746         }
3747
3748         fs_devices->seed = root->fs_info->fs_devices->seed;
3749         root->fs_info->fs_devices->seed = fs_devices;
3750 out:
3751         mutex_unlock(&uuid_mutex);
3752         return ret;
3753 }
3754
3755 static int read_one_dev(struct btrfs_root *root,
3756                         struct extent_buffer *leaf,
3757                         struct btrfs_dev_item *dev_item)
3758 {
3759         struct btrfs_device *device;
3760         u64 devid;
3761         int ret;
3762         u8 fs_uuid[BTRFS_UUID_SIZE];
3763         u8 dev_uuid[BTRFS_UUID_SIZE];
3764
3765         devid = btrfs_device_id(leaf, dev_item);
3766         read_extent_buffer(leaf, dev_uuid,
3767                            (unsigned long)btrfs_device_uuid(dev_item),
3768                            BTRFS_UUID_SIZE);
3769         read_extent_buffer(leaf, fs_uuid,
3770                            (unsigned long)btrfs_device_fsid(dev_item),
3771                            BTRFS_UUID_SIZE);
3772
3773         if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
3774                 ret = open_seed_devices(root, fs_uuid);
3775                 if (ret && !btrfs_test_opt(root, DEGRADED))
3776                         return ret;
3777         }
3778
3779         device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
3780         if (!device || !device->bdev) {
3781                 if (!btrfs_test_opt(root, DEGRADED))
3782                         return -EIO;
3783
3784                 if (!device) {
3785                         printk(KERN_WARNING "warning devid %llu missing\n",
3786                                (unsigned long long)devid);
3787                         device = add_missing_dev(root, devid, dev_uuid);
3788                         if (!device)
3789                                 return -ENOMEM;
3790                 } else if (!device->missing) {
3791                         /*
3792                          * this happens when a device that was properly setup
3793                          * in the device info lists suddenly goes bad.
3794                          * device->bdev is NULL, and so we have to set
3795                          * device->missing to one here
3796                          */
3797                         root->fs_info->fs_devices->missing_devices++;
3798                         device->missing = 1;
3799                 }
3800         }
3801
3802         if (device->fs_devices != root->fs_info->fs_devices) {
3803                 BUG_ON(device->writeable);
3804                 if (device->generation !=
3805                     btrfs_device_generation(leaf, dev_item))
3806                         return -EINVAL;
3807         }
3808
3809         fill_device_from_item(leaf, dev_item, device);
3810         device->dev_root = root->fs_info->dev_root;
3811         device->in_fs_metadata = 1;
3812         if (device->writeable) {
3813                 device->fs_devices->total_rw_bytes += device->total_bytes;
3814                 spin_lock(&root->fs_info->free_chunk_lock);
3815                 root->fs_info->free_chunk_space += device->total_bytes -
3816                         device->bytes_used;
3817                 spin_unlock(&root->fs_info->free_chunk_lock);
3818         }
3819         ret = 0;
3820         return ret;
3821 }
3822
3823 int btrfs_read_sys_array(struct btrfs_root *root)
3824 {
3825         struct btrfs_super_block *super_copy = root->fs_info->super_copy;
3826         struct extent_buffer *sb;
3827         struct btrfs_disk_key *disk_key;
3828         struct btrfs_chunk *chunk;
3829         u8 *ptr;
3830         unsigned long sb_ptr;
3831         int ret = 0;
3832         u32 num_stripes;
3833         u32 array_size;
3834         u32 len = 0;
3835         u32 cur;
3836         struct btrfs_key key;
3837
3838         sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
3839                                           BTRFS_SUPER_INFO_SIZE);
3840         if (!sb)
3841                 return -ENOMEM;
3842         btrfs_set_buffer_uptodate(sb);
3843         btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
3844
3845         write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
3846         array_size = btrfs_super_sys_array_size(super_copy);
3847
3848         ptr = super_copy->sys_chunk_array;
3849         sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
3850         cur = 0;
3851
3852         while (cur < array_size) {
3853                 disk_key = (struct btrfs_disk_key *)ptr;
3854                 btrfs_disk_key_to_cpu(&key, disk_key);
3855
3856                 len = sizeof(*disk_key); ptr += len;
3857                 sb_ptr += len;
3858                 cur += len;
3859
3860                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
3861                         chunk = (struct btrfs_chunk *)sb_ptr;
3862                         ret = read_one_chunk(root, &key, sb, chunk);
3863                         if (ret)
3864                                 break;
3865                         num_stripes = btrfs_chunk_num_stripes(sb, chunk);
3866                         len = btrfs_chunk_item_size(num_stripes);
3867                 } else {
3868                         ret = -EIO;
3869                         break;
3870                 }
3871                 ptr += len;
3872                 sb_ptr += len;
3873                 cur += len;
3874         }
3875         free_extent_buffer(sb);
3876         return ret;
3877 }
3878
3879 int btrfs_read_chunk_tree(struct btrfs_root *root)
3880 {
3881         struct btrfs_path *path;
3882         struct extent_buffer *leaf;
3883         struct btrfs_key key;
3884         struct btrfs_key found_key;
3885         int ret;
3886         int slot;
3887
3888         root = root->fs_info->chunk_root;
3889
3890         path = btrfs_alloc_path();
3891         if (!path)
3892                 return -ENOMEM;
3893
3894         /* first we search for all of the device items, and then we
3895          * read in all of the chunk items.  This way we can create chunk
3896          * mappings that reference all of the devices that are afound
3897          */
3898         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
3899         key.offset = 0;
3900         key.type = 0;
3901 again:
3902         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3903         if (ret < 0)
3904                 goto error;
3905         while (1) {
3906                 leaf = path->nodes[0];
3907                 slot = path->slots[0];
3908                 if (slot >= btrfs_header_nritems(leaf)) {
3909                         ret = btrfs_next_leaf(root, path);
3910                         if (ret == 0)
3911                                 continue;
3912                         if (ret < 0)
3913                                 goto error;
3914                         break;
3915                 }
3916                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3917                 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
3918                         if (found_key.objectid != BTRFS_DEV_ITEMS_OBJECTID)
3919                                 break;
3920                         if (found_key.type == BTRFS_DEV_ITEM_KEY) {
3921                                 struct btrfs_dev_item *dev_item;
3922                                 dev_item = btrfs_item_ptr(leaf, slot,
3923                                                   struct btrfs_dev_item);
3924                                 ret = read_one_dev(root, leaf, dev_item);
3925                                 if (ret)
3926                                         goto error;
3927                         }
3928                 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
3929                         struct btrfs_chunk *chunk;
3930                         chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3931                         ret = read_one_chunk(root, &found_key, leaf, chunk);
3932                         if (ret)
3933                                 goto error;
3934                 }
3935                 path->slots[0]++;
3936         }
3937         if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
3938                 key.objectid = 0;
3939                 btrfs_release_path(path);
3940                 goto again;
3941         }
3942         ret = 0;
3943 error:
3944         btrfs_free_path(path);
3945         return ret;
3946 }