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