Merge tag 'iommu-fixes-v5.7-rc3' of git://git.kernel.org/pub/scm/linux/kernel/git...
[sfrench/cifs-2.6.git] / fs / btrfs / transaction.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5
6 #include <linux/fs.h>
7 #include <linux/slab.h>
8 #include <linux/sched.h>
9 #include <linux/writeback.h>
10 #include <linux/pagemap.h>
11 #include <linux/blkdev.h>
12 #include <linux/uuid.h>
13 #include "misc.h"
14 #include "ctree.h"
15 #include "disk-io.h"
16 #include "transaction.h"
17 #include "locking.h"
18 #include "tree-log.h"
19 #include "inode-map.h"
20 #include "volumes.h"
21 #include "dev-replace.h"
22 #include "qgroup.h"
23 #include "block-group.h"
24
25 #define BTRFS_ROOT_TRANS_TAG 0
26
27 /*
28  * Transaction states and transitions
29  *
30  * No running transaction (fs tree blocks are not modified)
31  * |
32  * | To next stage:
33  * |  Call start_transaction() variants. Except btrfs_join_transaction_nostart().
34  * V
35  * Transaction N [[TRANS_STATE_RUNNING]]
36  * |
37  * | New trans handles can be attached to transaction N by calling all
38  * | start_transaction() variants.
39  * |
40  * | To next stage:
41  * |  Call btrfs_commit_transaction() on any trans handle attached to
42  * |  transaction N
43  * V
44  * Transaction N [[TRANS_STATE_COMMIT_START]]
45  * |
46  * | Will wait for previous running transaction to completely finish if there
47  * | is one
48  * |
49  * | Then one of the following happes:
50  * | - Wait for all other trans handle holders to release.
51  * |   The btrfs_commit_transaction() caller will do the commit work.
52  * | - Wait for current transaction to be committed by others.
53  * |   Other btrfs_commit_transaction() caller will do the commit work.
54  * |
55  * | At this stage, only btrfs_join_transaction*() variants can attach
56  * | to this running transaction.
57  * | All other variants will wait for current one to finish and attach to
58  * | transaction N+1.
59  * |
60  * | To next stage:
61  * |  Caller is chosen to commit transaction N, and all other trans handle
62  * |  haven been released.
63  * V
64  * Transaction N [[TRANS_STATE_COMMIT_DOING]]
65  * |
66  * | The heavy lifting transaction work is started.
67  * | From running delayed refs (modifying extent tree) to creating pending
68  * | snapshots, running qgroups.
69  * | In short, modify supporting trees to reflect modifications of subvolume
70  * | trees.
71  * |
72  * | At this stage, all start_transaction() calls will wait for this
73  * | transaction to finish and attach to transaction N+1.
74  * |
75  * | To next stage:
76  * |  Until all supporting trees are updated.
77  * V
78  * Transaction N [[TRANS_STATE_UNBLOCKED]]
79  * |                                                Transaction N+1
80  * | All needed trees are modified, thus we only    [[TRANS_STATE_RUNNING]]
81  * | need to write them back to disk and update     |
82  * | super blocks.                                  |
83  * |                                                |
84  * | At this stage, new transaction is allowed to   |
85  * | start.                                         |
86  * | All new start_transaction() calls will be      |
87  * | attached to transid N+1.                       |
88  * |                                                |
89  * | To next stage:                                 |
90  * |  Until all tree blocks are super blocks are    |
91  * |  written to block devices                      |
92  * V                                                |
93  * Transaction N [[TRANS_STATE_COMPLETED]]          V
94  *   All tree blocks and super blocks are written.  Transaction N+1
95  *   This transaction is finished and all its       [[TRANS_STATE_COMMIT_START]]
96  *   data structures will be cleaned up.            | Life goes on
97  */
98 static const unsigned int btrfs_blocked_trans_types[TRANS_STATE_MAX] = {
99         [TRANS_STATE_RUNNING]           = 0U,
100         [TRANS_STATE_COMMIT_START]      = (__TRANS_START | __TRANS_ATTACH),
101         [TRANS_STATE_COMMIT_DOING]      = (__TRANS_START |
102                                            __TRANS_ATTACH |
103                                            __TRANS_JOIN |
104                                            __TRANS_JOIN_NOSTART),
105         [TRANS_STATE_UNBLOCKED]         = (__TRANS_START |
106                                            __TRANS_ATTACH |
107                                            __TRANS_JOIN |
108                                            __TRANS_JOIN_NOLOCK |
109                                            __TRANS_JOIN_NOSTART),
110         [TRANS_STATE_COMPLETED]         = (__TRANS_START |
111                                            __TRANS_ATTACH |
112                                            __TRANS_JOIN |
113                                            __TRANS_JOIN_NOLOCK |
114                                            __TRANS_JOIN_NOSTART),
115 };
116
117 void btrfs_put_transaction(struct btrfs_transaction *transaction)
118 {
119         WARN_ON(refcount_read(&transaction->use_count) == 0);
120         if (refcount_dec_and_test(&transaction->use_count)) {
121                 BUG_ON(!list_empty(&transaction->list));
122                 WARN_ON(!RB_EMPTY_ROOT(
123                                 &transaction->delayed_refs.href_root.rb_root));
124                 WARN_ON(!RB_EMPTY_ROOT(
125                                 &transaction->delayed_refs.dirty_extent_root));
126                 if (transaction->delayed_refs.pending_csums)
127                         btrfs_err(transaction->fs_info,
128                                   "pending csums is %llu",
129                                   transaction->delayed_refs.pending_csums);
130                 /*
131                  * If any block groups are found in ->deleted_bgs then it's
132                  * because the transaction was aborted and a commit did not
133                  * happen (things failed before writing the new superblock
134                  * and calling btrfs_finish_extent_commit()), so we can not
135                  * discard the physical locations of the block groups.
136                  */
137                 while (!list_empty(&transaction->deleted_bgs)) {
138                         struct btrfs_block_group *cache;
139
140                         cache = list_first_entry(&transaction->deleted_bgs,
141                                                  struct btrfs_block_group,
142                                                  bg_list);
143                         list_del_init(&cache->bg_list);
144                         btrfs_put_block_group_trimming(cache);
145                         btrfs_put_block_group(cache);
146                 }
147                 WARN_ON(!list_empty(&transaction->dev_update_list));
148                 kfree(transaction);
149         }
150 }
151
152 static noinline void switch_commit_roots(struct btrfs_trans_handle *trans)
153 {
154         struct btrfs_transaction *cur_trans = trans->transaction;
155         struct btrfs_fs_info *fs_info = trans->fs_info;
156         struct btrfs_root *root, *tmp;
157
158         down_write(&fs_info->commit_root_sem);
159         list_for_each_entry_safe(root, tmp, &cur_trans->switch_commits,
160                                  dirty_list) {
161                 list_del_init(&root->dirty_list);
162                 free_extent_buffer(root->commit_root);
163                 root->commit_root = btrfs_root_node(root);
164                 if (is_fstree(root->root_key.objectid))
165                         btrfs_unpin_free_ino(root);
166                 extent_io_tree_release(&root->dirty_log_pages);
167                 btrfs_qgroup_clean_swapped_blocks(root);
168         }
169
170         /* We can free old roots now. */
171         spin_lock(&cur_trans->dropped_roots_lock);
172         while (!list_empty(&cur_trans->dropped_roots)) {
173                 root = list_first_entry(&cur_trans->dropped_roots,
174                                         struct btrfs_root, root_list);
175                 list_del_init(&root->root_list);
176                 spin_unlock(&cur_trans->dropped_roots_lock);
177                 btrfs_free_log(trans, root);
178                 btrfs_drop_and_free_fs_root(fs_info, root);
179                 spin_lock(&cur_trans->dropped_roots_lock);
180         }
181         spin_unlock(&cur_trans->dropped_roots_lock);
182         up_write(&fs_info->commit_root_sem);
183 }
184
185 static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
186                                          unsigned int type)
187 {
188         if (type & TRANS_EXTWRITERS)
189                 atomic_inc(&trans->num_extwriters);
190 }
191
192 static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
193                                          unsigned int type)
194 {
195         if (type & TRANS_EXTWRITERS)
196                 atomic_dec(&trans->num_extwriters);
197 }
198
199 static inline void extwriter_counter_init(struct btrfs_transaction *trans,
200                                           unsigned int type)
201 {
202         atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
203 }
204
205 static inline int extwriter_counter_read(struct btrfs_transaction *trans)
206 {
207         return atomic_read(&trans->num_extwriters);
208 }
209
210 /*
211  * To be called after all the new block groups attached to the transaction
212  * handle have been created (btrfs_create_pending_block_groups()).
213  */
214 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
215 {
216         struct btrfs_fs_info *fs_info = trans->fs_info;
217
218         if (!trans->chunk_bytes_reserved)
219                 return;
220
221         WARN_ON_ONCE(!list_empty(&trans->new_bgs));
222
223         btrfs_block_rsv_release(fs_info, &fs_info->chunk_block_rsv,
224                                 trans->chunk_bytes_reserved, NULL);
225         trans->chunk_bytes_reserved = 0;
226 }
227
228 /*
229  * either allocate a new transaction or hop into the existing one
230  */
231 static noinline int join_transaction(struct btrfs_fs_info *fs_info,
232                                      unsigned int type)
233 {
234         struct btrfs_transaction *cur_trans;
235
236         spin_lock(&fs_info->trans_lock);
237 loop:
238         /* The file system has been taken offline. No new transactions. */
239         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
240                 spin_unlock(&fs_info->trans_lock);
241                 return -EROFS;
242         }
243
244         cur_trans = fs_info->running_transaction;
245         if (cur_trans) {
246                 if (TRANS_ABORTED(cur_trans)) {
247                         spin_unlock(&fs_info->trans_lock);
248                         return cur_trans->aborted;
249                 }
250                 if (btrfs_blocked_trans_types[cur_trans->state] & type) {
251                         spin_unlock(&fs_info->trans_lock);
252                         return -EBUSY;
253                 }
254                 refcount_inc(&cur_trans->use_count);
255                 atomic_inc(&cur_trans->num_writers);
256                 extwriter_counter_inc(cur_trans, type);
257                 spin_unlock(&fs_info->trans_lock);
258                 return 0;
259         }
260         spin_unlock(&fs_info->trans_lock);
261
262         /*
263          * If we are ATTACH, we just want to catch the current transaction,
264          * and commit it. If there is no transaction, just return ENOENT.
265          */
266         if (type == TRANS_ATTACH)
267                 return -ENOENT;
268
269         /*
270          * JOIN_NOLOCK only happens during the transaction commit, so
271          * it is impossible that ->running_transaction is NULL
272          */
273         BUG_ON(type == TRANS_JOIN_NOLOCK);
274
275         cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
276         if (!cur_trans)
277                 return -ENOMEM;
278
279         spin_lock(&fs_info->trans_lock);
280         if (fs_info->running_transaction) {
281                 /*
282                  * someone started a transaction after we unlocked.  Make sure
283                  * to redo the checks above
284                  */
285                 kfree(cur_trans);
286                 goto loop;
287         } else if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
288                 spin_unlock(&fs_info->trans_lock);
289                 kfree(cur_trans);
290                 return -EROFS;
291         }
292
293         cur_trans->fs_info = fs_info;
294         atomic_set(&cur_trans->num_writers, 1);
295         extwriter_counter_init(cur_trans, type);
296         init_waitqueue_head(&cur_trans->writer_wait);
297         init_waitqueue_head(&cur_trans->commit_wait);
298         cur_trans->state = TRANS_STATE_RUNNING;
299         /*
300          * One for this trans handle, one so it will live on until we
301          * commit the transaction.
302          */
303         refcount_set(&cur_trans->use_count, 2);
304         cur_trans->flags = 0;
305         cur_trans->start_time = ktime_get_seconds();
306
307         memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
308
309         cur_trans->delayed_refs.href_root = RB_ROOT_CACHED;
310         cur_trans->delayed_refs.dirty_extent_root = RB_ROOT;
311         atomic_set(&cur_trans->delayed_refs.num_entries, 0);
312
313         /*
314          * although the tree mod log is per file system and not per transaction,
315          * the log must never go across transaction boundaries.
316          */
317         smp_mb();
318         if (!list_empty(&fs_info->tree_mod_seq_list))
319                 WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
320         if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
321                 WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
322         atomic64_set(&fs_info->tree_mod_seq, 0);
323
324         spin_lock_init(&cur_trans->delayed_refs.lock);
325
326         INIT_LIST_HEAD(&cur_trans->pending_snapshots);
327         INIT_LIST_HEAD(&cur_trans->dev_update_list);
328         INIT_LIST_HEAD(&cur_trans->switch_commits);
329         INIT_LIST_HEAD(&cur_trans->dirty_bgs);
330         INIT_LIST_HEAD(&cur_trans->io_bgs);
331         INIT_LIST_HEAD(&cur_trans->dropped_roots);
332         mutex_init(&cur_trans->cache_write_mutex);
333         spin_lock_init(&cur_trans->dirty_bgs_lock);
334         INIT_LIST_HEAD(&cur_trans->deleted_bgs);
335         spin_lock_init(&cur_trans->dropped_roots_lock);
336         list_add_tail(&cur_trans->list, &fs_info->trans_list);
337         extent_io_tree_init(fs_info, &cur_trans->dirty_pages,
338                         IO_TREE_TRANS_DIRTY_PAGES, fs_info->btree_inode);
339         extent_io_tree_init(fs_info, &cur_trans->pinned_extents,
340                         IO_TREE_FS_PINNED_EXTENTS, NULL);
341         fs_info->generation++;
342         cur_trans->transid = fs_info->generation;
343         fs_info->running_transaction = cur_trans;
344         cur_trans->aborted = 0;
345         spin_unlock(&fs_info->trans_lock);
346
347         return 0;
348 }
349
350 /*
351  * this does all the record keeping required to make sure that a reference
352  * counted root is properly recorded in a given transaction.  This is required
353  * to make sure the old root from before we joined the transaction is deleted
354  * when the transaction commits
355  */
356 static int record_root_in_trans(struct btrfs_trans_handle *trans,
357                                struct btrfs_root *root,
358                                int force)
359 {
360         struct btrfs_fs_info *fs_info = root->fs_info;
361
362         if ((test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
363             root->last_trans < trans->transid) || force) {
364                 WARN_ON(root == fs_info->extent_root);
365                 WARN_ON(!force && root->commit_root != root->node);
366
367                 /*
368                  * see below for IN_TRANS_SETUP usage rules
369                  * we have the reloc mutex held now, so there
370                  * is only one writer in this function
371                  */
372                 set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
373
374                 /* make sure readers find IN_TRANS_SETUP before
375                  * they find our root->last_trans update
376                  */
377                 smp_wmb();
378
379                 spin_lock(&fs_info->fs_roots_radix_lock);
380                 if (root->last_trans == trans->transid && !force) {
381                         spin_unlock(&fs_info->fs_roots_radix_lock);
382                         return 0;
383                 }
384                 radix_tree_tag_set(&fs_info->fs_roots_radix,
385                                    (unsigned long)root->root_key.objectid,
386                                    BTRFS_ROOT_TRANS_TAG);
387                 spin_unlock(&fs_info->fs_roots_radix_lock);
388                 root->last_trans = trans->transid;
389
390                 /* this is pretty tricky.  We don't want to
391                  * take the relocation lock in btrfs_record_root_in_trans
392                  * unless we're really doing the first setup for this root in
393                  * this transaction.
394                  *
395                  * Normally we'd use root->last_trans as a flag to decide
396                  * if we want to take the expensive mutex.
397                  *
398                  * But, we have to set root->last_trans before we
399                  * init the relocation root, otherwise, we trip over warnings
400                  * in ctree.c.  The solution used here is to flag ourselves
401                  * with root IN_TRANS_SETUP.  When this is 1, we're still
402                  * fixing up the reloc trees and everyone must wait.
403                  *
404                  * When this is zero, they can trust root->last_trans and fly
405                  * through btrfs_record_root_in_trans without having to take the
406                  * lock.  smp_wmb() makes sure that all the writes above are
407                  * done before we pop in the zero below
408                  */
409                 btrfs_init_reloc_root(trans, root);
410                 smp_mb__before_atomic();
411                 clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
412         }
413         return 0;
414 }
415
416
417 void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
418                             struct btrfs_root *root)
419 {
420         struct btrfs_fs_info *fs_info = root->fs_info;
421         struct btrfs_transaction *cur_trans = trans->transaction;
422
423         /* Add ourselves to the transaction dropped list */
424         spin_lock(&cur_trans->dropped_roots_lock);
425         list_add_tail(&root->root_list, &cur_trans->dropped_roots);
426         spin_unlock(&cur_trans->dropped_roots_lock);
427
428         /* Make sure we don't try to update the root at commit time */
429         spin_lock(&fs_info->fs_roots_radix_lock);
430         radix_tree_tag_clear(&fs_info->fs_roots_radix,
431                              (unsigned long)root->root_key.objectid,
432                              BTRFS_ROOT_TRANS_TAG);
433         spin_unlock(&fs_info->fs_roots_radix_lock);
434 }
435
436 int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
437                                struct btrfs_root *root)
438 {
439         struct btrfs_fs_info *fs_info = root->fs_info;
440
441         if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
442                 return 0;
443
444         /*
445          * see record_root_in_trans for comments about IN_TRANS_SETUP usage
446          * and barriers
447          */
448         smp_rmb();
449         if (root->last_trans == trans->transid &&
450             !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
451                 return 0;
452
453         mutex_lock(&fs_info->reloc_mutex);
454         record_root_in_trans(trans, root, 0);
455         mutex_unlock(&fs_info->reloc_mutex);
456
457         return 0;
458 }
459
460 static inline int is_transaction_blocked(struct btrfs_transaction *trans)
461 {
462         return (trans->state >= TRANS_STATE_COMMIT_START &&
463                 trans->state < TRANS_STATE_UNBLOCKED &&
464                 !TRANS_ABORTED(trans));
465 }
466
467 /* wait for commit against the current transaction to become unblocked
468  * when this is done, it is safe to start a new transaction, but the current
469  * transaction might not be fully on disk.
470  */
471 static void wait_current_trans(struct btrfs_fs_info *fs_info)
472 {
473         struct btrfs_transaction *cur_trans;
474
475         spin_lock(&fs_info->trans_lock);
476         cur_trans = fs_info->running_transaction;
477         if (cur_trans && is_transaction_blocked(cur_trans)) {
478                 refcount_inc(&cur_trans->use_count);
479                 spin_unlock(&fs_info->trans_lock);
480
481                 wait_event(fs_info->transaction_wait,
482                            cur_trans->state >= TRANS_STATE_UNBLOCKED ||
483                            TRANS_ABORTED(cur_trans));
484                 btrfs_put_transaction(cur_trans);
485         } else {
486                 spin_unlock(&fs_info->trans_lock);
487         }
488 }
489
490 static int may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
491 {
492         if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
493                 return 0;
494
495         if (type == TRANS_START)
496                 return 1;
497
498         return 0;
499 }
500
501 static inline bool need_reserve_reloc_root(struct btrfs_root *root)
502 {
503         struct btrfs_fs_info *fs_info = root->fs_info;
504
505         if (!fs_info->reloc_ctl ||
506             !test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
507             root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
508             root->reloc_root)
509                 return false;
510
511         return true;
512 }
513
514 static struct btrfs_trans_handle *
515 start_transaction(struct btrfs_root *root, unsigned int num_items,
516                   unsigned int type, enum btrfs_reserve_flush_enum flush,
517                   bool enforce_qgroups)
518 {
519         struct btrfs_fs_info *fs_info = root->fs_info;
520         struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
521         struct btrfs_trans_handle *h;
522         struct btrfs_transaction *cur_trans;
523         u64 num_bytes = 0;
524         u64 qgroup_reserved = 0;
525         bool reloc_reserved = false;
526         int ret;
527
528         /* Send isn't supposed to start transactions. */
529         ASSERT(current->journal_info != BTRFS_SEND_TRANS_STUB);
530
531         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
532                 return ERR_PTR(-EROFS);
533
534         if (current->journal_info) {
535                 WARN_ON(type & TRANS_EXTWRITERS);
536                 h = current->journal_info;
537                 refcount_inc(&h->use_count);
538                 WARN_ON(refcount_read(&h->use_count) > 2);
539                 h->orig_rsv = h->block_rsv;
540                 h->block_rsv = NULL;
541                 goto got_it;
542         }
543
544         /*
545          * Do the reservation before we join the transaction so we can do all
546          * the appropriate flushing if need be.
547          */
548         if (num_items && root != fs_info->chunk_root) {
549                 struct btrfs_block_rsv *rsv = &fs_info->trans_block_rsv;
550                 u64 delayed_refs_bytes = 0;
551
552                 qgroup_reserved = num_items * fs_info->nodesize;
553                 ret = btrfs_qgroup_reserve_meta_pertrans(root, qgroup_reserved,
554                                 enforce_qgroups);
555                 if (ret)
556                         return ERR_PTR(ret);
557
558                 /*
559                  * We want to reserve all the bytes we may need all at once, so
560                  * we only do 1 enospc flushing cycle per transaction start.  We
561                  * accomplish this by simply assuming we'll do 2 x num_items
562                  * worth of delayed refs updates in this trans handle, and
563                  * refill that amount for whatever is missing in the reserve.
564                  */
565                 num_bytes = btrfs_calc_insert_metadata_size(fs_info, num_items);
566                 if (delayed_refs_rsv->full == 0) {
567                         delayed_refs_bytes = num_bytes;
568                         num_bytes <<= 1;
569                 }
570
571                 /*
572                  * Do the reservation for the relocation root creation
573                  */
574                 if (need_reserve_reloc_root(root)) {
575                         num_bytes += fs_info->nodesize;
576                         reloc_reserved = true;
577                 }
578
579                 ret = btrfs_block_rsv_add(root, rsv, num_bytes, flush);
580                 if (ret)
581                         goto reserve_fail;
582                 if (delayed_refs_bytes) {
583                         btrfs_migrate_to_delayed_refs_rsv(fs_info, rsv,
584                                                           delayed_refs_bytes);
585                         num_bytes -= delayed_refs_bytes;
586                 }
587         } else if (num_items == 0 && flush == BTRFS_RESERVE_FLUSH_ALL &&
588                    !delayed_refs_rsv->full) {
589                 /*
590                  * Some people call with btrfs_start_transaction(root, 0)
591                  * because they can be throttled, but have some other mechanism
592                  * for reserving space.  We still want these guys to refill the
593                  * delayed block_rsv so just add 1 items worth of reservation
594                  * here.
595                  */
596                 ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
597                 if (ret)
598                         goto reserve_fail;
599         }
600 again:
601         h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
602         if (!h) {
603                 ret = -ENOMEM;
604                 goto alloc_fail;
605         }
606
607         /*
608          * If we are JOIN_NOLOCK we're already committing a transaction and
609          * waiting on this guy, so we don't need to do the sb_start_intwrite
610          * because we're already holding a ref.  We need this because we could
611          * have raced in and did an fsync() on a file which can kick a commit
612          * and then we deadlock with somebody doing a freeze.
613          *
614          * If we are ATTACH, it means we just want to catch the current
615          * transaction and commit it, so we needn't do sb_start_intwrite(). 
616          */
617         if (type & __TRANS_FREEZABLE)
618                 sb_start_intwrite(fs_info->sb);
619
620         if (may_wait_transaction(fs_info, type))
621                 wait_current_trans(fs_info);
622
623         do {
624                 ret = join_transaction(fs_info, type);
625                 if (ret == -EBUSY) {
626                         wait_current_trans(fs_info);
627                         if (unlikely(type == TRANS_ATTACH ||
628                                      type == TRANS_JOIN_NOSTART))
629                                 ret = -ENOENT;
630                 }
631         } while (ret == -EBUSY);
632
633         if (ret < 0)
634                 goto join_fail;
635
636         cur_trans = fs_info->running_transaction;
637
638         h->transid = cur_trans->transid;
639         h->transaction = cur_trans;
640         h->root = root;
641         refcount_set(&h->use_count, 1);
642         h->fs_info = root->fs_info;
643
644         h->type = type;
645         h->can_flush_pending_bgs = true;
646         INIT_LIST_HEAD(&h->new_bgs);
647
648         smp_mb();
649         if (cur_trans->state >= TRANS_STATE_COMMIT_START &&
650             may_wait_transaction(fs_info, type)) {
651                 current->journal_info = h;
652                 btrfs_commit_transaction(h);
653                 goto again;
654         }
655
656         if (num_bytes) {
657                 trace_btrfs_space_reservation(fs_info, "transaction",
658                                               h->transid, num_bytes, 1);
659                 h->block_rsv = &fs_info->trans_block_rsv;
660                 h->bytes_reserved = num_bytes;
661                 h->reloc_reserved = reloc_reserved;
662         }
663
664 got_it:
665         btrfs_record_root_in_trans(h, root);
666
667         if (!current->journal_info)
668                 current->journal_info = h;
669         return h;
670
671 join_fail:
672         if (type & __TRANS_FREEZABLE)
673                 sb_end_intwrite(fs_info->sb);
674         kmem_cache_free(btrfs_trans_handle_cachep, h);
675 alloc_fail:
676         if (num_bytes)
677                 btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
678                                         num_bytes, NULL);
679 reserve_fail:
680         btrfs_qgroup_free_meta_pertrans(root, qgroup_reserved);
681         return ERR_PTR(ret);
682 }
683
684 struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
685                                                    unsigned int num_items)
686 {
687         return start_transaction(root, num_items, TRANS_START,
688                                  BTRFS_RESERVE_FLUSH_ALL, true);
689 }
690
691 struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
692                                         struct btrfs_root *root,
693                                         unsigned int num_items,
694                                         int min_factor)
695 {
696         struct btrfs_fs_info *fs_info = root->fs_info;
697         struct btrfs_trans_handle *trans;
698         u64 num_bytes;
699         int ret;
700
701         /*
702          * We have two callers: unlink and block group removal.  The
703          * former should succeed even if we will temporarily exceed
704          * quota and the latter operates on the extent root so
705          * qgroup enforcement is ignored anyway.
706          */
707         trans = start_transaction(root, num_items, TRANS_START,
708                                   BTRFS_RESERVE_FLUSH_ALL, false);
709         if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
710                 return trans;
711
712         trans = btrfs_start_transaction(root, 0);
713         if (IS_ERR(trans))
714                 return trans;
715
716         num_bytes = btrfs_calc_insert_metadata_size(fs_info, num_items);
717         ret = btrfs_cond_migrate_bytes(fs_info, &fs_info->trans_block_rsv,
718                                        num_bytes, min_factor);
719         if (ret) {
720                 btrfs_end_transaction(trans);
721                 return ERR_PTR(ret);
722         }
723
724         trans->block_rsv = &fs_info->trans_block_rsv;
725         trans->bytes_reserved = num_bytes;
726         trace_btrfs_space_reservation(fs_info, "transaction",
727                                       trans->transid, num_bytes, 1);
728
729         return trans;
730 }
731
732 struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
733 {
734         return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
735                                  true);
736 }
737
738 struct btrfs_trans_handle *btrfs_join_transaction_spacecache(struct btrfs_root *root)
739 {
740         return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
741                                  BTRFS_RESERVE_NO_FLUSH, true);
742 }
743
744 /*
745  * Similar to regular join but it never starts a transaction when none is
746  * running or after waiting for the current one to finish.
747  */
748 struct btrfs_trans_handle *btrfs_join_transaction_nostart(struct btrfs_root *root)
749 {
750         return start_transaction(root, 0, TRANS_JOIN_NOSTART,
751                                  BTRFS_RESERVE_NO_FLUSH, true);
752 }
753
754 /*
755  * btrfs_attach_transaction() - catch the running transaction
756  *
757  * It is used when we want to commit the current the transaction, but
758  * don't want to start a new one.
759  *
760  * Note: If this function return -ENOENT, it just means there is no
761  * running transaction. But it is possible that the inactive transaction
762  * is still in the memory, not fully on disk. If you hope there is no
763  * inactive transaction in the fs when -ENOENT is returned, you should
764  * invoke
765  *     btrfs_attach_transaction_barrier()
766  */
767 struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
768 {
769         return start_transaction(root, 0, TRANS_ATTACH,
770                                  BTRFS_RESERVE_NO_FLUSH, true);
771 }
772
773 /*
774  * btrfs_attach_transaction_barrier() - catch the running transaction
775  *
776  * It is similar to the above function, the difference is this one
777  * will wait for all the inactive transactions until they fully
778  * complete.
779  */
780 struct btrfs_trans_handle *
781 btrfs_attach_transaction_barrier(struct btrfs_root *root)
782 {
783         struct btrfs_trans_handle *trans;
784
785         trans = start_transaction(root, 0, TRANS_ATTACH,
786                                   BTRFS_RESERVE_NO_FLUSH, true);
787         if (trans == ERR_PTR(-ENOENT))
788                 btrfs_wait_for_commit(root->fs_info, 0);
789
790         return trans;
791 }
792
793 /* wait for a transaction commit to be fully complete */
794 static noinline void wait_for_commit(struct btrfs_transaction *commit)
795 {
796         wait_event(commit->commit_wait, commit->state == TRANS_STATE_COMPLETED);
797 }
798
799 int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
800 {
801         struct btrfs_transaction *cur_trans = NULL, *t;
802         int ret = 0;
803
804         if (transid) {
805                 if (transid <= fs_info->last_trans_committed)
806                         goto out;
807
808                 /* find specified transaction */
809                 spin_lock(&fs_info->trans_lock);
810                 list_for_each_entry(t, &fs_info->trans_list, list) {
811                         if (t->transid == transid) {
812                                 cur_trans = t;
813                                 refcount_inc(&cur_trans->use_count);
814                                 ret = 0;
815                                 break;
816                         }
817                         if (t->transid > transid) {
818                                 ret = 0;
819                                 break;
820                         }
821                 }
822                 spin_unlock(&fs_info->trans_lock);
823
824                 /*
825                  * The specified transaction doesn't exist, or we
826                  * raced with btrfs_commit_transaction
827                  */
828                 if (!cur_trans) {
829                         if (transid > fs_info->last_trans_committed)
830                                 ret = -EINVAL;
831                         goto out;
832                 }
833         } else {
834                 /* find newest transaction that is committing | committed */
835                 spin_lock(&fs_info->trans_lock);
836                 list_for_each_entry_reverse(t, &fs_info->trans_list,
837                                             list) {
838                         if (t->state >= TRANS_STATE_COMMIT_START) {
839                                 if (t->state == TRANS_STATE_COMPLETED)
840                                         break;
841                                 cur_trans = t;
842                                 refcount_inc(&cur_trans->use_count);
843                                 break;
844                         }
845                 }
846                 spin_unlock(&fs_info->trans_lock);
847                 if (!cur_trans)
848                         goto out;  /* nothing committing|committed */
849         }
850
851         wait_for_commit(cur_trans);
852         btrfs_put_transaction(cur_trans);
853 out:
854         return ret;
855 }
856
857 void btrfs_throttle(struct btrfs_fs_info *fs_info)
858 {
859         wait_current_trans(fs_info);
860 }
861
862 static int should_end_transaction(struct btrfs_trans_handle *trans)
863 {
864         struct btrfs_fs_info *fs_info = trans->fs_info;
865
866         if (btrfs_check_space_for_delayed_refs(fs_info))
867                 return 1;
868
869         return !!btrfs_block_rsv_check(&fs_info->global_block_rsv, 5);
870 }
871
872 int btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
873 {
874         struct btrfs_transaction *cur_trans = trans->transaction;
875
876         smp_mb();
877         if (cur_trans->state >= TRANS_STATE_COMMIT_START ||
878             cur_trans->delayed_refs.flushing)
879                 return 1;
880
881         return should_end_transaction(trans);
882 }
883
884 static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
885
886 {
887         struct btrfs_fs_info *fs_info = trans->fs_info;
888
889         if (!trans->block_rsv) {
890                 ASSERT(!trans->bytes_reserved);
891                 return;
892         }
893
894         if (!trans->bytes_reserved)
895                 return;
896
897         ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
898         trace_btrfs_space_reservation(fs_info, "transaction",
899                                       trans->transid, trans->bytes_reserved, 0);
900         btrfs_block_rsv_release(fs_info, trans->block_rsv,
901                                 trans->bytes_reserved, NULL);
902         trans->bytes_reserved = 0;
903 }
904
905 static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
906                                    int throttle)
907 {
908         struct btrfs_fs_info *info = trans->fs_info;
909         struct btrfs_transaction *cur_trans = trans->transaction;
910         int err = 0;
911
912         if (refcount_read(&trans->use_count) > 1) {
913                 refcount_dec(&trans->use_count);
914                 trans->block_rsv = trans->orig_rsv;
915                 return 0;
916         }
917
918         btrfs_trans_release_metadata(trans);
919         trans->block_rsv = NULL;
920
921         btrfs_create_pending_block_groups(trans);
922
923         btrfs_trans_release_chunk_metadata(trans);
924
925         if (trans->type & __TRANS_FREEZABLE)
926                 sb_end_intwrite(info->sb);
927
928         WARN_ON(cur_trans != info->running_transaction);
929         WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
930         atomic_dec(&cur_trans->num_writers);
931         extwriter_counter_dec(cur_trans, trans->type);
932
933         cond_wake_up(&cur_trans->writer_wait);
934         btrfs_put_transaction(cur_trans);
935
936         if (current->journal_info == trans)
937                 current->journal_info = NULL;
938
939         if (throttle)
940                 btrfs_run_delayed_iputs(info);
941
942         if (TRANS_ABORTED(trans) ||
943             test_bit(BTRFS_FS_STATE_ERROR, &info->fs_state)) {
944                 wake_up_process(info->transaction_kthread);
945                 err = -EIO;
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);
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         if (ret) {
1594                 btrfs_tree_unlock(old);
1595                 free_extent_buffer(old);
1596                 btrfs_abort_transaction(trans, ret);
1597                 goto fail;
1598         }
1599
1600         btrfs_set_lock_blocking_write(old);
1601
1602         ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
1603         /* clean up in any case */
1604         btrfs_tree_unlock(old);
1605         free_extent_buffer(old);
1606         if (ret) {
1607                 btrfs_abort_transaction(trans, ret);
1608                 goto fail;
1609         }
1610         /* see comments in should_cow_block() */
1611         set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1612         smp_wmb();
1613
1614         btrfs_set_root_node(new_root_item, tmp);
1615         /* record when the snapshot was created in key.offset */
1616         key.offset = trans->transid;
1617         ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1618         btrfs_tree_unlock(tmp);
1619         free_extent_buffer(tmp);
1620         if (ret) {
1621                 btrfs_abort_transaction(trans, ret);
1622                 goto fail;
1623         }
1624
1625         /*
1626          * insert root back/forward references
1627          */
1628         ret = btrfs_add_root_ref(trans, objectid,
1629                                  parent_root->root_key.objectid,
1630                                  btrfs_ino(BTRFS_I(parent_inode)), index,
1631                                  dentry->d_name.name, dentry->d_name.len);
1632         if (ret) {
1633                 btrfs_abort_transaction(trans, ret);
1634                 goto fail;
1635         }
1636
1637         key.offset = (u64)-1;
1638         pending->snap = btrfs_get_fs_root(fs_info, &key, true);
1639         if (IS_ERR(pending->snap)) {
1640                 ret = PTR_ERR(pending->snap);
1641                 btrfs_abort_transaction(trans, ret);
1642                 goto fail;
1643         }
1644
1645         ret = btrfs_reloc_post_snapshot(trans, pending);
1646         if (ret) {
1647                 btrfs_abort_transaction(trans, ret);
1648                 goto fail;
1649         }
1650
1651         ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1652         if (ret) {
1653                 btrfs_abort_transaction(trans, ret);
1654                 goto fail;
1655         }
1656
1657         /*
1658          * Do special qgroup accounting for snapshot, as we do some qgroup
1659          * snapshot hack to do fast snapshot.
1660          * To co-operate with that hack, we do hack again.
1661          * Or snapshot will be greatly slowed down by a subtree qgroup rescan
1662          */
1663         ret = qgroup_account_snapshot(trans, root, parent_root,
1664                                       pending->inherit, objectid);
1665         if (ret < 0)
1666                 goto fail;
1667
1668         ret = btrfs_insert_dir_item(trans, dentry->d_name.name,
1669                                     dentry->d_name.len, BTRFS_I(parent_inode),
1670                                     &key, BTRFS_FT_DIR, index);
1671         /* We have check then name at the beginning, so it is impossible. */
1672         BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
1673         if (ret) {
1674                 btrfs_abort_transaction(trans, ret);
1675                 goto fail;
1676         }
1677
1678         btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
1679                                          dentry->d_name.len * 2);
1680         parent_inode->i_mtime = parent_inode->i_ctime =
1681                 current_time(parent_inode);
1682         ret = btrfs_update_inode_fallback(trans, parent_root, parent_inode);
1683         if (ret) {
1684                 btrfs_abort_transaction(trans, ret);
1685                 goto fail;
1686         }
1687         ret = btrfs_uuid_tree_add(trans, new_root_item->uuid,
1688                                   BTRFS_UUID_KEY_SUBVOL,
1689                                   objectid);
1690         if (ret) {
1691                 btrfs_abort_transaction(trans, ret);
1692                 goto fail;
1693         }
1694         if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1695                 ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1696                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1697                                           objectid);
1698                 if (ret && ret != -EEXIST) {
1699                         btrfs_abort_transaction(trans, ret);
1700                         goto fail;
1701                 }
1702         }
1703
1704         ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1705         if (ret) {
1706                 btrfs_abort_transaction(trans, ret);
1707                 goto fail;
1708         }
1709
1710 fail:
1711         pending->error = ret;
1712 dir_item_existed:
1713         trans->block_rsv = rsv;
1714         trans->bytes_reserved = 0;
1715 clear_skip_qgroup:
1716         btrfs_clear_skip_qgroup(trans);
1717 no_free_objectid:
1718         kfree(new_root_item);
1719         pending->root_item = NULL;
1720         btrfs_free_path(path);
1721         pending->path = NULL;
1722
1723         return ret;
1724 }
1725
1726 /*
1727  * create all the snapshots we've scheduled for creation
1728  */
1729 static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
1730 {
1731         struct btrfs_pending_snapshot *pending, *next;
1732         struct list_head *head = &trans->transaction->pending_snapshots;
1733         int ret = 0;
1734
1735         list_for_each_entry_safe(pending, next, head, list) {
1736                 list_del(&pending->list);
1737                 ret = create_pending_snapshot(trans, pending);
1738                 if (ret)
1739                         break;
1740         }
1741         return ret;
1742 }
1743
1744 static void update_super_roots(struct btrfs_fs_info *fs_info)
1745 {
1746         struct btrfs_root_item *root_item;
1747         struct btrfs_super_block *super;
1748
1749         super = fs_info->super_copy;
1750
1751         root_item = &fs_info->chunk_root->root_item;
1752         super->chunk_root = root_item->bytenr;
1753         super->chunk_root_generation = root_item->generation;
1754         super->chunk_root_level = root_item->level;
1755
1756         root_item = &fs_info->tree_root->root_item;
1757         super->root = root_item->bytenr;
1758         super->generation = root_item->generation;
1759         super->root_level = root_item->level;
1760         if (btrfs_test_opt(fs_info, SPACE_CACHE))
1761                 super->cache_generation = root_item->generation;
1762         if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1763                 super->uuid_tree_generation = root_item->generation;
1764 }
1765
1766 int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1767 {
1768         struct btrfs_transaction *trans;
1769         int ret = 0;
1770
1771         spin_lock(&info->trans_lock);
1772         trans = info->running_transaction;
1773         if (trans)
1774                 ret = (trans->state >= TRANS_STATE_COMMIT_START);
1775         spin_unlock(&info->trans_lock);
1776         return ret;
1777 }
1778
1779 int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1780 {
1781         struct btrfs_transaction *trans;
1782         int ret = 0;
1783
1784         spin_lock(&info->trans_lock);
1785         trans = info->running_transaction;
1786         if (trans)
1787                 ret = is_transaction_blocked(trans);
1788         spin_unlock(&info->trans_lock);
1789         return ret;
1790 }
1791
1792 /*
1793  * wait for the current transaction commit to start and block subsequent
1794  * transaction joins
1795  */
1796 static void wait_current_trans_commit_start(struct btrfs_fs_info *fs_info,
1797                                             struct btrfs_transaction *trans)
1798 {
1799         wait_event(fs_info->transaction_blocked_wait,
1800                    trans->state >= TRANS_STATE_COMMIT_START ||
1801                    TRANS_ABORTED(trans));
1802 }
1803
1804 /*
1805  * wait for the current transaction to start and then become unblocked.
1806  * caller holds ref.
1807  */
1808 static void wait_current_trans_commit_start_and_unblock(
1809                                         struct btrfs_fs_info *fs_info,
1810                                         struct btrfs_transaction *trans)
1811 {
1812         wait_event(fs_info->transaction_wait,
1813                    trans->state >= TRANS_STATE_UNBLOCKED ||
1814                    TRANS_ABORTED(trans));
1815 }
1816
1817 /*
1818  * commit transactions asynchronously. once btrfs_commit_transaction_async
1819  * returns, any subsequent transaction will not be allowed to join.
1820  */
1821 struct btrfs_async_commit {
1822         struct btrfs_trans_handle *newtrans;
1823         struct work_struct work;
1824 };
1825
1826 static void do_async_commit(struct work_struct *work)
1827 {
1828         struct btrfs_async_commit *ac =
1829                 container_of(work, struct btrfs_async_commit, work);
1830
1831         /*
1832          * We've got freeze protection passed with the transaction.
1833          * Tell lockdep about it.
1834          */
1835         if (ac->newtrans->type & __TRANS_FREEZABLE)
1836                 __sb_writers_acquired(ac->newtrans->fs_info->sb, SB_FREEZE_FS);
1837
1838         current->journal_info = ac->newtrans;
1839
1840         btrfs_commit_transaction(ac->newtrans);
1841         kfree(ac);
1842 }
1843
1844 int btrfs_commit_transaction_async(struct btrfs_trans_handle *trans,
1845                                    int wait_for_unblock)
1846 {
1847         struct btrfs_fs_info *fs_info = trans->fs_info;
1848         struct btrfs_async_commit *ac;
1849         struct btrfs_transaction *cur_trans;
1850
1851         ac = kmalloc(sizeof(*ac), GFP_NOFS);
1852         if (!ac)
1853                 return -ENOMEM;
1854
1855         INIT_WORK(&ac->work, do_async_commit);
1856         ac->newtrans = btrfs_join_transaction(trans->root);
1857         if (IS_ERR(ac->newtrans)) {
1858                 int err = PTR_ERR(ac->newtrans);
1859                 kfree(ac);
1860                 return err;
1861         }
1862
1863         /* take transaction reference */
1864         cur_trans = trans->transaction;
1865         refcount_inc(&cur_trans->use_count);
1866
1867         btrfs_end_transaction(trans);
1868
1869         /*
1870          * Tell lockdep we've released the freeze rwsem, since the
1871          * async commit thread will be the one to unlock it.
1872          */
1873         if (ac->newtrans->type & __TRANS_FREEZABLE)
1874                 __sb_writers_release(fs_info->sb, SB_FREEZE_FS);
1875
1876         schedule_work(&ac->work);
1877
1878         /* wait for transaction to start and unblock */
1879         if (wait_for_unblock)
1880                 wait_current_trans_commit_start_and_unblock(fs_info, cur_trans);
1881         else
1882                 wait_current_trans_commit_start(fs_info, cur_trans);
1883
1884         if (current->journal_info == trans)
1885                 current->journal_info = NULL;
1886
1887         btrfs_put_transaction(cur_trans);
1888         return 0;
1889 }
1890
1891
1892 static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
1893 {
1894         struct btrfs_fs_info *fs_info = trans->fs_info;
1895         struct btrfs_transaction *cur_trans = trans->transaction;
1896
1897         WARN_ON(refcount_read(&trans->use_count) > 1);
1898
1899         btrfs_abort_transaction(trans, err);
1900
1901         spin_lock(&fs_info->trans_lock);
1902
1903         /*
1904          * If the transaction is removed from the list, it means this
1905          * transaction has been committed successfully, so it is impossible
1906          * to call the cleanup function.
1907          */
1908         BUG_ON(list_empty(&cur_trans->list));
1909
1910         list_del_init(&cur_trans->list);
1911         if (cur_trans == fs_info->running_transaction) {
1912                 cur_trans->state = TRANS_STATE_COMMIT_DOING;
1913                 spin_unlock(&fs_info->trans_lock);
1914                 wait_event(cur_trans->writer_wait,
1915                            atomic_read(&cur_trans->num_writers) == 1);
1916
1917                 spin_lock(&fs_info->trans_lock);
1918         }
1919         spin_unlock(&fs_info->trans_lock);
1920
1921         btrfs_cleanup_one_transaction(trans->transaction, fs_info);
1922
1923         spin_lock(&fs_info->trans_lock);
1924         if (cur_trans == fs_info->running_transaction)
1925                 fs_info->running_transaction = NULL;
1926         spin_unlock(&fs_info->trans_lock);
1927
1928         if (trans->type & __TRANS_FREEZABLE)
1929                 sb_end_intwrite(fs_info->sb);
1930         btrfs_put_transaction(cur_trans);
1931         btrfs_put_transaction(cur_trans);
1932
1933         trace_btrfs_transaction_commit(trans->root);
1934
1935         if (current->journal_info == trans)
1936                 current->journal_info = NULL;
1937         btrfs_scrub_cancel(fs_info);
1938
1939         kmem_cache_free(btrfs_trans_handle_cachep, trans);
1940 }
1941
1942 /*
1943  * Release reserved delayed ref space of all pending block groups of the
1944  * transaction and remove them from the list
1945  */
1946 static void btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle *trans)
1947 {
1948        struct btrfs_fs_info *fs_info = trans->fs_info;
1949        struct btrfs_block_group *block_group, *tmp;
1950
1951        list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
1952                btrfs_delayed_refs_rsv_release(fs_info, 1);
1953                list_del_init(&block_group->bg_list);
1954        }
1955 }
1956
1957 static inline int btrfs_start_delalloc_flush(struct btrfs_trans_handle *trans)
1958 {
1959         struct btrfs_fs_info *fs_info = trans->fs_info;
1960
1961         /*
1962          * We use writeback_inodes_sb here because if we used
1963          * btrfs_start_delalloc_roots we would deadlock with fs freeze.
1964          * Currently are holding the fs freeze lock, if we do an async flush
1965          * we'll do btrfs_join_transaction() and deadlock because we need to
1966          * wait for the fs freeze lock.  Using the direct flushing we benefit
1967          * from already being in a transaction and our join_transaction doesn't
1968          * have to re-take the fs freeze lock.
1969          */
1970         if (btrfs_test_opt(fs_info, FLUSHONCOMMIT)) {
1971                 writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
1972         } else {
1973                 struct btrfs_pending_snapshot *pending;
1974                 struct list_head *head = &trans->transaction->pending_snapshots;
1975
1976                 /*
1977                  * Flush dellaloc for any root that is going to be snapshotted.
1978                  * This is done to avoid a corrupted version of files, in the
1979                  * snapshots, that had both buffered and direct IO writes (even
1980                  * if they were done sequentially) due to an unordered update of
1981                  * the inode's size on disk.
1982                  */
1983                 list_for_each_entry(pending, head, list) {
1984                         int ret;
1985
1986                         ret = btrfs_start_delalloc_snapshot(pending->root);
1987                         if (ret)
1988                                 return ret;
1989                 }
1990         }
1991         return 0;
1992 }
1993
1994 static inline void btrfs_wait_delalloc_flush(struct btrfs_trans_handle *trans)
1995 {
1996         struct btrfs_fs_info *fs_info = trans->fs_info;
1997
1998         if (btrfs_test_opt(fs_info, FLUSHONCOMMIT)) {
1999                 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
2000         } else {
2001                 struct btrfs_pending_snapshot *pending;
2002                 struct list_head *head = &trans->transaction->pending_snapshots;
2003
2004                 /*
2005                  * Wait for any dellaloc that we started previously for the roots
2006                  * that are going to be snapshotted. This is to avoid a corrupted
2007                  * version of files in the snapshots that had both buffered and
2008                  * direct IO writes (even if they were done sequentially).
2009                  */
2010                 list_for_each_entry(pending, head, list)
2011                         btrfs_wait_ordered_extents(pending->root,
2012                                                    U64_MAX, 0, U64_MAX);
2013         }
2014 }
2015
2016 int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
2017 {
2018         struct btrfs_fs_info *fs_info = trans->fs_info;
2019         struct btrfs_transaction *cur_trans = trans->transaction;
2020         struct btrfs_transaction *prev_trans = NULL;
2021         int ret;
2022
2023         ASSERT(refcount_read(&trans->use_count) == 1);
2024
2025         /*
2026          * Some places just start a transaction to commit it.  We need to make
2027          * sure that if this commit fails that the abort code actually marks the
2028          * transaction as failed, so set trans->dirty to make the abort code do
2029          * the right thing.
2030          */
2031         trans->dirty = true;
2032
2033         /* Stop the commit early if ->aborted is set */
2034         if (TRANS_ABORTED(cur_trans)) {
2035                 ret = cur_trans->aborted;
2036                 btrfs_end_transaction(trans);
2037                 return ret;
2038         }
2039
2040         btrfs_trans_release_metadata(trans);
2041         trans->block_rsv = NULL;
2042
2043         /* make a pass through all the delayed refs we have so far
2044          * any runnings procs may add more while we are here
2045          */
2046         ret = btrfs_run_delayed_refs(trans, 0);
2047         if (ret) {
2048                 btrfs_end_transaction(trans);
2049                 return ret;
2050         }
2051
2052         cur_trans = trans->transaction;
2053
2054         /*
2055          * set the flushing flag so procs in this transaction have to
2056          * start sending their work down.
2057          */
2058         cur_trans->delayed_refs.flushing = 1;
2059         smp_wmb();
2060
2061         btrfs_create_pending_block_groups(trans);
2062
2063         ret = btrfs_run_delayed_refs(trans, 0);
2064         if (ret) {
2065                 btrfs_end_transaction(trans);
2066                 return ret;
2067         }
2068
2069         if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
2070                 int run_it = 0;
2071
2072                 /* this mutex is also taken before trying to set
2073                  * block groups readonly.  We need to make sure
2074                  * that nobody has set a block group readonly
2075                  * after a extents from that block group have been
2076                  * allocated for cache files.  btrfs_set_block_group_ro
2077                  * will wait for the transaction to commit if it
2078                  * finds BTRFS_TRANS_DIRTY_BG_RUN set.
2079                  *
2080                  * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
2081                  * only one process starts all the block group IO.  It wouldn't
2082                  * hurt to have more than one go through, but there's no
2083                  * real advantage to it either.
2084                  */
2085                 mutex_lock(&fs_info->ro_block_group_mutex);
2086                 if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
2087                                       &cur_trans->flags))
2088                         run_it = 1;
2089                 mutex_unlock(&fs_info->ro_block_group_mutex);
2090
2091                 if (run_it) {
2092                         ret = btrfs_start_dirty_block_groups(trans);
2093                         if (ret) {
2094                                 btrfs_end_transaction(trans);
2095                                 return ret;
2096                         }
2097                 }
2098         }
2099
2100         spin_lock(&fs_info->trans_lock);
2101         if (cur_trans->state >= TRANS_STATE_COMMIT_START) {
2102                 spin_unlock(&fs_info->trans_lock);
2103                 refcount_inc(&cur_trans->use_count);
2104                 ret = btrfs_end_transaction(trans);
2105
2106                 wait_for_commit(cur_trans);
2107
2108                 if (TRANS_ABORTED(cur_trans))
2109                         ret = cur_trans->aborted;
2110
2111                 btrfs_put_transaction(cur_trans);
2112
2113                 return ret;
2114         }
2115
2116         cur_trans->state = TRANS_STATE_COMMIT_START;
2117         wake_up(&fs_info->transaction_blocked_wait);
2118
2119         if (cur_trans->list.prev != &fs_info->trans_list) {
2120                 prev_trans = list_entry(cur_trans->list.prev,
2121                                         struct btrfs_transaction, list);
2122                 if (prev_trans->state != TRANS_STATE_COMPLETED) {
2123                         refcount_inc(&prev_trans->use_count);
2124                         spin_unlock(&fs_info->trans_lock);
2125
2126                         wait_for_commit(prev_trans);
2127                         ret = READ_ONCE(prev_trans->aborted);
2128
2129                         btrfs_put_transaction(prev_trans);
2130                         if (ret)
2131                                 goto cleanup_transaction;
2132                 } else {
2133                         spin_unlock(&fs_info->trans_lock);
2134                 }
2135         } else {
2136                 spin_unlock(&fs_info->trans_lock);
2137                 /*
2138                  * The previous transaction was aborted and was already removed
2139                  * from the list of transactions at fs_info->trans_list. So we
2140                  * abort to prevent writing a new superblock that reflects a
2141                  * corrupt state (pointing to trees with unwritten nodes/leafs).
2142                  */
2143                 if (test_bit(BTRFS_FS_STATE_TRANS_ABORTED, &fs_info->fs_state)) {
2144                         ret = -EROFS;
2145                         goto cleanup_transaction;
2146                 }
2147         }
2148
2149         extwriter_counter_dec(cur_trans, trans->type);
2150
2151         ret = btrfs_start_delalloc_flush(trans);
2152         if (ret)
2153                 goto cleanup_transaction;
2154
2155         ret = btrfs_run_delayed_items(trans);
2156         if (ret)
2157                 goto cleanup_transaction;
2158
2159         wait_event(cur_trans->writer_wait,
2160                    extwriter_counter_read(cur_trans) == 0);
2161
2162         /* some pending stuffs might be added after the previous flush. */
2163         ret = btrfs_run_delayed_items(trans);
2164         if (ret)
2165                 goto cleanup_transaction;
2166
2167         btrfs_wait_delalloc_flush(trans);
2168
2169         btrfs_scrub_pause(fs_info);
2170         /*
2171          * Ok now we need to make sure to block out any other joins while we
2172          * commit the transaction.  We could have started a join before setting
2173          * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2174          */
2175         spin_lock(&fs_info->trans_lock);
2176         cur_trans->state = TRANS_STATE_COMMIT_DOING;
2177         spin_unlock(&fs_info->trans_lock);
2178         wait_event(cur_trans->writer_wait,
2179                    atomic_read(&cur_trans->num_writers) == 1);
2180
2181         if (TRANS_ABORTED(cur_trans)) {
2182                 ret = cur_trans->aborted;
2183                 goto scrub_continue;
2184         }
2185         /*
2186          * the reloc mutex makes sure that we stop
2187          * the balancing code from coming in and moving
2188          * extents around in the middle of the commit
2189          */
2190         mutex_lock(&fs_info->reloc_mutex);
2191
2192         /*
2193          * We needn't worry about the delayed items because we will
2194          * deal with them in create_pending_snapshot(), which is the
2195          * core function of the snapshot creation.
2196          */
2197         ret = create_pending_snapshots(trans);
2198         if (ret)
2199                 goto unlock_reloc;
2200
2201         /*
2202          * We insert the dir indexes of the snapshots and update the inode
2203          * of the snapshots' parents after the snapshot creation, so there
2204          * are some delayed items which are not dealt with. Now deal with
2205          * them.
2206          *
2207          * We needn't worry that this operation will corrupt the snapshots,
2208          * because all the tree which are snapshoted will be forced to COW
2209          * the nodes and leaves.
2210          */
2211         ret = btrfs_run_delayed_items(trans);
2212         if (ret)
2213                 goto unlock_reloc;
2214
2215         ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2216         if (ret)
2217                 goto unlock_reloc;
2218
2219         /*
2220          * make sure none of the code above managed to slip in a
2221          * delayed item
2222          */
2223         btrfs_assert_delayed_root_empty(fs_info);
2224
2225         WARN_ON(cur_trans != trans->transaction);
2226
2227         /* btrfs_commit_tree_roots is responsible for getting the
2228          * various roots consistent with each other.  Every pointer
2229          * in the tree of tree roots has to point to the most up to date
2230          * root for every subvolume and other tree.  So, we have to keep
2231          * the tree logging code from jumping in and changing any
2232          * of the trees.
2233          *
2234          * At this point in the commit, there can't be any tree-log
2235          * writers, but a little lower down we drop the trans mutex
2236          * and let new people in.  By holding the tree_log_mutex
2237          * from now until after the super is written, we avoid races
2238          * with the tree-log code.
2239          */
2240         mutex_lock(&fs_info->tree_log_mutex);
2241
2242         ret = commit_fs_roots(trans);
2243         if (ret)
2244                 goto unlock_tree_log;
2245
2246         /*
2247          * Since the transaction is done, we can apply the pending changes
2248          * before the next transaction.
2249          */
2250         btrfs_apply_pending_changes(fs_info);
2251
2252         /* commit_fs_roots gets rid of all the tree log roots, it is now
2253          * safe to free the root of tree log roots
2254          */
2255         btrfs_free_log_root_tree(trans, fs_info);
2256
2257         /*
2258          * commit_fs_roots() can call btrfs_save_ino_cache(), which generates
2259          * new delayed refs. Must handle them or qgroup can be wrong.
2260          */
2261         ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2262         if (ret)
2263                 goto unlock_tree_log;
2264
2265         /*
2266          * Since fs roots are all committed, we can get a quite accurate
2267          * new_roots. So let's do quota accounting.
2268          */
2269         ret = btrfs_qgroup_account_extents(trans);
2270         if (ret < 0)
2271                 goto unlock_tree_log;
2272
2273         ret = commit_cowonly_roots(trans);
2274         if (ret)
2275                 goto unlock_tree_log;
2276
2277         /*
2278          * The tasks which save the space cache and inode cache may also
2279          * update ->aborted, check it.
2280          */
2281         if (TRANS_ABORTED(cur_trans)) {
2282                 ret = cur_trans->aborted;
2283                 goto unlock_tree_log;
2284         }
2285
2286         btrfs_prepare_extent_commit(fs_info);
2287
2288         cur_trans = fs_info->running_transaction;
2289
2290         btrfs_set_root_node(&fs_info->tree_root->root_item,
2291                             fs_info->tree_root->node);
2292         list_add_tail(&fs_info->tree_root->dirty_list,
2293                       &cur_trans->switch_commits);
2294
2295         btrfs_set_root_node(&fs_info->chunk_root->root_item,
2296                             fs_info->chunk_root->node);
2297         list_add_tail(&fs_info->chunk_root->dirty_list,
2298                       &cur_trans->switch_commits);
2299
2300         switch_commit_roots(trans);
2301
2302         ASSERT(list_empty(&cur_trans->dirty_bgs));
2303         ASSERT(list_empty(&cur_trans->io_bgs));
2304         update_super_roots(fs_info);
2305
2306         btrfs_set_super_log_root(fs_info->super_copy, 0);
2307         btrfs_set_super_log_root_level(fs_info->super_copy, 0);
2308         memcpy(fs_info->super_for_commit, fs_info->super_copy,
2309                sizeof(*fs_info->super_copy));
2310
2311         btrfs_commit_device_sizes(cur_trans);
2312
2313         clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2314         clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2315
2316         btrfs_trans_release_chunk_metadata(trans);
2317
2318         spin_lock(&fs_info->trans_lock);
2319         cur_trans->state = TRANS_STATE_UNBLOCKED;
2320         fs_info->running_transaction = NULL;
2321         spin_unlock(&fs_info->trans_lock);
2322         mutex_unlock(&fs_info->reloc_mutex);
2323
2324         wake_up(&fs_info->transaction_wait);
2325
2326         ret = btrfs_write_and_wait_transaction(trans);
2327         if (ret) {
2328                 btrfs_handle_fs_error(fs_info, ret,
2329                                       "Error while writing out transaction");
2330                 /*
2331                  * reloc_mutex has been unlocked, tree_log_mutex is still held
2332                  * but we can't jump to unlock_tree_log causing double unlock
2333                  */
2334                 mutex_unlock(&fs_info->tree_log_mutex);
2335                 goto scrub_continue;
2336         }
2337
2338         ret = write_all_supers(fs_info, 0);
2339         /*
2340          * the super is written, we can safely allow the tree-loggers
2341          * to go about their business
2342          */
2343         mutex_unlock(&fs_info->tree_log_mutex);
2344         if (ret)
2345                 goto scrub_continue;
2346
2347         btrfs_finish_extent_commit(trans);
2348
2349         if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
2350                 btrfs_clear_space_info_full(fs_info);
2351
2352         fs_info->last_trans_committed = cur_trans->transid;
2353         /*
2354          * We needn't acquire the lock here because there is no other task
2355          * which can change it.
2356          */
2357         cur_trans->state = TRANS_STATE_COMPLETED;
2358         wake_up(&cur_trans->commit_wait);
2359         clear_bit(BTRFS_FS_NEED_ASYNC_COMMIT, &fs_info->flags);
2360
2361         spin_lock(&fs_info->trans_lock);
2362         list_del_init(&cur_trans->list);
2363         spin_unlock(&fs_info->trans_lock);
2364
2365         btrfs_put_transaction(cur_trans);
2366         btrfs_put_transaction(cur_trans);
2367
2368         if (trans->type & __TRANS_FREEZABLE)
2369                 sb_end_intwrite(fs_info->sb);
2370
2371         trace_btrfs_transaction_commit(trans->root);
2372
2373         btrfs_scrub_continue(fs_info);
2374
2375         if (current->journal_info == trans)
2376                 current->journal_info = NULL;
2377
2378         kmem_cache_free(btrfs_trans_handle_cachep, trans);
2379
2380         return ret;
2381
2382 unlock_tree_log:
2383         mutex_unlock(&fs_info->tree_log_mutex);
2384 unlock_reloc:
2385         mutex_unlock(&fs_info->reloc_mutex);
2386 scrub_continue:
2387         btrfs_scrub_continue(fs_info);
2388 cleanup_transaction:
2389         btrfs_trans_release_metadata(trans);
2390         btrfs_cleanup_pending_block_groups(trans);
2391         btrfs_trans_release_chunk_metadata(trans);
2392         trans->block_rsv = NULL;
2393         btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
2394         if (current->journal_info == trans)
2395                 current->journal_info = NULL;
2396         cleanup_transaction(trans, ret);
2397
2398         return ret;
2399 }
2400
2401 /*
2402  * return < 0 if error
2403  * 0 if there are no more dead_roots at the time of call
2404  * 1 there are more to be processed, call me again
2405  *
2406  * The return value indicates there are certainly more snapshots to delete, but
2407  * if there comes a new one during processing, it may return 0. We don't mind,
2408  * because btrfs_commit_super will poke cleaner thread and it will process it a
2409  * few seconds later.
2410  */
2411 int btrfs_clean_one_deleted_snapshot(struct btrfs_root *root)
2412 {
2413         int ret;
2414         struct btrfs_fs_info *fs_info = root->fs_info;
2415
2416         spin_lock(&fs_info->trans_lock);
2417         if (list_empty(&fs_info->dead_roots)) {
2418                 spin_unlock(&fs_info->trans_lock);
2419                 return 0;
2420         }
2421         root = list_first_entry(&fs_info->dead_roots,
2422                         struct btrfs_root, root_list);
2423         list_del_init(&root->root_list);
2424         spin_unlock(&fs_info->trans_lock);
2425
2426         btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
2427
2428         btrfs_kill_all_delayed_nodes(root);
2429         if (root->ino_cache_inode) {
2430                 iput(root->ino_cache_inode);
2431                 root->ino_cache_inode = NULL;
2432         }
2433
2434         if (btrfs_header_backref_rev(root->node) <
2435                         BTRFS_MIXED_BACKREF_REV)
2436                 ret = btrfs_drop_snapshot(root, 0, 0);
2437         else
2438                 ret = btrfs_drop_snapshot(root, 1, 0);
2439
2440         btrfs_put_root(root);
2441         return (ret < 0) ? 0 : 1;
2442 }
2443
2444 void btrfs_apply_pending_changes(struct btrfs_fs_info *fs_info)
2445 {
2446         unsigned long prev;
2447         unsigned long bit;
2448
2449         prev = xchg(&fs_info->pending_changes, 0);
2450         if (!prev)
2451                 return;
2452
2453         bit = 1 << BTRFS_PENDING_SET_INODE_MAP_CACHE;
2454         if (prev & bit)
2455                 btrfs_set_opt(fs_info->mount_opt, INODE_MAP_CACHE);
2456         prev &= ~bit;
2457
2458         bit = 1 << BTRFS_PENDING_CLEAR_INODE_MAP_CACHE;
2459         if (prev & bit)
2460                 btrfs_clear_opt(fs_info->mount_opt, INODE_MAP_CACHE);
2461         prev &= ~bit;
2462
2463         bit = 1 << BTRFS_PENDING_COMMIT;
2464         if (prev & bit)
2465                 btrfs_debug(fs_info, "pending commit done");
2466         prev &= ~bit;
2467
2468         if (prev)
2469                 btrfs_warn(fs_info,
2470                         "unknown pending changes left 0x%lx, ignoring", prev);
2471 }