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