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