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