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