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