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