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 #define BTRFS_ROOT_TRANS_TAG 0
31 * Transaction states and transitions
33 * No running transaction (fs tree blocks are not modified)
36 * | Call start_transaction() variants. Except btrfs_join_transaction_nostart().
38 * Transaction N [[TRANS_STATE_RUNNING]]
40 * | New trans handles can be attached to transaction N by calling all
41 * | start_transaction() variants.
44 * | Call btrfs_commit_transaction() on any trans handle attached to
47 * Transaction N [[TRANS_STATE_COMMIT_START]]
49 * | Will wait for previous running transaction to completely finish if there
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.
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
64 * | Caller is chosen to commit transaction N, and all other trans handle
65 * | haven been released.
67 * Transaction N [[TRANS_STATE_COMMIT_DOING]]
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
75 * | At this stage, all start_transaction() calls will wait for this
76 * | transaction to finish and attach to transaction N+1.
79 * | Until all supporting trees are updated.
81 * Transaction N [[TRANS_STATE_UNBLOCKED]]
83 * | All needed trees are modified, thus we only [[TRANS_STATE_RUNNING]]
84 * | need to write them back to disk and update |
87 * | At this stage, new transaction is allowed to |
89 * | All new start_transaction() calls will be |
90 * | attached to transid N+1. |
93 * | Until all tree blocks are super blocks are |
94 * | written to block devices |
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
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 |
107 __TRANS_JOIN_NOSTART),
108 [TRANS_STATE_UNBLOCKED] = (__TRANS_START |
111 __TRANS_JOIN_NOLOCK |
112 __TRANS_JOIN_NOSTART),
113 [TRANS_STATE_SUPER_COMMITTED] = (__TRANS_START |
116 __TRANS_JOIN_NOLOCK |
117 __TRANS_JOIN_NOSTART),
118 [TRANS_STATE_COMPLETED] = (__TRANS_START |
121 __TRANS_JOIN_NOLOCK |
122 __TRANS_JOIN_NOSTART),
125 void btrfs_put_transaction(struct btrfs_transaction *transaction)
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);
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.
145 while (!list_empty(&transaction->deleted_bgs)) {
146 struct btrfs_block_group *cache;
148 cache = list_first_entry(&transaction->deleted_bgs,
149 struct btrfs_block_group,
151 list_del_init(&cache->bg_list);
152 btrfs_unfreeze_block_group(cache);
153 btrfs_put_block_group(cache);
155 WARN_ON(!list_empty(&transaction->dev_update_list));
160 static noinline void switch_commit_roots(struct btrfs_trans_handle *trans)
162 struct btrfs_transaction *cur_trans = trans->transaction;
163 struct btrfs_fs_info *fs_info = trans->fs_info;
164 struct btrfs_root *root, *tmp;
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.
170 ASSERT(cur_trans->state == TRANS_STATE_COMMIT_DOING);
172 down_write(&fs_info->commit_root_sem);
174 if (test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
175 fs_info->last_reloc_trans = trans->transid;
177 list_for_each_entry_safe(root, tmp, &cur_trans->switch_commits,
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);
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);
197 spin_unlock(&cur_trans->dropped_roots_lock);
199 up_write(&fs_info->commit_root_sem);
202 static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
205 if (type & TRANS_EXTWRITERS)
206 atomic_inc(&trans->num_extwriters);
209 static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
212 if (type & TRANS_EXTWRITERS)
213 atomic_dec(&trans->num_extwriters);
216 static inline void extwriter_counter_init(struct btrfs_transaction *trans,
219 atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
222 static inline int extwriter_counter_read(struct btrfs_transaction *trans)
224 return atomic_read(&trans->num_extwriters);
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.
234 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
236 struct btrfs_fs_info *fs_info = trans->fs_info;
238 if (!trans->chunk_bytes_reserved)
241 btrfs_block_rsv_release(fs_info, &fs_info->chunk_block_rsv,
242 trans->chunk_bytes_reserved, NULL);
243 trans->chunk_bytes_reserved = 0;
247 * either allocate a new transaction or hop into the existing one
249 static noinline int join_transaction(struct btrfs_fs_info *fs_info,
252 struct btrfs_transaction *cur_trans;
254 spin_lock(&fs_info->trans_lock);
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);
262 cur_trans = fs_info->running_transaction;
264 if (TRANS_ABORTED(cur_trans)) {
265 spin_unlock(&fs_info->trans_lock);
266 return cur_trans->aborted;
268 if (btrfs_blocked_trans_types[cur_trans->state] & type) {
269 spin_unlock(&fs_info->trans_lock);
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);
280 spin_unlock(&fs_info->trans_lock);
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
287 if (type == TRANS_ATTACH || type == TRANS_JOIN_NOSTART)
291 * JOIN_NOLOCK only happens during the transaction commit, so
292 * it is impossible that ->running_transaction is NULL
294 BUG_ON(type == TRANS_JOIN_NOLOCK);
296 cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
300 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_writers);
301 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_extwriters);
303 spin_lock(&fs_info->trans_lock);
304 if (fs_info->running_transaction) {
306 * someone started a transaction after we unlocked. Make sure
307 * to redo the checks above
309 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
310 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
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);
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;
330 * One for this trans handle, one so it will live on until we
331 * commit the transaction.
333 refcount_set(&cur_trans->use_count, 2);
334 cur_trans->flags = 0;
335 cur_trans->start_time = ktime_get_seconds();
337 memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
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);
344 * although the tree mod log is per file system and not per transaction,
345 * the log must never go across transaction boundaries.
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);
354 spin_lock_init(&cur_trans->delayed_refs.lock);
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);
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.
388 static int record_root_in_trans(struct btrfs_trans_handle *trans,
389 struct btrfs_root *root,
392 struct btrfs_fs_info *fs_info = root->fs_info;
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);
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
404 set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
406 /* make sure readers find IN_TRANS_SETUP before
407 * they find our root->last_trans update
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);
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;
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
427 * Normally we'd use root->last_trans as a flag to decide
428 * if we want to take the expensive mutex.
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.
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
441 ret = btrfs_init_reloc_root(trans, root);
442 smp_mb__before_atomic();
443 clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
449 void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
450 struct btrfs_root *root)
452 struct btrfs_fs_info *fs_info = root->fs_info;
453 struct btrfs_transaction *cur_trans = trans->transaction;
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);
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);
468 int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
469 struct btrfs_root *root)
471 struct btrfs_fs_info *fs_info = root->fs_info;
474 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
478 * see record_root_in_trans for comments about IN_TRANS_SETUP usage
482 if (root->last_trans == trans->transid &&
483 !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
486 mutex_lock(&fs_info->reloc_mutex);
487 ret = record_root_in_trans(trans, root, 0);
488 mutex_unlock(&fs_info->reloc_mutex);
493 static inline int is_transaction_blocked(struct btrfs_transaction *trans)
495 return (trans->state >= TRANS_STATE_COMMIT_START &&
496 trans->state < TRANS_STATE_UNBLOCKED &&
497 !TRANS_ABORTED(trans));
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.
504 static void wait_current_trans(struct btrfs_fs_info *fs_info)
506 struct btrfs_transaction *cur_trans;
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);
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);
520 spin_unlock(&fs_info->trans_lock);
524 static int may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
526 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
529 if (type == TRANS_START)
535 static inline bool need_reserve_reloc_root(struct btrfs_root *root)
537 struct btrfs_fs_info *fs_info = root->fs_info;
539 if (!fs_info->reloc_ctl ||
540 !test_bit(BTRFS_ROOT_SHAREABLE, &root->state) ||
541 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
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)
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;
558 u64 qgroup_reserved = 0;
559 bool reloc_reserved = false;
560 bool do_chunk_alloc = false;
563 if (BTRFS_FS_ERROR(fs_info))
564 return ERR_PTR(-EROFS);
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;
577 * Do the reservation before we join the transaction so we can do all
578 * the appropriate flushing if need be.
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;
584 qgroup_reserved = num_items * fs_info->nodesize;
586 * Use prealloc for now, as there might be a currently running
587 * transaction that could free this reserved space prematurely
590 ret = btrfs_qgroup_reserve_meta_prealloc(root, qgroup_reserved,
591 enforce_qgroups, false);
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.
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;
610 * Do the reservation for the relocation root creation
612 if (need_reserve_reloc_root(root)) {
613 num_bytes += fs_info->nodesize;
614 reloc_reserved = true;
617 ret = btrfs_reserve_metadata_bytes(fs_info, rsv, num_bytes, flush);
620 if (delayed_refs_bytes) {
621 btrfs_migrate_to_delayed_refs_rsv(fs_info, delayed_refs_bytes);
622 num_bytes -= delayed_refs_bytes;
624 btrfs_block_rsv_add_bytes(rsv, num_bytes, true);
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)) {
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
637 ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
642 h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
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.
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().
658 if (type & __TRANS_FREEZABLE)
659 sb_start_intwrite(fs_info->sb);
661 if (may_wait_transaction(fs_info, type))
662 wait_current_trans(fs_info);
665 ret = join_transaction(fs_info, type);
667 wait_current_trans(fs_info);
668 if (unlikely(type == TRANS_ATTACH ||
669 type == TRANS_JOIN_NOSTART))
672 } while (ret == -EBUSY);
677 cur_trans = fs_info->running_transaction;
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;
685 INIT_LIST_HEAD(&h->new_bgs);
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);
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;
704 if (!current->journal_info)
705 current->journal_info = h;
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
713 if (do_chunk_alloc && num_bytes) {
714 u64 flags = h->block_rsv->space_info->flags;
716 btrfs_chunk_alloc(h, btrfs_get_alloc_profile(fs_info, flags),
717 CHUNK_ALLOC_NO_FORCE);
721 * btrfs_record_root_in_trans() needs to alloc new extents, and may
722 * call btrfs_join_transaction() while we're also starting a
725 * Thus it need to be called after current->journal_info initialized,
726 * or we can deadlock.
728 ret = btrfs_record_root_in_trans(h, root);
731 * The transaction handle is fully initialized and linked with
732 * other structures so it needs to be ended in case of errors,
735 btrfs_end_transaction(h);
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.
744 btrfs_qgroup_convert_reserved_meta(root, qgroup_reserved);
749 if (type & __TRANS_FREEZABLE)
750 sb_end_intwrite(fs_info->sb);
751 kmem_cache_free(btrfs_trans_handle_cachep, h);
754 btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
757 btrfs_qgroup_free_meta_prealloc(root, qgroup_reserved);
761 struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
762 unsigned int num_items)
764 return start_transaction(root, num_items, TRANS_START,
765 BTRFS_RESERVE_FLUSH_ALL, true);
768 struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
769 struct btrfs_root *root,
770 unsigned int num_items)
772 return start_transaction(root, num_items, TRANS_START,
773 BTRFS_RESERVE_FLUSH_ALL_STEAL, false);
776 struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
778 return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
782 struct btrfs_trans_handle *btrfs_join_transaction_spacecache(struct btrfs_root *root)
784 return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
785 BTRFS_RESERVE_NO_FLUSH, true);
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.
792 struct btrfs_trans_handle *btrfs_join_transaction_nostart(struct btrfs_root *root)
794 return start_transaction(root, 0, TRANS_JOIN_NOSTART,
795 BTRFS_RESERVE_NO_FLUSH, true);
799 * btrfs_attach_transaction() - catch the running transaction
801 * It is used when we want to commit the current the transaction, but
802 * don't want to start a new one.
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
809 * btrfs_attach_transaction_barrier()
811 struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
813 return start_transaction(root, 0, TRANS_ATTACH,
814 BTRFS_RESERVE_NO_FLUSH, true);
818 * btrfs_attach_transaction_barrier() - catch the running transaction
820 * It is similar to the above function, the difference is this one
821 * will wait for all the inactive transactions until they fully
824 struct btrfs_trans_handle *
825 btrfs_attach_transaction_barrier(struct btrfs_root *root)
827 struct btrfs_trans_handle *trans;
829 trans = start_transaction(root, 0, TRANS_ATTACH,
830 BTRFS_RESERVE_NO_FLUSH, true);
831 if (trans == ERR_PTR(-ENOENT)) {
834 ret = btrfs_wait_for_commit(root->fs_info, 0);
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)
846 struct btrfs_fs_info *fs_info = commit->fs_info;
847 u64 transid = commit->transid;
851 * At the moment this function is called with min_state either being
852 * TRANS_STATE_COMPLETED or TRANS_STATE_SUPER_COMMITTED.
854 if (min_state == TRANS_STATE_COMPLETED)
855 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
857 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
860 wait_event(commit->commit_wait, commit->state >= min_state);
862 btrfs_put_transaction(commit);
864 if (min_state < TRANS_STATE_COMPLETED)
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.
874 spin_lock(&fs_info->trans_lock);
875 commit = list_first_entry_or_null(&fs_info->trans_list,
876 struct btrfs_transaction,
878 if (!commit || commit->transid > transid) {
879 spin_unlock(&fs_info->trans_lock);
882 refcount_inc(&commit->use_count);
884 spin_unlock(&fs_info->trans_lock);
888 int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
890 struct btrfs_transaction *cur_trans = NULL, *t;
894 if (transid <= fs_info->last_trans_committed)
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) {
902 refcount_inc(&cur_trans->use_count);
906 if (t->transid > transid) {
911 spin_unlock(&fs_info->trans_lock);
914 * The specified transaction doesn't exist, or we
915 * raced with btrfs_commit_transaction
918 if (transid > fs_info->last_trans_committed)
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,
927 if (t->state >= TRANS_STATE_COMMIT_START) {
928 if (t->state == TRANS_STATE_COMPLETED)
931 refcount_inc(&cur_trans->use_count);
935 spin_unlock(&fs_info->trans_lock);
937 goto out; /* nothing committing|committed */
940 wait_for_commit(cur_trans, TRANS_STATE_COMPLETED);
941 ret = cur_trans->aborted;
942 btrfs_put_transaction(cur_trans);
947 void btrfs_throttle(struct btrfs_fs_info *fs_info)
949 wait_current_trans(fs_info);
952 static bool should_end_transaction(struct btrfs_trans_handle *trans)
954 struct btrfs_fs_info *fs_info = trans->fs_info;
956 if (btrfs_check_space_for_delayed_refs(fs_info))
959 return !!btrfs_block_rsv_check(&fs_info->global_block_rsv, 5);
962 bool btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
964 struct btrfs_transaction *cur_trans = trans->transaction;
966 if (cur_trans->state >= TRANS_STATE_COMMIT_START ||
967 test_bit(BTRFS_DELAYED_REFS_FLUSHING, &cur_trans->delayed_refs.flags))
970 return should_end_transaction(trans);
973 static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
976 struct btrfs_fs_info *fs_info = trans->fs_info;
978 if (!trans->block_rsv) {
979 ASSERT(!trans->bytes_reserved);
983 if (!trans->bytes_reserved)
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;
994 static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
997 struct btrfs_fs_info *info = trans->fs_info;
998 struct btrfs_transaction *cur_trans = trans->transaction;
1001 if (refcount_read(&trans->use_count) > 1) {
1002 refcount_dec(&trans->use_count);
1003 trans->block_rsv = trans->orig_rsv;
1007 btrfs_trans_release_metadata(trans);
1008 trans->block_rsv = NULL;
1010 btrfs_create_pending_block_groups(trans);
1012 btrfs_trans_release_chunk_metadata(trans);
1014 if (trans->type & __TRANS_FREEZABLE)
1015 sb_end_intwrite(info->sb);
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);
1022 cond_wake_up(&cur_trans->writer_wait);
1024 btrfs_lockdep_release(info, btrfs_trans_num_extwriters);
1025 btrfs_lockdep_release(info, btrfs_trans_num_writers);
1027 btrfs_put_transaction(cur_trans);
1029 if (current->journal_info == trans)
1030 current->journal_info = NULL;
1033 btrfs_run_delayed_iputs(info);
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;
1043 kmem_cache_free(btrfs_trans_handle_cachep, trans);
1047 int btrfs_end_transaction(struct btrfs_trans_handle *trans)
1049 return __btrfs_end_transaction(trans, 0);
1052 int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
1054 return __btrfs_end_transaction(trans, 1);
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
1062 int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
1063 struct extent_io_tree *dirty_pages, int mark)
1067 struct address_space *mapping = fs_info->btree_inode->i_mapping;
1068 struct extent_state *cached_state = NULL;
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;
1077 err = convert_extent_bit(dirty_pages, start, end,
1079 mark, &cached_state);
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()).
1093 if (err == -ENOMEM) {
1095 wait_writeback = true;
1098 err = filemap_fdatawrite_range(mapping, start, end);
1101 else if (wait_writeback)
1102 werr = filemap_fdatawait_range(mapping, start, end);
1103 free_extent_state(cached_state);
1104 cached_state = NULL;
1108 atomic_dec(&BTRFS_I(fs_info->btree_inode)->sync_writers);
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
1118 static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
1119 struct extent_io_tree *dirty_pages)
1123 struct address_space *mapping = fs_info->btree_inode->i_mapping;
1124 struct extent_state *cached_state = NULL;
1128 while (!find_first_extent_bit(dirty_pages, start, &start, &end,
1129 EXTENT_NEED_WAIT, &cached_state)) {
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()).
1138 err = clear_extent_bit(dirty_pages, start, end,
1139 EXTENT_NEED_WAIT, &cached_state);
1143 err = filemap_fdatawait_range(mapping, start, end);
1146 free_extent_state(cached_state);
1147 cached_state = NULL;
1156 static int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
1157 struct extent_io_tree *dirty_pages)
1159 bool errors = false;
1162 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1163 if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1171 int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
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;
1178 ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
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))
1185 if ((mark & EXTENT_NEW) &&
1186 test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
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
1199 * @trans: transaction whose dirty pages we'd like to write
1201 static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
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;
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);
1214 extent_io_tree_release(&trans->transaction->dirty_pages);
1225 * this is used to update the root pointer in the tree of tree roots.
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
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.
1234 static int update_cowonly_root(struct btrfs_trans_handle *trans,
1235 struct btrfs_root *root)
1238 u64 old_root_bytenr;
1240 struct btrfs_fs_info *fs_info = root->fs_info;
1241 struct btrfs_root *tree_root = fs_info->tree_root;
1243 old_root_used = btrfs_root_used(&root->root_item);
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))
1251 btrfs_set_root_node(&root->root_item, root->node);
1252 ret = btrfs_update_root(trans, tree_root,
1258 old_root_used = btrfs_root_used(&root->root_item);
1265 * update all the cowonly tree roots on disk
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.
1271 static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
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;
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.
1284 ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
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);
1295 ret = btrfs_run_dev_stats(trans);
1298 ret = btrfs_run_dev_replace(trans);
1301 ret = btrfs_run_qgroups(trans);
1305 ret = btrfs_setup_space_cache(trans);
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);
1317 list_add_tail(&root->dirty_list,
1318 &trans->transaction->switch_commits);
1319 ret = update_cowonly_root(trans, root);
1324 /* Now flush any delayed refs generated by updating all of the roots */
1325 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1329 while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
1330 ret = btrfs_write_dirty_block_groups(trans);
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.
1340 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1345 if (!list_empty(&fs_info->dirty_cowonly_roots))
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;
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.
1359 void btrfs_maybe_wake_unfinished_drop(struct btrfs_fs_info *fs_info)
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
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,
1371 if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state)) {
1372 spin_unlock(&fs_info->trans_lock);
1376 spin_unlock(&fs_info->trans_lock);
1378 btrfs_wake_unfinished_drop(fs_info);
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
1386 void btrfs_add_dead_root(struct btrfs_root *root)
1388 struct btrfs_fs_info *fs_info = root->fs_info;
1390 spin_lock(&fs_info->trans_lock);
1391 if (list_empty(&root->root_list)) {
1392 btrfs_grab_root(root);
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);
1398 list_add_tail(&root->root_list, &fs_info->dead_roots);
1400 spin_unlock(&fs_info->trans_lock);
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.
1407 static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
1409 struct btrfs_fs_info *fs_info = trans->fs_info;
1410 struct btrfs_root *gang[8];
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.
1418 ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1420 spin_lock(&fs_info->fs_roots_radix_lock);
1422 ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
1425 BTRFS_ROOT_TRANS_TAG);
1428 for (i = 0; i < ret; i++) {
1429 struct btrfs_root *root = gang[i];
1433 * At this point we can neither have tasks logging inodes
1434 * from a root nor trying to commit a log tree.
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);
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);
1445 btrfs_free_log(trans, root);
1446 ret2 = btrfs_update_reloc_root(trans, root);
1450 /* see comments in should_cow_block() */
1451 clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1452 smp_mb__after_atomic();
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,
1461 ret2 = btrfs_update_root(trans, fs_info->tree_root,
1466 spin_lock(&fs_info->fs_roots_radix_lock);
1467 btrfs_qgroup_free_meta_all_pertrans(root);
1470 spin_unlock(&fs_info->fs_roots_radix_lock);
1475 * defrag a given btree.
1476 * Every leaf in the btree is read and defragged.
1478 int btrfs_defrag_root(struct btrfs_root *root)
1480 struct btrfs_fs_info *info = root->fs_info;
1481 struct btrfs_trans_handle *trans;
1484 if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
1488 trans = btrfs_start_transaction(root, 0);
1489 if (IS_ERR(trans)) {
1490 ret = PTR_ERR(trans);
1494 ret = btrfs_defrag_leaves(trans, root);
1496 btrfs_end_transaction(trans);
1497 btrfs_btree_balance_dirty(info);
1500 if (btrfs_fs_closing(info) || ret != -EAGAIN)
1503 if (btrfs_defrag_cancelled(info)) {
1504 btrfs_debug(info, "defrag_root cancelled");
1509 clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
1514 * Do all special snapshot related qgroup dirty hack.
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
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,
1526 struct btrfs_fs_info *fs_info = src->fs_info;
1530 * Save some performance in the case that qgroups are not
1531 * enabled. If this check races with the ioctl, rescan will
1534 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
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
1543 ret = record_root_in_trans(trans, src, 1);
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.
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.
1558 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1560 btrfs_abort_transaction(trans, ret);
1564 ret = commit_fs_roots(trans);
1567 ret = btrfs_qgroup_account_extents(trans);
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,
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.
1589 ret = commit_cowonly_roots(trans);
1592 switch_commit_roots(trans);
1593 ret = btrfs_write_and_wait_transaction(trans);
1595 btrfs_handle_fs_error(fs_info, ret,
1596 "Error while writing out transaction for qgroup");
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
1606 ret = record_root_in_trans(trans, parent, 1);
1611 * new snapshots need to be created at a very specific time in the
1612 * transaction commit. This does the actual creation.
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.
1619 static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
1620 struct btrfs_pending_snapshot *pending)
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;
1641 unsigned int nofs_flags;
1642 struct fscrypt_name fname;
1644 ASSERT(pending->path);
1645 path = pending->path;
1647 ASSERT(pending->root_item);
1648 new_root_item = pending->root_item;
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
1655 nofs_flags = memalloc_nofs_save();
1656 pending->error = fscrypt_setup_filename(parent_inode,
1657 &pending->dentry->d_name, 0,
1659 memalloc_nofs_restore(nofs_flags);
1663 pending->error = btrfs_get_free_objectid(tree_root, &objectid);
1668 * Make qgroup to skip current new snapshot's qgroupid, as it is
1669 * accounted by later btrfs_qgroup_inherit().
1671 btrfs_set_skip_qgroup(trans, objectid);
1673 btrfs_reloc_pre_snapshot(pending, &to_reserve);
1675 if (to_reserve > 0) {
1676 pending->error = btrfs_block_rsv_add(fs_info,
1677 &pending->block_rsv,
1679 BTRFS_RESERVE_NO_FLUSH);
1681 goto clear_skip_qgroup;
1684 key.objectid = objectid;
1685 key.offset = (u64)-1;
1686 key.type = BTRFS_ROOT_ITEM_KEY;
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",
1693 trans->bytes_reserved, 1);
1694 parent_root = BTRFS_I(parent_inode)->root;
1695 ret = record_root_in_trans(trans, parent_root, 0);
1698 cur_time = current_time(parent_inode);
1701 * insert the directory item
1703 ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
1704 BUG_ON(ret); /* -ENOMEM */
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);
1718 btrfs_release_path(path);
1721 * pull in the delayed directory update
1722 * and the delayed inode item
1723 * otherwise we corrupt the FS during
1726 ret = btrfs_run_delayed_items(trans);
1727 if (ret) { /* Transaction aborted */
1728 btrfs_abort_transaction(trans, ret);
1732 ret = record_root_in_trans(trans, root, 0);
1734 btrfs_abort_transaction(trans, ret);
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);
1741 root_flags = btrfs_root_flags(new_root_item);
1742 if (pending->readonly)
1743 root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1745 root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1746 btrfs_set_root_flags(new_root_item, root_flags);
1748 btrfs_set_root_generation_v2(new_root_item,
1750 generate_random_guid(new_root_item->uuid);
1751 memcpy(new_root_item->parent_uuid, root->root_item.uuid,
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);
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);
1765 old = btrfs_lock_root_node(root);
1766 ret = btrfs_cow_block(trans, root, old, NULL, 0, &old,
1769 btrfs_tree_unlock(old);
1770 free_extent_buffer(old);
1771 btrfs_abort_transaction(trans, ret);
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);
1780 btrfs_abort_transaction(trans, ret);
1783 /* see comments in should_cow_block() */
1784 set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
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);
1794 btrfs_abort_transaction(trans, ret);
1799 * insert root back/forward references
1801 ret = btrfs_add_root_ref(trans, objectid,
1802 parent_root->root_key.objectid,
1803 btrfs_ino(BTRFS_I(parent_inode)), index,
1806 btrfs_abort_transaction(trans, ret);
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);
1819 ret = btrfs_reloc_post_snapshot(trans, pending);
1821 btrfs_abort_transaction(trans, ret);
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
1831 ret = qgroup_account_snapshot(trans, root, parent_root,
1832 pending->inherit, objectid);
1836 ret = btrfs_insert_dir_item(trans, &fname.disk_name,
1837 BTRFS_I(parent_inode), &key, BTRFS_FT_DIR,
1839 /* We have check then name at the beginning, so it is impossible. */
1840 BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
1842 btrfs_abort_transaction(trans, ret);
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));
1852 btrfs_abort_transaction(trans, ret);
1855 ret = btrfs_uuid_tree_add(trans, new_root_item->uuid,
1856 BTRFS_UUID_KEY_SUBVOL,
1859 btrfs_abort_transaction(trans, ret);
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,
1866 if (ret && ret != -EEXIST) {
1867 btrfs_abort_transaction(trans, ret);
1873 pending->error = ret;
1875 trans->block_rsv = rsv;
1876 trans->bytes_reserved = 0;
1878 btrfs_clear_skip_qgroup(trans);
1880 fscrypt_free_filename(&fname);
1882 kfree(new_root_item);
1883 pending->root_item = NULL;
1884 btrfs_free_path(path);
1885 pending->path = NULL;
1891 * create all the snapshots we've scheduled for creation
1893 static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
1895 struct btrfs_pending_snapshot *pending, *next;
1896 struct list_head *head = &trans->transaction->pending_snapshots;
1899 list_for_each_entry_safe(pending, next, head, list) {
1900 list_del(&pending->list);
1901 ret = create_pending_snapshot(trans, pending);
1908 static void update_super_roots(struct btrfs_fs_info *fs_info)
1910 struct btrfs_root_item *root_item;
1911 struct btrfs_super_block *super;
1913 super = fs_info->super_copy;
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;
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;
1932 int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1934 struct btrfs_transaction *trans;
1937 spin_lock(&info->trans_lock);
1938 trans = info->running_transaction;
1940 ret = (trans->state >= TRANS_STATE_COMMIT_START);
1941 spin_unlock(&info->trans_lock);
1945 int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1947 struct btrfs_transaction *trans;
1950 spin_lock(&info->trans_lock);
1951 trans = info->running_transaction;
1953 ret = is_transaction_blocked(trans);
1954 spin_unlock(&info->trans_lock);
1958 void btrfs_commit_transaction_async(struct btrfs_trans_handle *trans)
1960 struct btrfs_fs_info *fs_info = trans->fs_info;
1961 struct btrfs_transaction *cur_trans;
1963 /* Kick the transaction kthread. */
1964 set_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
1965 wake_up_process(fs_info->transaction_kthread);
1967 /* take transaction reference */
1968 cur_trans = trans->transaction;
1969 refcount_inc(&cur_trans->use_count);
1971 btrfs_end_transaction(trans);
1974 * Wait for the current transaction commit to start and block
1975 * subsequent transaction joins
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);
1984 static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
1986 struct btrfs_fs_info *fs_info = trans->fs_info;
1987 struct btrfs_transaction *cur_trans = trans->transaction;
1989 WARN_ON(refcount_read(&trans->use_count) > 1);
1991 btrfs_abort_transaction(trans, err);
1993 spin_lock(&fs_info->trans_lock);
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.
2000 BUG_ON(list_empty(&cur_trans->list));
2002 if (cur_trans == fs_info->running_transaction) {
2003 cur_trans->state = TRANS_STATE_COMMIT_DOING;
2004 spin_unlock(&fs_info->trans_lock);
2007 * The thread has already released the lockdep map as reader
2008 * already in btrfs_commit_transaction().
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);
2014 spin_lock(&fs_info->trans_lock);
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.
2025 list_del_init(&cur_trans->list);
2027 spin_unlock(&fs_info->trans_lock);
2029 btrfs_cleanup_one_transaction(trans->transaction, fs_info);
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);
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);
2041 trace_btrfs_transaction_commit(fs_info);
2043 if (current->journal_info == trans)
2044 current->journal_info = NULL;
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.
2057 if (!test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
2058 btrfs_scrub_cancel(fs_info);
2060 kmem_cache_free(btrfs_trans_handle_cachep, trans);
2064 * Release reserved delayed ref space of all pending block groups of the
2065 * transaction and remove them from the list
2067 static void btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle *trans)
2069 struct btrfs_fs_info *fs_info = trans->fs_info;
2070 struct btrfs_block_group *block_group, *tmp;
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);
2078 static inline int btrfs_start_delalloc_flush(struct btrfs_fs_info *fs_info)
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.
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.
2097 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2098 try_to_writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
2102 static inline void btrfs_wait_delalloc_flush(struct btrfs_fs_info *fs_info)
2104 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2105 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
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()
2116 static void add_pending_snapshot(struct btrfs_trans_handle *trans)
2118 struct btrfs_transaction *cur_trans = trans->transaction;
2120 if (!trans->pending_snapshot)
2123 lockdep_assert_held(&trans->fs_info->trans_lock);
2124 ASSERT(cur_trans->state >= TRANS_STATE_COMMIT_START);
2126 list_add(&trans->pending_snapshot->list, &cur_trans->pending_snapshots);
2129 static void update_commit_stats(struct btrfs_fs_info *fs_info, ktime_t interval)
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;
2138 int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
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;
2147 ASSERT(refcount_read(&trans->use_count) == 1);
2148 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_START);
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;
2156 btrfs_trans_release_metadata(trans);
2157 trans->block_rsv = NULL;
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.
2163 if (!test_and_set_bit(BTRFS_DELAYED_REFS_FLUSHING,
2164 &cur_trans->delayed_refs.flags)) {
2166 * Make a pass through all the delayed refs we have so far.
2167 * Any running threads may add more while we are here.
2169 ret = btrfs_run_delayed_refs(trans, 0);
2171 goto lockdep_trans_commit_start_release;
2174 btrfs_create_pending_block_groups(trans);
2176 if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
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.
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.
2192 mutex_lock(&fs_info->ro_block_group_mutex);
2193 if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
2196 mutex_unlock(&fs_info->ro_block_group_mutex);
2199 ret = btrfs_start_dirty_block_groups(trans);
2201 goto lockdep_trans_commit_start_release;
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;
2209 add_pending_snapshot(trans);
2211 spin_unlock(&fs_info->trans_lock);
2212 refcount_inc(&cur_trans->use_count);
2214 if (trans->in_fsync)
2215 want_state = TRANS_STATE_SUPER_COMMITTED;
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);
2222 if (TRANS_ABORTED(cur_trans))
2223 ret = cur_trans->aborted;
2225 btrfs_put_transaction(cur_trans);
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);
2234 if (cur_trans->list.prev != &fs_info->trans_list) {
2235 enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2237 if (trans->in_fsync)
2238 want_state = TRANS_STATE_SUPER_COMMITTED;
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);
2246 wait_for_commit(prev_trans, want_state);
2248 ret = READ_ONCE(prev_trans->aborted);
2250 btrfs_put_transaction(prev_trans);
2252 goto lockdep_release;
2254 spin_unlock(&fs_info->trans_lock);
2257 spin_unlock(&fs_info->trans_lock);
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).
2264 if (BTRFS_FS_ERROR(fs_info)) {
2266 goto lockdep_release;
2271 * Get the time spent on the work done by the commit thread and not
2272 * the time spent waiting on a previous commit
2274 start_time = ktime_get_ns();
2276 extwriter_counter_dec(cur_trans, trans->type);
2278 ret = btrfs_start_delalloc_flush(fs_info);
2280 goto lockdep_release;
2282 ret = btrfs_run_delayed_items(trans);
2284 goto lockdep_release;
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.
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);
2296 /* some pending stuffs might be added after the previous flush. */
2297 ret = btrfs_run_delayed_items(trans);
2299 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2300 goto cleanup_transaction;
2303 btrfs_wait_delalloc_flush(fs_info);
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.
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);
2314 btrfs_scrub_pause(fs_info);
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.
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);
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.
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);
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.
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);
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.
2350 clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
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;
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
2362 mutex_lock(&fs_info->reloc_mutex);
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.
2369 ret = create_pending_snapshots(trans);
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
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.
2383 ret = btrfs_run_delayed_items(trans);
2387 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2392 * make sure none of the code above managed to slip in a
2395 btrfs_assert_delayed_root_empty(fs_info);
2397 WARN_ON(cur_trans != trans->transaction);
2399 ret = commit_fs_roots(trans);
2404 * Since the transaction is done, we can apply the pending changes
2405 * before the next transaction.
2407 btrfs_apply_pending_changes(fs_info);
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
2412 btrfs_free_log_root_tree(trans, fs_info);
2415 * Since fs roots are all committed, we can get a quite accurate
2416 * new_roots. So let's do quota accounting.
2418 ret = btrfs_qgroup_account_extents(trans);
2422 ret = commit_cowonly_roots(trans);
2427 * The tasks which save the space cache and inode cache may also
2428 * update ->aborted, check it.
2430 if (TRANS_ABORTED(cur_trans)) {
2431 ret = cur_trans->aborted;
2435 cur_trans = fs_info->running_transaction;
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);
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);
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);
2454 switch_commit_roots(trans);
2456 ASSERT(list_empty(&cur_trans->dirty_bgs));
2457 ASSERT(list_empty(&cur_trans->io_bgs));
2458 update_super_roots(fs_info);
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));
2465 btrfs_commit_device_sizes(cur_trans);
2467 clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2468 clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2470 btrfs_trans_release_chunk_metadata(trans);
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.
2480 mutex_lock(&fs_info->tree_log_mutex);
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);
2488 wake_up(&fs_info->transaction_wait);
2489 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2491 ret = btrfs_write_and_wait_transaction(trans);
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;
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
2504 btrfs_free_redirty_list(cur_trans);
2506 ret = write_all_supers(fs_info, 0);
2508 * the super is written, we can safely allow the tree-loggers
2509 * to go about their business
2511 mutex_unlock(&fs_info->tree_log_mutex);
2513 goto scrub_continue;
2516 * We needn't acquire the lock here because there is no other task
2517 * which can change it.
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);
2523 btrfs_finish_extent_commit(trans);
2525 if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
2526 btrfs_clear_space_info_full(fs_info);
2528 fs_info->last_trans_committed = cur_trans->transid;
2530 * We needn't acquire the lock here because there is no other task
2531 * which can change it.
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);
2537 spin_lock(&fs_info->trans_lock);
2538 list_del_init(&cur_trans->list);
2539 spin_unlock(&fs_info->trans_lock);
2541 btrfs_put_transaction(cur_trans);
2542 btrfs_put_transaction(cur_trans);
2544 if (trans->type & __TRANS_FREEZABLE)
2545 sb_end_intwrite(fs_info->sb);
2547 trace_btrfs_transaction_commit(fs_info);
2549 interval = ktime_get_ns() - start_time;
2551 btrfs_scrub_continue(fs_info);
2553 if (current->journal_info == trans)
2554 current->journal_info = NULL;
2556 kmem_cache_free(btrfs_trans_handle_cachep, trans);
2558 update_commit_stats(fs_info, interval);
2563 mutex_unlock(&fs_info->reloc_mutex);
2564 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
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);
2582 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2583 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2584 goto cleanup_transaction;
2586 lockdep_trans_commit_start_release:
2587 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_START);
2588 btrfs_end_transaction(trans);
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
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.
2602 int btrfs_clean_one_deleted_snapshot(struct btrfs_fs_info *fs_info)
2604 struct btrfs_root *root;
2607 spin_lock(&fs_info->trans_lock);
2608 if (list_empty(&fs_info->dead_roots)) {
2609 spin_unlock(&fs_info->trans_lock);
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);
2617 btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
2619 btrfs_kill_all_delayed_nodes(root);
2621 if (btrfs_header_backref_rev(root->node) <
2622 BTRFS_MIXED_BACKREF_REV)
2623 ret = btrfs_drop_snapshot(root, 0, 0);
2625 ret = btrfs_drop_snapshot(root, 1, 0);
2627 btrfs_put_root(root);
2628 return (ret < 0) ? 0 : 1;
2631 void btrfs_apply_pending_changes(struct btrfs_fs_info *fs_info)
2636 prev = xchg(&fs_info->pending_changes, 0);
2640 bit = 1 << BTRFS_PENDING_COMMIT;
2642 btrfs_debug(fs_info, "pending commit done");
2647 "unknown pending changes left 0x%lx, ignoring", prev);