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