1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
7 #include <linux/slab.h>
8 #include <linux/sched.h>
9 #include <linux/sched/mm.h>
10 #include <linux/writeback.h>
11 #include <linux/pagemap.h>
12 #include <linux/blkdev.h>
13 #include <linux/uuid.h>
14 #include <linux/timekeeping.h>
18 #include "transaction.h"
22 #include "dev-replace.h"
24 #include "block-group.h"
25 #include "space-info.h"
28 #include "accessors.h"
29 #include "extent-tree.h"
30 #include "root-tree.h"
33 #include "uuid-tree.h"
35 #include "relocation.h"
38 static struct kmem_cache *btrfs_trans_handle_cachep;
41 * Transaction states and transitions
43 * No running transaction (fs tree blocks are not modified)
46 * | Call start_transaction() variants. Except btrfs_join_transaction_nostart().
48 * Transaction N [[TRANS_STATE_RUNNING]]
50 * | New trans handles can be attached to transaction N by calling all
51 * | start_transaction() variants.
54 * | Call btrfs_commit_transaction() on any trans handle attached to
57 * Transaction N [[TRANS_STATE_COMMIT_PREP]]
59 * | If there are simultaneous calls to btrfs_commit_transaction() one will win
60 * | the race and the rest will wait for the winner to commit the transaction.
62 * | The winner will wait for previous running transaction to completely finish
65 * Transaction N [[TRANS_STATE_COMMIT_START]]
67 * | Then one of the following happens:
68 * | - Wait for all other trans handle holders to release.
69 * | The btrfs_commit_transaction() caller will do the commit work.
70 * | - Wait for current transaction to be committed by others.
71 * | Other btrfs_commit_transaction() caller will do the commit work.
73 * | At this stage, only btrfs_join_transaction*() variants can attach
74 * | to this running transaction.
75 * | All other variants will wait for current one to finish and attach to
79 * | Caller is chosen to commit transaction N, and all other trans handle
80 * | haven been released.
82 * Transaction N [[TRANS_STATE_COMMIT_DOING]]
84 * | The heavy lifting transaction work is started.
85 * | From running delayed refs (modifying extent tree) to creating pending
86 * | snapshots, running qgroups.
87 * | In short, modify supporting trees to reflect modifications of subvolume
90 * | At this stage, all start_transaction() calls will wait for this
91 * | transaction to finish and attach to transaction N+1.
94 * | Until all supporting trees are updated.
96 * Transaction N [[TRANS_STATE_UNBLOCKED]]
98 * | All needed trees are modified, thus we only [[TRANS_STATE_RUNNING]]
99 * | need to write them back to disk and update |
102 * | At this stage, new transaction is allowed to |
104 * | All new start_transaction() calls will be |
105 * | attached to transid N+1. |
108 * | Until all tree blocks are super blocks are |
109 * | written to block devices |
111 * Transaction N [[TRANS_STATE_COMPLETED]] V
112 * All tree blocks and super blocks are written. Transaction N+1
113 * This transaction is finished and all its [[TRANS_STATE_COMMIT_START]]
114 * data structures will be cleaned up. | Life goes on
116 static const unsigned int btrfs_blocked_trans_types[TRANS_STATE_MAX] = {
117 [TRANS_STATE_RUNNING] = 0U,
118 [TRANS_STATE_COMMIT_PREP] = 0U,
119 [TRANS_STATE_COMMIT_START] = (__TRANS_START | __TRANS_ATTACH),
120 [TRANS_STATE_COMMIT_DOING] = (__TRANS_START |
123 __TRANS_JOIN_NOSTART),
124 [TRANS_STATE_UNBLOCKED] = (__TRANS_START |
127 __TRANS_JOIN_NOLOCK |
128 __TRANS_JOIN_NOSTART),
129 [TRANS_STATE_SUPER_COMMITTED] = (__TRANS_START |
132 __TRANS_JOIN_NOLOCK |
133 __TRANS_JOIN_NOSTART),
134 [TRANS_STATE_COMPLETED] = (__TRANS_START |
137 __TRANS_JOIN_NOLOCK |
138 __TRANS_JOIN_NOSTART),
141 void btrfs_put_transaction(struct btrfs_transaction *transaction)
143 WARN_ON(refcount_read(&transaction->use_count) == 0);
144 if (refcount_dec_and_test(&transaction->use_count)) {
145 BUG_ON(!list_empty(&transaction->list));
146 WARN_ON(!RB_EMPTY_ROOT(
147 &transaction->delayed_refs.href_root.rb_root));
148 WARN_ON(!RB_EMPTY_ROOT(
149 &transaction->delayed_refs.dirty_extent_root));
150 if (transaction->delayed_refs.pending_csums)
151 btrfs_err(transaction->fs_info,
152 "pending csums is %llu",
153 transaction->delayed_refs.pending_csums);
155 * If any block groups are found in ->deleted_bgs then it's
156 * because the transaction was aborted and a commit did not
157 * happen (things failed before writing the new superblock
158 * and calling btrfs_finish_extent_commit()), so we can not
159 * discard the physical locations of the block groups.
161 while (!list_empty(&transaction->deleted_bgs)) {
162 struct btrfs_block_group *cache;
164 cache = list_first_entry(&transaction->deleted_bgs,
165 struct btrfs_block_group,
167 list_del_init(&cache->bg_list);
168 btrfs_unfreeze_block_group(cache);
169 btrfs_put_block_group(cache);
171 WARN_ON(!list_empty(&transaction->dev_update_list));
176 static noinline void switch_commit_roots(struct btrfs_trans_handle *trans)
178 struct btrfs_transaction *cur_trans = trans->transaction;
179 struct btrfs_fs_info *fs_info = trans->fs_info;
180 struct btrfs_root *root, *tmp;
183 * At this point no one can be using this transaction to modify any tree
184 * and no one can start another transaction to modify any tree either.
186 ASSERT(cur_trans->state == TRANS_STATE_COMMIT_DOING);
188 down_write(&fs_info->commit_root_sem);
190 if (test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
191 fs_info->last_reloc_trans = trans->transid;
193 list_for_each_entry_safe(root, tmp, &cur_trans->switch_commits,
195 list_del_init(&root->dirty_list);
196 free_extent_buffer(root->commit_root);
197 root->commit_root = btrfs_root_node(root);
198 extent_io_tree_release(&root->dirty_log_pages);
199 btrfs_qgroup_clean_swapped_blocks(root);
202 /* We can free old roots now. */
203 spin_lock(&cur_trans->dropped_roots_lock);
204 while (!list_empty(&cur_trans->dropped_roots)) {
205 root = list_first_entry(&cur_trans->dropped_roots,
206 struct btrfs_root, root_list);
207 list_del_init(&root->root_list);
208 spin_unlock(&cur_trans->dropped_roots_lock);
209 btrfs_free_log(trans, root);
210 btrfs_drop_and_free_fs_root(fs_info, root);
211 spin_lock(&cur_trans->dropped_roots_lock);
213 spin_unlock(&cur_trans->dropped_roots_lock);
215 up_write(&fs_info->commit_root_sem);
218 static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
221 if (type & TRANS_EXTWRITERS)
222 atomic_inc(&trans->num_extwriters);
225 static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
228 if (type & TRANS_EXTWRITERS)
229 atomic_dec(&trans->num_extwriters);
232 static inline void extwriter_counter_init(struct btrfs_transaction *trans,
235 atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
238 static inline int extwriter_counter_read(struct btrfs_transaction *trans)
240 return atomic_read(&trans->num_extwriters);
244 * To be called after doing the chunk btree updates right after allocating a new
245 * chunk (after btrfs_chunk_alloc_add_chunk_item() is called), when removing a
246 * chunk after all chunk btree updates and after finishing the second phase of
247 * chunk allocation (btrfs_create_pending_block_groups()) in case some block
248 * group had its chunk item insertion delayed to the second phase.
250 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
252 struct btrfs_fs_info *fs_info = trans->fs_info;
254 if (!trans->chunk_bytes_reserved)
257 btrfs_block_rsv_release(fs_info, &fs_info->chunk_block_rsv,
258 trans->chunk_bytes_reserved, NULL);
259 trans->chunk_bytes_reserved = 0;
263 * either allocate a new transaction or hop into the existing one
265 static noinline int join_transaction(struct btrfs_fs_info *fs_info,
268 struct btrfs_transaction *cur_trans;
270 spin_lock(&fs_info->trans_lock);
272 /* The file system has been taken offline. No new transactions. */
273 if (BTRFS_FS_ERROR(fs_info)) {
274 spin_unlock(&fs_info->trans_lock);
278 cur_trans = fs_info->running_transaction;
280 if (TRANS_ABORTED(cur_trans)) {
281 spin_unlock(&fs_info->trans_lock);
282 return cur_trans->aborted;
284 if (btrfs_blocked_trans_types[cur_trans->state] & type) {
285 spin_unlock(&fs_info->trans_lock);
288 refcount_inc(&cur_trans->use_count);
289 atomic_inc(&cur_trans->num_writers);
290 extwriter_counter_inc(cur_trans, type);
291 spin_unlock(&fs_info->trans_lock);
292 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_writers);
293 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_extwriters);
296 spin_unlock(&fs_info->trans_lock);
299 * If we are ATTACH or TRANS_JOIN_NOSTART, we just want to catch the
300 * current transaction, and commit it. If there is no transaction, just
303 if (type == TRANS_ATTACH || type == TRANS_JOIN_NOSTART)
307 * JOIN_NOLOCK only happens during the transaction commit, so
308 * it is impossible that ->running_transaction is NULL
310 BUG_ON(type == TRANS_JOIN_NOLOCK);
312 cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
316 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_writers);
317 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_extwriters);
319 spin_lock(&fs_info->trans_lock);
320 if (fs_info->running_transaction) {
322 * someone started a transaction after we unlocked. Make sure
323 * to redo the checks above
325 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
326 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
329 } else if (BTRFS_FS_ERROR(fs_info)) {
330 spin_unlock(&fs_info->trans_lock);
331 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
332 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
337 cur_trans->fs_info = fs_info;
338 atomic_set(&cur_trans->pending_ordered, 0);
339 init_waitqueue_head(&cur_trans->pending_wait);
340 atomic_set(&cur_trans->num_writers, 1);
341 extwriter_counter_init(cur_trans, type);
342 init_waitqueue_head(&cur_trans->writer_wait);
343 init_waitqueue_head(&cur_trans->commit_wait);
344 cur_trans->state = TRANS_STATE_RUNNING;
346 * One for this trans handle, one so it will live on until we
347 * commit the transaction.
349 refcount_set(&cur_trans->use_count, 2);
350 cur_trans->flags = 0;
351 cur_trans->start_time = ktime_get_seconds();
353 memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
355 cur_trans->delayed_refs.href_root = RB_ROOT_CACHED;
356 cur_trans->delayed_refs.dirty_extent_root = RB_ROOT;
357 atomic_set(&cur_trans->delayed_refs.num_entries, 0);
360 * although the tree mod log is per file system and not per transaction,
361 * the log must never go across transaction boundaries.
364 if (!list_empty(&fs_info->tree_mod_seq_list))
365 WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
366 if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
367 WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
368 atomic64_set(&fs_info->tree_mod_seq, 0);
370 spin_lock_init(&cur_trans->delayed_refs.lock);
372 INIT_LIST_HEAD(&cur_trans->pending_snapshots);
373 INIT_LIST_HEAD(&cur_trans->dev_update_list);
374 INIT_LIST_HEAD(&cur_trans->switch_commits);
375 INIT_LIST_HEAD(&cur_trans->dirty_bgs);
376 INIT_LIST_HEAD(&cur_trans->io_bgs);
377 INIT_LIST_HEAD(&cur_trans->dropped_roots);
378 mutex_init(&cur_trans->cache_write_mutex);
379 spin_lock_init(&cur_trans->dirty_bgs_lock);
380 INIT_LIST_HEAD(&cur_trans->deleted_bgs);
381 spin_lock_init(&cur_trans->dropped_roots_lock);
382 list_add_tail(&cur_trans->list, &fs_info->trans_list);
383 extent_io_tree_init(fs_info, &cur_trans->dirty_pages,
384 IO_TREE_TRANS_DIRTY_PAGES);
385 extent_io_tree_init(fs_info, &cur_trans->pinned_extents,
386 IO_TREE_FS_PINNED_EXTENTS);
387 fs_info->generation++;
388 cur_trans->transid = fs_info->generation;
389 fs_info->running_transaction = cur_trans;
390 cur_trans->aborted = 0;
391 spin_unlock(&fs_info->trans_lock);
397 * This does all the record keeping required to make sure that a shareable root
398 * is properly recorded in a given transaction. This is required to make sure
399 * the old root from before we joined the transaction is deleted when the
400 * transaction commits.
402 static int record_root_in_trans(struct btrfs_trans_handle *trans,
403 struct btrfs_root *root,
406 struct btrfs_fs_info *fs_info = root->fs_info;
409 if ((test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
410 root->last_trans < trans->transid) || force) {
411 WARN_ON(!force && root->commit_root != root->node);
414 * see below for IN_TRANS_SETUP usage rules
415 * we have the reloc mutex held now, so there
416 * is only one writer in this function
418 set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
420 /* make sure readers find IN_TRANS_SETUP before
421 * they find our root->last_trans update
425 spin_lock(&fs_info->fs_roots_radix_lock);
426 if (root->last_trans == trans->transid && !force) {
427 spin_unlock(&fs_info->fs_roots_radix_lock);
430 radix_tree_tag_set(&fs_info->fs_roots_radix,
431 (unsigned long)root->root_key.objectid,
432 BTRFS_ROOT_TRANS_TAG);
433 spin_unlock(&fs_info->fs_roots_radix_lock);
434 root->last_trans = trans->transid;
436 /* this is pretty tricky. We don't want to
437 * take the relocation lock in btrfs_record_root_in_trans
438 * unless we're really doing the first setup for this root in
441 * Normally we'd use root->last_trans as a flag to decide
442 * if we want to take the expensive mutex.
444 * But, we have to set root->last_trans before we
445 * init the relocation root, otherwise, we trip over warnings
446 * in ctree.c. The solution used here is to flag ourselves
447 * with root IN_TRANS_SETUP. When this is 1, we're still
448 * fixing up the reloc trees and everyone must wait.
450 * When this is zero, they can trust root->last_trans and fly
451 * through btrfs_record_root_in_trans without having to take the
452 * lock. smp_wmb() makes sure that all the writes above are
453 * done before we pop in the zero below
455 ret = btrfs_init_reloc_root(trans, root);
456 smp_mb__before_atomic();
457 clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
463 void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
464 struct btrfs_root *root)
466 struct btrfs_fs_info *fs_info = root->fs_info;
467 struct btrfs_transaction *cur_trans = trans->transaction;
469 /* Add ourselves to the transaction dropped list */
470 spin_lock(&cur_trans->dropped_roots_lock);
471 list_add_tail(&root->root_list, &cur_trans->dropped_roots);
472 spin_unlock(&cur_trans->dropped_roots_lock);
474 /* Make sure we don't try to update the root at commit time */
475 spin_lock(&fs_info->fs_roots_radix_lock);
476 radix_tree_tag_clear(&fs_info->fs_roots_radix,
477 (unsigned long)root->root_key.objectid,
478 BTRFS_ROOT_TRANS_TAG);
479 spin_unlock(&fs_info->fs_roots_radix_lock);
482 int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
483 struct btrfs_root *root)
485 struct btrfs_fs_info *fs_info = root->fs_info;
488 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
492 * see record_root_in_trans for comments about IN_TRANS_SETUP usage
496 if (root->last_trans == trans->transid &&
497 !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
500 mutex_lock(&fs_info->reloc_mutex);
501 ret = record_root_in_trans(trans, root, 0);
502 mutex_unlock(&fs_info->reloc_mutex);
507 static inline int is_transaction_blocked(struct btrfs_transaction *trans)
509 return (trans->state >= TRANS_STATE_COMMIT_START &&
510 trans->state < TRANS_STATE_UNBLOCKED &&
511 !TRANS_ABORTED(trans));
514 /* wait for commit against the current transaction to become unblocked
515 * when this is done, it is safe to start a new transaction, but the current
516 * transaction might not be fully on disk.
518 static void wait_current_trans(struct btrfs_fs_info *fs_info)
520 struct btrfs_transaction *cur_trans;
522 spin_lock(&fs_info->trans_lock);
523 cur_trans = fs_info->running_transaction;
524 if (cur_trans && is_transaction_blocked(cur_trans)) {
525 refcount_inc(&cur_trans->use_count);
526 spin_unlock(&fs_info->trans_lock);
528 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
529 wait_event(fs_info->transaction_wait,
530 cur_trans->state >= TRANS_STATE_UNBLOCKED ||
531 TRANS_ABORTED(cur_trans));
532 btrfs_put_transaction(cur_trans);
534 spin_unlock(&fs_info->trans_lock);
538 static int may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
540 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
543 if (type == TRANS_START)
549 static inline bool need_reserve_reloc_root(struct btrfs_root *root)
551 struct btrfs_fs_info *fs_info = root->fs_info;
553 if (!fs_info->reloc_ctl ||
554 !test_bit(BTRFS_ROOT_SHAREABLE, &root->state) ||
555 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
562 static struct btrfs_trans_handle *
563 start_transaction(struct btrfs_root *root, unsigned int num_items,
564 unsigned int type, enum btrfs_reserve_flush_enum flush,
565 bool enforce_qgroups)
567 struct btrfs_fs_info *fs_info = root->fs_info;
568 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
569 struct btrfs_trans_handle *h;
570 struct btrfs_transaction *cur_trans;
572 u64 qgroup_reserved = 0;
573 bool reloc_reserved = false;
574 bool do_chunk_alloc = false;
577 if (BTRFS_FS_ERROR(fs_info))
578 return ERR_PTR(-EROFS);
580 if (current->journal_info) {
581 WARN_ON(type & TRANS_EXTWRITERS);
582 h = current->journal_info;
583 refcount_inc(&h->use_count);
584 WARN_ON(refcount_read(&h->use_count) > 2);
585 h->orig_rsv = h->block_rsv;
591 * Do the reservation before we join the transaction so we can do all
592 * the appropriate flushing if need be.
594 if (num_items && root != fs_info->chunk_root) {
595 struct btrfs_block_rsv *rsv = &fs_info->trans_block_rsv;
596 u64 delayed_refs_bytes = 0;
598 qgroup_reserved = num_items * fs_info->nodesize;
600 * Use prealloc for now, as there might be a currently running
601 * transaction that could free this reserved space prematurely
604 ret = btrfs_qgroup_reserve_meta_prealloc(root, qgroup_reserved,
605 enforce_qgroups, false);
610 * We want to reserve all the bytes we may need all at once, so
611 * we only do 1 enospc flushing cycle per transaction start. We
612 * accomplish this by simply assuming we'll do num_items worth
613 * of delayed refs updates in this trans handle, and refill that
614 * amount for whatever is missing in the reserve.
616 num_bytes = btrfs_calc_insert_metadata_size(fs_info, num_items);
617 if (flush == BTRFS_RESERVE_FLUSH_ALL &&
618 !btrfs_block_rsv_full(delayed_refs_rsv)) {
619 delayed_refs_bytes = btrfs_calc_delayed_ref_bytes(fs_info,
621 num_bytes += delayed_refs_bytes;
625 * Do the reservation for the relocation root creation
627 if (need_reserve_reloc_root(root)) {
628 num_bytes += fs_info->nodesize;
629 reloc_reserved = true;
632 ret = btrfs_reserve_metadata_bytes(fs_info, rsv, num_bytes, flush);
635 if (delayed_refs_bytes) {
636 btrfs_migrate_to_delayed_refs_rsv(fs_info, delayed_refs_bytes);
637 num_bytes -= delayed_refs_bytes;
639 btrfs_block_rsv_add_bytes(rsv, num_bytes, true);
641 if (rsv->space_info->force_alloc)
642 do_chunk_alloc = true;
643 } else if (num_items == 0 && flush == BTRFS_RESERVE_FLUSH_ALL &&
644 !btrfs_block_rsv_full(delayed_refs_rsv)) {
646 * Some people call with btrfs_start_transaction(root, 0)
647 * because they can be throttled, but have some other mechanism
648 * for reserving space. We still want these guys to refill the
649 * delayed block_rsv so just add 1 items worth of reservation
652 ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
657 h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
664 * If we are JOIN_NOLOCK we're already committing a transaction and
665 * waiting on this guy, so we don't need to do the sb_start_intwrite
666 * because we're already holding a ref. We need this because we could
667 * have raced in and did an fsync() on a file which can kick a commit
668 * and then we deadlock with somebody doing a freeze.
670 * If we are ATTACH, it means we just want to catch the current
671 * transaction and commit it, so we needn't do sb_start_intwrite().
673 if (type & __TRANS_FREEZABLE)
674 sb_start_intwrite(fs_info->sb);
676 if (may_wait_transaction(fs_info, type))
677 wait_current_trans(fs_info);
680 ret = join_transaction(fs_info, type);
682 wait_current_trans(fs_info);
683 if (unlikely(type == TRANS_ATTACH ||
684 type == TRANS_JOIN_NOSTART))
687 } while (ret == -EBUSY);
692 cur_trans = fs_info->running_transaction;
694 h->transid = cur_trans->transid;
695 h->transaction = cur_trans;
696 refcount_set(&h->use_count, 1);
697 h->fs_info = root->fs_info;
700 INIT_LIST_HEAD(&h->new_bgs);
703 if (cur_trans->state >= TRANS_STATE_COMMIT_START &&
704 may_wait_transaction(fs_info, type)) {
705 current->journal_info = h;
706 btrfs_commit_transaction(h);
711 trace_btrfs_space_reservation(fs_info, "transaction",
712 h->transid, num_bytes, 1);
713 h->block_rsv = &fs_info->trans_block_rsv;
714 h->bytes_reserved = num_bytes;
715 h->reloc_reserved = reloc_reserved;
719 * Now that we have found a transaction to be a part of, convert the
720 * qgroup reservation from prealloc to pertrans. A different transaction
721 * can't race in and free our pertrans out from under us.
724 btrfs_qgroup_convert_reserved_meta(root, qgroup_reserved);
727 if (!current->journal_info)
728 current->journal_info = h;
731 * If the space_info is marked ALLOC_FORCE then we'll get upgraded to
732 * ALLOC_FORCE the first run through, and then we won't allocate for
733 * anybody else who races in later. We don't care about the return
736 if (do_chunk_alloc && num_bytes) {
737 u64 flags = h->block_rsv->space_info->flags;
739 btrfs_chunk_alloc(h, btrfs_get_alloc_profile(fs_info, flags),
740 CHUNK_ALLOC_NO_FORCE);
744 * btrfs_record_root_in_trans() needs to alloc new extents, and may
745 * call btrfs_join_transaction() while we're also starting a
748 * Thus it need to be called after current->journal_info initialized,
749 * or we can deadlock.
751 ret = btrfs_record_root_in_trans(h, root);
754 * The transaction handle is fully initialized and linked with
755 * other structures so it needs to be ended in case of errors,
758 btrfs_end_transaction(h);
765 if (type & __TRANS_FREEZABLE)
766 sb_end_intwrite(fs_info->sb);
767 kmem_cache_free(btrfs_trans_handle_cachep, h);
770 btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
773 btrfs_qgroup_free_meta_prealloc(root, qgroup_reserved);
777 struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
778 unsigned int num_items)
780 return start_transaction(root, num_items, TRANS_START,
781 BTRFS_RESERVE_FLUSH_ALL, true);
784 struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
785 struct btrfs_root *root,
786 unsigned int num_items)
788 return start_transaction(root, num_items, TRANS_START,
789 BTRFS_RESERVE_FLUSH_ALL_STEAL, false);
792 struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
794 return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
798 struct btrfs_trans_handle *btrfs_join_transaction_spacecache(struct btrfs_root *root)
800 return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
801 BTRFS_RESERVE_NO_FLUSH, true);
805 * Similar to regular join but it never starts a transaction when none is
806 * running or when there's a running one at a state >= TRANS_STATE_UNBLOCKED.
807 * This is similar to btrfs_attach_transaction() but it allows the join to
808 * happen if the transaction commit already started but it's not yet in the
809 * "doing" phase (the state is < TRANS_STATE_COMMIT_DOING).
811 struct btrfs_trans_handle *btrfs_join_transaction_nostart(struct btrfs_root *root)
813 return start_transaction(root, 0, TRANS_JOIN_NOSTART,
814 BTRFS_RESERVE_NO_FLUSH, true);
818 * btrfs_attach_transaction() - catch the running transaction
820 * It is used when we want to commit the current the transaction, but
821 * don't want to start a new one.
823 * Note: If this function return -ENOENT, it just means there is no
824 * running transaction. But it is possible that the inactive transaction
825 * is still in the memory, not fully on disk. If you hope there is no
826 * inactive transaction in the fs when -ENOENT is returned, you should
828 * btrfs_attach_transaction_barrier()
830 struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
832 return start_transaction(root, 0, TRANS_ATTACH,
833 BTRFS_RESERVE_NO_FLUSH, true);
837 * btrfs_attach_transaction_barrier() - catch the running transaction
839 * It is similar to the above function, the difference is this one
840 * will wait for all the inactive transactions until they fully
843 struct btrfs_trans_handle *
844 btrfs_attach_transaction_barrier(struct btrfs_root *root)
846 struct btrfs_trans_handle *trans;
848 trans = start_transaction(root, 0, TRANS_ATTACH,
849 BTRFS_RESERVE_NO_FLUSH, true);
850 if (trans == ERR_PTR(-ENOENT)) {
853 ret = btrfs_wait_for_commit(root->fs_info, 0);
861 /* Wait for a transaction commit to reach at least the given state. */
862 static noinline void wait_for_commit(struct btrfs_transaction *commit,
863 const enum btrfs_trans_state min_state)
865 struct btrfs_fs_info *fs_info = commit->fs_info;
866 u64 transid = commit->transid;
870 * At the moment this function is called with min_state either being
871 * TRANS_STATE_COMPLETED or TRANS_STATE_SUPER_COMMITTED.
873 if (min_state == TRANS_STATE_COMPLETED)
874 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
876 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
879 wait_event(commit->commit_wait, commit->state >= min_state);
881 btrfs_put_transaction(commit);
883 if (min_state < TRANS_STATE_COMPLETED)
887 * A transaction isn't really completed until all of the
888 * previous transactions are completed, but with fsync we can
889 * end up with SUPER_COMMITTED transactions before a COMPLETED
890 * transaction. Wait for those.
893 spin_lock(&fs_info->trans_lock);
894 commit = list_first_entry_or_null(&fs_info->trans_list,
895 struct btrfs_transaction,
897 if (!commit || commit->transid > transid) {
898 spin_unlock(&fs_info->trans_lock);
901 refcount_inc(&commit->use_count);
903 spin_unlock(&fs_info->trans_lock);
907 int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
909 struct btrfs_transaction *cur_trans = NULL, *t;
913 if (transid <= fs_info->last_trans_committed)
916 /* find specified transaction */
917 spin_lock(&fs_info->trans_lock);
918 list_for_each_entry(t, &fs_info->trans_list, list) {
919 if (t->transid == transid) {
921 refcount_inc(&cur_trans->use_count);
925 if (t->transid > transid) {
930 spin_unlock(&fs_info->trans_lock);
933 * The specified transaction doesn't exist, or we
934 * raced with btrfs_commit_transaction
937 if (transid > fs_info->last_trans_committed)
942 /* find newest transaction that is committing | committed */
943 spin_lock(&fs_info->trans_lock);
944 list_for_each_entry_reverse(t, &fs_info->trans_list,
946 if (t->state >= TRANS_STATE_COMMIT_START) {
947 if (t->state == TRANS_STATE_COMPLETED)
950 refcount_inc(&cur_trans->use_count);
954 spin_unlock(&fs_info->trans_lock);
956 goto out; /* nothing committing|committed */
959 wait_for_commit(cur_trans, TRANS_STATE_COMPLETED);
960 ret = cur_trans->aborted;
961 btrfs_put_transaction(cur_trans);
966 void btrfs_throttle(struct btrfs_fs_info *fs_info)
968 wait_current_trans(fs_info);
971 bool btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
973 struct btrfs_transaction *cur_trans = trans->transaction;
975 if (cur_trans->state >= TRANS_STATE_COMMIT_START ||
976 test_bit(BTRFS_DELAYED_REFS_FLUSHING, &cur_trans->delayed_refs.flags))
979 if (btrfs_check_space_for_delayed_refs(trans->fs_info))
982 return !!btrfs_block_rsv_check(&trans->fs_info->global_block_rsv, 50);
985 static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
988 struct btrfs_fs_info *fs_info = trans->fs_info;
990 if (!trans->block_rsv) {
991 ASSERT(!trans->bytes_reserved);
995 if (!trans->bytes_reserved)
998 ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
999 trace_btrfs_space_reservation(fs_info, "transaction",
1000 trans->transid, trans->bytes_reserved, 0);
1001 btrfs_block_rsv_release(fs_info, trans->block_rsv,
1002 trans->bytes_reserved, NULL);
1003 trans->bytes_reserved = 0;
1006 static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
1009 struct btrfs_fs_info *info = trans->fs_info;
1010 struct btrfs_transaction *cur_trans = trans->transaction;
1013 if (refcount_read(&trans->use_count) > 1) {
1014 refcount_dec(&trans->use_count);
1015 trans->block_rsv = trans->orig_rsv;
1019 btrfs_trans_release_metadata(trans);
1020 trans->block_rsv = NULL;
1022 btrfs_create_pending_block_groups(trans);
1024 btrfs_trans_release_chunk_metadata(trans);
1026 if (trans->type & __TRANS_FREEZABLE)
1027 sb_end_intwrite(info->sb);
1029 WARN_ON(cur_trans != info->running_transaction);
1030 WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
1031 atomic_dec(&cur_trans->num_writers);
1032 extwriter_counter_dec(cur_trans, trans->type);
1034 cond_wake_up(&cur_trans->writer_wait);
1036 btrfs_lockdep_release(info, btrfs_trans_num_extwriters);
1037 btrfs_lockdep_release(info, btrfs_trans_num_writers);
1039 btrfs_put_transaction(cur_trans);
1041 if (current->journal_info == trans)
1042 current->journal_info = NULL;
1045 btrfs_run_delayed_iputs(info);
1047 if (TRANS_ABORTED(trans) || BTRFS_FS_ERROR(info)) {
1048 wake_up_process(info->transaction_kthread);
1049 if (TRANS_ABORTED(trans))
1050 err = trans->aborted;
1055 kmem_cache_free(btrfs_trans_handle_cachep, trans);
1059 int btrfs_end_transaction(struct btrfs_trans_handle *trans)
1061 return __btrfs_end_transaction(trans, 0);
1064 int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
1066 return __btrfs_end_transaction(trans, 1);
1070 * when btree blocks are allocated, they have some corresponding bits set for
1071 * them in one of two extent_io trees. This is used to make sure all of
1072 * those extents are sent to disk but does not wait on them
1074 int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
1075 struct extent_io_tree *dirty_pages, int mark)
1079 struct address_space *mapping = fs_info->btree_inode->i_mapping;
1080 struct extent_state *cached_state = NULL;
1084 while (find_first_extent_bit(dirty_pages, start, &start, &end,
1085 mark, &cached_state)) {
1086 bool wait_writeback = false;
1088 err = convert_extent_bit(dirty_pages, start, end,
1090 mark, &cached_state);
1092 * convert_extent_bit can return -ENOMEM, which is most of the
1093 * time a temporary error. So when it happens, ignore the error
1094 * and wait for writeback of this range to finish - because we
1095 * failed to set the bit EXTENT_NEED_WAIT for the range, a call
1096 * to __btrfs_wait_marked_extents() would not know that
1097 * writeback for this range started and therefore wouldn't
1098 * wait for it to finish - we don't want to commit a
1099 * superblock that points to btree nodes/leafs for which
1100 * writeback hasn't finished yet (and without errors).
1101 * We cleanup any entries left in the io tree when committing
1102 * the transaction (through extent_io_tree_release()).
1104 if (err == -ENOMEM) {
1106 wait_writeback = true;
1109 err = filemap_fdatawrite_range(mapping, start, end);
1112 else if (wait_writeback)
1113 werr = filemap_fdatawait_range(mapping, start, end);
1114 free_extent_state(cached_state);
1115 cached_state = NULL;
1123 * when btree blocks are allocated, they have some corresponding bits set for
1124 * them in one of two extent_io trees. This is used to make sure all of
1125 * those extents are on disk for transaction or log commit. We wait
1126 * on all the pages and clear them from the dirty pages state tree
1128 static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
1129 struct extent_io_tree *dirty_pages)
1133 struct address_space *mapping = fs_info->btree_inode->i_mapping;
1134 struct extent_state *cached_state = NULL;
1138 while (find_first_extent_bit(dirty_pages, start, &start, &end,
1139 EXTENT_NEED_WAIT, &cached_state)) {
1141 * Ignore -ENOMEM errors returned by clear_extent_bit().
1142 * When committing the transaction, we'll remove any entries
1143 * left in the io tree. For a log commit, we don't remove them
1144 * after committing the log because the tree can be accessed
1145 * concurrently - we do it only at transaction commit time when
1146 * it's safe to do it (through extent_io_tree_release()).
1148 err = clear_extent_bit(dirty_pages, start, end,
1149 EXTENT_NEED_WAIT, &cached_state);
1153 err = filemap_fdatawait_range(mapping, start, end);
1156 free_extent_state(cached_state);
1157 cached_state = NULL;
1166 static int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
1167 struct extent_io_tree *dirty_pages)
1169 bool errors = false;
1172 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1173 if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1181 int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
1183 struct btrfs_fs_info *fs_info = log_root->fs_info;
1184 struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
1185 bool errors = false;
1188 ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
1190 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1191 if ((mark & EXTENT_DIRTY) &&
1192 test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1195 if ((mark & EXTENT_NEW) &&
1196 test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1205 * When btree blocks are allocated the corresponding extents are marked dirty.
1206 * This function ensures such extents are persisted on disk for transaction or
1209 * @trans: transaction whose dirty pages we'd like to write
1211 static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1215 struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
1216 struct btrfs_fs_info *fs_info = trans->fs_info;
1217 struct blk_plug plug;
1219 blk_start_plug(&plug);
1220 ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1221 blk_finish_plug(&plug);
1222 ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1224 extent_io_tree_release(&trans->transaction->dirty_pages);
1235 * this is used to update the root pointer in the tree of tree roots.
1237 * But, in the case of the extent allocation tree, updating the root
1238 * pointer may allocate blocks which may change the root of the extent
1241 * So, this loops and repeats and makes sure the cowonly root didn't
1242 * change while the root pointer was being updated in the metadata.
1244 static int update_cowonly_root(struct btrfs_trans_handle *trans,
1245 struct btrfs_root *root)
1248 u64 old_root_bytenr;
1250 struct btrfs_fs_info *fs_info = root->fs_info;
1251 struct btrfs_root *tree_root = fs_info->tree_root;
1253 old_root_used = btrfs_root_used(&root->root_item);
1256 old_root_bytenr = btrfs_root_bytenr(&root->root_item);
1257 if (old_root_bytenr == root->node->start &&
1258 old_root_used == btrfs_root_used(&root->root_item))
1261 btrfs_set_root_node(&root->root_item, root->node);
1262 ret = btrfs_update_root(trans, tree_root,
1268 old_root_used = btrfs_root_used(&root->root_item);
1275 * update all the cowonly tree roots on disk
1277 * The error handling in this function may not be obvious. Any of the
1278 * failures will cause the file system to go offline. We still need
1279 * to clean up the delayed refs.
1281 static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
1283 struct btrfs_fs_info *fs_info = trans->fs_info;
1284 struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
1285 struct list_head *io_bgs = &trans->transaction->io_bgs;
1286 struct list_head *next;
1287 struct extent_buffer *eb;
1291 * At this point no one can be using this transaction to modify any tree
1292 * and no one can start another transaction to modify any tree either.
1294 ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1296 eb = btrfs_lock_root_node(fs_info->tree_root);
1297 ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
1298 0, &eb, BTRFS_NESTING_COW);
1299 btrfs_tree_unlock(eb);
1300 free_extent_buffer(eb);
1305 ret = btrfs_run_dev_stats(trans);
1308 ret = btrfs_run_dev_replace(trans);
1311 ret = btrfs_run_qgroups(trans);
1315 ret = btrfs_setup_space_cache(trans);
1320 while (!list_empty(&fs_info->dirty_cowonly_roots)) {
1321 struct btrfs_root *root;
1322 next = fs_info->dirty_cowonly_roots.next;
1323 list_del_init(next);
1324 root = list_entry(next, struct btrfs_root, dirty_list);
1325 clear_bit(BTRFS_ROOT_DIRTY, &root->state);
1327 list_add_tail(&root->dirty_list,
1328 &trans->transaction->switch_commits);
1329 ret = update_cowonly_root(trans, root);
1334 /* Now flush any delayed refs generated by updating all of the roots */
1335 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1339 while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
1340 ret = btrfs_write_dirty_block_groups(trans);
1345 * We're writing the dirty block groups, which could generate
1346 * delayed refs, which could generate more dirty block groups,
1347 * so we want to keep this flushing in this loop to make sure
1348 * everything gets run.
1350 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1355 if (!list_empty(&fs_info->dirty_cowonly_roots))
1358 /* Update dev-replace pointer once everything is committed */
1359 fs_info->dev_replace.committed_cursor_left =
1360 fs_info->dev_replace.cursor_left_last_write_of_item;
1366 * If we had a pending drop we need to see if there are any others left in our
1367 * dead roots list, and if not clear our bit and wake any waiters.
1369 void btrfs_maybe_wake_unfinished_drop(struct btrfs_fs_info *fs_info)
1372 * We put the drop in progress roots at the front of the list, so if the
1373 * first entry doesn't have UNFINISHED_DROP set we can wake everybody
1376 spin_lock(&fs_info->trans_lock);
1377 if (!list_empty(&fs_info->dead_roots)) {
1378 struct btrfs_root *root = list_first_entry(&fs_info->dead_roots,
1381 if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state)) {
1382 spin_unlock(&fs_info->trans_lock);
1386 spin_unlock(&fs_info->trans_lock);
1388 btrfs_wake_unfinished_drop(fs_info);
1392 * dead roots are old snapshots that need to be deleted. This allocates
1393 * a dirty root struct and adds it into the list of dead roots that need to
1396 void btrfs_add_dead_root(struct btrfs_root *root)
1398 struct btrfs_fs_info *fs_info = root->fs_info;
1400 spin_lock(&fs_info->trans_lock);
1401 if (list_empty(&root->root_list)) {
1402 btrfs_grab_root(root);
1404 /* We want to process the partially complete drops first. */
1405 if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state))
1406 list_add(&root->root_list, &fs_info->dead_roots);
1408 list_add_tail(&root->root_list, &fs_info->dead_roots);
1410 spin_unlock(&fs_info->trans_lock);
1414 * Update each subvolume root and its relocation root, if it exists, in the tree
1415 * of tree roots. Also free log roots if they exist.
1417 static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
1419 struct btrfs_fs_info *fs_info = trans->fs_info;
1420 struct btrfs_root *gang[8];
1425 * At this point no one can be using this transaction to modify any tree
1426 * and no one can start another transaction to modify any tree either.
1428 ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1430 spin_lock(&fs_info->fs_roots_radix_lock);
1432 ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
1435 BTRFS_ROOT_TRANS_TAG);
1438 for (i = 0; i < ret; i++) {
1439 struct btrfs_root *root = gang[i];
1443 * At this point we can neither have tasks logging inodes
1444 * from a root nor trying to commit a log tree.
1446 ASSERT(atomic_read(&root->log_writers) == 0);
1447 ASSERT(atomic_read(&root->log_commit[0]) == 0);
1448 ASSERT(atomic_read(&root->log_commit[1]) == 0);
1450 radix_tree_tag_clear(&fs_info->fs_roots_radix,
1451 (unsigned long)root->root_key.objectid,
1452 BTRFS_ROOT_TRANS_TAG);
1453 spin_unlock(&fs_info->fs_roots_radix_lock);
1455 btrfs_free_log(trans, root);
1456 ret2 = btrfs_update_reloc_root(trans, root);
1460 /* see comments in should_cow_block() */
1461 clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1462 smp_mb__after_atomic();
1464 if (root->commit_root != root->node) {
1465 list_add_tail(&root->dirty_list,
1466 &trans->transaction->switch_commits);
1467 btrfs_set_root_node(&root->root_item,
1471 ret2 = btrfs_update_root(trans, fs_info->tree_root,
1476 spin_lock(&fs_info->fs_roots_radix_lock);
1477 btrfs_qgroup_free_meta_all_pertrans(root);
1480 spin_unlock(&fs_info->fs_roots_radix_lock);
1485 * defrag a given btree.
1486 * Every leaf in the btree is read and defragged.
1488 int btrfs_defrag_root(struct btrfs_root *root)
1490 struct btrfs_fs_info *info = root->fs_info;
1491 struct btrfs_trans_handle *trans;
1494 if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
1498 trans = btrfs_start_transaction(root, 0);
1499 if (IS_ERR(trans)) {
1500 ret = PTR_ERR(trans);
1504 ret = btrfs_defrag_leaves(trans, root);
1506 btrfs_end_transaction(trans);
1507 btrfs_btree_balance_dirty(info);
1510 if (btrfs_fs_closing(info) || ret != -EAGAIN)
1513 if (btrfs_defrag_cancelled(info)) {
1514 btrfs_debug(info, "defrag_root cancelled");
1519 clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
1524 * Do all special snapshot related qgroup dirty hack.
1526 * Will do all needed qgroup inherit and dirty hack like switch commit
1527 * roots inside one transaction and write all btree into disk, to make
1530 static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
1531 struct btrfs_root *src,
1532 struct btrfs_root *parent,
1533 struct btrfs_qgroup_inherit *inherit,
1536 struct btrfs_fs_info *fs_info = src->fs_info;
1540 * Save some performance in the case that qgroups are not
1541 * enabled. If this check races with the ioctl, rescan will
1544 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1548 * Ensure dirty @src will be committed. Or, after coming
1549 * commit_fs_roots() and switch_commit_roots(), any dirty but not
1550 * recorded root will never be updated again, causing an outdated root
1553 ret = record_root_in_trans(trans, src, 1);
1558 * btrfs_qgroup_inherit relies on a consistent view of the usage for the
1559 * src root, so we must run the delayed refs here.
1561 * However this isn't particularly fool proof, because there's no
1562 * synchronization keeping us from changing the tree after this point
1563 * before we do the qgroup_inherit, or even from making changes while
1564 * we're doing the qgroup_inherit. But that's a problem for the future,
1565 * for now flush the delayed refs to narrow the race window where the
1566 * qgroup counters could end up wrong.
1568 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1570 btrfs_abort_transaction(trans, ret);
1574 ret = commit_fs_roots(trans);
1577 ret = btrfs_qgroup_account_extents(trans);
1581 /* Now qgroup are all updated, we can inherit it to new qgroups */
1582 ret = btrfs_qgroup_inherit(trans, src->root_key.objectid, dst_objectid,
1588 * Now we do a simplified commit transaction, which will:
1589 * 1) commit all subvolume and extent tree
1590 * To ensure all subvolume and extent tree have a valid
1591 * commit_root to accounting later insert_dir_item()
1592 * 2) write all btree blocks onto disk
1593 * This is to make sure later btree modification will be cowed
1594 * Or commit_root can be populated and cause wrong qgroup numbers
1595 * In this simplified commit, we don't really care about other trees
1596 * like chunk and root tree, as they won't affect qgroup.
1597 * And we don't write super to avoid half committed status.
1599 ret = commit_cowonly_roots(trans);
1602 switch_commit_roots(trans);
1603 ret = btrfs_write_and_wait_transaction(trans);
1605 btrfs_handle_fs_error(fs_info, ret,
1606 "Error while writing out transaction for qgroup");
1610 * Force parent root to be updated, as we recorded it before so its
1611 * last_trans == cur_transid.
1612 * Or it won't be committed again onto disk after later
1616 ret = record_root_in_trans(trans, parent, 1);
1621 * new snapshots need to be created at a very specific time in the
1622 * transaction commit. This does the actual creation.
1625 * If the error which may affect the commitment of the current transaction
1626 * happens, we should return the error number. If the error which just affect
1627 * the creation of the pending snapshots, just return 0.
1629 static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
1630 struct btrfs_pending_snapshot *pending)
1633 struct btrfs_fs_info *fs_info = trans->fs_info;
1634 struct btrfs_key key;
1635 struct btrfs_root_item *new_root_item;
1636 struct btrfs_root *tree_root = fs_info->tree_root;
1637 struct btrfs_root *root = pending->root;
1638 struct btrfs_root *parent_root;
1639 struct btrfs_block_rsv *rsv;
1640 struct inode *parent_inode = pending->dir;
1641 struct btrfs_path *path;
1642 struct btrfs_dir_item *dir_item;
1643 struct extent_buffer *tmp;
1644 struct extent_buffer *old;
1645 struct timespec64 cur_time;
1651 unsigned int nofs_flags;
1652 struct fscrypt_name fname;
1654 ASSERT(pending->path);
1655 path = pending->path;
1657 ASSERT(pending->root_item);
1658 new_root_item = pending->root_item;
1661 * We're inside a transaction and must make sure that any potential
1662 * allocations with GFP_KERNEL in fscrypt won't recurse back to
1665 nofs_flags = memalloc_nofs_save();
1666 pending->error = fscrypt_setup_filename(parent_inode,
1667 &pending->dentry->d_name, 0,
1669 memalloc_nofs_restore(nofs_flags);
1673 pending->error = btrfs_get_free_objectid(tree_root, &objectid);
1678 * Make qgroup to skip current new snapshot's qgroupid, as it is
1679 * accounted by later btrfs_qgroup_inherit().
1681 btrfs_set_skip_qgroup(trans, objectid);
1683 btrfs_reloc_pre_snapshot(pending, &to_reserve);
1685 if (to_reserve > 0) {
1686 pending->error = btrfs_block_rsv_add(fs_info,
1687 &pending->block_rsv,
1689 BTRFS_RESERVE_NO_FLUSH);
1691 goto clear_skip_qgroup;
1694 key.objectid = objectid;
1695 key.offset = (u64)-1;
1696 key.type = BTRFS_ROOT_ITEM_KEY;
1698 rsv = trans->block_rsv;
1699 trans->block_rsv = &pending->block_rsv;
1700 trans->bytes_reserved = trans->block_rsv->reserved;
1701 trace_btrfs_space_reservation(fs_info, "transaction",
1703 trans->bytes_reserved, 1);
1704 parent_root = BTRFS_I(parent_inode)->root;
1705 ret = record_root_in_trans(trans, parent_root, 0);
1708 cur_time = current_time(parent_inode);
1711 * insert the directory item
1713 ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
1715 btrfs_abort_transaction(trans, ret);
1719 /* check if there is a file/dir which has the same name. */
1720 dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
1721 btrfs_ino(BTRFS_I(parent_inode)),
1722 &fname.disk_name, 0);
1723 if (dir_item != NULL && !IS_ERR(dir_item)) {
1724 pending->error = -EEXIST;
1725 goto dir_item_existed;
1726 } else if (IS_ERR(dir_item)) {
1727 ret = PTR_ERR(dir_item);
1728 btrfs_abort_transaction(trans, ret);
1731 btrfs_release_path(path);
1734 * pull in the delayed directory update
1735 * and the delayed inode item
1736 * otherwise we corrupt the FS during
1739 ret = btrfs_run_delayed_items(trans);
1740 if (ret) { /* Transaction aborted */
1741 btrfs_abort_transaction(trans, ret);
1745 ret = record_root_in_trans(trans, root, 0);
1747 btrfs_abort_transaction(trans, ret);
1750 btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
1751 memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
1752 btrfs_check_and_init_root_item(new_root_item);
1754 root_flags = btrfs_root_flags(new_root_item);
1755 if (pending->readonly)
1756 root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1758 root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1759 btrfs_set_root_flags(new_root_item, root_flags);
1761 btrfs_set_root_generation_v2(new_root_item,
1763 generate_random_guid(new_root_item->uuid);
1764 memcpy(new_root_item->parent_uuid, root->root_item.uuid,
1766 if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
1767 memset(new_root_item->received_uuid, 0,
1768 sizeof(new_root_item->received_uuid));
1769 memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
1770 memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
1771 btrfs_set_root_stransid(new_root_item, 0);
1772 btrfs_set_root_rtransid(new_root_item, 0);
1774 btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
1775 btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
1776 btrfs_set_root_otransid(new_root_item, trans->transid);
1778 old = btrfs_lock_root_node(root);
1779 ret = btrfs_cow_block(trans, root, old, NULL, 0, &old,
1782 btrfs_tree_unlock(old);
1783 free_extent_buffer(old);
1784 btrfs_abort_transaction(trans, ret);
1788 ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
1789 /* clean up in any case */
1790 btrfs_tree_unlock(old);
1791 free_extent_buffer(old);
1793 btrfs_abort_transaction(trans, ret);
1796 /* see comments in should_cow_block() */
1797 set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1800 btrfs_set_root_node(new_root_item, tmp);
1801 /* record when the snapshot was created in key.offset */
1802 key.offset = trans->transid;
1803 ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1804 btrfs_tree_unlock(tmp);
1805 free_extent_buffer(tmp);
1807 btrfs_abort_transaction(trans, ret);
1812 * insert root back/forward references
1814 ret = btrfs_add_root_ref(trans, objectid,
1815 parent_root->root_key.objectid,
1816 btrfs_ino(BTRFS_I(parent_inode)), index,
1819 btrfs_abort_transaction(trans, ret);
1823 key.offset = (u64)-1;
1824 pending->snap = btrfs_get_new_fs_root(fs_info, objectid, pending->anon_dev);
1825 if (IS_ERR(pending->snap)) {
1826 ret = PTR_ERR(pending->snap);
1827 pending->snap = NULL;
1828 btrfs_abort_transaction(trans, ret);
1832 ret = btrfs_reloc_post_snapshot(trans, pending);
1834 btrfs_abort_transaction(trans, ret);
1839 * Do special qgroup accounting for snapshot, as we do some qgroup
1840 * snapshot hack to do fast snapshot.
1841 * To co-operate with that hack, we do hack again.
1842 * Or snapshot will be greatly slowed down by a subtree qgroup rescan
1844 ret = qgroup_account_snapshot(trans, root, parent_root,
1845 pending->inherit, objectid);
1849 ret = btrfs_insert_dir_item(trans, &fname.disk_name,
1850 BTRFS_I(parent_inode), &key, BTRFS_FT_DIR,
1852 /* We have check then name at the beginning, so it is impossible. */
1853 BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
1855 btrfs_abort_transaction(trans, ret);
1859 btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
1860 fname.disk_name.len * 2);
1861 parent_inode->i_mtime = inode_set_ctime_current(parent_inode);
1862 ret = btrfs_update_inode_fallback(trans, parent_root, BTRFS_I(parent_inode));
1864 btrfs_abort_transaction(trans, ret);
1867 ret = btrfs_uuid_tree_add(trans, new_root_item->uuid,
1868 BTRFS_UUID_KEY_SUBVOL,
1871 btrfs_abort_transaction(trans, ret);
1874 if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1875 ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1876 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1878 if (ret && ret != -EEXIST) {
1879 btrfs_abort_transaction(trans, ret);
1885 pending->error = ret;
1887 trans->block_rsv = rsv;
1888 trans->bytes_reserved = 0;
1890 btrfs_clear_skip_qgroup(trans);
1892 fscrypt_free_filename(&fname);
1894 kfree(new_root_item);
1895 pending->root_item = NULL;
1896 btrfs_free_path(path);
1897 pending->path = NULL;
1903 * create all the snapshots we've scheduled for creation
1905 static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
1907 struct btrfs_pending_snapshot *pending, *next;
1908 struct list_head *head = &trans->transaction->pending_snapshots;
1911 list_for_each_entry_safe(pending, next, head, list) {
1912 list_del(&pending->list);
1913 ret = create_pending_snapshot(trans, pending);
1920 static void update_super_roots(struct btrfs_fs_info *fs_info)
1922 struct btrfs_root_item *root_item;
1923 struct btrfs_super_block *super;
1925 super = fs_info->super_copy;
1927 root_item = &fs_info->chunk_root->root_item;
1928 super->chunk_root = root_item->bytenr;
1929 super->chunk_root_generation = root_item->generation;
1930 super->chunk_root_level = root_item->level;
1932 root_item = &fs_info->tree_root->root_item;
1933 super->root = root_item->bytenr;
1934 super->generation = root_item->generation;
1935 super->root_level = root_item->level;
1936 if (btrfs_test_opt(fs_info, SPACE_CACHE))
1937 super->cache_generation = root_item->generation;
1938 else if (test_bit(BTRFS_FS_CLEANUP_SPACE_CACHE_V1, &fs_info->flags))
1939 super->cache_generation = 0;
1940 if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1941 super->uuid_tree_generation = root_item->generation;
1944 int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1946 struct btrfs_transaction *trans;
1949 spin_lock(&info->trans_lock);
1950 trans = info->running_transaction;
1952 ret = (trans->state >= TRANS_STATE_COMMIT_START);
1953 spin_unlock(&info->trans_lock);
1957 int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1959 struct btrfs_transaction *trans;
1962 spin_lock(&info->trans_lock);
1963 trans = info->running_transaction;
1965 ret = is_transaction_blocked(trans);
1966 spin_unlock(&info->trans_lock);
1970 void btrfs_commit_transaction_async(struct btrfs_trans_handle *trans)
1972 struct btrfs_fs_info *fs_info = trans->fs_info;
1973 struct btrfs_transaction *cur_trans;
1975 /* Kick the transaction kthread. */
1976 set_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
1977 wake_up_process(fs_info->transaction_kthread);
1979 /* take transaction reference */
1980 cur_trans = trans->transaction;
1981 refcount_inc(&cur_trans->use_count);
1983 btrfs_end_transaction(trans);
1986 * Wait for the current transaction commit to start and block
1987 * subsequent transaction joins
1989 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
1990 wait_event(fs_info->transaction_blocked_wait,
1991 cur_trans->state >= TRANS_STATE_COMMIT_START ||
1992 TRANS_ABORTED(cur_trans));
1993 btrfs_put_transaction(cur_trans);
1996 static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
1998 struct btrfs_fs_info *fs_info = trans->fs_info;
1999 struct btrfs_transaction *cur_trans = trans->transaction;
2001 WARN_ON(refcount_read(&trans->use_count) > 1);
2003 btrfs_abort_transaction(trans, err);
2005 spin_lock(&fs_info->trans_lock);
2008 * If the transaction is removed from the list, it means this
2009 * transaction has been committed successfully, so it is impossible
2010 * to call the cleanup function.
2012 BUG_ON(list_empty(&cur_trans->list));
2014 if (cur_trans == fs_info->running_transaction) {
2015 cur_trans->state = TRANS_STATE_COMMIT_DOING;
2016 spin_unlock(&fs_info->trans_lock);
2019 * The thread has already released the lockdep map as reader
2020 * already in btrfs_commit_transaction().
2022 btrfs_might_wait_for_event(fs_info, btrfs_trans_num_writers);
2023 wait_event(cur_trans->writer_wait,
2024 atomic_read(&cur_trans->num_writers) == 1);
2026 spin_lock(&fs_info->trans_lock);
2030 * Now that we know no one else is still using the transaction we can
2031 * remove the transaction from the list of transactions. This avoids
2032 * the transaction kthread from cleaning up the transaction while some
2033 * other task is still using it, which could result in a use-after-free
2034 * on things like log trees, as it forces the transaction kthread to
2035 * wait for this transaction to be cleaned up by us.
2037 list_del_init(&cur_trans->list);
2039 spin_unlock(&fs_info->trans_lock);
2041 btrfs_cleanup_one_transaction(trans->transaction, fs_info);
2043 spin_lock(&fs_info->trans_lock);
2044 if (cur_trans == fs_info->running_transaction)
2045 fs_info->running_transaction = NULL;
2046 spin_unlock(&fs_info->trans_lock);
2048 if (trans->type & __TRANS_FREEZABLE)
2049 sb_end_intwrite(fs_info->sb);
2050 btrfs_put_transaction(cur_trans);
2051 btrfs_put_transaction(cur_trans);
2053 trace_btrfs_transaction_commit(fs_info);
2055 if (current->journal_info == trans)
2056 current->journal_info = NULL;
2059 * If relocation is running, we can't cancel scrub because that will
2060 * result in a deadlock. Before relocating a block group, relocation
2061 * pauses scrub, then starts and commits a transaction before unpausing
2062 * scrub. If the transaction commit is being done by the relocation
2063 * task or triggered by another task and the relocation task is waiting
2064 * for the commit, and we end up here due to an error in the commit
2065 * path, then calling btrfs_scrub_cancel() will deadlock, as we are
2066 * asking for scrub to stop while having it asked to be paused higher
2067 * above in relocation code.
2069 if (!test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
2070 btrfs_scrub_cancel(fs_info);
2072 kmem_cache_free(btrfs_trans_handle_cachep, trans);
2076 * Release reserved delayed ref space of all pending block groups of the
2077 * transaction and remove them from the list
2079 static void btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle *trans)
2081 struct btrfs_fs_info *fs_info = trans->fs_info;
2082 struct btrfs_block_group *block_group, *tmp;
2084 list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
2085 btrfs_delayed_refs_rsv_release(fs_info, 1);
2086 list_del_init(&block_group->bg_list);
2090 static inline int btrfs_start_delalloc_flush(struct btrfs_fs_info *fs_info)
2093 * We use try_to_writeback_inodes_sb() here because if we used
2094 * btrfs_start_delalloc_roots we would deadlock with fs freeze.
2095 * Currently are holding the fs freeze lock, if we do an async flush
2096 * we'll do btrfs_join_transaction() and deadlock because we need to
2097 * wait for the fs freeze lock. Using the direct flushing we benefit
2098 * from already being in a transaction and our join_transaction doesn't
2099 * have to re-take the fs freeze lock.
2101 * Note that try_to_writeback_inodes_sb() will only trigger writeback
2102 * if it can read lock sb->s_umount. It will always be able to lock it,
2103 * except when the filesystem is being unmounted or being frozen, but in
2104 * those cases sync_filesystem() is called, which results in calling
2105 * writeback_inodes_sb() while holding a write lock on sb->s_umount.
2106 * Note that we don't call writeback_inodes_sb() directly, because it
2107 * will emit a warning if sb->s_umount is not locked.
2109 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2110 try_to_writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
2114 static inline void btrfs_wait_delalloc_flush(struct btrfs_fs_info *fs_info)
2116 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2117 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
2121 * Add a pending snapshot associated with the given transaction handle to the
2122 * respective handle. This must be called after the transaction commit started
2123 * and while holding fs_info->trans_lock.
2124 * This serves to guarantee a caller of btrfs_commit_transaction() that it can
2125 * safely free the pending snapshot pointer in case btrfs_commit_transaction()
2128 static void add_pending_snapshot(struct btrfs_trans_handle *trans)
2130 struct btrfs_transaction *cur_trans = trans->transaction;
2132 if (!trans->pending_snapshot)
2135 lockdep_assert_held(&trans->fs_info->trans_lock);
2136 ASSERT(cur_trans->state >= TRANS_STATE_COMMIT_PREP);
2138 list_add(&trans->pending_snapshot->list, &cur_trans->pending_snapshots);
2141 static void update_commit_stats(struct btrfs_fs_info *fs_info, ktime_t interval)
2143 fs_info->commit_stats.commit_count++;
2144 fs_info->commit_stats.last_commit_dur = interval;
2145 fs_info->commit_stats.max_commit_dur =
2146 max_t(u64, fs_info->commit_stats.max_commit_dur, interval);
2147 fs_info->commit_stats.total_commit_dur += interval;
2150 int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
2152 struct btrfs_fs_info *fs_info = trans->fs_info;
2153 struct btrfs_transaction *cur_trans = trans->transaction;
2154 struct btrfs_transaction *prev_trans = NULL;
2159 ASSERT(refcount_read(&trans->use_count) == 1);
2160 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2162 clear_bit(BTRFS_FS_NEED_TRANS_COMMIT, &fs_info->flags);
2164 /* Stop the commit early if ->aborted is set */
2165 if (TRANS_ABORTED(cur_trans)) {
2166 ret = cur_trans->aborted;
2167 goto lockdep_trans_commit_start_release;
2170 btrfs_trans_release_metadata(trans);
2171 trans->block_rsv = NULL;
2174 * We only want one transaction commit doing the flushing so we do not
2175 * waste a bunch of time on lock contention on the extent root node.
2177 if (!test_and_set_bit(BTRFS_DELAYED_REFS_FLUSHING,
2178 &cur_trans->delayed_refs.flags)) {
2180 * Make a pass through all the delayed refs we have so far.
2181 * Any running threads may add more while we are here.
2183 ret = btrfs_run_delayed_refs(trans, 0);
2185 goto lockdep_trans_commit_start_release;
2188 btrfs_create_pending_block_groups(trans);
2190 if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
2193 /* this mutex is also taken before trying to set
2194 * block groups readonly. We need to make sure
2195 * that nobody has set a block group readonly
2196 * after a extents from that block group have been
2197 * allocated for cache files. btrfs_set_block_group_ro
2198 * will wait for the transaction to commit if it
2199 * finds BTRFS_TRANS_DIRTY_BG_RUN set.
2201 * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
2202 * only one process starts all the block group IO. It wouldn't
2203 * hurt to have more than one go through, but there's no
2204 * real advantage to it either.
2206 mutex_lock(&fs_info->ro_block_group_mutex);
2207 if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
2210 mutex_unlock(&fs_info->ro_block_group_mutex);
2213 ret = btrfs_start_dirty_block_groups(trans);
2215 goto lockdep_trans_commit_start_release;
2219 spin_lock(&fs_info->trans_lock);
2220 if (cur_trans->state >= TRANS_STATE_COMMIT_PREP) {
2221 enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2223 add_pending_snapshot(trans);
2225 spin_unlock(&fs_info->trans_lock);
2226 refcount_inc(&cur_trans->use_count);
2228 if (trans->in_fsync)
2229 want_state = TRANS_STATE_SUPER_COMMITTED;
2231 btrfs_trans_state_lockdep_release(fs_info,
2232 BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2233 ret = btrfs_end_transaction(trans);
2234 wait_for_commit(cur_trans, want_state);
2236 if (TRANS_ABORTED(cur_trans))
2237 ret = cur_trans->aborted;
2239 btrfs_put_transaction(cur_trans);
2244 cur_trans->state = TRANS_STATE_COMMIT_PREP;
2245 wake_up(&fs_info->transaction_blocked_wait);
2246 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2248 if (cur_trans->list.prev != &fs_info->trans_list) {
2249 enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2251 if (trans->in_fsync)
2252 want_state = TRANS_STATE_SUPER_COMMITTED;
2254 prev_trans = list_entry(cur_trans->list.prev,
2255 struct btrfs_transaction, list);
2256 if (prev_trans->state < want_state) {
2257 refcount_inc(&prev_trans->use_count);
2258 spin_unlock(&fs_info->trans_lock);
2260 wait_for_commit(prev_trans, want_state);
2262 ret = READ_ONCE(prev_trans->aborted);
2264 btrfs_put_transaction(prev_trans);
2266 goto lockdep_release;
2267 spin_lock(&fs_info->trans_lock);
2271 * The previous transaction was aborted and was already removed
2272 * from the list of transactions at fs_info->trans_list. So we
2273 * abort to prevent writing a new superblock that reflects a
2274 * corrupt state (pointing to trees with unwritten nodes/leafs).
2276 if (BTRFS_FS_ERROR(fs_info)) {
2277 spin_unlock(&fs_info->trans_lock);
2279 goto lockdep_release;
2283 cur_trans->state = TRANS_STATE_COMMIT_START;
2284 wake_up(&fs_info->transaction_blocked_wait);
2285 spin_unlock(&fs_info->trans_lock);
2288 * Get the time spent on the work done by the commit thread and not
2289 * the time spent waiting on a previous commit
2291 start_time = ktime_get_ns();
2293 extwriter_counter_dec(cur_trans, trans->type);
2295 ret = btrfs_start_delalloc_flush(fs_info);
2297 goto lockdep_release;
2299 ret = btrfs_run_delayed_items(trans);
2301 goto lockdep_release;
2304 * The thread has started/joined the transaction thus it holds the
2305 * lockdep map as a reader. It has to release it before acquiring the
2306 * lockdep map as a writer.
2308 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2309 btrfs_might_wait_for_event(fs_info, btrfs_trans_num_extwriters);
2310 wait_event(cur_trans->writer_wait,
2311 extwriter_counter_read(cur_trans) == 0);
2313 /* some pending stuffs might be added after the previous flush. */
2314 ret = btrfs_run_delayed_items(trans);
2316 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2317 goto cleanup_transaction;
2320 btrfs_wait_delalloc_flush(fs_info);
2323 * Wait for all ordered extents started by a fast fsync that joined this
2324 * transaction. Otherwise if this transaction commits before the ordered
2325 * extents complete we lose logged data after a power failure.
2327 btrfs_might_wait_for_event(fs_info, btrfs_trans_pending_ordered);
2328 wait_event(cur_trans->pending_wait,
2329 atomic_read(&cur_trans->pending_ordered) == 0);
2331 btrfs_scrub_pause(fs_info);
2333 * Ok now we need to make sure to block out any other joins while we
2334 * commit the transaction. We could have started a join before setting
2335 * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2337 spin_lock(&fs_info->trans_lock);
2338 add_pending_snapshot(trans);
2339 cur_trans->state = TRANS_STATE_COMMIT_DOING;
2340 spin_unlock(&fs_info->trans_lock);
2343 * The thread has started/joined the transaction thus it holds the
2344 * lockdep map as a reader. It has to release it before acquiring the
2345 * lockdep map as a writer.
2347 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2348 btrfs_might_wait_for_event(fs_info, btrfs_trans_num_writers);
2349 wait_event(cur_trans->writer_wait,
2350 atomic_read(&cur_trans->num_writers) == 1);
2353 * Make lockdep happy by acquiring the state locks after
2354 * btrfs_trans_num_writers is released. If we acquired the state locks
2355 * before releasing the btrfs_trans_num_writers lock then lockdep would
2356 * complain because we did not follow the reverse order unlocking rule.
2358 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2359 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2360 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2363 * We've started the commit, clear the flag in case we were triggered to
2364 * do an async commit but somebody else started before the transaction
2365 * kthread could do the work.
2367 clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
2369 if (TRANS_ABORTED(cur_trans)) {
2370 ret = cur_trans->aborted;
2371 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2372 goto scrub_continue;
2375 * the reloc mutex makes sure that we stop
2376 * the balancing code from coming in and moving
2377 * extents around in the middle of the commit
2379 mutex_lock(&fs_info->reloc_mutex);
2382 * We needn't worry about the delayed items because we will
2383 * deal with them in create_pending_snapshot(), which is the
2384 * core function of the snapshot creation.
2386 ret = create_pending_snapshots(trans);
2391 * We insert the dir indexes of the snapshots and update the inode
2392 * of the snapshots' parents after the snapshot creation, so there
2393 * are some delayed items which are not dealt with. Now deal with
2396 * We needn't worry that this operation will corrupt the snapshots,
2397 * because all the tree which are snapshoted will be forced to COW
2398 * the nodes and leaves.
2400 ret = btrfs_run_delayed_items(trans);
2404 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2409 * make sure none of the code above managed to slip in a
2412 btrfs_assert_delayed_root_empty(fs_info);
2414 WARN_ON(cur_trans != trans->transaction);
2416 ret = commit_fs_roots(trans);
2420 /* commit_fs_roots gets rid of all the tree log roots, it is now
2421 * safe to free the root of tree log roots
2423 btrfs_free_log_root_tree(trans, fs_info);
2426 * Since fs roots are all committed, we can get a quite accurate
2427 * new_roots. So let's do quota accounting.
2429 ret = btrfs_qgroup_account_extents(trans);
2433 ret = commit_cowonly_roots(trans);
2438 * The tasks which save the space cache and inode cache may also
2439 * update ->aborted, check it.
2441 if (TRANS_ABORTED(cur_trans)) {
2442 ret = cur_trans->aborted;
2446 cur_trans = fs_info->running_transaction;
2448 btrfs_set_root_node(&fs_info->tree_root->root_item,
2449 fs_info->tree_root->node);
2450 list_add_tail(&fs_info->tree_root->dirty_list,
2451 &cur_trans->switch_commits);
2453 btrfs_set_root_node(&fs_info->chunk_root->root_item,
2454 fs_info->chunk_root->node);
2455 list_add_tail(&fs_info->chunk_root->dirty_list,
2456 &cur_trans->switch_commits);
2458 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
2459 btrfs_set_root_node(&fs_info->block_group_root->root_item,
2460 fs_info->block_group_root->node);
2461 list_add_tail(&fs_info->block_group_root->dirty_list,
2462 &cur_trans->switch_commits);
2465 switch_commit_roots(trans);
2467 ASSERT(list_empty(&cur_trans->dirty_bgs));
2468 ASSERT(list_empty(&cur_trans->io_bgs));
2469 update_super_roots(fs_info);
2471 btrfs_set_super_log_root(fs_info->super_copy, 0);
2472 btrfs_set_super_log_root_level(fs_info->super_copy, 0);
2473 memcpy(fs_info->super_for_commit, fs_info->super_copy,
2474 sizeof(*fs_info->super_copy));
2476 btrfs_commit_device_sizes(cur_trans);
2478 clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2479 clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2481 btrfs_trans_release_chunk_metadata(trans);
2484 * Before changing the transaction state to TRANS_STATE_UNBLOCKED and
2485 * setting fs_info->running_transaction to NULL, lock tree_log_mutex to
2486 * make sure that before we commit our superblock, no other task can
2487 * start a new transaction and commit a log tree before we commit our
2488 * superblock. Anyone trying to commit a log tree locks this mutex before
2489 * writing its superblock.
2491 mutex_lock(&fs_info->tree_log_mutex);
2493 spin_lock(&fs_info->trans_lock);
2494 cur_trans->state = TRANS_STATE_UNBLOCKED;
2495 fs_info->running_transaction = NULL;
2496 spin_unlock(&fs_info->trans_lock);
2497 mutex_unlock(&fs_info->reloc_mutex);
2499 wake_up(&fs_info->transaction_wait);
2500 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2502 /* If we have features changed, wake up the cleaner to update sysfs. */
2503 if (test_bit(BTRFS_FS_FEATURE_CHANGED, &fs_info->flags) &&
2504 fs_info->cleaner_kthread)
2505 wake_up_process(fs_info->cleaner_kthread);
2507 ret = btrfs_write_and_wait_transaction(trans);
2509 btrfs_handle_fs_error(fs_info, ret,
2510 "Error while writing out transaction");
2511 mutex_unlock(&fs_info->tree_log_mutex);
2512 goto scrub_continue;
2515 ret = write_all_supers(fs_info, 0);
2517 * the super is written, we can safely allow the tree-loggers
2518 * to go about their business
2520 mutex_unlock(&fs_info->tree_log_mutex);
2522 goto scrub_continue;
2525 * We needn't acquire the lock here because there is no other task
2526 * which can change it.
2528 cur_trans->state = TRANS_STATE_SUPER_COMMITTED;
2529 wake_up(&cur_trans->commit_wait);
2530 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2532 btrfs_finish_extent_commit(trans);
2534 if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
2535 btrfs_clear_space_info_full(fs_info);
2537 fs_info->last_trans_committed = cur_trans->transid;
2539 * We needn't acquire the lock here because there is no other task
2540 * which can change it.
2542 cur_trans->state = TRANS_STATE_COMPLETED;
2543 wake_up(&cur_trans->commit_wait);
2544 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2546 spin_lock(&fs_info->trans_lock);
2547 list_del_init(&cur_trans->list);
2548 spin_unlock(&fs_info->trans_lock);
2550 btrfs_put_transaction(cur_trans);
2551 btrfs_put_transaction(cur_trans);
2553 if (trans->type & __TRANS_FREEZABLE)
2554 sb_end_intwrite(fs_info->sb);
2556 trace_btrfs_transaction_commit(fs_info);
2558 interval = ktime_get_ns() - start_time;
2560 btrfs_scrub_continue(fs_info);
2562 if (current->journal_info == trans)
2563 current->journal_info = NULL;
2565 kmem_cache_free(btrfs_trans_handle_cachep, trans);
2567 update_commit_stats(fs_info, interval);
2572 mutex_unlock(&fs_info->reloc_mutex);
2573 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2575 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2576 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2577 btrfs_scrub_continue(fs_info);
2578 cleanup_transaction:
2579 btrfs_trans_release_metadata(trans);
2580 btrfs_cleanup_pending_block_groups(trans);
2581 btrfs_trans_release_chunk_metadata(trans);
2582 trans->block_rsv = NULL;
2583 btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
2584 if (current->journal_info == trans)
2585 current->journal_info = NULL;
2586 cleanup_transaction(trans, ret);
2591 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2592 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2593 goto cleanup_transaction;
2595 lockdep_trans_commit_start_release:
2596 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2597 btrfs_end_transaction(trans);
2602 * return < 0 if error
2603 * 0 if there are no more dead_roots at the time of call
2604 * 1 there are more to be processed, call me again
2606 * The return value indicates there are certainly more snapshots to delete, but
2607 * if there comes a new one during processing, it may return 0. We don't mind,
2608 * because btrfs_commit_super will poke cleaner thread and it will process it a
2609 * few seconds later.
2611 int btrfs_clean_one_deleted_snapshot(struct btrfs_fs_info *fs_info)
2613 struct btrfs_root *root;
2616 spin_lock(&fs_info->trans_lock);
2617 if (list_empty(&fs_info->dead_roots)) {
2618 spin_unlock(&fs_info->trans_lock);
2621 root = list_first_entry(&fs_info->dead_roots,
2622 struct btrfs_root, root_list);
2623 list_del_init(&root->root_list);
2624 spin_unlock(&fs_info->trans_lock);
2626 btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
2628 btrfs_kill_all_delayed_nodes(root);
2630 if (btrfs_header_backref_rev(root->node) <
2631 BTRFS_MIXED_BACKREF_REV)
2632 ret = btrfs_drop_snapshot(root, 0, 0);
2634 ret = btrfs_drop_snapshot(root, 1, 0);
2636 btrfs_put_root(root);
2637 return (ret < 0) ? 0 : 1;
2641 * We only mark the transaction aborted and then set the file system read-only.
2642 * This will prevent new transactions from starting or trying to join this
2645 * This means that error recovery at the call site is limited to freeing
2646 * any local memory allocations and passing the error code up without
2647 * further cleanup. The transaction should complete as it normally would
2648 * in the call path but will return -EIO.
2650 * We'll complete the cleanup in btrfs_end_transaction and
2651 * btrfs_commit_transaction.
2653 void __cold __btrfs_abort_transaction(struct btrfs_trans_handle *trans,
2654 const char *function,
2655 unsigned int line, int errno, bool first_hit)
2657 struct btrfs_fs_info *fs_info = trans->fs_info;
2659 WRITE_ONCE(trans->aborted, errno);
2660 WRITE_ONCE(trans->transaction->aborted, errno);
2661 if (first_hit && errno == -ENOSPC)
2662 btrfs_dump_space_info_for_trans_abort(fs_info);
2663 /* Wake up anybody who may be waiting on this transaction */
2664 wake_up(&fs_info->transaction_wait);
2665 wake_up(&fs_info->transaction_blocked_wait);
2666 __btrfs_handle_fs_error(fs_info, function, line, errno, NULL);
2669 int __init btrfs_transaction_init(void)
2671 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
2672 sizeof(struct btrfs_trans_handle), 0,
2673 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
2674 if (!btrfs_trans_handle_cachep)
2679 void __cold btrfs_transaction_exit(void)
2681 kmem_cache_destroy(btrfs_trans_handle_cachep);