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