1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
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>
18 #include "transaction.h"
22 #include "dev-replace.h"
24 #include "block-group.h"
25 #include "space-info.h"
28 #include "accessors.h"
29 #include "extent-tree.h"
30 #include "root-tree.h"
33 #include "uuid-tree.h"
35 #include "relocation.h"
38 static struct kmem_cache *btrfs_trans_handle_cachep;
41 * Transaction states and transitions
43 * No running transaction (fs tree blocks are not modified)
46 * | Call start_transaction() variants. Except btrfs_join_transaction_nostart().
48 * Transaction N [[TRANS_STATE_RUNNING]]
50 * | New trans handles can be attached to transaction N by calling all
51 * | start_transaction() variants.
54 * | Call btrfs_commit_transaction() on any trans handle attached to
57 * Transaction N [[TRANS_STATE_COMMIT_PREP]]
59 * | If there are simultaneous calls to btrfs_commit_transaction() one will win
60 * | the race and the rest will wait for the winner to commit the transaction.
62 * | The winner will wait for previous running transaction to completely finish
65 * Transaction N [[TRANS_STATE_COMMIT_START]]
67 * | Then one of the following happens:
68 * | - Wait for all other trans handle holders to release.
69 * | The btrfs_commit_transaction() caller will do the commit work.
70 * | - Wait for current transaction to be committed by others.
71 * | Other btrfs_commit_transaction() caller will do the commit work.
73 * | At this stage, only btrfs_join_transaction*() variants can attach
74 * | to this running transaction.
75 * | All other variants will wait for current one to finish and attach to
79 * | Caller is chosen to commit transaction N, and all other trans handle
80 * | haven been released.
82 * Transaction N [[TRANS_STATE_COMMIT_DOING]]
84 * | The heavy lifting transaction work is started.
85 * | From running delayed refs (modifying extent tree) to creating pending
86 * | snapshots, running qgroups.
87 * | In short, modify supporting trees to reflect modifications of subvolume
90 * | At this stage, all start_transaction() calls will wait for this
91 * | transaction to finish and attach to transaction N+1.
94 * | Until all supporting trees are updated.
96 * Transaction N [[TRANS_STATE_UNBLOCKED]]
98 * | All needed trees are modified, thus we only [[TRANS_STATE_RUNNING]]
99 * | need to write them back to disk and update |
102 * | At this stage, new transaction is allowed to |
104 * | All new start_transaction() calls will be |
105 * | attached to transid N+1. |
108 * | Until all tree blocks are super blocks are |
109 * | written to block devices |
111 * Transaction N [[TRANS_STATE_COMPLETED]] V
112 * All tree blocks and super blocks are written. Transaction N+1
113 * This transaction is finished and all its [[TRANS_STATE_COMMIT_START]]
114 * data structures will be cleaned up. | Life goes on
116 static const unsigned int btrfs_blocked_trans_types[TRANS_STATE_MAX] = {
117 [TRANS_STATE_RUNNING] = 0U,
118 [TRANS_STATE_COMMIT_PREP] = 0U,
119 [TRANS_STATE_COMMIT_START] = (__TRANS_START | __TRANS_ATTACH),
120 [TRANS_STATE_COMMIT_DOING] = (__TRANS_START |
123 __TRANS_JOIN_NOSTART),
124 [TRANS_STATE_UNBLOCKED] = (__TRANS_START |
127 __TRANS_JOIN_NOLOCK |
128 __TRANS_JOIN_NOSTART),
129 [TRANS_STATE_SUPER_COMMITTED] = (__TRANS_START |
132 __TRANS_JOIN_NOLOCK |
133 __TRANS_JOIN_NOSTART),
134 [TRANS_STATE_COMPLETED] = (__TRANS_START |
137 __TRANS_JOIN_NOLOCK |
138 __TRANS_JOIN_NOSTART),
141 void btrfs_put_transaction(struct btrfs_transaction *transaction)
143 WARN_ON(refcount_read(&transaction->use_count) == 0);
144 if (refcount_dec_and_test(&transaction->use_count)) {
145 BUG_ON(!list_empty(&transaction->list));
146 WARN_ON(!RB_EMPTY_ROOT(
147 &transaction->delayed_refs.href_root.rb_root));
148 WARN_ON(!RB_EMPTY_ROOT(
149 &transaction->delayed_refs.dirty_extent_root));
150 if (transaction->delayed_refs.pending_csums)
151 btrfs_err(transaction->fs_info,
152 "pending csums is %llu",
153 transaction->delayed_refs.pending_csums);
155 * If any block groups are found in ->deleted_bgs then it's
156 * because the transaction was aborted and a commit did not
157 * happen (things failed before writing the new superblock
158 * and calling btrfs_finish_extent_commit()), so we can not
159 * discard the physical locations of the block groups.
161 while (!list_empty(&transaction->deleted_bgs)) {
162 struct btrfs_block_group *cache;
164 cache = list_first_entry(&transaction->deleted_bgs,
165 struct btrfs_block_group,
167 list_del_init(&cache->bg_list);
168 btrfs_unfreeze_block_group(cache);
169 btrfs_put_block_group(cache);
171 WARN_ON(!list_empty(&transaction->dev_update_list));
176 static noinline void switch_commit_roots(struct btrfs_trans_handle *trans)
178 struct btrfs_transaction *cur_trans = trans->transaction;
179 struct btrfs_fs_info *fs_info = trans->fs_info;
180 struct btrfs_root *root, *tmp;
183 * At this point no one can be using this transaction to modify any tree
184 * and no one can start another transaction to modify any tree either.
186 ASSERT(cur_trans->state == TRANS_STATE_COMMIT_DOING);
188 down_write(&fs_info->commit_root_sem);
190 if (test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
191 fs_info->last_reloc_trans = trans->transid;
193 list_for_each_entry_safe(root, tmp, &cur_trans->switch_commits,
195 list_del_init(&root->dirty_list);
196 free_extent_buffer(root->commit_root);
197 root->commit_root = btrfs_root_node(root);
198 extent_io_tree_release(&root->dirty_log_pages);
199 btrfs_qgroup_clean_swapped_blocks(root);
202 /* We can free old roots now. */
203 spin_lock(&cur_trans->dropped_roots_lock);
204 while (!list_empty(&cur_trans->dropped_roots)) {
205 root = list_first_entry(&cur_trans->dropped_roots,
206 struct btrfs_root, root_list);
207 list_del_init(&root->root_list);
208 spin_unlock(&cur_trans->dropped_roots_lock);
209 btrfs_free_log(trans, root);
210 btrfs_drop_and_free_fs_root(fs_info, root);
211 spin_lock(&cur_trans->dropped_roots_lock);
213 spin_unlock(&cur_trans->dropped_roots_lock);
215 up_write(&fs_info->commit_root_sem);
218 static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
221 if (type & TRANS_EXTWRITERS)
222 atomic_inc(&trans->num_extwriters);
225 static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
228 if (type & TRANS_EXTWRITERS)
229 atomic_dec(&trans->num_extwriters);
232 static inline void extwriter_counter_init(struct btrfs_transaction *trans,
235 atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
238 static inline int extwriter_counter_read(struct btrfs_transaction *trans)
240 return atomic_read(&trans->num_extwriters);
244 * To be called after doing the chunk btree updates right after allocating a new
245 * chunk (after btrfs_chunk_alloc_add_chunk_item() is called), when removing a
246 * chunk after all chunk btree updates and after finishing the second phase of
247 * chunk allocation (btrfs_create_pending_block_groups()) in case some block
248 * group had its chunk item insertion delayed to the second phase.
250 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
252 struct btrfs_fs_info *fs_info = trans->fs_info;
254 if (!trans->chunk_bytes_reserved)
257 btrfs_block_rsv_release(fs_info, &fs_info->chunk_block_rsv,
258 trans->chunk_bytes_reserved, NULL);
259 trans->chunk_bytes_reserved = 0;
263 * either allocate a new transaction or hop into the existing one
265 static noinline int join_transaction(struct btrfs_fs_info *fs_info,
268 struct btrfs_transaction *cur_trans;
270 spin_lock(&fs_info->trans_lock);
272 /* The file system has been taken offline. No new transactions. */
273 if (BTRFS_FS_ERROR(fs_info)) {
274 spin_unlock(&fs_info->trans_lock);
278 cur_trans = fs_info->running_transaction;
280 if (TRANS_ABORTED(cur_trans)) {
281 spin_unlock(&fs_info->trans_lock);
282 return cur_trans->aborted;
284 if (btrfs_blocked_trans_types[cur_trans->state] & type) {
285 spin_unlock(&fs_info->trans_lock);
288 refcount_inc(&cur_trans->use_count);
289 atomic_inc(&cur_trans->num_writers);
290 extwriter_counter_inc(cur_trans, type);
291 spin_unlock(&fs_info->trans_lock);
292 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_writers);
293 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_extwriters);
296 spin_unlock(&fs_info->trans_lock);
299 * If we are ATTACH or TRANS_JOIN_NOSTART, we just want to catch the
300 * current transaction, and commit it. If there is no transaction, just
303 if (type == TRANS_ATTACH || type == TRANS_JOIN_NOSTART)
307 * JOIN_NOLOCK only happens during the transaction commit, so
308 * it is impossible that ->running_transaction is NULL
310 BUG_ON(type == TRANS_JOIN_NOLOCK);
312 cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
316 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_writers);
317 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_extwriters);
319 spin_lock(&fs_info->trans_lock);
320 if (fs_info->running_transaction) {
322 * someone started a transaction after we unlocked. Make sure
323 * to redo the checks above
325 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
326 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
329 } else if (BTRFS_FS_ERROR(fs_info)) {
330 spin_unlock(&fs_info->trans_lock);
331 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
332 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
337 cur_trans->fs_info = fs_info;
338 atomic_set(&cur_trans->pending_ordered, 0);
339 init_waitqueue_head(&cur_trans->pending_wait);
340 atomic_set(&cur_trans->num_writers, 1);
341 extwriter_counter_init(cur_trans, type);
342 init_waitqueue_head(&cur_trans->writer_wait);
343 init_waitqueue_head(&cur_trans->commit_wait);
344 cur_trans->state = TRANS_STATE_RUNNING;
346 * One for this trans handle, one so it will live on until we
347 * commit the transaction.
349 refcount_set(&cur_trans->use_count, 2);
350 cur_trans->flags = 0;
351 cur_trans->start_time = ktime_get_seconds();
353 memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
355 cur_trans->delayed_refs.href_root = RB_ROOT_CACHED;
356 cur_trans->delayed_refs.dirty_extent_root = RB_ROOT;
357 atomic_set(&cur_trans->delayed_refs.num_entries, 0);
360 * although the tree mod log is per file system and not per transaction,
361 * the log must never go across transaction boundaries.
364 if (!list_empty(&fs_info->tree_mod_seq_list))
365 WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
366 if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
367 WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
368 atomic64_set(&fs_info->tree_mod_seq, 0);
370 spin_lock_init(&cur_trans->delayed_refs.lock);
372 INIT_LIST_HEAD(&cur_trans->pending_snapshots);
373 INIT_LIST_HEAD(&cur_trans->dev_update_list);
374 INIT_LIST_HEAD(&cur_trans->switch_commits);
375 INIT_LIST_HEAD(&cur_trans->dirty_bgs);
376 INIT_LIST_HEAD(&cur_trans->io_bgs);
377 INIT_LIST_HEAD(&cur_trans->dropped_roots);
378 mutex_init(&cur_trans->cache_write_mutex);
379 spin_lock_init(&cur_trans->dirty_bgs_lock);
380 INIT_LIST_HEAD(&cur_trans->deleted_bgs);
381 spin_lock_init(&cur_trans->dropped_roots_lock);
382 list_add_tail(&cur_trans->list, &fs_info->trans_list);
383 extent_io_tree_init(fs_info, &cur_trans->dirty_pages,
384 IO_TREE_TRANS_DIRTY_PAGES);
385 extent_io_tree_init(fs_info, &cur_trans->pinned_extents,
386 IO_TREE_FS_PINNED_EXTENTS);
387 btrfs_set_fs_generation(fs_info, fs_info->generation + 1);
388 cur_trans->transid = fs_info->generation;
389 fs_info->running_transaction = cur_trans;
390 cur_trans->aborted = 0;
391 spin_unlock(&fs_info->trans_lock);
397 * This does all the record keeping required to make sure that a shareable root
398 * is properly recorded in a given transaction. This is required to make sure
399 * the old root from before we joined the transaction is deleted when the
400 * transaction commits.
402 static int record_root_in_trans(struct btrfs_trans_handle *trans,
403 struct btrfs_root *root,
406 struct btrfs_fs_info *fs_info = root->fs_info;
409 if ((test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
410 root->last_trans < trans->transid) || force) {
411 WARN_ON(!force && root->commit_root != root->node);
414 * see below for IN_TRANS_SETUP usage rules
415 * we have the reloc mutex held now, so there
416 * is only one writer in this function
418 set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
420 /* make sure readers find IN_TRANS_SETUP before
421 * they find our root->last_trans update
425 spin_lock(&fs_info->fs_roots_radix_lock);
426 if (root->last_trans == trans->transid && !force) {
427 spin_unlock(&fs_info->fs_roots_radix_lock);
430 radix_tree_tag_set(&fs_info->fs_roots_radix,
431 (unsigned long)root->root_key.objectid,
432 BTRFS_ROOT_TRANS_TAG);
433 spin_unlock(&fs_info->fs_roots_radix_lock);
434 root->last_trans = trans->transid;
436 /* this is pretty tricky. We don't want to
437 * take the relocation lock in btrfs_record_root_in_trans
438 * unless we're really doing the first setup for this root in
441 * Normally we'd use root->last_trans as a flag to decide
442 * if we want to take the expensive mutex.
444 * But, we have to set root->last_trans before we
445 * init the relocation root, otherwise, we trip over warnings
446 * in ctree.c. The solution used here is to flag ourselves
447 * with root IN_TRANS_SETUP. When this is 1, we're still
448 * fixing up the reloc trees and everyone must wait.
450 * When this is zero, they can trust root->last_trans and fly
451 * through btrfs_record_root_in_trans without having to take the
452 * lock. smp_wmb() makes sure that all the writes above are
453 * done before we pop in the zero below
455 ret = btrfs_init_reloc_root(trans, root);
456 smp_mb__before_atomic();
457 clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
463 void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
464 struct btrfs_root *root)
466 struct btrfs_fs_info *fs_info = root->fs_info;
467 struct btrfs_transaction *cur_trans = trans->transaction;
469 /* Add ourselves to the transaction dropped list */
470 spin_lock(&cur_trans->dropped_roots_lock);
471 list_add_tail(&root->root_list, &cur_trans->dropped_roots);
472 spin_unlock(&cur_trans->dropped_roots_lock);
474 /* Make sure we don't try to update the root at commit time */
475 spin_lock(&fs_info->fs_roots_radix_lock);
476 radix_tree_tag_clear(&fs_info->fs_roots_radix,
477 (unsigned long)root->root_key.objectid,
478 BTRFS_ROOT_TRANS_TAG);
479 spin_unlock(&fs_info->fs_roots_radix_lock);
482 int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
483 struct btrfs_root *root)
485 struct btrfs_fs_info *fs_info = root->fs_info;
488 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
492 * see record_root_in_trans for comments about IN_TRANS_SETUP usage
496 if (root->last_trans == trans->transid &&
497 !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
500 mutex_lock(&fs_info->reloc_mutex);
501 ret = record_root_in_trans(trans, root, 0);
502 mutex_unlock(&fs_info->reloc_mutex);
507 static inline int is_transaction_blocked(struct btrfs_transaction *trans)
509 return (trans->state >= TRANS_STATE_COMMIT_START &&
510 trans->state < TRANS_STATE_UNBLOCKED &&
511 !TRANS_ABORTED(trans));
514 /* wait for commit against the current transaction to become unblocked
515 * when this is done, it is safe to start a new transaction, but the current
516 * transaction might not be fully on disk.
518 static void wait_current_trans(struct btrfs_fs_info *fs_info)
520 struct btrfs_transaction *cur_trans;
522 spin_lock(&fs_info->trans_lock);
523 cur_trans = fs_info->running_transaction;
524 if (cur_trans && is_transaction_blocked(cur_trans)) {
525 refcount_inc(&cur_trans->use_count);
526 spin_unlock(&fs_info->trans_lock);
528 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
529 wait_event(fs_info->transaction_wait,
530 cur_trans->state >= TRANS_STATE_UNBLOCKED ||
531 TRANS_ABORTED(cur_trans));
532 btrfs_put_transaction(cur_trans);
534 spin_unlock(&fs_info->trans_lock);
538 static int may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
540 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
543 if (type == TRANS_START)
549 static inline bool need_reserve_reloc_root(struct btrfs_root *root)
551 struct btrfs_fs_info *fs_info = root->fs_info;
553 if (!fs_info->reloc_ctl ||
554 !test_bit(BTRFS_ROOT_SHAREABLE, &root->state) ||
555 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
562 static int btrfs_reserve_trans_metadata(struct btrfs_fs_info *fs_info,
563 enum btrfs_reserve_flush_enum flush,
565 u64 *delayed_refs_bytes)
567 struct btrfs_space_info *si = fs_info->trans_block_rsv.space_info;
568 u64 bytes = num_bytes + *delayed_refs_bytes;
572 * We want to reserve all the bytes we may need all at once, so we only
573 * do 1 enospc flushing cycle per transaction start.
575 ret = btrfs_reserve_metadata_bytes(fs_info, si, bytes, flush);
578 * If we are an emergency flush, which can steal from the global block
579 * reserve, then attempt to not reserve space for the delayed refs, as
580 * we will consume space for them from the global block reserve.
582 if (ret && flush == BTRFS_RESERVE_FLUSH_ALL_STEAL) {
583 bytes -= *delayed_refs_bytes;
584 *delayed_refs_bytes = 0;
585 ret = btrfs_reserve_metadata_bytes(fs_info, si, bytes, flush);
591 static struct btrfs_trans_handle *
592 start_transaction(struct btrfs_root *root, unsigned int num_items,
593 unsigned int type, enum btrfs_reserve_flush_enum flush,
594 bool enforce_qgroups)
596 struct btrfs_fs_info *fs_info = root->fs_info;
597 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
598 struct btrfs_block_rsv *trans_rsv = &fs_info->trans_block_rsv;
599 struct btrfs_trans_handle *h;
600 struct btrfs_transaction *cur_trans;
602 u64 qgroup_reserved = 0;
603 u64 delayed_refs_bytes = 0;
604 bool reloc_reserved = false;
605 bool do_chunk_alloc = false;
608 if (BTRFS_FS_ERROR(fs_info))
609 return ERR_PTR(-EROFS);
611 if (current->journal_info) {
612 WARN_ON(type & TRANS_EXTWRITERS);
613 h = current->journal_info;
614 refcount_inc(&h->use_count);
615 WARN_ON(refcount_read(&h->use_count) > 2);
616 h->orig_rsv = h->block_rsv;
622 * Do the reservation before we join the transaction so we can do all
623 * the appropriate flushing if need be.
625 if (num_items && root != fs_info->chunk_root) {
626 qgroup_reserved = num_items * fs_info->nodesize;
628 * Use prealloc for now, as there might be a currently running
629 * transaction that could free this reserved space prematurely
632 ret = btrfs_qgroup_reserve_meta_prealloc(root, qgroup_reserved,
633 enforce_qgroups, false);
637 num_bytes = btrfs_calc_insert_metadata_size(fs_info, num_items);
639 * If we plan to insert/update/delete "num_items" from a btree,
640 * we will also generate delayed refs for extent buffers in the
641 * respective btree paths, so reserve space for the delayed refs
642 * that will be generated by the caller as it modifies btrees.
643 * Try to reserve them to avoid excessive use of the global
646 delayed_refs_bytes = btrfs_calc_delayed_ref_bytes(fs_info, num_items);
649 * Do the reservation for the relocation root creation
651 if (need_reserve_reloc_root(root)) {
652 num_bytes += fs_info->nodesize;
653 reloc_reserved = true;
656 ret = btrfs_reserve_trans_metadata(fs_info, flush, num_bytes,
657 &delayed_refs_bytes);
661 btrfs_block_rsv_add_bytes(trans_rsv, num_bytes, true);
663 if (trans_rsv->space_info->force_alloc)
664 do_chunk_alloc = true;
665 } else if (num_items == 0 && flush == BTRFS_RESERVE_FLUSH_ALL &&
666 !btrfs_block_rsv_full(delayed_refs_rsv)) {
668 * Some people call with btrfs_start_transaction(root, 0)
669 * because they can be throttled, but have some other mechanism
670 * for reserving space. We still want these guys to refill the
671 * delayed block_rsv so just add 1 items worth of reservation
674 ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
679 h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
686 * If we are JOIN_NOLOCK we're already committing a transaction and
687 * waiting on this guy, so we don't need to do the sb_start_intwrite
688 * because we're already holding a ref. We need this because we could
689 * have raced in and did an fsync() on a file which can kick a commit
690 * and then we deadlock with somebody doing a freeze.
692 * If we are ATTACH, it means we just want to catch the current
693 * transaction and commit it, so we needn't do sb_start_intwrite().
695 if (type & __TRANS_FREEZABLE)
696 sb_start_intwrite(fs_info->sb);
698 if (may_wait_transaction(fs_info, type))
699 wait_current_trans(fs_info);
702 ret = join_transaction(fs_info, type);
704 wait_current_trans(fs_info);
705 if (unlikely(type == TRANS_ATTACH ||
706 type == TRANS_JOIN_NOSTART))
709 } while (ret == -EBUSY);
714 cur_trans = fs_info->running_transaction;
716 h->transid = cur_trans->transid;
717 h->transaction = cur_trans;
718 refcount_set(&h->use_count, 1);
719 h->fs_info = root->fs_info;
722 INIT_LIST_HEAD(&h->new_bgs);
723 btrfs_init_metadata_block_rsv(fs_info, &h->delayed_rsv, BTRFS_BLOCK_RSV_DELOPS);
726 if (cur_trans->state >= TRANS_STATE_COMMIT_START &&
727 may_wait_transaction(fs_info, type)) {
728 current->journal_info = h;
729 btrfs_commit_transaction(h);
734 trace_btrfs_space_reservation(fs_info, "transaction",
735 h->transid, num_bytes, 1);
736 h->block_rsv = trans_rsv;
737 h->bytes_reserved = num_bytes;
738 if (delayed_refs_bytes > 0) {
739 trace_btrfs_space_reservation(fs_info,
740 "local_delayed_refs_rsv",
742 delayed_refs_bytes, 1);
743 h->delayed_refs_bytes_reserved = delayed_refs_bytes;
744 btrfs_block_rsv_add_bytes(&h->delayed_rsv, delayed_refs_bytes, true);
745 delayed_refs_bytes = 0;
747 h->reloc_reserved = reloc_reserved;
751 if (!current->journal_info)
752 current->journal_info = h;
755 * If the space_info is marked ALLOC_FORCE then we'll get upgraded to
756 * ALLOC_FORCE the first run through, and then we won't allocate for
757 * anybody else who races in later. We don't care about the return
760 if (do_chunk_alloc && num_bytes) {
761 u64 flags = h->block_rsv->space_info->flags;
763 btrfs_chunk_alloc(h, btrfs_get_alloc_profile(fs_info, flags),
764 CHUNK_ALLOC_NO_FORCE);
768 * btrfs_record_root_in_trans() needs to alloc new extents, and may
769 * call btrfs_join_transaction() while we're also starting a
772 * Thus it need to be called after current->journal_info initialized,
773 * or we can deadlock.
775 ret = btrfs_record_root_in_trans(h, root);
778 * The transaction handle is fully initialized and linked with
779 * other structures so it needs to be ended in case of errors,
782 btrfs_end_transaction(h);
786 * Now that we have found a transaction to be a part of, convert the
787 * qgroup reservation from prealloc to pertrans. A different transaction
788 * can't race in and free our pertrans out from under us.
791 btrfs_qgroup_convert_reserved_meta(root, qgroup_reserved);
796 if (type & __TRANS_FREEZABLE)
797 sb_end_intwrite(fs_info->sb);
798 kmem_cache_free(btrfs_trans_handle_cachep, h);
801 btrfs_block_rsv_release(fs_info, trans_rsv, num_bytes, NULL);
802 if (delayed_refs_bytes)
803 btrfs_space_info_free_bytes_may_use(fs_info, trans_rsv->space_info,
806 btrfs_qgroup_free_meta_prealloc(root, qgroup_reserved);
810 struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
811 unsigned int num_items)
813 return start_transaction(root, num_items, TRANS_START,
814 BTRFS_RESERVE_FLUSH_ALL, true);
817 struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
818 struct btrfs_root *root,
819 unsigned int num_items)
821 return start_transaction(root, num_items, TRANS_START,
822 BTRFS_RESERVE_FLUSH_ALL_STEAL, false);
825 struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
827 return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
831 struct btrfs_trans_handle *btrfs_join_transaction_spacecache(struct btrfs_root *root)
833 return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
834 BTRFS_RESERVE_NO_FLUSH, true);
838 * Similar to regular join but it never starts a transaction when none is
839 * running or when there's a running one at a state >= TRANS_STATE_UNBLOCKED.
840 * This is similar to btrfs_attach_transaction() but it allows the join to
841 * happen if the transaction commit already started but it's not yet in the
842 * "doing" phase (the state is < TRANS_STATE_COMMIT_DOING).
844 struct btrfs_trans_handle *btrfs_join_transaction_nostart(struct btrfs_root *root)
846 return start_transaction(root, 0, TRANS_JOIN_NOSTART,
847 BTRFS_RESERVE_NO_FLUSH, true);
851 * Catch the running transaction.
853 * It is used when we want to commit the current the transaction, but
854 * don't want to start a new one.
856 * Note: If this function return -ENOENT, it just means there is no
857 * running transaction. But it is possible that the inactive transaction
858 * is still in the memory, not fully on disk. If you hope there is no
859 * inactive transaction in the fs when -ENOENT is returned, you should
861 * btrfs_attach_transaction_barrier()
863 struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
865 return start_transaction(root, 0, TRANS_ATTACH,
866 BTRFS_RESERVE_NO_FLUSH, true);
870 * Catch the running transaction.
872 * It is similar to the above function, the difference is this one
873 * will wait for all the inactive transactions until they fully
876 struct btrfs_trans_handle *
877 btrfs_attach_transaction_barrier(struct btrfs_root *root)
879 struct btrfs_trans_handle *trans;
881 trans = start_transaction(root, 0, TRANS_ATTACH,
882 BTRFS_RESERVE_NO_FLUSH, true);
883 if (trans == ERR_PTR(-ENOENT)) {
886 ret = btrfs_wait_for_commit(root->fs_info, 0);
894 /* Wait for a transaction commit to reach at least the given state. */
895 static noinline void wait_for_commit(struct btrfs_transaction *commit,
896 const enum btrfs_trans_state min_state)
898 struct btrfs_fs_info *fs_info = commit->fs_info;
899 u64 transid = commit->transid;
903 * At the moment this function is called with min_state either being
904 * TRANS_STATE_COMPLETED or TRANS_STATE_SUPER_COMMITTED.
906 if (min_state == TRANS_STATE_COMPLETED)
907 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
909 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
912 wait_event(commit->commit_wait, commit->state >= min_state);
914 btrfs_put_transaction(commit);
916 if (min_state < TRANS_STATE_COMPLETED)
920 * A transaction isn't really completed until all of the
921 * previous transactions are completed, but with fsync we can
922 * end up with SUPER_COMMITTED transactions before a COMPLETED
923 * transaction. Wait for those.
926 spin_lock(&fs_info->trans_lock);
927 commit = list_first_entry_or_null(&fs_info->trans_list,
928 struct btrfs_transaction,
930 if (!commit || commit->transid > transid) {
931 spin_unlock(&fs_info->trans_lock);
934 refcount_inc(&commit->use_count);
936 spin_unlock(&fs_info->trans_lock);
940 int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
942 struct btrfs_transaction *cur_trans = NULL, *t;
946 if (transid <= btrfs_get_last_trans_committed(fs_info))
949 /* find specified transaction */
950 spin_lock(&fs_info->trans_lock);
951 list_for_each_entry(t, &fs_info->trans_list, list) {
952 if (t->transid == transid) {
954 refcount_inc(&cur_trans->use_count);
958 if (t->transid > transid) {
963 spin_unlock(&fs_info->trans_lock);
966 * The specified transaction doesn't exist, or we
967 * raced with btrfs_commit_transaction
970 if (transid > btrfs_get_last_trans_committed(fs_info))
975 /* find newest transaction that is committing | committed */
976 spin_lock(&fs_info->trans_lock);
977 list_for_each_entry_reverse(t, &fs_info->trans_list,
979 if (t->state >= TRANS_STATE_COMMIT_START) {
980 if (t->state == TRANS_STATE_COMPLETED)
983 refcount_inc(&cur_trans->use_count);
987 spin_unlock(&fs_info->trans_lock);
989 goto out; /* nothing committing|committed */
992 wait_for_commit(cur_trans, TRANS_STATE_COMPLETED);
993 ret = cur_trans->aborted;
994 btrfs_put_transaction(cur_trans);
999 void btrfs_throttle(struct btrfs_fs_info *fs_info)
1001 wait_current_trans(fs_info);
1004 bool btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
1006 struct btrfs_transaction *cur_trans = trans->transaction;
1008 if (cur_trans->state >= TRANS_STATE_COMMIT_START ||
1009 test_bit(BTRFS_DELAYED_REFS_FLUSHING, &cur_trans->delayed_refs.flags))
1012 if (btrfs_check_space_for_delayed_refs(trans->fs_info))
1015 return !!btrfs_block_rsv_check(&trans->fs_info->global_block_rsv, 50);
1018 static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
1021 struct btrfs_fs_info *fs_info = trans->fs_info;
1023 if (!trans->block_rsv) {
1024 ASSERT(!trans->bytes_reserved);
1025 ASSERT(!trans->delayed_refs_bytes_reserved);
1029 if (!trans->bytes_reserved) {
1030 ASSERT(!trans->delayed_refs_bytes_reserved);
1034 ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
1035 trace_btrfs_space_reservation(fs_info, "transaction",
1036 trans->transid, trans->bytes_reserved, 0);
1037 btrfs_block_rsv_release(fs_info, trans->block_rsv,
1038 trans->bytes_reserved, NULL);
1039 trans->bytes_reserved = 0;
1041 if (!trans->delayed_refs_bytes_reserved)
1044 trace_btrfs_space_reservation(fs_info, "local_delayed_refs_rsv",
1046 trans->delayed_refs_bytes_reserved, 0);
1047 btrfs_block_rsv_release(fs_info, &trans->delayed_rsv,
1048 trans->delayed_refs_bytes_reserved, NULL);
1049 trans->delayed_refs_bytes_reserved = 0;
1052 static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
1055 struct btrfs_fs_info *info = trans->fs_info;
1056 struct btrfs_transaction *cur_trans = trans->transaction;
1059 if (refcount_read(&trans->use_count) > 1) {
1060 refcount_dec(&trans->use_count);
1061 trans->block_rsv = trans->orig_rsv;
1065 btrfs_trans_release_metadata(trans);
1066 trans->block_rsv = NULL;
1068 btrfs_create_pending_block_groups(trans);
1070 btrfs_trans_release_chunk_metadata(trans);
1072 if (trans->type & __TRANS_FREEZABLE)
1073 sb_end_intwrite(info->sb);
1075 WARN_ON(cur_trans != info->running_transaction);
1076 WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
1077 atomic_dec(&cur_trans->num_writers);
1078 extwriter_counter_dec(cur_trans, trans->type);
1080 cond_wake_up(&cur_trans->writer_wait);
1082 btrfs_lockdep_release(info, btrfs_trans_num_extwriters);
1083 btrfs_lockdep_release(info, btrfs_trans_num_writers);
1085 btrfs_put_transaction(cur_trans);
1087 if (current->journal_info == trans)
1088 current->journal_info = NULL;
1091 btrfs_run_delayed_iputs(info);
1093 if (TRANS_ABORTED(trans) || BTRFS_FS_ERROR(info)) {
1094 wake_up_process(info->transaction_kthread);
1095 if (TRANS_ABORTED(trans))
1096 err = trans->aborted;
1101 kmem_cache_free(btrfs_trans_handle_cachep, trans);
1105 int btrfs_end_transaction(struct btrfs_trans_handle *trans)
1107 return __btrfs_end_transaction(trans, 0);
1110 int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
1112 return __btrfs_end_transaction(trans, 1);
1116 * when btree blocks are allocated, they have some corresponding bits set for
1117 * them in one of two extent_io trees. This is used to make sure all of
1118 * those extents are sent to disk but does not wait on them
1120 int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
1121 struct extent_io_tree *dirty_pages, int mark)
1125 struct address_space *mapping = fs_info->btree_inode->i_mapping;
1126 struct extent_state *cached_state = NULL;
1130 while (find_first_extent_bit(dirty_pages, start, &start, &end,
1131 mark, &cached_state)) {
1132 bool wait_writeback = false;
1134 err = convert_extent_bit(dirty_pages, start, end,
1136 mark, &cached_state);
1138 * convert_extent_bit can return -ENOMEM, which is most of the
1139 * time a temporary error. So when it happens, ignore the error
1140 * and wait for writeback of this range to finish - because we
1141 * failed to set the bit EXTENT_NEED_WAIT for the range, a call
1142 * to __btrfs_wait_marked_extents() would not know that
1143 * writeback for this range started and therefore wouldn't
1144 * wait for it to finish - we don't want to commit a
1145 * superblock that points to btree nodes/leafs for which
1146 * writeback hasn't finished yet (and without errors).
1147 * We cleanup any entries left in the io tree when committing
1148 * the transaction (through extent_io_tree_release()).
1150 if (err == -ENOMEM) {
1152 wait_writeback = true;
1155 err = filemap_fdatawrite_range(mapping, start, end);
1158 else if (wait_writeback)
1159 werr = filemap_fdatawait_range(mapping, start, end);
1160 free_extent_state(cached_state);
1161 cached_state = NULL;
1169 * when btree blocks are allocated, they have some corresponding bits set for
1170 * them in one of two extent_io trees. This is used to make sure all of
1171 * those extents are on disk for transaction or log commit. We wait
1172 * on all the pages and clear them from the dirty pages state tree
1174 static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
1175 struct extent_io_tree *dirty_pages)
1179 struct address_space *mapping = fs_info->btree_inode->i_mapping;
1180 struct extent_state *cached_state = NULL;
1184 while (find_first_extent_bit(dirty_pages, start, &start, &end,
1185 EXTENT_NEED_WAIT, &cached_state)) {
1187 * Ignore -ENOMEM errors returned by clear_extent_bit().
1188 * When committing the transaction, we'll remove any entries
1189 * left in the io tree. For a log commit, we don't remove them
1190 * after committing the log because the tree can be accessed
1191 * concurrently - we do it only at transaction commit time when
1192 * it's safe to do it (through extent_io_tree_release()).
1194 err = clear_extent_bit(dirty_pages, start, end,
1195 EXTENT_NEED_WAIT, &cached_state);
1199 err = filemap_fdatawait_range(mapping, start, end);
1202 free_extent_state(cached_state);
1203 cached_state = NULL;
1212 static int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
1213 struct extent_io_tree *dirty_pages)
1215 bool errors = false;
1218 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1219 if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1227 int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
1229 struct btrfs_fs_info *fs_info = log_root->fs_info;
1230 struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
1231 bool errors = false;
1234 ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
1236 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1237 if ((mark & EXTENT_DIRTY) &&
1238 test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1241 if ((mark & EXTENT_NEW) &&
1242 test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1251 * When btree blocks are allocated the corresponding extents are marked dirty.
1252 * This function ensures such extents are persisted on disk for transaction or
1255 * @trans: transaction whose dirty pages we'd like to write
1257 static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1261 struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
1262 struct btrfs_fs_info *fs_info = trans->fs_info;
1263 struct blk_plug plug;
1265 blk_start_plug(&plug);
1266 ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1267 blk_finish_plug(&plug);
1268 ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1270 extent_io_tree_release(&trans->transaction->dirty_pages);
1281 * this is used to update the root pointer in the tree of tree roots.
1283 * But, in the case of the extent allocation tree, updating the root
1284 * pointer may allocate blocks which may change the root of the extent
1287 * So, this loops and repeats and makes sure the cowonly root didn't
1288 * change while the root pointer was being updated in the metadata.
1290 static int update_cowonly_root(struct btrfs_trans_handle *trans,
1291 struct btrfs_root *root)
1294 u64 old_root_bytenr;
1296 struct btrfs_fs_info *fs_info = root->fs_info;
1297 struct btrfs_root *tree_root = fs_info->tree_root;
1299 old_root_used = btrfs_root_used(&root->root_item);
1302 old_root_bytenr = btrfs_root_bytenr(&root->root_item);
1303 if (old_root_bytenr == root->node->start &&
1304 old_root_used == btrfs_root_used(&root->root_item))
1307 btrfs_set_root_node(&root->root_item, root->node);
1308 ret = btrfs_update_root(trans, tree_root,
1314 old_root_used = btrfs_root_used(&root->root_item);
1321 * update all the cowonly tree roots on disk
1323 * The error handling in this function may not be obvious. Any of the
1324 * failures will cause the file system to go offline. We still need
1325 * to clean up the delayed refs.
1327 static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
1329 struct btrfs_fs_info *fs_info = trans->fs_info;
1330 struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
1331 struct list_head *io_bgs = &trans->transaction->io_bgs;
1332 struct list_head *next;
1333 struct extent_buffer *eb;
1337 * At this point no one can be using this transaction to modify any tree
1338 * and no one can start another transaction to modify any tree either.
1340 ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1342 eb = btrfs_lock_root_node(fs_info->tree_root);
1343 ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
1344 0, &eb, BTRFS_NESTING_COW);
1345 btrfs_tree_unlock(eb);
1346 free_extent_buffer(eb);
1351 ret = btrfs_run_dev_stats(trans);
1354 ret = btrfs_run_dev_replace(trans);
1357 ret = btrfs_run_qgroups(trans);
1361 ret = btrfs_setup_space_cache(trans);
1366 while (!list_empty(&fs_info->dirty_cowonly_roots)) {
1367 struct btrfs_root *root;
1368 next = fs_info->dirty_cowonly_roots.next;
1369 list_del_init(next);
1370 root = list_entry(next, struct btrfs_root, dirty_list);
1371 clear_bit(BTRFS_ROOT_DIRTY, &root->state);
1373 list_add_tail(&root->dirty_list,
1374 &trans->transaction->switch_commits);
1375 ret = update_cowonly_root(trans, root);
1380 /* Now flush any delayed refs generated by updating all of the roots */
1381 ret = btrfs_run_delayed_refs(trans, U64_MAX);
1385 while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
1386 ret = btrfs_write_dirty_block_groups(trans);
1391 * We're writing the dirty block groups, which could generate
1392 * delayed refs, which could generate more dirty block groups,
1393 * so we want to keep this flushing in this loop to make sure
1394 * everything gets run.
1396 ret = btrfs_run_delayed_refs(trans, U64_MAX);
1401 if (!list_empty(&fs_info->dirty_cowonly_roots))
1404 /* Update dev-replace pointer once everything is committed */
1405 fs_info->dev_replace.committed_cursor_left =
1406 fs_info->dev_replace.cursor_left_last_write_of_item;
1412 * If we had a pending drop we need to see if there are any others left in our
1413 * dead roots list, and if not clear our bit and wake any waiters.
1415 void btrfs_maybe_wake_unfinished_drop(struct btrfs_fs_info *fs_info)
1418 * We put the drop in progress roots at the front of the list, so if the
1419 * first entry doesn't have UNFINISHED_DROP set we can wake everybody
1422 spin_lock(&fs_info->trans_lock);
1423 if (!list_empty(&fs_info->dead_roots)) {
1424 struct btrfs_root *root = list_first_entry(&fs_info->dead_roots,
1427 if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state)) {
1428 spin_unlock(&fs_info->trans_lock);
1432 spin_unlock(&fs_info->trans_lock);
1434 btrfs_wake_unfinished_drop(fs_info);
1438 * dead roots are old snapshots that need to be deleted. This allocates
1439 * a dirty root struct and adds it into the list of dead roots that need to
1442 void btrfs_add_dead_root(struct btrfs_root *root)
1444 struct btrfs_fs_info *fs_info = root->fs_info;
1446 spin_lock(&fs_info->trans_lock);
1447 if (list_empty(&root->root_list)) {
1448 btrfs_grab_root(root);
1450 /* We want to process the partially complete drops first. */
1451 if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state))
1452 list_add(&root->root_list, &fs_info->dead_roots);
1454 list_add_tail(&root->root_list, &fs_info->dead_roots);
1456 spin_unlock(&fs_info->trans_lock);
1460 * Update each subvolume root and its relocation root, if it exists, in the tree
1461 * of tree roots. Also free log roots if they exist.
1463 static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
1465 struct btrfs_fs_info *fs_info = trans->fs_info;
1466 struct btrfs_root *gang[8];
1471 * At this point no one can be using this transaction to modify any tree
1472 * and no one can start another transaction to modify any tree either.
1474 ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1476 spin_lock(&fs_info->fs_roots_radix_lock);
1478 ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
1481 BTRFS_ROOT_TRANS_TAG);
1484 for (i = 0; i < ret; i++) {
1485 struct btrfs_root *root = gang[i];
1489 * At this point we can neither have tasks logging inodes
1490 * from a root nor trying to commit a log tree.
1492 ASSERT(atomic_read(&root->log_writers) == 0);
1493 ASSERT(atomic_read(&root->log_commit[0]) == 0);
1494 ASSERT(atomic_read(&root->log_commit[1]) == 0);
1496 radix_tree_tag_clear(&fs_info->fs_roots_radix,
1497 (unsigned long)root->root_key.objectid,
1498 BTRFS_ROOT_TRANS_TAG);
1499 spin_unlock(&fs_info->fs_roots_radix_lock);
1501 btrfs_free_log(trans, root);
1502 ret2 = btrfs_update_reloc_root(trans, root);
1506 /* see comments in should_cow_block() */
1507 clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1508 smp_mb__after_atomic();
1510 if (root->commit_root != root->node) {
1511 list_add_tail(&root->dirty_list,
1512 &trans->transaction->switch_commits);
1513 btrfs_set_root_node(&root->root_item,
1517 ret2 = btrfs_update_root(trans, fs_info->tree_root,
1522 spin_lock(&fs_info->fs_roots_radix_lock);
1523 btrfs_qgroup_free_meta_all_pertrans(root);
1526 spin_unlock(&fs_info->fs_roots_radix_lock);
1531 * Do all special snapshot related qgroup dirty hack.
1533 * Will do all needed qgroup inherit and dirty hack like switch commit
1534 * roots inside one transaction and write all btree into disk, to make
1537 static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
1538 struct btrfs_root *src,
1539 struct btrfs_root *parent,
1540 struct btrfs_qgroup_inherit *inherit,
1543 struct btrfs_fs_info *fs_info = src->fs_info;
1547 * Save some performance in the case that qgroups are not enabled. If
1548 * this check races with the ioctl, rescan will kick in anyway.
1550 if (!btrfs_qgroup_full_accounting(fs_info))
1554 * Ensure dirty @src will be committed. Or, after coming
1555 * commit_fs_roots() and switch_commit_roots(), any dirty but not
1556 * recorded root will never be updated again, causing an outdated root
1559 ret = record_root_in_trans(trans, src, 1);
1564 * btrfs_qgroup_inherit relies on a consistent view of the usage for the
1565 * src root, so we must run the delayed refs here.
1567 * However this isn't particularly fool proof, because there's no
1568 * synchronization keeping us from changing the tree after this point
1569 * before we do the qgroup_inherit, or even from making changes while
1570 * we're doing the qgroup_inherit. But that's a problem for the future,
1571 * for now flush the delayed refs to narrow the race window where the
1572 * qgroup counters could end up wrong.
1574 ret = btrfs_run_delayed_refs(trans, U64_MAX);
1576 btrfs_abort_transaction(trans, ret);
1580 ret = commit_fs_roots(trans);
1583 ret = btrfs_qgroup_account_extents(trans);
1587 /* Now qgroup are all updated, we can inherit it to new qgroups */
1588 ret = btrfs_qgroup_inherit(trans, src->root_key.objectid, dst_objectid,
1589 parent->root_key.objectid, inherit);
1594 * Now we do a simplified commit transaction, which will:
1595 * 1) commit all subvolume and extent tree
1596 * To ensure all subvolume and extent tree have a valid
1597 * commit_root to accounting later insert_dir_item()
1598 * 2) write all btree blocks onto disk
1599 * This is to make sure later btree modification will be cowed
1600 * Or commit_root can be populated and cause wrong qgroup numbers
1601 * In this simplified commit, we don't really care about other trees
1602 * like chunk and root tree, as they won't affect qgroup.
1603 * And we don't write super to avoid half committed status.
1605 ret = commit_cowonly_roots(trans);
1608 switch_commit_roots(trans);
1609 ret = btrfs_write_and_wait_transaction(trans);
1611 btrfs_handle_fs_error(fs_info, ret,
1612 "Error while writing out transaction for qgroup");
1616 * Force parent root to be updated, as we recorded it before so its
1617 * last_trans == cur_transid.
1618 * Or it won't be committed again onto disk after later
1622 ret = record_root_in_trans(trans, parent, 1);
1627 * new snapshots need to be created at a very specific time in the
1628 * transaction commit. This does the actual creation.
1631 * If the error which may affect the commitment of the current transaction
1632 * happens, we should return the error number. If the error which just affect
1633 * the creation of the pending snapshots, just return 0.
1635 static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
1636 struct btrfs_pending_snapshot *pending)
1639 struct btrfs_fs_info *fs_info = trans->fs_info;
1640 struct btrfs_key key;
1641 struct btrfs_root_item *new_root_item;
1642 struct btrfs_root *tree_root = fs_info->tree_root;
1643 struct btrfs_root *root = pending->root;
1644 struct btrfs_root *parent_root;
1645 struct btrfs_block_rsv *rsv;
1646 struct inode *parent_inode = pending->dir;
1647 struct btrfs_path *path;
1648 struct btrfs_dir_item *dir_item;
1649 struct extent_buffer *tmp;
1650 struct extent_buffer *old;
1651 struct timespec64 cur_time;
1657 unsigned int nofs_flags;
1658 struct fscrypt_name fname;
1660 ASSERT(pending->path);
1661 path = pending->path;
1663 ASSERT(pending->root_item);
1664 new_root_item = pending->root_item;
1667 * We're inside a transaction and must make sure that any potential
1668 * allocations with GFP_KERNEL in fscrypt won't recurse back to
1671 nofs_flags = memalloc_nofs_save();
1672 pending->error = fscrypt_setup_filename(parent_inode,
1673 &pending->dentry->d_name, 0,
1675 memalloc_nofs_restore(nofs_flags);
1679 pending->error = btrfs_get_free_objectid(tree_root, &objectid);
1684 * Make qgroup to skip current new snapshot's qgroupid, as it is
1685 * accounted by later btrfs_qgroup_inherit().
1687 btrfs_set_skip_qgroup(trans, objectid);
1689 btrfs_reloc_pre_snapshot(pending, &to_reserve);
1691 if (to_reserve > 0) {
1692 pending->error = btrfs_block_rsv_add(fs_info,
1693 &pending->block_rsv,
1695 BTRFS_RESERVE_NO_FLUSH);
1697 goto clear_skip_qgroup;
1700 key.objectid = objectid;
1701 key.offset = (u64)-1;
1702 key.type = BTRFS_ROOT_ITEM_KEY;
1704 rsv = trans->block_rsv;
1705 trans->block_rsv = &pending->block_rsv;
1706 trans->bytes_reserved = trans->block_rsv->reserved;
1707 trace_btrfs_space_reservation(fs_info, "transaction",
1709 trans->bytes_reserved, 1);
1710 parent_root = BTRFS_I(parent_inode)->root;
1711 ret = record_root_in_trans(trans, parent_root, 0);
1714 cur_time = current_time(parent_inode);
1717 * insert the directory item
1719 ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
1721 btrfs_abort_transaction(trans, ret);
1725 /* check if there is a file/dir which has the same name. */
1726 dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
1727 btrfs_ino(BTRFS_I(parent_inode)),
1728 &fname.disk_name, 0);
1729 if (dir_item != NULL && !IS_ERR(dir_item)) {
1730 pending->error = -EEXIST;
1731 goto dir_item_existed;
1732 } else if (IS_ERR(dir_item)) {
1733 ret = PTR_ERR(dir_item);
1734 btrfs_abort_transaction(trans, ret);
1737 btrfs_release_path(path);
1739 ret = btrfs_create_qgroup(trans, objectid);
1740 if (ret && ret != -EEXIST) {
1741 btrfs_abort_transaction(trans, ret);
1746 * pull in the delayed directory update
1747 * and the delayed inode item
1748 * otherwise we corrupt the FS during
1751 ret = btrfs_run_delayed_items(trans);
1752 if (ret) { /* Transaction aborted */
1753 btrfs_abort_transaction(trans, ret);
1757 ret = record_root_in_trans(trans, root, 0);
1759 btrfs_abort_transaction(trans, ret);
1762 btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
1763 memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
1764 btrfs_check_and_init_root_item(new_root_item);
1766 root_flags = btrfs_root_flags(new_root_item);
1767 if (pending->readonly)
1768 root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1770 root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1771 btrfs_set_root_flags(new_root_item, root_flags);
1773 btrfs_set_root_generation_v2(new_root_item,
1775 generate_random_guid(new_root_item->uuid);
1776 memcpy(new_root_item->parent_uuid, root->root_item.uuid,
1778 if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
1779 memset(new_root_item->received_uuid, 0,
1780 sizeof(new_root_item->received_uuid));
1781 memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
1782 memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
1783 btrfs_set_root_stransid(new_root_item, 0);
1784 btrfs_set_root_rtransid(new_root_item, 0);
1786 btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
1787 btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
1788 btrfs_set_root_otransid(new_root_item, trans->transid);
1790 old = btrfs_lock_root_node(root);
1791 ret = btrfs_cow_block(trans, root, old, NULL, 0, &old,
1794 btrfs_tree_unlock(old);
1795 free_extent_buffer(old);
1796 btrfs_abort_transaction(trans, ret);
1800 ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
1801 /* clean up in any case */
1802 btrfs_tree_unlock(old);
1803 free_extent_buffer(old);
1805 btrfs_abort_transaction(trans, ret);
1808 /* see comments in should_cow_block() */
1809 set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1812 btrfs_set_root_node(new_root_item, tmp);
1813 /* record when the snapshot was created in key.offset */
1814 key.offset = trans->transid;
1815 ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1816 btrfs_tree_unlock(tmp);
1817 free_extent_buffer(tmp);
1819 btrfs_abort_transaction(trans, ret);
1824 * insert root back/forward references
1826 ret = btrfs_add_root_ref(trans, objectid,
1827 parent_root->root_key.objectid,
1828 btrfs_ino(BTRFS_I(parent_inode)), index,
1831 btrfs_abort_transaction(trans, ret);
1835 key.offset = (u64)-1;
1836 pending->snap = btrfs_get_new_fs_root(fs_info, objectid, &pending->anon_dev);
1837 if (IS_ERR(pending->snap)) {
1838 ret = PTR_ERR(pending->snap);
1839 pending->snap = NULL;
1840 btrfs_abort_transaction(trans, ret);
1844 ret = btrfs_reloc_post_snapshot(trans, pending);
1846 btrfs_abort_transaction(trans, ret);
1851 * Do special qgroup accounting for snapshot, as we do some qgroup
1852 * snapshot hack to do fast snapshot.
1853 * To co-operate with that hack, we do hack again.
1854 * Or snapshot will be greatly slowed down by a subtree qgroup rescan
1856 if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_FULL)
1857 ret = qgroup_account_snapshot(trans, root, parent_root,
1858 pending->inherit, objectid);
1859 else if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE)
1860 ret = btrfs_qgroup_inherit(trans, root->root_key.objectid, objectid,
1861 parent_root->root_key.objectid, pending->inherit);
1865 ret = btrfs_insert_dir_item(trans, &fname.disk_name,
1866 BTRFS_I(parent_inode), &key, BTRFS_FT_DIR,
1868 /* We have check then name at the beginning, so it is impossible. */
1869 BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
1871 btrfs_abort_transaction(trans, ret);
1875 btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
1876 fname.disk_name.len * 2);
1877 inode_set_mtime_to_ts(parent_inode,
1878 inode_set_ctime_current(parent_inode));
1879 ret = btrfs_update_inode_fallback(trans, BTRFS_I(parent_inode));
1881 btrfs_abort_transaction(trans, ret);
1884 ret = btrfs_uuid_tree_add(trans, new_root_item->uuid,
1885 BTRFS_UUID_KEY_SUBVOL,
1888 btrfs_abort_transaction(trans, ret);
1891 if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1892 ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1893 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1895 if (ret && ret != -EEXIST) {
1896 btrfs_abort_transaction(trans, ret);
1902 pending->error = ret;
1904 trans->block_rsv = rsv;
1905 trans->bytes_reserved = 0;
1907 btrfs_clear_skip_qgroup(trans);
1909 fscrypt_free_filename(&fname);
1911 kfree(new_root_item);
1912 pending->root_item = NULL;
1913 btrfs_free_path(path);
1914 pending->path = NULL;
1920 * create all the snapshots we've scheduled for creation
1922 static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
1924 struct btrfs_pending_snapshot *pending, *next;
1925 struct list_head *head = &trans->transaction->pending_snapshots;
1928 list_for_each_entry_safe(pending, next, head, list) {
1929 list_del(&pending->list);
1930 ret = create_pending_snapshot(trans, pending);
1937 static void update_super_roots(struct btrfs_fs_info *fs_info)
1939 struct btrfs_root_item *root_item;
1940 struct btrfs_super_block *super;
1942 super = fs_info->super_copy;
1944 root_item = &fs_info->chunk_root->root_item;
1945 super->chunk_root = root_item->bytenr;
1946 super->chunk_root_generation = root_item->generation;
1947 super->chunk_root_level = root_item->level;
1949 root_item = &fs_info->tree_root->root_item;
1950 super->root = root_item->bytenr;
1951 super->generation = root_item->generation;
1952 super->root_level = root_item->level;
1953 if (btrfs_test_opt(fs_info, SPACE_CACHE))
1954 super->cache_generation = root_item->generation;
1955 else if (test_bit(BTRFS_FS_CLEANUP_SPACE_CACHE_V1, &fs_info->flags))
1956 super->cache_generation = 0;
1957 if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1958 super->uuid_tree_generation = root_item->generation;
1961 int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1963 struct btrfs_transaction *trans;
1966 spin_lock(&info->trans_lock);
1967 trans = info->running_transaction;
1969 ret = (trans->state >= TRANS_STATE_COMMIT_START);
1970 spin_unlock(&info->trans_lock);
1974 int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1976 struct btrfs_transaction *trans;
1979 spin_lock(&info->trans_lock);
1980 trans = info->running_transaction;
1982 ret = is_transaction_blocked(trans);
1983 spin_unlock(&info->trans_lock);
1987 void btrfs_commit_transaction_async(struct btrfs_trans_handle *trans)
1989 struct btrfs_fs_info *fs_info = trans->fs_info;
1990 struct btrfs_transaction *cur_trans;
1992 /* Kick the transaction kthread. */
1993 set_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
1994 wake_up_process(fs_info->transaction_kthread);
1996 /* take transaction reference */
1997 cur_trans = trans->transaction;
1998 refcount_inc(&cur_trans->use_count);
2000 btrfs_end_transaction(trans);
2003 * Wait for the current transaction commit to start and block
2004 * subsequent transaction joins
2006 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2007 wait_event(fs_info->transaction_blocked_wait,
2008 cur_trans->state >= TRANS_STATE_COMMIT_START ||
2009 TRANS_ABORTED(cur_trans));
2010 btrfs_put_transaction(cur_trans);
2013 static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
2015 struct btrfs_fs_info *fs_info = trans->fs_info;
2016 struct btrfs_transaction *cur_trans = trans->transaction;
2018 WARN_ON(refcount_read(&trans->use_count) > 1);
2020 btrfs_abort_transaction(trans, err);
2022 spin_lock(&fs_info->trans_lock);
2025 * If the transaction is removed from the list, it means this
2026 * transaction has been committed successfully, so it is impossible
2027 * to call the cleanup function.
2029 BUG_ON(list_empty(&cur_trans->list));
2031 if (cur_trans == fs_info->running_transaction) {
2032 cur_trans->state = TRANS_STATE_COMMIT_DOING;
2033 spin_unlock(&fs_info->trans_lock);
2036 * The thread has already released the lockdep map as reader
2037 * already in btrfs_commit_transaction().
2039 btrfs_might_wait_for_event(fs_info, btrfs_trans_num_writers);
2040 wait_event(cur_trans->writer_wait,
2041 atomic_read(&cur_trans->num_writers) == 1);
2043 spin_lock(&fs_info->trans_lock);
2047 * Now that we know no one else is still using the transaction we can
2048 * remove the transaction from the list of transactions. This avoids
2049 * the transaction kthread from cleaning up the transaction while some
2050 * other task is still using it, which could result in a use-after-free
2051 * on things like log trees, as it forces the transaction kthread to
2052 * wait for this transaction to be cleaned up by us.
2054 list_del_init(&cur_trans->list);
2056 spin_unlock(&fs_info->trans_lock);
2058 btrfs_cleanup_one_transaction(trans->transaction, fs_info);
2060 spin_lock(&fs_info->trans_lock);
2061 if (cur_trans == fs_info->running_transaction)
2062 fs_info->running_transaction = NULL;
2063 spin_unlock(&fs_info->trans_lock);
2065 if (trans->type & __TRANS_FREEZABLE)
2066 sb_end_intwrite(fs_info->sb);
2067 btrfs_put_transaction(cur_trans);
2068 btrfs_put_transaction(cur_trans);
2070 trace_btrfs_transaction_commit(fs_info);
2072 if (current->journal_info == trans)
2073 current->journal_info = NULL;
2076 * If relocation is running, we can't cancel scrub because that will
2077 * result in a deadlock. Before relocating a block group, relocation
2078 * pauses scrub, then starts and commits a transaction before unpausing
2079 * scrub. If the transaction commit is being done by the relocation
2080 * task or triggered by another task and the relocation task is waiting
2081 * for the commit, and we end up here due to an error in the commit
2082 * path, then calling btrfs_scrub_cancel() will deadlock, as we are
2083 * asking for scrub to stop while having it asked to be paused higher
2084 * above in relocation code.
2086 if (!test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
2087 btrfs_scrub_cancel(fs_info);
2089 kmem_cache_free(btrfs_trans_handle_cachep, trans);
2093 * Release reserved delayed ref space of all pending block groups of the
2094 * transaction and remove them from the list
2096 static void btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle *trans)
2098 struct btrfs_fs_info *fs_info = trans->fs_info;
2099 struct btrfs_block_group *block_group, *tmp;
2101 list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
2102 btrfs_dec_delayed_refs_rsv_bg_inserts(fs_info);
2103 list_del_init(&block_group->bg_list);
2107 static inline int btrfs_start_delalloc_flush(struct btrfs_fs_info *fs_info)
2110 * We use try_to_writeback_inodes_sb() here because if we used
2111 * btrfs_start_delalloc_roots we would deadlock with fs freeze.
2112 * Currently are holding the fs freeze lock, if we do an async flush
2113 * we'll do btrfs_join_transaction() and deadlock because we need to
2114 * wait for the fs freeze lock. Using the direct flushing we benefit
2115 * from already being in a transaction and our join_transaction doesn't
2116 * have to re-take the fs freeze lock.
2118 * Note that try_to_writeback_inodes_sb() will only trigger writeback
2119 * if it can read lock sb->s_umount. It will always be able to lock it,
2120 * except when the filesystem is being unmounted or being frozen, but in
2121 * those cases sync_filesystem() is called, which results in calling
2122 * writeback_inodes_sb() while holding a write lock on sb->s_umount.
2123 * Note that we don't call writeback_inodes_sb() directly, because it
2124 * will emit a warning if sb->s_umount is not locked.
2126 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2127 try_to_writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
2131 static inline void btrfs_wait_delalloc_flush(struct btrfs_fs_info *fs_info)
2133 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2134 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
2138 * Add a pending snapshot associated with the given transaction handle to the
2139 * respective handle. This must be called after the transaction commit started
2140 * and while holding fs_info->trans_lock.
2141 * This serves to guarantee a caller of btrfs_commit_transaction() that it can
2142 * safely free the pending snapshot pointer in case btrfs_commit_transaction()
2145 static void add_pending_snapshot(struct btrfs_trans_handle *trans)
2147 struct btrfs_transaction *cur_trans = trans->transaction;
2149 if (!trans->pending_snapshot)
2152 lockdep_assert_held(&trans->fs_info->trans_lock);
2153 ASSERT(cur_trans->state >= TRANS_STATE_COMMIT_PREP);
2155 list_add(&trans->pending_snapshot->list, &cur_trans->pending_snapshots);
2158 static void update_commit_stats(struct btrfs_fs_info *fs_info, ktime_t interval)
2160 fs_info->commit_stats.commit_count++;
2161 fs_info->commit_stats.last_commit_dur = interval;
2162 fs_info->commit_stats.max_commit_dur =
2163 max_t(u64, fs_info->commit_stats.max_commit_dur, interval);
2164 fs_info->commit_stats.total_commit_dur += interval;
2167 int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
2169 struct btrfs_fs_info *fs_info = trans->fs_info;
2170 struct btrfs_transaction *cur_trans = trans->transaction;
2171 struct btrfs_transaction *prev_trans = NULL;
2176 ASSERT(refcount_read(&trans->use_count) == 1);
2177 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2179 clear_bit(BTRFS_FS_NEED_TRANS_COMMIT, &fs_info->flags);
2181 /* Stop the commit early if ->aborted is set */
2182 if (TRANS_ABORTED(cur_trans)) {
2183 ret = cur_trans->aborted;
2184 goto lockdep_trans_commit_start_release;
2187 btrfs_trans_release_metadata(trans);
2188 trans->block_rsv = NULL;
2191 * We only want one transaction commit doing the flushing so we do not
2192 * waste a bunch of time on lock contention on the extent root node.
2194 if (!test_and_set_bit(BTRFS_DELAYED_REFS_FLUSHING,
2195 &cur_trans->delayed_refs.flags)) {
2197 * Make a pass through all the delayed refs we have so far.
2198 * Any running threads may add more while we are here.
2200 ret = btrfs_run_delayed_refs(trans, 0);
2202 goto lockdep_trans_commit_start_release;
2205 btrfs_create_pending_block_groups(trans);
2207 if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
2210 /* this mutex is also taken before trying to set
2211 * block groups readonly. We need to make sure
2212 * that nobody has set a block group readonly
2213 * after a extents from that block group have been
2214 * allocated for cache files. btrfs_set_block_group_ro
2215 * will wait for the transaction to commit if it
2216 * finds BTRFS_TRANS_DIRTY_BG_RUN set.
2218 * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
2219 * only one process starts all the block group IO. It wouldn't
2220 * hurt to have more than one go through, but there's no
2221 * real advantage to it either.
2223 mutex_lock(&fs_info->ro_block_group_mutex);
2224 if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
2227 mutex_unlock(&fs_info->ro_block_group_mutex);
2230 ret = btrfs_start_dirty_block_groups(trans);
2232 goto lockdep_trans_commit_start_release;
2236 spin_lock(&fs_info->trans_lock);
2237 if (cur_trans->state >= TRANS_STATE_COMMIT_PREP) {
2238 enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2240 add_pending_snapshot(trans);
2242 spin_unlock(&fs_info->trans_lock);
2243 refcount_inc(&cur_trans->use_count);
2245 if (trans->in_fsync)
2246 want_state = TRANS_STATE_SUPER_COMMITTED;
2248 btrfs_trans_state_lockdep_release(fs_info,
2249 BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2250 ret = btrfs_end_transaction(trans);
2251 wait_for_commit(cur_trans, want_state);
2253 if (TRANS_ABORTED(cur_trans))
2254 ret = cur_trans->aborted;
2256 btrfs_put_transaction(cur_trans);
2261 cur_trans->state = TRANS_STATE_COMMIT_PREP;
2262 wake_up(&fs_info->transaction_blocked_wait);
2263 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2265 if (cur_trans->list.prev != &fs_info->trans_list) {
2266 enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2268 if (trans->in_fsync)
2269 want_state = TRANS_STATE_SUPER_COMMITTED;
2271 prev_trans = list_entry(cur_trans->list.prev,
2272 struct btrfs_transaction, list);
2273 if (prev_trans->state < want_state) {
2274 refcount_inc(&prev_trans->use_count);
2275 spin_unlock(&fs_info->trans_lock);
2277 wait_for_commit(prev_trans, want_state);
2279 ret = READ_ONCE(prev_trans->aborted);
2281 btrfs_put_transaction(prev_trans);
2283 goto lockdep_release;
2284 spin_lock(&fs_info->trans_lock);
2288 * The previous transaction was aborted and was already removed
2289 * from the list of transactions at fs_info->trans_list. So we
2290 * abort to prevent writing a new superblock that reflects a
2291 * corrupt state (pointing to trees with unwritten nodes/leafs).
2293 if (BTRFS_FS_ERROR(fs_info)) {
2294 spin_unlock(&fs_info->trans_lock);
2296 goto lockdep_release;
2300 cur_trans->state = TRANS_STATE_COMMIT_START;
2301 wake_up(&fs_info->transaction_blocked_wait);
2302 spin_unlock(&fs_info->trans_lock);
2305 * Get the time spent on the work done by the commit thread and not
2306 * the time spent waiting on a previous commit
2308 start_time = ktime_get_ns();
2310 extwriter_counter_dec(cur_trans, trans->type);
2312 ret = btrfs_start_delalloc_flush(fs_info);
2314 goto lockdep_release;
2316 ret = btrfs_run_delayed_items(trans);
2318 goto lockdep_release;
2321 * The thread has started/joined the transaction thus it holds the
2322 * lockdep map as a reader. It has to release it before acquiring the
2323 * lockdep map as a writer.
2325 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2326 btrfs_might_wait_for_event(fs_info, btrfs_trans_num_extwriters);
2327 wait_event(cur_trans->writer_wait,
2328 extwriter_counter_read(cur_trans) == 0);
2330 /* some pending stuffs might be added after the previous flush. */
2331 ret = btrfs_run_delayed_items(trans);
2333 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2334 goto cleanup_transaction;
2337 btrfs_wait_delalloc_flush(fs_info);
2340 * Wait for all ordered extents started by a fast fsync that joined this
2341 * transaction. Otherwise if this transaction commits before the ordered
2342 * extents complete we lose logged data after a power failure.
2344 btrfs_might_wait_for_event(fs_info, btrfs_trans_pending_ordered);
2345 wait_event(cur_trans->pending_wait,
2346 atomic_read(&cur_trans->pending_ordered) == 0);
2348 btrfs_scrub_pause(fs_info);
2350 * Ok now we need to make sure to block out any other joins while we
2351 * commit the transaction. We could have started a join before setting
2352 * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2354 spin_lock(&fs_info->trans_lock);
2355 add_pending_snapshot(trans);
2356 cur_trans->state = TRANS_STATE_COMMIT_DOING;
2357 spin_unlock(&fs_info->trans_lock);
2360 * The thread has started/joined the transaction thus it holds the
2361 * lockdep map as a reader. It has to release it before acquiring the
2362 * lockdep map as a writer.
2364 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2365 btrfs_might_wait_for_event(fs_info, btrfs_trans_num_writers);
2366 wait_event(cur_trans->writer_wait,
2367 atomic_read(&cur_trans->num_writers) == 1);
2370 * Make lockdep happy by acquiring the state locks after
2371 * btrfs_trans_num_writers is released. If we acquired the state locks
2372 * before releasing the btrfs_trans_num_writers lock then lockdep would
2373 * complain because we did not follow the reverse order unlocking rule.
2375 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2376 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2377 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2380 * We've started the commit, clear the flag in case we were triggered to
2381 * do an async commit but somebody else started before the transaction
2382 * kthread could do the work.
2384 clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
2386 if (TRANS_ABORTED(cur_trans)) {
2387 ret = cur_trans->aborted;
2388 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2389 goto scrub_continue;
2392 * the reloc mutex makes sure that we stop
2393 * the balancing code from coming in and moving
2394 * extents around in the middle of the commit
2396 mutex_lock(&fs_info->reloc_mutex);
2399 * We needn't worry about the delayed items because we will
2400 * deal with them in create_pending_snapshot(), which is the
2401 * core function of the snapshot creation.
2403 ret = create_pending_snapshots(trans);
2408 * We insert the dir indexes of the snapshots and update the inode
2409 * of the snapshots' parents after the snapshot creation, so there
2410 * are some delayed items which are not dealt with. Now deal with
2413 * We needn't worry that this operation will corrupt the snapshots,
2414 * because all the tree which are snapshoted will be forced to COW
2415 * the nodes and leaves.
2417 ret = btrfs_run_delayed_items(trans);
2421 ret = btrfs_run_delayed_refs(trans, U64_MAX);
2426 * make sure none of the code above managed to slip in a
2429 btrfs_assert_delayed_root_empty(fs_info);
2431 WARN_ON(cur_trans != trans->transaction);
2433 ret = commit_fs_roots(trans);
2437 /* commit_fs_roots gets rid of all the tree log roots, it is now
2438 * safe to free the root of tree log roots
2440 btrfs_free_log_root_tree(trans, fs_info);
2443 * Since fs roots are all committed, we can get a quite accurate
2444 * new_roots. So let's do quota accounting.
2446 ret = btrfs_qgroup_account_extents(trans);
2450 ret = commit_cowonly_roots(trans);
2455 * The tasks which save the space cache and inode cache may also
2456 * update ->aborted, check it.
2458 if (TRANS_ABORTED(cur_trans)) {
2459 ret = cur_trans->aborted;
2463 cur_trans = fs_info->running_transaction;
2465 btrfs_set_root_node(&fs_info->tree_root->root_item,
2466 fs_info->tree_root->node);
2467 list_add_tail(&fs_info->tree_root->dirty_list,
2468 &cur_trans->switch_commits);
2470 btrfs_set_root_node(&fs_info->chunk_root->root_item,
2471 fs_info->chunk_root->node);
2472 list_add_tail(&fs_info->chunk_root->dirty_list,
2473 &cur_trans->switch_commits);
2475 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
2476 btrfs_set_root_node(&fs_info->block_group_root->root_item,
2477 fs_info->block_group_root->node);
2478 list_add_tail(&fs_info->block_group_root->dirty_list,
2479 &cur_trans->switch_commits);
2482 switch_commit_roots(trans);
2484 ASSERT(list_empty(&cur_trans->dirty_bgs));
2485 ASSERT(list_empty(&cur_trans->io_bgs));
2486 update_super_roots(fs_info);
2488 btrfs_set_super_log_root(fs_info->super_copy, 0);
2489 btrfs_set_super_log_root_level(fs_info->super_copy, 0);
2490 memcpy(fs_info->super_for_commit, fs_info->super_copy,
2491 sizeof(*fs_info->super_copy));
2493 btrfs_commit_device_sizes(cur_trans);
2495 clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2496 clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2498 btrfs_trans_release_chunk_metadata(trans);
2501 * Before changing the transaction state to TRANS_STATE_UNBLOCKED and
2502 * setting fs_info->running_transaction to NULL, lock tree_log_mutex to
2503 * make sure that before we commit our superblock, no other task can
2504 * start a new transaction and commit a log tree before we commit our
2505 * superblock. Anyone trying to commit a log tree locks this mutex before
2506 * writing its superblock.
2508 mutex_lock(&fs_info->tree_log_mutex);
2510 spin_lock(&fs_info->trans_lock);
2511 cur_trans->state = TRANS_STATE_UNBLOCKED;
2512 fs_info->running_transaction = NULL;
2513 spin_unlock(&fs_info->trans_lock);
2514 mutex_unlock(&fs_info->reloc_mutex);
2516 wake_up(&fs_info->transaction_wait);
2517 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2519 /* If we have features changed, wake up the cleaner to update sysfs. */
2520 if (test_bit(BTRFS_FS_FEATURE_CHANGED, &fs_info->flags) &&
2521 fs_info->cleaner_kthread)
2522 wake_up_process(fs_info->cleaner_kthread);
2524 ret = btrfs_write_and_wait_transaction(trans);
2526 btrfs_handle_fs_error(fs_info, ret,
2527 "Error while writing out transaction");
2528 mutex_unlock(&fs_info->tree_log_mutex);
2529 goto scrub_continue;
2532 ret = write_all_supers(fs_info, 0);
2534 * the super is written, we can safely allow the tree-loggers
2535 * to go about their business
2537 mutex_unlock(&fs_info->tree_log_mutex);
2539 goto scrub_continue;
2542 * We needn't acquire the lock here because there is no other task
2543 * which can change it.
2545 cur_trans->state = TRANS_STATE_SUPER_COMMITTED;
2546 wake_up(&cur_trans->commit_wait);
2547 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2549 btrfs_finish_extent_commit(trans);
2551 if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
2552 btrfs_clear_space_info_full(fs_info);
2554 btrfs_set_last_trans_committed(fs_info, cur_trans->transid);
2556 * We needn't acquire the lock here because there is no other task
2557 * which can change it.
2559 cur_trans->state = TRANS_STATE_COMPLETED;
2560 wake_up(&cur_trans->commit_wait);
2561 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2563 spin_lock(&fs_info->trans_lock);
2564 list_del_init(&cur_trans->list);
2565 spin_unlock(&fs_info->trans_lock);
2567 btrfs_put_transaction(cur_trans);
2568 btrfs_put_transaction(cur_trans);
2570 if (trans->type & __TRANS_FREEZABLE)
2571 sb_end_intwrite(fs_info->sb);
2573 trace_btrfs_transaction_commit(fs_info);
2575 interval = ktime_get_ns() - start_time;
2577 btrfs_scrub_continue(fs_info);
2579 if (current->journal_info == trans)
2580 current->journal_info = NULL;
2582 kmem_cache_free(btrfs_trans_handle_cachep, trans);
2584 update_commit_stats(fs_info, interval);
2589 mutex_unlock(&fs_info->reloc_mutex);
2590 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2592 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2593 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2594 btrfs_scrub_continue(fs_info);
2595 cleanup_transaction:
2596 btrfs_trans_release_metadata(trans);
2597 btrfs_cleanup_pending_block_groups(trans);
2598 btrfs_trans_release_chunk_metadata(trans);
2599 trans->block_rsv = NULL;
2600 btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
2601 if (current->journal_info == trans)
2602 current->journal_info = NULL;
2603 cleanup_transaction(trans, ret);
2608 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2609 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2610 goto cleanup_transaction;
2612 lockdep_trans_commit_start_release:
2613 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2614 btrfs_end_transaction(trans);
2619 * return < 0 if error
2620 * 0 if there are no more dead_roots at the time of call
2621 * 1 there are more to be processed, call me again
2623 * The return value indicates there are certainly more snapshots to delete, but
2624 * if there comes a new one during processing, it may return 0. We don't mind,
2625 * because btrfs_commit_super will poke cleaner thread and it will process it a
2626 * few seconds later.
2628 int btrfs_clean_one_deleted_snapshot(struct btrfs_fs_info *fs_info)
2630 struct btrfs_root *root;
2633 spin_lock(&fs_info->trans_lock);
2634 if (list_empty(&fs_info->dead_roots)) {
2635 spin_unlock(&fs_info->trans_lock);
2638 root = list_first_entry(&fs_info->dead_roots,
2639 struct btrfs_root, root_list);
2640 list_del_init(&root->root_list);
2641 spin_unlock(&fs_info->trans_lock);
2643 btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
2645 btrfs_kill_all_delayed_nodes(root);
2647 if (btrfs_header_backref_rev(root->node) <
2648 BTRFS_MIXED_BACKREF_REV)
2649 ret = btrfs_drop_snapshot(root, 0, 0);
2651 ret = btrfs_drop_snapshot(root, 1, 0);
2653 btrfs_put_root(root);
2654 return (ret < 0) ? 0 : 1;
2658 * We only mark the transaction aborted and then set the file system read-only.
2659 * This will prevent new transactions from starting or trying to join this
2662 * This means that error recovery at the call site is limited to freeing
2663 * any local memory allocations and passing the error code up without
2664 * further cleanup. The transaction should complete as it normally would
2665 * in the call path but will return -EIO.
2667 * We'll complete the cleanup in btrfs_end_transaction and
2668 * btrfs_commit_transaction.
2670 void __cold __btrfs_abort_transaction(struct btrfs_trans_handle *trans,
2671 const char *function,
2672 unsigned int line, int error, bool first_hit)
2674 struct btrfs_fs_info *fs_info = trans->fs_info;
2676 WRITE_ONCE(trans->aborted, error);
2677 WRITE_ONCE(trans->transaction->aborted, error);
2678 if (first_hit && error == -ENOSPC)
2679 btrfs_dump_space_info_for_trans_abort(fs_info);
2680 /* Wake up anybody who may be waiting on this transaction */
2681 wake_up(&fs_info->transaction_wait);
2682 wake_up(&fs_info->transaction_blocked_wait);
2683 __btrfs_handle_fs_error(fs_info, function, line, error, NULL);
2686 int __init btrfs_transaction_init(void)
2688 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
2689 sizeof(struct btrfs_trans_handle), 0,
2690 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
2691 if (!btrfs_trans_handle_cachep)
2696 void __cold btrfs_transaction_exit(void)
2698 kmem_cache_destroy(btrfs_trans_handle_cachep);