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