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/writeback.h>
10 #include <linux/pagemap.h>
11 #include <linux/blkdev.h>
12 #include <linux/uuid.h>
13 #include <linux/timekeeping.h>
17 #include "transaction.h"
21 #include "dev-replace.h"
23 #include "block-group.h"
24 #include "space-info.h"
27 #define BTRFS_ROOT_TRANS_TAG 0
30 * Transaction states and transitions
32 * No running transaction (fs tree blocks are not modified)
35 * | Call start_transaction() variants. Except btrfs_join_transaction_nostart().
37 * Transaction N [[TRANS_STATE_RUNNING]]
39 * | New trans handles can be attached to transaction N by calling all
40 * | start_transaction() variants.
43 * | Call btrfs_commit_transaction() on any trans handle attached to
46 * Transaction N [[TRANS_STATE_COMMIT_START]]
48 * | Will wait for previous running transaction to completely finish if there
51 * | Then one of the following happes:
52 * | - Wait for all other trans handle holders to release.
53 * | The btrfs_commit_transaction() caller will do the commit work.
54 * | - Wait for current transaction to be committed by others.
55 * | Other btrfs_commit_transaction() caller will do the commit work.
57 * | At this stage, only btrfs_join_transaction*() variants can attach
58 * | to this running transaction.
59 * | All other variants will wait for current one to finish and attach to
63 * | Caller is chosen to commit transaction N, and all other trans handle
64 * | haven been released.
66 * Transaction N [[TRANS_STATE_COMMIT_DOING]]
68 * | The heavy lifting transaction work is started.
69 * | From running delayed refs (modifying extent tree) to creating pending
70 * | snapshots, running qgroups.
71 * | In short, modify supporting trees to reflect modifications of subvolume
74 * | At this stage, all start_transaction() calls will wait for this
75 * | transaction to finish and attach to transaction N+1.
78 * | Until all supporting trees are updated.
80 * Transaction N [[TRANS_STATE_UNBLOCKED]]
82 * | All needed trees are modified, thus we only [[TRANS_STATE_RUNNING]]
83 * | need to write them back to disk and update |
86 * | At this stage, new transaction is allowed to |
88 * | All new start_transaction() calls will be |
89 * | attached to transid N+1. |
92 * | Until all tree blocks are super blocks are |
93 * | written to block devices |
95 * Transaction N [[TRANS_STATE_COMPLETED]] V
96 * All tree blocks and super blocks are written. Transaction N+1
97 * This transaction is finished and all its [[TRANS_STATE_COMMIT_START]]
98 * data structures will be cleaned up. | Life goes on
100 static const unsigned int btrfs_blocked_trans_types[TRANS_STATE_MAX] = {
101 [TRANS_STATE_RUNNING] = 0U,
102 [TRANS_STATE_COMMIT_START] = (__TRANS_START | __TRANS_ATTACH),
103 [TRANS_STATE_COMMIT_DOING] = (__TRANS_START |
106 __TRANS_JOIN_NOSTART),
107 [TRANS_STATE_UNBLOCKED] = (__TRANS_START |
110 __TRANS_JOIN_NOLOCK |
111 __TRANS_JOIN_NOSTART),
112 [TRANS_STATE_SUPER_COMMITTED] = (__TRANS_START |
115 __TRANS_JOIN_NOLOCK |
116 __TRANS_JOIN_NOSTART),
117 [TRANS_STATE_COMPLETED] = (__TRANS_START |
120 __TRANS_JOIN_NOLOCK |
121 __TRANS_JOIN_NOSTART),
124 void btrfs_put_transaction(struct btrfs_transaction *transaction)
126 WARN_ON(refcount_read(&transaction->use_count) == 0);
127 if (refcount_dec_and_test(&transaction->use_count)) {
128 BUG_ON(!list_empty(&transaction->list));
129 WARN_ON(!RB_EMPTY_ROOT(
130 &transaction->delayed_refs.href_root.rb_root));
131 WARN_ON(!RB_EMPTY_ROOT(
132 &transaction->delayed_refs.dirty_extent_root));
133 if (transaction->delayed_refs.pending_csums)
134 btrfs_err(transaction->fs_info,
135 "pending csums is %llu",
136 transaction->delayed_refs.pending_csums);
138 * If any block groups are found in ->deleted_bgs then it's
139 * because the transaction was aborted and a commit did not
140 * happen (things failed before writing the new superblock
141 * and calling btrfs_finish_extent_commit()), so we can not
142 * discard the physical locations of the block groups.
144 while (!list_empty(&transaction->deleted_bgs)) {
145 struct btrfs_block_group *cache;
147 cache = list_first_entry(&transaction->deleted_bgs,
148 struct btrfs_block_group,
150 list_del_init(&cache->bg_list);
151 btrfs_unfreeze_block_group(cache);
152 btrfs_put_block_group(cache);
154 WARN_ON(!list_empty(&transaction->dev_update_list));
159 static noinline void switch_commit_roots(struct btrfs_trans_handle *trans)
161 struct btrfs_transaction *cur_trans = trans->transaction;
162 struct btrfs_fs_info *fs_info = trans->fs_info;
163 struct btrfs_root *root, *tmp;
166 * At this point no one can be using this transaction to modify any tree
167 * and no one can start another transaction to modify any tree either.
169 ASSERT(cur_trans->state == TRANS_STATE_COMMIT_DOING);
171 down_write(&fs_info->commit_root_sem);
173 if (test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
174 fs_info->last_reloc_trans = trans->transid;
176 list_for_each_entry_safe(root, tmp, &cur_trans->switch_commits,
178 list_del_init(&root->dirty_list);
179 free_extent_buffer(root->commit_root);
180 root->commit_root = btrfs_root_node(root);
181 extent_io_tree_release(&root->dirty_log_pages);
182 btrfs_qgroup_clean_swapped_blocks(root);
185 /* We can free old roots now. */
186 spin_lock(&cur_trans->dropped_roots_lock);
187 while (!list_empty(&cur_trans->dropped_roots)) {
188 root = list_first_entry(&cur_trans->dropped_roots,
189 struct btrfs_root, root_list);
190 list_del_init(&root->root_list);
191 spin_unlock(&cur_trans->dropped_roots_lock);
192 btrfs_free_log(trans, root);
193 btrfs_drop_and_free_fs_root(fs_info, root);
194 spin_lock(&cur_trans->dropped_roots_lock);
196 spin_unlock(&cur_trans->dropped_roots_lock);
198 up_write(&fs_info->commit_root_sem);
201 static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
204 if (type & TRANS_EXTWRITERS)
205 atomic_inc(&trans->num_extwriters);
208 static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
211 if (type & TRANS_EXTWRITERS)
212 atomic_dec(&trans->num_extwriters);
215 static inline void extwriter_counter_init(struct btrfs_transaction *trans,
218 atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
221 static inline int extwriter_counter_read(struct btrfs_transaction *trans)
223 return atomic_read(&trans->num_extwriters);
227 * To be called after doing the chunk btree updates right after allocating a new
228 * chunk (after btrfs_chunk_alloc_add_chunk_item() is called), when removing a
229 * chunk after all chunk btree updates and after finishing the second phase of
230 * chunk allocation (btrfs_create_pending_block_groups()) in case some block
231 * group had its chunk item insertion delayed to the second phase.
233 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
235 struct btrfs_fs_info *fs_info = trans->fs_info;
237 if (!trans->chunk_bytes_reserved)
240 btrfs_block_rsv_release(fs_info, &fs_info->chunk_block_rsv,
241 trans->chunk_bytes_reserved, NULL);
242 trans->chunk_bytes_reserved = 0;
246 * either allocate a new transaction or hop into the existing one
248 static noinline int join_transaction(struct btrfs_fs_info *fs_info,
251 struct btrfs_transaction *cur_trans;
253 spin_lock(&fs_info->trans_lock);
255 /* The file system has been taken offline. No new transactions. */
256 if (BTRFS_FS_ERROR(fs_info)) {
257 spin_unlock(&fs_info->trans_lock);
261 cur_trans = fs_info->running_transaction;
263 if (TRANS_ABORTED(cur_trans)) {
264 spin_unlock(&fs_info->trans_lock);
265 return cur_trans->aborted;
267 if (btrfs_blocked_trans_types[cur_trans->state] & type) {
268 spin_unlock(&fs_info->trans_lock);
271 refcount_inc(&cur_trans->use_count);
272 atomic_inc(&cur_trans->num_writers);
273 extwriter_counter_inc(cur_trans, type);
274 spin_unlock(&fs_info->trans_lock);
275 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_writers);
276 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_extwriters);
279 spin_unlock(&fs_info->trans_lock);
282 * If we are ATTACH, we just want to catch the current transaction,
283 * and commit it. If there is no transaction, just return ENOENT.
285 if (type == TRANS_ATTACH)
289 * JOIN_NOLOCK only happens during the transaction commit, so
290 * it is impossible that ->running_transaction is NULL
292 BUG_ON(type == TRANS_JOIN_NOLOCK);
294 cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
298 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_writers);
299 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_extwriters);
301 spin_lock(&fs_info->trans_lock);
302 if (fs_info->running_transaction) {
304 * someone started a transaction after we unlocked. Make sure
305 * to redo the checks above
307 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
308 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
311 } else if (BTRFS_FS_ERROR(fs_info)) {
312 spin_unlock(&fs_info->trans_lock);
313 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
314 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
319 cur_trans->fs_info = fs_info;
320 atomic_set(&cur_trans->pending_ordered, 0);
321 init_waitqueue_head(&cur_trans->pending_wait);
322 atomic_set(&cur_trans->num_writers, 1);
323 extwriter_counter_init(cur_trans, type);
324 init_waitqueue_head(&cur_trans->writer_wait);
325 init_waitqueue_head(&cur_trans->commit_wait);
326 cur_trans->state = TRANS_STATE_RUNNING;
328 * One for this trans handle, one so it will live on until we
329 * commit the transaction.
331 refcount_set(&cur_trans->use_count, 2);
332 cur_trans->flags = 0;
333 cur_trans->start_time = ktime_get_seconds();
335 memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
337 cur_trans->delayed_refs.href_root = RB_ROOT_CACHED;
338 cur_trans->delayed_refs.dirty_extent_root = RB_ROOT;
339 atomic_set(&cur_trans->delayed_refs.num_entries, 0);
342 * although the tree mod log is per file system and not per transaction,
343 * the log must never go across transaction boundaries.
346 if (!list_empty(&fs_info->tree_mod_seq_list))
347 WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
348 if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
349 WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
350 atomic64_set(&fs_info->tree_mod_seq, 0);
352 spin_lock_init(&cur_trans->delayed_refs.lock);
354 INIT_LIST_HEAD(&cur_trans->pending_snapshots);
355 INIT_LIST_HEAD(&cur_trans->dev_update_list);
356 INIT_LIST_HEAD(&cur_trans->switch_commits);
357 INIT_LIST_HEAD(&cur_trans->dirty_bgs);
358 INIT_LIST_HEAD(&cur_trans->io_bgs);
359 INIT_LIST_HEAD(&cur_trans->dropped_roots);
360 mutex_init(&cur_trans->cache_write_mutex);
361 spin_lock_init(&cur_trans->dirty_bgs_lock);
362 INIT_LIST_HEAD(&cur_trans->deleted_bgs);
363 spin_lock_init(&cur_trans->dropped_roots_lock);
364 INIT_LIST_HEAD(&cur_trans->releasing_ebs);
365 spin_lock_init(&cur_trans->releasing_ebs_lock);
366 list_add_tail(&cur_trans->list, &fs_info->trans_list);
367 extent_io_tree_init(fs_info, &cur_trans->dirty_pages,
368 IO_TREE_TRANS_DIRTY_PAGES, NULL);
369 extent_io_tree_init(fs_info, &cur_trans->pinned_extents,
370 IO_TREE_FS_PINNED_EXTENTS, NULL);
371 fs_info->generation++;
372 cur_trans->transid = fs_info->generation;
373 fs_info->running_transaction = cur_trans;
374 cur_trans->aborted = 0;
375 spin_unlock(&fs_info->trans_lock);
381 * This does all the record keeping required to make sure that a shareable root
382 * is properly recorded in a given transaction. This is required to make sure
383 * the old root from before we joined the transaction is deleted when the
384 * transaction commits.
386 static int record_root_in_trans(struct btrfs_trans_handle *trans,
387 struct btrfs_root *root,
390 struct btrfs_fs_info *fs_info = root->fs_info;
393 if ((test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
394 root->last_trans < trans->transid) || force) {
395 WARN_ON(!force && root->commit_root != root->node);
398 * see below for IN_TRANS_SETUP usage rules
399 * we have the reloc mutex held now, so there
400 * is only one writer in this function
402 set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
404 /* make sure readers find IN_TRANS_SETUP before
405 * they find our root->last_trans update
409 spin_lock(&fs_info->fs_roots_radix_lock);
410 if (root->last_trans == trans->transid && !force) {
411 spin_unlock(&fs_info->fs_roots_radix_lock);
414 radix_tree_tag_set(&fs_info->fs_roots_radix,
415 (unsigned long)root->root_key.objectid,
416 BTRFS_ROOT_TRANS_TAG);
417 spin_unlock(&fs_info->fs_roots_radix_lock);
418 root->last_trans = trans->transid;
420 /* this is pretty tricky. We don't want to
421 * take the relocation lock in btrfs_record_root_in_trans
422 * unless we're really doing the first setup for this root in
425 * Normally we'd use root->last_trans as a flag to decide
426 * if we want to take the expensive mutex.
428 * But, we have to set root->last_trans before we
429 * init the relocation root, otherwise, we trip over warnings
430 * in ctree.c. The solution used here is to flag ourselves
431 * with root IN_TRANS_SETUP. When this is 1, we're still
432 * fixing up the reloc trees and everyone must wait.
434 * When this is zero, they can trust root->last_trans and fly
435 * through btrfs_record_root_in_trans without having to take the
436 * lock. smp_wmb() makes sure that all the writes above are
437 * done before we pop in the zero below
439 ret = btrfs_init_reloc_root(trans, root);
440 smp_mb__before_atomic();
441 clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
447 void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
448 struct btrfs_root *root)
450 struct btrfs_fs_info *fs_info = root->fs_info;
451 struct btrfs_transaction *cur_trans = trans->transaction;
453 /* Add ourselves to the transaction dropped list */
454 spin_lock(&cur_trans->dropped_roots_lock);
455 list_add_tail(&root->root_list, &cur_trans->dropped_roots);
456 spin_unlock(&cur_trans->dropped_roots_lock);
458 /* Make sure we don't try to update the root at commit time */
459 spin_lock(&fs_info->fs_roots_radix_lock);
460 radix_tree_tag_clear(&fs_info->fs_roots_radix,
461 (unsigned long)root->root_key.objectid,
462 BTRFS_ROOT_TRANS_TAG);
463 spin_unlock(&fs_info->fs_roots_radix_lock);
466 int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
467 struct btrfs_root *root)
469 struct btrfs_fs_info *fs_info = root->fs_info;
472 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
476 * see record_root_in_trans for comments about IN_TRANS_SETUP usage
480 if (root->last_trans == trans->transid &&
481 !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
484 mutex_lock(&fs_info->reloc_mutex);
485 ret = record_root_in_trans(trans, root, 0);
486 mutex_unlock(&fs_info->reloc_mutex);
491 static inline int is_transaction_blocked(struct btrfs_transaction *trans)
493 return (trans->state >= TRANS_STATE_COMMIT_START &&
494 trans->state < TRANS_STATE_UNBLOCKED &&
495 !TRANS_ABORTED(trans));
498 /* wait for commit against the current transaction to become unblocked
499 * when this is done, it is safe to start a new transaction, but the current
500 * transaction might not be fully on disk.
502 static void wait_current_trans(struct btrfs_fs_info *fs_info)
504 struct btrfs_transaction *cur_trans;
506 spin_lock(&fs_info->trans_lock);
507 cur_trans = fs_info->running_transaction;
508 if (cur_trans && is_transaction_blocked(cur_trans)) {
509 refcount_inc(&cur_trans->use_count);
510 spin_unlock(&fs_info->trans_lock);
512 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
513 wait_event(fs_info->transaction_wait,
514 cur_trans->state >= TRANS_STATE_UNBLOCKED ||
515 TRANS_ABORTED(cur_trans));
516 btrfs_put_transaction(cur_trans);
518 spin_unlock(&fs_info->trans_lock);
522 static int may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
524 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
527 if (type == TRANS_START)
533 static inline bool need_reserve_reloc_root(struct btrfs_root *root)
535 struct btrfs_fs_info *fs_info = root->fs_info;
537 if (!fs_info->reloc_ctl ||
538 !test_bit(BTRFS_ROOT_SHAREABLE, &root->state) ||
539 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
546 static struct btrfs_trans_handle *
547 start_transaction(struct btrfs_root *root, unsigned int num_items,
548 unsigned int type, enum btrfs_reserve_flush_enum flush,
549 bool enforce_qgroups)
551 struct btrfs_fs_info *fs_info = root->fs_info;
552 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
553 struct btrfs_trans_handle *h;
554 struct btrfs_transaction *cur_trans;
556 u64 qgroup_reserved = 0;
557 bool reloc_reserved = false;
558 bool do_chunk_alloc = false;
561 if (BTRFS_FS_ERROR(fs_info))
562 return ERR_PTR(-EROFS);
564 if (current->journal_info) {
565 WARN_ON(type & TRANS_EXTWRITERS);
566 h = current->journal_info;
567 refcount_inc(&h->use_count);
568 WARN_ON(refcount_read(&h->use_count) > 2);
569 h->orig_rsv = h->block_rsv;
575 * Do the reservation before we join the transaction so we can do all
576 * the appropriate flushing if need be.
578 if (num_items && root != fs_info->chunk_root) {
579 struct btrfs_block_rsv *rsv = &fs_info->trans_block_rsv;
580 u64 delayed_refs_bytes = 0;
582 qgroup_reserved = num_items * fs_info->nodesize;
583 ret = btrfs_qgroup_reserve_meta_pertrans(root, qgroup_reserved,
589 * We want to reserve all the bytes we may need all at once, so
590 * we only do 1 enospc flushing cycle per transaction start. We
591 * accomplish this by simply assuming we'll do 2 x num_items
592 * worth of delayed refs updates in this trans handle, and
593 * refill that amount for whatever is missing in the reserve.
595 num_bytes = btrfs_calc_insert_metadata_size(fs_info, num_items);
596 if (flush == BTRFS_RESERVE_FLUSH_ALL &&
597 btrfs_block_rsv_full(delayed_refs_rsv) == 0) {
598 delayed_refs_bytes = num_bytes;
603 * Do the reservation for the relocation root creation
605 if (need_reserve_reloc_root(root)) {
606 num_bytes += fs_info->nodesize;
607 reloc_reserved = true;
610 ret = btrfs_block_rsv_add(fs_info, rsv, num_bytes, flush);
613 if (delayed_refs_bytes) {
614 btrfs_migrate_to_delayed_refs_rsv(fs_info, rsv,
616 num_bytes -= delayed_refs_bytes;
619 if (rsv->space_info->force_alloc)
620 do_chunk_alloc = true;
621 } else if (num_items == 0 && flush == BTRFS_RESERVE_FLUSH_ALL &&
622 !btrfs_block_rsv_full(delayed_refs_rsv)) {
624 * Some people call with btrfs_start_transaction(root, 0)
625 * because they can be throttled, but have some other mechanism
626 * for reserving space. We still want these guys to refill the
627 * delayed block_rsv so just add 1 items worth of reservation
630 ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
635 h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
642 * If we are JOIN_NOLOCK we're already committing a transaction and
643 * waiting on this guy, so we don't need to do the sb_start_intwrite
644 * because we're already holding a ref. We need this because we could
645 * have raced in and did an fsync() on a file which can kick a commit
646 * and then we deadlock with somebody doing a freeze.
648 * If we are ATTACH, it means we just want to catch the current
649 * transaction and commit it, so we needn't do sb_start_intwrite().
651 if (type & __TRANS_FREEZABLE)
652 sb_start_intwrite(fs_info->sb);
654 if (may_wait_transaction(fs_info, type))
655 wait_current_trans(fs_info);
658 ret = join_transaction(fs_info, type);
660 wait_current_trans(fs_info);
661 if (unlikely(type == TRANS_ATTACH ||
662 type == TRANS_JOIN_NOSTART))
665 } while (ret == -EBUSY);
670 cur_trans = fs_info->running_transaction;
672 h->transid = cur_trans->transid;
673 h->transaction = cur_trans;
674 refcount_set(&h->use_count, 1);
675 h->fs_info = root->fs_info;
678 INIT_LIST_HEAD(&h->new_bgs);
681 if (cur_trans->state >= TRANS_STATE_COMMIT_START &&
682 may_wait_transaction(fs_info, type)) {
683 current->journal_info = h;
684 btrfs_commit_transaction(h);
689 trace_btrfs_space_reservation(fs_info, "transaction",
690 h->transid, num_bytes, 1);
691 h->block_rsv = &fs_info->trans_block_rsv;
692 h->bytes_reserved = num_bytes;
693 h->reloc_reserved = reloc_reserved;
697 if (!current->journal_info)
698 current->journal_info = h;
701 * If the space_info is marked ALLOC_FORCE then we'll get upgraded to
702 * ALLOC_FORCE the first run through, and then we won't allocate for
703 * anybody else who races in later. We don't care about the return
706 if (do_chunk_alloc && num_bytes) {
707 u64 flags = h->block_rsv->space_info->flags;
709 btrfs_chunk_alloc(h, btrfs_get_alloc_profile(fs_info, flags),
710 CHUNK_ALLOC_NO_FORCE);
714 * btrfs_record_root_in_trans() needs to alloc new extents, and may
715 * call btrfs_join_transaction() while we're also starting a
718 * Thus it need to be called after current->journal_info initialized,
719 * or we can deadlock.
721 ret = btrfs_record_root_in_trans(h, root);
724 * The transaction handle is fully initialized and linked with
725 * other structures so it needs to be ended in case of errors,
728 btrfs_end_transaction(h);
735 if (type & __TRANS_FREEZABLE)
736 sb_end_intwrite(fs_info->sb);
737 kmem_cache_free(btrfs_trans_handle_cachep, h);
740 btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
743 btrfs_qgroup_free_meta_pertrans(root, qgroup_reserved);
747 struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
748 unsigned int num_items)
750 return start_transaction(root, num_items, TRANS_START,
751 BTRFS_RESERVE_FLUSH_ALL, true);
754 struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
755 struct btrfs_root *root,
756 unsigned int num_items)
758 return start_transaction(root, num_items, TRANS_START,
759 BTRFS_RESERVE_FLUSH_ALL_STEAL, false);
762 struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
764 return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
768 struct btrfs_trans_handle *btrfs_join_transaction_spacecache(struct btrfs_root *root)
770 return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
771 BTRFS_RESERVE_NO_FLUSH, true);
775 * Similar to regular join but it never starts a transaction when none is
776 * running or after waiting for the current one to finish.
778 struct btrfs_trans_handle *btrfs_join_transaction_nostart(struct btrfs_root *root)
780 return start_transaction(root, 0, TRANS_JOIN_NOSTART,
781 BTRFS_RESERVE_NO_FLUSH, true);
785 * btrfs_attach_transaction() - catch the running transaction
787 * It is used when we want to commit the current the transaction, but
788 * don't want to start a new one.
790 * Note: If this function return -ENOENT, it just means there is no
791 * running transaction. But it is possible that the inactive transaction
792 * is still in the memory, not fully on disk. If you hope there is no
793 * inactive transaction in the fs when -ENOENT is returned, you should
795 * btrfs_attach_transaction_barrier()
797 struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
799 return start_transaction(root, 0, TRANS_ATTACH,
800 BTRFS_RESERVE_NO_FLUSH, true);
804 * btrfs_attach_transaction_barrier() - catch the running transaction
806 * It is similar to the above function, the difference is this one
807 * will wait for all the inactive transactions until they fully
810 struct btrfs_trans_handle *
811 btrfs_attach_transaction_barrier(struct btrfs_root *root)
813 struct btrfs_trans_handle *trans;
815 trans = start_transaction(root, 0, TRANS_ATTACH,
816 BTRFS_RESERVE_NO_FLUSH, true);
817 if (trans == ERR_PTR(-ENOENT))
818 btrfs_wait_for_commit(root->fs_info, 0);
823 /* Wait for a transaction commit to reach at least the given state. */
824 static noinline void wait_for_commit(struct btrfs_transaction *commit,
825 const enum btrfs_trans_state min_state)
827 struct btrfs_fs_info *fs_info = commit->fs_info;
828 u64 transid = commit->transid;
832 * At the moment this function is called with min_state either being
833 * TRANS_STATE_COMPLETED or TRANS_STATE_SUPER_COMMITTED.
835 if (min_state == TRANS_STATE_COMPLETED)
836 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
838 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
841 wait_event(commit->commit_wait, commit->state >= min_state);
843 btrfs_put_transaction(commit);
845 if (min_state < TRANS_STATE_COMPLETED)
849 * A transaction isn't really completed until all of the
850 * previous transactions are completed, but with fsync we can
851 * end up with SUPER_COMMITTED transactions before a COMPLETED
852 * transaction. Wait for those.
855 spin_lock(&fs_info->trans_lock);
856 commit = list_first_entry_or_null(&fs_info->trans_list,
857 struct btrfs_transaction,
859 if (!commit || commit->transid > transid) {
860 spin_unlock(&fs_info->trans_lock);
863 refcount_inc(&commit->use_count);
865 spin_unlock(&fs_info->trans_lock);
869 int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
871 struct btrfs_transaction *cur_trans = NULL, *t;
875 if (transid <= fs_info->last_trans_committed)
878 /* find specified transaction */
879 spin_lock(&fs_info->trans_lock);
880 list_for_each_entry(t, &fs_info->trans_list, list) {
881 if (t->transid == transid) {
883 refcount_inc(&cur_trans->use_count);
887 if (t->transid > transid) {
892 spin_unlock(&fs_info->trans_lock);
895 * The specified transaction doesn't exist, or we
896 * raced with btrfs_commit_transaction
899 if (transid > fs_info->last_trans_committed)
904 /* find newest transaction that is committing | committed */
905 spin_lock(&fs_info->trans_lock);
906 list_for_each_entry_reverse(t, &fs_info->trans_list,
908 if (t->state >= TRANS_STATE_COMMIT_START) {
909 if (t->state == TRANS_STATE_COMPLETED)
912 refcount_inc(&cur_trans->use_count);
916 spin_unlock(&fs_info->trans_lock);
918 goto out; /* nothing committing|committed */
921 wait_for_commit(cur_trans, TRANS_STATE_COMPLETED);
922 btrfs_put_transaction(cur_trans);
927 void btrfs_throttle(struct btrfs_fs_info *fs_info)
929 wait_current_trans(fs_info);
932 static bool should_end_transaction(struct btrfs_trans_handle *trans)
934 struct btrfs_fs_info *fs_info = trans->fs_info;
936 if (btrfs_check_space_for_delayed_refs(fs_info))
939 return !!btrfs_block_rsv_check(&fs_info->global_block_rsv, 5);
942 bool btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
944 struct btrfs_transaction *cur_trans = trans->transaction;
946 if (cur_trans->state >= TRANS_STATE_COMMIT_START ||
947 test_bit(BTRFS_DELAYED_REFS_FLUSHING, &cur_trans->delayed_refs.flags))
950 return should_end_transaction(trans);
953 static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
956 struct btrfs_fs_info *fs_info = trans->fs_info;
958 if (!trans->block_rsv) {
959 ASSERT(!trans->bytes_reserved);
963 if (!trans->bytes_reserved)
966 ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
967 trace_btrfs_space_reservation(fs_info, "transaction",
968 trans->transid, trans->bytes_reserved, 0);
969 btrfs_block_rsv_release(fs_info, trans->block_rsv,
970 trans->bytes_reserved, NULL);
971 trans->bytes_reserved = 0;
974 static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
977 struct btrfs_fs_info *info = trans->fs_info;
978 struct btrfs_transaction *cur_trans = trans->transaction;
981 if (refcount_read(&trans->use_count) > 1) {
982 refcount_dec(&trans->use_count);
983 trans->block_rsv = trans->orig_rsv;
987 btrfs_trans_release_metadata(trans);
988 trans->block_rsv = NULL;
990 btrfs_create_pending_block_groups(trans);
992 btrfs_trans_release_chunk_metadata(trans);
994 if (trans->type & __TRANS_FREEZABLE)
995 sb_end_intwrite(info->sb);
997 WARN_ON(cur_trans != info->running_transaction);
998 WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
999 atomic_dec(&cur_trans->num_writers);
1000 extwriter_counter_dec(cur_trans, trans->type);
1002 cond_wake_up(&cur_trans->writer_wait);
1004 btrfs_lockdep_release(info, btrfs_trans_num_extwriters);
1005 btrfs_lockdep_release(info, btrfs_trans_num_writers);
1007 btrfs_put_transaction(cur_trans);
1009 if (current->journal_info == trans)
1010 current->journal_info = NULL;
1013 btrfs_run_delayed_iputs(info);
1015 if (TRANS_ABORTED(trans) || BTRFS_FS_ERROR(info)) {
1016 wake_up_process(info->transaction_kthread);
1017 if (TRANS_ABORTED(trans))
1018 err = trans->aborted;
1023 kmem_cache_free(btrfs_trans_handle_cachep, trans);
1027 int btrfs_end_transaction(struct btrfs_trans_handle *trans)
1029 return __btrfs_end_transaction(trans, 0);
1032 int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
1034 return __btrfs_end_transaction(trans, 1);
1038 * when btree blocks are allocated, they have some corresponding bits set for
1039 * them in one of two extent_io trees. This is used to make sure all of
1040 * those extents are sent to disk but does not wait on them
1042 int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
1043 struct extent_io_tree *dirty_pages, int mark)
1047 struct address_space *mapping = fs_info->btree_inode->i_mapping;
1048 struct extent_state *cached_state = NULL;
1052 atomic_inc(&BTRFS_I(fs_info->btree_inode)->sync_writers);
1053 while (!find_first_extent_bit(dirty_pages, start, &start, &end,
1054 mark, &cached_state)) {
1055 bool wait_writeback = false;
1057 err = convert_extent_bit(dirty_pages, start, end,
1059 mark, &cached_state);
1061 * convert_extent_bit can return -ENOMEM, which is most of the
1062 * time a temporary error. So when it happens, ignore the error
1063 * and wait for writeback of this range to finish - because we
1064 * failed to set the bit EXTENT_NEED_WAIT for the range, a call
1065 * to __btrfs_wait_marked_extents() would not know that
1066 * writeback for this range started and therefore wouldn't
1067 * wait for it to finish - we don't want to commit a
1068 * superblock that points to btree nodes/leafs for which
1069 * writeback hasn't finished yet (and without errors).
1070 * We cleanup any entries left in the io tree when committing
1071 * the transaction (through extent_io_tree_release()).
1073 if (err == -ENOMEM) {
1075 wait_writeback = true;
1078 err = filemap_fdatawrite_range(mapping, start, end);
1081 else if (wait_writeback)
1082 werr = filemap_fdatawait_range(mapping, start, end);
1083 free_extent_state(cached_state);
1084 cached_state = NULL;
1088 atomic_dec(&BTRFS_I(fs_info->btree_inode)->sync_writers);
1093 * when btree blocks are allocated, they have some corresponding bits set for
1094 * them in one of two extent_io trees. This is used to make sure all of
1095 * those extents are on disk for transaction or log commit. We wait
1096 * on all the pages and clear them from the dirty pages state tree
1098 static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
1099 struct extent_io_tree *dirty_pages)
1103 struct address_space *mapping = fs_info->btree_inode->i_mapping;
1104 struct extent_state *cached_state = NULL;
1108 while (!find_first_extent_bit(dirty_pages, start, &start, &end,
1109 EXTENT_NEED_WAIT, &cached_state)) {
1111 * Ignore -ENOMEM errors returned by clear_extent_bit().
1112 * When committing the transaction, we'll remove any entries
1113 * left in the io tree. For a log commit, we don't remove them
1114 * after committing the log because the tree can be accessed
1115 * concurrently - we do it only at transaction commit time when
1116 * it's safe to do it (through extent_io_tree_release()).
1118 err = clear_extent_bit(dirty_pages, start, end,
1119 EXTENT_NEED_WAIT, &cached_state);
1123 err = filemap_fdatawait_range(mapping, start, end);
1126 free_extent_state(cached_state);
1127 cached_state = NULL;
1136 static int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
1137 struct extent_io_tree *dirty_pages)
1139 bool errors = false;
1142 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1143 if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1151 int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
1153 struct btrfs_fs_info *fs_info = log_root->fs_info;
1154 struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
1155 bool errors = false;
1158 ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
1160 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1161 if ((mark & EXTENT_DIRTY) &&
1162 test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1165 if ((mark & EXTENT_NEW) &&
1166 test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1175 * When btree blocks are allocated the corresponding extents are marked dirty.
1176 * This function ensures such extents are persisted on disk for transaction or
1179 * @trans: transaction whose dirty pages we'd like to write
1181 static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1185 struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
1186 struct btrfs_fs_info *fs_info = trans->fs_info;
1187 struct blk_plug plug;
1189 blk_start_plug(&plug);
1190 ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1191 blk_finish_plug(&plug);
1192 ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1194 extent_io_tree_release(&trans->transaction->dirty_pages);
1205 * this is used to update the root pointer in the tree of tree roots.
1207 * But, in the case of the extent allocation tree, updating the root
1208 * pointer may allocate blocks which may change the root of the extent
1211 * So, this loops and repeats and makes sure the cowonly root didn't
1212 * change while the root pointer was being updated in the metadata.
1214 static int update_cowonly_root(struct btrfs_trans_handle *trans,
1215 struct btrfs_root *root)
1218 u64 old_root_bytenr;
1220 struct btrfs_fs_info *fs_info = root->fs_info;
1221 struct btrfs_root *tree_root = fs_info->tree_root;
1223 old_root_used = btrfs_root_used(&root->root_item);
1226 old_root_bytenr = btrfs_root_bytenr(&root->root_item);
1227 if (old_root_bytenr == root->node->start &&
1228 old_root_used == btrfs_root_used(&root->root_item))
1231 btrfs_set_root_node(&root->root_item, root->node);
1232 ret = btrfs_update_root(trans, tree_root,
1238 old_root_used = btrfs_root_used(&root->root_item);
1245 * update all the cowonly tree roots on disk
1247 * The error handling in this function may not be obvious. Any of the
1248 * failures will cause the file system to go offline. We still need
1249 * to clean up the delayed refs.
1251 static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
1253 struct btrfs_fs_info *fs_info = trans->fs_info;
1254 struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
1255 struct list_head *io_bgs = &trans->transaction->io_bgs;
1256 struct list_head *next;
1257 struct extent_buffer *eb;
1261 * At this point no one can be using this transaction to modify any tree
1262 * and no one can start another transaction to modify any tree either.
1264 ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1266 eb = btrfs_lock_root_node(fs_info->tree_root);
1267 ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
1268 0, &eb, BTRFS_NESTING_COW);
1269 btrfs_tree_unlock(eb);
1270 free_extent_buffer(eb);
1275 ret = btrfs_run_dev_stats(trans);
1278 ret = btrfs_run_dev_replace(trans);
1281 ret = btrfs_run_qgroups(trans);
1285 ret = btrfs_setup_space_cache(trans);
1290 while (!list_empty(&fs_info->dirty_cowonly_roots)) {
1291 struct btrfs_root *root;
1292 next = fs_info->dirty_cowonly_roots.next;
1293 list_del_init(next);
1294 root = list_entry(next, struct btrfs_root, dirty_list);
1295 clear_bit(BTRFS_ROOT_DIRTY, &root->state);
1297 list_add_tail(&root->dirty_list,
1298 &trans->transaction->switch_commits);
1299 ret = update_cowonly_root(trans, root);
1304 /* Now flush any delayed refs generated by updating all of the roots */
1305 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1309 while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
1310 ret = btrfs_write_dirty_block_groups(trans);
1315 * We're writing the dirty block groups, which could generate
1316 * delayed refs, which could generate more dirty block groups,
1317 * so we want to keep this flushing in this loop to make sure
1318 * everything gets run.
1320 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1325 if (!list_empty(&fs_info->dirty_cowonly_roots))
1328 /* Update dev-replace pointer once everything is committed */
1329 fs_info->dev_replace.committed_cursor_left =
1330 fs_info->dev_replace.cursor_left_last_write_of_item;
1336 * If we had a pending drop we need to see if there are any others left in our
1337 * dead roots list, and if not clear our bit and wake any waiters.
1339 void btrfs_maybe_wake_unfinished_drop(struct btrfs_fs_info *fs_info)
1342 * We put the drop in progress roots at the front of the list, so if the
1343 * first entry doesn't have UNFINISHED_DROP set we can wake everybody
1346 spin_lock(&fs_info->trans_lock);
1347 if (!list_empty(&fs_info->dead_roots)) {
1348 struct btrfs_root *root = list_first_entry(&fs_info->dead_roots,
1351 if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state)) {
1352 spin_unlock(&fs_info->trans_lock);
1356 spin_unlock(&fs_info->trans_lock);
1358 btrfs_wake_unfinished_drop(fs_info);
1362 * dead roots are old snapshots that need to be deleted. This allocates
1363 * a dirty root struct and adds it into the list of dead roots that need to
1366 void btrfs_add_dead_root(struct btrfs_root *root)
1368 struct btrfs_fs_info *fs_info = root->fs_info;
1370 spin_lock(&fs_info->trans_lock);
1371 if (list_empty(&root->root_list)) {
1372 btrfs_grab_root(root);
1374 /* We want to process the partially complete drops first. */
1375 if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state))
1376 list_add(&root->root_list, &fs_info->dead_roots);
1378 list_add_tail(&root->root_list, &fs_info->dead_roots);
1380 spin_unlock(&fs_info->trans_lock);
1384 * Update each subvolume root and its relocation root, if it exists, in the tree
1385 * of tree roots. Also free log roots if they exist.
1387 static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
1389 struct btrfs_fs_info *fs_info = trans->fs_info;
1390 struct btrfs_root *gang[8];
1395 * At this point no one can be using this transaction to modify any tree
1396 * and no one can start another transaction to modify any tree either.
1398 ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1400 spin_lock(&fs_info->fs_roots_radix_lock);
1402 ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
1405 BTRFS_ROOT_TRANS_TAG);
1408 for (i = 0; i < ret; i++) {
1409 struct btrfs_root *root = gang[i];
1413 * At this point we can neither have tasks logging inodes
1414 * from a root nor trying to commit a log tree.
1416 ASSERT(atomic_read(&root->log_writers) == 0);
1417 ASSERT(atomic_read(&root->log_commit[0]) == 0);
1418 ASSERT(atomic_read(&root->log_commit[1]) == 0);
1420 radix_tree_tag_clear(&fs_info->fs_roots_radix,
1421 (unsigned long)root->root_key.objectid,
1422 BTRFS_ROOT_TRANS_TAG);
1423 spin_unlock(&fs_info->fs_roots_radix_lock);
1425 btrfs_free_log(trans, root);
1426 ret2 = btrfs_update_reloc_root(trans, root);
1430 /* see comments in should_cow_block() */
1431 clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1432 smp_mb__after_atomic();
1434 if (root->commit_root != root->node) {
1435 list_add_tail(&root->dirty_list,
1436 &trans->transaction->switch_commits);
1437 btrfs_set_root_node(&root->root_item,
1441 ret2 = btrfs_update_root(trans, fs_info->tree_root,
1446 spin_lock(&fs_info->fs_roots_radix_lock);
1447 btrfs_qgroup_free_meta_all_pertrans(root);
1450 spin_unlock(&fs_info->fs_roots_radix_lock);
1455 * defrag a given btree.
1456 * Every leaf in the btree is read and defragged.
1458 int btrfs_defrag_root(struct btrfs_root *root)
1460 struct btrfs_fs_info *info = root->fs_info;
1461 struct btrfs_trans_handle *trans;
1464 if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
1468 trans = btrfs_start_transaction(root, 0);
1469 if (IS_ERR(trans)) {
1470 ret = PTR_ERR(trans);
1474 ret = btrfs_defrag_leaves(trans, root);
1476 btrfs_end_transaction(trans);
1477 btrfs_btree_balance_dirty(info);
1480 if (btrfs_fs_closing(info) || ret != -EAGAIN)
1483 if (btrfs_defrag_cancelled(info)) {
1484 btrfs_debug(info, "defrag_root cancelled");
1489 clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
1494 * Do all special snapshot related qgroup dirty hack.
1496 * Will do all needed qgroup inherit and dirty hack like switch commit
1497 * roots inside one transaction and write all btree into disk, to make
1500 static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
1501 struct btrfs_root *src,
1502 struct btrfs_root *parent,
1503 struct btrfs_qgroup_inherit *inherit,
1506 struct btrfs_fs_info *fs_info = src->fs_info;
1510 * Save some performance in the case that qgroups are not
1511 * enabled. If this check races with the ioctl, rescan will
1514 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1518 * Ensure dirty @src will be committed. Or, after coming
1519 * commit_fs_roots() and switch_commit_roots(), any dirty but not
1520 * recorded root will never be updated again, causing an outdated root
1523 ret = record_root_in_trans(trans, src, 1);
1528 * btrfs_qgroup_inherit relies on a consistent view of the usage for the
1529 * src root, so we must run the delayed refs here.
1531 * However this isn't particularly fool proof, because there's no
1532 * synchronization keeping us from changing the tree after this point
1533 * before we do the qgroup_inherit, or even from making changes while
1534 * we're doing the qgroup_inherit. But that's a problem for the future,
1535 * for now flush the delayed refs to narrow the race window where the
1536 * qgroup counters could end up wrong.
1538 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1540 btrfs_abort_transaction(trans, ret);
1544 ret = commit_fs_roots(trans);
1547 ret = btrfs_qgroup_account_extents(trans);
1551 /* Now qgroup are all updated, we can inherit it to new qgroups */
1552 ret = btrfs_qgroup_inherit(trans, src->root_key.objectid, dst_objectid,
1558 * Now we do a simplified commit transaction, which will:
1559 * 1) commit all subvolume and extent tree
1560 * To ensure all subvolume and extent tree have a valid
1561 * commit_root to accounting later insert_dir_item()
1562 * 2) write all btree blocks onto disk
1563 * This is to make sure later btree modification will be cowed
1564 * Or commit_root can be populated and cause wrong qgroup numbers
1565 * In this simplified commit, we don't really care about other trees
1566 * like chunk and root tree, as they won't affect qgroup.
1567 * And we don't write super to avoid half committed status.
1569 ret = commit_cowonly_roots(trans);
1572 switch_commit_roots(trans);
1573 ret = btrfs_write_and_wait_transaction(trans);
1575 btrfs_handle_fs_error(fs_info, ret,
1576 "Error while writing out transaction for qgroup");
1580 * Force parent root to be updated, as we recorded it before so its
1581 * last_trans == cur_transid.
1582 * Or it won't be committed again onto disk after later
1586 ret = record_root_in_trans(trans, parent, 1);
1591 * new snapshots need to be created at a very specific time in the
1592 * transaction commit. This does the actual creation.
1595 * If the error which may affect the commitment of the current transaction
1596 * happens, we should return the error number. If the error which just affect
1597 * the creation of the pending snapshots, just return 0.
1599 static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
1600 struct btrfs_pending_snapshot *pending)
1603 struct btrfs_fs_info *fs_info = trans->fs_info;
1604 struct btrfs_key key;
1605 struct btrfs_root_item *new_root_item;
1606 struct btrfs_root *tree_root = fs_info->tree_root;
1607 struct btrfs_root *root = pending->root;
1608 struct btrfs_root *parent_root;
1609 struct btrfs_block_rsv *rsv;
1610 struct inode *parent_inode;
1611 struct btrfs_path *path;
1612 struct btrfs_dir_item *dir_item;
1613 struct dentry *dentry;
1614 struct extent_buffer *tmp;
1615 struct extent_buffer *old;
1616 struct timespec64 cur_time;
1623 ASSERT(pending->path);
1624 path = pending->path;
1626 ASSERT(pending->root_item);
1627 new_root_item = pending->root_item;
1629 pending->error = btrfs_get_free_objectid(tree_root, &objectid);
1631 goto no_free_objectid;
1634 * Make qgroup to skip current new snapshot's qgroupid, as it is
1635 * accounted by later btrfs_qgroup_inherit().
1637 btrfs_set_skip_qgroup(trans, objectid);
1639 btrfs_reloc_pre_snapshot(pending, &to_reserve);
1641 if (to_reserve > 0) {
1642 pending->error = btrfs_block_rsv_add(fs_info,
1643 &pending->block_rsv,
1645 BTRFS_RESERVE_NO_FLUSH);
1647 goto clear_skip_qgroup;
1650 key.objectid = objectid;
1651 key.offset = (u64)-1;
1652 key.type = BTRFS_ROOT_ITEM_KEY;
1654 rsv = trans->block_rsv;
1655 trans->block_rsv = &pending->block_rsv;
1656 trans->bytes_reserved = trans->block_rsv->reserved;
1657 trace_btrfs_space_reservation(fs_info, "transaction",
1659 trans->bytes_reserved, 1);
1660 dentry = pending->dentry;
1661 parent_inode = pending->dir;
1662 parent_root = BTRFS_I(parent_inode)->root;
1663 ret = record_root_in_trans(trans, parent_root, 0);
1666 cur_time = current_time(parent_inode);
1669 * insert the directory item
1671 ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
1672 BUG_ON(ret); /* -ENOMEM */
1674 /* check if there is a file/dir which has the same name. */
1675 dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
1676 btrfs_ino(BTRFS_I(parent_inode)),
1677 dentry->d_name.name,
1678 dentry->d_name.len, 0);
1679 if (dir_item != NULL && !IS_ERR(dir_item)) {
1680 pending->error = -EEXIST;
1681 goto dir_item_existed;
1682 } else if (IS_ERR(dir_item)) {
1683 ret = PTR_ERR(dir_item);
1684 btrfs_abort_transaction(trans, ret);
1687 btrfs_release_path(path);
1690 * pull in the delayed directory update
1691 * and the delayed inode item
1692 * otherwise we corrupt the FS during
1695 ret = btrfs_run_delayed_items(trans);
1696 if (ret) { /* Transaction aborted */
1697 btrfs_abort_transaction(trans, ret);
1701 ret = record_root_in_trans(trans, root, 0);
1703 btrfs_abort_transaction(trans, ret);
1706 btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
1707 memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
1708 btrfs_check_and_init_root_item(new_root_item);
1710 root_flags = btrfs_root_flags(new_root_item);
1711 if (pending->readonly)
1712 root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1714 root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1715 btrfs_set_root_flags(new_root_item, root_flags);
1717 btrfs_set_root_generation_v2(new_root_item,
1719 generate_random_guid(new_root_item->uuid);
1720 memcpy(new_root_item->parent_uuid, root->root_item.uuid,
1722 if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
1723 memset(new_root_item->received_uuid, 0,
1724 sizeof(new_root_item->received_uuid));
1725 memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
1726 memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
1727 btrfs_set_root_stransid(new_root_item, 0);
1728 btrfs_set_root_rtransid(new_root_item, 0);
1730 btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
1731 btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
1732 btrfs_set_root_otransid(new_root_item, trans->transid);
1734 old = btrfs_lock_root_node(root);
1735 ret = btrfs_cow_block(trans, root, old, NULL, 0, &old,
1738 btrfs_tree_unlock(old);
1739 free_extent_buffer(old);
1740 btrfs_abort_transaction(trans, ret);
1744 ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
1745 /* clean up in any case */
1746 btrfs_tree_unlock(old);
1747 free_extent_buffer(old);
1749 btrfs_abort_transaction(trans, ret);
1752 /* see comments in should_cow_block() */
1753 set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1756 btrfs_set_root_node(new_root_item, tmp);
1757 /* record when the snapshot was created in key.offset */
1758 key.offset = trans->transid;
1759 ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1760 btrfs_tree_unlock(tmp);
1761 free_extent_buffer(tmp);
1763 btrfs_abort_transaction(trans, ret);
1768 * insert root back/forward references
1770 ret = btrfs_add_root_ref(trans, objectid,
1771 parent_root->root_key.objectid,
1772 btrfs_ino(BTRFS_I(parent_inode)), index,
1773 dentry->d_name.name, dentry->d_name.len);
1775 btrfs_abort_transaction(trans, ret);
1779 key.offset = (u64)-1;
1780 pending->snap = btrfs_get_new_fs_root(fs_info, objectid, pending->anon_dev);
1781 if (IS_ERR(pending->snap)) {
1782 ret = PTR_ERR(pending->snap);
1783 pending->snap = NULL;
1784 btrfs_abort_transaction(trans, ret);
1788 ret = btrfs_reloc_post_snapshot(trans, pending);
1790 btrfs_abort_transaction(trans, ret);
1795 * Do special qgroup accounting for snapshot, as we do some qgroup
1796 * snapshot hack to do fast snapshot.
1797 * To co-operate with that hack, we do hack again.
1798 * Or snapshot will be greatly slowed down by a subtree qgroup rescan
1800 ret = qgroup_account_snapshot(trans, root, parent_root,
1801 pending->inherit, objectid);
1805 ret = btrfs_insert_dir_item(trans, dentry->d_name.name,
1806 dentry->d_name.len, BTRFS_I(parent_inode),
1807 &key, BTRFS_FT_DIR, index);
1808 /* We have check then name at the beginning, so it is impossible. */
1809 BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
1811 btrfs_abort_transaction(trans, ret);
1815 btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
1816 dentry->d_name.len * 2);
1817 parent_inode->i_mtime = current_time(parent_inode);
1818 parent_inode->i_ctime = parent_inode->i_mtime;
1819 ret = btrfs_update_inode_fallback(trans, parent_root, BTRFS_I(parent_inode));
1821 btrfs_abort_transaction(trans, ret);
1824 ret = btrfs_uuid_tree_add(trans, new_root_item->uuid,
1825 BTRFS_UUID_KEY_SUBVOL,
1828 btrfs_abort_transaction(trans, ret);
1831 if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1832 ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1833 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1835 if (ret && ret != -EEXIST) {
1836 btrfs_abort_transaction(trans, ret);
1842 pending->error = ret;
1844 trans->block_rsv = rsv;
1845 trans->bytes_reserved = 0;
1847 btrfs_clear_skip_qgroup(trans);
1849 kfree(new_root_item);
1850 pending->root_item = NULL;
1851 btrfs_free_path(path);
1852 pending->path = NULL;
1858 * create all the snapshots we've scheduled for creation
1860 static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
1862 struct btrfs_pending_snapshot *pending, *next;
1863 struct list_head *head = &trans->transaction->pending_snapshots;
1866 list_for_each_entry_safe(pending, next, head, list) {
1867 list_del(&pending->list);
1868 ret = create_pending_snapshot(trans, pending);
1875 static void update_super_roots(struct btrfs_fs_info *fs_info)
1877 struct btrfs_root_item *root_item;
1878 struct btrfs_super_block *super;
1880 super = fs_info->super_copy;
1882 root_item = &fs_info->chunk_root->root_item;
1883 super->chunk_root = root_item->bytenr;
1884 super->chunk_root_generation = root_item->generation;
1885 super->chunk_root_level = root_item->level;
1887 root_item = &fs_info->tree_root->root_item;
1888 super->root = root_item->bytenr;
1889 super->generation = root_item->generation;
1890 super->root_level = root_item->level;
1891 if (btrfs_test_opt(fs_info, SPACE_CACHE))
1892 super->cache_generation = root_item->generation;
1893 else if (test_bit(BTRFS_FS_CLEANUP_SPACE_CACHE_V1, &fs_info->flags))
1894 super->cache_generation = 0;
1895 if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1896 super->uuid_tree_generation = root_item->generation;
1899 int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1901 struct btrfs_transaction *trans;
1904 spin_lock(&info->trans_lock);
1905 trans = info->running_transaction;
1907 ret = (trans->state >= TRANS_STATE_COMMIT_START);
1908 spin_unlock(&info->trans_lock);
1912 int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1914 struct btrfs_transaction *trans;
1917 spin_lock(&info->trans_lock);
1918 trans = info->running_transaction;
1920 ret = is_transaction_blocked(trans);
1921 spin_unlock(&info->trans_lock);
1925 void btrfs_commit_transaction_async(struct btrfs_trans_handle *trans)
1927 struct btrfs_fs_info *fs_info = trans->fs_info;
1928 struct btrfs_transaction *cur_trans;
1930 /* Kick the transaction kthread. */
1931 set_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
1932 wake_up_process(fs_info->transaction_kthread);
1934 /* take transaction reference */
1935 cur_trans = trans->transaction;
1936 refcount_inc(&cur_trans->use_count);
1938 btrfs_end_transaction(trans);
1941 * Wait for the current transaction commit to start and block
1942 * subsequent transaction joins
1944 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_START);
1945 wait_event(fs_info->transaction_blocked_wait,
1946 cur_trans->state >= TRANS_STATE_COMMIT_START ||
1947 TRANS_ABORTED(cur_trans));
1948 btrfs_put_transaction(cur_trans);
1951 static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
1953 struct btrfs_fs_info *fs_info = trans->fs_info;
1954 struct btrfs_transaction *cur_trans = trans->transaction;
1956 WARN_ON(refcount_read(&trans->use_count) > 1);
1958 btrfs_abort_transaction(trans, err);
1960 spin_lock(&fs_info->trans_lock);
1963 * If the transaction is removed from the list, it means this
1964 * transaction has been committed successfully, so it is impossible
1965 * to call the cleanup function.
1967 BUG_ON(list_empty(&cur_trans->list));
1969 if (cur_trans == fs_info->running_transaction) {
1970 cur_trans->state = TRANS_STATE_COMMIT_DOING;
1971 spin_unlock(&fs_info->trans_lock);
1974 * The thread has already released the lockdep map as reader
1975 * already in btrfs_commit_transaction().
1977 btrfs_might_wait_for_event(fs_info, btrfs_trans_num_writers);
1978 wait_event(cur_trans->writer_wait,
1979 atomic_read(&cur_trans->num_writers) == 1);
1981 spin_lock(&fs_info->trans_lock);
1985 * Now that we know no one else is still using the transaction we can
1986 * remove the transaction from the list of transactions. This avoids
1987 * the transaction kthread from cleaning up the transaction while some
1988 * other task is still using it, which could result in a use-after-free
1989 * on things like log trees, as it forces the transaction kthread to
1990 * wait for this transaction to be cleaned up by us.
1992 list_del_init(&cur_trans->list);
1994 spin_unlock(&fs_info->trans_lock);
1996 btrfs_cleanup_one_transaction(trans->transaction, fs_info);
1998 spin_lock(&fs_info->trans_lock);
1999 if (cur_trans == fs_info->running_transaction)
2000 fs_info->running_transaction = NULL;
2001 spin_unlock(&fs_info->trans_lock);
2003 if (trans->type & __TRANS_FREEZABLE)
2004 sb_end_intwrite(fs_info->sb);
2005 btrfs_put_transaction(cur_trans);
2006 btrfs_put_transaction(cur_trans);
2008 trace_btrfs_transaction_commit(fs_info);
2010 if (current->journal_info == trans)
2011 current->journal_info = NULL;
2012 btrfs_scrub_cancel(fs_info);
2014 kmem_cache_free(btrfs_trans_handle_cachep, trans);
2018 * Release reserved delayed ref space of all pending block groups of the
2019 * transaction and remove them from the list
2021 static void btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle *trans)
2023 struct btrfs_fs_info *fs_info = trans->fs_info;
2024 struct btrfs_block_group *block_group, *tmp;
2026 list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
2027 btrfs_delayed_refs_rsv_release(fs_info, 1);
2028 list_del_init(&block_group->bg_list);
2032 static inline int btrfs_start_delalloc_flush(struct btrfs_fs_info *fs_info)
2035 * We use try_to_writeback_inodes_sb() here because if we used
2036 * btrfs_start_delalloc_roots we would deadlock with fs freeze.
2037 * Currently are holding the fs freeze lock, if we do an async flush
2038 * we'll do btrfs_join_transaction() and deadlock because we need to
2039 * wait for the fs freeze lock. Using the direct flushing we benefit
2040 * from already being in a transaction and our join_transaction doesn't
2041 * have to re-take the fs freeze lock.
2043 * Note that try_to_writeback_inodes_sb() will only trigger writeback
2044 * if it can read lock sb->s_umount. It will always be able to lock it,
2045 * except when the filesystem is being unmounted or being frozen, but in
2046 * those cases sync_filesystem() is called, which results in calling
2047 * writeback_inodes_sb() while holding a write lock on sb->s_umount.
2048 * Note that we don't call writeback_inodes_sb() directly, because it
2049 * will emit a warning if sb->s_umount is not locked.
2051 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2052 try_to_writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
2056 static inline void btrfs_wait_delalloc_flush(struct btrfs_fs_info *fs_info)
2058 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2059 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
2063 * Add a pending snapshot associated with the given transaction handle to the
2064 * respective handle. This must be called after the transaction commit started
2065 * and while holding fs_info->trans_lock.
2066 * This serves to guarantee a caller of btrfs_commit_transaction() that it can
2067 * safely free the pending snapshot pointer in case btrfs_commit_transaction()
2070 static void add_pending_snapshot(struct btrfs_trans_handle *trans)
2072 struct btrfs_transaction *cur_trans = trans->transaction;
2074 if (!trans->pending_snapshot)
2077 lockdep_assert_held(&trans->fs_info->trans_lock);
2078 ASSERT(cur_trans->state >= TRANS_STATE_COMMIT_START);
2080 list_add(&trans->pending_snapshot->list, &cur_trans->pending_snapshots);
2083 static void update_commit_stats(struct btrfs_fs_info *fs_info, ktime_t interval)
2085 fs_info->commit_stats.commit_count++;
2086 fs_info->commit_stats.last_commit_dur = interval;
2087 fs_info->commit_stats.max_commit_dur =
2088 max_t(u64, fs_info->commit_stats.max_commit_dur, interval);
2089 fs_info->commit_stats.total_commit_dur += interval;
2092 int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
2094 struct btrfs_fs_info *fs_info = trans->fs_info;
2095 struct btrfs_transaction *cur_trans = trans->transaction;
2096 struct btrfs_transaction *prev_trans = NULL;
2101 ASSERT(refcount_read(&trans->use_count) == 1);
2102 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_START);
2104 /* Stop the commit early if ->aborted is set */
2105 if (TRANS_ABORTED(cur_trans)) {
2106 ret = cur_trans->aborted;
2107 goto lockdep_trans_commit_start_release;
2110 btrfs_trans_release_metadata(trans);
2111 trans->block_rsv = NULL;
2114 * We only want one transaction commit doing the flushing so we do not
2115 * waste a bunch of time on lock contention on the extent root node.
2117 if (!test_and_set_bit(BTRFS_DELAYED_REFS_FLUSHING,
2118 &cur_trans->delayed_refs.flags)) {
2120 * Make a pass through all the delayed refs we have so far.
2121 * Any running threads may add more while we are here.
2123 ret = btrfs_run_delayed_refs(trans, 0);
2125 goto lockdep_trans_commit_start_release;
2128 btrfs_create_pending_block_groups(trans);
2130 if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
2133 /* this mutex is also taken before trying to set
2134 * block groups readonly. We need to make sure
2135 * that nobody has set a block group readonly
2136 * after a extents from that block group have been
2137 * allocated for cache files. btrfs_set_block_group_ro
2138 * will wait for the transaction to commit if it
2139 * finds BTRFS_TRANS_DIRTY_BG_RUN set.
2141 * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
2142 * only one process starts all the block group IO. It wouldn't
2143 * hurt to have more than one go through, but there's no
2144 * real advantage to it either.
2146 mutex_lock(&fs_info->ro_block_group_mutex);
2147 if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
2150 mutex_unlock(&fs_info->ro_block_group_mutex);
2153 ret = btrfs_start_dirty_block_groups(trans);
2155 goto lockdep_trans_commit_start_release;
2159 spin_lock(&fs_info->trans_lock);
2160 if (cur_trans->state >= TRANS_STATE_COMMIT_START) {
2161 enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2163 add_pending_snapshot(trans);
2165 spin_unlock(&fs_info->trans_lock);
2166 refcount_inc(&cur_trans->use_count);
2168 if (trans->in_fsync)
2169 want_state = TRANS_STATE_SUPER_COMMITTED;
2171 btrfs_trans_state_lockdep_release(fs_info,
2172 BTRFS_LOCKDEP_TRANS_COMMIT_START);
2173 ret = btrfs_end_transaction(trans);
2174 wait_for_commit(cur_trans, want_state);
2176 if (TRANS_ABORTED(cur_trans))
2177 ret = cur_trans->aborted;
2179 btrfs_put_transaction(cur_trans);
2184 cur_trans->state = TRANS_STATE_COMMIT_START;
2185 wake_up(&fs_info->transaction_blocked_wait);
2186 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_START);
2188 if (cur_trans->list.prev != &fs_info->trans_list) {
2189 enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2191 if (trans->in_fsync)
2192 want_state = TRANS_STATE_SUPER_COMMITTED;
2194 prev_trans = list_entry(cur_trans->list.prev,
2195 struct btrfs_transaction, list);
2196 if (prev_trans->state < want_state) {
2197 refcount_inc(&prev_trans->use_count);
2198 spin_unlock(&fs_info->trans_lock);
2200 wait_for_commit(prev_trans, want_state);
2202 ret = READ_ONCE(prev_trans->aborted);
2204 btrfs_put_transaction(prev_trans);
2206 goto lockdep_release;
2208 spin_unlock(&fs_info->trans_lock);
2211 spin_unlock(&fs_info->trans_lock);
2213 * The previous transaction was aborted and was already removed
2214 * from the list of transactions at fs_info->trans_list. So we
2215 * abort to prevent writing a new superblock that reflects a
2216 * corrupt state (pointing to trees with unwritten nodes/leafs).
2218 if (BTRFS_FS_ERROR(fs_info)) {
2220 goto lockdep_release;
2225 * Get the time spent on the work done by the commit thread and not
2226 * the time spent waiting on a previous commit
2228 start_time = ktime_get_ns();
2230 extwriter_counter_dec(cur_trans, trans->type);
2232 ret = btrfs_start_delalloc_flush(fs_info);
2234 goto lockdep_release;
2236 ret = btrfs_run_delayed_items(trans);
2238 goto lockdep_release;
2241 * The thread has started/joined the transaction thus it holds the
2242 * lockdep map as a reader. It has to release it before acquiring the
2243 * lockdep map as a writer.
2245 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2246 btrfs_might_wait_for_event(fs_info, btrfs_trans_num_extwriters);
2247 wait_event(cur_trans->writer_wait,
2248 extwriter_counter_read(cur_trans) == 0);
2250 /* some pending stuffs might be added after the previous flush. */
2251 ret = btrfs_run_delayed_items(trans);
2253 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2254 goto cleanup_transaction;
2257 btrfs_wait_delalloc_flush(fs_info);
2260 * Wait for all ordered extents started by a fast fsync that joined this
2261 * transaction. Otherwise if this transaction commits before the ordered
2262 * extents complete we lose logged data after a power failure.
2264 btrfs_might_wait_for_event(fs_info, btrfs_trans_pending_ordered);
2265 wait_event(cur_trans->pending_wait,
2266 atomic_read(&cur_trans->pending_ordered) == 0);
2268 btrfs_scrub_pause(fs_info);
2270 * Ok now we need to make sure to block out any other joins while we
2271 * commit the transaction. We could have started a join before setting
2272 * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2274 spin_lock(&fs_info->trans_lock);
2275 add_pending_snapshot(trans);
2276 cur_trans->state = TRANS_STATE_COMMIT_DOING;
2277 spin_unlock(&fs_info->trans_lock);
2280 * The thread has started/joined the transaction thus it holds the
2281 * lockdep map as a reader. It has to release it before acquiring the
2282 * lockdep map as a writer.
2284 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2285 btrfs_might_wait_for_event(fs_info, btrfs_trans_num_writers);
2286 wait_event(cur_trans->writer_wait,
2287 atomic_read(&cur_trans->num_writers) == 1);
2290 * Make lockdep happy by acquiring the state locks after
2291 * btrfs_trans_num_writers is released. If we acquired the state locks
2292 * before releasing the btrfs_trans_num_writers lock then lockdep would
2293 * complain because we did not follow the reverse order unlocking rule.
2295 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2296 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2297 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2300 * We've started the commit, clear the flag in case we were triggered to
2301 * do an async commit but somebody else started before the transaction
2302 * kthread could do the work.
2304 clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
2306 if (TRANS_ABORTED(cur_trans)) {
2307 ret = cur_trans->aborted;
2308 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2309 goto scrub_continue;
2312 * the reloc mutex makes sure that we stop
2313 * the balancing code from coming in and moving
2314 * extents around in the middle of the commit
2316 mutex_lock(&fs_info->reloc_mutex);
2319 * We needn't worry about the delayed items because we will
2320 * deal with them in create_pending_snapshot(), which is the
2321 * core function of the snapshot creation.
2323 ret = create_pending_snapshots(trans);
2328 * We insert the dir indexes of the snapshots and update the inode
2329 * of the snapshots' parents after the snapshot creation, so there
2330 * are some delayed items which are not dealt with. Now deal with
2333 * We needn't worry that this operation will corrupt the snapshots,
2334 * because all the tree which are snapshoted will be forced to COW
2335 * the nodes and leaves.
2337 ret = btrfs_run_delayed_items(trans);
2341 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2346 * make sure none of the code above managed to slip in a
2349 btrfs_assert_delayed_root_empty(fs_info);
2351 WARN_ON(cur_trans != trans->transaction);
2353 ret = commit_fs_roots(trans);
2358 * Since the transaction is done, we can apply the pending changes
2359 * before the next transaction.
2361 btrfs_apply_pending_changes(fs_info);
2363 /* commit_fs_roots gets rid of all the tree log roots, it is now
2364 * safe to free the root of tree log roots
2366 btrfs_free_log_root_tree(trans, fs_info);
2369 * Since fs roots are all committed, we can get a quite accurate
2370 * new_roots. So let's do quota accounting.
2372 ret = btrfs_qgroup_account_extents(trans);
2376 ret = commit_cowonly_roots(trans);
2381 * The tasks which save the space cache and inode cache may also
2382 * update ->aborted, check it.
2384 if (TRANS_ABORTED(cur_trans)) {
2385 ret = cur_trans->aborted;
2389 cur_trans = fs_info->running_transaction;
2391 btrfs_set_root_node(&fs_info->tree_root->root_item,
2392 fs_info->tree_root->node);
2393 list_add_tail(&fs_info->tree_root->dirty_list,
2394 &cur_trans->switch_commits);
2396 btrfs_set_root_node(&fs_info->chunk_root->root_item,
2397 fs_info->chunk_root->node);
2398 list_add_tail(&fs_info->chunk_root->dirty_list,
2399 &cur_trans->switch_commits);
2401 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
2402 btrfs_set_root_node(&fs_info->block_group_root->root_item,
2403 fs_info->block_group_root->node);
2404 list_add_tail(&fs_info->block_group_root->dirty_list,
2405 &cur_trans->switch_commits);
2408 switch_commit_roots(trans);
2410 ASSERT(list_empty(&cur_trans->dirty_bgs));
2411 ASSERT(list_empty(&cur_trans->io_bgs));
2412 update_super_roots(fs_info);
2414 btrfs_set_super_log_root(fs_info->super_copy, 0);
2415 btrfs_set_super_log_root_level(fs_info->super_copy, 0);
2416 memcpy(fs_info->super_for_commit, fs_info->super_copy,
2417 sizeof(*fs_info->super_copy));
2419 btrfs_commit_device_sizes(cur_trans);
2421 clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2422 clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2424 btrfs_trans_release_chunk_metadata(trans);
2427 * Before changing the transaction state to TRANS_STATE_UNBLOCKED and
2428 * setting fs_info->running_transaction to NULL, lock tree_log_mutex to
2429 * make sure that before we commit our superblock, no other task can
2430 * start a new transaction and commit a log tree before we commit our
2431 * superblock. Anyone trying to commit a log tree locks this mutex before
2432 * writing its superblock.
2434 mutex_lock(&fs_info->tree_log_mutex);
2436 spin_lock(&fs_info->trans_lock);
2437 cur_trans->state = TRANS_STATE_UNBLOCKED;
2438 fs_info->running_transaction = NULL;
2439 spin_unlock(&fs_info->trans_lock);
2440 mutex_unlock(&fs_info->reloc_mutex);
2442 wake_up(&fs_info->transaction_wait);
2443 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2445 ret = btrfs_write_and_wait_transaction(trans);
2447 btrfs_handle_fs_error(fs_info, ret,
2448 "Error while writing out transaction");
2449 mutex_unlock(&fs_info->tree_log_mutex);
2450 goto scrub_continue;
2454 * At this point, we should have written all the tree blocks allocated
2455 * in this transaction. So it's now safe to free the redirtyied extent
2458 btrfs_free_redirty_list(cur_trans);
2460 ret = write_all_supers(fs_info, 0);
2462 * the super is written, we can safely allow the tree-loggers
2463 * to go about their business
2465 mutex_unlock(&fs_info->tree_log_mutex);
2467 goto scrub_continue;
2470 * We needn't acquire the lock here because there is no other task
2471 * which can change it.
2473 cur_trans->state = TRANS_STATE_SUPER_COMMITTED;
2474 wake_up(&cur_trans->commit_wait);
2475 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2477 btrfs_finish_extent_commit(trans);
2479 if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
2480 btrfs_clear_space_info_full(fs_info);
2482 fs_info->last_trans_committed = cur_trans->transid;
2484 * We needn't acquire the lock here because there is no other task
2485 * which can change it.
2487 cur_trans->state = TRANS_STATE_COMPLETED;
2488 wake_up(&cur_trans->commit_wait);
2489 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2491 spin_lock(&fs_info->trans_lock);
2492 list_del_init(&cur_trans->list);
2493 spin_unlock(&fs_info->trans_lock);
2495 btrfs_put_transaction(cur_trans);
2496 btrfs_put_transaction(cur_trans);
2498 if (trans->type & __TRANS_FREEZABLE)
2499 sb_end_intwrite(fs_info->sb);
2501 trace_btrfs_transaction_commit(fs_info);
2503 interval = ktime_get_ns() - start_time;
2505 btrfs_scrub_continue(fs_info);
2507 if (current->journal_info == trans)
2508 current->journal_info = NULL;
2510 kmem_cache_free(btrfs_trans_handle_cachep, trans);
2512 update_commit_stats(fs_info, interval);
2517 mutex_unlock(&fs_info->reloc_mutex);
2518 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2520 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2521 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2522 btrfs_scrub_continue(fs_info);
2523 cleanup_transaction:
2524 btrfs_trans_release_metadata(trans);
2525 btrfs_cleanup_pending_block_groups(trans);
2526 btrfs_trans_release_chunk_metadata(trans);
2527 trans->block_rsv = NULL;
2528 btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
2529 if (current->journal_info == trans)
2530 current->journal_info = NULL;
2531 cleanup_transaction(trans, ret);
2536 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2537 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2538 goto cleanup_transaction;
2540 lockdep_trans_commit_start_release:
2541 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_START);
2542 btrfs_end_transaction(trans);
2547 * return < 0 if error
2548 * 0 if there are no more dead_roots at the time of call
2549 * 1 there are more to be processed, call me again
2551 * The return value indicates there are certainly more snapshots to delete, but
2552 * if there comes a new one during processing, it may return 0. We don't mind,
2553 * because btrfs_commit_super will poke cleaner thread and it will process it a
2554 * few seconds later.
2556 int btrfs_clean_one_deleted_snapshot(struct btrfs_fs_info *fs_info)
2558 struct btrfs_root *root;
2561 spin_lock(&fs_info->trans_lock);
2562 if (list_empty(&fs_info->dead_roots)) {
2563 spin_unlock(&fs_info->trans_lock);
2566 root = list_first_entry(&fs_info->dead_roots,
2567 struct btrfs_root, root_list);
2568 list_del_init(&root->root_list);
2569 spin_unlock(&fs_info->trans_lock);
2571 btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
2573 btrfs_kill_all_delayed_nodes(root);
2575 if (btrfs_header_backref_rev(root->node) <
2576 BTRFS_MIXED_BACKREF_REV)
2577 ret = btrfs_drop_snapshot(root, 0, 0);
2579 ret = btrfs_drop_snapshot(root, 1, 0);
2581 btrfs_put_root(root);
2582 return (ret < 0) ? 0 : 1;
2585 void btrfs_apply_pending_changes(struct btrfs_fs_info *fs_info)
2590 prev = xchg(&fs_info->pending_changes, 0);
2594 bit = 1 << BTRFS_PENDING_COMMIT;
2596 btrfs_debug(fs_info, "pending commit done");
2601 "unknown pending changes left 0x%lx, ignoring", prev);