Revert "btrfs: clear PF_NOFREEZE in cleaner_kthread()"
[linux-2.6-block.git] / fs / btrfs / disk-io.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
19 #include <linux/fs.h>
20 #include <linux/blkdev.h>
21 #include <linux/scatterlist.h>
22 #include <linux/swap.h>
23 #include <linux/radix-tree.h>
24 #include <linux/writeback.h>
25 #include <linux/buffer_head.h>
26 #include <linux/workqueue.h>
27 #include <linux/kthread.h>
28 #include <linux/freezer.h>
29 #include <linux/slab.h>
30 #include <linux/migrate.h>
31 #include <linux/ratelimit.h>
32 #include <linux/uuid.h>
33 #include <linux/semaphore.h>
34 #include <asm/unaligned.h>
35 #include "ctree.h"
36 #include "disk-io.h"
37 #include "hash.h"
38 #include "transaction.h"
39 #include "btrfs_inode.h"
40 #include "volumes.h"
41 #include "print-tree.h"
42 #include "locking.h"
43 #include "tree-log.h"
44 #include "free-space-cache.h"
45 #include "free-space-tree.h"
46 #include "inode-map.h"
47 #include "check-integrity.h"
48 #include "rcu-string.h"
49 #include "dev-replace.h"
50 #include "raid56.h"
51 #include "sysfs.h"
52 #include "qgroup.h"
53
54 #ifdef CONFIG_X86
55 #include <asm/cpufeature.h>
56 #endif
57
58 #define BTRFS_SUPER_FLAG_SUPP   (BTRFS_HEADER_FLAG_WRITTEN |\
59                                  BTRFS_HEADER_FLAG_RELOC |\
60                                  BTRFS_SUPER_FLAG_ERROR |\
61                                  BTRFS_SUPER_FLAG_SEEDING |\
62                                  BTRFS_SUPER_FLAG_METADUMP)
63
64 static const struct extent_io_ops btree_extent_io_ops;
65 static void end_workqueue_fn(struct btrfs_work *work);
66 static void free_fs_root(struct btrfs_root *root);
67 static int btrfs_check_super_valid(struct btrfs_fs_info *fs_info,
68                                     int read_only);
69 static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
70 static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
71                                       struct btrfs_root *root);
72 static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
73 static int btrfs_destroy_marked_extents(struct btrfs_root *root,
74                                         struct extent_io_tree *dirty_pages,
75                                         int mark);
76 static int btrfs_destroy_pinned_extent(struct btrfs_root *root,
77                                        struct extent_io_tree *pinned_extents);
78 static int btrfs_cleanup_transaction(struct btrfs_root *root);
79 static void btrfs_error_commit_super(struct btrfs_root *root);
80
81 /*
82  * btrfs_end_io_wq structs are used to do processing in task context when an IO
83  * is complete.  This is used during reads to verify checksums, and it is used
84  * by writes to insert metadata for new file extents after IO is complete.
85  */
86 struct btrfs_end_io_wq {
87         struct bio *bio;
88         bio_end_io_t *end_io;
89         void *private;
90         struct btrfs_fs_info *info;
91         int error;
92         enum btrfs_wq_endio_type metadata;
93         struct list_head list;
94         struct btrfs_work work;
95 };
96
97 static struct kmem_cache *btrfs_end_io_wq_cache;
98
99 int __init btrfs_end_io_wq_init(void)
100 {
101         btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
102                                         sizeof(struct btrfs_end_io_wq),
103                                         0,
104                                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
105                                         NULL);
106         if (!btrfs_end_io_wq_cache)
107                 return -ENOMEM;
108         return 0;
109 }
110
111 void btrfs_end_io_wq_exit(void)
112 {
113         if (btrfs_end_io_wq_cache)
114                 kmem_cache_destroy(btrfs_end_io_wq_cache);
115 }
116
117 /*
118  * async submit bios are used to offload expensive checksumming
119  * onto the worker threads.  They checksum file and metadata bios
120  * just before they are sent down the IO stack.
121  */
122 struct async_submit_bio {
123         struct inode *inode;
124         struct bio *bio;
125         struct list_head list;
126         extent_submit_bio_hook_t *submit_bio_start;
127         extent_submit_bio_hook_t *submit_bio_done;
128         int rw;
129         int mirror_num;
130         unsigned long bio_flags;
131         /*
132          * bio_offset is optional, can be used if the pages in the bio
133          * can't tell us where in the file the bio should go
134          */
135         u64 bio_offset;
136         struct btrfs_work work;
137         int error;
138 };
139
140 /*
141  * Lockdep class keys for extent_buffer->lock's in this root.  For a given
142  * eb, the lockdep key is determined by the btrfs_root it belongs to and
143  * the level the eb occupies in the tree.
144  *
145  * Different roots are used for different purposes and may nest inside each
146  * other and they require separate keysets.  As lockdep keys should be
147  * static, assign keysets according to the purpose of the root as indicated
148  * by btrfs_root->objectid.  This ensures that all special purpose roots
149  * have separate keysets.
150  *
151  * Lock-nesting across peer nodes is always done with the immediate parent
152  * node locked thus preventing deadlock.  As lockdep doesn't know this, use
153  * subclass to avoid triggering lockdep warning in such cases.
154  *
155  * The key is set by the readpage_end_io_hook after the buffer has passed
156  * csum validation but before the pages are unlocked.  It is also set by
157  * btrfs_init_new_buffer on freshly allocated blocks.
158  *
159  * We also add a check to make sure the highest level of the tree is the
160  * same as our lockdep setup here.  If BTRFS_MAX_LEVEL changes, this code
161  * needs update as well.
162  */
163 #ifdef CONFIG_DEBUG_LOCK_ALLOC
164 # if BTRFS_MAX_LEVEL != 8
165 #  error
166 # endif
167
168 static struct btrfs_lockdep_keyset {
169         u64                     id;             /* root objectid */
170         const char              *name_stem;     /* lock name stem */
171         char                    names[BTRFS_MAX_LEVEL + 1][20];
172         struct lock_class_key   keys[BTRFS_MAX_LEVEL + 1];
173 } btrfs_lockdep_keysets[] = {
174         { .id = BTRFS_ROOT_TREE_OBJECTID,       .name_stem = "root"     },
175         { .id = BTRFS_EXTENT_TREE_OBJECTID,     .name_stem = "extent"   },
176         { .id = BTRFS_CHUNK_TREE_OBJECTID,      .name_stem = "chunk"    },
177         { .id = BTRFS_DEV_TREE_OBJECTID,        .name_stem = "dev"      },
178         { .id = BTRFS_FS_TREE_OBJECTID,         .name_stem = "fs"       },
179         { .id = BTRFS_CSUM_TREE_OBJECTID,       .name_stem = "csum"     },
180         { .id = BTRFS_QUOTA_TREE_OBJECTID,      .name_stem = "quota"    },
181         { .id = BTRFS_TREE_LOG_OBJECTID,        .name_stem = "log"      },
182         { .id = BTRFS_TREE_RELOC_OBJECTID,      .name_stem = "treloc"   },
183         { .id = BTRFS_DATA_RELOC_TREE_OBJECTID, .name_stem = "dreloc"   },
184         { .id = BTRFS_UUID_TREE_OBJECTID,       .name_stem = "uuid"     },
185         { .id = 0,                              .name_stem = "tree"     },
186 };
187
188 void __init btrfs_init_lockdep(void)
189 {
190         int i, j;
191
192         /* initialize lockdep class names */
193         for (i = 0; i < ARRAY_SIZE(btrfs_lockdep_keysets); i++) {
194                 struct btrfs_lockdep_keyset *ks = &btrfs_lockdep_keysets[i];
195
196                 for (j = 0; j < ARRAY_SIZE(ks->names); j++)
197                         snprintf(ks->names[j], sizeof(ks->names[j]),
198                                  "btrfs-%s-%02d", ks->name_stem, j);
199         }
200 }
201
202 void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
203                                     int level)
204 {
205         struct btrfs_lockdep_keyset *ks;
206
207         BUG_ON(level >= ARRAY_SIZE(ks->keys));
208
209         /* find the matching keyset, id 0 is the default entry */
210         for (ks = btrfs_lockdep_keysets; ks->id; ks++)
211                 if (ks->id == objectid)
212                         break;
213
214         lockdep_set_class_and_name(&eb->lock,
215                                    &ks->keys[level], ks->names[level]);
216 }
217
218 #endif
219
220 /*
221  * extents on the btree inode are pretty simple, there's one extent
222  * that covers the entire device
223  */
224 static struct extent_map *btree_get_extent(struct inode *inode,
225                 struct page *page, size_t pg_offset, u64 start, u64 len,
226                 int create)
227 {
228         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
229         struct extent_map *em;
230         int ret;
231
232         read_lock(&em_tree->lock);
233         em = lookup_extent_mapping(em_tree, start, len);
234         if (em) {
235                 em->bdev =
236                         BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev;
237                 read_unlock(&em_tree->lock);
238                 goto out;
239         }
240         read_unlock(&em_tree->lock);
241
242         em = alloc_extent_map();
243         if (!em) {
244                 em = ERR_PTR(-ENOMEM);
245                 goto out;
246         }
247         em->start = 0;
248         em->len = (u64)-1;
249         em->block_len = (u64)-1;
250         em->block_start = 0;
251         em->bdev = BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev;
252
253         write_lock(&em_tree->lock);
254         ret = add_extent_mapping(em_tree, em, 0);
255         if (ret == -EEXIST) {
256                 free_extent_map(em);
257                 em = lookup_extent_mapping(em_tree, start, len);
258                 if (!em)
259                         em = ERR_PTR(-EIO);
260         } else if (ret) {
261                 free_extent_map(em);
262                 em = ERR_PTR(ret);
263         }
264         write_unlock(&em_tree->lock);
265
266 out:
267         return em;
268 }
269
270 u32 btrfs_csum_data(char *data, u32 seed, size_t len)
271 {
272         return btrfs_crc32c(seed, data, len);
273 }
274
275 void btrfs_csum_final(u32 crc, char *result)
276 {
277         put_unaligned_le32(~crc, result);
278 }
279
280 /*
281  * compute the csum for a btree block, and either verify it or write it
282  * into the csum field of the block.
283  */
284 static int csum_tree_block(struct btrfs_fs_info *fs_info,
285                            struct extent_buffer *buf,
286                            int verify)
287 {
288         u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
289         char *result = NULL;
290         unsigned long len;
291         unsigned long cur_len;
292         unsigned long offset = BTRFS_CSUM_SIZE;
293         char *kaddr;
294         unsigned long map_start;
295         unsigned long map_len;
296         int err;
297         u32 crc = ~(u32)0;
298         unsigned long inline_result;
299
300         len = buf->len - offset;
301         while (len > 0) {
302                 err = map_private_extent_buffer(buf, offset, 32,
303                                         &kaddr, &map_start, &map_len);
304                 if (err)
305                         return 1;
306                 cur_len = min(len, map_len - (offset - map_start));
307                 crc = btrfs_csum_data(kaddr + offset - map_start,
308                                       crc, cur_len);
309                 len -= cur_len;
310                 offset += cur_len;
311         }
312         if (csum_size > sizeof(inline_result)) {
313                 result = kzalloc(csum_size, GFP_NOFS);
314                 if (!result)
315                         return 1;
316         } else {
317                 result = (char *)&inline_result;
318         }
319
320         btrfs_csum_final(crc, result);
321
322         if (verify) {
323                 if (memcmp_extent_buffer(buf, result, 0, csum_size)) {
324                         u32 val;
325                         u32 found = 0;
326                         memcpy(&found, result, csum_size);
327
328                         read_extent_buffer(buf, &val, 0, csum_size);
329                         btrfs_warn_rl(fs_info,
330                                 "%s checksum verify failed on %llu wanted %X found %X "
331                                 "level %d",
332                                 fs_info->sb->s_id, buf->start,
333                                 val, found, btrfs_header_level(buf));
334                         if (result != (char *)&inline_result)
335                                 kfree(result);
336                         return 1;
337                 }
338         } else {
339                 write_extent_buffer(buf, result, 0, csum_size);
340         }
341         if (result != (char *)&inline_result)
342                 kfree(result);
343         return 0;
344 }
345
346 /*
347  * we can't consider a given block up to date unless the transid of the
348  * block matches the transid in the parent node's pointer.  This is how we
349  * detect blocks that either didn't get written at all or got written
350  * in the wrong place.
351  */
352 static int verify_parent_transid(struct extent_io_tree *io_tree,
353                                  struct extent_buffer *eb, u64 parent_transid,
354                                  int atomic)
355 {
356         struct extent_state *cached_state = NULL;
357         int ret;
358         bool need_lock = (current->journal_info == BTRFS_SEND_TRANS_STUB);
359
360         if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
361                 return 0;
362
363         if (atomic)
364                 return -EAGAIN;
365
366         if (need_lock) {
367                 btrfs_tree_read_lock(eb);
368                 btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
369         }
370
371         lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
372                          &cached_state);
373         if (extent_buffer_uptodate(eb) &&
374             btrfs_header_generation(eb) == parent_transid) {
375                 ret = 0;
376                 goto out;
377         }
378         btrfs_err_rl(eb->fs_info,
379                 "parent transid verify failed on %llu wanted %llu found %llu",
380                         eb->start,
381                         parent_transid, btrfs_header_generation(eb));
382         ret = 1;
383
384         /*
385          * Things reading via commit roots that don't have normal protection,
386          * like send, can have a really old block in cache that may point at a
387          * block that has been free'd and re-allocated.  So don't clear uptodate
388          * if we find an eb that is under IO (dirty/writeback) because we could
389          * end up reading in the stale data and then writing it back out and
390          * making everybody very sad.
391          */
392         if (!extent_buffer_under_io(eb))
393                 clear_extent_buffer_uptodate(eb);
394 out:
395         unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
396                              &cached_state, GFP_NOFS);
397         if (need_lock)
398                 btrfs_tree_read_unlock_blocking(eb);
399         return ret;
400 }
401
402 /*
403  * Return 0 if the superblock checksum type matches the checksum value of that
404  * algorithm. Pass the raw disk superblock data.
405  */
406 static int btrfs_check_super_csum(char *raw_disk_sb)
407 {
408         struct btrfs_super_block *disk_sb =
409                 (struct btrfs_super_block *)raw_disk_sb;
410         u16 csum_type = btrfs_super_csum_type(disk_sb);
411         int ret = 0;
412
413         if (csum_type == BTRFS_CSUM_TYPE_CRC32) {
414                 u32 crc = ~(u32)0;
415                 const int csum_size = sizeof(crc);
416                 char result[csum_size];
417
418                 /*
419                  * The super_block structure does not span the whole
420                  * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space
421                  * is filled with zeros and is included in the checkum.
422                  */
423                 crc = btrfs_csum_data(raw_disk_sb + BTRFS_CSUM_SIZE,
424                                 crc, BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
425                 btrfs_csum_final(crc, result);
426
427                 if (memcmp(raw_disk_sb, result, csum_size))
428                         ret = 1;
429         }
430
431         if (csum_type >= ARRAY_SIZE(btrfs_csum_sizes)) {
432                 printk(KERN_ERR "BTRFS: unsupported checksum algorithm %u\n",
433                                 csum_type);
434                 ret = 1;
435         }
436
437         return ret;
438 }
439
440 /*
441  * helper to read a given tree block, doing retries as required when
442  * the checksums don't match and we have alternate mirrors to try.
443  */
444 static int btree_read_extent_buffer_pages(struct btrfs_root *root,
445                                           struct extent_buffer *eb,
446                                           u64 start, u64 parent_transid)
447 {
448         struct extent_io_tree *io_tree;
449         int failed = 0;
450         int ret;
451         int num_copies = 0;
452         int mirror_num = 0;
453         int failed_mirror = 0;
454
455         clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
456         io_tree = &BTRFS_I(root->fs_info->btree_inode)->io_tree;
457         while (1) {
458                 ret = read_extent_buffer_pages(io_tree, eb, start,
459                                                WAIT_COMPLETE,
460                                                btree_get_extent, mirror_num);
461                 if (!ret) {
462                         if (!verify_parent_transid(io_tree, eb,
463                                                    parent_transid, 0))
464                                 break;
465                         else
466                                 ret = -EIO;
467                 }
468
469                 /*
470                  * This buffer's crc is fine, but its contents are corrupted, so
471                  * there is no reason to read the other copies, they won't be
472                  * any less wrong.
473                  */
474                 if (test_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags))
475                         break;
476
477                 num_copies = btrfs_num_copies(root->fs_info,
478                                               eb->start, eb->len);
479                 if (num_copies == 1)
480                         break;
481
482                 if (!failed_mirror) {
483                         failed = 1;
484                         failed_mirror = eb->read_mirror;
485                 }
486
487                 mirror_num++;
488                 if (mirror_num == failed_mirror)
489                         mirror_num++;
490
491                 if (mirror_num > num_copies)
492                         break;
493         }
494
495         if (failed && !ret && failed_mirror)
496                 repair_eb_io_failure(root, eb, failed_mirror);
497
498         return ret;
499 }
500
501 /*
502  * checksum a dirty tree block before IO.  This has extra checks to make sure
503  * we only fill in the checksum field in the first page of a multi-page block
504  */
505
506 static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct page *page)
507 {
508         u64 start = page_offset(page);
509         u64 found_start;
510         struct extent_buffer *eb;
511
512         eb = (struct extent_buffer *)page->private;
513         if (page != eb->pages[0])
514                 return 0;
515         found_start = btrfs_header_bytenr(eb);
516         if (WARN_ON(found_start != start || !PageUptodate(page)))
517                 return 0;
518         csum_tree_block(fs_info, eb, 0);
519         return 0;
520 }
521
522 static int check_tree_block_fsid(struct btrfs_fs_info *fs_info,
523                                  struct extent_buffer *eb)
524 {
525         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
526         u8 fsid[BTRFS_UUID_SIZE];
527         int ret = 1;
528
529         read_extent_buffer(eb, fsid, btrfs_header_fsid(), BTRFS_FSID_SIZE);
530         while (fs_devices) {
531                 if (!memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE)) {
532                         ret = 0;
533                         break;
534                 }
535                 fs_devices = fs_devices->seed;
536         }
537         return ret;
538 }
539
540 #define CORRUPT(reason, eb, root, slot)                         \
541         btrfs_crit(root->fs_info, "corrupt leaf, %s: block=%llu,"       \
542                    "root=%llu, slot=%d", reason,                        \
543                btrfs_header_bytenr(eb), root->objectid, slot)
544
545 static noinline int check_leaf(struct btrfs_root *root,
546                                struct extent_buffer *leaf)
547 {
548         struct btrfs_key key;
549         struct btrfs_key leaf_key;
550         u32 nritems = btrfs_header_nritems(leaf);
551         int slot;
552
553         if (nritems == 0)
554                 return 0;
555
556         /* Check the 0 item */
557         if (btrfs_item_offset_nr(leaf, 0) + btrfs_item_size_nr(leaf, 0) !=
558             BTRFS_LEAF_DATA_SIZE(root)) {
559                 CORRUPT("invalid item offset size pair", leaf, root, 0);
560                 return -EIO;
561         }
562
563         /*
564          * Check to make sure each items keys are in the correct order and their
565          * offsets make sense.  We only have to loop through nritems-1 because
566          * we check the current slot against the next slot, which verifies the
567          * next slot's offset+size makes sense and that the current's slot
568          * offset is correct.
569          */
570         for (slot = 0; slot < nritems - 1; slot++) {
571                 btrfs_item_key_to_cpu(leaf, &leaf_key, slot);
572                 btrfs_item_key_to_cpu(leaf, &key, slot + 1);
573
574                 /* Make sure the keys are in the right order */
575                 if (btrfs_comp_cpu_keys(&leaf_key, &key) >= 0) {
576                         CORRUPT("bad key order", leaf, root, slot);
577                         return -EIO;
578                 }
579
580                 /*
581                  * Make sure the offset and ends are right, remember that the
582                  * item data starts at the end of the leaf and grows towards the
583                  * front.
584                  */
585                 if (btrfs_item_offset_nr(leaf, slot) !=
586                         btrfs_item_end_nr(leaf, slot + 1)) {
587                         CORRUPT("slot offset bad", leaf, root, slot);
588                         return -EIO;
589                 }
590
591                 /*
592                  * Check to make sure that we don't point outside of the leaf,
593                  * just incase all the items are consistent to eachother, but
594                  * all point outside of the leaf.
595                  */
596                 if (btrfs_item_end_nr(leaf, slot) >
597                     BTRFS_LEAF_DATA_SIZE(root)) {
598                         CORRUPT("slot end outside of leaf", leaf, root, slot);
599                         return -EIO;
600                 }
601         }
602
603         return 0;
604 }
605
606 static int btree_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
607                                       u64 phy_offset, struct page *page,
608                                       u64 start, u64 end, int mirror)
609 {
610         u64 found_start;
611         int found_level;
612         struct extent_buffer *eb;
613         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
614         int ret = 0;
615         int reads_done;
616
617         if (!page->private)
618                 goto out;
619
620         eb = (struct extent_buffer *)page->private;
621
622         /* the pending IO might have been the only thing that kept this buffer
623          * in memory.  Make sure we have a ref for all this other checks
624          */
625         extent_buffer_get(eb);
626
627         reads_done = atomic_dec_and_test(&eb->io_pages);
628         if (!reads_done)
629                 goto err;
630
631         eb->read_mirror = mirror;
632         if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
633                 ret = -EIO;
634                 goto err;
635         }
636
637         found_start = btrfs_header_bytenr(eb);
638         if (found_start != eb->start) {
639                 btrfs_err_rl(eb->fs_info, "bad tree block start %llu %llu",
640                                found_start, eb->start);
641                 ret = -EIO;
642                 goto err;
643         }
644         if (check_tree_block_fsid(root->fs_info, eb)) {
645                 btrfs_err_rl(eb->fs_info, "bad fsid on block %llu",
646                                eb->start);
647                 ret = -EIO;
648                 goto err;
649         }
650         found_level = btrfs_header_level(eb);
651         if (found_level >= BTRFS_MAX_LEVEL) {
652                 btrfs_err(root->fs_info, "bad tree block level %d",
653                            (int)btrfs_header_level(eb));
654                 ret = -EIO;
655                 goto err;
656         }
657
658         btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
659                                        eb, found_level);
660
661         ret = csum_tree_block(root->fs_info, eb, 1);
662         if (ret) {
663                 ret = -EIO;
664                 goto err;
665         }
666
667         /*
668          * If this is a leaf block and it is corrupt, set the corrupt bit so
669          * that we don't try and read the other copies of this block, just
670          * return -EIO.
671          */
672         if (found_level == 0 && check_leaf(root, eb)) {
673                 set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
674                 ret = -EIO;
675         }
676
677         if (!ret)
678                 set_extent_buffer_uptodate(eb);
679 err:
680         if (reads_done &&
681             test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
682                 btree_readahead_hook(root, eb, eb->start, ret);
683
684         if (ret) {
685                 /*
686                  * our io error hook is going to dec the io pages
687                  * again, we have to make sure it has something
688                  * to decrement
689                  */
690                 atomic_inc(&eb->io_pages);
691                 clear_extent_buffer_uptodate(eb);
692         }
693         free_extent_buffer(eb);
694 out:
695         return ret;
696 }
697
698 static int btree_io_failed_hook(struct page *page, int failed_mirror)
699 {
700         struct extent_buffer *eb;
701         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
702
703         eb = (struct extent_buffer *)page->private;
704         set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
705         eb->read_mirror = failed_mirror;
706         atomic_dec(&eb->io_pages);
707         if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
708                 btree_readahead_hook(root, eb, eb->start, -EIO);
709         return -EIO;    /* we fixed nothing */
710 }
711
712 static void end_workqueue_bio(struct bio *bio)
713 {
714         struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
715         struct btrfs_fs_info *fs_info;
716         struct btrfs_workqueue *wq;
717         btrfs_work_func_t func;
718
719         fs_info = end_io_wq->info;
720         end_io_wq->error = bio->bi_error;
721
722         if (bio->bi_rw & REQ_WRITE) {
723                 if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA) {
724                         wq = fs_info->endio_meta_write_workers;
725                         func = btrfs_endio_meta_write_helper;
726                 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE) {
727                         wq = fs_info->endio_freespace_worker;
728                         func = btrfs_freespace_write_helper;
729                 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
730                         wq = fs_info->endio_raid56_workers;
731                         func = btrfs_endio_raid56_helper;
732                 } else {
733                         wq = fs_info->endio_write_workers;
734                         func = btrfs_endio_write_helper;
735                 }
736         } else {
737                 if (unlikely(end_io_wq->metadata ==
738                              BTRFS_WQ_ENDIO_DIO_REPAIR)) {
739                         wq = fs_info->endio_repair_workers;
740                         func = btrfs_endio_repair_helper;
741                 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
742                         wq = fs_info->endio_raid56_workers;
743                         func = btrfs_endio_raid56_helper;
744                 } else if (end_io_wq->metadata) {
745                         wq = fs_info->endio_meta_workers;
746                         func = btrfs_endio_meta_helper;
747                 } else {
748                         wq = fs_info->endio_workers;
749                         func = btrfs_endio_helper;
750                 }
751         }
752
753         btrfs_init_work(&end_io_wq->work, func, end_workqueue_fn, NULL, NULL);
754         btrfs_queue_work(wq, &end_io_wq->work);
755 }
756
757 int btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
758                         enum btrfs_wq_endio_type metadata)
759 {
760         struct btrfs_end_io_wq *end_io_wq;
761
762         end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
763         if (!end_io_wq)
764                 return -ENOMEM;
765
766         end_io_wq->private = bio->bi_private;
767         end_io_wq->end_io = bio->bi_end_io;
768         end_io_wq->info = info;
769         end_io_wq->error = 0;
770         end_io_wq->bio = bio;
771         end_io_wq->metadata = metadata;
772
773         bio->bi_private = end_io_wq;
774         bio->bi_end_io = end_workqueue_bio;
775         return 0;
776 }
777
778 unsigned long btrfs_async_submit_limit(struct btrfs_fs_info *info)
779 {
780         unsigned long limit = min_t(unsigned long,
781                                     info->thread_pool_size,
782                                     info->fs_devices->open_devices);
783         return 256 * limit;
784 }
785
786 static void run_one_async_start(struct btrfs_work *work)
787 {
788         struct async_submit_bio *async;
789         int ret;
790
791         async = container_of(work, struct  async_submit_bio, work);
792         ret = async->submit_bio_start(async->inode, async->rw, async->bio,
793                                       async->mirror_num, async->bio_flags,
794                                       async->bio_offset);
795         if (ret)
796                 async->error = ret;
797 }
798
799 static void run_one_async_done(struct btrfs_work *work)
800 {
801         struct btrfs_fs_info *fs_info;
802         struct async_submit_bio *async;
803         int limit;
804
805         async = container_of(work, struct  async_submit_bio, work);
806         fs_info = BTRFS_I(async->inode)->root->fs_info;
807
808         limit = btrfs_async_submit_limit(fs_info);
809         limit = limit * 2 / 3;
810
811         /*
812          * atomic_dec_return implies a barrier for waitqueue_active
813          */
814         if (atomic_dec_return(&fs_info->nr_async_submits) < limit &&
815             waitqueue_active(&fs_info->async_submit_wait))
816                 wake_up(&fs_info->async_submit_wait);
817
818         /* If an error occured we just want to clean up the bio and move on */
819         if (async->error) {
820                 async->bio->bi_error = async->error;
821                 bio_endio(async->bio);
822                 return;
823         }
824
825         async->submit_bio_done(async->inode, async->rw, async->bio,
826                                async->mirror_num, async->bio_flags,
827                                async->bio_offset);
828 }
829
830 static void run_one_async_free(struct btrfs_work *work)
831 {
832         struct async_submit_bio *async;
833
834         async = container_of(work, struct  async_submit_bio, work);
835         kfree(async);
836 }
837
838 int btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct inode *inode,
839                         int rw, struct bio *bio, int mirror_num,
840                         unsigned long bio_flags,
841                         u64 bio_offset,
842                         extent_submit_bio_hook_t *submit_bio_start,
843                         extent_submit_bio_hook_t *submit_bio_done)
844 {
845         struct async_submit_bio *async;
846
847         async = kmalloc(sizeof(*async), GFP_NOFS);
848         if (!async)
849                 return -ENOMEM;
850
851         async->inode = inode;
852         async->rw = rw;
853         async->bio = bio;
854         async->mirror_num = mirror_num;
855         async->submit_bio_start = submit_bio_start;
856         async->submit_bio_done = submit_bio_done;
857
858         btrfs_init_work(&async->work, btrfs_worker_helper, run_one_async_start,
859                         run_one_async_done, run_one_async_free);
860
861         async->bio_flags = bio_flags;
862         async->bio_offset = bio_offset;
863
864         async->error = 0;
865
866         atomic_inc(&fs_info->nr_async_submits);
867
868         if (rw & REQ_SYNC)
869                 btrfs_set_work_high_priority(&async->work);
870
871         btrfs_queue_work(fs_info->workers, &async->work);
872
873         while (atomic_read(&fs_info->async_submit_draining) &&
874               atomic_read(&fs_info->nr_async_submits)) {
875                 wait_event(fs_info->async_submit_wait,
876                            (atomic_read(&fs_info->nr_async_submits) == 0));
877         }
878
879         return 0;
880 }
881
882 static int btree_csum_one_bio(struct bio *bio)
883 {
884         struct bio_vec *bvec;
885         struct btrfs_root *root;
886         int i, ret = 0;
887
888         bio_for_each_segment_all(bvec, bio, i) {
889                 root = BTRFS_I(bvec->bv_page->mapping->host)->root;
890                 ret = csum_dirty_buffer(root->fs_info, bvec->bv_page);
891                 if (ret)
892                         break;
893         }
894
895         return ret;
896 }
897
898 static int __btree_submit_bio_start(struct inode *inode, int rw,
899                                     struct bio *bio, int mirror_num,
900                                     unsigned long bio_flags,
901                                     u64 bio_offset)
902 {
903         /*
904          * when we're called for a write, we're already in the async
905          * submission context.  Just jump into btrfs_map_bio
906          */
907         return btree_csum_one_bio(bio);
908 }
909
910 static int __btree_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
911                                  int mirror_num, unsigned long bio_flags,
912                                  u64 bio_offset)
913 {
914         int ret;
915
916         /*
917          * when we're called for a write, we're already in the async
918          * submission context.  Just jump into btrfs_map_bio
919          */
920         ret = btrfs_map_bio(BTRFS_I(inode)->root, rw, bio, mirror_num, 1);
921         if (ret) {
922                 bio->bi_error = ret;
923                 bio_endio(bio);
924         }
925         return ret;
926 }
927
928 static int check_async_write(struct inode *inode, unsigned long bio_flags)
929 {
930         if (bio_flags & EXTENT_BIO_TREE_LOG)
931                 return 0;
932 #ifdef CONFIG_X86
933         if (cpu_has_xmm4_2)
934                 return 0;
935 #endif
936         return 1;
937 }
938
939 static int btree_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
940                                  int mirror_num, unsigned long bio_flags,
941                                  u64 bio_offset)
942 {
943         int async = check_async_write(inode, bio_flags);
944         int ret;
945
946         if (!(rw & REQ_WRITE)) {
947                 /*
948                  * called for a read, do the setup so that checksum validation
949                  * can happen in the async kernel threads
950                  */
951                 ret = btrfs_bio_wq_end_io(BTRFS_I(inode)->root->fs_info,
952                                           bio, BTRFS_WQ_ENDIO_METADATA);
953                 if (ret)
954                         goto out_w_error;
955                 ret = btrfs_map_bio(BTRFS_I(inode)->root, rw, bio,
956                                     mirror_num, 0);
957         } else if (!async) {
958                 ret = btree_csum_one_bio(bio);
959                 if (ret)
960                         goto out_w_error;
961                 ret = btrfs_map_bio(BTRFS_I(inode)->root, rw, bio,
962                                     mirror_num, 0);
963         } else {
964                 /*
965                  * kthread helpers are used to submit writes so that
966                  * checksumming can happen in parallel across all CPUs
967                  */
968                 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
969                                           inode, rw, bio, mirror_num, 0,
970                                           bio_offset,
971                                           __btree_submit_bio_start,
972                                           __btree_submit_bio_done);
973         }
974
975         if (ret)
976                 goto out_w_error;
977         return 0;
978
979 out_w_error:
980         bio->bi_error = ret;
981         bio_endio(bio);
982         return ret;
983 }
984
985 #ifdef CONFIG_MIGRATION
986 static int btree_migratepage(struct address_space *mapping,
987                         struct page *newpage, struct page *page,
988                         enum migrate_mode mode)
989 {
990         /*
991          * we can't safely write a btree page from here,
992          * we haven't done the locking hook
993          */
994         if (PageDirty(page))
995                 return -EAGAIN;
996         /*
997          * Buffers may be managed in a filesystem specific way.
998          * We must have no buffers or drop them.
999          */
1000         if (page_has_private(page) &&
1001             !try_to_release_page(page, GFP_KERNEL))
1002                 return -EAGAIN;
1003         return migrate_page(mapping, newpage, page, mode);
1004 }
1005 #endif
1006
1007
1008 static int btree_writepages(struct address_space *mapping,
1009                             struct writeback_control *wbc)
1010 {
1011         struct btrfs_fs_info *fs_info;
1012         int ret;
1013
1014         if (wbc->sync_mode == WB_SYNC_NONE) {
1015
1016                 if (wbc->for_kupdate)
1017                         return 0;
1018
1019                 fs_info = BTRFS_I(mapping->host)->root->fs_info;
1020                 /* this is a bit racy, but that's ok */
1021                 ret = percpu_counter_compare(&fs_info->dirty_metadata_bytes,
1022                                              BTRFS_DIRTY_METADATA_THRESH);
1023                 if (ret < 0)
1024                         return 0;
1025         }
1026         return btree_write_cache_pages(mapping, wbc);
1027 }
1028
1029 static int btree_readpage(struct file *file, struct page *page)
1030 {
1031         struct extent_io_tree *tree;
1032         tree = &BTRFS_I(page->mapping->host)->io_tree;
1033         return extent_read_full_page(tree, page, btree_get_extent, 0);
1034 }
1035
1036 static int btree_releasepage(struct page *page, gfp_t gfp_flags)
1037 {
1038         if (PageWriteback(page) || PageDirty(page))
1039                 return 0;
1040
1041         return try_release_extent_buffer(page);
1042 }
1043
1044 static void btree_invalidatepage(struct page *page, unsigned int offset,
1045                                  unsigned int length)
1046 {
1047         struct extent_io_tree *tree;
1048         tree = &BTRFS_I(page->mapping->host)->io_tree;
1049         extent_invalidatepage(tree, page, offset);
1050         btree_releasepage(page, GFP_NOFS);
1051         if (PagePrivate(page)) {
1052                 btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
1053                            "page private not zero on page %llu",
1054                            (unsigned long long)page_offset(page));
1055                 ClearPagePrivate(page);
1056                 set_page_private(page, 0);
1057                 page_cache_release(page);
1058         }
1059 }
1060
1061 static int btree_set_page_dirty(struct page *page)
1062 {
1063 #ifdef DEBUG
1064         struct extent_buffer *eb;
1065
1066         BUG_ON(!PagePrivate(page));
1067         eb = (struct extent_buffer *)page->private;
1068         BUG_ON(!eb);
1069         BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
1070         BUG_ON(!atomic_read(&eb->refs));
1071         btrfs_assert_tree_locked(eb);
1072 #endif
1073         return __set_page_dirty_nobuffers(page);
1074 }
1075
1076 static const struct address_space_operations btree_aops = {
1077         .readpage       = btree_readpage,
1078         .writepages     = btree_writepages,
1079         .releasepage    = btree_releasepage,
1080         .invalidatepage = btree_invalidatepage,
1081 #ifdef CONFIG_MIGRATION
1082         .migratepage    = btree_migratepage,
1083 #endif
1084         .set_page_dirty = btree_set_page_dirty,
1085 };
1086
1087 void readahead_tree_block(struct btrfs_root *root, u64 bytenr)
1088 {
1089         struct extent_buffer *buf = NULL;
1090         struct inode *btree_inode = root->fs_info->btree_inode;
1091
1092         buf = btrfs_find_create_tree_block(root, bytenr);
1093         if (!buf)
1094                 return;
1095         read_extent_buffer_pages(&BTRFS_I(btree_inode)->io_tree,
1096                                  buf, 0, WAIT_NONE, btree_get_extent, 0);
1097         free_extent_buffer(buf);
1098 }
1099
1100 int reada_tree_block_flagged(struct btrfs_root *root, u64 bytenr,
1101                          int mirror_num, struct extent_buffer **eb)
1102 {
1103         struct extent_buffer *buf = NULL;
1104         struct inode *btree_inode = root->fs_info->btree_inode;
1105         struct extent_io_tree *io_tree = &BTRFS_I(btree_inode)->io_tree;
1106         int ret;
1107
1108         buf = btrfs_find_create_tree_block(root, bytenr);
1109         if (!buf)
1110                 return 0;
1111
1112         set_bit(EXTENT_BUFFER_READAHEAD, &buf->bflags);
1113
1114         ret = read_extent_buffer_pages(io_tree, buf, 0, WAIT_PAGE_LOCK,
1115                                        btree_get_extent, mirror_num);
1116         if (ret) {
1117                 free_extent_buffer(buf);
1118                 return ret;
1119         }
1120
1121         if (test_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags)) {
1122                 free_extent_buffer(buf);
1123                 return -EIO;
1124         } else if (extent_buffer_uptodate(buf)) {
1125                 *eb = buf;
1126         } else {
1127                 free_extent_buffer(buf);
1128         }
1129         return 0;
1130 }
1131
1132 struct extent_buffer *btrfs_find_tree_block(struct btrfs_fs_info *fs_info,
1133                                             u64 bytenr)
1134 {
1135         return find_extent_buffer(fs_info, bytenr);
1136 }
1137
1138 struct extent_buffer *btrfs_find_create_tree_block(struct btrfs_root *root,
1139                                                  u64 bytenr)
1140 {
1141         if (btrfs_test_is_dummy_root(root))
1142                 return alloc_test_extent_buffer(root->fs_info, bytenr);
1143         return alloc_extent_buffer(root->fs_info, bytenr);
1144 }
1145
1146
1147 int btrfs_write_tree_block(struct extent_buffer *buf)
1148 {
1149         return filemap_fdatawrite_range(buf->pages[0]->mapping, buf->start,
1150                                         buf->start + buf->len - 1);
1151 }
1152
1153 int btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
1154 {
1155         return filemap_fdatawait_range(buf->pages[0]->mapping,
1156                                        buf->start, buf->start + buf->len - 1);
1157 }
1158
1159 struct extent_buffer *read_tree_block(struct btrfs_root *root, u64 bytenr,
1160                                       u64 parent_transid)
1161 {
1162         struct extent_buffer *buf = NULL;
1163         int ret;
1164
1165         buf = btrfs_find_create_tree_block(root, bytenr);
1166         if (!buf)
1167                 return ERR_PTR(-ENOMEM);
1168
1169         ret = btree_read_extent_buffer_pages(root, buf, 0, parent_transid);
1170         if (ret) {
1171                 free_extent_buffer(buf);
1172                 return ERR_PTR(ret);
1173         }
1174         return buf;
1175
1176 }
1177
1178 void clean_tree_block(struct btrfs_trans_handle *trans,
1179                       struct btrfs_fs_info *fs_info,
1180                       struct extent_buffer *buf)
1181 {
1182         if (btrfs_header_generation(buf) ==
1183             fs_info->running_transaction->transid) {
1184                 btrfs_assert_tree_locked(buf);
1185
1186                 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1187                         __percpu_counter_add(&fs_info->dirty_metadata_bytes,
1188                                              -buf->len,
1189                                              fs_info->dirty_metadata_batch);
1190                         /* ugh, clear_extent_buffer_dirty needs to lock the page */
1191                         btrfs_set_lock_blocking(buf);
1192                         clear_extent_buffer_dirty(buf);
1193                 }
1194         }
1195 }
1196
1197 static struct btrfs_subvolume_writers *btrfs_alloc_subvolume_writers(void)
1198 {
1199         struct btrfs_subvolume_writers *writers;
1200         int ret;
1201
1202         writers = kmalloc(sizeof(*writers), GFP_NOFS);
1203         if (!writers)
1204                 return ERR_PTR(-ENOMEM);
1205
1206         ret = percpu_counter_init(&writers->counter, 0, GFP_KERNEL);
1207         if (ret < 0) {
1208                 kfree(writers);
1209                 return ERR_PTR(ret);
1210         }
1211
1212         init_waitqueue_head(&writers->wait);
1213         return writers;
1214 }
1215
1216 static void
1217 btrfs_free_subvolume_writers(struct btrfs_subvolume_writers *writers)
1218 {
1219         percpu_counter_destroy(&writers->counter);
1220         kfree(writers);
1221 }
1222
1223 static void __setup_root(u32 nodesize, u32 sectorsize, u32 stripesize,
1224                          struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1225                          u64 objectid)
1226 {
1227         root->node = NULL;
1228         root->commit_root = NULL;
1229         root->sectorsize = sectorsize;
1230         root->nodesize = nodesize;
1231         root->stripesize = stripesize;
1232         root->state = 0;
1233         root->orphan_cleanup_state = 0;
1234
1235         root->objectid = objectid;
1236         root->last_trans = 0;
1237         root->highest_objectid = 0;
1238         root->nr_delalloc_inodes = 0;
1239         root->nr_ordered_extents = 0;
1240         root->name = NULL;
1241         root->inode_tree = RB_ROOT;
1242         INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1243         root->block_rsv = NULL;
1244         root->orphan_block_rsv = NULL;
1245
1246         INIT_LIST_HEAD(&root->dirty_list);
1247         INIT_LIST_HEAD(&root->root_list);
1248         INIT_LIST_HEAD(&root->delalloc_inodes);
1249         INIT_LIST_HEAD(&root->delalloc_root);
1250         INIT_LIST_HEAD(&root->ordered_extents);
1251         INIT_LIST_HEAD(&root->ordered_root);
1252         INIT_LIST_HEAD(&root->logged_list[0]);
1253         INIT_LIST_HEAD(&root->logged_list[1]);
1254         spin_lock_init(&root->orphan_lock);
1255         spin_lock_init(&root->inode_lock);
1256         spin_lock_init(&root->delalloc_lock);
1257         spin_lock_init(&root->ordered_extent_lock);
1258         spin_lock_init(&root->accounting_lock);
1259         spin_lock_init(&root->log_extents_lock[0]);
1260         spin_lock_init(&root->log_extents_lock[1]);
1261         mutex_init(&root->objectid_mutex);
1262         mutex_init(&root->log_mutex);
1263         mutex_init(&root->ordered_extent_mutex);
1264         mutex_init(&root->delalloc_mutex);
1265         init_waitqueue_head(&root->log_writer_wait);
1266         init_waitqueue_head(&root->log_commit_wait[0]);
1267         init_waitqueue_head(&root->log_commit_wait[1]);
1268         INIT_LIST_HEAD(&root->log_ctxs[0]);
1269         INIT_LIST_HEAD(&root->log_ctxs[1]);
1270         atomic_set(&root->log_commit[0], 0);
1271         atomic_set(&root->log_commit[1], 0);
1272         atomic_set(&root->log_writers, 0);
1273         atomic_set(&root->log_batch, 0);
1274         atomic_set(&root->orphan_inodes, 0);
1275         atomic_set(&root->refs, 1);
1276         atomic_set(&root->will_be_snapshoted, 0);
1277         atomic_set(&root->qgroup_meta_rsv, 0);
1278         root->log_transid = 0;
1279         root->log_transid_committed = -1;
1280         root->last_log_commit = 0;
1281         if (fs_info)
1282                 extent_io_tree_init(&root->dirty_log_pages,
1283                                      fs_info->btree_inode->i_mapping);
1284
1285         memset(&root->root_key, 0, sizeof(root->root_key));
1286         memset(&root->root_item, 0, sizeof(root->root_item));
1287         memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
1288         if (fs_info)
1289                 root->defrag_trans_start = fs_info->generation;
1290         else
1291                 root->defrag_trans_start = 0;
1292         root->root_key.objectid = objectid;
1293         root->anon_dev = 0;
1294
1295         spin_lock_init(&root->root_item_lock);
1296 }
1297
1298 static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info)
1299 {
1300         struct btrfs_root *root = kzalloc(sizeof(*root), GFP_NOFS);
1301         if (root)
1302                 root->fs_info = fs_info;
1303         return root;
1304 }
1305
1306 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
1307 /* Should only be used by the testing infrastructure */
1308 struct btrfs_root *btrfs_alloc_dummy_root(void)
1309 {
1310         struct btrfs_root *root;
1311
1312         root = btrfs_alloc_root(NULL);
1313         if (!root)
1314                 return ERR_PTR(-ENOMEM);
1315         __setup_root(4096, 4096, 4096, root, NULL, 1);
1316         set_bit(BTRFS_ROOT_DUMMY_ROOT, &root->state);
1317         root->alloc_bytenr = 0;
1318
1319         return root;
1320 }
1321 #endif
1322
1323 struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
1324                                      struct btrfs_fs_info *fs_info,
1325                                      u64 objectid)
1326 {
1327         struct extent_buffer *leaf;
1328         struct btrfs_root *tree_root = fs_info->tree_root;
1329         struct btrfs_root *root;
1330         struct btrfs_key key;
1331         int ret = 0;
1332         uuid_le uuid;
1333
1334         root = btrfs_alloc_root(fs_info);
1335         if (!root)
1336                 return ERR_PTR(-ENOMEM);
1337
1338         __setup_root(tree_root->nodesize, tree_root->sectorsize,
1339                 tree_root->stripesize, root, fs_info, objectid);
1340         root->root_key.objectid = objectid;
1341         root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1342         root->root_key.offset = 0;
1343
1344         leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
1345         if (IS_ERR(leaf)) {
1346                 ret = PTR_ERR(leaf);
1347                 leaf = NULL;
1348                 goto fail;
1349         }
1350
1351         memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
1352         btrfs_set_header_bytenr(leaf, leaf->start);
1353         btrfs_set_header_generation(leaf, trans->transid);
1354         btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
1355         btrfs_set_header_owner(leaf, objectid);
1356         root->node = leaf;
1357
1358         write_extent_buffer(leaf, fs_info->fsid, btrfs_header_fsid(),
1359                             BTRFS_FSID_SIZE);
1360         write_extent_buffer(leaf, fs_info->chunk_tree_uuid,
1361                             btrfs_header_chunk_tree_uuid(leaf),
1362                             BTRFS_UUID_SIZE);
1363         btrfs_mark_buffer_dirty(leaf);
1364
1365         root->commit_root = btrfs_root_node(root);
1366         set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
1367
1368         root->root_item.flags = 0;
1369         root->root_item.byte_limit = 0;
1370         btrfs_set_root_bytenr(&root->root_item, leaf->start);
1371         btrfs_set_root_generation(&root->root_item, trans->transid);
1372         btrfs_set_root_level(&root->root_item, 0);
1373         btrfs_set_root_refs(&root->root_item, 1);
1374         btrfs_set_root_used(&root->root_item, leaf->len);
1375         btrfs_set_root_last_snapshot(&root->root_item, 0);
1376         btrfs_set_root_dirid(&root->root_item, 0);
1377         uuid_le_gen(&uuid);
1378         memcpy(root->root_item.uuid, uuid.b, BTRFS_UUID_SIZE);
1379         root->root_item.drop_level = 0;
1380
1381         key.objectid = objectid;
1382         key.type = BTRFS_ROOT_ITEM_KEY;
1383         key.offset = 0;
1384         ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
1385         if (ret)
1386                 goto fail;
1387
1388         btrfs_tree_unlock(leaf);
1389
1390         return root;
1391
1392 fail:
1393         if (leaf) {
1394                 btrfs_tree_unlock(leaf);
1395                 free_extent_buffer(root->commit_root);
1396                 free_extent_buffer(leaf);
1397         }
1398         kfree(root);
1399
1400         return ERR_PTR(ret);
1401 }
1402
1403 static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1404                                          struct btrfs_fs_info *fs_info)
1405 {
1406         struct btrfs_root *root;
1407         struct btrfs_root *tree_root = fs_info->tree_root;
1408         struct extent_buffer *leaf;
1409
1410         root = btrfs_alloc_root(fs_info);
1411         if (!root)
1412                 return ERR_PTR(-ENOMEM);
1413
1414         __setup_root(tree_root->nodesize, tree_root->sectorsize,
1415                      tree_root->stripesize, root, fs_info,
1416                      BTRFS_TREE_LOG_OBJECTID);
1417
1418         root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1419         root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1420         root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
1421
1422         /*
1423          * DON'T set REF_COWS for log trees
1424          *
1425          * log trees do not get reference counted because they go away
1426          * before a real commit is actually done.  They do store pointers
1427          * to file data extents, and those reference counts still get
1428          * updated (along with back refs to the log tree).
1429          */
1430
1431         leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
1432                         NULL, 0, 0, 0);
1433         if (IS_ERR(leaf)) {
1434                 kfree(root);
1435                 return ERR_CAST(leaf);
1436         }
1437
1438         memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
1439         btrfs_set_header_bytenr(leaf, leaf->start);
1440         btrfs_set_header_generation(leaf, trans->transid);
1441         btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
1442         btrfs_set_header_owner(leaf, BTRFS_TREE_LOG_OBJECTID);
1443         root->node = leaf;
1444
1445         write_extent_buffer(root->node, root->fs_info->fsid,
1446                             btrfs_header_fsid(), BTRFS_FSID_SIZE);
1447         btrfs_mark_buffer_dirty(root->node);
1448         btrfs_tree_unlock(root->node);
1449         return root;
1450 }
1451
1452 int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
1453                              struct btrfs_fs_info *fs_info)
1454 {
1455         struct btrfs_root *log_root;
1456
1457         log_root = alloc_log_tree(trans, fs_info);
1458         if (IS_ERR(log_root))
1459                 return PTR_ERR(log_root);
1460         WARN_ON(fs_info->log_root_tree);
1461         fs_info->log_root_tree = log_root;
1462         return 0;
1463 }
1464
1465 int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
1466                        struct btrfs_root *root)
1467 {
1468         struct btrfs_root *log_root;
1469         struct btrfs_inode_item *inode_item;
1470
1471         log_root = alloc_log_tree(trans, root->fs_info);
1472         if (IS_ERR(log_root))
1473                 return PTR_ERR(log_root);
1474
1475         log_root->last_trans = trans->transid;
1476         log_root->root_key.offset = root->root_key.objectid;
1477
1478         inode_item = &log_root->root_item.inode;
1479         btrfs_set_stack_inode_generation(inode_item, 1);
1480         btrfs_set_stack_inode_size(inode_item, 3);
1481         btrfs_set_stack_inode_nlink(inode_item, 1);
1482         btrfs_set_stack_inode_nbytes(inode_item, root->nodesize);
1483         btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
1484
1485         btrfs_set_root_node(&log_root->root_item, log_root->node);
1486
1487         WARN_ON(root->log_root);
1488         root->log_root = log_root;
1489         root->log_transid = 0;
1490         root->log_transid_committed = -1;
1491         root->last_log_commit = 0;
1492         return 0;
1493 }
1494
1495 static struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1496                                                struct btrfs_key *key)
1497 {
1498         struct btrfs_root *root;
1499         struct btrfs_fs_info *fs_info = tree_root->fs_info;
1500         struct btrfs_path *path;
1501         u64 generation;
1502         int ret;
1503
1504         path = btrfs_alloc_path();
1505         if (!path)
1506                 return ERR_PTR(-ENOMEM);
1507
1508         root = btrfs_alloc_root(fs_info);
1509         if (!root) {
1510                 ret = -ENOMEM;
1511                 goto alloc_fail;
1512         }
1513
1514         __setup_root(tree_root->nodesize, tree_root->sectorsize,
1515                 tree_root->stripesize, root, fs_info, key->objectid);
1516
1517         ret = btrfs_find_root(tree_root, key, path,
1518                               &root->root_item, &root->root_key);
1519         if (ret) {
1520                 if (ret > 0)
1521                         ret = -ENOENT;
1522                 goto find_fail;
1523         }
1524
1525         generation = btrfs_root_generation(&root->root_item);
1526         root->node = read_tree_block(root, btrfs_root_bytenr(&root->root_item),
1527                                      generation);
1528         if (IS_ERR(root->node)) {
1529                 ret = PTR_ERR(root->node);
1530                 goto find_fail;
1531         } else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1532                 ret = -EIO;
1533                 free_extent_buffer(root->node);
1534                 goto find_fail;
1535         }
1536         root->commit_root = btrfs_root_node(root);
1537 out:
1538         btrfs_free_path(path);
1539         return root;
1540
1541 find_fail:
1542         kfree(root);
1543 alloc_fail:
1544         root = ERR_PTR(ret);
1545         goto out;
1546 }
1547
1548 struct btrfs_root *btrfs_read_fs_root(struct btrfs_root *tree_root,
1549                                       struct btrfs_key *location)
1550 {
1551         struct btrfs_root *root;
1552
1553         root = btrfs_read_tree_root(tree_root, location);
1554         if (IS_ERR(root))
1555                 return root;
1556
1557         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
1558                 set_bit(BTRFS_ROOT_REF_COWS, &root->state);
1559                 btrfs_check_and_init_root_item(&root->root_item);
1560         }
1561
1562         return root;
1563 }
1564
1565 int btrfs_init_fs_root(struct btrfs_root *root)
1566 {
1567         int ret;
1568         struct btrfs_subvolume_writers *writers;
1569
1570         root->free_ino_ctl = kzalloc(sizeof(*root->free_ino_ctl), GFP_NOFS);
1571         root->free_ino_pinned = kzalloc(sizeof(*root->free_ino_pinned),
1572                                         GFP_NOFS);
1573         if (!root->free_ino_pinned || !root->free_ino_ctl) {
1574                 ret = -ENOMEM;
1575                 goto fail;
1576         }
1577
1578         writers = btrfs_alloc_subvolume_writers();
1579         if (IS_ERR(writers)) {
1580                 ret = PTR_ERR(writers);
1581                 goto fail;
1582         }
1583         root->subv_writers = writers;
1584
1585         btrfs_init_free_ino_ctl(root);
1586         spin_lock_init(&root->ino_cache_lock);
1587         init_waitqueue_head(&root->ino_cache_wait);
1588
1589         ret = get_anon_bdev(&root->anon_dev);
1590         if (ret)
1591                 goto free_writers;
1592
1593         mutex_lock(&root->objectid_mutex);
1594         ret = btrfs_find_highest_objectid(root,
1595                                         &root->highest_objectid);
1596         if (ret) {
1597                 mutex_unlock(&root->objectid_mutex);
1598                 goto free_root_dev;
1599         }
1600
1601         ASSERT(root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
1602
1603         mutex_unlock(&root->objectid_mutex);
1604
1605         return 0;
1606
1607 free_root_dev:
1608         free_anon_bdev(root->anon_dev);
1609 free_writers:
1610         btrfs_free_subvolume_writers(root->subv_writers);
1611 fail:
1612         kfree(root->free_ino_ctl);
1613         kfree(root->free_ino_pinned);
1614         return ret;
1615 }
1616
1617 static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1618                                                u64 root_id)
1619 {
1620         struct btrfs_root *root;
1621
1622         spin_lock(&fs_info->fs_roots_radix_lock);
1623         root = radix_tree_lookup(&fs_info->fs_roots_radix,
1624                                  (unsigned long)root_id);
1625         spin_unlock(&fs_info->fs_roots_radix_lock);
1626         return root;
1627 }
1628
1629 int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1630                          struct btrfs_root *root)
1631 {
1632         int ret;
1633
1634         ret = radix_tree_preload(GFP_NOFS & ~__GFP_HIGHMEM);
1635         if (ret)
1636                 return ret;
1637
1638         spin_lock(&fs_info->fs_roots_radix_lock);
1639         ret = radix_tree_insert(&fs_info->fs_roots_radix,
1640                                 (unsigned long)root->root_key.objectid,
1641                                 root);
1642         if (ret == 0)
1643                 set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1644         spin_unlock(&fs_info->fs_roots_radix_lock);
1645         radix_tree_preload_end();
1646
1647         return ret;
1648 }
1649
1650 struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1651                                      struct btrfs_key *location,
1652                                      bool check_ref)
1653 {
1654         struct btrfs_root *root;
1655         struct btrfs_path *path;
1656         struct btrfs_key key;
1657         int ret;
1658
1659         if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
1660                 return fs_info->tree_root;
1661         if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
1662                 return fs_info->extent_root;
1663         if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
1664                 return fs_info->chunk_root;
1665         if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
1666                 return fs_info->dev_root;
1667         if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
1668                 return fs_info->csum_root;
1669         if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
1670                 return fs_info->quota_root ? fs_info->quota_root :
1671                                              ERR_PTR(-ENOENT);
1672         if (location->objectid == BTRFS_UUID_TREE_OBJECTID)
1673                 return fs_info->uuid_root ? fs_info->uuid_root :
1674                                             ERR_PTR(-ENOENT);
1675         if (location->objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
1676                 return fs_info->free_space_root ? fs_info->free_space_root :
1677                                                   ERR_PTR(-ENOENT);
1678 again:
1679         root = btrfs_lookup_fs_root(fs_info, location->objectid);
1680         if (root) {
1681                 if (check_ref && btrfs_root_refs(&root->root_item) == 0)
1682                         return ERR_PTR(-ENOENT);
1683                 return root;
1684         }
1685
1686         root = btrfs_read_fs_root(fs_info->tree_root, location);
1687         if (IS_ERR(root))
1688                 return root;
1689
1690         if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1691                 ret = -ENOENT;
1692                 goto fail;
1693         }
1694
1695         ret = btrfs_init_fs_root(root);
1696         if (ret)
1697                 goto fail;
1698
1699         path = btrfs_alloc_path();
1700         if (!path) {
1701                 ret = -ENOMEM;
1702                 goto fail;
1703         }
1704         key.objectid = BTRFS_ORPHAN_OBJECTID;
1705         key.type = BTRFS_ORPHAN_ITEM_KEY;
1706         key.offset = location->objectid;
1707
1708         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1709         btrfs_free_path(path);
1710         if (ret < 0)
1711                 goto fail;
1712         if (ret == 0)
1713                 set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1714
1715         ret = btrfs_insert_fs_root(fs_info, root);
1716         if (ret) {
1717                 if (ret == -EEXIST) {
1718                         free_fs_root(root);
1719                         goto again;
1720                 }
1721                 goto fail;
1722         }
1723         return root;
1724 fail:
1725         free_fs_root(root);
1726         return ERR_PTR(ret);
1727 }
1728
1729 static int btrfs_congested_fn(void *congested_data, int bdi_bits)
1730 {
1731         struct btrfs_fs_info *info = (struct btrfs_fs_info *)congested_data;
1732         int ret = 0;
1733         struct btrfs_device *device;
1734         struct backing_dev_info *bdi;
1735
1736         rcu_read_lock();
1737         list_for_each_entry_rcu(device, &info->fs_devices->devices, dev_list) {
1738                 if (!device->bdev)
1739                         continue;
1740                 bdi = blk_get_backing_dev_info(device->bdev);
1741                 if (bdi_congested(bdi, bdi_bits)) {
1742                         ret = 1;
1743                         break;
1744                 }
1745         }
1746         rcu_read_unlock();
1747         return ret;
1748 }
1749
1750 static int setup_bdi(struct btrfs_fs_info *info, struct backing_dev_info *bdi)
1751 {
1752         int err;
1753
1754         err = bdi_setup_and_register(bdi, "btrfs");
1755         if (err)
1756                 return err;
1757
1758         bdi->ra_pages = VM_MAX_READAHEAD * 1024 / PAGE_CACHE_SIZE;
1759         bdi->congested_fn       = btrfs_congested_fn;
1760         bdi->congested_data     = info;
1761         bdi->capabilities |= BDI_CAP_CGROUP_WRITEBACK;
1762         return 0;
1763 }
1764
1765 /*
1766  * called by the kthread helper functions to finally call the bio end_io
1767  * functions.  This is where read checksum verification actually happens
1768  */
1769 static void end_workqueue_fn(struct btrfs_work *work)
1770 {
1771         struct bio *bio;
1772         struct btrfs_end_io_wq *end_io_wq;
1773
1774         end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1775         bio = end_io_wq->bio;
1776
1777         bio->bi_error = end_io_wq->error;
1778         bio->bi_private = end_io_wq->private;
1779         bio->bi_end_io = end_io_wq->end_io;
1780         kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
1781         bio_endio(bio);
1782 }
1783
1784 static int cleaner_kthread(void *arg)
1785 {
1786         struct btrfs_root *root = arg;
1787         int again;
1788         struct btrfs_trans_handle *trans;
1789
1790         do {
1791                 again = 0;
1792
1793                 /* Make the cleaner go to sleep early. */
1794                 if (btrfs_need_cleaner_sleep(root))
1795                         goto sleep;
1796
1797                 if (!mutex_trylock(&root->fs_info->cleaner_mutex))
1798                         goto sleep;
1799
1800                 /*
1801                  * Avoid the problem that we change the status of the fs
1802                  * during the above check and trylock.
1803                  */
1804                 if (btrfs_need_cleaner_sleep(root)) {
1805                         mutex_unlock(&root->fs_info->cleaner_mutex);
1806                         goto sleep;
1807                 }
1808
1809                 mutex_lock(&root->fs_info->cleaner_delayed_iput_mutex);
1810                 btrfs_run_delayed_iputs(root);
1811                 mutex_unlock(&root->fs_info->cleaner_delayed_iput_mutex);
1812
1813                 again = btrfs_clean_one_deleted_snapshot(root);
1814                 mutex_unlock(&root->fs_info->cleaner_mutex);
1815
1816                 /*
1817                  * The defragger has dealt with the R/O remount and umount,
1818                  * needn't do anything special here.
1819                  */
1820                 btrfs_run_defrag_inodes(root->fs_info);
1821
1822                 /*
1823                  * Acquires fs_info->delete_unused_bgs_mutex to avoid racing
1824                  * with relocation (btrfs_relocate_chunk) and relocation
1825                  * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1826                  * after acquiring fs_info->delete_unused_bgs_mutex. So we
1827                  * can't hold, nor need to, fs_info->cleaner_mutex when deleting
1828                  * unused block groups.
1829                  */
1830                 btrfs_delete_unused_bgs(root->fs_info);
1831 sleep:
1832                 if (!try_to_freeze() && !again) {
1833                         set_current_state(TASK_INTERRUPTIBLE);
1834                         if (!kthread_should_stop())
1835                                 schedule();
1836                         __set_current_state(TASK_RUNNING);
1837                 }
1838         } while (!kthread_should_stop());
1839
1840         /*
1841          * Transaction kthread is stopped before us and wakes us up.
1842          * However we might have started a new transaction and COWed some
1843          * tree blocks when deleting unused block groups for example. So
1844          * make sure we commit the transaction we started to have a clean
1845          * shutdown when evicting the btree inode - if it has dirty pages
1846          * when we do the final iput() on it, eviction will trigger a
1847          * writeback for it which will fail with null pointer dereferences
1848          * since work queues and other resources were already released and
1849          * destroyed by the time the iput/eviction/writeback is made.
1850          */
1851         trans = btrfs_attach_transaction(root);
1852         if (IS_ERR(trans)) {
1853                 if (PTR_ERR(trans) != -ENOENT)
1854                         btrfs_err(root->fs_info,
1855                                   "cleaner transaction attach returned %ld",
1856                                   PTR_ERR(trans));
1857         } else {
1858                 int ret;
1859
1860                 ret = btrfs_commit_transaction(trans, root);
1861                 if (ret)
1862                         btrfs_err(root->fs_info,
1863                                   "cleaner open transaction commit returned %d",
1864                                   ret);
1865         }
1866
1867         return 0;
1868 }
1869
1870 static int transaction_kthread(void *arg)
1871 {
1872         struct btrfs_root *root = arg;
1873         struct btrfs_trans_handle *trans;
1874         struct btrfs_transaction *cur;
1875         u64 transid;
1876         unsigned long now;
1877         unsigned long delay;
1878         bool cannot_commit;
1879
1880         do {
1881                 cannot_commit = false;
1882                 delay = HZ * root->fs_info->commit_interval;
1883                 mutex_lock(&root->fs_info->transaction_kthread_mutex);
1884
1885                 spin_lock(&root->fs_info->trans_lock);
1886                 cur = root->fs_info->running_transaction;
1887                 if (!cur) {
1888                         spin_unlock(&root->fs_info->trans_lock);
1889                         goto sleep;
1890                 }
1891
1892                 now = get_seconds();
1893                 if (cur->state < TRANS_STATE_BLOCKED &&
1894                     (now < cur->start_time ||
1895                      now - cur->start_time < root->fs_info->commit_interval)) {
1896                         spin_unlock(&root->fs_info->trans_lock);
1897                         delay = HZ * 5;
1898                         goto sleep;
1899                 }
1900                 transid = cur->transid;
1901                 spin_unlock(&root->fs_info->trans_lock);
1902
1903                 /* If the file system is aborted, this will always fail. */
1904                 trans = btrfs_attach_transaction(root);
1905                 if (IS_ERR(trans)) {
1906                         if (PTR_ERR(trans) != -ENOENT)
1907                                 cannot_commit = true;
1908                         goto sleep;
1909                 }
1910                 if (transid == trans->transid) {
1911                         btrfs_commit_transaction(trans, root);
1912                 } else {
1913                         btrfs_end_transaction(trans, root);
1914                 }
1915 sleep:
1916                 wake_up_process(root->fs_info->cleaner_kthread);
1917                 mutex_unlock(&root->fs_info->transaction_kthread_mutex);
1918
1919                 if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
1920                                       &root->fs_info->fs_state)))
1921                         btrfs_cleanup_transaction(root);
1922                 if (!try_to_freeze()) {
1923                         set_current_state(TASK_INTERRUPTIBLE);
1924                         if (!kthread_should_stop() &&
1925                             (!btrfs_transaction_blocked(root->fs_info) ||
1926                              cannot_commit))
1927                                 schedule_timeout(delay);
1928                         __set_current_state(TASK_RUNNING);
1929                 }
1930         } while (!kthread_should_stop());
1931         return 0;
1932 }
1933
1934 /*
1935  * this will find the highest generation in the array of
1936  * root backups.  The index of the highest array is returned,
1937  * or -1 if we can't find anything.
1938  *
1939  * We check to make sure the array is valid by comparing the
1940  * generation of the latest  root in the array with the generation
1941  * in the super block.  If they don't match we pitch it.
1942  */
1943 static int find_newest_super_backup(struct btrfs_fs_info *info, u64 newest_gen)
1944 {
1945         u64 cur;
1946         int newest_index = -1;
1947         struct btrfs_root_backup *root_backup;
1948         int i;
1949
1950         for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1951                 root_backup = info->super_copy->super_roots + i;
1952                 cur = btrfs_backup_tree_root_gen(root_backup);
1953                 if (cur == newest_gen)
1954                         newest_index = i;
1955         }
1956
1957         /* check to see if we actually wrapped around */
1958         if (newest_index == BTRFS_NUM_BACKUP_ROOTS - 1) {
1959                 root_backup = info->super_copy->super_roots;
1960                 cur = btrfs_backup_tree_root_gen(root_backup);
1961                 if (cur == newest_gen)
1962                         newest_index = 0;
1963         }
1964         return newest_index;
1965 }
1966
1967
1968 /*
1969  * find the oldest backup so we know where to store new entries
1970  * in the backup array.  This will set the backup_root_index
1971  * field in the fs_info struct
1972  */
1973 static void find_oldest_super_backup(struct btrfs_fs_info *info,
1974                                      u64 newest_gen)
1975 {
1976         int newest_index = -1;
1977
1978         newest_index = find_newest_super_backup(info, newest_gen);
1979         /* if there was garbage in there, just move along */
1980         if (newest_index == -1) {
1981                 info->backup_root_index = 0;
1982         } else {
1983                 info->backup_root_index = (newest_index + 1) % BTRFS_NUM_BACKUP_ROOTS;
1984         }
1985 }
1986
1987 /*
1988  * copy all the root pointers into the super backup array.
1989  * this will bump the backup pointer by one when it is
1990  * done
1991  */
1992 static void backup_super_roots(struct btrfs_fs_info *info)
1993 {
1994         int next_backup;
1995         struct btrfs_root_backup *root_backup;
1996         int last_backup;
1997
1998         next_backup = info->backup_root_index;
1999         last_backup = (next_backup + BTRFS_NUM_BACKUP_ROOTS - 1) %
2000                 BTRFS_NUM_BACKUP_ROOTS;
2001
2002         /*
2003          * just overwrite the last backup if we're at the same generation
2004          * this happens only at umount
2005          */
2006         root_backup = info->super_for_commit->super_roots + last_backup;
2007         if (btrfs_backup_tree_root_gen(root_backup) ==
2008             btrfs_header_generation(info->tree_root->node))
2009                 next_backup = last_backup;
2010
2011         root_backup = info->super_for_commit->super_roots + next_backup;
2012
2013         /*
2014          * make sure all of our padding and empty slots get zero filled
2015          * regardless of which ones we use today
2016          */
2017         memset(root_backup, 0, sizeof(*root_backup));
2018
2019         info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
2020
2021         btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
2022         btrfs_set_backup_tree_root_gen(root_backup,
2023                                btrfs_header_generation(info->tree_root->node));
2024
2025         btrfs_set_backup_tree_root_level(root_backup,
2026                                btrfs_header_level(info->tree_root->node));
2027
2028         btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
2029         btrfs_set_backup_chunk_root_gen(root_backup,
2030                                btrfs_header_generation(info->chunk_root->node));
2031         btrfs_set_backup_chunk_root_level(root_backup,
2032                                btrfs_header_level(info->chunk_root->node));
2033
2034         btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
2035         btrfs_set_backup_extent_root_gen(root_backup,
2036                                btrfs_header_generation(info->extent_root->node));
2037         btrfs_set_backup_extent_root_level(root_backup,
2038                                btrfs_header_level(info->extent_root->node));
2039
2040         /*
2041          * we might commit during log recovery, which happens before we set
2042          * the fs_root.  Make sure it is valid before we fill it in.
2043          */
2044         if (info->fs_root && info->fs_root->node) {
2045                 btrfs_set_backup_fs_root(root_backup,
2046                                          info->fs_root->node->start);
2047                 btrfs_set_backup_fs_root_gen(root_backup,
2048                                btrfs_header_generation(info->fs_root->node));
2049                 btrfs_set_backup_fs_root_level(root_backup,
2050                                btrfs_header_level(info->fs_root->node));
2051         }
2052
2053         btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
2054         btrfs_set_backup_dev_root_gen(root_backup,
2055                                btrfs_header_generation(info->dev_root->node));
2056         btrfs_set_backup_dev_root_level(root_backup,
2057                                        btrfs_header_level(info->dev_root->node));
2058
2059         btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
2060         btrfs_set_backup_csum_root_gen(root_backup,
2061                                btrfs_header_generation(info->csum_root->node));
2062         btrfs_set_backup_csum_root_level(root_backup,
2063                                btrfs_header_level(info->csum_root->node));
2064
2065         btrfs_set_backup_total_bytes(root_backup,
2066                              btrfs_super_total_bytes(info->super_copy));
2067         btrfs_set_backup_bytes_used(root_backup,
2068                              btrfs_super_bytes_used(info->super_copy));
2069         btrfs_set_backup_num_devices(root_backup,
2070                              btrfs_super_num_devices(info->super_copy));
2071
2072         /*
2073          * if we don't copy this out to the super_copy, it won't get remembered
2074          * for the next commit
2075          */
2076         memcpy(&info->super_copy->super_roots,
2077                &info->super_for_commit->super_roots,
2078                sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
2079 }
2080
2081 /*
2082  * this copies info out of the root backup array and back into
2083  * the in-memory super block.  It is meant to help iterate through
2084  * the array, so you send it the number of backups you've already
2085  * tried and the last backup index you used.
2086  *
2087  * this returns -1 when it has tried all the backups
2088  */
2089 static noinline int next_root_backup(struct btrfs_fs_info *info,
2090                                      struct btrfs_super_block *super,
2091                                      int *num_backups_tried, int *backup_index)
2092 {
2093         struct btrfs_root_backup *root_backup;
2094         int newest = *backup_index;
2095
2096         if (*num_backups_tried == 0) {
2097                 u64 gen = btrfs_super_generation(super);
2098
2099                 newest = find_newest_super_backup(info, gen);
2100                 if (newest == -1)
2101                         return -1;
2102
2103                 *backup_index = newest;
2104                 *num_backups_tried = 1;
2105         } else if (*num_backups_tried == BTRFS_NUM_BACKUP_ROOTS) {
2106                 /* we've tried all the backups, all done */
2107                 return -1;
2108         } else {
2109                 /* jump to the next oldest backup */
2110                 newest = (*backup_index + BTRFS_NUM_BACKUP_ROOTS - 1) %
2111                         BTRFS_NUM_BACKUP_ROOTS;
2112                 *backup_index = newest;
2113                 *num_backups_tried += 1;
2114         }
2115         root_backup = super->super_roots + newest;
2116
2117         btrfs_set_super_generation(super,
2118                                    btrfs_backup_tree_root_gen(root_backup));
2119         btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2120         btrfs_set_super_root_level(super,
2121                                    btrfs_backup_tree_root_level(root_backup));
2122         btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2123
2124         /*
2125          * fixme: the total bytes and num_devices need to match or we should
2126          * need a fsck
2127          */
2128         btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2129         btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2130         return 0;
2131 }
2132
2133 /* helper to cleanup workers */
2134 static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
2135 {
2136         btrfs_destroy_workqueue(fs_info->fixup_workers);
2137         btrfs_destroy_workqueue(fs_info->delalloc_workers);
2138         btrfs_destroy_workqueue(fs_info->workers);
2139         btrfs_destroy_workqueue(fs_info->endio_workers);
2140         btrfs_destroy_workqueue(fs_info->endio_meta_workers);
2141         btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
2142         btrfs_destroy_workqueue(fs_info->endio_repair_workers);
2143         btrfs_destroy_workqueue(fs_info->rmw_workers);
2144         btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
2145         btrfs_destroy_workqueue(fs_info->endio_write_workers);
2146         btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
2147         btrfs_destroy_workqueue(fs_info->submit_workers);
2148         btrfs_destroy_workqueue(fs_info->delayed_workers);
2149         btrfs_destroy_workqueue(fs_info->caching_workers);
2150         btrfs_destroy_workqueue(fs_info->readahead_workers);
2151         btrfs_destroy_workqueue(fs_info->flush_workers);
2152         btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2153         btrfs_destroy_workqueue(fs_info->extent_workers);
2154 }
2155
2156 static void free_root_extent_buffers(struct btrfs_root *root)
2157 {
2158         if (root) {
2159                 free_extent_buffer(root->node);
2160                 free_extent_buffer(root->commit_root);
2161                 root->node = NULL;
2162                 root->commit_root = NULL;
2163         }
2164 }
2165
2166 /* helper to cleanup tree roots */
2167 static void free_root_pointers(struct btrfs_fs_info *info, int chunk_root)
2168 {
2169         free_root_extent_buffers(info->tree_root);
2170
2171         free_root_extent_buffers(info->dev_root);
2172         free_root_extent_buffers(info->extent_root);
2173         free_root_extent_buffers(info->csum_root);
2174         free_root_extent_buffers(info->quota_root);
2175         free_root_extent_buffers(info->uuid_root);
2176         if (chunk_root)
2177                 free_root_extent_buffers(info->chunk_root);
2178         free_root_extent_buffers(info->free_space_root);
2179 }
2180
2181 void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2182 {
2183         int ret;
2184         struct btrfs_root *gang[8];
2185         int i;
2186
2187         while (!list_empty(&fs_info->dead_roots)) {
2188                 gang[0] = list_entry(fs_info->dead_roots.next,
2189                                      struct btrfs_root, root_list);
2190                 list_del(&gang[0]->root_list);
2191
2192                 if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state)) {
2193                         btrfs_drop_and_free_fs_root(fs_info, gang[0]);
2194                 } else {
2195                         free_extent_buffer(gang[0]->node);
2196                         free_extent_buffer(gang[0]->commit_root);
2197                         btrfs_put_fs_root(gang[0]);
2198                 }
2199         }
2200
2201         while (1) {
2202                 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2203                                              (void **)gang, 0,
2204                                              ARRAY_SIZE(gang));
2205                 if (!ret)
2206                         break;
2207                 for (i = 0; i < ret; i++)
2208                         btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2209         }
2210
2211         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
2212                 btrfs_free_log_root_tree(NULL, fs_info);
2213                 btrfs_destroy_pinned_extent(fs_info->tree_root,
2214                                             fs_info->pinned_extents);
2215         }
2216 }
2217
2218 static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2219 {
2220         mutex_init(&fs_info->scrub_lock);
2221         atomic_set(&fs_info->scrubs_running, 0);
2222         atomic_set(&fs_info->scrub_pause_req, 0);
2223         atomic_set(&fs_info->scrubs_paused, 0);
2224         atomic_set(&fs_info->scrub_cancel_req, 0);
2225         init_waitqueue_head(&fs_info->scrub_pause_wait);
2226         fs_info->scrub_workers_refcnt = 0;
2227 }
2228
2229 static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2230 {
2231         spin_lock_init(&fs_info->balance_lock);
2232         mutex_init(&fs_info->balance_mutex);
2233         atomic_set(&fs_info->balance_running, 0);
2234         atomic_set(&fs_info->balance_pause_req, 0);
2235         atomic_set(&fs_info->balance_cancel_req, 0);
2236         fs_info->balance_ctl = NULL;
2237         init_waitqueue_head(&fs_info->balance_wait_q);
2238 }
2239
2240 static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info,
2241                                    struct btrfs_root *tree_root)
2242 {
2243         fs_info->btree_inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
2244         set_nlink(fs_info->btree_inode, 1);
2245         /*
2246          * we set the i_size on the btree inode to the max possible int.
2247          * the real end of the address space is determined by all of
2248          * the devices in the system
2249          */
2250         fs_info->btree_inode->i_size = OFFSET_MAX;
2251         fs_info->btree_inode->i_mapping->a_ops = &btree_aops;
2252
2253         RB_CLEAR_NODE(&BTRFS_I(fs_info->btree_inode)->rb_node);
2254         extent_io_tree_init(&BTRFS_I(fs_info->btree_inode)->io_tree,
2255                              fs_info->btree_inode->i_mapping);
2256         BTRFS_I(fs_info->btree_inode)->io_tree.track_uptodate = 0;
2257         extent_map_tree_init(&BTRFS_I(fs_info->btree_inode)->extent_tree);
2258
2259         BTRFS_I(fs_info->btree_inode)->io_tree.ops = &btree_extent_io_ops;
2260
2261         BTRFS_I(fs_info->btree_inode)->root = tree_root;
2262         memset(&BTRFS_I(fs_info->btree_inode)->location, 0,
2263                sizeof(struct btrfs_key));
2264         set_bit(BTRFS_INODE_DUMMY,
2265                 &BTRFS_I(fs_info->btree_inode)->runtime_flags);
2266         btrfs_insert_inode_hash(fs_info->btree_inode);
2267 }
2268
2269 static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2270 {
2271         fs_info->dev_replace.lock_owner = 0;
2272         atomic_set(&fs_info->dev_replace.nesting_level, 0);
2273         mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2274         mutex_init(&fs_info->dev_replace.lock_management_lock);
2275         mutex_init(&fs_info->dev_replace.lock);
2276         init_waitqueue_head(&fs_info->replace_wait);
2277 }
2278
2279 static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2280 {
2281         spin_lock_init(&fs_info->qgroup_lock);
2282         mutex_init(&fs_info->qgroup_ioctl_lock);
2283         fs_info->qgroup_tree = RB_ROOT;
2284         fs_info->qgroup_op_tree = RB_ROOT;
2285         INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2286         fs_info->qgroup_seq = 1;
2287         fs_info->quota_enabled = 0;
2288         fs_info->pending_quota_state = 0;
2289         fs_info->qgroup_ulist = NULL;
2290         mutex_init(&fs_info->qgroup_rescan_lock);
2291 }
2292
2293 static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
2294                 struct btrfs_fs_devices *fs_devices)
2295 {
2296         int max_active = fs_info->thread_pool_size;
2297         unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
2298
2299         fs_info->workers =
2300                 btrfs_alloc_workqueue("worker", flags | WQ_HIGHPRI,
2301                                       max_active, 16);
2302
2303         fs_info->delalloc_workers =
2304                 btrfs_alloc_workqueue("delalloc", flags, max_active, 2);
2305
2306         fs_info->flush_workers =
2307                 btrfs_alloc_workqueue("flush_delalloc", flags, max_active, 0);
2308
2309         fs_info->caching_workers =
2310                 btrfs_alloc_workqueue("cache", flags, max_active, 0);
2311
2312         /*
2313          * a higher idle thresh on the submit workers makes it much more
2314          * likely that bios will be send down in a sane order to the
2315          * devices
2316          */
2317         fs_info->submit_workers =
2318                 btrfs_alloc_workqueue("submit", flags,
2319                                       min_t(u64, fs_devices->num_devices,
2320                                             max_active), 64);
2321
2322         fs_info->fixup_workers =
2323                 btrfs_alloc_workqueue("fixup", flags, 1, 0);
2324
2325         /*
2326          * endios are largely parallel and should have a very
2327          * low idle thresh
2328          */
2329         fs_info->endio_workers =
2330                 btrfs_alloc_workqueue("endio", flags, max_active, 4);
2331         fs_info->endio_meta_workers =
2332                 btrfs_alloc_workqueue("endio-meta", flags, max_active, 4);
2333         fs_info->endio_meta_write_workers =
2334                 btrfs_alloc_workqueue("endio-meta-write", flags, max_active, 2);
2335         fs_info->endio_raid56_workers =
2336                 btrfs_alloc_workqueue("endio-raid56", flags, max_active, 4);
2337         fs_info->endio_repair_workers =
2338                 btrfs_alloc_workqueue("endio-repair", flags, 1, 0);
2339         fs_info->rmw_workers =
2340                 btrfs_alloc_workqueue("rmw", flags, max_active, 2);
2341         fs_info->endio_write_workers =
2342                 btrfs_alloc_workqueue("endio-write", flags, max_active, 2);
2343         fs_info->endio_freespace_worker =
2344                 btrfs_alloc_workqueue("freespace-write", flags, max_active, 0);
2345         fs_info->delayed_workers =
2346                 btrfs_alloc_workqueue("delayed-meta", flags, max_active, 0);
2347         fs_info->readahead_workers =
2348                 btrfs_alloc_workqueue("readahead", flags, max_active, 2);
2349         fs_info->qgroup_rescan_workers =
2350                 btrfs_alloc_workqueue("qgroup-rescan", flags, 1, 0);
2351         fs_info->extent_workers =
2352                 btrfs_alloc_workqueue("extent-refs", flags,
2353                                       min_t(u64, fs_devices->num_devices,
2354                                             max_active), 8);
2355
2356         if (!(fs_info->workers && fs_info->delalloc_workers &&
2357               fs_info->submit_workers && fs_info->flush_workers &&
2358               fs_info->endio_workers && fs_info->endio_meta_workers &&
2359               fs_info->endio_meta_write_workers &&
2360               fs_info->endio_repair_workers &&
2361               fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
2362               fs_info->endio_freespace_worker && fs_info->rmw_workers &&
2363               fs_info->caching_workers && fs_info->readahead_workers &&
2364               fs_info->fixup_workers && fs_info->delayed_workers &&
2365               fs_info->extent_workers &&
2366               fs_info->qgroup_rescan_workers)) {
2367                 return -ENOMEM;
2368         }
2369
2370         return 0;
2371 }
2372
2373 static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
2374                             struct btrfs_fs_devices *fs_devices)
2375 {
2376         int ret;
2377         struct btrfs_root *tree_root = fs_info->tree_root;
2378         struct btrfs_root *log_tree_root;
2379         struct btrfs_super_block *disk_super = fs_info->super_copy;
2380         u64 bytenr = btrfs_super_log_root(disk_super);
2381
2382         if (fs_devices->rw_devices == 0) {
2383                 btrfs_warn(fs_info, "log replay required on RO media");
2384                 return -EIO;
2385         }
2386
2387         log_tree_root = btrfs_alloc_root(fs_info);
2388         if (!log_tree_root)
2389                 return -ENOMEM;
2390
2391         __setup_root(tree_root->nodesize, tree_root->sectorsize,
2392                         tree_root->stripesize, log_tree_root, fs_info,
2393                         BTRFS_TREE_LOG_OBJECTID);
2394
2395         log_tree_root->node = read_tree_block(tree_root, bytenr,
2396                         fs_info->generation + 1);
2397         if (IS_ERR(log_tree_root->node)) {
2398                 btrfs_warn(fs_info, "failed to read log tree");
2399                 ret = PTR_ERR(log_tree_root->node);
2400                 kfree(log_tree_root);
2401                 return ret;
2402         } else if (!extent_buffer_uptodate(log_tree_root->node)) {
2403                 btrfs_err(fs_info, "failed to read log tree");
2404                 free_extent_buffer(log_tree_root->node);
2405                 kfree(log_tree_root);
2406                 return -EIO;
2407         }
2408         /* returns with log_tree_root freed on success */
2409         ret = btrfs_recover_log_trees(log_tree_root);
2410         if (ret) {
2411                 btrfs_std_error(tree_root->fs_info, ret,
2412                             "Failed to recover log tree");
2413                 free_extent_buffer(log_tree_root->node);
2414                 kfree(log_tree_root);
2415                 return ret;
2416         }
2417
2418         if (fs_info->sb->s_flags & MS_RDONLY) {
2419                 ret = btrfs_commit_super(tree_root);
2420                 if (ret)
2421                         return ret;
2422         }
2423
2424         return 0;
2425 }
2426
2427 static int btrfs_read_roots(struct btrfs_fs_info *fs_info,
2428                             struct btrfs_root *tree_root)
2429 {
2430         struct btrfs_root *root;
2431         struct btrfs_key location;
2432         int ret;
2433
2434         location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
2435         location.type = BTRFS_ROOT_ITEM_KEY;
2436         location.offset = 0;
2437
2438         root = btrfs_read_tree_root(tree_root, &location);
2439         if (IS_ERR(root))
2440                 return PTR_ERR(root);
2441         set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2442         fs_info->extent_root = root;
2443
2444         location.objectid = BTRFS_DEV_TREE_OBJECTID;
2445         root = btrfs_read_tree_root(tree_root, &location);
2446         if (IS_ERR(root))
2447                 return PTR_ERR(root);
2448         set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2449         fs_info->dev_root = root;
2450         btrfs_init_devices_late(fs_info);
2451
2452         location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2453         root = btrfs_read_tree_root(tree_root, &location);
2454         if (IS_ERR(root))
2455                 return PTR_ERR(root);
2456         set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2457         fs_info->csum_root = root;
2458
2459         location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2460         root = btrfs_read_tree_root(tree_root, &location);
2461         if (!IS_ERR(root)) {
2462                 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2463                 fs_info->quota_enabled = 1;
2464                 fs_info->pending_quota_state = 1;
2465                 fs_info->quota_root = root;
2466         }
2467
2468         location.objectid = BTRFS_UUID_TREE_OBJECTID;
2469         root = btrfs_read_tree_root(tree_root, &location);
2470         if (IS_ERR(root)) {
2471                 ret = PTR_ERR(root);
2472                 if (ret != -ENOENT)
2473                         return ret;
2474         } else {
2475                 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2476                 fs_info->uuid_root = root;
2477         }
2478
2479         if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
2480                 location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
2481                 root = btrfs_read_tree_root(tree_root, &location);
2482                 if (IS_ERR(root))
2483                         return PTR_ERR(root);
2484                 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2485                 fs_info->free_space_root = root;
2486         }
2487
2488         return 0;
2489 }
2490
2491 int open_ctree(struct super_block *sb,
2492                struct btrfs_fs_devices *fs_devices,
2493                char *options)
2494 {
2495         u32 sectorsize;
2496         u32 nodesize;
2497         u32 stripesize;
2498         u64 generation;
2499         u64 features;
2500         struct btrfs_key location;
2501         struct buffer_head *bh;
2502         struct btrfs_super_block *disk_super;
2503         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2504         struct btrfs_root *tree_root;
2505         struct btrfs_root *chunk_root;
2506         int ret;
2507         int err = -EINVAL;
2508         int num_backups_tried = 0;
2509         int backup_index = 0;
2510         int max_active;
2511
2512         tree_root = fs_info->tree_root = btrfs_alloc_root(fs_info);
2513         chunk_root = fs_info->chunk_root = btrfs_alloc_root(fs_info);
2514         if (!tree_root || !chunk_root) {
2515                 err = -ENOMEM;
2516                 goto fail;
2517         }
2518
2519         ret = init_srcu_struct(&fs_info->subvol_srcu);
2520         if (ret) {
2521                 err = ret;
2522                 goto fail;
2523         }
2524
2525         ret = setup_bdi(fs_info, &fs_info->bdi);
2526         if (ret) {
2527                 err = ret;
2528                 goto fail_srcu;
2529         }
2530
2531         ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2532         if (ret) {
2533                 err = ret;
2534                 goto fail_bdi;
2535         }
2536         fs_info->dirty_metadata_batch = PAGE_CACHE_SIZE *
2537                                         (1 + ilog2(nr_cpu_ids));
2538
2539         ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2540         if (ret) {
2541                 err = ret;
2542                 goto fail_dirty_metadata_bytes;
2543         }
2544
2545         ret = percpu_counter_init(&fs_info->bio_counter, 0, GFP_KERNEL);
2546         if (ret) {
2547                 err = ret;
2548                 goto fail_delalloc_bytes;
2549         }
2550
2551         fs_info->btree_inode = new_inode(sb);
2552         if (!fs_info->btree_inode) {
2553                 err = -ENOMEM;
2554                 goto fail_bio_counter;
2555         }
2556
2557         mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
2558
2559         INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2560         INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
2561         INIT_LIST_HEAD(&fs_info->trans_list);
2562         INIT_LIST_HEAD(&fs_info->dead_roots);
2563         INIT_LIST_HEAD(&fs_info->delayed_iputs);
2564         INIT_LIST_HEAD(&fs_info->delalloc_roots);
2565         INIT_LIST_HEAD(&fs_info->caching_block_groups);
2566         spin_lock_init(&fs_info->delalloc_root_lock);
2567         spin_lock_init(&fs_info->trans_lock);
2568         spin_lock_init(&fs_info->fs_roots_radix_lock);
2569         spin_lock_init(&fs_info->delayed_iput_lock);
2570         spin_lock_init(&fs_info->defrag_inodes_lock);
2571         spin_lock_init(&fs_info->free_chunk_lock);
2572         spin_lock_init(&fs_info->tree_mod_seq_lock);
2573         spin_lock_init(&fs_info->super_lock);
2574         spin_lock_init(&fs_info->qgroup_op_lock);
2575         spin_lock_init(&fs_info->buffer_lock);
2576         spin_lock_init(&fs_info->unused_bgs_lock);
2577         rwlock_init(&fs_info->tree_mod_log_lock);
2578         mutex_init(&fs_info->unused_bg_unpin_mutex);
2579         mutex_init(&fs_info->delete_unused_bgs_mutex);
2580         mutex_init(&fs_info->reloc_mutex);
2581         mutex_init(&fs_info->delalloc_root_mutex);
2582         mutex_init(&fs_info->cleaner_delayed_iput_mutex);
2583         seqlock_init(&fs_info->profiles_lock);
2584
2585         INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
2586         INIT_LIST_HEAD(&fs_info->space_info);
2587         INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
2588         INIT_LIST_HEAD(&fs_info->unused_bgs);
2589         btrfs_mapping_init(&fs_info->mapping_tree);
2590         btrfs_init_block_rsv(&fs_info->global_block_rsv,
2591                              BTRFS_BLOCK_RSV_GLOBAL);
2592         btrfs_init_block_rsv(&fs_info->delalloc_block_rsv,
2593                              BTRFS_BLOCK_RSV_DELALLOC);
2594         btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
2595         btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
2596         btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
2597         btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
2598                              BTRFS_BLOCK_RSV_DELOPS);
2599         atomic_set(&fs_info->nr_async_submits, 0);
2600         atomic_set(&fs_info->async_delalloc_pages, 0);
2601         atomic_set(&fs_info->async_submit_draining, 0);
2602         atomic_set(&fs_info->nr_async_bios, 0);
2603         atomic_set(&fs_info->defrag_running, 0);
2604         atomic_set(&fs_info->qgroup_op_seq, 0);
2605         atomic64_set(&fs_info->tree_mod_seq, 0);
2606         fs_info->sb = sb;
2607         fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
2608         fs_info->metadata_ratio = 0;
2609         fs_info->defrag_inodes = RB_ROOT;
2610         fs_info->free_chunk_space = 0;
2611         fs_info->tree_mod_log = RB_ROOT;
2612         fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2613         fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
2614         /* readahead state */
2615         INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
2616         spin_lock_init(&fs_info->reada_lock);
2617
2618         fs_info->thread_pool_size = min_t(unsigned long,
2619                                           num_online_cpus() + 2, 8);
2620
2621         INIT_LIST_HEAD(&fs_info->ordered_roots);
2622         spin_lock_init(&fs_info->ordered_root_lock);
2623         fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
2624                                         GFP_NOFS);
2625         if (!fs_info->delayed_root) {
2626                 err = -ENOMEM;
2627                 goto fail_iput;
2628         }
2629         btrfs_init_delayed_root(fs_info->delayed_root);
2630
2631         btrfs_init_scrub(fs_info);
2632 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
2633         fs_info->check_integrity_print_mask = 0;
2634 #endif
2635         btrfs_init_balance(fs_info);
2636         btrfs_init_async_reclaim_work(&fs_info->async_reclaim_work);
2637
2638         sb->s_blocksize = 4096;
2639         sb->s_blocksize_bits = blksize_bits(4096);
2640         sb->s_bdi = &fs_info->bdi;
2641
2642         btrfs_init_btree_inode(fs_info, tree_root);
2643
2644         spin_lock_init(&fs_info->block_group_cache_lock);
2645         fs_info->block_group_cache_tree = RB_ROOT;
2646         fs_info->first_logical_byte = (u64)-1;
2647
2648         extent_io_tree_init(&fs_info->freed_extents[0],
2649                              fs_info->btree_inode->i_mapping);
2650         extent_io_tree_init(&fs_info->freed_extents[1],
2651                              fs_info->btree_inode->i_mapping);
2652         fs_info->pinned_extents = &fs_info->freed_extents[0];
2653         fs_info->do_barriers = 1;
2654
2655
2656         mutex_init(&fs_info->ordered_operations_mutex);
2657         mutex_init(&fs_info->tree_log_mutex);
2658         mutex_init(&fs_info->chunk_mutex);
2659         mutex_init(&fs_info->transaction_kthread_mutex);
2660         mutex_init(&fs_info->cleaner_mutex);
2661         mutex_init(&fs_info->volume_mutex);
2662         mutex_init(&fs_info->ro_block_group_mutex);
2663         init_rwsem(&fs_info->commit_root_sem);
2664         init_rwsem(&fs_info->cleanup_work_sem);
2665         init_rwsem(&fs_info->subvol_sem);
2666         sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2667
2668         btrfs_init_dev_replace_locks(fs_info);
2669         btrfs_init_qgroup(fs_info);
2670
2671         btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2672         btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2673
2674         init_waitqueue_head(&fs_info->transaction_throttle);
2675         init_waitqueue_head(&fs_info->transaction_wait);
2676         init_waitqueue_head(&fs_info->transaction_blocked_wait);
2677         init_waitqueue_head(&fs_info->async_submit_wait);
2678
2679         INIT_LIST_HEAD(&fs_info->pinned_chunks);
2680
2681         ret = btrfs_alloc_stripe_hash_table(fs_info);
2682         if (ret) {
2683                 err = ret;
2684                 goto fail_alloc;
2685         }
2686
2687         __setup_root(4096, 4096, 4096, tree_root,
2688                      fs_info, BTRFS_ROOT_TREE_OBJECTID);
2689
2690         invalidate_bdev(fs_devices->latest_bdev);
2691
2692         /*
2693          * Read super block and check the signature bytes only
2694          */
2695         bh = btrfs_read_dev_super(fs_devices->latest_bdev);
2696         if (IS_ERR(bh)) {
2697                 err = PTR_ERR(bh);
2698                 goto fail_alloc;
2699         }
2700
2701         /*
2702          * We want to check superblock checksum, the type is stored inside.
2703          * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
2704          */
2705         if (btrfs_check_super_csum(bh->b_data)) {
2706                 printk(KERN_ERR "BTRFS: superblock checksum mismatch\n");
2707                 err = -EINVAL;
2708                 brelse(bh);
2709                 goto fail_alloc;
2710         }
2711
2712         /*
2713          * super_copy is zeroed at allocation time and we never touch the
2714          * following bytes up to INFO_SIZE, the checksum is calculated from
2715          * the whole block of INFO_SIZE
2716          */
2717         memcpy(fs_info->super_copy, bh->b_data, sizeof(*fs_info->super_copy));
2718         memcpy(fs_info->super_for_commit, fs_info->super_copy,
2719                sizeof(*fs_info->super_for_commit));
2720         brelse(bh);
2721
2722         memcpy(fs_info->fsid, fs_info->super_copy->fsid, BTRFS_FSID_SIZE);
2723
2724         ret = btrfs_check_super_valid(fs_info, sb->s_flags & MS_RDONLY);
2725         if (ret) {
2726                 printk(KERN_ERR "BTRFS: superblock contains fatal errors\n");
2727                 err = -EINVAL;
2728                 goto fail_alloc;
2729         }
2730
2731         disk_super = fs_info->super_copy;
2732         if (!btrfs_super_root(disk_super))
2733                 goto fail_alloc;
2734
2735         /* check FS state, whether FS is broken. */
2736         if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
2737                 set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
2738
2739         /*
2740          * run through our array of backup supers and setup
2741          * our ring pointer to the oldest one
2742          */
2743         generation = btrfs_super_generation(disk_super);
2744         find_oldest_super_backup(fs_info, generation);
2745
2746         /*
2747          * In the long term, we'll store the compression type in the super
2748          * block, and it'll be used for per file compression control.
2749          */
2750         fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
2751
2752         ret = btrfs_parse_options(tree_root, options);
2753         if (ret) {
2754                 err = ret;
2755                 goto fail_alloc;
2756         }
2757
2758         features = btrfs_super_incompat_flags(disk_super) &
2759                 ~BTRFS_FEATURE_INCOMPAT_SUPP;
2760         if (features) {
2761                 printk(KERN_ERR "BTRFS: couldn't mount because of "
2762                        "unsupported optional features (%Lx).\n",
2763                        features);
2764                 err = -EINVAL;
2765                 goto fail_alloc;
2766         }
2767
2768         features = btrfs_super_incompat_flags(disk_super);
2769         features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
2770         if (tree_root->fs_info->compress_type == BTRFS_COMPRESS_LZO)
2771                 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
2772
2773         if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
2774                 printk(KERN_INFO "BTRFS: has skinny extents\n");
2775
2776         /*
2777          * flag our filesystem as having big metadata blocks if
2778          * they are bigger than the page size
2779          */
2780         if (btrfs_super_nodesize(disk_super) > PAGE_CACHE_SIZE) {
2781                 if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
2782                         printk(KERN_INFO "BTRFS: flagging fs with big metadata feature\n");
2783                 features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
2784         }
2785
2786         nodesize = btrfs_super_nodesize(disk_super);
2787         sectorsize = btrfs_super_sectorsize(disk_super);
2788         stripesize = btrfs_super_stripesize(disk_super);
2789         fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
2790         fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
2791
2792         /*
2793          * mixed block groups end up with duplicate but slightly offset
2794          * extent buffers for the same range.  It leads to corruptions
2795          */
2796         if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
2797             (sectorsize != nodesize)) {
2798                 printk(KERN_ERR "BTRFS: unequal leaf/node/sector sizes "
2799                                 "are not allowed for mixed block groups on %s\n",
2800                                 sb->s_id);
2801                 goto fail_alloc;
2802         }
2803
2804         /*
2805          * Needn't use the lock because there is no other task which will
2806          * update the flag.
2807          */
2808         btrfs_set_super_incompat_flags(disk_super, features);
2809
2810         features = btrfs_super_compat_ro_flags(disk_super) &
2811                 ~BTRFS_FEATURE_COMPAT_RO_SUPP;
2812         if (!(sb->s_flags & MS_RDONLY) && features) {
2813                 printk(KERN_ERR "BTRFS: couldn't mount RDWR because of "
2814                        "unsupported option features (%Lx).\n",
2815                        features);
2816                 err = -EINVAL;
2817                 goto fail_alloc;
2818         }
2819
2820         max_active = fs_info->thread_pool_size;
2821
2822         ret = btrfs_init_workqueues(fs_info, fs_devices);
2823         if (ret) {
2824                 err = ret;
2825                 goto fail_sb_buffer;
2826         }
2827
2828         fs_info->bdi.ra_pages *= btrfs_super_num_devices(disk_super);
2829         fs_info->bdi.ra_pages = max(fs_info->bdi.ra_pages,
2830                                     SZ_4M / PAGE_CACHE_SIZE);
2831
2832         tree_root->nodesize = nodesize;
2833         tree_root->sectorsize = sectorsize;
2834         tree_root->stripesize = stripesize;
2835
2836         sb->s_blocksize = sectorsize;
2837         sb->s_blocksize_bits = blksize_bits(sectorsize);
2838
2839         mutex_lock(&fs_info->chunk_mutex);
2840         ret = btrfs_read_sys_array(tree_root);
2841         mutex_unlock(&fs_info->chunk_mutex);
2842         if (ret) {
2843                 printk(KERN_ERR "BTRFS: failed to read the system "
2844                        "array on %s\n", sb->s_id);
2845                 goto fail_sb_buffer;
2846         }
2847
2848         generation = btrfs_super_chunk_root_generation(disk_super);
2849
2850         __setup_root(nodesize, sectorsize, stripesize, chunk_root,
2851                      fs_info, BTRFS_CHUNK_TREE_OBJECTID);
2852
2853         chunk_root->node = read_tree_block(chunk_root,
2854                                            btrfs_super_chunk_root(disk_super),
2855                                            generation);
2856         if (IS_ERR(chunk_root->node) ||
2857             !extent_buffer_uptodate(chunk_root->node)) {
2858                 printk(KERN_ERR "BTRFS: failed to read chunk root on %s\n",
2859                        sb->s_id);
2860                 if (!IS_ERR(chunk_root->node))
2861                         free_extent_buffer(chunk_root->node);
2862                 chunk_root->node = NULL;
2863                 goto fail_tree_roots;
2864         }
2865         btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
2866         chunk_root->commit_root = btrfs_root_node(chunk_root);
2867
2868         read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
2869            btrfs_header_chunk_tree_uuid(chunk_root->node), BTRFS_UUID_SIZE);
2870
2871         ret = btrfs_read_chunk_tree(chunk_root);
2872         if (ret) {
2873                 printk(KERN_ERR "BTRFS: failed to read chunk tree on %s\n",
2874                        sb->s_id);
2875                 goto fail_tree_roots;
2876         }
2877
2878         /*
2879          * keep the device that is marked to be the target device for the
2880          * dev_replace procedure
2881          */
2882         btrfs_close_extra_devices(fs_devices, 0);
2883
2884         if (!fs_devices->latest_bdev) {
2885                 printk(KERN_ERR "BTRFS: failed to read devices on %s\n",
2886                        sb->s_id);
2887                 goto fail_tree_roots;
2888         }
2889
2890 retry_root_backup:
2891         generation = btrfs_super_generation(disk_super);
2892
2893         tree_root->node = read_tree_block(tree_root,
2894                                           btrfs_super_root(disk_super),
2895                                           generation);
2896         if (IS_ERR(tree_root->node) ||
2897             !extent_buffer_uptodate(tree_root->node)) {
2898                 printk(KERN_WARNING "BTRFS: failed to read tree root on %s\n",
2899                        sb->s_id);
2900                 if (!IS_ERR(tree_root->node))
2901                         free_extent_buffer(tree_root->node);
2902                 tree_root->node = NULL;
2903                 goto recovery_tree_root;
2904         }
2905
2906         btrfs_set_root_node(&tree_root->root_item, tree_root->node);
2907         tree_root->commit_root = btrfs_root_node(tree_root);
2908         btrfs_set_root_refs(&tree_root->root_item, 1);
2909
2910         mutex_lock(&tree_root->objectid_mutex);
2911         ret = btrfs_find_highest_objectid(tree_root,
2912                                         &tree_root->highest_objectid);
2913         if (ret) {
2914                 mutex_unlock(&tree_root->objectid_mutex);
2915                 goto recovery_tree_root;
2916         }
2917
2918         ASSERT(tree_root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
2919
2920         mutex_unlock(&tree_root->objectid_mutex);
2921
2922         ret = btrfs_read_roots(fs_info, tree_root);
2923         if (ret)
2924                 goto recovery_tree_root;
2925
2926         fs_info->generation = generation;
2927         fs_info->last_trans_committed = generation;
2928
2929         ret = btrfs_recover_balance(fs_info);
2930         if (ret) {
2931                 printk(KERN_ERR "BTRFS: failed to recover balance\n");
2932                 goto fail_block_groups;
2933         }
2934
2935         ret = btrfs_init_dev_stats(fs_info);
2936         if (ret) {
2937                 printk(KERN_ERR "BTRFS: failed to init dev_stats: %d\n",
2938                        ret);
2939                 goto fail_block_groups;
2940         }
2941
2942         ret = btrfs_init_dev_replace(fs_info);
2943         if (ret) {
2944                 pr_err("BTRFS: failed to init dev_replace: %d\n", ret);
2945                 goto fail_block_groups;
2946         }
2947
2948         btrfs_close_extra_devices(fs_devices, 1);
2949
2950         ret = btrfs_sysfs_add_fsid(fs_devices, NULL);
2951         if (ret) {
2952                 pr_err("BTRFS: failed to init sysfs fsid interface: %d\n", ret);
2953                 goto fail_block_groups;
2954         }
2955
2956         ret = btrfs_sysfs_add_device(fs_devices);
2957         if (ret) {
2958                 pr_err("BTRFS: failed to init sysfs device interface: %d\n", ret);
2959                 goto fail_fsdev_sysfs;
2960         }
2961
2962         ret = btrfs_sysfs_add_mounted(fs_info);
2963         if (ret) {
2964                 pr_err("BTRFS: failed to init sysfs interface: %d\n", ret);
2965                 goto fail_fsdev_sysfs;
2966         }
2967
2968         ret = btrfs_init_space_info(fs_info);
2969         if (ret) {
2970                 printk(KERN_ERR "BTRFS: Failed to initial space info: %d\n", ret);
2971                 goto fail_sysfs;
2972         }
2973
2974         ret = btrfs_read_block_groups(fs_info->extent_root);
2975         if (ret) {
2976                 printk(KERN_ERR "BTRFS: Failed to read block groups: %d\n", ret);
2977                 goto fail_sysfs;
2978         }
2979         fs_info->num_tolerated_disk_barrier_failures =
2980                 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
2981         if (fs_info->fs_devices->missing_devices >
2982              fs_info->num_tolerated_disk_barrier_failures &&
2983             !(sb->s_flags & MS_RDONLY)) {
2984                 pr_warn("BTRFS: missing devices(%llu) exceeds the limit(%d), writeable mount is not allowed\n",
2985                         fs_info->fs_devices->missing_devices,
2986                         fs_info->num_tolerated_disk_barrier_failures);
2987                 goto fail_sysfs;
2988         }
2989
2990         fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
2991                                                "btrfs-cleaner");
2992         if (IS_ERR(fs_info->cleaner_kthread))
2993                 goto fail_sysfs;
2994
2995         fs_info->transaction_kthread = kthread_run(transaction_kthread,
2996                                                    tree_root,
2997                                                    "btrfs-transaction");
2998         if (IS_ERR(fs_info->transaction_kthread))
2999                 goto fail_cleaner;
3000
3001         if (!btrfs_test_opt(tree_root, SSD) &&
3002             !btrfs_test_opt(tree_root, NOSSD) &&
3003             !fs_info->fs_devices->rotating) {
3004                 printk(KERN_INFO "BTRFS: detected SSD devices, enabling SSD "
3005                        "mode\n");
3006                 btrfs_set_opt(fs_info->mount_opt, SSD);
3007         }
3008
3009         /*
3010          * Mount does not set all options immediatelly, we can do it now and do
3011          * not have to wait for transaction commit
3012          */
3013         btrfs_apply_pending_changes(fs_info);
3014
3015 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
3016         if (btrfs_test_opt(tree_root, CHECK_INTEGRITY)) {
3017                 ret = btrfsic_mount(tree_root, fs_devices,
3018                                     btrfs_test_opt(tree_root,
3019                                         CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
3020                                     1 : 0,
3021                                     fs_info->check_integrity_print_mask);
3022                 if (ret)
3023                         printk(KERN_WARNING "BTRFS: failed to initialize"
3024                                " integrity check module %s\n", sb->s_id);
3025         }
3026 #endif
3027         ret = btrfs_read_qgroup_config(fs_info);
3028         if (ret)
3029                 goto fail_trans_kthread;
3030
3031         /* do not make disk changes in broken FS */
3032         if (btrfs_super_log_root(disk_super) != 0) {
3033                 ret = btrfs_replay_log(fs_info, fs_devices);
3034                 if (ret) {
3035                         err = ret;
3036                         goto fail_qgroup;
3037                 }
3038         }
3039
3040         ret = btrfs_find_orphan_roots(tree_root);
3041         if (ret)
3042                 goto fail_qgroup;
3043
3044         if (!(sb->s_flags & MS_RDONLY)) {
3045                 ret = btrfs_cleanup_fs_roots(fs_info);
3046                 if (ret)
3047                         goto fail_qgroup;
3048
3049                 mutex_lock(&fs_info->cleaner_mutex);
3050                 ret = btrfs_recover_relocation(tree_root);
3051                 mutex_unlock(&fs_info->cleaner_mutex);
3052                 if (ret < 0) {
3053                         printk(KERN_WARNING
3054                                "BTRFS: failed to recover relocation\n");
3055                         err = -EINVAL;
3056                         goto fail_qgroup;
3057                 }
3058         }
3059
3060         location.objectid = BTRFS_FS_TREE_OBJECTID;
3061         location.type = BTRFS_ROOT_ITEM_KEY;
3062         location.offset = 0;
3063
3064         fs_info->fs_root = btrfs_read_fs_root_no_name(fs_info, &location);
3065         if (IS_ERR(fs_info->fs_root)) {
3066                 err = PTR_ERR(fs_info->fs_root);
3067                 goto fail_qgroup;
3068         }
3069
3070         if (sb->s_flags & MS_RDONLY)
3071                 return 0;
3072
3073         if (btrfs_test_opt(tree_root, FREE_SPACE_TREE) &&
3074             !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3075                 pr_info("BTRFS: creating free space tree\n");
3076                 ret = btrfs_create_free_space_tree(fs_info);
3077                 if (ret) {
3078                         pr_warn("BTRFS: failed to create free space tree %d\n",
3079                                 ret);
3080                         close_ctree(tree_root);
3081                         return ret;
3082                 }
3083         }
3084
3085         down_read(&fs_info->cleanup_work_sem);
3086         if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
3087             (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
3088                 up_read(&fs_info->cleanup_work_sem);
3089                 close_ctree(tree_root);
3090                 return ret;
3091         }
3092         up_read(&fs_info->cleanup_work_sem);
3093
3094         ret = btrfs_resume_balance_async(fs_info);
3095         if (ret) {
3096                 printk(KERN_WARNING "BTRFS: failed to resume balance\n");
3097                 close_ctree(tree_root);
3098                 return ret;
3099         }
3100
3101         ret = btrfs_resume_dev_replace_async(fs_info);
3102         if (ret) {
3103                 pr_warn("BTRFS: failed to resume dev_replace\n");
3104                 close_ctree(tree_root);
3105                 return ret;
3106         }
3107
3108         btrfs_qgroup_rescan_resume(fs_info);
3109
3110         if (btrfs_test_opt(tree_root, CLEAR_CACHE) &&
3111             btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3112                 pr_info("BTRFS: clearing free space tree\n");
3113                 ret = btrfs_clear_free_space_tree(fs_info);
3114                 if (ret) {
3115                         pr_warn("BTRFS: failed to clear free space tree %d\n",
3116                                 ret);
3117                         close_ctree(tree_root);
3118                         return ret;
3119                 }
3120         }
3121
3122         if (!fs_info->uuid_root) {
3123                 pr_info("BTRFS: creating UUID tree\n");
3124                 ret = btrfs_create_uuid_tree(fs_info);
3125                 if (ret) {
3126                         pr_warn("BTRFS: failed to create the UUID tree %d\n",
3127                                 ret);
3128                         close_ctree(tree_root);
3129                         return ret;
3130                 }
3131         } else if (btrfs_test_opt(tree_root, RESCAN_UUID_TREE) ||
3132                    fs_info->generation !=
3133                                 btrfs_super_uuid_tree_generation(disk_super)) {
3134                 pr_info("BTRFS: checking UUID tree\n");
3135                 ret = btrfs_check_uuid_tree(fs_info);
3136                 if (ret) {
3137                         pr_warn("BTRFS: failed to check the UUID tree %d\n",
3138                                 ret);
3139                         close_ctree(tree_root);
3140                         return ret;
3141                 }
3142         } else {
3143                 fs_info->update_uuid_tree_gen = 1;
3144         }
3145
3146         fs_info->open = 1;
3147
3148         return 0;
3149
3150 fail_qgroup:
3151         btrfs_free_qgroup_config(fs_info);
3152 fail_trans_kthread:
3153         kthread_stop(fs_info->transaction_kthread);
3154         btrfs_cleanup_transaction(fs_info->tree_root);
3155         btrfs_free_fs_roots(fs_info);
3156 fail_cleaner:
3157         kthread_stop(fs_info->cleaner_kthread);
3158
3159         /*
3160          * make sure we're done with the btree inode before we stop our
3161          * kthreads
3162          */
3163         filemap_write_and_wait(fs_info->btree_inode->i_mapping);
3164
3165 fail_sysfs:
3166         btrfs_sysfs_remove_mounted(fs_info);
3167
3168 fail_fsdev_sysfs:
3169         btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3170
3171 fail_block_groups:
3172         btrfs_put_block_group_cache(fs_info);
3173         btrfs_free_block_groups(fs_info);
3174
3175 fail_tree_roots:
3176         free_root_pointers(fs_info, 1);
3177         invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3178
3179 fail_sb_buffer:
3180         btrfs_stop_all_workers(fs_info);
3181 fail_alloc:
3182 fail_iput:
3183         btrfs_mapping_tree_free(&fs_info->mapping_tree);
3184
3185         iput(fs_info->btree_inode);
3186 fail_bio_counter:
3187         percpu_counter_destroy(&fs_info->bio_counter);
3188 fail_delalloc_bytes:
3189         percpu_counter_destroy(&fs_info->delalloc_bytes);
3190 fail_dirty_metadata_bytes:
3191         percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
3192 fail_bdi:
3193         bdi_destroy(&fs_info->bdi);
3194 fail_srcu:
3195         cleanup_srcu_struct(&fs_info->subvol_srcu);
3196 fail:
3197         btrfs_free_stripe_hash_table(fs_info);
3198         btrfs_close_devices(fs_info->fs_devices);
3199         return err;
3200
3201 recovery_tree_root:
3202         if (!btrfs_test_opt(tree_root, RECOVERY))
3203                 goto fail_tree_roots;
3204
3205         free_root_pointers(fs_info, 0);
3206
3207         /* don't use the log in recovery mode, it won't be valid */
3208         btrfs_set_super_log_root(disk_super, 0);
3209
3210         /* we can't trust the free space cache either */
3211         btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
3212
3213         ret = next_root_backup(fs_info, fs_info->super_copy,
3214                                &num_backups_tried, &backup_index);
3215         if (ret == -1)
3216                 goto fail_block_groups;
3217         goto retry_root_backup;
3218 }
3219
3220 static void btrfs_end_buffer_write_sync(struct buffer_head *bh, int uptodate)
3221 {
3222         if (uptodate) {
3223                 set_buffer_uptodate(bh);
3224         } else {
3225                 struct btrfs_device *device = (struct btrfs_device *)
3226                         bh->b_private;
3227
3228                 btrfs_warn_rl_in_rcu(device->dev_root->fs_info,
3229                                 "lost page write due to IO error on %s",
3230                                           rcu_str_deref(device->name));
3231                 /* note, we dont' set_buffer_write_io_error because we have
3232                  * our own ways of dealing with the IO errors
3233                  */
3234                 clear_buffer_uptodate(bh);
3235                 btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_WRITE_ERRS);
3236         }
3237         unlock_buffer(bh);
3238         put_bh(bh);
3239 }
3240
3241 int btrfs_read_dev_one_super(struct block_device *bdev, int copy_num,
3242                         struct buffer_head **bh_ret)
3243 {
3244         struct buffer_head *bh;
3245         struct btrfs_super_block *super;
3246         u64 bytenr;
3247
3248         bytenr = btrfs_sb_offset(copy_num);
3249         if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
3250                 return -EINVAL;
3251
3252         bh = __bread(bdev, bytenr / 4096, BTRFS_SUPER_INFO_SIZE);
3253         /*
3254          * If we fail to read from the underlying devices, as of now
3255          * the best option we have is to mark it EIO.
3256          */
3257         if (!bh)
3258                 return -EIO;
3259
3260         super = (struct btrfs_super_block *)bh->b_data;
3261         if (btrfs_super_bytenr(super) != bytenr ||
3262                     btrfs_super_magic(super) != BTRFS_MAGIC) {
3263                 brelse(bh);
3264                 return -EINVAL;
3265         }
3266
3267         *bh_ret = bh;
3268         return 0;
3269 }
3270
3271
3272 struct buffer_head *btrfs_read_dev_super(struct block_device *bdev)
3273 {
3274         struct buffer_head *bh;
3275         struct buffer_head *latest = NULL;
3276         struct btrfs_super_block *super;
3277         int i;
3278         u64 transid = 0;
3279         int ret = -EINVAL;
3280
3281         /* we would like to check all the supers, but that would make
3282          * a btrfs mount succeed after a mkfs from a different FS.
3283          * So, we need to add a special mount option to scan for
3284          * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3285          */
3286         for (i = 0; i < 1; i++) {
3287                 ret = btrfs_read_dev_one_super(bdev, i, &bh);
3288                 if (ret)
3289                         continue;
3290
3291                 super = (struct btrfs_super_block *)bh->b_data;
3292
3293                 if (!latest || btrfs_super_generation(super) > transid) {
3294                         brelse(latest);
3295                         latest = bh;
3296                         transid = btrfs_super_generation(super);
3297                 } else {
3298                         brelse(bh);
3299                 }
3300         }
3301
3302         if (!latest)
3303                 return ERR_PTR(ret);
3304
3305         return latest;
3306 }
3307
3308 /*
3309  * this should be called twice, once with wait == 0 and
3310  * once with wait == 1.  When wait == 0 is done, all the buffer heads
3311  * we write are pinned.
3312  *
3313  * They are released when wait == 1 is done.
3314  * max_mirrors must be the same for both runs, and it indicates how
3315  * many supers on this one device should be written.
3316  *
3317  * max_mirrors == 0 means to write them all.
3318  */
3319 static int write_dev_supers(struct btrfs_device *device,
3320                             struct btrfs_super_block *sb,
3321                             int do_barriers, int wait, int max_mirrors)
3322 {
3323         struct buffer_head *bh;
3324         int i;
3325         int ret;
3326         int errors = 0;
3327         u32 crc;
3328         u64 bytenr;
3329
3330         if (max_mirrors == 0)
3331                 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3332
3333         for (i = 0; i < max_mirrors; i++) {
3334                 bytenr = btrfs_sb_offset(i);
3335                 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3336                     device->commit_total_bytes)
3337                         break;
3338
3339                 if (wait) {
3340                         bh = __find_get_block(device->bdev, bytenr / 4096,
3341                                               BTRFS_SUPER_INFO_SIZE);
3342                         if (!bh) {
3343                                 errors++;
3344                                 continue;
3345                         }
3346                         wait_on_buffer(bh);
3347                         if (!buffer_uptodate(bh))
3348                                 errors++;
3349
3350                         /* drop our reference */
3351                         brelse(bh);
3352
3353                         /* drop the reference from the wait == 0 run */
3354                         brelse(bh);
3355                         continue;
3356                 } else {
3357                         btrfs_set_super_bytenr(sb, bytenr);
3358
3359                         crc = ~(u32)0;
3360                         crc = btrfs_csum_data((char *)sb +
3361                                               BTRFS_CSUM_SIZE, crc,
3362                                               BTRFS_SUPER_INFO_SIZE -
3363                                               BTRFS_CSUM_SIZE);
3364                         btrfs_csum_final(crc, sb->csum);
3365
3366                         /*
3367                          * one reference for us, and we leave it for the
3368                          * caller
3369                          */
3370                         bh = __getblk(device->bdev, bytenr / 4096,
3371                                       BTRFS_SUPER_INFO_SIZE);
3372                         if (!bh) {
3373                                 btrfs_err(device->dev_root->fs_info,
3374                                     "couldn't get super buffer head for bytenr %llu",
3375                                     bytenr);
3376                                 errors++;
3377                                 continue;
3378                         }
3379
3380                         memcpy(bh->b_data, sb, BTRFS_SUPER_INFO_SIZE);
3381
3382                         /* one reference for submit_bh */
3383                         get_bh(bh);
3384
3385                         set_buffer_uptodate(bh);
3386                         lock_buffer(bh);
3387                         bh->b_end_io = btrfs_end_buffer_write_sync;
3388                         bh->b_private = device;
3389                 }
3390
3391                 /*
3392                  * we fua the first super.  The others we allow
3393                  * to go down lazy.
3394                  */
3395                 if (i == 0)
3396                         ret = btrfsic_submit_bh(WRITE_FUA, bh);
3397                 else
3398                         ret = btrfsic_submit_bh(WRITE_SYNC, bh);
3399                 if (ret)
3400                         errors++;
3401         }
3402         return errors < i ? 0 : -1;
3403 }
3404
3405 /*
3406  * endio for the write_dev_flush, this will wake anyone waiting
3407  * for the barrier when it is done
3408  */
3409 static void btrfs_end_empty_barrier(struct bio *bio)
3410 {
3411         if (bio->bi_private)
3412                 complete(bio->bi_private);
3413         bio_put(bio);
3414 }
3415
3416 /*
3417  * trigger flushes for one the devices.  If you pass wait == 0, the flushes are
3418  * sent down.  With wait == 1, it waits for the previous flush.
3419  *
3420  * any device where the flush fails with eopnotsupp are flagged as not-barrier
3421  * capable
3422  */
3423 static int write_dev_flush(struct btrfs_device *device, int wait)
3424 {
3425         struct bio *bio;
3426         int ret = 0;
3427
3428         if (device->nobarriers)
3429                 return 0;
3430
3431         if (wait) {
3432                 bio = device->flush_bio;
3433                 if (!bio)
3434                         return 0;
3435
3436                 wait_for_completion(&device->flush_wait);
3437
3438                 if (bio->bi_error) {
3439                         ret = bio->bi_error;
3440                         btrfs_dev_stat_inc_and_print(device,
3441                                 BTRFS_DEV_STAT_FLUSH_ERRS);
3442                 }
3443
3444                 /* drop the reference from the wait == 0 run */
3445                 bio_put(bio);
3446                 device->flush_bio = NULL;
3447
3448                 return ret;
3449         }
3450
3451         /*
3452          * one reference for us, and we leave it for the
3453          * caller
3454          */
3455         device->flush_bio = NULL;
3456         bio = btrfs_io_bio_alloc(GFP_NOFS, 0);
3457         if (!bio)
3458                 return -ENOMEM;
3459
3460         bio->bi_end_io = btrfs_end_empty_barrier;
3461         bio->bi_bdev = device->bdev;
3462         init_completion(&device->flush_wait);
3463         bio->bi_private = &device->flush_wait;
3464         device->flush_bio = bio;
3465
3466         bio_get(bio);
3467         btrfsic_submit_bio(WRITE_FLUSH, bio);
3468
3469         return 0;
3470 }
3471
3472 /*
3473  * send an empty flush down to each device in parallel,
3474  * then wait for them
3475  */
3476 static int barrier_all_devices(struct btrfs_fs_info *info)
3477 {
3478         struct list_head *head;
3479         struct btrfs_device *dev;
3480         int errors_send = 0;
3481         int errors_wait = 0;
3482         int ret;
3483
3484         /* send down all the barriers */
3485         head = &info->fs_devices->devices;
3486         list_for_each_entry_rcu(dev, head, dev_list) {
3487                 if (dev->missing)
3488                         continue;
3489                 if (!dev->bdev) {
3490                         errors_send++;
3491                         continue;
3492                 }
3493                 if (!dev->in_fs_metadata || !dev->writeable)
3494                         continue;
3495
3496                 ret = write_dev_flush(dev, 0);
3497                 if (ret)
3498                         errors_send++;
3499         }
3500
3501         /* wait for all the barriers */
3502         list_for_each_entry_rcu(dev, head, dev_list) {
3503                 if (dev->missing)
3504                         continue;
3505                 if (!dev->bdev) {
3506                         errors_wait++;
3507                         continue;
3508                 }
3509                 if (!dev->in_fs_metadata || !dev->writeable)
3510                         continue;
3511
3512                 ret = write_dev_flush(dev, 1);
3513                 if (ret)
3514                         errors_wait++;
3515         }
3516         if (errors_send > info->num_tolerated_disk_barrier_failures ||
3517             errors_wait > info->num_tolerated_disk_barrier_failures)
3518                 return -EIO;
3519         return 0;
3520 }
3521
3522 int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3523 {
3524         int raid_type;
3525         int min_tolerated = INT_MAX;
3526
3527         if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
3528             (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
3529                 min_tolerated = min(min_tolerated,
3530                                     btrfs_raid_array[BTRFS_RAID_SINGLE].
3531                                     tolerated_failures);
3532
3533         for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
3534                 if (raid_type == BTRFS_RAID_SINGLE)
3535                         continue;
3536                 if (!(flags & btrfs_raid_group[raid_type]))
3537                         continue;
3538                 min_tolerated = min(min_tolerated,
3539                                     btrfs_raid_array[raid_type].
3540                                     tolerated_failures);
3541         }
3542
3543         if (min_tolerated == INT_MAX) {
3544                 pr_warn("BTRFS: unknown raid flag: %llu\n", flags);
3545                 min_tolerated = 0;
3546         }
3547
3548         return min_tolerated;
3549 }
3550
3551 int btrfs_calc_num_tolerated_disk_barrier_failures(
3552         struct btrfs_fs_info *fs_info)
3553 {
3554         struct btrfs_ioctl_space_info space;
3555         struct btrfs_space_info *sinfo;
3556         u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
3557                        BTRFS_BLOCK_GROUP_SYSTEM,
3558                        BTRFS_BLOCK_GROUP_METADATA,
3559                        BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
3560         int i;
3561         int c;
3562         int num_tolerated_disk_barrier_failures =
3563                 (int)fs_info->fs_devices->num_devices;
3564
3565         for (i = 0; i < ARRAY_SIZE(types); i++) {
3566                 struct btrfs_space_info *tmp;
3567
3568                 sinfo = NULL;
3569                 rcu_read_lock();
3570                 list_for_each_entry_rcu(tmp, &fs_info->space_info, list) {
3571                         if (tmp->flags == types[i]) {
3572                                 sinfo = tmp;
3573                                 break;
3574                         }
3575                 }
3576                 rcu_read_unlock();
3577
3578                 if (!sinfo)
3579                         continue;
3580
3581                 down_read(&sinfo->groups_sem);
3582                 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3583                         u64 flags;
3584
3585                         if (list_empty(&sinfo->block_groups[c]))
3586                                 continue;
3587
3588                         btrfs_get_block_group_info(&sinfo->block_groups[c],
3589                                                    &space);
3590                         if (space.total_bytes == 0 || space.used_bytes == 0)
3591                                 continue;
3592                         flags = space.flags;
3593
3594                         num_tolerated_disk_barrier_failures = min(
3595                                 num_tolerated_disk_barrier_failures,
3596                                 btrfs_get_num_tolerated_disk_barrier_failures(
3597                                         flags));
3598                 }
3599                 up_read(&sinfo->groups_sem);
3600         }
3601
3602         return num_tolerated_disk_barrier_failures;
3603 }
3604
3605 static int write_all_supers(struct btrfs_root *root, int max_mirrors)
3606 {
3607         struct list_head *head;
3608         struct btrfs_device *dev;
3609         struct btrfs_super_block *sb;
3610         struct btrfs_dev_item *dev_item;
3611         int ret;
3612         int do_barriers;
3613         int max_errors;
3614         int total_errors = 0;
3615         u64 flags;
3616
3617         do_barriers = !btrfs_test_opt(root, NOBARRIER);
3618         backup_super_roots(root->fs_info);
3619
3620         sb = root->fs_info->super_for_commit;
3621         dev_item = &sb->dev_item;
3622
3623         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
3624         head = &root->fs_info->fs_devices->devices;
3625         max_errors = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
3626
3627         if (do_barriers) {
3628                 ret = barrier_all_devices(root->fs_info);
3629                 if (ret) {
3630                         mutex_unlock(
3631                                 &root->fs_info->fs_devices->device_list_mutex);
3632                         btrfs_std_error(root->fs_info, ret,
3633                                     "errors while submitting device barriers.");
3634                         return ret;
3635                 }
3636         }
3637
3638         list_for_each_entry_rcu(dev, head, dev_list) {
3639                 if (!dev->bdev) {
3640                         total_errors++;
3641                         continue;
3642                 }
3643                 if (!dev->in_fs_metadata || !dev->writeable)
3644                         continue;
3645
3646                 btrfs_set_stack_device_generation(dev_item, 0);
3647                 btrfs_set_stack_device_type(dev_item, dev->type);
3648                 btrfs_set_stack_device_id(dev_item, dev->devid);
3649                 btrfs_set_stack_device_total_bytes(dev_item,
3650                                                    dev->commit_total_bytes);
3651                 btrfs_set_stack_device_bytes_used(dev_item,
3652                                                   dev->commit_bytes_used);
3653                 btrfs_set_stack_device_io_align(dev_item, dev->io_align);
3654                 btrfs_set_stack_device_io_width(dev_item, dev->io_width);
3655                 btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
3656                 memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
3657                 memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_UUID_SIZE);
3658
3659                 flags = btrfs_super_flags(sb);
3660                 btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
3661
3662                 ret = write_dev_supers(dev, sb, do_barriers, 0, max_mirrors);
3663                 if (ret)
3664                         total_errors++;
3665         }
3666         if (total_errors > max_errors) {
3667                 btrfs_err(root->fs_info, "%d errors while writing supers",
3668                        total_errors);
3669                 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
3670
3671                 /* FUA is masked off if unsupported and can't be the reason */
3672                 btrfs_std_error(root->fs_info, -EIO,
3673                             "%d errors while writing supers", total_errors);
3674                 return -EIO;
3675         }
3676
3677         total_errors = 0;
3678         list_for_each_entry_rcu(dev, head, dev_list) {
3679                 if (!dev->bdev)
3680                         continue;
3681                 if (!dev->in_fs_metadata || !dev->writeable)
3682                         continue;
3683
3684                 ret = write_dev_supers(dev, sb, do_barriers, 1, max_mirrors);
3685                 if (ret)
3686                         total_errors++;
3687         }
3688         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
3689         if (total_errors > max_errors) {
3690                 btrfs_std_error(root->fs_info, -EIO,
3691                             "%d errors while writing supers", total_errors);
3692                 return -EIO;
3693         }
3694         return 0;
3695 }
3696
3697 int write_ctree_super(struct btrfs_trans_handle *trans,
3698                       struct btrfs_root *root, int max_mirrors)
3699 {
3700         return write_all_supers(root, max_mirrors);
3701 }
3702
3703 /* Drop a fs root from the radix tree and free it. */
3704 void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
3705                                   struct btrfs_root *root)
3706 {
3707         spin_lock(&fs_info->fs_roots_radix_lock);
3708         radix_tree_delete(&fs_info->fs_roots_radix,
3709                           (unsigned long)root->root_key.objectid);
3710         spin_unlock(&fs_info->fs_roots_radix_lock);
3711
3712         if (btrfs_root_refs(&root->root_item) == 0)
3713                 synchronize_srcu(&fs_info->subvol_srcu);
3714
3715         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
3716                 btrfs_free_log(NULL, root);
3717
3718         if (root->free_ino_pinned)
3719                 __btrfs_remove_free_space_cache(root->free_ino_pinned);
3720         if (root->free_ino_ctl)
3721                 __btrfs_remove_free_space_cache(root->free_ino_ctl);
3722         free_fs_root(root);
3723 }
3724
3725 static void free_fs_root(struct btrfs_root *root)
3726 {
3727         iput(root->ino_cache_inode);
3728         WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
3729         btrfs_free_block_rsv(root, root->orphan_block_rsv);
3730         root->orphan_block_rsv = NULL;
3731         if (root->anon_dev)
3732                 free_anon_bdev(root->anon_dev);
3733         if (root->subv_writers)
3734                 btrfs_free_subvolume_writers(root->subv_writers);
3735         free_extent_buffer(root->node);
3736         free_extent_buffer(root->commit_root);
3737         kfree(root->free_ino_ctl);
3738         kfree(root->free_ino_pinned);
3739         kfree(root->name);
3740         btrfs_put_fs_root(root);
3741 }
3742
3743 void btrfs_free_fs_root(struct btrfs_root *root)
3744 {
3745         free_fs_root(root);
3746 }
3747
3748 int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
3749 {
3750         u64 root_objectid = 0;
3751         struct btrfs_root *gang[8];
3752         int i = 0;
3753         int err = 0;
3754         unsigned int ret = 0;
3755         int index;
3756
3757         while (1) {
3758                 index = srcu_read_lock(&fs_info->subvol_srcu);
3759                 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
3760                                              (void **)gang, root_objectid,
3761                                              ARRAY_SIZE(gang));
3762                 if (!ret) {
3763                         srcu_read_unlock(&fs_info->subvol_srcu, index);
3764                         break;
3765                 }
3766                 root_objectid = gang[ret - 1]->root_key.objectid + 1;
3767
3768                 for (i = 0; i < ret; i++) {
3769                         /* Avoid to grab roots in dead_roots */
3770                         if (btrfs_root_refs(&gang[i]->root_item) == 0) {
3771                                 gang[i] = NULL;
3772                                 continue;
3773                         }
3774                         /* grab all the search result for later use */
3775                         gang[i] = btrfs_grab_fs_root(gang[i]);
3776                 }
3777                 srcu_read_unlock(&fs_info->subvol_srcu, index);
3778
3779                 for (i = 0; i < ret; i++) {
3780                         if (!gang[i])
3781                                 continue;
3782                         root_objectid = gang[i]->root_key.objectid;
3783                         err = btrfs_orphan_cleanup(gang[i]);
3784                         if (err)
3785                                 break;
3786                         btrfs_put_fs_root(gang[i]);
3787                 }
3788                 root_objectid++;
3789         }
3790
3791         /* release the uncleaned roots due to error */
3792         for (; i < ret; i++) {
3793                 if (gang[i])
3794                         btrfs_put_fs_root(gang[i]);
3795         }
3796         return err;
3797 }
3798
3799 int btrfs_commit_super(struct btrfs_root *root)
3800 {
3801         struct btrfs_trans_handle *trans;
3802
3803         mutex_lock(&root->fs_info->cleaner_mutex);
3804         btrfs_run_delayed_iputs(root);
3805         mutex_unlock(&root->fs_info->cleaner_mutex);
3806         wake_up_process(root->fs_info->cleaner_kthread);
3807
3808         /* wait until ongoing cleanup work done */
3809         down_write(&root->fs_info->cleanup_work_sem);
3810         up_write(&root->fs_info->cleanup_work_sem);
3811
3812         trans = btrfs_join_transaction(root);
3813         if (IS_ERR(trans))
3814                 return PTR_ERR(trans);
3815         return btrfs_commit_transaction(trans, root);
3816 }
3817
3818 void close_ctree(struct btrfs_root *root)
3819 {
3820         struct btrfs_fs_info *fs_info = root->fs_info;
3821         int ret;
3822
3823         fs_info->closing = 1;
3824         smp_mb();
3825
3826         /* wait for the qgroup rescan worker to stop */
3827         btrfs_qgroup_wait_for_completion(fs_info);
3828
3829         /* wait for the uuid_scan task to finish */
3830         down(&fs_info->uuid_tree_rescan_sem);
3831         /* avoid complains from lockdep et al., set sem back to initial state */
3832         up(&fs_info->uuid_tree_rescan_sem);
3833
3834         /* pause restriper - we want to resume on mount */
3835         btrfs_pause_balance(fs_info);
3836
3837         btrfs_dev_replace_suspend_for_unmount(fs_info);
3838
3839         btrfs_scrub_cancel(fs_info);
3840
3841         /* wait for any defraggers to finish */
3842         wait_event(fs_info->transaction_wait,
3843                    (atomic_read(&fs_info->defrag_running) == 0));
3844
3845         /* clear out the rbtree of defraggable inodes */
3846         btrfs_cleanup_defrag_inodes(fs_info);
3847
3848         cancel_work_sync(&fs_info->async_reclaim_work);
3849
3850         if (!(fs_info->sb->s_flags & MS_RDONLY)) {
3851                 /*
3852                  * If the cleaner thread is stopped and there are
3853                  * block groups queued for removal, the deletion will be
3854                  * skipped when we quit the cleaner thread.
3855                  */
3856                 btrfs_delete_unused_bgs(root->fs_info);
3857
3858                 ret = btrfs_commit_super(root);
3859                 if (ret)
3860                         btrfs_err(fs_info, "commit super ret %d", ret);
3861         }
3862
3863         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
3864                 btrfs_error_commit_super(root);
3865
3866         kthread_stop(fs_info->transaction_kthread);
3867         kthread_stop(fs_info->cleaner_kthread);
3868
3869         fs_info->closing = 2;
3870         smp_mb();
3871
3872         btrfs_free_qgroup_config(fs_info);
3873
3874         if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
3875                 btrfs_info(fs_info, "at unmount delalloc count %lld",
3876                        percpu_counter_sum(&fs_info->delalloc_bytes));
3877         }
3878
3879         btrfs_sysfs_remove_mounted(fs_info);
3880         btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3881
3882         btrfs_free_fs_roots(fs_info);
3883
3884         btrfs_put_block_group_cache(fs_info);
3885
3886         btrfs_free_block_groups(fs_info);
3887
3888         /*
3889          * we must make sure there is not any read request to
3890          * submit after we stopping all workers.
3891          */
3892         invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3893         btrfs_stop_all_workers(fs_info);
3894
3895         fs_info->open = 0;
3896         free_root_pointers(fs_info, 1);
3897
3898         iput(fs_info->btree_inode);
3899
3900 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
3901         if (btrfs_test_opt(root, CHECK_INTEGRITY))
3902                 btrfsic_unmount(root, fs_info->fs_devices);
3903 #endif
3904
3905         btrfs_close_devices(fs_info->fs_devices);
3906         btrfs_mapping_tree_free(&fs_info->mapping_tree);
3907
3908         percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
3909         percpu_counter_destroy(&fs_info->delalloc_bytes);
3910         percpu_counter_destroy(&fs_info->bio_counter);
3911         bdi_destroy(&fs_info->bdi);
3912         cleanup_srcu_struct(&fs_info->subvol_srcu);
3913
3914         btrfs_free_stripe_hash_table(fs_info);
3915
3916         __btrfs_free_block_rsv(root->orphan_block_rsv);
3917         root->orphan_block_rsv = NULL;
3918
3919         lock_chunks(root);
3920         while (!list_empty(&fs_info->pinned_chunks)) {
3921                 struct extent_map *em;
3922
3923                 em = list_first_entry(&fs_info->pinned_chunks,
3924                                       struct extent_map, list);
3925                 list_del_init(&em->list);
3926                 free_extent_map(em);
3927         }
3928         unlock_chunks(root);
3929 }
3930
3931 int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
3932                           int atomic)
3933 {
3934         int ret;
3935         struct inode *btree_inode = buf->pages[0]->mapping->host;
3936
3937         ret = extent_buffer_uptodate(buf);
3938         if (!ret)
3939                 return ret;
3940
3941         ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
3942                                     parent_transid, atomic);
3943         if (ret == -EAGAIN)
3944                 return ret;
3945         return !ret;
3946 }
3947
3948 void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
3949 {
3950         struct btrfs_root *root;
3951         u64 transid = btrfs_header_generation(buf);
3952         int was_dirty;
3953
3954 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
3955         /*
3956          * This is a fast path so only do this check if we have sanity tests
3957          * enabled.  Normal people shouldn't be marking dummy buffers as dirty
3958          * outside of the sanity tests.
3959          */
3960         if (unlikely(test_bit(EXTENT_BUFFER_DUMMY, &buf->bflags)))
3961                 return;
3962 #endif
3963         root = BTRFS_I(buf->pages[0]->mapping->host)->root;
3964         btrfs_assert_tree_locked(buf);
3965         if (transid != root->fs_info->generation)
3966                 WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, "
3967                        "found %llu running %llu\n",
3968                         buf->start, transid, root->fs_info->generation);
3969         was_dirty = set_extent_buffer_dirty(buf);
3970         if (!was_dirty)
3971                 __percpu_counter_add(&root->fs_info->dirty_metadata_bytes,
3972                                      buf->len,
3973                                      root->fs_info->dirty_metadata_batch);
3974 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
3975         if (btrfs_header_level(buf) == 0 && check_leaf(root, buf)) {
3976                 btrfs_print_leaf(root, buf);
3977                 ASSERT(0);
3978         }
3979 #endif
3980 }
3981
3982 static void __btrfs_btree_balance_dirty(struct btrfs_root *root,
3983                                         int flush_delayed)
3984 {
3985         /*
3986          * looks as though older kernels can get into trouble with
3987          * this code, they end up stuck in balance_dirty_pages forever
3988          */
3989         int ret;
3990
3991         if (current->flags & PF_MEMALLOC)
3992                 return;
3993
3994         if (flush_delayed)
3995                 btrfs_balance_delayed_items(root);
3996
3997         ret = percpu_counter_compare(&root->fs_info->dirty_metadata_bytes,
3998                                      BTRFS_DIRTY_METADATA_THRESH);
3999         if (ret > 0) {
4000                 balance_dirty_pages_ratelimited(
4001                                    root->fs_info->btree_inode->i_mapping);
4002         }
4003 }
4004
4005 void btrfs_btree_balance_dirty(struct btrfs_root *root)
4006 {
4007         __btrfs_btree_balance_dirty(root, 1);
4008 }
4009
4010 void btrfs_btree_balance_dirty_nodelay(struct btrfs_root *root)
4011 {
4012         __btrfs_btree_balance_dirty(root, 0);
4013 }
4014
4015 int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid)
4016 {
4017         struct btrfs_root *root = BTRFS_I(buf->pages[0]->mapping->host)->root;
4018         return btree_read_extent_buffer_pages(root, buf, 0, parent_transid);
4019 }
4020
4021 static int btrfs_check_super_valid(struct btrfs_fs_info *fs_info,
4022                               int read_only)
4023 {
4024         struct btrfs_super_block *sb = fs_info->super_copy;
4025         u64 nodesize = btrfs_super_nodesize(sb);
4026         u64 sectorsize = btrfs_super_sectorsize(sb);
4027         int ret = 0;
4028
4029         if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
4030                 printk(KERN_ERR "BTRFS: no valid FS found\n");
4031                 ret = -EINVAL;
4032         }
4033         if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP)
4034                 printk(KERN_WARNING "BTRFS: unrecognized super flag: %llu\n",
4035                                 btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
4036         if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
4037                 printk(KERN_ERR "BTRFS: tree_root level too big: %d >= %d\n",
4038                                 btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
4039                 ret = -EINVAL;
4040         }
4041         if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
4042                 printk(KERN_ERR "BTRFS: chunk_root level too big: %d >= %d\n",
4043                                 btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
4044                 ret = -EINVAL;
4045         }
4046         if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
4047                 printk(KERN_ERR "BTRFS: log_root level too big: %d >= %d\n",
4048                                 btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
4049                 ret = -EINVAL;
4050         }
4051
4052         /*
4053          * Check sectorsize and nodesize first, other check will need it.
4054          * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
4055          */
4056         if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
4057             sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
4058                 printk(KERN_ERR "BTRFS: invalid sectorsize %llu\n", sectorsize);
4059                 ret = -EINVAL;
4060         }
4061         /* Only PAGE SIZE is supported yet */
4062         if (sectorsize != PAGE_CACHE_SIZE) {
4063                 printk(KERN_ERR "BTRFS: sectorsize %llu not supported yet, only support %lu\n",
4064                                 sectorsize, PAGE_CACHE_SIZE);
4065                 ret = -EINVAL;
4066         }
4067         if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
4068             nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
4069                 printk(KERN_ERR "BTRFS: invalid nodesize %llu\n", nodesize);
4070                 ret = -EINVAL;
4071         }
4072         if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
4073                 printk(KERN_ERR "BTRFS: invalid leafsize %u, should be %llu\n",
4074                                 le32_to_cpu(sb->__unused_leafsize),
4075                                 nodesize);
4076                 ret = -EINVAL;
4077         }
4078
4079         /* Root alignment check */
4080         if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
4081                 printk(KERN_WARNING "BTRFS: tree_root block unaligned: %llu\n",
4082                                 btrfs_super_root(sb));
4083                 ret = -EINVAL;
4084         }
4085         if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
4086                 printk(KERN_WARNING "BTRFS: chunk_root block unaligned: %llu\n",
4087                                 btrfs_super_chunk_root(sb));
4088                 ret = -EINVAL;
4089         }
4090         if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
4091                 printk(KERN_WARNING "BTRFS: log_root block unaligned: %llu\n",
4092                                 btrfs_super_log_root(sb));
4093                 ret = -EINVAL;
4094         }
4095
4096         if (memcmp(fs_info->fsid, sb->dev_item.fsid, BTRFS_UUID_SIZE) != 0) {
4097                 printk(KERN_ERR "BTRFS: dev_item UUID does not match fsid: %pU != %pU\n",
4098                                 fs_info->fsid, sb->dev_item.fsid);
4099                 ret = -EINVAL;
4100         }
4101
4102         /*
4103          * Hint to catch really bogus numbers, bitflips or so, more exact checks are
4104          * done later
4105          */
4106         if (btrfs_super_num_devices(sb) > (1UL << 31))
4107                 printk(KERN_WARNING "BTRFS: suspicious number of devices: %llu\n",
4108                                 btrfs_super_num_devices(sb));
4109         if (btrfs_super_num_devices(sb) == 0) {
4110                 printk(KERN_ERR "BTRFS: number of devices is 0\n");
4111                 ret = -EINVAL;
4112         }
4113
4114         if (btrfs_super_bytenr(sb) != BTRFS_SUPER_INFO_OFFSET) {
4115                 printk(KERN_ERR "BTRFS: super offset mismatch %llu != %u\n",
4116                                 btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
4117                 ret = -EINVAL;
4118         }
4119
4120         /*
4121          * Obvious sys_chunk_array corruptions, it must hold at least one key
4122          * and one chunk
4123          */
4124         if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4125                 printk(KERN_ERR "BTRFS: system chunk array too big %u > %u\n",
4126                                 btrfs_super_sys_array_size(sb),
4127                                 BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
4128                 ret = -EINVAL;
4129         }
4130         if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
4131                         + sizeof(struct btrfs_chunk)) {
4132                 printk(KERN_ERR "BTRFS: system chunk array too small %u < %zu\n",
4133                                 btrfs_super_sys_array_size(sb),
4134                                 sizeof(struct btrfs_disk_key)
4135                                 + sizeof(struct btrfs_chunk));
4136                 ret = -EINVAL;
4137         }
4138
4139         /*
4140          * The generation is a global counter, we'll trust it more than the others
4141          * but it's still possible that it's the one that's wrong.
4142          */
4143         if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
4144                 printk(KERN_WARNING
4145                         "BTRFS: suspicious: generation < chunk_root_generation: %llu < %llu\n",
4146                         btrfs_super_generation(sb), btrfs_super_chunk_root_generation(sb));
4147         if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
4148             && btrfs_super_cache_generation(sb) != (u64)-1)
4149                 printk(KERN_WARNING
4150                         "BTRFS: suspicious: generation < cache_generation: %llu < %llu\n",
4151                         btrfs_super_generation(sb), btrfs_super_cache_generation(sb));
4152
4153         return ret;
4154 }
4155
4156 static void btrfs_error_commit_super(struct btrfs_root *root)
4157 {
4158         mutex_lock(&root->fs_info->cleaner_mutex);
4159         btrfs_run_delayed_iputs(root);
4160         mutex_unlock(&root->fs_info->cleaner_mutex);
4161
4162         down_write(&root->fs_info->cleanup_work_sem);
4163         up_write(&root->fs_info->cleanup_work_sem);
4164
4165         /* cleanup FS via transaction */
4166         btrfs_cleanup_transaction(root);
4167 }
4168
4169 static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4170 {
4171         struct btrfs_ordered_extent *ordered;
4172
4173         spin_lock(&root->ordered_extent_lock);
4174         /*
4175          * This will just short circuit the ordered completion stuff which will
4176          * make sure the ordered extent gets properly cleaned up.
4177          */
4178         list_for_each_entry(ordered, &root->ordered_extents,
4179                             root_extent_list)
4180                 set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4181         spin_unlock(&root->ordered_extent_lock);
4182 }
4183
4184 static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4185 {
4186         struct btrfs_root *root;
4187         struct list_head splice;
4188
4189         INIT_LIST_HEAD(&splice);
4190
4191         spin_lock(&fs_info->ordered_root_lock);
4192         list_splice_init(&fs_info->ordered_roots, &splice);
4193         while (!list_empty(&splice)) {
4194                 root = list_first_entry(&splice, struct btrfs_root,
4195                                         ordered_root);
4196                 list_move_tail(&root->ordered_root,
4197                                &fs_info->ordered_roots);
4198
4199                 spin_unlock(&fs_info->ordered_root_lock);
4200                 btrfs_destroy_ordered_extents(root);
4201
4202                 cond_resched();
4203                 spin_lock(&fs_info->ordered_root_lock);
4204         }
4205         spin_unlock(&fs_info->ordered_root_lock);
4206 }
4207
4208 static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
4209                                       struct btrfs_root *root)
4210 {
4211         struct rb_node *node;
4212         struct btrfs_delayed_ref_root *delayed_refs;
4213         struct btrfs_delayed_ref_node *ref;
4214         int ret = 0;
4215
4216         delayed_refs = &trans->delayed_refs;
4217
4218         spin_lock(&delayed_refs->lock);
4219         if (atomic_read(&delayed_refs->num_entries) == 0) {
4220                 spin_unlock(&delayed_refs->lock);
4221                 btrfs_info(root->fs_info, "delayed_refs has NO entry");
4222                 return ret;
4223         }
4224
4225         while ((node = rb_first(&delayed_refs->href_root)) != NULL) {
4226                 struct btrfs_delayed_ref_head *head;
4227                 struct btrfs_delayed_ref_node *tmp;
4228                 bool pin_bytes = false;
4229
4230                 head = rb_entry(node, struct btrfs_delayed_ref_head,
4231                                 href_node);
4232                 if (!mutex_trylock(&head->mutex)) {
4233                         atomic_inc(&head->node.refs);
4234                         spin_unlock(&delayed_refs->lock);
4235
4236                         mutex_lock(&head->mutex);
4237                         mutex_unlock(&head->mutex);
4238                         btrfs_put_delayed_ref(&head->node);
4239                         spin_lock(&delayed_refs->lock);
4240                         continue;
4241                 }
4242                 spin_lock(&head->lock);
4243                 list_for_each_entry_safe_reverse(ref, tmp, &head->ref_list,
4244                                                  list) {
4245                         ref->in_tree = 0;
4246                         list_del(&ref->list);
4247                         atomic_dec(&delayed_refs->num_entries);
4248                         btrfs_put_delayed_ref(ref);
4249                 }
4250                 if (head->must_insert_reserved)
4251                         pin_bytes = true;
4252                 btrfs_free_delayed_extent_op(head->extent_op);
4253                 delayed_refs->num_heads--;
4254                 if (head->processing == 0)
4255                         delayed_refs->num_heads_ready--;
4256                 atomic_dec(&delayed_refs->num_entries);
4257                 head->node.in_tree = 0;
4258                 rb_erase(&head->href_node, &delayed_refs->href_root);
4259                 spin_unlock(&head->lock);
4260                 spin_unlock(&delayed_refs->lock);
4261                 mutex_unlock(&head->mutex);
4262
4263                 if (pin_bytes)
4264                         btrfs_pin_extent(root, head->node.bytenr,
4265                                          head->node.num_bytes, 1);
4266                 btrfs_put_delayed_ref(&head->node);
4267                 cond_resched();
4268                 spin_lock(&delayed_refs->lock);
4269         }
4270
4271         spin_unlock(&delayed_refs->lock);
4272
4273         return ret;
4274 }
4275
4276 static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4277 {
4278         struct btrfs_inode *btrfs_inode;
4279         struct list_head splice;
4280
4281         INIT_LIST_HEAD(&splice);
4282
4283         spin_lock(&root->delalloc_lock);
4284         list_splice_init(&root->delalloc_inodes, &splice);
4285
4286         while (!list_empty(&splice)) {
4287                 btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4288                                                delalloc_inodes);
4289
4290                 list_del_init(&btrfs_inode->delalloc_inodes);
4291                 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
4292                           &btrfs_inode->runtime_flags);
4293                 spin_unlock(&root->delalloc_lock);
4294
4295                 btrfs_invalidate_inodes(btrfs_inode->root);
4296
4297                 spin_lock(&root->delalloc_lock);
4298         }
4299
4300         spin_unlock(&root->delalloc_lock);
4301 }
4302
4303 static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4304 {
4305         struct btrfs_root *root;
4306         struct list_head splice;
4307
4308         INIT_LIST_HEAD(&splice);
4309
4310         spin_lock(&fs_info->delalloc_root_lock);
4311         list_splice_init(&fs_info->delalloc_roots, &splice);
4312         while (!list_empty(&splice)) {
4313                 root = list_first_entry(&splice, struct btrfs_root,
4314                                          delalloc_root);
4315                 list_del_init(&root->delalloc_root);
4316                 root = btrfs_grab_fs_root(root);
4317                 BUG_ON(!root);
4318                 spin_unlock(&fs_info->delalloc_root_lock);
4319
4320                 btrfs_destroy_delalloc_inodes(root);
4321                 btrfs_put_fs_root(root);
4322
4323                 spin_lock(&fs_info->delalloc_root_lock);
4324         }
4325         spin_unlock(&fs_info->delalloc_root_lock);
4326 }
4327
4328 static int btrfs_destroy_marked_extents(struct btrfs_root *root,
4329                                         struct extent_io_tree *dirty_pages,
4330                                         int mark)
4331 {
4332         int ret;
4333         struct extent_buffer *eb;
4334         u64 start = 0;
4335         u64 end;
4336
4337         while (1) {
4338                 ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4339                                             mark, NULL);
4340                 if (ret)
4341                         break;
4342
4343                 clear_extent_bits(dirty_pages, start, end, mark, GFP_NOFS);
4344                 while (start <= end) {
4345                         eb = btrfs_find_tree_block(root->fs_info, start);
4346                         start += root->nodesize;
4347                         if (!eb)
4348                                 continue;
4349                         wait_on_extent_buffer_writeback(eb);
4350
4351                         if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
4352                                                &eb->bflags))
4353                                 clear_extent_buffer_dirty(eb);
4354                         free_extent_buffer_stale(eb);
4355                 }
4356         }
4357
4358         return ret;
4359 }
4360
4361 static int btrfs_destroy_pinned_extent(struct btrfs_root *root,
4362                                        struct extent_io_tree *pinned_extents)
4363 {
4364         struct extent_io_tree *unpin;
4365         u64 start;
4366         u64 end;
4367         int ret;
4368         bool loop = true;
4369
4370         unpin = pinned_extents;
4371 again:
4372         while (1) {
4373                 ret = find_first_extent_bit(unpin, 0, &start, &end,
4374                                             EXTENT_DIRTY, NULL);
4375                 if (ret)
4376                         break;
4377
4378                 clear_extent_dirty(unpin, start, end, GFP_NOFS);
4379                 btrfs_error_unpin_extent_range(root, start, end);
4380                 cond_resched();
4381         }
4382
4383         if (loop) {
4384                 if (unpin == &root->fs_info->freed_extents[0])
4385                         unpin = &root->fs_info->freed_extents[1];
4386                 else
4387                         unpin = &root->fs_info->freed_extents[0];
4388                 loop = false;
4389                 goto again;
4390         }
4391
4392         return 0;
4393 }
4394
4395 void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
4396                                    struct btrfs_root *root)
4397 {
4398         btrfs_destroy_delayed_refs(cur_trans, root);
4399
4400         cur_trans->state = TRANS_STATE_COMMIT_START;
4401         wake_up(&root->fs_info->transaction_blocked_wait);
4402
4403         cur_trans->state = TRANS_STATE_UNBLOCKED;
4404         wake_up(&root->fs_info->transaction_wait);
4405
4406         btrfs_destroy_delayed_inodes(root);
4407         btrfs_assert_delayed_root_empty(root);
4408
4409         btrfs_destroy_marked_extents(root, &cur_trans->dirty_pages,
4410                                      EXTENT_DIRTY);
4411         btrfs_destroy_pinned_extent(root,
4412                                     root->fs_info->pinned_extents);
4413
4414         cur_trans->state =TRANS_STATE_COMPLETED;
4415         wake_up(&cur_trans->commit_wait);
4416
4417         /*
4418         memset(cur_trans, 0, sizeof(*cur_trans));
4419         kmem_cache_free(btrfs_transaction_cachep, cur_trans);
4420         */
4421 }
4422
4423 static int btrfs_cleanup_transaction(struct btrfs_root *root)
4424 {
4425         struct btrfs_transaction *t;
4426
4427         mutex_lock(&root->fs_info->transaction_kthread_mutex);
4428
4429         spin_lock(&root->fs_info->trans_lock);
4430         while (!list_empty(&root->fs_info->trans_list)) {
4431                 t = list_first_entry(&root->fs_info->trans_list,
4432                                      struct btrfs_transaction, list);
4433                 if (t->state >= TRANS_STATE_COMMIT_START) {
4434                         atomic_inc(&t->use_count);
4435                         spin_unlock(&root->fs_info->trans_lock);
4436                         btrfs_wait_for_commit(root, t->transid);
4437                         btrfs_put_transaction(t);
4438                         spin_lock(&root->fs_info->trans_lock);
4439                         continue;
4440                 }
4441                 if (t == root->fs_info->running_transaction) {
4442                         t->state = TRANS_STATE_COMMIT_DOING;
4443                         spin_unlock(&root->fs_info->trans_lock);
4444                         /*
4445                          * We wait for 0 num_writers since we don't hold a trans
4446                          * handle open currently for this transaction.
4447                          */
4448                         wait_event(t->writer_wait,
4449                                    atomic_read(&t->num_writers) == 0);
4450                 } else {
4451                         spin_unlock(&root->fs_info->trans_lock);
4452                 }
4453                 btrfs_cleanup_one_transaction(t, root);
4454
4455                 spin_lock(&root->fs_info->trans_lock);
4456                 if (t == root->fs_info->running_transaction)
4457                         root->fs_info->running_transaction = NULL;
4458                 list_del_init(&t->list);
4459                 spin_unlock(&root->fs_info->trans_lock);
4460
4461                 btrfs_put_transaction(t);
4462                 trace_btrfs_transaction_commit(root);
4463                 spin_lock(&root->fs_info->trans_lock);
4464         }
4465         spin_unlock(&root->fs_info->trans_lock);
4466         btrfs_destroy_all_ordered_extents(root->fs_info);
4467         btrfs_destroy_delayed_inodes(root);
4468         btrfs_assert_delayed_root_empty(root);
4469         btrfs_destroy_pinned_extent(root, root->fs_info->pinned_extents);
4470         btrfs_destroy_all_delalloc_inodes(root->fs_info);
4471         mutex_unlock(&root->fs_info->transaction_kthread_mutex);
4472
4473         return 0;
4474 }
4475
4476 static const struct extent_io_ops btree_extent_io_ops = {
4477         .readpage_end_io_hook = btree_readpage_end_io_hook,
4478         .readpage_io_failed_hook = btree_io_failed_hook,
4479         .submit_bio_hook = btree_submit_bio_hook,
4480         /* note we're sharing with inode.c for the merge bio hook */
4481         .merge_bio_hook = btrfs_merge_bio_hook,
4482 };