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 * Now that we have found a transaction to be a part of, convert the
705 * qgroup reservation from prealloc to pertrans. A different transaction
706 * can't race in and free our pertrans out from under us.
709 btrfs_qgroup_convert_reserved_meta(root, qgroup_reserved);
712 if (!current->journal_info)
713 current->journal_info = h;
716 * If the space_info is marked ALLOC_FORCE then we'll get upgraded to
717 * ALLOC_FORCE the first run through, and then we won't allocate for
718 * anybody else who races in later. We don't care about the return
721 if (do_chunk_alloc && num_bytes) {
722 u64 flags = h->block_rsv->space_info->flags;
724 btrfs_chunk_alloc(h, btrfs_get_alloc_profile(fs_info, flags),
725 CHUNK_ALLOC_NO_FORCE);
729 * btrfs_record_root_in_trans() needs to alloc new extents, and may
730 * call btrfs_join_transaction() while we're also starting a
733 * Thus it need to be called after current->journal_info initialized,
734 * or we can deadlock.
736 ret = btrfs_record_root_in_trans(h, root);
739 * The transaction handle is fully initialized and linked with
740 * other structures so it needs to be ended in case of errors,
743 btrfs_end_transaction(h);
750 if (type & __TRANS_FREEZABLE)
751 sb_end_intwrite(fs_info->sb);
752 kmem_cache_free(btrfs_trans_handle_cachep, h);
755 btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
758 btrfs_qgroup_free_meta_prealloc(root, qgroup_reserved);
762 struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
763 unsigned int num_items)
765 return start_transaction(root, num_items, TRANS_START,
766 BTRFS_RESERVE_FLUSH_ALL, true);
769 struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
770 struct btrfs_root *root,
771 unsigned int num_items)
773 return start_transaction(root, num_items, TRANS_START,
774 BTRFS_RESERVE_FLUSH_ALL_STEAL, false);
777 struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
779 return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
783 struct btrfs_trans_handle *btrfs_join_transaction_spacecache(struct btrfs_root *root)
785 return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
786 BTRFS_RESERVE_NO_FLUSH, true);
790 * Similar to regular join but it never starts a transaction when none is
791 * running or after waiting for the current one to finish.
793 struct btrfs_trans_handle *btrfs_join_transaction_nostart(struct btrfs_root *root)
795 return start_transaction(root, 0, TRANS_JOIN_NOSTART,
796 BTRFS_RESERVE_NO_FLUSH, true);
800 * btrfs_attach_transaction() - catch the running transaction
802 * It is used when we want to commit the current the transaction, but
803 * don't want to start a new one.
805 * Note: If this function return -ENOENT, it just means there is no
806 * running transaction. But it is possible that the inactive transaction
807 * is still in the memory, not fully on disk. If you hope there is no
808 * inactive transaction in the fs when -ENOENT is returned, you should
810 * btrfs_attach_transaction_barrier()
812 struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
814 return start_transaction(root, 0, TRANS_ATTACH,
815 BTRFS_RESERVE_NO_FLUSH, true);
819 * btrfs_attach_transaction_barrier() - catch the running transaction
821 * It is similar to the above function, the difference is this one
822 * will wait for all the inactive transactions until they fully
825 struct btrfs_trans_handle *
826 btrfs_attach_transaction_barrier(struct btrfs_root *root)
828 struct btrfs_trans_handle *trans;
830 trans = start_transaction(root, 0, TRANS_ATTACH,
831 BTRFS_RESERVE_NO_FLUSH, true);
832 if (trans == ERR_PTR(-ENOENT)) {
835 ret = btrfs_wait_for_commit(root->fs_info, 0);
843 /* Wait for a transaction commit to reach at least the given state. */
844 static noinline void wait_for_commit(struct btrfs_transaction *commit,
845 const enum btrfs_trans_state min_state)
847 struct btrfs_fs_info *fs_info = commit->fs_info;
848 u64 transid = commit->transid;
852 * At the moment this function is called with min_state either being
853 * TRANS_STATE_COMPLETED or TRANS_STATE_SUPER_COMMITTED.
855 if (min_state == TRANS_STATE_COMPLETED)
856 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
858 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
861 wait_event(commit->commit_wait, commit->state >= min_state);
863 btrfs_put_transaction(commit);
865 if (min_state < TRANS_STATE_COMPLETED)
869 * A transaction isn't really completed until all of the
870 * previous transactions are completed, but with fsync we can
871 * end up with SUPER_COMMITTED transactions before a COMPLETED
872 * transaction. Wait for those.
875 spin_lock(&fs_info->trans_lock);
876 commit = list_first_entry_or_null(&fs_info->trans_list,
877 struct btrfs_transaction,
879 if (!commit || commit->transid > transid) {
880 spin_unlock(&fs_info->trans_lock);
883 refcount_inc(&commit->use_count);
885 spin_unlock(&fs_info->trans_lock);
889 int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
891 struct btrfs_transaction *cur_trans = NULL, *t;
895 if (transid <= fs_info->last_trans_committed)
898 /* find specified transaction */
899 spin_lock(&fs_info->trans_lock);
900 list_for_each_entry(t, &fs_info->trans_list, list) {
901 if (t->transid == transid) {
903 refcount_inc(&cur_trans->use_count);
907 if (t->transid > transid) {
912 spin_unlock(&fs_info->trans_lock);
915 * The specified transaction doesn't exist, or we
916 * raced with btrfs_commit_transaction
919 if (transid > fs_info->last_trans_committed)
924 /* find newest transaction that is committing | committed */
925 spin_lock(&fs_info->trans_lock);
926 list_for_each_entry_reverse(t, &fs_info->trans_list,
928 if (t->state >= TRANS_STATE_COMMIT_START) {
929 if (t->state == TRANS_STATE_COMPLETED)
932 refcount_inc(&cur_trans->use_count);
936 spin_unlock(&fs_info->trans_lock);
938 goto out; /* nothing committing|committed */
941 wait_for_commit(cur_trans, TRANS_STATE_COMPLETED);
942 ret = cur_trans->aborted;
943 btrfs_put_transaction(cur_trans);
948 void btrfs_throttle(struct btrfs_fs_info *fs_info)
950 wait_current_trans(fs_info);
953 static bool should_end_transaction(struct btrfs_trans_handle *trans)
955 struct btrfs_fs_info *fs_info = trans->fs_info;
957 if (btrfs_check_space_for_delayed_refs(fs_info))
960 return !!btrfs_block_rsv_check(&fs_info->global_block_rsv, 5);
963 bool btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
965 struct btrfs_transaction *cur_trans = trans->transaction;
967 if (cur_trans->state >= TRANS_STATE_COMMIT_START ||
968 test_bit(BTRFS_DELAYED_REFS_FLUSHING, &cur_trans->delayed_refs.flags))
971 return should_end_transaction(trans);
974 static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
977 struct btrfs_fs_info *fs_info = trans->fs_info;
979 if (!trans->block_rsv) {
980 ASSERT(!trans->bytes_reserved);
984 if (!trans->bytes_reserved)
987 ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
988 trace_btrfs_space_reservation(fs_info, "transaction",
989 trans->transid, trans->bytes_reserved, 0);
990 btrfs_block_rsv_release(fs_info, trans->block_rsv,
991 trans->bytes_reserved, NULL);
992 trans->bytes_reserved = 0;
995 static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
998 struct btrfs_fs_info *info = trans->fs_info;
999 struct btrfs_transaction *cur_trans = trans->transaction;
1002 if (refcount_read(&trans->use_count) > 1) {
1003 refcount_dec(&trans->use_count);
1004 trans->block_rsv = trans->orig_rsv;
1008 btrfs_trans_release_metadata(trans);
1009 trans->block_rsv = NULL;
1011 btrfs_create_pending_block_groups(trans);
1013 btrfs_trans_release_chunk_metadata(trans);
1015 if (trans->type & __TRANS_FREEZABLE)
1016 sb_end_intwrite(info->sb);
1018 WARN_ON(cur_trans != info->running_transaction);
1019 WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
1020 atomic_dec(&cur_trans->num_writers);
1021 extwriter_counter_dec(cur_trans, trans->type);
1023 cond_wake_up(&cur_trans->writer_wait);
1025 btrfs_lockdep_release(info, btrfs_trans_num_extwriters);
1026 btrfs_lockdep_release(info, btrfs_trans_num_writers);
1028 btrfs_put_transaction(cur_trans);
1030 if (current->journal_info == trans)
1031 current->journal_info = NULL;
1034 btrfs_run_delayed_iputs(info);
1036 if (TRANS_ABORTED(trans) || BTRFS_FS_ERROR(info)) {
1037 wake_up_process(info->transaction_kthread);
1038 if (TRANS_ABORTED(trans))
1039 err = trans->aborted;
1044 kmem_cache_free(btrfs_trans_handle_cachep, trans);
1048 int btrfs_end_transaction(struct btrfs_trans_handle *trans)
1050 return __btrfs_end_transaction(trans, 0);
1053 int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
1055 return __btrfs_end_transaction(trans, 1);
1059 * when btree blocks are allocated, they have some corresponding bits set for
1060 * them in one of two extent_io trees. This is used to make sure all of
1061 * those extents are sent to disk but does not wait on them
1063 int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
1064 struct extent_io_tree *dirty_pages, int mark)
1068 struct address_space *mapping = fs_info->btree_inode->i_mapping;
1069 struct extent_state *cached_state = NULL;
1073 atomic_inc(&BTRFS_I(fs_info->btree_inode)->sync_writers);
1074 while (!find_first_extent_bit(dirty_pages, start, &start, &end,
1075 mark, &cached_state)) {
1076 bool wait_writeback = false;
1078 err = convert_extent_bit(dirty_pages, start, end,
1080 mark, &cached_state);
1082 * convert_extent_bit can return -ENOMEM, which is most of the
1083 * time a temporary error. So when it happens, ignore the error
1084 * and wait for writeback of this range to finish - because we
1085 * failed to set the bit EXTENT_NEED_WAIT for the range, a call
1086 * to __btrfs_wait_marked_extents() would not know that
1087 * writeback for this range started and therefore wouldn't
1088 * wait for it to finish - we don't want to commit a
1089 * superblock that points to btree nodes/leafs for which
1090 * writeback hasn't finished yet (and without errors).
1091 * We cleanup any entries left in the io tree when committing
1092 * the transaction (through extent_io_tree_release()).
1094 if (err == -ENOMEM) {
1096 wait_writeback = true;
1099 err = filemap_fdatawrite_range(mapping, start, end);
1102 else if (wait_writeback)
1103 werr = filemap_fdatawait_range(mapping, start, end);
1104 free_extent_state(cached_state);
1105 cached_state = NULL;
1109 atomic_dec(&BTRFS_I(fs_info->btree_inode)->sync_writers);
1114 * when btree blocks are allocated, they have some corresponding bits set for
1115 * them in one of two extent_io trees. This is used to make sure all of
1116 * those extents are on disk for transaction or log commit. We wait
1117 * on all the pages and clear them from the dirty pages state tree
1119 static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
1120 struct extent_io_tree *dirty_pages)
1124 struct address_space *mapping = fs_info->btree_inode->i_mapping;
1125 struct extent_state *cached_state = NULL;
1129 while (!find_first_extent_bit(dirty_pages, start, &start, &end,
1130 EXTENT_NEED_WAIT, &cached_state)) {
1132 * Ignore -ENOMEM errors returned by clear_extent_bit().
1133 * When committing the transaction, we'll remove any entries
1134 * left in the io tree. For a log commit, we don't remove them
1135 * after committing the log because the tree can be accessed
1136 * concurrently - we do it only at transaction commit time when
1137 * it's safe to do it (through extent_io_tree_release()).
1139 err = clear_extent_bit(dirty_pages, start, end,
1140 EXTENT_NEED_WAIT, &cached_state);
1144 err = filemap_fdatawait_range(mapping, start, end);
1147 free_extent_state(cached_state);
1148 cached_state = NULL;
1157 static int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
1158 struct extent_io_tree *dirty_pages)
1160 bool errors = false;
1163 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1164 if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1172 int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
1174 struct btrfs_fs_info *fs_info = log_root->fs_info;
1175 struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
1176 bool errors = false;
1179 ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
1181 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1182 if ((mark & EXTENT_DIRTY) &&
1183 test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1186 if ((mark & EXTENT_NEW) &&
1187 test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1196 * When btree blocks are allocated the corresponding extents are marked dirty.
1197 * This function ensures such extents are persisted on disk for transaction or
1200 * @trans: transaction whose dirty pages we'd like to write
1202 static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1206 struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
1207 struct btrfs_fs_info *fs_info = trans->fs_info;
1208 struct blk_plug plug;
1210 blk_start_plug(&plug);
1211 ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1212 blk_finish_plug(&plug);
1213 ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1215 extent_io_tree_release(&trans->transaction->dirty_pages);
1226 * this is used to update the root pointer in the tree of tree roots.
1228 * But, in the case of the extent allocation tree, updating the root
1229 * pointer may allocate blocks which may change the root of the extent
1232 * So, this loops and repeats and makes sure the cowonly root didn't
1233 * change while the root pointer was being updated in the metadata.
1235 static int update_cowonly_root(struct btrfs_trans_handle *trans,
1236 struct btrfs_root *root)
1239 u64 old_root_bytenr;
1241 struct btrfs_fs_info *fs_info = root->fs_info;
1242 struct btrfs_root *tree_root = fs_info->tree_root;
1244 old_root_used = btrfs_root_used(&root->root_item);
1247 old_root_bytenr = btrfs_root_bytenr(&root->root_item);
1248 if (old_root_bytenr == root->node->start &&
1249 old_root_used == btrfs_root_used(&root->root_item))
1252 btrfs_set_root_node(&root->root_item, root->node);
1253 ret = btrfs_update_root(trans, tree_root,
1259 old_root_used = btrfs_root_used(&root->root_item);
1266 * update all the cowonly tree roots on disk
1268 * The error handling in this function may not be obvious. Any of the
1269 * failures will cause the file system to go offline. We still need
1270 * to clean up the delayed refs.
1272 static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
1274 struct btrfs_fs_info *fs_info = trans->fs_info;
1275 struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
1276 struct list_head *io_bgs = &trans->transaction->io_bgs;
1277 struct list_head *next;
1278 struct extent_buffer *eb;
1282 * At this point no one can be using this transaction to modify any tree
1283 * and no one can start another transaction to modify any tree either.
1285 ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1287 eb = btrfs_lock_root_node(fs_info->tree_root);
1288 ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
1289 0, &eb, BTRFS_NESTING_COW);
1290 btrfs_tree_unlock(eb);
1291 free_extent_buffer(eb);
1296 ret = btrfs_run_dev_stats(trans);
1299 ret = btrfs_run_dev_replace(trans);
1302 ret = btrfs_run_qgroups(trans);
1306 ret = btrfs_setup_space_cache(trans);
1311 while (!list_empty(&fs_info->dirty_cowonly_roots)) {
1312 struct btrfs_root *root;
1313 next = fs_info->dirty_cowonly_roots.next;
1314 list_del_init(next);
1315 root = list_entry(next, struct btrfs_root, dirty_list);
1316 clear_bit(BTRFS_ROOT_DIRTY, &root->state);
1318 list_add_tail(&root->dirty_list,
1319 &trans->transaction->switch_commits);
1320 ret = update_cowonly_root(trans, root);
1325 /* Now flush any delayed refs generated by updating all of the roots */
1326 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1330 while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
1331 ret = btrfs_write_dirty_block_groups(trans);
1336 * We're writing the dirty block groups, which could generate
1337 * delayed refs, which could generate more dirty block groups,
1338 * so we want to keep this flushing in this loop to make sure
1339 * everything gets run.
1341 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1346 if (!list_empty(&fs_info->dirty_cowonly_roots))
1349 /* Update dev-replace pointer once everything is committed */
1350 fs_info->dev_replace.committed_cursor_left =
1351 fs_info->dev_replace.cursor_left_last_write_of_item;
1357 * If we had a pending drop we need to see if there are any others left in our
1358 * dead roots list, and if not clear our bit and wake any waiters.
1360 void btrfs_maybe_wake_unfinished_drop(struct btrfs_fs_info *fs_info)
1363 * We put the drop in progress roots at the front of the list, so if the
1364 * first entry doesn't have UNFINISHED_DROP set we can wake everybody
1367 spin_lock(&fs_info->trans_lock);
1368 if (!list_empty(&fs_info->dead_roots)) {
1369 struct btrfs_root *root = list_first_entry(&fs_info->dead_roots,
1372 if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state)) {
1373 spin_unlock(&fs_info->trans_lock);
1377 spin_unlock(&fs_info->trans_lock);
1379 btrfs_wake_unfinished_drop(fs_info);
1383 * dead roots are old snapshots that need to be deleted. This allocates
1384 * a dirty root struct and adds it into the list of dead roots that need to
1387 void btrfs_add_dead_root(struct btrfs_root *root)
1389 struct btrfs_fs_info *fs_info = root->fs_info;
1391 spin_lock(&fs_info->trans_lock);
1392 if (list_empty(&root->root_list)) {
1393 btrfs_grab_root(root);
1395 /* We want to process the partially complete drops first. */
1396 if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state))
1397 list_add(&root->root_list, &fs_info->dead_roots);
1399 list_add_tail(&root->root_list, &fs_info->dead_roots);
1401 spin_unlock(&fs_info->trans_lock);
1405 * Update each subvolume root and its relocation root, if it exists, in the tree
1406 * of tree roots. Also free log roots if they exist.
1408 static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
1410 struct btrfs_fs_info *fs_info = trans->fs_info;
1411 struct btrfs_root *gang[8];
1416 * At this point no one can be using this transaction to modify any tree
1417 * and no one can start another transaction to modify any tree either.
1419 ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1421 spin_lock(&fs_info->fs_roots_radix_lock);
1423 ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
1426 BTRFS_ROOT_TRANS_TAG);
1429 for (i = 0; i < ret; i++) {
1430 struct btrfs_root *root = gang[i];
1434 * At this point we can neither have tasks logging inodes
1435 * from a root nor trying to commit a log tree.
1437 ASSERT(atomic_read(&root->log_writers) == 0);
1438 ASSERT(atomic_read(&root->log_commit[0]) == 0);
1439 ASSERT(atomic_read(&root->log_commit[1]) == 0);
1441 radix_tree_tag_clear(&fs_info->fs_roots_radix,
1442 (unsigned long)root->root_key.objectid,
1443 BTRFS_ROOT_TRANS_TAG);
1444 spin_unlock(&fs_info->fs_roots_radix_lock);
1446 btrfs_free_log(trans, root);
1447 ret2 = btrfs_update_reloc_root(trans, root);
1451 /* see comments in should_cow_block() */
1452 clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1453 smp_mb__after_atomic();
1455 if (root->commit_root != root->node) {
1456 list_add_tail(&root->dirty_list,
1457 &trans->transaction->switch_commits);
1458 btrfs_set_root_node(&root->root_item,
1462 ret2 = btrfs_update_root(trans, fs_info->tree_root,
1467 spin_lock(&fs_info->fs_roots_radix_lock);
1468 btrfs_qgroup_free_meta_all_pertrans(root);
1471 spin_unlock(&fs_info->fs_roots_radix_lock);
1476 * defrag a given btree.
1477 * Every leaf in the btree is read and defragged.
1479 int btrfs_defrag_root(struct btrfs_root *root)
1481 struct btrfs_fs_info *info = root->fs_info;
1482 struct btrfs_trans_handle *trans;
1485 if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
1489 trans = btrfs_start_transaction(root, 0);
1490 if (IS_ERR(trans)) {
1491 ret = PTR_ERR(trans);
1495 ret = btrfs_defrag_leaves(trans, root);
1497 btrfs_end_transaction(trans);
1498 btrfs_btree_balance_dirty(info);
1501 if (btrfs_fs_closing(info) || ret != -EAGAIN)
1504 if (btrfs_defrag_cancelled(info)) {
1505 btrfs_debug(info, "defrag_root cancelled");
1510 clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
1515 * Do all special snapshot related qgroup dirty hack.
1517 * Will do all needed qgroup inherit and dirty hack like switch commit
1518 * roots inside one transaction and write all btree into disk, to make
1521 static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
1522 struct btrfs_root *src,
1523 struct btrfs_root *parent,
1524 struct btrfs_qgroup_inherit *inherit,
1527 struct btrfs_fs_info *fs_info = src->fs_info;
1531 * Save some performance in the case that qgroups are not
1532 * enabled. If this check races with the ioctl, rescan will
1535 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1539 * Ensure dirty @src will be committed. Or, after coming
1540 * commit_fs_roots() and switch_commit_roots(), any dirty but not
1541 * recorded root will never be updated again, causing an outdated root
1544 ret = record_root_in_trans(trans, src, 1);
1549 * btrfs_qgroup_inherit relies on a consistent view of the usage for the
1550 * src root, so we must run the delayed refs here.
1552 * However this isn't particularly fool proof, because there's no
1553 * synchronization keeping us from changing the tree after this point
1554 * before we do the qgroup_inherit, or even from making changes while
1555 * we're doing the qgroup_inherit. But that's a problem for the future,
1556 * for now flush the delayed refs to narrow the race window where the
1557 * qgroup counters could end up wrong.
1559 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1561 btrfs_abort_transaction(trans, ret);
1565 ret = commit_fs_roots(trans);
1568 ret = btrfs_qgroup_account_extents(trans);
1572 /* Now qgroup are all updated, we can inherit it to new qgroups */
1573 ret = btrfs_qgroup_inherit(trans, src->root_key.objectid, dst_objectid,
1579 * Now we do a simplified commit transaction, which will:
1580 * 1) commit all subvolume and extent tree
1581 * To ensure all subvolume and extent tree have a valid
1582 * commit_root to accounting later insert_dir_item()
1583 * 2) write all btree blocks onto disk
1584 * This is to make sure later btree modification will be cowed
1585 * Or commit_root can be populated and cause wrong qgroup numbers
1586 * In this simplified commit, we don't really care about other trees
1587 * like chunk and root tree, as they won't affect qgroup.
1588 * And we don't write super to avoid half committed status.
1590 ret = commit_cowonly_roots(trans);
1593 switch_commit_roots(trans);
1594 ret = btrfs_write_and_wait_transaction(trans);
1596 btrfs_handle_fs_error(fs_info, ret,
1597 "Error while writing out transaction for qgroup");
1601 * Force parent root to be updated, as we recorded it before so its
1602 * last_trans == cur_transid.
1603 * Or it won't be committed again onto disk after later
1607 ret = record_root_in_trans(trans, parent, 1);
1612 * new snapshots need to be created at a very specific time in the
1613 * transaction commit. This does the actual creation.
1616 * If the error which may affect the commitment of the current transaction
1617 * happens, we should return the error number. If the error which just affect
1618 * the creation of the pending snapshots, just return 0.
1620 static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
1621 struct btrfs_pending_snapshot *pending)
1624 struct btrfs_fs_info *fs_info = trans->fs_info;
1625 struct btrfs_key key;
1626 struct btrfs_root_item *new_root_item;
1627 struct btrfs_root *tree_root = fs_info->tree_root;
1628 struct btrfs_root *root = pending->root;
1629 struct btrfs_root *parent_root;
1630 struct btrfs_block_rsv *rsv;
1631 struct inode *parent_inode = pending->dir;
1632 struct btrfs_path *path;
1633 struct btrfs_dir_item *dir_item;
1634 struct extent_buffer *tmp;
1635 struct extent_buffer *old;
1636 struct timespec64 cur_time;
1642 unsigned int nofs_flags;
1643 struct fscrypt_name fname;
1645 ASSERT(pending->path);
1646 path = pending->path;
1648 ASSERT(pending->root_item);
1649 new_root_item = pending->root_item;
1652 * We're inside a transaction and must make sure that any potential
1653 * allocations with GFP_KERNEL in fscrypt won't recurse back to
1656 nofs_flags = memalloc_nofs_save();
1657 pending->error = fscrypt_setup_filename(parent_inode,
1658 &pending->dentry->d_name, 0,
1660 memalloc_nofs_restore(nofs_flags);
1664 pending->error = btrfs_get_free_objectid(tree_root, &objectid);
1669 * Make qgroup to skip current new snapshot's qgroupid, as it is
1670 * accounted by later btrfs_qgroup_inherit().
1672 btrfs_set_skip_qgroup(trans, objectid);
1674 btrfs_reloc_pre_snapshot(pending, &to_reserve);
1676 if (to_reserve > 0) {
1677 pending->error = btrfs_block_rsv_add(fs_info,
1678 &pending->block_rsv,
1680 BTRFS_RESERVE_NO_FLUSH);
1682 goto clear_skip_qgroup;
1685 key.objectid = objectid;
1686 key.offset = (u64)-1;
1687 key.type = BTRFS_ROOT_ITEM_KEY;
1689 rsv = trans->block_rsv;
1690 trans->block_rsv = &pending->block_rsv;
1691 trans->bytes_reserved = trans->block_rsv->reserved;
1692 trace_btrfs_space_reservation(fs_info, "transaction",
1694 trans->bytes_reserved, 1);
1695 parent_root = BTRFS_I(parent_inode)->root;
1696 ret = record_root_in_trans(trans, parent_root, 0);
1699 cur_time = current_time(parent_inode);
1702 * insert the directory item
1704 ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
1705 BUG_ON(ret); /* -ENOMEM */
1707 /* check if there is a file/dir which has the same name. */
1708 dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
1709 btrfs_ino(BTRFS_I(parent_inode)),
1710 &fname.disk_name, 0);
1711 if (dir_item != NULL && !IS_ERR(dir_item)) {
1712 pending->error = -EEXIST;
1713 goto dir_item_existed;
1714 } else if (IS_ERR(dir_item)) {
1715 ret = PTR_ERR(dir_item);
1716 btrfs_abort_transaction(trans, ret);
1719 btrfs_release_path(path);
1722 * pull in the delayed directory update
1723 * and the delayed inode item
1724 * otherwise we corrupt the FS during
1727 ret = btrfs_run_delayed_items(trans);
1728 if (ret) { /* Transaction aborted */
1729 btrfs_abort_transaction(trans, ret);
1733 ret = record_root_in_trans(trans, root, 0);
1735 btrfs_abort_transaction(trans, ret);
1738 btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
1739 memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
1740 btrfs_check_and_init_root_item(new_root_item);
1742 root_flags = btrfs_root_flags(new_root_item);
1743 if (pending->readonly)
1744 root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1746 root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1747 btrfs_set_root_flags(new_root_item, root_flags);
1749 btrfs_set_root_generation_v2(new_root_item,
1751 generate_random_guid(new_root_item->uuid);
1752 memcpy(new_root_item->parent_uuid, root->root_item.uuid,
1754 if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
1755 memset(new_root_item->received_uuid, 0,
1756 sizeof(new_root_item->received_uuid));
1757 memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
1758 memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
1759 btrfs_set_root_stransid(new_root_item, 0);
1760 btrfs_set_root_rtransid(new_root_item, 0);
1762 btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
1763 btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
1764 btrfs_set_root_otransid(new_root_item, trans->transid);
1766 old = btrfs_lock_root_node(root);
1767 ret = btrfs_cow_block(trans, root, old, NULL, 0, &old,
1770 btrfs_tree_unlock(old);
1771 free_extent_buffer(old);
1772 btrfs_abort_transaction(trans, ret);
1776 ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
1777 /* clean up in any case */
1778 btrfs_tree_unlock(old);
1779 free_extent_buffer(old);
1781 btrfs_abort_transaction(trans, ret);
1784 /* see comments in should_cow_block() */
1785 set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1788 btrfs_set_root_node(new_root_item, tmp);
1789 /* record when the snapshot was created in key.offset */
1790 key.offset = trans->transid;
1791 ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1792 btrfs_tree_unlock(tmp);
1793 free_extent_buffer(tmp);
1795 btrfs_abort_transaction(trans, ret);
1800 * insert root back/forward references
1802 ret = btrfs_add_root_ref(trans, objectid,
1803 parent_root->root_key.objectid,
1804 btrfs_ino(BTRFS_I(parent_inode)), index,
1807 btrfs_abort_transaction(trans, ret);
1811 key.offset = (u64)-1;
1812 pending->snap = btrfs_get_new_fs_root(fs_info, objectid, &pending->anon_dev);
1813 if (IS_ERR(pending->snap)) {
1814 ret = PTR_ERR(pending->snap);
1815 pending->snap = NULL;
1816 btrfs_abort_transaction(trans, ret);
1820 ret = btrfs_reloc_post_snapshot(trans, pending);
1822 btrfs_abort_transaction(trans, ret);
1827 * Do special qgroup accounting for snapshot, as we do some qgroup
1828 * snapshot hack to do fast snapshot.
1829 * To co-operate with that hack, we do hack again.
1830 * Or snapshot will be greatly slowed down by a subtree qgroup rescan
1832 ret = qgroup_account_snapshot(trans, root, parent_root,
1833 pending->inherit, objectid);
1837 ret = btrfs_insert_dir_item(trans, &fname.disk_name,
1838 BTRFS_I(parent_inode), &key, BTRFS_FT_DIR,
1840 /* We have check then name at the beginning, so it is impossible. */
1841 BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
1843 btrfs_abort_transaction(trans, ret);
1847 btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
1848 fname.disk_name.len * 2);
1849 parent_inode->i_mtime = current_time(parent_inode);
1850 parent_inode->i_ctime = parent_inode->i_mtime;
1851 ret = btrfs_update_inode_fallback(trans, parent_root, BTRFS_I(parent_inode));
1853 btrfs_abort_transaction(trans, ret);
1856 ret = btrfs_uuid_tree_add(trans, new_root_item->uuid,
1857 BTRFS_UUID_KEY_SUBVOL,
1860 btrfs_abort_transaction(trans, ret);
1863 if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1864 ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1865 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1867 if (ret && ret != -EEXIST) {
1868 btrfs_abort_transaction(trans, ret);
1874 pending->error = ret;
1876 trans->block_rsv = rsv;
1877 trans->bytes_reserved = 0;
1879 btrfs_clear_skip_qgroup(trans);
1881 fscrypt_free_filename(&fname);
1883 kfree(new_root_item);
1884 pending->root_item = NULL;
1885 btrfs_free_path(path);
1886 pending->path = NULL;
1892 * create all the snapshots we've scheduled for creation
1894 static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
1896 struct btrfs_pending_snapshot *pending, *next;
1897 struct list_head *head = &trans->transaction->pending_snapshots;
1900 list_for_each_entry_safe(pending, next, head, list) {
1901 list_del(&pending->list);
1902 ret = create_pending_snapshot(trans, pending);
1909 static void update_super_roots(struct btrfs_fs_info *fs_info)
1911 struct btrfs_root_item *root_item;
1912 struct btrfs_super_block *super;
1914 super = fs_info->super_copy;
1916 root_item = &fs_info->chunk_root->root_item;
1917 super->chunk_root = root_item->bytenr;
1918 super->chunk_root_generation = root_item->generation;
1919 super->chunk_root_level = root_item->level;
1921 root_item = &fs_info->tree_root->root_item;
1922 super->root = root_item->bytenr;
1923 super->generation = root_item->generation;
1924 super->root_level = root_item->level;
1925 if (btrfs_test_opt(fs_info, SPACE_CACHE))
1926 super->cache_generation = root_item->generation;
1927 else if (test_bit(BTRFS_FS_CLEANUP_SPACE_CACHE_V1, &fs_info->flags))
1928 super->cache_generation = 0;
1929 if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1930 super->uuid_tree_generation = root_item->generation;
1933 int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1935 struct btrfs_transaction *trans;
1938 spin_lock(&info->trans_lock);
1939 trans = info->running_transaction;
1941 ret = (trans->state >= TRANS_STATE_COMMIT_START);
1942 spin_unlock(&info->trans_lock);
1946 int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1948 struct btrfs_transaction *trans;
1951 spin_lock(&info->trans_lock);
1952 trans = info->running_transaction;
1954 ret = is_transaction_blocked(trans);
1955 spin_unlock(&info->trans_lock);
1959 void btrfs_commit_transaction_async(struct btrfs_trans_handle *trans)
1961 struct btrfs_fs_info *fs_info = trans->fs_info;
1962 struct btrfs_transaction *cur_trans;
1964 /* Kick the transaction kthread. */
1965 set_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
1966 wake_up_process(fs_info->transaction_kthread);
1968 /* take transaction reference */
1969 cur_trans = trans->transaction;
1970 refcount_inc(&cur_trans->use_count);
1972 btrfs_end_transaction(trans);
1975 * Wait for the current transaction commit to start and block
1976 * subsequent transaction joins
1978 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_START);
1979 wait_event(fs_info->transaction_blocked_wait,
1980 cur_trans->state >= TRANS_STATE_COMMIT_START ||
1981 TRANS_ABORTED(cur_trans));
1982 btrfs_put_transaction(cur_trans);
1985 static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
1987 struct btrfs_fs_info *fs_info = trans->fs_info;
1988 struct btrfs_transaction *cur_trans = trans->transaction;
1990 WARN_ON(refcount_read(&trans->use_count) > 1);
1992 btrfs_abort_transaction(trans, err);
1994 spin_lock(&fs_info->trans_lock);
1997 * If the transaction is removed from the list, it means this
1998 * transaction has been committed successfully, so it is impossible
1999 * to call the cleanup function.
2001 BUG_ON(list_empty(&cur_trans->list));
2003 if (cur_trans == fs_info->running_transaction) {
2004 cur_trans->state = TRANS_STATE_COMMIT_DOING;
2005 spin_unlock(&fs_info->trans_lock);
2008 * The thread has already released the lockdep map as reader
2009 * already in btrfs_commit_transaction().
2011 btrfs_might_wait_for_event(fs_info, btrfs_trans_num_writers);
2012 wait_event(cur_trans->writer_wait,
2013 atomic_read(&cur_trans->num_writers) == 1);
2015 spin_lock(&fs_info->trans_lock);
2019 * Now that we know no one else is still using the transaction we can
2020 * remove the transaction from the list of transactions. This avoids
2021 * the transaction kthread from cleaning up the transaction while some
2022 * other task is still using it, which could result in a use-after-free
2023 * on things like log trees, as it forces the transaction kthread to
2024 * wait for this transaction to be cleaned up by us.
2026 list_del_init(&cur_trans->list);
2028 spin_unlock(&fs_info->trans_lock);
2030 btrfs_cleanup_one_transaction(trans->transaction, fs_info);
2032 spin_lock(&fs_info->trans_lock);
2033 if (cur_trans == fs_info->running_transaction)
2034 fs_info->running_transaction = NULL;
2035 spin_unlock(&fs_info->trans_lock);
2037 if (trans->type & __TRANS_FREEZABLE)
2038 sb_end_intwrite(fs_info->sb);
2039 btrfs_put_transaction(cur_trans);
2040 btrfs_put_transaction(cur_trans);
2042 trace_btrfs_transaction_commit(fs_info);
2044 if (current->journal_info == trans)
2045 current->journal_info = NULL;
2048 * If relocation is running, we can't cancel scrub because that will
2049 * result in a deadlock. Before relocating a block group, relocation
2050 * pauses scrub, then starts and commits a transaction before unpausing
2051 * scrub. If the transaction commit is being done by the relocation
2052 * task or triggered by another task and the relocation task is waiting
2053 * for the commit, and we end up here due to an error in the commit
2054 * path, then calling btrfs_scrub_cancel() will deadlock, as we are
2055 * asking for scrub to stop while having it asked to be paused higher
2056 * above in relocation code.
2058 if (!test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
2059 btrfs_scrub_cancel(fs_info);
2061 kmem_cache_free(btrfs_trans_handle_cachep, trans);
2065 * Release reserved delayed ref space of all pending block groups of the
2066 * transaction and remove them from the list
2068 static void btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle *trans)
2070 struct btrfs_fs_info *fs_info = trans->fs_info;
2071 struct btrfs_block_group *block_group, *tmp;
2073 list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
2074 btrfs_delayed_refs_rsv_release(fs_info, 1);
2075 list_del_init(&block_group->bg_list);
2079 static inline int btrfs_start_delalloc_flush(struct btrfs_fs_info *fs_info)
2082 * We use try_to_writeback_inodes_sb() here because if we used
2083 * btrfs_start_delalloc_roots we would deadlock with fs freeze.
2084 * Currently are holding the fs freeze lock, if we do an async flush
2085 * we'll do btrfs_join_transaction() and deadlock because we need to
2086 * wait for the fs freeze lock. Using the direct flushing we benefit
2087 * from already being in a transaction and our join_transaction doesn't
2088 * have to re-take the fs freeze lock.
2090 * Note that try_to_writeback_inodes_sb() will only trigger writeback
2091 * if it can read lock sb->s_umount. It will always be able to lock it,
2092 * except when the filesystem is being unmounted or being frozen, but in
2093 * those cases sync_filesystem() is called, which results in calling
2094 * writeback_inodes_sb() while holding a write lock on sb->s_umount.
2095 * Note that we don't call writeback_inodes_sb() directly, because it
2096 * will emit a warning if sb->s_umount is not locked.
2098 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2099 try_to_writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
2103 static inline void btrfs_wait_delalloc_flush(struct btrfs_fs_info *fs_info)
2105 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2106 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
2110 * Add a pending snapshot associated with the given transaction handle to the
2111 * respective handle. This must be called after the transaction commit started
2112 * and while holding fs_info->trans_lock.
2113 * This serves to guarantee a caller of btrfs_commit_transaction() that it can
2114 * safely free the pending snapshot pointer in case btrfs_commit_transaction()
2117 static void add_pending_snapshot(struct btrfs_trans_handle *trans)
2119 struct btrfs_transaction *cur_trans = trans->transaction;
2121 if (!trans->pending_snapshot)
2124 lockdep_assert_held(&trans->fs_info->trans_lock);
2125 ASSERT(cur_trans->state >= TRANS_STATE_COMMIT_START);
2127 list_add(&trans->pending_snapshot->list, &cur_trans->pending_snapshots);
2130 static void update_commit_stats(struct btrfs_fs_info *fs_info, ktime_t interval)
2132 fs_info->commit_stats.commit_count++;
2133 fs_info->commit_stats.last_commit_dur = interval;
2134 fs_info->commit_stats.max_commit_dur =
2135 max_t(u64, fs_info->commit_stats.max_commit_dur, interval);
2136 fs_info->commit_stats.total_commit_dur += interval;
2139 int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
2141 struct btrfs_fs_info *fs_info = trans->fs_info;
2142 struct btrfs_transaction *cur_trans = trans->transaction;
2143 struct btrfs_transaction *prev_trans = NULL;
2148 ASSERT(refcount_read(&trans->use_count) == 1);
2149 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_START);
2151 /* Stop the commit early if ->aborted is set */
2152 if (TRANS_ABORTED(cur_trans)) {
2153 ret = cur_trans->aborted;
2154 goto lockdep_trans_commit_start_release;
2157 btrfs_trans_release_metadata(trans);
2158 trans->block_rsv = NULL;
2161 * We only want one transaction commit doing the flushing so we do not
2162 * waste a bunch of time on lock contention on the extent root node.
2164 if (!test_and_set_bit(BTRFS_DELAYED_REFS_FLUSHING,
2165 &cur_trans->delayed_refs.flags)) {
2167 * Make a pass through all the delayed refs we have so far.
2168 * Any running threads may add more while we are here.
2170 ret = btrfs_run_delayed_refs(trans, 0);
2172 goto lockdep_trans_commit_start_release;
2175 btrfs_create_pending_block_groups(trans);
2177 if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
2180 /* this mutex is also taken before trying to set
2181 * block groups readonly. We need to make sure
2182 * that nobody has set a block group readonly
2183 * after a extents from that block group have been
2184 * allocated for cache files. btrfs_set_block_group_ro
2185 * will wait for the transaction to commit if it
2186 * finds BTRFS_TRANS_DIRTY_BG_RUN set.
2188 * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
2189 * only one process starts all the block group IO. It wouldn't
2190 * hurt to have more than one go through, but there's no
2191 * real advantage to it either.
2193 mutex_lock(&fs_info->ro_block_group_mutex);
2194 if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
2197 mutex_unlock(&fs_info->ro_block_group_mutex);
2200 ret = btrfs_start_dirty_block_groups(trans);
2202 goto lockdep_trans_commit_start_release;
2206 spin_lock(&fs_info->trans_lock);
2207 if (cur_trans->state >= TRANS_STATE_COMMIT_START) {
2208 enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2210 add_pending_snapshot(trans);
2212 spin_unlock(&fs_info->trans_lock);
2213 refcount_inc(&cur_trans->use_count);
2215 if (trans->in_fsync)
2216 want_state = TRANS_STATE_SUPER_COMMITTED;
2218 btrfs_trans_state_lockdep_release(fs_info,
2219 BTRFS_LOCKDEP_TRANS_COMMIT_START);
2220 ret = btrfs_end_transaction(trans);
2221 wait_for_commit(cur_trans, want_state);
2223 if (TRANS_ABORTED(cur_trans))
2224 ret = cur_trans->aborted;
2226 btrfs_put_transaction(cur_trans);
2231 cur_trans->state = TRANS_STATE_COMMIT_START;
2232 wake_up(&fs_info->transaction_blocked_wait);
2233 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_START);
2235 if (cur_trans->list.prev != &fs_info->trans_list) {
2236 enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2238 if (trans->in_fsync)
2239 want_state = TRANS_STATE_SUPER_COMMITTED;
2241 prev_trans = list_entry(cur_trans->list.prev,
2242 struct btrfs_transaction, list);
2243 if (prev_trans->state < want_state) {
2244 refcount_inc(&prev_trans->use_count);
2245 spin_unlock(&fs_info->trans_lock);
2247 wait_for_commit(prev_trans, want_state);
2249 ret = READ_ONCE(prev_trans->aborted);
2251 btrfs_put_transaction(prev_trans);
2253 goto lockdep_release;
2255 spin_unlock(&fs_info->trans_lock);
2258 spin_unlock(&fs_info->trans_lock);
2260 * The previous transaction was aborted and was already removed
2261 * from the list of transactions at fs_info->trans_list. So we
2262 * abort to prevent writing a new superblock that reflects a
2263 * corrupt state (pointing to trees with unwritten nodes/leafs).
2265 if (BTRFS_FS_ERROR(fs_info)) {
2267 goto lockdep_release;
2272 * Get the time spent on the work done by the commit thread and not
2273 * the time spent waiting on a previous commit
2275 start_time = ktime_get_ns();
2277 extwriter_counter_dec(cur_trans, trans->type);
2279 ret = btrfs_start_delalloc_flush(fs_info);
2281 goto lockdep_release;
2283 ret = btrfs_run_delayed_items(trans);
2285 goto lockdep_release;
2288 * The thread has started/joined the transaction thus it holds the
2289 * lockdep map as a reader. It has to release it before acquiring the
2290 * lockdep map as a writer.
2292 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2293 btrfs_might_wait_for_event(fs_info, btrfs_trans_num_extwriters);
2294 wait_event(cur_trans->writer_wait,
2295 extwriter_counter_read(cur_trans) == 0);
2297 /* some pending stuffs might be added after the previous flush. */
2298 ret = btrfs_run_delayed_items(trans);
2300 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2301 goto cleanup_transaction;
2304 btrfs_wait_delalloc_flush(fs_info);
2307 * Wait for all ordered extents started by a fast fsync that joined this
2308 * transaction. Otherwise if this transaction commits before the ordered
2309 * extents complete we lose logged data after a power failure.
2311 btrfs_might_wait_for_event(fs_info, btrfs_trans_pending_ordered);
2312 wait_event(cur_trans->pending_wait,
2313 atomic_read(&cur_trans->pending_ordered) == 0);
2315 btrfs_scrub_pause(fs_info);
2317 * Ok now we need to make sure to block out any other joins while we
2318 * commit the transaction. We could have started a join before setting
2319 * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2321 spin_lock(&fs_info->trans_lock);
2322 add_pending_snapshot(trans);
2323 cur_trans->state = TRANS_STATE_COMMIT_DOING;
2324 spin_unlock(&fs_info->trans_lock);
2327 * The thread has started/joined the transaction thus it holds the
2328 * lockdep map as a reader. It has to release it before acquiring the
2329 * lockdep map as a writer.
2331 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2332 btrfs_might_wait_for_event(fs_info, btrfs_trans_num_writers);
2333 wait_event(cur_trans->writer_wait,
2334 atomic_read(&cur_trans->num_writers) == 1);
2337 * Make lockdep happy by acquiring the state locks after
2338 * btrfs_trans_num_writers is released. If we acquired the state locks
2339 * before releasing the btrfs_trans_num_writers lock then lockdep would
2340 * complain because we did not follow the reverse order unlocking rule.
2342 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2343 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2344 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2347 * We've started the commit, clear the flag in case we were triggered to
2348 * do an async commit but somebody else started before the transaction
2349 * kthread could do the work.
2351 clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
2353 if (TRANS_ABORTED(cur_trans)) {
2354 ret = cur_trans->aborted;
2355 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2356 goto scrub_continue;
2359 * the reloc mutex makes sure that we stop
2360 * the balancing code from coming in and moving
2361 * extents around in the middle of the commit
2363 mutex_lock(&fs_info->reloc_mutex);
2366 * We needn't worry about the delayed items because we will
2367 * deal with them in create_pending_snapshot(), which is the
2368 * core function of the snapshot creation.
2370 ret = create_pending_snapshots(trans);
2375 * We insert the dir indexes of the snapshots and update the inode
2376 * of the snapshots' parents after the snapshot creation, so there
2377 * are some delayed items which are not dealt with. Now deal with
2380 * We needn't worry that this operation will corrupt the snapshots,
2381 * because all the tree which are snapshoted will be forced to COW
2382 * the nodes and leaves.
2384 ret = btrfs_run_delayed_items(trans);
2388 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2393 * make sure none of the code above managed to slip in a
2396 btrfs_assert_delayed_root_empty(fs_info);
2398 WARN_ON(cur_trans != trans->transaction);
2400 ret = commit_fs_roots(trans);
2405 * Since the transaction is done, we can apply the pending changes
2406 * before the next transaction.
2408 btrfs_apply_pending_changes(fs_info);
2410 /* commit_fs_roots gets rid of all the tree log roots, it is now
2411 * safe to free the root of tree log roots
2413 btrfs_free_log_root_tree(trans, fs_info);
2416 * Since fs roots are all committed, we can get a quite accurate
2417 * new_roots. So let's do quota accounting.
2419 ret = btrfs_qgroup_account_extents(trans);
2423 ret = commit_cowonly_roots(trans);
2428 * The tasks which save the space cache and inode cache may also
2429 * update ->aborted, check it.
2431 if (TRANS_ABORTED(cur_trans)) {
2432 ret = cur_trans->aborted;
2436 cur_trans = fs_info->running_transaction;
2438 btrfs_set_root_node(&fs_info->tree_root->root_item,
2439 fs_info->tree_root->node);
2440 list_add_tail(&fs_info->tree_root->dirty_list,
2441 &cur_trans->switch_commits);
2443 btrfs_set_root_node(&fs_info->chunk_root->root_item,
2444 fs_info->chunk_root->node);
2445 list_add_tail(&fs_info->chunk_root->dirty_list,
2446 &cur_trans->switch_commits);
2448 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
2449 btrfs_set_root_node(&fs_info->block_group_root->root_item,
2450 fs_info->block_group_root->node);
2451 list_add_tail(&fs_info->block_group_root->dirty_list,
2452 &cur_trans->switch_commits);
2455 switch_commit_roots(trans);
2457 ASSERT(list_empty(&cur_trans->dirty_bgs));
2458 ASSERT(list_empty(&cur_trans->io_bgs));
2459 update_super_roots(fs_info);
2461 btrfs_set_super_log_root(fs_info->super_copy, 0);
2462 btrfs_set_super_log_root_level(fs_info->super_copy, 0);
2463 memcpy(fs_info->super_for_commit, fs_info->super_copy,
2464 sizeof(*fs_info->super_copy));
2466 btrfs_commit_device_sizes(cur_trans);
2468 clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2469 clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2471 btrfs_trans_release_chunk_metadata(trans);
2474 * Before changing the transaction state to TRANS_STATE_UNBLOCKED and
2475 * setting fs_info->running_transaction to NULL, lock tree_log_mutex to
2476 * make sure that before we commit our superblock, no other task can
2477 * start a new transaction and commit a log tree before we commit our
2478 * superblock. Anyone trying to commit a log tree locks this mutex before
2479 * writing its superblock.
2481 mutex_lock(&fs_info->tree_log_mutex);
2483 spin_lock(&fs_info->trans_lock);
2484 cur_trans->state = TRANS_STATE_UNBLOCKED;
2485 fs_info->running_transaction = NULL;
2486 spin_unlock(&fs_info->trans_lock);
2487 mutex_unlock(&fs_info->reloc_mutex);
2489 wake_up(&fs_info->transaction_wait);
2490 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2492 ret = btrfs_write_and_wait_transaction(trans);
2494 btrfs_handle_fs_error(fs_info, ret,
2495 "Error while writing out transaction");
2496 mutex_unlock(&fs_info->tree_log_mutex);
2497 goto scrub_continue;
2501 * At this point, we should have written all the tree blocks allocated
2502 * in this transaction. So it's now safe to free the redirtyied extent
2505 btrfs_free_redirty_list(cur_trans);
2507 ret = write_all_supers(fs_info, 0);
2509 * the super is written, we can safely allow the tree-loggers
2510 * to go about their business
2512 mutex_unlock(&fs_info->tree_log_mutex);
2514 goto scrub_continue;
2517 * We needn't acquire the lock here because there is no other task
2518 * which can change it.
2520 cur_trans->state = TRANS_STATE_SUPER_COMMITTED;
2521 wake_up(&cur_trans->commit_wait);
2522 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2524 btrfs_finish_extent_commit(trans);
2526 if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
2527 btrfs_clear_space_info_full(fs_info);
2529 fs_info->last_trans_committed = cur_trans->transid;
2531 * We needn't acquire the lock here because there is no other task
2532 * which can change it.
2534 cur_trans->state = TRANS_STATE_COMPLETED;
2535 wake_up(&cur_trans->commit_wait);
2536 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2538 spin_lock(&fs_info->trans_lock);
2539 list_del_init(&cur_trans->list);
2540 spin_unlock(&fs_info->trans_lock);
2542 btrfs_put_transaction(cur_trans);
2543 btrfs_put_transaction(cur_trans);
2545 if (trans->type & __TRANS_FREEZABLE)
2546 sb_end_intwrite(fs_info->sb);
2548 trace_btrfs_transaction_commit(fs_info);
2550 interval = ktime_get_ns() - start_time;
2552 btrfs_scrub_continue(fs_info);
2554 if (current->journal_info == trans)
2555 current->journal_info = NULL;
2557 kmem_cache_free(btrfs_trans_handle_cachep, trans);
2559 update_commit_stats(fs_info, interval);
2564 mutex_unlock(&fs_info->reloc_mutex);
2565 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2567 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2568 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2569 btrfs_scrub_continue(fs_info);
2570 cleanup_transaction:
2571 btrfs_trans_release_metadata(trans);
2572 btrfs_cleanup_pending_block_groups(trans);
2573 btrfs_trans_release_chunk_metadata(trans);
2574 trans->block_rsv = NULL;
2575 btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
2576 if (current->journal_info == trans)
2577 current->journal_info = NULL;
2578 cleanup_transaction(trans, ret);
2583 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2584 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2585 goto cleanup_transaction;
2587 lockdep_trans_commit_start_release:
2588 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_START);
2589 btrfs_end_transaction(trans);
2594 * return < 0 if error
2595 * 0 if there are no more dead_roots at the time of call
2596 * 1 there are more to be processed, call me again
2598 * The return value indicates there are certainly more snapshots to delete, but
2599 * if there comes a new one during processing, it may return 0. We don't mind,
2600 * because btrfs_commit_super will poke cleaner thread and it will process it a
2601 * few seconds later.
2603 int btrfs_clean_one_deleted_snapshot(struct btrfs_fs_info *fs_info)
2605 struct btrfs_root *root;
2608 spin_lock(&fs_info->trans_lock);
2609 if (list_empty(&fs_info->dead_roots)) {
2610 spin_unlock(&fs_info->trans_lock);
2613 root = list_first_entry(&fs_info->dead_roots,
2614 struct btrfs_root, root_list);
2615 list_del_init(&root->root_list);
2616 spin_unlock(&fs_info->trans_lock);
2618 btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
2620 btrfs_kill_all_delayed_nodes(root);
2622 if (btrfs_header_backref_rev(root->node) <
2623 BTRFS_MIXED_BACKREF_REV)
2624 ret = btrfs_drop_snapshot(root, 0, 0);
2626 ret = btrfs_drop_snapshot(root, 1, 0);
2628 btrfs_put_root(root);
2629 return (ret < 0) ? 0 : 1;
2632 void btrfs_apply_pending_changes(struct btrfs_fs_info *fs_info)
2637 prev = xchg(&fs_info->pending_changes, 0);
2641 bit = 1 << BTRFS_PENDING_COMMIT;
2643 btrfs_debug(fs_info, "pending commit done");
2648 "unknown pending changes left 0x%lx, ignoring", prev);