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