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