btrfs: use EXPORT_FOR_TESTS for conditionally exported functions
[sfrench/cifs-2.6.git] / fs / btrfs / transaction.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/slab.h>
8 #include <linux/sched.h>
9 #include <linux/writeback.h>
10 #include <linux/pagemap.h>
11 #include <linux/blkdev.h>
12 #include <linux/uuid.h>
13 #include "ctree.h"
14 #include "disk-io.h"
15 #include "transaction.h"
16 #include "locking.h"
17 #include "tree-log.h"
18 #include "inode-map.h"
19 #include "volumes.h"
20 #include "dev-replace.h"
21 #include "qgroup.h"
22
23 #define BTRFS_ROOT_TRANS_TAG 0
24
25 static const unsigned int btrfs_blocked_trans_types[TRANS_STATE_MAX] = {
26         [TRANS_STATE_RUNNING]           = 0U,
27         [TRANS_STATE_BLOCKED]           =  __TRANS_START,
28         [TRANS_STATE_COMMIT_START]      = (__TRANS_START | __TRANS_ATTACH),
29         [TRANS_STATE_COMMIT_DOING]      = (__TRANS_START |
30                                            __TRANS_ATTACH |
31                                            __TRANS_JOIN),
32         [TRANS_STATE_UNBLOCKED]         = (__TRANS_START |
33                                            __TRANS_ATTACH |
34                                            __TRANS_JOIN |
35                                            __TRANS_JOIN_NOLOCK),
36         [TRANS_STATE_COMPLETED]         = (__TRANS_START |
37                                            __TRANS_ATTACH |
38                                            __TRANS_JOIN |
39                                            __TRANS_JOIN_NOLOCK),
40 };
41
42 void btrfs_put_transaction(struct btrfs_transaction *transaction)
43 {
44         WARN_ON(refcount_read(&transaction->use_count) == 0);
45         if (refcount_dec_and_test(&transaction->use_count)) {
46                 BUG_ON(!list_empty(&transaction->list));
47                 WARN_ON(!RB_EMPTY_ROOT(
48                                 &transaction->delayed_refs.href_root.rb_root));
49                 if (transaction->delayed_refs.pending_csums)
50                         btrfs_err(transaction->fs_info,
51                                   "pending csums is %llu",
52                                   transaction->delayed_refs.pending_csums);
53                 while (!list_empty(&transaction->pending_chunks)) {
54                         struct extent_map *em;
55
56                         em = list_first_entry(&transaction->pending_chunks,
57                                               struct extent_map, list);
58                         list_del_init(&em->list);
59                         free_extent_map(em);
60                 }
61                 /*
62                  * If any block groups are found in ->deleted_bgs then it's
63                  * because the transaction was aborted and a commit did not
64                  * happen (things failed before writing the new superblock
65                  * and calling btrfs_finish_extent_commit()), so we can not
66                  * discard the physical locations of the block groups.
67                  */
68                 while (!list_empty(&transaction->deleted_bgs)) {
69                         struct btrfs_block_group_cache *cache;
70
71                         cache = list_first_entry(&transaction->deleted_bgs,
72                                                  struct btrfs_block_group_cache,
73                                                  bg_list);
74                         list_del_init(&cache->bg_list);
75                         btrfs_put_block_group_trimming(cache);
76                         btrfs_put_block_group(cache);
77                 }
78                 kfree(transaction);
79         }
80 }
81
82 static void clear_btree_io_tree(struct extent_io_tree *tree)
83 {
84         spin_lock(&tree->lock);
85         /*
86          * Do a single barrier for the waitqueue_active check here, the state
87          * of the waitqueue should not change once clear_btree_io_tree is
88          * called.
89          */
90         smp_mb();
91         while (!RB_EMPTY_ROOT(&tree->state)) {
92                 struct rb_node *node;
93                 struct extent_state *state;
94
95                 node = rb_first(&tree->state);
96                 state = rb_entry(node, struct extent_state, rb_node);
97                 rb_erase(&state->rb_node, &tree->state);
98                 RB_CLEAR_NODE(&state->rb_node);
99                 /*
100                  * btree io trees aren't supposed to have tasks waiting for
101                  * changes in the flags of extent states ever.
102                  */
103                 ASSERT(!waitqueue_active(&state->wq));
104                 free_extent_state(state);
105
106                 cond_resched_lock(&tree->lock);
107         }
108         spin_unlock(&tree->lock);
109 }
110
111 static noinline void switch_commit_roots(struct btrfs_transaction *trans)
112 {
113         struct btrfs_fs_info *fs_info = trans->fs_info;
114         struct btrfs_root *root, *tmp;
115
116         down_write(&fs_info->commit_root_sem);
117         list_for_each_entry_safe(root, tmp, &trans->switch_commits,
118                                  dirty_list) {
119                 list_del_init(&root->dirty_list);
120                 free_extent_buffer(root->commit_root);
121                 root->commit_root = btrfs_root_node(root);
122                 if (is_fstree(root->root_key.objectid))
123                         btrfs_unpin_free_ino(root);
124                 clear_btree_io_tree(&root->dirty_log_pages);
125         }
126
127         /* We can free old roots now. */
128         spin_lock(&trans->dropped_roots_lock);
129         while (!list_empty(&trans->dropped_roots)) {
130                 root = list_first_entry(&trans->dropped_roots,
131                                         struct btrfs_root, root_list);
132                 list_del_init(&root->root_list);
133                 spin_unlock(&trans->dropped_roots_lock);
134                 btrfs_drop_and_free_fs_root(fs_info, root);
135                 spin_lock(&trans->dropped_roots_lock);
136         }
137         spin_unlock(&trans->dropped_roots_lock);
138         up_write(&fs_info->commit_root_sem);
139 }
140
141 static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
142                                          unsigned int type)
143 {
144         if (type & TRANS_EXTWRITERS)
145                 atomic_inc(&trans->num_extwriters);
146 }
147
148 static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
149                                          unsigned int type)
150 {
151         if (type & TRANS_EXTWRITERS)
152                 atomic_dec(&trans->num_extwriters);
153 }
154
155 static inline void extwriter_counter_init(struct btrfs_transaction *trans,
156                                           unsigned int type)
157 {
158         atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
159 }
160
161 static inline int extwriter_counter_read(struct btrfs_transaction *trans)
162 {
163         return atomic_read(&trans->num_extwriters);
164 }
165
166 /*
167  * either allocate a new transaction or hop into the existing one
168  */
169 static noinline int join_transaction(struct btrfs_fs_info *fs_info,
170                                      unsigned int type)
171 {
172         struct btrfs_transaction *cur_trans;
173
174         spin_lock(&fs_info->trans_lock);
175 loop:
176         /* The file system has been taken offline. No new transactions. */
177         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
178                 spin_unlock(&fs_info->trans_lock);
179                 return -EROFS;
180         }
181
182         cur_trans = fs_info->running_transaction;
183         if (cur_trans) {
184                 if (cur_trans->aborted) {
185                         spin_unlock(&fs_info->trans_lock);
186                         return cur_trans->aborted;
187                 }
188                 if (btrfs_blocked_trans_types[cur_trans->state] & type) {
189                         spin_unlock(&fs_info->trans_lock);
190                         return -EBUSY;
191                 }
192                 refcount_inc(&cur_trans->use_count);
193                 atomic_inc(&cur_trans->num_writers);
194                 extwriter_counter_inc(cur_trans, type);
195                 spin_unlock(&fs_info->trans_lock);
196                 return 0;
197         }
198         spin_unlock(&fs_info->trans_lock);
199
200         /*
201          * If we are ATTACH, we just want to catch the current transaction,
202          * and commit it. If there is no transaction, just return ENOENT.
203          */
204         if (type == TRANS_ATTACH)
205                 return -ENOENT;
206
207         /*
208          * JOIN_NOLOCK only happens during the transaction commit, so
209          * it is impossible that ->running_transaction is NULL
210          */
211         BUG_ON(type == TRANS_JOIN_NOLOCK);
212
213         cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
214         if (!cur_trans)
215                 return -ENOMEM;
216
217         spin_lock(&fs_info->trans_lock);
218         if (fs_info->running_transaction) {
219                 /*
220                  * someone started a transaction after we unlocked.  Make sure
221                  * to redo the checks above
222                  */
223                 kfree(cur_trans);
224                 goto loop;
225         } else if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
226                 spin_unlock(&fs_info->trans_lock);
227                 kfree(cur_trans);
228                 return -EROFS;
229         }
230
231         cur_trans->fs_info = fs_info;
232         atomic_set(&cur_trans->num_writers, 1);
233         extwriter_counter_init(cur_trans, type);
234         init_waitqueue_head(&cur_trans->writer_wait);
235         init_waitqueue_head(&cur_trans->commit_wait);
236         cur_trans->state = TRANS_STATE_RUNNING;
237         /*
238          * One for this trans handle, one so it will live on until we
239          * commit the transaction.
240          */
241         refcount_set(&cur_trans->use_count, 2);
242         cur_trans->flags = 0;
243         cur_trans->start_time = ktime_get_seconds();
244
245         memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
246
247         cur_trans->delayed_refs.href_root = RB_ROOT_CACHED;
248         cur_trans->delayed_refs.dirty_extent_root = RB_ROOT;
249         atomic_set(&cur_trans->delayed_refs.num_entries, 0);
250
251         /*
252          * although the tree mod log is per file system and not per transaction,
253          * the log must never go across transaction boundaries.
254          */
255         smp_mb();
256         if (!list_empty(&fs_info->tree_mod_seq_list))
257                 WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
258         if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
259                 WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
260         atomic64_set(&fs_info->tree_mod_seq, 0);
261
262         spin_lock_init(&cur_trans->delayed_refs.lock);
263
264         INIT_LIST_HEAD(&cur_trans->pending_snapshots);
265         INIT_LIST_HEAD(&cur_trans->pending_chunks);
266         INIT_LIST_HEAD(&cur_trans->switch_commits);
267         INIT_LIST_HEAD(&cur_trans->dirty_bgs);
268         INIT_LIST_HEAD(&cur_trans->io_bgs);
269         INIT_LIST_HEAD(&cur_trans->dropped_roots);
270         mutex_init(&cur_trans->cache_write_mutex);
271         cur_trans->num_dirty_bgs = 0;
272         spin_lock_init(&cur_trans->dirty_bgs_lock);
273         INIT_LIST_HEAD(&cur_trans->deleted_bgs);
274         spin_lock_init(&cur_trans->dropped_roots_lock);
275         list_add_tail(&cur_trans->list, &fs_info->trans_list);
276         extent_io_tree_init(&cur_trans->dirty_pages,
277                              fs_info->btree_inode);
278         fs_info->generation++;
279         cur_trans->transid = fs_info->generation;
280         fs_info->running_transaction = cur_trans;
281         cur_trans->aborted = 0;
282         spin_unlock(&fs_info->trans_lock);
283
284         return 0;
285 }
286
287 /*
288  * this does all the record keeping required to make sure that a reference
289  * counted root is properly recorded in a given transaction.  This is required
290  * to make sure the old root from before we joined the transaction is deleted
291  * when the transaction commits
292  */
293 static int record_root_in_trans(struct btrfs_trans_handle *trans,
294                                struct btrfs_root *root,
295                                int force)
296 {
297         struct btrfs_fs_info *fs_info = root->fs_info;
298
299         if ((test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
300             root->last_trans < trans->transid) || force) {
301                 WARN_ON(root == fs_info->extent_root);
302                 WARN_ON(!force && root->commit_root != root->node);
303
304                 /*
305                  * see below for IN_TRANS_SETUP usage rules
306                  * we have the reloc mutex held now, so there
307                  * is only one writer in this function
308                  */
309                 set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
310
311                 /* make sure readers find IN_TRANS_SETUP before
312                  * they find our root->last_trans update
313                  */
314                 smp_wmb();
315
316                 spin_lock(&fs_info->fs_roots_radix_lock);
317                 if (root->last_trans == trans->transid && !force) {
318                         spin_unlock(&fs_info->fs_roots_radix_lock);
319                         return 0;
320                 }
321                 radix_tree_tag_set(&fs_info->fs_roots_radix,
322                                    (unsigned long)root->root_key.objectid,
323                                    BTRFS_ROOT_TRANS_TAG);
324                 spin_unlock(&fs_info->fs_roots_radix_lock);
325                 root->last_trans = trans->transid;
326
327                 /* this is pretty tricky.  We don't want to
328                  * take the relocation lock in btrfs_record_root_in_trans
329                  * unless we're really doing the first setup for this root in
330                  * this transaction.
331                  *
332                  * Normally we'd use root->last_trans as a flag to decide
333                  * if we want to take the expensive mutex.
334                  *
335                  * But, we have to set root->last_trans before we
336                  * init the relocation root, otherwise, we trip over warnings
337                  * in ctree.c.  The solution used here is to flag ourselves
338                  * with root IN_TRANS_SETUP.  When this is 1, we're still
339                  * fixing up the reloc trees and everyone must wait.
340                  *
341                  * When this is zero, they can trust root->last_trans and fly
342                  * through btrfs_record_root_in_trans without having to take the
343                  * lock.  smp_wmb() makes sure that all the writes above are
344                  * done before we pop in the zero below
345                  */
346                 btrfs_init_reloc_root(trans, root);
347                 smp_mb__before_atomic();
348                 clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
349         }
350         return 0;
351 }
352
353
354 void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
355                             struct btrfs_root *root)
356 {
357         struct btrfs_fs_info *fs_info = root->fs_info;
358         struct btrfs_transaction *cur_trans = trans->transaction;
359
360         /* Add ourselves to the transaction dropped list */
361         spin_lock(&cur_trans->dropped_roots_lock);
362         list_add_tail(&root->root_list, &cur_trans->dropped_roots);
363         spin_unlock(&cur_trans->dropped_roots_lock);
364
365         /* Make sure we don't try to update the root at commit time */
366         spin_lock(&fs_info->fs_roots_radix_lock);
367         radix_tree_tag_clear(&fs_info->fs_roots_radix,
368                              (unsigned long)root->root_key.objectid,
369                              BTRFS_ROOT_TRANS_TAG);
370         spin_unlock(&fs_info->fs_roots_radix_lock);
371 }
372
373 int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
374                                struct btrfs_root *root)
375 {
376         struct btrfs_fs_info *fs_info = root->fs_info;
377
378         if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
379                 return 0;
380
381         /*
382          * see record_root_in_trans for comments about IN_TRANS_SETUP usage
383          * and barriers
384          */
385         smp_rmb();
386         if (root->last_trans == trans->transid &&
387             !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
388                 return 0;
389
390         mutex_lock(&fs_info->reloc_mutex);
391         record_root_in_trans(trans, root, 0);
392         mutex_unlock(&fs_info->reloc_mutex);
393
394         return 0;
395 }
396
397 static inline int is_transaction_blocked(struct btrfs_transaction *trans)
398 {
399         return (trans->state >= TRANS_STATE_BLOCKED &&
400                 trans->state < TRANS_STATE_UNBLOCKED &&
401                 !trans->aborted);
402 }
403
404 /* wait for commit against the current transaction to become unblocked
405  * when this is done, it is safe to start a new transaction, but the current
406  * transaction might not be fully on disk.
407  */
408 static void wait_current_trans(struct btrfs_fs_info *fs_info)
409 {
410         struct btrfs_transaction *cur_trans;
411
412         spin_lock(&fs_info->trans_lock);
413         cur_trans = fs_info->running_transaction;
414         if (cur_trans && is_transaction_blocked(cur_trans)) {
415                 refcount_inc(&cur_trans->use_count);
416                 spin_unlock(&fs_info->trans_lock);
417
418                 wait_event(fs_info->transaction_wait,
419                            cur_trans->state >= TRANS_STATE_UNBLOCKED ||
420                            cur_trans->aborted);
421                 btrfs_put_transaction(cur_trans);
422         } else {
423                 spin_unlock(&fs_info->trans_lock);
424         }
425 }
426
427 static int may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
428 {
429         if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
430                 return 0;
431
432         if (type == TRANS_START)
433                 return 1;
434
435         return 0;
436 }
437
438 static inline bool need_reserve_reloc_root(struct btrfs_root *root)
439 {
440         struct btrfs_fs_info *fs_info = root->fs_info;
441
442         if (!fs_info->reloc_ctl ||
443             !test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
444             root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
445             root->reloc_root)
446                 return false;
447
448         return true;
449 }
450
451 static struct btrfs_trans_handle *
452 start_transaction(struct btrfs_root *root, unsigned int num_items,
453                   unsigned int type, enum btrfs_reserve_flush_enum flush,
454                   bool enforce_qgroups)
455 {
456         struct btrfs_fs_info *fs_info = root->fs_info;
457
458         struct btrfs_trans_handle *h;
459         struct btrfs_transaction *cur_trans;
460         u64 num_bytes = 0;
461         u64 qgroup_reserved = 0;
462         bool reloc_reserved = false;
463         int ret;
464
465         /* Send isn't supposed to start transactions. */
466         ASSERT(current->journal_info != BTRFS_SEND_TRANS_STUB);
467
468         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
469                 return ERR_PTR(-EROFS);
470
471         if (current->journal_info) {
472                 WARN_ON(type & TRANS_EXTWRITERS);
473                 h = current->journal_info;
474                 refcount_inc(&h->use_count);
475                 WARN_ON(refcount_read(&h->use_count) > 2);
476                 h->orig_rsv = h->block_rsv;
477                 h->block_rsv = NULL;
478                 goto got_it;
479         }
480
481         /*
482          * Do the reservation before we join the transaction so we can do all
483          * the appropriate flushing if need be.
484          */
485         if (num_items && root != fs_info->chunk_root) {
486                 qgroup_reserved = num_items * fs_info->nodesize;
487                 ret = btrfs_qgroup_reserve_meta_pertrans(root, qgroup_reserved,
488                                 enforce_qgroups);
489                 if (ret)
490                         return ERR_PTR(ret);
491
492                 num_bytes = btrfs_calc_trans_metadata_size(fs_info, num_items);
493                 /*
494                  * Do the reservation for the relocation root creation
495                  */
496                 if (need_reserve_reloc_root(root)) {
497                         num_bytes += fs_info->nodesize;
498                         reloc_reserved = true;
499                 }
500
501                 ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
502                                           num_bytes, flush);
503                 if (ret)
504                         goto reserve_fail;
505         }
506 again:
507         h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
508         if (!h) {
509                 ret = -ENOMEM;
510                 goto alloc_fail;
511         }
512
513         /*
514          * If we are JOIN_NOLOCK we're already committing a transaction and
515          * waiting on this guy, so we don't need to do the sb_start_intwrite
516          * because we're already holding a ref.  We need this because we could
517          * have raced in and did an fsync() on a file which can kick a commit
518          * and then we deadlock with somebody doing a freeze.
519          *
520          * If we are ATTACH, it means we just want to catch the current
521          * transaction and commit it, so we needn't do sb_start_intwrite(). 
522          */
523         if (type & __TRANS_FREEZABLE)
524                 sb_start_intwrite(fs_info->sb);
525
526         if (may_wait_transaction(fs_info, type))
527                 wait_current_trans(fs_info);
528
529         do {
530                 ret = join_transaction(fs_info, type);
531                 if (ret == -EBUSY) {
532                         wait_current_trans(fs_info);
533                         if (unlikely(type == TRANS_ATTACH))
534                                 ret = -ENOENT;
535                 }
536         } while (ret == -EBUSY);
537
538         if (ret < 0)
539                 goto join_fail;
540
541         cur_trans = fs_info->running_transaction;
542
543         h->transid = cur_trans->transid;
544         h->transaction = cur_trans;
545         h->root = root;
546         refcount_set(&h->use_count, 1);
547         h->fs_info = root->fs_info;
548
549         h->type = type;
550         h->can_flush_pending_bgs = true;
551         INIT_LIST_HEAD(&h->new_bgs);
552
553         smp_mb();
554         if (cur_trans->state >= TRANS_STATE_BLOCKED &&
555             may_wait_transaction(fs_info, type)) {
556                 current->journal_info = h;
557                 btrfs_commit_transaction(h);
558                 goto again;
559         }
560
561         if (num_bytes) {
562                 trace_btrfs_space_reservation(fs_info, "transaction",
563                                               h->transid, num_bytes, 1);
564                 h->block_rsv = &fs_info->trans_block_rsv;
565                 h->bytes_reserved = num_bytes;
566                 h->reloc_reserved = reloc_reserved;
567         }
568
569 got_it:
570         btrfs_record_root_in_trans(h, root);
571
572         if (!current->journal_info)
573                 current->journal_info = h;
574         return h;
575
576 join_fail:
577         if (type & __TRANS_FREEZABLE)
578                 sb_end_intwrite(fs_info->sb);
579         kmem_cache_free(btrfs_trans_handle_cachep, h);
580 alloc_fail:
581         if (num_bytes)
582                 btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
583                                         num_bytes);
584 reserve_fail:
585         btrfs_qgroup_free_meta_pertrans(root, qgroup_reserved);
586         return ERR_PTR(ret);
587 }
588
589 struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
590                                                    unsigned int num_items)
591 {
592         return start_transaction(root, num_items, TRANS_START,
593                                  BTRFS_RESERVE_FLUSH_ALL, true);
594 }
595
596 struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
597                                         struct btrfs_root *root,
598                                         unsigned int num_items,
599                                         int min_factor)
600 {
601         struct btrfs_fs_info *fs_info = root->fs_info;
602         struct btrfs_trans_handle *trans;
603         u64 num_bytes;
604         int ret;
605
606         /*
607          * We have two callers: unlink and block group removal.  The
608          * former should succeed even if we will temporarily exceed
609          * quota and the latter operates on the extent root so
610          * qgroup enforcement is ignored anyway.
611          */
612         trans = start_transaction(root, num_items, TRANS_START,
613                                   BTRFS_RESERVE_FLUSH_ALL, false);
614         if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
615                 return trans;
616
617         trans = btrfs_start_transaction(root, 0);
618         if (IS_ERR(trans))
619                 return trans;
620
621         num_bytes = btrfs_calc_trans_metadata_size(fs_info, num_items);
622         ret = btrfs_cond_migrate_bytes(fs_info, &fs_info->trans_block_rsv,
623                                        num_bytes, min_factor);
624         if (ret) {
625                 btrfs_end_transaction(trans);
626                 return ERR_PTR(ret);
627         }
628
629         trans->block_rsv = &fs_info->trans_block_rsv;
630         trans->bytes_reserved = num_bytes;
631         trace_btrfs_space_reservation(fs_info, "transaction",
632                                       trans->transid, num_bytes, 1);
633
634         return trans;
635 }
636
637 struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
638 {
639         return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
640                                  true);
641 }
642
643 struct btrfs_trans_handle *btrfs_join_transaction_nolock(struct btrfs_root *root)
644 {
645         return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
646                                  BTRFS_RESERVE_NO_FLUSH, true);
647 }
648
649 /*
650  * btrfs_attach_transaction() - catch the running transaction
651  *
652  * It is used when we want to commit the current the transaction, but
653  * don't want to start a new one.
654  *
655  * Note: If this function return -ENOENT, it just means there is no
656  * running transaction. But it is possible that the inactive transaction
657  * is still in the memory, not fully on disk. If you hope there is no
658  * inactive transaction in the fs when -ENOENT is returned, you should
659  * invoke
660  *     btrfs_attach_transaction_barrier()
661  */
662 struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
663 {
664         return start_transaction(root, 0, TRANS_ATTACH,
665                                  BTRFS_RESERVE_NO_FLUSH, true);
666 }
667
668 /*
669  * btrfs_attach_transaction_barrier() - catch the running transaction
670  *
671  * It is similar to the above function, the differentia is this one
672  * will wait for all the inactive transactions until they fully
673  * complete.
674  */
675 struct btrfs_trans_handle *
676 btrfs_attach_transaction_barrier(struct btrfs_root *root)
677 {
678         struct btrfs_trans_handle *trans;
679
680         trans = start_transaction(root, 0, TRANS_ATTACH,
681                                   BTRFS_RESERVE_NO_FLUSH, true);
682         if (trans == ERR_PTR(-ENOENT))
683                 btrfs_wait_for_commit(root->fs_info, 0);
684
685         return trans;
686 }
687
688 /* wait for a transaction commit to be fully complete */
689 static noinline void wait_for_commit(struct btrfs_transaction *commit)
690 {
691         wait_event(commit->commit_wait, commit->state == TRANS_STATE_COMPLETED);
692 }
693
694 int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
695 {
696         struct btrfs_transaction *cur_trans = NULL, *t;
697         int ret = 0;
698
699         if (transid) {
700                 if (transid <= fs_info->last_trans_committed)
701                         goto out;
702
703                 /* find specified transaction */
704                 spin_lock(&fs_info->trans_lock);
705                 list_for_each_entry(t, &fs_info->trans_list, list) {
706                         if (t->transid == transid) {
707                                 cur_trans = t;
708                                 refcount_inc(&cur_trans->use_count);
709                                 ret = 0;
710                                 break;
711                         }
712                         if (t->transid > transid) {
713                                 ret = 0;
714                                 break;
715                         }
716                 }
717                 spin_unlock(&fs_info->trans_lock);
718
719                 /*
720                  * The specified transaction doesn't exist, or we
721                  * raced with btrfs_commit_transaction
722                  */
723                 if (!cur_trans) {
724                         if (transid > fs_info->last_trans_committed)
725                                 ret = -EINVAL;
726                         goto out;
727                 }
728         } else {
729                 /* find newest transaction that is committing | committed */
730                 spin_lock(&fs_info->trans_lock);
731                 list_for_each_entry_reverse(t, &fs_info->trans_list,
732                                             list) {
733                         if (t->state >= TRANS_STATE_COMMIT_START) {
734                                 if (t->state == TRANS_STATE_COMPLETED)
735                                         break;
736                                 cur_trans = t;
737                                 refcount_inc(&cur_trans->use_count);
738                                 break;
739                         }
740                 }
741                 spin_unlock(&fs_info->trans_lock);
742                 if (!cur_trans)
743                         goto out;  /* nothing committing|committed */
744         }
745
746         wait_for_commit(cur_trans);
747         btrfs_put_transaction(cur_trans);
748 out:
749         return ret;
750 }
751
752 void btrfs_throttle(struct btrfs_fs_info *fs_info)
753 {
754         wait_current_trans(fs_info);
755 }
756
757 static int should_end_transaction(struct btrfs_trans_handle *trans)
758 {
759         struct btrfs_fs_info *fs_info = trans->fs_info;
760
761         if (btrfs_check_space_for_delayed_refs(trans))
762                 return 1;
763
764         return !!btrfs_block_rsv_check(&fs_info->global_block_rsv, 5);
765 }
766
767 int btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
768 {
769         struct btrfs_transaction *cur_trans = trans->transaction;
770         int updates;
771         int err;
772
773         smp_mb();
774         if (cur_trans->state >= TRANS_STATE_BLOCKED ||
775             cur_trans->delayed_refs.flushing)
776                 return 1;
777
778         updates = trans->delayed_ref_updates;
779         trans->delayed_ref_updates = 0;
780         if (updates) {
781                 err = btrfs_run_delayed_refs(trans, updates * 2);
782                 if (err) /* Error code will also eval true */
783                         return err;
784         }
785
786         return should_end_transaction(trans);
787 }
788
789 static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
790
791 {
792         struct btrfs_fs_info *fs_info = trans->fs_info;
793
794         if (!trans->block_rsv) {
795                 ASSERT(!trans->bytes_reserved);
796                 return;
797         }
798
799         if (!trans->bytes_reserved)
800                 return;
801
802         ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
803         trace_btrfs_space_reservation(fs_info, "transaction",
804                                       trans->transid, trans->bytes_reserved, 0);
805         btrfs_block_rsv_release(fs_info, trans->block_rsv,
806                                 trans->bytes_reserved);
807         trans->bytes_reserved = 0;
808 }
809
810 static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
811                                    int throttle)
812 {
813         struct btrfs_fs_info *info = trans->fs_info;
814         struct btrfs_transaction *cur_trans = trans->transaction;
815         u64 transid = trans->transid;
816         unsigned long cur = trans->delayed_ref_updates;
817         int lock = (trans->type != TRANS_JOIN_NOLOCK);
818         int err = 0;
819         int must_run_delayed_refs = 0;
820
821         if (refcount_read(&trans->use_count) > 1) {
822                 refcount_dec(&trans->use_count);
823                 trans->block_rsv = trans->orig_rsv;
824                 return 0;
825         }
826
827         btrfs_trans_release_metadata(trans);
828         trans->block_rsv = NULL;
829
830         if (!list_empty(&trans->new_bgs))
831                 btrfs_create_pending_block_groups(trans);
832
833         trans->delayed_ref_updates = 0;
834         if (!trans->sync) {
835                 must_run_delayed_refs =
836                         btrfs_should_throttle_delayed_refs(trans);
837                 cur = max_t(unsigned long, cur, 32);
838
839                 /*
840                  * don't make the caller wait if they are from a NOLOCK
841                  * or ATTACH transaction, it will deadlock with commit
842                  */
843                 if (must_run_delayed_refs == 1 &&
844                     (trans->type & (__TRANS_JOIN_NOLOCK | __TRANS_ATTACH)))
845                         must_run_delayed_refs = 2;
846         }
847
848         btrfs_trans_release_metadata(trans);
849         trans->block_rsv = NULL;
850
851         if (!list_empty(&trans->new_bgs))
852                 btrfs_create_pending_block_groups(trans);
853
854         btrfs_trans_release_chunk_metadata(trans);
855
856         if (lock && should_end_transaction(trans) &&
857             READ_ONCE(cur_trans->state) == TRANS_STATE_RUNNING) {
858                 spin_lock(&info->trans_lock);
859                 if (cur_trans->state == TRANS_STATE_RUNNING)
860                         cur_trans->state = TRANS_STATE_BLOCKED;
861                 spin_unlock(&info->trans_lock);
862         }
863
864         if (lock && READ_ONCE(cur_trans->state) == TRANS_STATE_BLOCKED) {
865                 if (throttle)
866                         return btrfs_commit_transaction(trans);
867                 else
868                         wake_up_process(info->transaction_kthread);
869         }
870
871         if (trans->type & __TRANS_FREEZABLE)
872                 sb_end_intwrite(info->sb);
873
874         WARN_ON(cur_trans != info->running_transaction);
875         WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
876         atomic_dec(&cur_trans->num_writers);
877         extwriter_counter_dec(cur_trans, trans->type);
878
879         cond_wake_up(&cur_trans->writer_wait);
880         btrfs_put_transaction(cur_trans);
881
882         if (current->journal_info == trans)
883                 current->journal_info = NULL;
884
885         if (throttle)
886                 btrfs_run_delayed_iputs(info);
887
888         if (trans->aborted ||
889             test_bit(BTRFS_FS_STATE_ERROR, &info->fs_state)) {
890                 wake_up_process(info->transaction_kthread);
891                 err = -EIO;
892         }
893
894         kmem_cache_free(btrfs_trans_handle_cachep, trans);
895         if (must_run_delayed_refs) {
896                 btrfs_async_run_delayed_refs(info, cur, transid,
897                                              must_run_delayed_refs == 1);
898         }
899         return err;
900 }
901
902 int btrfs_end_transaction(struct btrfs_trans_handle *trans)
903 {
904         return __btrfs_end_transaction(trans, 0);
905 }
906
907 int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
908 {
909         return __btrfs_end_transaction(trans, 1);
910 }
911
912 /*
913  * when btree blocks are allocated, they have some corresponding bits set for
914  * them in one of two extent_io trees.  This is used to make sure all of
915  * those extents are sent to disk but does not wait on them
916  */
917 int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
918                                struct extent_io_tree *dirty_pages, int mark)
919 {
920         int err = 0;
921         int werr = 0;
922         struct address_space *mapping = fs_info->btree_inode->i_mapping;
923         struct extent_state *cached_state = NULL;
924         u64 start = 0;
925         u64 end;
926
927         atomic_inc(&BTRFS_I(fs_info->btree_inode)->sync_writers);
928         while (!find_first_extent_bit(dirty_pages, start, &start, &end,
929                                       mark, &cached_state)) {
930                 bool wait_writeback = false;
931
932                 err = convert_extent_bit(dirty_pages, start, end,
933                                          EXTENT_NEED_WAIT,
934                                          mark, &cached_state);
935                 /*
936                  * convert_extent_bit can return -ENOMEM, which is most of the
937                  * time a temporary error. So when it happens, ignore the error
938                  * and wait for writeback of this range to finish - because we
939                  * failed to set the bit EXTENT_NEED_WAIT for the range, a call
940                  * to __btrfs_wait_marked_extents() would not know that
941                  * writeback for this range started and therefore wouldn't
942                  * wait for it to finish - we don't want to commit a
943                  * superblock that points to btree nodes/leafs for which
944                  * writeback hasn't finished yet (and without errors).
945                  * We cleanup any entries left in the io tree when committing
946                  * the transaction (through clear_btree_io_tree()).
947                  */
948                 if (err == -ENOMEM) {
949                         err = 0;
950                         wait_writeback = true;
951                 }
952                 if (!err)
953                         err = filemap_fdatawrite_range(mapping, start, end);
954                 if (err)
955                         werr = err;
956                 else if (wait_writeback)
957                         werr = filemap_fdatawait_range(mapping, start, end);
958                 free_extent_state(cached_state);
959                 cached_state = NULL;
960                 cond_resched();
961                 start = end + 1;
962         }
963         atomic_dec(&BTRFS_I(fs_info->btree_inode)->sync_writers);
964         return werr;
965 }
966
967 /*
968  * when btree blocks are allocated, they have some corresponding bits set for
969  * them in one of two extent_io trees.  This is used to make sure all of
970  * those extents are on disk for transaction or log commit.  We wait
971  * on all the pages and clear them from the dirty pages state tree
972  */
973 static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
974                                        struct extent_io_tree *dirty_pages)
975 {
976         int err = 0;
977         int werr = 0;
978         struct address_space *mapping = fs_info->btree_inode->i_mapping;
979         struct extent_state *cached_state = NULL;
980         u64 start = 0;
981         u64 end;
982
983         while (!find_first_extent_bit(dirty_pages, start, &start, &end,
984                                       EXTENT_NEED_WAIT, &cached_state)) {
985                 /*
986                  * Ignore -ENOMEM errors returned by clear_extent_bit().
987                  * When committing the transaction, we'll remove any entries
988                  * left in the io tree. For a log commit, we don't remove them
989                  * after committing the log because the tree can be accessed
990                  * concurrently - we do it only at transaction commit time when
991                  * it's safe to do it (through clear_btree_io_tree()).
992                  */
993                 err = clear_extent_bit(dirty_pages, start, end,
994                                        EXTENT_NEED_WAIT, 0, 0, &cached_state);
995                 if (err == -ENOMEM)
996                         err = 0;
997                 if (!err)
998                         err = filemap_fdatawait_range(mapping, start, end);
999                 if (err)
1000                         werr = err;
1001                 free_extent_state(cached_state);
1002                 cached_state = NULL;
1003                 cond_resched();
1004                 start = end + 1;
1005         }
1006         if (err)
1007                 werr = err;
1008         return werr;
1009 }
1010
1011 int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
1012                        struct extent_io_tree *dirty_pages)
1013 {
1014         bool errors = false;
1015         int err;
1016
1017         err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1018         if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1019                 errors = true;
1020
1021         if (errors && !err)
1022                 err = -EIO;
1023         return err;
1024 }
1025
1026 int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
1027 {
1028         struct btrfs_fs_info *fs_info = log_root->fs_info;
1029         struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
1030         bool errors = false;
1031         int err;
1032
1033         ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
1034
1035         err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1036         if ((mark & EXTENT_DIRTY) &&
1037             test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1038                 errors = true;
1039
1040         if ((mark & EXTENT_NEW) &&
1041             test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1042                 errors = true;
1043
1044         if (errors && !err)
1045                 err = -EIO;
1046         return err;
1047 }
1048
1049 /*
1050  * When btree blocks are allocated the corresponding extents are marked dirty.
1051  * This function ensures such extents are persisted on disk for transaction or
1052  * log commit.
1053  *
1054  * @trans: transaction whose dirty pages we'd like to write
1055  */
1056 static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1057 {
1058         int ret;
1059         int ret2;
1060         struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
1061         struct btrfs_fs_info *fs_info = trans->fs_info;
1062         struct blk_plug plug;
1063
1064         blk_start_plug(&plug);
1065         ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1066         blk_finish_plug(&plug);
1067         ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1068
1069         clear_btree_io_tree(&trans->transaction->dirty_pages);
1070
1071         if (ret)
1072                 return ret;
1073         else if (ret2)
1074                 return ret2;
1075         else
1076                 return 0;
1077 }
1078
1079 /*
1080  * this is used to update the root pointer in the tree of tree roots.
1081  *
1082  * But, in the case of the extent allocation tree, updating the root
1083  * pointer may allocate blocks which may change the root of the extent
1084  * allocation tree.
1085  *
1086  * So, this loops and repeats and makes sure the cowonly root didn't
1087  * change while the root pointer was being updated in the metadata.
1088  */
1089 static int update_cowonly_root(struct btrfs_trans_handle *trans,
1090                                struct btrfs_root *root)
1091 {
1092         int ret;
1093         u64 old_root_bytenr;
1094         u64 old_root_used;
1095         struct btrfs_fs_info *fs_info = root->fs_info;
1096         struct btrfs_root *tree_root = fs_info->tree_root;
1097
1098         old_root_used = btrfs_root_used(&root->root_item);
1099
1100         while (1) {
1101                 old_root_bytenr = btrfs_root_bytenr(&root->root_item);
1102                 if (old_root_bytenr == root->node->start &&
1103                     old_root_used == btrfs_root_used(&root->root_item))
1104                         break;
1105
1106                 btrfs_set_root_node(&root->root_item, root->node);
1107                 ret = btrfs_update_root(trans, tree_root,
1108                                         &root->root_key,
1109                                         &root->root_item);
1110                 if (ret)
1111                         return ret;
1112
1113                 old_root_used = btrfs_root_used(&root->root_item);
1114         }
1115
1116         return 0;
1117 }
1118
1119 /*
1120  * update all the cowonly tree roots on disk
1121  *
1122  * The error handling in this function may not be obvious. Any of the
1123  * failures will cause the file system to go offline. We still need
1124  * to clean up the delayed refs.
1125  */
1126 static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
1127 {
1128         struct btrfs_fs_info *fs_info = trans->fs_info;
1129         struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
1130         struct list_head *io_bgs = &trans->transaction->io_bgs;
1131         struct list_head *next;
1132         struct extent_buffer *eb;
1133         int ret;
1134
1135         eb = btrfs_lock_root_node(fs_info->tree_root);
1136         ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
1137                               0, &eb);
1138         btrfs_tree_unlock(eb);
1139         free_extent_buffer(eb);
1140
1141         if (ret)
1142                 return ret;
1143
1144         ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1145         if (ret)
1146                 return ret;
1147
1148         ret = btrfs_run_dev_stats(trans, fs_info);
1149         if (ret)
1150                 return ret;
1151         ret = btrfs_run_dev_replace(trans, fs_info);
1152         if (ret)
1153                 return ret;
1154         ret = btrfs_run_qgroups(trans);
1155         if (ret)
1156                 return ret;
1157
1158         ret = btrfs_setup_space_cache(trans, fs_info);
1159         if (ret)
1160                 return ret;
1161
1162         /* run_qgroups might have added some more refs */
1163         ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1164         if (ret)
1165                 return ret;
1166 again:
1167         while (!list_empty(&fs_info->dirty_cowonly_roots)) {
1168                 struct btrfs_root *root;
1169                 next = fs_info->dirty_cowonly_roots.next;
1170                 list_del_init(next);
1171                 root = list_entry(next, struct btrfs_root, dirty_list);
1172                 clear_bit(BTRFS_ROOT_DIRTY, &root->state);
1173
1174                 if (root != fs_info->extent_root)
1175                         list_add_tail(&root->dirty_list,
1176                                       &trans->transaction->switch_commits);
1177                 ret = update_cowonly_root(trans, root);
1178                 if (ret)
1179                         return ret;
1180                 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1181                 if (ret)
1182                         return ret;
1183         }
1184
1185         while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
1186                 ret = btrfs_write_dirty_block_groups(trans, fs_info);
1187                 if (ret)
1188                         return ret;
1189                 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1190                 if (ret)
1191                         return ret;
1192         }
1193
1194         if (!list_empty(&fs_info->dirty_cowonly_roots))
1195                 goto again;
1196
1197         list_add_tail(&fs_info->extent_root->dirty_list,
1198                       &trans->transaction->switch_commits);
1199
1200         /* Update dev-replace pointer once everything is committed */
1201         fs_info->dev_replace.committed_cursor_left =
1202                 fs_info->dev_replace.cursor_left_last_write_of_item;
1203
1204         return 0;
1205 }
1206
1207 /*
1208  * dead roots are old snapshots that need to be deleted.  This allocates
1209  * a dirty root struct and adds it into the list of dead roots that need to
1210  * be deleted
1211  */
1212 void btrfs_add_dead_root(struct btrfs_root *root)
1213 {
1214         struct btrfs_fs_info *fs_info = root->fs_info;
1215
1216         spin_lock(&fs_info->trans_lock);
1217         if (list_empty(&root->root_list))
1218                 list_add_tail(&root->root_list, &fs_info->dead_roots);
1219         spin_unlock(&fs_info->trans_lock);
1220 }
1221
1222 /*
1223  * update all the cowonly tree roots on disk
1224  */
1225 static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
1226 {
1227         struct btrfs_fs_info *fs_info = trans->fs_info;
1228         struct btrfs_root *gang[8];
1229         int i;
1230         int ret;
1231         int err = 0;
1232
1233         spin_lock(&fs_info->fs_roots_radix_lock);
1234         while (1) {
1235                 ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
1236                                                  (void **)gang, 0,
1237                                                  ARRAY_SIZE(gang),
1238                                                  BTRFS_ROOT_TRANS_TAG);
1239                 if (ret == 0)
1240                         break;
1241                 for (i = 0; i < ret; i++) {
1242                         struct btrfs_root *root = gang[i];
1243                         radix_tree_tag_clear(&fs_info->fs_roots_radix,
1244                                         (unsigned long)root->root_key.objectid,
1245                                         BTRFS_ROOT_TRANS_TAG);
1246                         spin_unlock(&fs_info->fs_roots_radix_lock);
1247
1248                         btrfs_free_log(trans, root);
1249                         btrfs_update_reloc_root(trans, root);
1250
1251                         btrfs_save_ino_cache(root, trans);
1252
1253                         /* see comments in should_cow_block() */
1254                         clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1255                         smp_mb__after_atomic();
1256
1257                         if (root->commit_root != root->node) {
1258                                 list_add_tail(&root->dirty_list,
1259                                         &trans->transaction->switch_commits);
1260                                 btrfs_set_root_node(&root->root_item,
1261                                                     root->node);
1262                         }
1263
1264                         err = btrfs_update_root(trans, fs_info->tree_root,
1265                                                 &root->root_key,
1266                                                 &root->root_item);
1267                         spin_lock(&fs_info->fs_roots_radix_lock);
1268                         if (err)
1269                                 break;
1270                         btrfs_qgroup_free_meta_all_pertrans(root);
1271                 }
1272         }
1273         spin_unlock(&fs_info->fs_roots_radix_lock);
1274         return err;
1275 }
1276
1277 /*
1278  * defrag a given btree.
1279  * Every leaf in the btree is read and defragged.
1280  */
1281 int btrfs_defrag_root(struct btrfs_root *root)
1282 {
1283         struct btrfs_fs_info *info = root->fs_info;
1284         struct btrfs_trans_handle *trans;
1285         int ret;
1286
1287         if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
1288                 return 0;
1289
1290         while (1) {
1291                 trans = btrfs_start_transaction(root, 0);
1292                 if (IS_ERR(trans))
1293                         return PTR_ERR(trans);
1294
1295                 ret = btrfs_defrag_leaves(trans, root);
1296
1297                 btrfs_end_transaction(trans);
1298                 btrfs_btree_balance_dirty(info);
1299                 cond_resched();
1300
1301                 if (btrfs_fs_closing(info) || ret != -EAGAIN)
1302                         break;
1303
1304                 if (btrfs_defrag_cancelled(info)) {
1305                         btrfs_debug(info, "defrag_root cancelled");
1306                         ret = -EAGAIN;
1307                         break;
1308                 }
1309         }
1310         clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
1311         return ret;
1312 }
1313
1314 /*
1315  * Do all special snapshot related qgroup dirty hack.
1316  *
1317  * Will do all needed qgroup inherit and dirty hack like switch commit
1318  * roots inside one transaction and write all btree into disk, to make
1319  * qgroup works.
1320  */
1321 static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
1322                                    struct btrfs_root *src,
1323                                    struct btrfs_root *parent,
1324                                    struct btrfs_qgroup_inherit *inherit,
1325                                    u64 dst_objectid)
1326 {
1327         struct btrfs_fs_info *fs_info = src->fs_info;
1328         int ret;
1329
1330         /*
1331          * Save some performance in the case that qgroups are not
1332          * enabled. If this check races with the ioctl, rescan will
1333          * kick in anyway.
1334          */
1335         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1336                 return 0;
1337
1338         /*
1339          * Ensure dirty @src will be commited.  Or, after comming
1340          * commit_fs_roots() and switch_commit_roots(), any dirty but not
1341          * recorded root will never be updated again, causing an outdated root
1342          * item.
1343          */
1344         record_root_in_trans(trans, src, 1);
1345
1346         /*
1347          * We are going to commit transaction, see btrfs_commit_transaction()
1348          * comment for reason locking tree_log_mutex
1349          */
1350         mutex_lock(&fs_info->tree_log_mutex);
1351
1352         ret = commit_fs_roots(trans);
1353         if (ret)
1354                 goto out;
1355         ret = btrfs_qgroup_account_extents(trans);
1356         if (ret < 0)
1357                 goto out;
1358
1359         /* Now qgroup are all updated, we can inherit it to new qgroups */
1360         ret = btrfs_qgroup_inherit(trans, src->root_key.objectid, dst_objectid,
1361                                    inherit);
1362         if (ret < 0)
1363                 goto out;
1364
1365         /*
1366          * Now we do a simplified commit transaction, which will:
1367          * 1) commit all subvolume and extent tree
1368          *    To ensure all subvolume and extent tree have a valid
1369          *    commit_root to accounting later insert_dir_item()
1370          * 2) write all btree blocks onto disk
1371          *    This is to make sure later btree modification will be cowed
1372          *    Or commit_root can be populated and cause wrong qgroup numbers
1373          * In this simplified commit, we don't really care about other trees
1374          * like chunk and root tree, as they won't affect qgroup.
1375          * And we don't write super to avoid half committed status.
1376          */
1377         ret = commit_cowonly_roots(trans);
1378         if (ret)
1379                 goto out;
1380         switch_commit_roots(trans->transaction);
1381         ret = btrfs_write_and_wait_transaction(trans);
1382         if (ret)
1383                 btrfs_handle_fs_error(fs_info, ret,
1384                         "Error while writing out transaction for qgroup");
1385
1386 out:
1387         mutex_unlock(&fs_info->tree_log_mutex);
1388
1389         /*
1390          * Force parent root to be updated, as we recorded it before so its
1391          * last_trans == cur_transid.
1392          * Or it won't be committed again onto disk after later
1393          * insert_dir_item()
1394          */
1395         if (!ret)
1396                 record_root_in_trans(trans, parent, 1);
1397         return ret;
1398 }
1399
1400 /*
1401  * new snapshots need to be created at a very specific time in the
1402  * transaction commit.  This does the actual creation.
1403  *
1404  * Note:
1405  * If the error which may affect the commitment of the current transaction
1406  * happens, we should return the error number. If the error which just affect
1407  * the creation of the pending snapshots, just return 0.
1408  */
1409 static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
1410                                    struct btrfs_pending_snapshot *pending)
1411 {
1412
1413         struct btrfs_fs_info *fs_info = trans->fs_info;
1414         struct btrfs_key key;
1415         struct btrfs_root_item *new_root_item;
1416         struct btrfs_root *tree_root = fs_info->tree_root;
1417         struct btrfs_root *root = pending->root;
1418         struct btrfs_root *parent_root;
1419         struct btrfs_block_rsv *rsv;
1420         struct inode *parent_inode;
1421         struct btrfs_path *path;
1422         struct btrfs_dir_item *dir_item;
1423         struct dentry *dentry;
1424         struct extent_buffer *tmp;
1425         struct extent_buffer *old;
1426         struct timespec64 cur_time;
1427         int ret = 0;
1428         u64 to_reserve = 0;
1429         u64 index = 0;
1430         u64 objectid;
1431         u64 root_flags;
1432         uuid_le new_uuid;
1433
1434         ASSERT(pending->path);
1435         path = pending->path;
1436
1437         ASSERT(pending->root_item);
1438         new_root_item = pending->root_item;
1439
1440         pending->error = btrfs_find_free_objectid(tree_root, &objectid);
1441         if (pending->error)
1442                 goto no_free_objectid;
1443
1444         /*
1445          * Make qgroup to skip current new snapshot's qgroupid, as it is
1446          * accounted by later btrfs_qgroup_inherit().
1447          */
1448         btrfs_set_skip_qgroup(trans, objectid);
1449
1450         btrfs_reloc_pre_snapshot(pending, &to_reserve);
1451
1452         if (to_reserve > 0) {
1453                 pending->error = btrfs_block_rsv_add(root,
1454                                                      &pending->block_rsv,
1455                                                      to_reserve,
1456                                                      BTRFS_RESERVE_NO_FLUSH);
1457                 if (pending->error)
1458                         goto clear_skip_qgroup;
1459         }
1460
1461         key.objectid = objectid;
1462         key.offset = (u64)-1;
1463         key.type = BTRFS_ROOT_ITEM_KEY;
1464
1465         rsv = trans->block_rsv;
1466         trans->block_rsv = &pending->block_rsv;
1467         trans->bytes_reserved = trans->block_rsv->reserved;
1468         trace_btrfs_space_reservation(fs_info, "transaction",
1469                                       trans->transid,
1470                                       trans->bytes_reserved, 1);
1471         dentry = pending->dentry;
1472         parent_inode = pending->dir;
1473         parent_root = BTRFS_I(parent_inode)->root;
1474         record_root_in_trans(trans, parent_root, 0);
1475
1476         cur_time = current_time(parent_inode);
1477
1478         /*
1479          * insert the directory item
1480          */
1481         ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
1482         BUG_ON(ret); /* -ENOMEM */
1483
1484         /* check if there is a file/dir which has the same name. */
1485         dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
1486                                          btrfs_ino(BTRFS_I(parent_inode)),
1487                                          dentry->d_name.name,
1488                                          dentry->d_name.len, 0);
1489         if (dir_item != NULL && !IS_ERR(dir_item)) {
1490                 pending->error = -EEXIST;
1491                 goto dir_item_existed;
1492         } else if (IS_ERR(dir_item)) {
1493                 ret = PTR_ERR(dir_item);
1494                 btrfs_abort_transaction(trans, ret);
1495                 goto fail;
1496         }
1497         btrfs_release_path(path);
1498
1499         /*
1500          * pull in the delayed directory update
1501          * and the delayed inode item
1502          * otherwise we corrupt the FS during
1503          * snapshot
1504          */
1505         ret = btrfs_run_delayed_items(trans);
1506         if (ret) {      /* Transaction aborted */
1507                 btrfs_abort_transaction(trans, ret);
1508                 goto fail;
1509         }
1510
1511         record_root_in_trans(trans, root, 0);
1512         btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
1513         memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
1514         btrfs_check_and_init_root_item(new_root_item);
1515
1516         root_flags = btrfs_root_flags(new_root_item);
1517         if (pending->readonly)
1518                 root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1519         else
1520                 root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1521         btrfs_set_root_flags(new_root_item, root_flags);
1522
1523         btrfs_set_root_generation_v2(new_root_item,
1524                         trans->transid);
1525         uuid_le_gen(&new_uuid);
1526         memcpy(new_root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
1527         memcpy(new_root_item->parent_uuid, root->root_item.uuid,
1528                         BTRFS_UUID_SIZE);
1529         if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
1530                 memset(new_root_item->received_uuid, 0,
1531                        sizeof(new_root_item->received_uuid));
1532                 memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
1533                 memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
1534                 btrfs_set_root_stransid(new_root_item, 0);
1535                 btrfs_set_root_rtransid(new_root_item, 0);
1536         }
1537         btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
1538         btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
1539         btrfs_set_root_otransid(new_root_item, trans->transid);
1540
1541         old = btrfs_lock_root_node(root);
1542         ret = btrfs_cow_block(trans, root, old, NULL, 0, &old);
1543         if (ret) {
1544                 btrfs_tree_unlock(old);
1545                 free_extent_buffer(old);
1546                 btrfs_abort_transaction(trans, ret);
1547                 goto fail;
1548         }
1549
1550         btrfs_set_lock_blocking(old);
1551
1552         ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
1553         /* clean up in any case */
1554         btrfs_tree_unlock(old);
1555         free_extent_buffer(old);
1556         if (ret) {
1557                 btrfs_abort_transaction(trans, ret);
1558                 goto fail;
1559         }
1560         /* see comments in should_cow_block() */
1561         set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1562         smp_wmb();
1563
1564         btrfs_set_root_node(new_root_item, tmp);
1565         /* record when the snapshot was created in key.offset */
1566         key.offset = trans->transid;
1567         ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1568         btrfs_tree_unlock(tmp);
1569         free_extent_buffer(tmp);
1570         if (ret) {
1571                 btrfs_abort_transaction(trans, ret);
1572                 goto fail;
1573         }
1574
1575         /*
1576          * insert root back/forward references
1577          */
1578         ret = btrfs_add_root_ref(trans, objectid,
1579                                  parent_root->root_key.objectid,
1580                                  btrfs_ino(BTRFS_I(parent_inode)), index,
1581                                  dentry->d_name.name, dentry->d_name.len);
1582         if (ret) {
1583                 btrfs_abort_transaction(trans, ret);
1584                 goto fail;
1585         }
1586
1587         key.offset = (u64)-1;
1588         pending->snap = btrfs_read_fs_root_no_name(fs_info, &key);
1589         if (IS_ERR(pending->snap)) {
1590                 ret = PTR_ERR(pending->snap);
1591                 btrfs_abort_transaction(trans, ret);
1592                 goto fail;
1593         }
1594
1595         ret = btrfs_reloc_post_snapshot(trans, pending);
1596         if (ret) {
1597                 btrfs_abort_transaction(trans, ret);
1598                 goto fail;
1599         }
1600
1601         ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1602         if (ret) {
1603                 btrfs_abort_transaction(trans, ret);
1604                 goto fail;
1605         }
1606
1607         /*
1608          * Do special qgroup accounting for snapshot, as we do some qgroup
1609          * snapshot hack to do fast snapshot.
1610          * To co-operate with that hack, we do hack again.
1611          * Or snapshot will be greatly slowed down by a subtree qgroup rescan
1612          */
1613         ret = qgroup_account_snapshot(trans, root, parent_root,
1614                                       pending->inherit, objectid);
1615         if (ret < 0)
1616                 goto fail;
1617
1618         ret = btrfs_insert_dir_item(trans, dentry->d_name.name,
1619                                     dentry->d_name.len, BTRFS_I(parent_inode),
1620                                     &key, BTRFS_FT_DIR, index);
1621         /* We have check then name at the beginning, so it is impossible. */
1622         BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
1623         if (ret) {
1624                 btrfs_abort_transaction(trans, ret);
1625                 goto fail;
1626         }
1627
1628         btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
1629                                          dentry->d_name.len * 2);
1630         parent_inode->i_mtime = parent_inode->i_ctime =
1631                 current_time(parent_inode);
1632         ret = btrfs_update_inode_fallback(trans, parent_root, parent_inode);
1633         if (ret) {
1634                 btrfs_abort_transaction(trans, ret);
1635                 goto fail;
1636         }
1637         ret = btrfs_uuid_tree_add(trans, new_uuid.b, BTRFS_UUID_KEY_SUBVOL,
1638                                   objectid);
1639         if (ret) {
1640                 btrfs_abort_transaction(trans, ret);
1641                 goto fail;
1642         }
1643         if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1644                 ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1645                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1646                                           objectid);
1647                 if (ret && ret != -EEXIST) {
1648                         btrfs_abort_transaction(trans, ret);
1649                         goto fail;
1650                 }
1651         }
1652
1653         ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1654         if (ret) {
1655                 btrfs_abort_transaction(trans, ret);
1656                 goto fail;
1657         }
1658
1659 fail:
1660         pending->error = ret;
1661 dir_item_existed:
1662         trans->block_rsv = rsv;
1663         trans->bytes_reserved = 0;
1664 clear_skip_qgroup:
1665         btrfs_clear_skip_qgroup(trans);
1666 no_free_objectid:
1667         kfree(new_root_item);
1668         pending->root_item = NULL;
1669         btrfs_free_path(path);
1670         pending->path = NULL;
1671
1672         return ret;
1673 }
1674
1675 /*
1676  * create all the snapshots we've scheduled for creation
1677  */
1678 static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
1679 {
1680         struct btrfs_pending_snapshot *pending, *next;
1681         struct list_head *head = &trans->transaction->pending_snapshots;
1682         int ret = 0;
1683
1684         list_for_each_entry_safe(pending, next, head, list) {
1685                 list_del(&pending->list);
1686                 ret = create_pending_snapshot(trans, pending);
1687                 if (ret)
1688                         break;
1689         }
1690         return ret;
1691 }
1692
1693 static void update_super_roots(struct btrfs_fs_info *fs_info)
1694 {
1695         struct btrfs_root_item *root_item;
1696         struct btrfs_super_block *super;
1697
1698         super = fs_info->super_copy;
1699
1700         root_item = &fs_info->chunk_root->root_item;
1701         super->chunk_root = root_item->bytenr;
1702         super->chunk_root_generation = root_item->generation;
1703         super->chunk_root_level = root_item->level;
1704
1705         root_item = &fs_info->tree_root->root_item;
1706         super->root = root_item->bytenr;
1707         super->generation = root_item->generation;
1708         super->root_level = root_item->level;
1709         if (btrfs_test_opt(fs_info, SPACE_CACHE))
1710                 super->cache_generation = root_item->generation;
1711         if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1712                 super->uuid_tree_generation = root_item->generation;
1713 }
1714
1715 int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1716 {
1717         struct btrfs_transaction *trans;
1718         int ret = 0;
1719
1720         spin_lock(&info->trans_lock);
1721         trans = info->running_transaction;
1722         if (trans)
1723                 ret = (trans->state >= TRANS_STATE_COMMIT_START);
1724         spin_unlock(&info->trans_lock);
1725         return ret;
1726 }
1727
1728 int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1729 {
1730         struct btrfs_transaction *trans;
1731         int ret = 0;
1732
1733         spin_lock(&info->trans_lock);
1734         trans = info->running_transaction;
1735         if (trans)
1736                 ret = is_transaction_blocked(trans);
1737         spin_unlock(&info->trans_lock);
1738         return ret;
1739 }
1740
1741 /*
1742  * wait for the current transaction commit to start and block subsequent
1743  * transaction joins
1744  */
1745 static void wait_current_trans_commit_start(struct btrfs_fs_info *fs_info,
1746                                             struct btrfs_transaction *trans)
1747 {
1748         wait_event(fs_info->transaction_blocked_wait,
1749                    trans->state >= TRANS_STATE_COMMIT_START || trans->aborted);
1750 }
1751
1752 /*
1753  * wait for the current transaction to start and then become unblocked.
1754  * caller holds ref.
1755  */
1756 static void wait_current_trans_commit_start_and_unblock(
1757                                         struct btrfs_fs_info *fs_info,
1758                                         struct btrfs_transaction *trans)
1759 {
1760         wait_event(fs_info->transaction_wait,
1761                    trans->state >= TRANS_STATE_UNBLOCKED || trans->aborted);
1762 }
1763
1764 /*
1765  * commit transactions asynchronously. once btrfs_commit_transaction_async
1766  * returns, any subsequent transaction will not be allowed to join.
1767  */
1768 struct btrfs_async_commit {
1769         struct btrfs_trans_handle *newtrans;
1770         struct work_struct work;
1771 };
1772
1773 static void do_async_commit(struct work_struct *work)
1774 {
1775         struct btrfs_async_commit *ac =
1776                 container_of(work, struct btrfs_async_commit, work);
1777
1778         /*
1779          * We've got freeze protection passed with the transaction.
1780          * Tell lockdep about it.
1781          */
1782         if (ac->newtrans->type & __TRANS_FREEZABLE)
1783                 __sb_writers_acquired(ac->newtrans->fs_info->sb, SB_FREEZE_FS);
1784
1785         current->journal_info = ac->newtrans;
1786
1787         btrfs_commit_transaction(ac->newtrans);
1788         kfree(ac);
1789 }
1790
1791 int btrfs_commit_transaction_async(struct btrfs_trans_handle *trans,
1792                                    int wait_for_unblock)
1793 {
1794         struct btrfs_fs_info *fs_info = trans->fs_info;
1795         struct btrfs_async_commit *ac;
1796         struct btrfs_transaction *cur_trans;
1797
1798         ac = kmalloc(sizeof(*ac), GFP_NOFS);
1799         if (!ac)
1800                 return -ENOMEM;
1801
1802         INIT_WORK(&ac->work, do_async_commit);
1803         ac->newtrans = btrfs_join_transaction(trans->root);
1804         if (IS_ERR(ac->newtrans)) {
1805                 int err = PTR_ERR(ac->newtrans);
1806                 kfree(ac);
1807                 return err;
1808         }
1809
1810         /* take transaction reference */
1811         cur_trans = trans->transaction;
1812         refcount_inc(&cur_trans->use_count);
1813
1814         btrfs_end_transaction(trans);
1815
1816         /*
1817          * Tell lockdep we've released the freeze rwsem, since the
1818          * async commit thread will be the one to unlock it.
1819          */
1820         if (ac->newtrans->type & __TRANS_FREEZABLE)
1821                 __sb_writers_release(fs_info->sb, SB_FREEZE_FS);
1822
1823         schedule_work(&ac->work);
1824
1825         /* wait for transaction to start and unblock */
1826         if (wait_for_unblock)
1827                 wait_current_trans_commit_start_and_unblock(fs_info, cur_trans);
1828         else
1829                 wait_current_trans_commit_start(fs_info, cur_trans);
1830
1831         if (current->journal_info == trans)
1832                 current->journal_info = NULL;
1833
1834         btrfs_put_transaction(cur_trans);
1835         return 0;
1836 }
1837
1838
1839 static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
1840 {
1841         struct btrfs_fs_info *fs_info = trans->fs_info;
1842         struct btrfs_transaction *cur_trans = trans->transaction;
1843         DEFINE_WAIT(wait);
1844
1845         WARN_ON(refcount_read(&trans->use_count) > 1);
1846
1847         btrfs_abort_transaction(trans, err);
1848
1849         spin_lock(&fs_info->trans_lock);
1850
1851         /*
1852          * If the transaction is removed from the list, it means this
1853          * transaction has been committed successfully, so it is impossible
1854          * to call the cleanup function.
1855          */
1856         BUG_ON(list_empty(&cur_trans->list));
1857
1858         list_del_init(&cur_trans->list);
1859         if (cur_trans == fs_info->running_transaction) {
1860                 cur_trans->state = TRANS_STATE_COMMIT_DOING;
1861                 spin_unlock(&fs_info->trans_lock);
1862                 wait_event(cur_trans->writer_wait,
1863                            atomic_read(&cur_trans->num_writers) == 1);
1864
1865                 spin_lock(&fs_info->trans_lock);
1866         }
1867         spin_unlock(&fs_info->trans_lock);
1868
1869         btrfs_cleanup_one_transaction(trans->transaction, fs_info);
1870
1871         spin_lock(&fs_info->trans_lock);
1872         if (cur_trans == fs_info->running_transaction)
1873                 fs_info->running_transaction = NULL;
1874         spin_unlock(&fs_info->trans_lock);
1875
1876         if (trans->type & __TRANS_FREEZABLE)
1877                 sb_end_intwrite(fs_info->sb);
1878         btrfs_put_transaction(cur_trans);
1879         btrfs_put_transaction(cur_trans);
1880
1881         trace_btrfs_transaction_commit(trans->root);
1882
1883         if (current->journal_info == trans)
1884                 current->journal_info = NULL;
1885         btrfs_scrub_cancel(fs_info);
1886
1887         kmem_cache_free(btrfs_trans_handle_cachep, trans);
1888 }
1889
1890 static inline int btrfs_start_delalloc_flush(struct btrfs_fs_info *fs_info)
1891 {
1892         /*
1893          * We use writeback_inodes_sb here because if we used
1894          * btrfs_start_delalloc_roots we would deadlock with fs freeze.
1895          * Currently are holding the fs freeze lock, if we do an async flush
1896          * we'll do btrfs_join_transaction() and deadlock because we need to
1897          * wait for the fs freeze lock.  Using the direct flushing we benefit
1898          * from already being in a transaction and our join_transaction doesn't
1899          * have to re-take the fs freeze lock.
1900          */
1901         if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
1902                 writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
1903         return 0;
1904 }
1905
1906 static inline void btrfs_wait_delalloc_flush(struct btrfs_fs_info *fs_info)
1907 {
1908         if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
1909                 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
1910 }
1911
1912 int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
1913 {
1914         struct btrfs_fs_info *fs_info = trans->fs_info;
1915         struct btrfs_transaction *cur_trans = trans->transaction;
1916         struct btrfs_transaction *prev_trans = NULL;
1917         int ret;
1918
1919         /* Stop the commit early if ->aborted is set */
1920         if (unlikely(READ_ONCE(cur_trans->aborted))) {
1921                 ret = cur_trans->aborted;
1922                 btrfs_end_transaction(trans);
1923                 return ret;
1924         }
1925
1926         btrfs_trans_release_metadata(trans);
1927         trans->block_rsv = NULL;
1928
1929         /* make a pass through all the delayed refs we have so far
1930          * any runnings procs may add more while we are here
1931          */
1932         ret = btrfs_run_delayed_refs(trans, 0);
1933         if (ret) {
1934                 btrfs_end_transaction(trans);
1935                 return ret;
1936         }
1937
1938         cur_trans = trans->transaction;
1939
1940         /*
1941          * set the flushing flag so procs in this transaction have to
1942          * start sending their work down.
1943          */
1944         cur_trans->delayed_refs.flushing = 1;
1945         smp_wmb();
1946
1947         if (!list_empty(&trans->new_bgs))
1948                 btrfs_create_pending_block_groups(trans);
1949
1950         ret = btrfs_run_delayed_refs(trans, 0);
1951         if (ret) {
1952                 btrfs_end_transaction(trans);
1953                 return ret;
1954         }
1955
1956         if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
1957                 int run_it = 0;
1958
1959                 /* this mutex is also taken before trying to set
1960                  * block groups readonly.  We need to make sure
1961                  * that nobody has set a block group readonly
1962                  * after a extents from that block group have been
1963                  * allocated for cache files.  btrfs_set_block_group_ro
1964                  * will wait for the transaction to commit if it
1965                  * finds BTRFS_TRANS_DIRTY_BG_RUN set.
1966                  *
1967                  * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
1968                  * only one process starts all the block group IO.  It wouldn't
1969                  * hurt to have more than one go through, but there's no
1970                  * real advantage to it either.
1971                  */
1972                 mutex_lock(&fs_info->ro_block_group_mutex);
1973                 if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
1974                                       &cur_trans->flags))
1975                         run_it = 1;
1976                 mutex_unlock(&fs_info->ro_block_group_mutex);
1977
1978                 if (run_it) {
1979                         ret = btrfs_start_dirty_block_groups(trans);
1980                         if (ret) {
1981                                 btrfs_end_transaction(trans);
1982                                 return ret;
1983                         }
1984                 }
1985         }
1986
1987         spin_lock(&fs_info->trans_lock);
1988         if (cur_trans->state >= TRANS_STATE_COMMIT_START) {
1989                 spin_unlock(&fs_info->trans_lock);
1990                 refcount_inc(&cur_trans->use_count);
1991                 ret = btrfs_end_transaction(trans);
1992
1993                 wait_for_commit(cur_trans);
1994
1995                 if (unlikely(cur_trans->aborted))
1996                         ret = cur_trans->aborted;
1997
1998                 btrfs_put_transaction(cur_trans);
1999
2000                 return ret;
2001         }
2002
2003         cur_trans->state = TRANS_STATE_COMMIT_START;
2004         wake_up(&fs_info->transaction_blocked_wait);
2005
2006         if (cur_trans->list.prev != &fs_info->trans_list) {
2007                 prev_trans = list_entry(cur_trans->list.prev,
2008                                         struct btrfs_transaction, list);
2009                 if (prev_trans->state != TRANS_STATE_COMPLETED) {
2010                         refcount_inc(&prev_trans->use_count);
2011                         spin_unlock(&fs_info->trans_lock);
2012
2013                         wait_for_commit(prev_trans);
2014                         ret = prev_trans->aborted;
2015
2016                         btrfs_put_transaction(prev_trans);
2017                         if (ret)
2018                                 goto cleanup_transaction;
2019                 } else {
2020                         spin_unlock(&fs_info->trans_lock);
2021                 }
2022         } else {
2023                 spin_unlock(&fs_info->trans_lock);
2024         }
2025
2026         extwriter_counter_dec(cur_trans, trans->type);
2027
2028         ret = btrfs_start_delalloc_flush(fs_info);
2029         if (ret)
2030                 goto cleanup_transaction;
2031
2032         ret = btrfs_run_delayed_items(trans);
2033         if (ret)
2034                 goto cleanup_transaction;
2035
2036         wait_event(cur_trans->writer_wait,
2037                    extwriter_counter_read(cur_trans) == 0);
2038
2039         /* some pending stuffs might be added after the previous flush. */
2040         ret = btrfs_run_delayed_items(trans);
2041         if (ret)
2042                 goto cleanup_transaction;
2043
2044         btrfs_wait_delalloc_flush(fs_info);
2045
2046         btrfs_scrub_pause(fs_info);
2047         /*
2048          * Ok now we need to make sure to block out any other joins while we
2049          * commit the transaction.  We could have started a join before setting
2050          * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2051          */
2052         spin_lock(&fs_info->trans_lock);
2053         cur_trans->state = TRANS_STATE_COMMIT_DOING;
2054         spin_unlock(&fs_info->trans_lock);
2055         wait_event(cur_trans->writer_wait,
2056                    atomic_read(&cur_trans->num_writers) == 1);
2057
2058         /* ->aborted might be set after the previous check, so check it */
2059         if (unlikely(READ_ONCE(cur_trans->aborted))) {
2060                 ret = cur_trans->aborted;
2061                 goto scrub_continue;
2062         }
2063         /*
2064          * the reloc mutex makes sure that we stop
2065          * the balancing code from coming in and moving
2066          * extents around in the middle of the commit
2067          */
2068         mutex_lock(&fs_info->reloc_mutex);
2069
2070         /*
2071          * We needn't worry about the delayed items because we will
2072          * deal with them in create_pending_snapshot(), which is the
2073          * core function of the snapshot creation.
2074          */
2075         ret = create_pending_snapshots(trans);
2076         if (ret) {
2077                 mutex_unlock(&fs_info->reloc_mutex);
2078                 goto scrub_continue;
2079         }
2080
2081         /*
2082          * We insert the dir indexes of the snapshots and update the inode
2083          * of the snapshots' parents after the snapshot creation, so there
2084          * are some delayed items which are not dealt with. Now deal with
2085          * them.
2086          *
2087          * We needn't worry that this operation will corrupt the snapshots,
2088          * because all the tree which are snapshoted will be forced to COW
2089          * the nodes and leaves.
2090          */
2091         ret = btrfs_run_delayed_items(trans);
2092         if (ret) {
2093                 mutex_unlock(&fs_info->reloc_mutex);
2094                 goto scrub_continue;
2095         }
2096
2097         ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2098         if (ret) {
2099                 mutex_unlock(&fs_info->reloc_mutex);
2100                 goto scrub_continue;
2101         }
2102
2103         /*
2104          * make sure none of the code above managed to slip in a
2105          * delayed item
2106          */
2107         btrfs_assert_delayed_root_empty(fs_info);
2108
2109         WARN_ON(cur_trans != trans->transaction);
2110
2111         /* btrfs_commit_tree_roots is responsible for getting the
2112          * various roots consistent with each other.  Every pointer
2113          * in the tree of tree roots has to point to the most up to date
2114          * root for every subvolume and other tree.  So, we have to keep
2115          * the tree logging code from jumping in and changing any
2116          * of the trees.
2117          *
2118          * At this point in the commit, there can't be any tree-log
2119          * writers, but a little lower down we drop the trans mutex
2120          * and let new people in.  By holding the tree_log_mutex
2121          * from now until after the super is written, we avoid races
2122          * with the tree-log code.
2123          */
2124         mutex_lock(&fs_info->tree_log_mutex);
2125
2126         ret = commit_fs_roots(trans);
2127         if (ret) {
2128                 mutex_unlock(&fs_info->tree_log_mutex);
2129                 mutex_unlock(&fs_info->reloc_mutex);
2130                 goto scrub_continue;
2131         }
2132
2133         /*
2134          * Since the transaction is done, we can apply the pending changes
2135          * before the next transaction.
2136          */
2137         btrfs_apply_pending_changes(fs_info);
2138
2139         /* commit_fs_roots gets rid of all the tree log roots, it is now
2140          * safe to free the root of tree log roots
2141          */
2142         btrfs_free_log_root_tree(trans, fs_info);
2143
2144         /*
2145          * commit_fs_roots() can call btrfs_save_ino_cache(), which generates
2146          * new delayed refs. Must handle them or qgroup can be wrong.
2147          */
2148         ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2149         if (ret) {
2150                 mutex_unlock(&fs_info->tree_log_mutex);
2151                 mutex_unlock(&fs_info->reloc_mutex);
2152                 goto scrub_continue;
2153         }
2154
2155         /*
2156          * Since fs roots are all committed, we can get a quite accurate
2157          * new_roots. So let's do quota accounting.
2158          */
2159         ret = btrfs_qgroup_account_extents(trans);
2160         if (ret < 0) {
2161                 mutex_unlock(&fs_info->tree_log_mutex);
2162                 mutex_unlock(&fs_info->reloc_mutex);
2163                 goto scrub_continue;
2164         }
2165
2166         ret = commit_cowonly_roots(trans);
2167         if (ret) {
2168                 mutex_unlock(&fs_info->tree_log_mutex);
2169                 mutex_unlock(&fs_info->reloc_mutex);
2170                 goto scrub_continue;
2171         }
2172
2173         /*
2174          * The tasks which save the space cache and inode cache may also
2175          * update ->aborted, check it.
2176          */
2177         if (unlikely(READ_ONCE(cur_trans->aborted))) {
2178                 ret = cur_trans->aborted;
2179                 mutex_unlock(&fs_info->tree_log_mutex);
2180                 mutex_unlock(&fs_info->reloc_mutex);
2181                 goto scrub_continue;
2182         }
2183
2184         btrfs_prepare_extent_commit(fs_info);
2185
2186         cur_trans = fs_info->running_transaction;
2187
2188         btrfs_set_root_node(&fs_info->tree_root->root_item,
2189                             fs_info->tree_root->node);
2190         list_add_tail(&fs_info->tree_root->dirty_list,
2191                       &cur_trans->switch_commits);
2192
2193         btrfs_set_root_node(&fs_info->chunk_root->root_item,
2194                             fs_info->chunk_root->node);
2195         list_add_tail(&fs_info->chunk_root->dirty_list,
2196                       &cur_trans->switch_commits);
2197
2198         switch_commit_roots(cur_trans);
2199
2200         ASSERT(list_empty(&cur_trans->dirty_bgs));
2201         ASSERT(list_empty(&cur_trans->io_bgs));
2202         update_super_roots(fs_info);
2203
2204         btrfs_set_super_log_root(fs_info->super_copy, 0);
2205         btrfs_set_super_log_root_level(fs_info->super_copy, 0);
2206         memcpy(fs_info->super_for_commit, fs_info->super_copy,
2207                sizeof(*fs_info->super_copy));
2208
2209         btrfs_update_commit_device_size(fs_info);
2210         btrfs_update_commit_device_bytes_used(cur_trans);
2211
2212         clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2213         clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2214
2215         btrfs_trans_release_chunk_metadata(trans);
2216
2217         spin_lock(&fs_info->trans_lock);
2218         cur_trans->state = TRANS_STATE_UNBLOCKED;
2219         fs_info->running_transaction = NULL;
2220         spin_unlock(&fs_info->trans_lock);
2221         mutex_unlock(&fs_info->reloc_mutex);
2222
2223         wake_up(&fs_info->transaction_wait);
2224
2225         ret = btrfs_write_and_wait_transaction(trans);
2226         if (ret) {
2227                 btrfs_handle_fs_error(fs_info, ret,
2228                                       "Error while writing out transaction");
2229                 mutex_unlock(&fs_info->tree_log_mutex);
2230                 goto scrub_continue;
2231         }
2232
2233         ret = write_all_supers(fs_info, 0);
2234         /*
2235          * the super is written, we can safely allow the tree-loggers
2236          * to go about their business
2237          */
2238         mutex_unlock(&fs_info->tree_log_mutex);
2239         if (ret)
2240                 goto scrub_continue;
2241
2242         btrfs_finish_extent_commit(trans);
2243
2244         if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
2245                 btrfs_clear_space_info_full(fs_info);
2246
2247         fs_info->last_trans_committed = cur_trans->transid;
2248         /*
2249          * We needn't acquire the lock here because there is no other task
2250          * which can change it.
2251          */
2252         cur_trans->state = TRANS_STATE_COMPLETED;
2253         wake_up(&cur_trans->commit_wait);
2254         clear_bit(BTRFS_FS_NEED_ASYNC_COMMIT, &fs_info->flags);
2255
2256         spin_lock(&fs_info->trans_lock);
2257         list_del_init(&cur_trans->list);
2258         spin_unlock(&fs_info->trans_lock);
2259
2260         btrfs_put_transaction(cur_trans);
2261         btrfs_put_transaction(cur_trans);
2262
2263         if (trans->type & __TRANS_FREEZABLE)
2264                 sb_end_intwrite(fs_info->sb);
2265
2266         trace_btrfs_transaction_commit(trans->root);
2267
2268         btrfs_scrub_continue(fs_info);
2269
2270         if (current->journal_info == trans)
2271                 current->journal_info = NULL;
2272
2273         kmem_cache_free(btrfs_trans_handle_cachep, trans);
2274
2275         return ret;
2276
2277 scrub_continue:
2278         btrfs_scrub_continue(fs_info);
2279 cleanup_transaction:
2280         btrfs_trans_release_metadata(trans);
2281         btrfs_trans_release_chunk_metadata(trans);
2282         trans->block_rsv = NULL;
2283         btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
2284         if (current->journal_info == trans)
2285                 current->journal_info = NULL;
2286         cleanup_transaction(trans, ret);
2287
2288         return ret;
2289 }
2290
2291 /*
2292  * return < 0 if error
2293  * 0 if there are no more dead_roots at the time of call
2294  * 1 there are more to be processed, call me again
2295  *
2296  * The return value indicates there are certainly more snapshots to delete, but
2297  * if there comes a new one during processing, it may return 0. We don't mind,
2298  * because btrfs_commit_super will poke cleaner thread and it will process it a
2299  * few seconds later.
2300  */
2301 int btrfs_clean_one_deleted_snapshot(struct btrfs_root *root)
2302 {
2303         int ret;
2304         struct btrfs_fs_info *fs_info = root->fs_info;
2305
2306         spin_lock(&fs_info->trans_lock);
2307         if (list_empty(&fs_info->dead_roots)) {
2308                 spin_unlock(&fs_info->trans_lock);
2309                 return 0;
2310         }
2311         root = list_first_entry(&fs_info->dead_roots,
2312                         struct btrfs_root, root_list);
2313         list_del_init(&root->root_list);
2314         spin_unlock(&fs_info->trans_lock);
2315
2316         btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
2317
2318         btrfs_kill_all_delayed_nodes(root);
2319
2320         if (btrfs_header_backref_rev(root->node) <
2321                         BTRFS_MIXED_BACKREF_REV)
2322                 ret = btrfs_drop_snapshot(root, NULL, 0, 0);
2323         else
2324                 ret = btrfs_drop_snapshot(root, NULL, 1, 0);
2325
2326         return (ret < 0) ? 0 : 1;
2327 }
2328
2329 void btrfs_apply_pending_changes(struct btrfs_fs_info *fs_info)
2330 {
2331         unsigned long prev;
2332         unsigned long bit;
2333
2334         prev = xchg(&fs_info->pending_changes, 0);
2335         if (!prev)
2336                 return;
2337
2338         bit = 1 << BTRFS_PENDING_SET_INODE_MAP_CACHE;
2339         if (prev & bit)
2340                 btrfs_set_opt(fs_info->mount_opt, INODE_MAP_CACHE);
2341         prev &= ~bit;
2342
2343         bit = 1 << BTRFS_PENDING_CLEAR_INODE_MAP_CACHE;
2344         if (prev & bit)
2345                 btrfs_clear_opt(fs_info->mount_opt, INODE_MAP_CACHE);
2346         prev &= ~bit;
2347
2348         bit = 1 << BTRFS_PENDING_COMMIT;
2349         if (prev & bit)
2350                 btrfs_debug(fs_info, "pending commit done");
2351         prev &= ~bit;
2352
2353         if (prev)
2354                 btrfs_warn(fs_info,
2355                         "unknown pending changes left 0x%lx, ignoring", prev);
2356 }