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>
15 #include "transaction.h"
18 #include "inode-map.h"
20 #include "dev-replace.h"
23 #define BTRFS_ROOT_TRANS_TAG 0
25 static const unsigned int btrfs_blocked_trans_types[TRANS_STATE_MAX] = {
26 [TRANS_STATE_RUNNING] = 0U,
27 [TRANS_STATE_BLOCKED] = __TRANS_START,
28 [TRANS_STATE_COMMIT_START] = (__TRANS_START | __TRANS_ATTACH),
29 [TRANS_STATE_COMMIT_DOING] = (__TRANS_START |
32 [TRANS_STATE_UNBLOCKED] = (__TRANS_START |
36 [TRANS_STATE_COMPLETED] = (__TRANS_START |
42 void btrfs_put_transaction(struct btrfs_transaction *transaction)
44 WARN_ON(refcount_read(&transaction->use_count) == 0);
45 if (refcount_dec_and_test(&transaction->use_count)) {
46 BUG_ON(!list_empty(&transaction->list));
47 WARN_ON(!RB_EMPTY_ROOT(
48 &transaction->delayed_refs.href_root.rb_root));
49 if (transaction->delayed_refs.pending_csums)
50 btrfs_err(transaction->fs_info,
51 "pending csums is %llu",
52 transaction->delayed_refs.pending_csums);
53 while (!list_empty(&transaction->pending_chunks)) {
54 struct extent_map *em;
56 em = list_first_entry(&transaction->pending_chunks,
57 struct extent_map, list);
58 list_del_init(&em->list);
62 * If any block groups are found in ->deleted_bgs then it's
63 * because the transaction was aborted and a commit did not
64 * happen (things failed before writing the new superblock
65 * and calling btrfs_finish_extent_commit()), so we can not
66 * discard the physical locations of the block groups.
68 while (!list_empty(&transaction->deleted_bgs)) {
69 struct btrfs_block_group_cache *cache;
71 cache = list_first_entry(&transaction->deleted_bgs,
72 struct btrfs_block_group_cache,
74 list_del_init(&cache->bg_list);
75 btrfs_put_block_group_trimming(cache);
76 btrfs_put_block_group(cache);
82 static void clear_btree_io_tree(struct extent_io_tree *tree)
84 spin_lock(&tree->lock);
86 * Do a single barrier for the waitqueue_active check here, the state
87 * of the waitqueue should not change once clear_btree_io_tree is
91 while (!RB_EMPTY_ROOT(&tree->state)) {
93 struct extent_state *state;
95 node = rb_first(&tree->state);
96 state = rb_entry(node, struct extent_state, rb_node);
97 rb_erase(&state->rb_node, &tree->state);
98 RB_CLEAR_NODE(&state->rb_node);
100 * btree io trees aren't supposed to have tasks waiting for
101 * changes in the flags of extent states ever.
103 ASSERT(!waitqueue_active(&state->wq));
104 free_extent_state(state);
106 cond_resched_lock(&tree->lock);
108 spin_unlock(&tree->lock);
111 static noinline void switch_commit_roots(struct btrfs_transaction *trans)
113 struct btrfs_fs_info *fs_info = trans->fs_info;
114 struct btrfs_root *root, *tmp;
116 down_write(&fs_info->commit_root_sem);
117 list_for_each_entry_safe(root, tmp, &trans->switch_commits,
119 list_del_init(&root->dirty_list);
120 free_extent_buffer(root->commit_root);
121 root->commit_root = btrfs_root_node(root);
122 if (is_fstree(root->root_key.objectid))
123 btrfs_unpin_free_ino(root);
124 clear_btree_io_tree(&root->dirty_log_pages);
125 btrfs_qgroup_clean_swapped_blocks(root);
128 /* We can free old roots now. */
129 spin_lock(&trans->dropped_roots_lock);
130 while (!list_empty(&trans->dropped_roots)) {
131 root = list_first_entry(&trans->dropped_roots,
132 struct btrfs_root, root_list);
133 list_del_init(&root->root_list);
134 spin_unlock(&trans->dropped_roots_lock);
135 btrfs_drop_and_free_fs_root(fs_info, root);
136 spin_lock(&trans->dropped_roots_lock);
138 spin_unlock(&trans->dropped_roots_lock);
139 up_write(&fs_info->commit_root_sem);
142 static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
145 if (type & TRANS_EXTWRITERS)
146 atomic_inc(&trans->num_extwriters);
149 static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
152 if (type & TRANS_EXTWRITERS)
153 atomic_dec(&trans->num_extwriters);
156 static inline void extwriter_counter_init(struct btrfs_transaction *trans,
159 atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
162 static inline int extwriter_counter_read(struct btrfs_transaction *trans)
164 return atomic_read(&trans->num_extwriters);
168 * either allocate a new transaction or hop into the existing one
170 static noinline int join_transaction(struct btrfs_fs_info *fs_info,
173 struct btrfs_transaction *cur_trans;
175 spin_lock(&fs_info->trans_lock);
177 /* The file system has been taken offline. No new transactions. */
178 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
179 spin_unlock(&fs_info->trans_lock);
183 cur_trans = fs_info->running_transaction;
185 if (cur_trans->aborted) {
186 spin_unlock(&fs_info->trans_lock);
187 return cur_trans->aborted;
189 if (btrfs_blocked_trans_types[cur_trans->state] & type) {
190 spin_unlock(&fs_info->trans_lock);
193 refcount_inc(&cur_trans->use_count);
194 atomic_inc(&cur_trans->num_writers);
195 extwriter_counter_inc(cur_trans, type);
196 spin_unlock(&fs_info->trans_lock);
199 spin_unlock(&fs_info->trans_lock);
202 * If we are ATTACH, we just want to catch the current transaction,
203 * and commit it. If there is no transaction, just return ENOENT.
205 if (type == TRANS_ATTACH)
209 * JOIN_NOLOCK only happens during the transaction commit, so
210 * it is impossible that ->running_transaction is NULL
212 BUG_ON(type == TRANS_JOIN_NOLOCK);
214 cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
218 spin_lock(&fs_info->trans_lock);
219 if (fs_info->running_transaction) {
221 * someone started a transaction after we unlocked. Make sure
222 * to redo the checks above
226 } else if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
227 spin_unlock(&fs_info->trans_lock);
232 cur_trans->fs_info = fs_info;
233 atomic_set(&cur_trans->num_writers, 1);
234 extwriter_counter_init(cur_trans, type);
235 init_waitqueue_head(&cur_trans->writer_wait);
236 init_waitqueue_head(&cur_trans->commit_wait);
237 cur_trans->state = TRANS_STATE_RUNNING;
239 * One for this trans handle, one so it will live on until we
240 * commit the transaction.
242 refcount_set(&cur_trans->use_count, 2);
243 cur_trans->flags = 0;
244 cur_trans->start_time = ktime_get_seconds();
246 memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
248 cur_trans->delayed_refs.href_root = RB_ROOT_CACHED;
249 cur_trans->delayed_refs.dirty_extent_root = RB_ROOT;
250 atomic_set(&cur_trans->delayed_refs.num_entries, 0);
253 * although the tree mod log is per file system and not per transaction,
254 * the log must never go across transaction boundaries.
257 if (!list_empty(&fs_info->tree_mod_seq_list))
258 WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
259 if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
260 WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
261 atomic64_set(&fs_info->tree_mod_seq, 0);
263 spin_lock_init(&cur_trans->delayed_refs.lock);
265 INIT_LIST_HEAD(&cur_trans->pending_snapshots);
266 INIT_LIST_HEAD(&cur_trans->pending_chunks);
267 INIT_LIST_HEAD(&cur_trans->switch_commits);
268 INIT_LIST_HEAD(&cur_trans->dirty_bgs);
269 INIT_LIST_HEAD(&cur_trans->io_bgs);
270 INIT_LIST_HEAD(&cur_trans->dropped_roots);
271 mutex_init(&cur_trans->cache_write_mutex);
272 cur_trans->num_dirty_bgs = 0;
273 spin_lock_init(&cur_trans->dirty_bgs_lock);
274 INIT_LIST_HEAD(&cur_trans->deleted_bgs);
275 spin_lock_init(&cur_trans->dropped_roots_lock);
276 list_add_tail(&cur_trans->list, &fs_info->trans_list);
277 extent_io_tree_init(&cur_trans->dirty_pages,
278 fs_info->btree_inode);
279 fs_info->generation++;
280 cur_trans->transid = fs_info->generation;
281 fs_info->running_transaction = cur_trans;
282 cur_trans->aborted = 0;
283 spin_unlock(&fs_info->trans_lock);
289 * this does all the record keeping required to make sure that a reference
290 * counted root is properly recorded in a given transaction. This is required
291 * to make sure the old root from before we joined the transaction is deleted
292 * when the transaction commits
294 static int record_root_in_trans(struct btrfs_trans_handle *trans,
295 struct btrfs_root *root,
298 struct btrfs_fs_info *fs_info = root->fs_info;
300 if ((test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
301 root->last_trans < trans->transid) || force) {
302 WARN_ON(root == fs_info->extent_root);
303 WARN_ON(!force && root->commit_root != root->node);
306 * see below for IN_TRANS_SETUP usage rules
307 * we have the reloc mutex held now, so there
308 * is only one writer in this function
310 set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
312 /* make sure readers find IN_TRANS_SETUP before
313 * they find our root->last_trans update
317 spin_lock(&fs_info->fs_roots_radix_lock);
318 if (root->last_trans == trans->transid && !force) {
319 spin_unlock(&fs_info->fs_roots_radix_lock);
322 radix_tree_tag_set(&fs_info->fs_roots_radix,
323 (unsigned long)root->root_key.objectid,
324 BTRFS_ROOT_TRANS_TAG);
325 spin_unlock(&fs_info->fs_roots_radix_lock);
326 root->last_trans = trans->transid;
328 /* this is pretty tricky. We don't want to
329 * take the relocation lock in btrfs_record_root_in_trans
330 * unless we're really doing the first setup for this root in
333 * Normally we'd use root->last_trans as a flag to decide
334 * if we want to take the expensive mutex.
336 * But, we have to set root->last_trans before we
337 * init the relocation root, otherwise, we trip over warnings
338 * in ctree.c. The solution used here is to flag ourselves
339 * with root IN_TRANS_SETUP. When this is 1, we're still
340 * fixing up the reloc trees and everyone must wait.
342 * When this is zero, they can trust root->last_trans and fly
343 * through btrfs_record_root_in_trans without having to take the
344 * lock. smp_wmb() makes sure that all the writes above are
345 * done before we pop in the zero below
347 btrfs_init_reloc_root(trans, root);
348 smp_mb__before_atomic();
349 clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
355 void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
356 struct btrfs_root *root)
358 struct btrfs_fs_info *fs_info = root->fs_info;
359 struct btrfs_transaction *cur_trans = trans->transaction;
361 /* Add ourselves to the transaction dropped list */
362 spin_lock(&cur_trans->dropped_roots_lock);
363 list_add_tail(&root->root_list, &cur_trans->dropped_roots);
364 spin_unlock(&cur_trans->dropped_roots_lock);
366 /* Make sure we don't try to update the root at commit time */
367 spin_lock(&fs_info->fs_roots_radix_lock);
368 radix_tree_tag_clear(&fs_info->fs_roots_radix,
369 (unsigned long)root->root_key.objectid,
370 BTRFS_ROOT_TRANS_TAG);
371 spin_unlock(&fs_info->fs_roots_radix_lock);
374 int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
375 struct btrfs_root *root)
377 struct btrfs_fs_info *fs_info = root->fs_info;
379 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
383 * see record_root_in_trans for comments about IN_TRANS_SETUP usage
387 if (root->last_trans == trans->transid &&
388 !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
391 mutex_lock(&fs_info->reloc_mutex);
392 record_root_in_trans(trans, root, 0);
393 mutex_unlock(&fs_info->reloc_mutex);
398 static inline int is_transaction_blocked(struct btrfs_transaction *trans)
400 return (trans->state >= TRANS_STATE_BLOCKED &&
401 trans->state < TRANS_STATE_UNBLOCKED &&
405 /* wait for commit against the current transaction to become unblocked
406 * when this is done, it is safe to start a new transaction, but the current
407 * transaction might not be fully on disk.
409 static void wait_current_trans(struct btrfs_fs_info *fs_info)
411 struct btrfs_transaction *cur_trans;
413 spin_lock(&fs_info->trans_lock);
414 cur_trans = fs_info->running_transaction;
415 if (cur_trans && is_transaction_blocked(cur_trans)) {
416 refcount_inc(&cur_trans->use_count);
417 spin_unlock(&fs_info->trans_lock);
419 wait_event(fs_info->transaction_wait,
420 cur_trans->state >= TRANS_STATE_UNBLOCKED ||
422 btrfs_put_transaction(cur_trans);
424 spin_unlock(&fs_info->trans_lock);
428 static int may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
430 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
433 if (type == TRANS_START)
439 static inline bool need_reserve_reloc_root(struct btrfs_root *root)
441 struct btrfs_fs_info *fs_info = root->fs_info;
443 if (!fs_info->reloc_ctl ||
444 !test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
445 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
452 static struct btrfs_trans_handle *
453 start_transaction(struct btrfs_root *root, unsigned int num_items,
454 unsigned int type, enum btrfs_reserve_flush_enum flush,
455 bool enforce_qgroups)
457 struct btrfs_fs_info *fs_info = root->fs_info;
458 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
459 struct btrfs_trans_handle *h;
460 struct btrfs_transaction *cur_trans;
462 u64 qgroup_reserved = 0;
463 bool reloc_reserved = false;
466 /* Send isn't supposed to start transactions. */
467 ASSERT(current->journal_info != BTRFS_SEND_TRANS_STUB);
469 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
470 return ERR_PTR(-EROFS);
472 if (current->journal_info) {
473 WARN_ON(type & TRANS_EXTWRITERS);
474 h = current->journal_info;
475 refcount_inc(&h->use_count);
476 WARN_ON(refcount_read(&h->use_count) > 2);
477 h->orig_rsv = h->block_rsv;
483 * Do the reservation before we join the transaction so we can do all
484 * the appropriate flushing if need be.
486 if (num_items && root != fs_info->chunk_root) {
487 struct btrfs_block_rsv *rsv = &fs_info->trans_block_rsv;
488 u64 delayed_refs_bytes = 0;
490 qgroup_reserved = num_items * fs_info->nodesize;
491 ret = btrfs_qgroup_reserve_meta_pertrans(root, qgroup_reserved,
497 * We want to reserve all the bytes we may need all at once, so
498 * we only do 1 enospc flushing cycle per transaction start. We
499 * accomplish this by simply assuming we'll do 2 x num_items
500 * worth of delayed refs updates in this trans handle, and
501 * refill that amount for whatever is missing in the reserve.
503 num_bytes = btrfs_calc_trans_metadata_size(fs_info, num_items);
504 if (delayed_refs_rsv->full == 0) {
505 delayed_refs_bytes = num_bytes;
510 * Do the reservation for the relocation root creation
512 if (need_reserve_reloc_root(root)) {
513 num_bytes += fs_info->nodesize;
514 reloc_reserved = true;
517 ret = btrfs_block_rsv_add(root, rsv, num_bytes, flush);
520 if (delayed_refs_bytes) {
521 btrfs_migrate_to_delayed_refs_rsv(fs_info, rsv,
523 num_bytes -= delayed_refs_bytes;
525 } else if (num_items == 0 && flush == BTRFS_RESERVE_FLUSH_ALL &&
526 !delayed_refs_rsv->full) {
528 * Some people call with btrfs_start_transaction(root, 0)
529 * because they can be throttled, but have some other mechanism
530 * for reserving space. We still want these guys to refill the
531 * delayed block_rsv so just add 1 items worth of reservation
534 ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
539 h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
546 * If we are JOIN_NOLOCK we're already committing a transaction and
547 * waiting on this guy, so we don't need to do the sb_start_intwrite
548 * because we're already holding a ref. We need this because we could
549 * have raced in and did an fsync() on a file which can kick a commit
550 * and then we deadlock with somebody doing a freeze.
552 * If we are ATTACH, it means we just want to catch the current
553 * transaction and commit it, so we needn't do sb_start_intwrite().
555 if (type & __TRANS_FREEZABLE)
556 sb_start_intwrite(fs_info->sb);
558 if (may_wait_transaction(fs_info, type))
559 wait_current_trans(fs_info);
562 ret = join_transaction(fs_info, type);
564 wait_current_trans(fs_info);
565 if (unlikely(type == TRANS_ATTACH))
568 } while (ret == -EBUSY);
573 cur_trans = fs_info->running_transaction;
575 h->transid = cur_trans->transid;
576 h->transaction = cur_trans;
578 refcount_set(&h->use_count, 1);
579 h->fs_info = root->fs_info;
582 h->can_flush_pending_bgs = true;
583 INIT_LIST_HEAD(&h->new_bgs);
586 if (cur_trans->state >= TRANS_STATE_BLOCKED &&
587 may_wait_transaction(fs_info, type)) {
588 current->journal_info = h;
589 btrfs_commit_transaction(h);
594 trace_btrfs_space_reservation(fs_info, "transaction",
595 h->transid, num_bytes, 1);
596 h->block_rsv = &fs_info->trans_block_rsv;
597 h->bytes_reserved = num_bytes;
598 h->reloc_reserved = reloc_reserved;
602 btrfs_record_root_in_trans(h, root);
604 if (!current->journal_info)
605 current->journal_info = h;
609 if (type & __TRANS_FREEZABLE)
610 sb_end_intwrite(fs_info->sb);
611 kmem_cache_free(btrfs_trans_handle_cachep, h);
614 btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
617 btrfs_qgroup_free_meta_pertrans(root, qgroup_reserved);
621 struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
622 unsigned int num_items)
624 return start_transaction(root, num_items, TRANS_START,
625 BTRFS_RESERVE_FLUSH_ALL, true);
628 struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
629 struct btrfs_root *root,
630 unsigned int num_items,
633 struct btrfs_fs_info *fs_info = root->fs_info;
634 struct btrfs_trans_handle *trans;
639 * We have two callers: unlink and block group removal. The
640 * former should succeed even if we will temporarily exceed
641 * quota and the latter operates on the extent root so
642 * qgroup enforcement is ignored anyway.
644 trans = start_transaction(root, num_items, TRANS_START,
645 BTRFS_RESERVE_FLUSH_ALL, false);
646 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
649 trans = btrfs_start_transaction(root, 0);
653 num_bytes = btrfs_calc_trans_metadata_size(fs_info, num_items);
654 ret = btrfs_cond_migrate_bytes(fs_info, &fs_info->trans_block_rsv,
655 num_bytes, min_factor);
657 btrfs_end_transaction(trans);
661 trans->block_rsv = &fs_info->trans_block_rsv;
662 trans->bytes_reserved = num_bytes;
663 trace_btrfs_space_reservation(fs_info, "transaction",
664 trans->transid, num_bytes, 1);
669 struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
671 return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
675 struct btrfs_trans_handle *btrfs_join_transaction_nolock(struct btrfs_root *root)
677 return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
678 BTRFS_RESERVE_NO_FLUSH, true);
682 * btrfs_attach_transaction() - catch the running transaction
684 * It is used when we want to commit the current the transaction, but
685 * don't want to start a new one.
687 * Note: If this function return -ENOENT, it just means there is no
688 * running transaction. But it is possible that the inactive transaction
689 * is still in the memory, not fully on disk. If you hope there is no
690 * inactive transaction in the fs when -ENOENT is returned, you should
692 * btrfs_attach_transaction_barrier()
694 struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
696 return start_transaction(root, 0, TRANS_ATTACH,
697 BTRFS_RESERVE_NO_FLUSH, true);
701 * btrfs_attach_transaction_barrier() - catch the running transaction
703 * It is similar to the above function, the difference is this one
704 * will wait for all the inactive transactions until they fully
707 struct btrfs_trans_handle *
708 btrfs_attach_transaction_barrier(struct btrfs_root *root)
710 struct btrfs_trans_handle *trans;
712 trans = start_transaction(root, 0, TRANS_ATTACH,
713 BTRFS_RESERVE_NO_FLUSH, true);
714 if (trans == ERR_PTR(-ENOENT))
715 btrfs_wait_for_commit(root->fs_info, 0);
720 /* wait for a transaction commit to be fully complete */
721 static noinline void wait_for_commit(struct btrfs_transaction *commit)
723 wait_event(commit->commit_wait, commit->state == TRANS_STATE_COMPLETED);
726 int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
728 struct btrfs_transaction *cur_trans = NULL, *t;
732 if (transid <= fs_info->last_trans_committed)
735 /* find specified transaction */
736 spin_lock(&fs_info->trans_lock);
737 list_for_each_entry(t, &fs_info->trans_list, list) {
738 if (t->transid == transid) {
740 refcount_inc(&cur_trans->use_count);
744 if (t->transid > transid) {
749 spin_unlock(&fs_info->trans_lock);
752 * The specified transaction doesn't exist, or we
753 * raced with btrfs_commit_transaction
756 if (transid > fs_info->last_trans_committed)
761 /* find newest transaction that is committing | committed */
762 spin_lock(&fs_info->trans_lock);
763 list_for_each_entry_reverse(t, &fs_info->trans_list,
765 if (t->state >= TRANS_STATE_COMMIT_START) {
766 if (t->state == TRANS_STATE_COMPLETED)
769 refcount_inc(&cur_trans->use_count);
773 spin_unlock(&fs_info->trans_lock);
775 goto out; /* nothing committing|committed */
778 wait_for_commit(cur_trans);
779 btrfs_put_transaction(cur_trans);
784 void btrfs_throttle(struct btrfs_fs_info *fs_info)
786 wait_current_trans(fs_info);
789 static int should_end_transaction(struct btrfs_trans_handle *trans)
791 struct btrfs_fs_info *fs_info = trans->fs_info;
793 if (btrfs_check_space_for_delayed_refs(fs_info))
796 return !!btrfs_block_rsv_check(&fs_info->global_block_rsv, 5);
799 int btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
801 struct btrfs_transaction *cur_trans = trans->transaction;
804 if (cur_trans->state >= TRANS_STATE_BLOCKED ||
805 cur_trans->delayed_refs.flushing)
808 return should_end_transaction(trans);
811 static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
814 struct btrfs_fs_info *fs_info = trans->fs_info;
816 if (!trans->block_rsv) {
817 ASSERT(!trans->bytes_reserved);
821 if (!trans->bytes_reserved)
824 ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
825 trace_btrfs_space_reservation(fs_info, "transaction",
826 trans->transid, trans->bytes_reserved, 0);
827 btrfs_block_rsv_release(fs_info, trans->block_rsv,
828 trans->bytes_reserved);
829 trans->bytes_reserved = 0;
832 static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
835 struct btrfs_fs_info *info = trans->fs_info;
836 struct btrfs_transaction *cur_trans = trans->transaction;
837 int lock = (trans->type != TRANS_JOIN_NOLOCK);
840 if (refcount_read(&trans->use_count) > 1) {
841 refcount_dec(&trans->use_count);
842 trans->block_rsv = trans->orig_rsv;
846 btrfs_trans_release_metadata(trans);
847 trans->block_rsv = NULL;
849 btrfs_create_pending_block_groups(trans);
851 btrfs_trans_release_chunk_metadata(trans);
853 if (lock && READ_ONCE(cur_trans->state) == TRANS_STATE_BLOCKED) {
855 return btrfs_commit_transaction(trans);
857 wake_up_process(info->transaction_kthread);
860 if (trans->type & __TRANS_FREEZABLE)
861 sb_end_intwrite(info->sb);
863 WARN_ON(cur_trans != info->running_transaction);
864 WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
865 atomic_dec(&cur_trans->num_writers);
866 extwriter_counter_dec(cur_trans, trans->type);
868 cond_wake_up(&cur_trans->writer_wait);
869 btrfs_put_transaction(cur_trans);
871 if (current->journal_info == trans)
872 current->journal_info = NULL;
875 btrfs_run_delayed_iputs(info);
877 if (trans->aborted ||
878 test_bit(BTRFS_FS_STATE_ERROR, &info->fs_state)) {
879 wake_up_process(info->transaction_kthread);
883 kmem_cache_free(btrfs_trans_handle_cachep, trans);
887 int btrfs_end_transaction(struct btrfs_trans_handle *trans)
889 return __btrfs_end_transaction(trans, 0);
892 int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
894 return __btrfs_end_transaction(trans, 1);
898 * when btree blocks are allocated, they have some corresponding bits set for
899 * them in one of two extent_io trees. This is used to make sure all of
900 * those extents are sent to disk but does not wait on them
902 int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
903 struct extent_io_tree *dirty_pages, int mark)
907 struct address_space *mapping = fs_info->btree_inode->i_mapping;
908 struct extent_state *cached_state = NULL;
912 atomic_inc(&BTRFS_I(fs_info->btree_inode)->sync_writers);
913 while (!find_first_extent_bit(dirty_pages, start, &start, &end,
914 mark, &cached_state)) {
915 bool wait_writeback = false;
917 err = convert_extent_bit(dirty_pages, start, end,
919 mark, &cached_state);
921 * convert_extent_bit can return -ENOMEM, which is most of the
922 * time a temporary error. So when it happens, ignore the error
923 * and wait for writeback of this range to finish - because we
924 * failed to set the bit EXTENT_NEED_WAIT for the range, a call
925 * to __btrfs_wait_marked_extents() would not know that
926 * writeback for this range started and therefore wouldn't
927 * wait for it to finish - we don't want to commit a
928 * superblock that points to btree nodes/leafs for which
929 * writeback hasn't finished yet (and without errors).
930 * We cleanup any entries left in the io tree when committing
931 * the transaction (through clear_btree_io_tree()).
933 if (err == -ENOMEM) {
935 wait_writeback = true;
938 err = filemap_fdatawrite_range(mapping, start, end);
941 else if (wait_writeback)
942 werr = filemap_fdatawait_range(mapping, start, end);
943 free_extent_state(cached_state);
948 atomic_dec(&BTRFS_I(fs_info->btree_inode)->sync_writers);
953 * when btree blocks are allocated, they have some corresponding bits set for
954 * them in one of two extent_io trees. This is used to make sure all of
955 * those extents are on disk for transaction or log commit. We wait
956 * on all the pages and clear them from the dirty pages state tree
958 static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
959 struct extent_io_tree *dirty_pages)
963 struct address_space *mapping = fs_info->btree_inode->i_mapping;
964 struct extent_state *cached_state = NULL;
968 while (!find_first_extent_bit(dirty_pages, start, &start, &end,
969 EXTENT_NEED_WAIT, &cached_state)) {
971 * Ignore -ENOMEM errors returned by clear_extent_bit().
972 * When committing the transaction, we'll remove any entries
973 * left in the io tree. For a log commit, we don't remove them
974 * after committing the log because the tree can be accessed
975 * concurrently - we do it only at transaction commit time when
976 * it's safe to do it (through clear_btree_io_tree()).
978 err = clear_extent_bit(dirty_pages, start, end,
979 EXTENT_NEED_WAIT, 0, 0, &cached_state);
983 err = filemap_fdatawait_range(mapping, start, end);
986 free_extent_state(cached_state);
996 int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
997 struct extent_io_tree *dirty_pages)
1002 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1003 if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1011 int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
1013 struct btrfs_fs_info *fs_info = log_root->fs_info;
1014 struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
1015 bool errors = false;
1018 ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
1020 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1021 if ((mark & EXTENT_DIRTY) &&
1022 test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1025 if ((mark & EXTENT_NEW) &&
1026 test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1035 * When btree blocks are allocated the corresponding extents are marked dirty.
1036 * This function ensures such extents are persisted on disk for transaction or
1039 * @trans: transaction whose dirty pages we'd like to write
1041 static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1045 struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
1046 struct btrfs_fs_info *fs_info = trans->fs_info;
1047 struct blk_plug plug;
1049 blk_start_plug(&plug);
1050 ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1051 blk_finish_plug(&plug);
1052 ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1054 clear_btree_io_tree(&trans->transaction->dirty_pages);
1065 * this is used to update the root pointer in the tree of tree roots.
1067 * But, in the case of the extent allocation tree, updating the root
1068 * pointer may allocate blocks which may change the root of the extent
1071 * So, this loops and repeats and makes sure the cowonly root didn't
1072 * change while the root pointer was being updated in the metadata.
1074 static int update_cowonly_root(struct btrfs_trans_handle *trans,
1075 struct btrfs_root *root)
1078 u64 old_root_bytenr;
1080 struct btrfs_fs_info *fs_info = root->fs_info;
1081 struct btrfs_root *tree_root = fs_info->tree_root;
1083 old_root_used = btrfs_root_used(&root->root_item);
1086 old_root_bytenr = btrfs_root_bytenr(&root->root_item);
1087 if (old_root_bytenr == root->node->start &&
1088 old_root_used == btrfs_root_used(&root->root_item))
1091 btrfs_set_root_node(&root->root_item, root->node);
1092 ret = btrfs_update_root(trans, tree_root,
1098 old_root_used = btrfs_root_used(&root->root_item);
1105 * update all the cowonly tree roots on disk
1107 * The error handling in this function may not be obvious. Any of the
1108 * failures will cause the file system to go offline. We still need
1109 * to clean up the delayed refs.
1111 static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
1113 struct btrfs_fs_info *fs_info = trans->fs_info;
1114 struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
1115 struct list_head *io_bgs = &trans->transaction->io_bgs;
1116 struct list_head *next;
1117 struct extent_buffer *eb;
1120 eb = btrfs_lock_root_node(fs_info->tree_root);
1121 ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
1123 btrfs_tree_unlock(eb);
1124 free_extent_buffer(eb);
1129 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1133 ret = btrfs_run_dev_stats(trans, fs_info);
1136 ret = btrfs_run_dev_replace(trans, fs_info);
1139 ret = btrfs_run_qgroups(trans);
1143 ret = btrfs_setup_space_cache(trans, fs_info);
1147 /* run_qgroups might have added some more refs */
1148 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1152 while (!list_empty(&fs_info->dirty_cowonly_roots)) {
1153 struct btrfs_root *root;
1154 next = fs_info->dirty_cowonly_roots.next;
1155 list_del_init(next);
1156 root = list_entry(next, struct btrfs_root, dirty_list);
1157 clear_bit(BTRFS_ROOT_DIRTY, &root->state);
1159 if (root != fs_info->extent_root)
1160 list_add_tail(&root->dirty_list,
1161 &trans->transaction->switch_commits);
1162 ret = update_cowonly_root(trans, root);
1165 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1170 while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
1171 ret = btrfs_write_dirty_block_groups(trans, fs_info);
1174 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1179 if (!list_empty(&fs_info->dirty_cowonly_roots))
1182 list_add_tail(&fs_info->extent_root->dirty_list,
1183 &trans->transaction->switch_commits);
1185 /* Update dev-replace pointer once everything is committed */
1186 fs_info->dev_replace.committed_cursor_left =
1187 fs_info->dev_replace.cursor_left_last_write_of_item;
1193 * dead roots are old snapshots that need to be deleted. This allocates
1194 * a dirty root struct and adds it into the list of dead roots that need to
1197 void btrfs_add_dead_root(struct btrfs_root *root)
1199 struct btrfs_fs_info *fs_info = root->fs_info;
1201 spin_lock(&fs_info->trans_lock);
1202 if (list_empty(&root->root_list))
1203 list_add_tail(&root->root_list, &fs_info->dead_roots);
1204 spin_unlock(&fs_info->trans_lock);
1208 * update all the cowonly tree roots on disk
1210 static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
1212 struct btrfs_fs_info *fs_info = trans->fs_info;
1213 struct btrfs_root *gang[8];
1218 spin_lock(&fs_info->fs_roots_radix_lock);
1220 ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
1223 BTRFS_ROOT_TRANS_TAG);
1226 for (i = 0; i < ret; i++) {
1227 struct btrfs_root *root = gang[i];
1228 radix_tree_tag_clear(&fs_info->fs_roots_radix,
1229 (unsigned long)root->root_key.objectid,
1230 BTRFS_ROOT_TRANS_TAG);
1231 spin_unlock(&fs_info->fs_roots_radix_lock);
1233 btrfs_free_log(trans, root);
1234 btrfs_update_reloc_root(trans, root);
1236 btrfs_save_ino_cache(root, trans);
1238 /* see comments in should_cow_block() */
1239 clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1240 smp_mb__after_atomic();
1242 if (root->commit_root != root->node) {
1243 list_add_tail(&root->dirty_list,
1244 &trans->transaction->switch_commits);
1245 btrfs_set_root_node(&root->root_item,
1249 err = btrfs_update_root(trans, fs_info->tree_root,
1252 spin_lock(&fs_info->fs_roots_radix_lock);
1255 btrfs_qgroup_free_meta_all_pertrans(root);
1258 spin_unlock(&fs_info->fs_roots_radix_lock);
1263 * defrag a given btree.
1264 * Every leaf in the btree is read and defragged.
1266 int btrfs_defrag_root(struct btrfs_root *root)
1268 struct btrfs_fs_info *info = root->fs_info;
1269 struct btrfs_trans_handle *trans;
1272 if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
1276 trans = btrfs_start_transaction(root, 0);
1278 return PTR_ERR(trans);
1280 ret = btrfs_defrag_leaves(trans, root);
1282 btrfs_end_transaction(trans);
1283 btrfs_btree_balance_dirty(info);
1286 if (btrfs_fs_closing(info) || ret != -EAGAIN)
1289 if (btrfs_defrag_cancelled(info)) {
1290 btrfs_debug(info, "defrag_root cancelled");
1295 clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
1300 * Do all special snapshot related qgroup dirty hack.
1302 * Will do all needed qgroup inherit and dirty hack like switch commit
1303 * roots inside one transaction and write all btree into disk, to make
1306 static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
1307 struct btrfs_root *src,
1308 struct btrfs_root *parent,
1309 struct btrfs_qgroup_inherit *inherit,
1312 struct btrfs_fs_info *fs_info = src->fs_info;
1316 * Save some performance in the case that qgroups are not
1317 * enabled. If this check races with the ioctl, rescan will
1320 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1324 * Ensure dirty @src will be committed. Or, after coming
1325 * commit_fs_roots() and switch_commit_roots(), any dirty but not
1326 * recorded root will never be updated again, causing an outdated root
1329 record_root_in_trans(trans, src, 1);
1332 * We are going to commit transaction, see btrfs_commit_transaction()
1333 * comment for reason locking tree_log_mutex
1335 mutex_lock(&fs_info->tree_log_mutex);
1337 ret = commit_fs_roots(trans);
1340 ret = btrfs_qgroup_account_extents(trans);
1344 /* Now qgroup are all updated, we can inherit it to new qgroups */
1345 ret = btrfs_qgroup_inherit(trans, src->root_key.objectid, dst_objectid,
1351 * Now we do a simplified commit transaction, which will:
1352 * 1) commit all subvolume and extent tree
1353 * To ensure all subvolume and extent tree have a valid
1354 * commit_root to accounting later insert_dir_item()
1355 * 2) write all btree blocks onto disk
1356 * This is to make sure later btree modification will be cowed
1357 * Or commit_root can be populated and cause wrong qgroup numbers
1358 * In this simplified commit, we don't really care about other trees
1359 * like chunk and root tree, as they won't affect qgroup.
1360 * And we don't write super to avoid half committed status.
1362 ret = commit_cowonly_roots(trans);
1365 switch_commit_roots(trans->transaction);
1366 ret = btrfs_write_and_wait_transaction(trans);
1368 btrfs_handle_fs_error(fs_info, ret,
1369 "Error while writing out transaction for qgroup");
1372 mutex_unlock(&fs_info->tree_log_mutex);
1375 * Force parent root to be updated, as we recorded it before so its
1376 * last_trans == cur_transid.
1377 * Or it won't be committed again onto disk after later
1381 record_root_in_trans(trans, parent, 1);
1386 * new snapshots need to be created at a very specific time in the
1387 * transaction commit. This does the actual creation.
1390 * If the error which may affect the commitment of the current transaction
1391 * happens, we should return the error number. If the error which just affect
1392 * the creation of the pending snapshots, just return 0.
1394 static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
1395 struct btrfs_pending_snapshot *pending)
1398 struct btrfs_fs_info *fs_info = trans->fs_info;
1399 struct btrfs_key key;
1400 struct btrfs_root_item *new_root_item;
1401 struct btrfs_root *tree_root = fs_info->tree_root;
1402 struct btrfs_root *root = pending->root;
1403 struct btrfs_root *parent_root;
1404 struct btrfs_block_rsv *rsv;
1405 struct inode *parent_inode;
1406 struct btrfs_path *path;
1407 struct btrfs_dir_item *dir_item;
1408 struct dentry *dentry;
1409 struct extent_buffer *tmp;
1410 struct extent_buffer *old;
1411 struct timespec64 cur_time;
1419 ASSERT(pending->path);
1420 path = pending->path;
1422 ASSERT(pending->root_item);
1423 new_root_item = pending->root_item;
1425 pending->error = btrfs_find_free_objectid(tree_root, &objectid);
1427 goto no_free_objectid;
1430 * Make qgroup to skip current new snapshot's qgroupid, as it is
1431 * accounted by later btrfs_qgroup_inherit().
1433 btrfs_set_skip_qgroup(trans, objectid);
1435 btrfs_reloc_pre_snapshot(pending, &to_reserve);
1437 if (to_reserve > 0) {
1438 pending->error = btrfs_block_rsv_add(root,
1439 &pending->block_rsv,
1441 BTRFS_RESERVE_NO_FLUSH);
1443 goto clear_skip_qgroup;
1446 key.objectid = objectid;
1447 key.offset = (u64)-1;
1448 key.type = BTRFS_ROOT_ITEM_KEY;
1450 rsv = trans->block_rsv;
1451 trans->block_rsv = &pending->block_rsv;
1452 trans->bytes_reserved = trans->block_rsv->reserved;
1453 trace_btrfs_space_reservation(fs_info, "transaction",
1455 trans->bytes_reserved, 1);
1456 dentry = pending->dentry;
1457 parent_inode = pending->dir;
1458 parent_root = BTRFS_I(parent_inode)->root;
1459 record_root_in_trans(trans, parent_root, 0);
1461 cur_time = current_time(parent_inode);
1464 * insert the directory item
1466 ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
1467 BUG_ON(ret); /* -ENOMEM */
1469 /* check if there is a file/dir which has the same name. */
1470 dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
1471 btrfs_ino(BTRFS_I(parent_inode)),
1472 dentry->d_name.name,
1473 dentry->d_name.len, 0);
1474 if (dir_item != NULL && !IS_ERR(dir_item)) {
1475 pending->error = -EEXIST;
1476 goto dir_item_existed;
1477 } else if (IS_ERR(dir_item)) {
1478 ret = PTR_ERR(dir_item);
1479 btrfs_abort_transaction(trans, ret);
1482 btrfs_release_path(path);
1485 * pull in the delayed directory update
1486 * and the delayed inode item
1487 * otherwise we corrupt the FS during
1490 ret = btrfs_run_delayed_items(trans);
1491 if (ret) { /* Transaction aborted */
1492 btrfs_abort_transaction(trans, ret);
1496 record_root_in_trans(trans, root, 0);
1497 btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
1498 memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
1499 btrfs_check_and_init_root_item(new_root_item);
1501 root_flags = btrfs_root_flags(new_root_item);
1502 if (pending->readonly)
1503 root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1505 root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1506 btrfs_set_root_flags(new_root_item, root_flags);
1508 btrfs_set_root_generation_v2(new_root_item,
1510 uuid_le_gen(&new_uuid);
1511 memcpy(new_root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
1512 memcpy(new_root_item->parent_uuid, root->root_item.uuid,
1514 if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
1515 memset(new_root_item->received_uuid, 0,
1516 sizeof(new_root_item->received_uuid));
1517 memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
1518 memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
1519 btrfs_set_root_stransid(new_root_item, 0);
1520 btrfs_set_root_rtransid(new_root_item, 0);
1522 btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
1523 btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
1524 btrfs_set_root_otransid(new_root_item, trans->transid);
1526 old = btrfs_lock_root_node(root);
1527 ret = btrfs_cow_block(trans, root, old, NULL, 0, &old);
1529 btrfs_tree_unlock(old);
1530 free_extent_buffer(old);
1531 btrfs_abort_transaction(trans, ret);
1535 btrfs_set_lock_blocking_write(old);
1537 ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
1538 /* clean up in any case */
1539 btrfs_tree_unlock(old);
1540 free_extent_buffer(old);
1542 btrfs_abort_transaction(trans, ret);
1545 /* see comments in should_cow_block() */
1546 set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1549 btrfs_set_root_node(new_root_item, tmp);
1550 /* record when the snapshot was created in key.offset */
1551 key.offset = trans->transid;
1552 ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1553 btrfs_tree_unlock(tmp);
1554 free_extent_buffer(tmp);
1556 btrfs_abort_transaction(trans, ret);
1561 * insert root back/forward references
1563 ret = btrfs_add_root_ref(trans, objectid,
1564 parent_root->root_key.objectid,
1565 btrfs_ino(BTRFS_I(parent_inode)), index,
1566 dentry->d_name.name, dentry->d_name.len);
1568 btrfs_abort_transaction(trans, ret);
1572 key.offset = (u64)-1;
1573 pending->snap = btrfs_read_fs_root_no_name(fs_info, &key);
1574 if (IS_ERR(pending->snap)) {
1575 ret = PTR_ERR(pending->snap);
1576 btrfs_abort_transaction(trans, ret);
1580 ret = btrfs_reloc_post_snapshot(trans, pending);
1582 btrfs_abort_transaction(trans, ret);
1586 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1588 btrfs_abort_transaction(trans, ret);
1593 * Do special qgroup accounting for snapshot, as we do some qgroup
1594 * snapshot hack to do fast snapshot.
1595 * To co-operate with that hack, we do hack again.
1596 * Or snapshot will be greatly slowed down by a subtree qgroup rescan
1598 ret = qgroup_account_snapshot(trans, root, parent_root,
1599 pending->inherit, objectid);
1603 ret = btrfs_insert_dir_item(trans, dentry->d_name.name,
1604 dentry->d_name.len, BTRFS_I(parent_inode),
1605 &key, BTRFS_FT_DIR, index);
1606 /* We have check then name at the beginning, so it is impossible. */
1607 BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
1609 btrfs_abort_transaction(trans, ret);
1613 btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
1614 dentry->d_name.len * 2);
1615 parent_inode->i_mtime = parent_inode->i_ctime =
1616 current_time(parent_inode);
1617 ret = btrfs_update_inode_fallback(trans, parent_root, parent_inode);
1619 btrfs_abort_transaction(trans, ret);
1622 ret = btrfs_uuid_tree_add(trans, new_uuid.b, BTRFS_UUID_KEY_SUBVOL,
1625 btrfs_abort_transaction(trans, ret);
1628 if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1629 ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1630 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1632 if (ret && ret != -EEXIST) {
1633 btrfs_abort_transaction(trans, ret);
1638 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1640 btrfs_abort_transaction(trans, ret);
1645 pending->error = ret;
1647 trans->block_rsv = rsv;
1648 trans->bytes_reserved = 0;
1650 btrfs_clear_skip_qgroup(trans);
1652 kfree(new_root_item);
1653 pending->root_item = NULL;
1654 btrfs_free_path(path);
1655 pending->path = NULL;
1661 * create all the snapshots we've scheduled for creation
1663 static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
1665 struct btrfs_pending_snapshot *pending, *next;
1666 struct list_head *head = &trans->transaction->pending_snapshots;
1669 list_for_each_entry_safe(pending, next, head, list) {
1670 list_del(&pending->list);
1671 ret = create_pending_snapshot(trans, pending);
1678 static void update_super_roots(struct btrfs_fs_info *fs_info)
1680 struct btrfs_root_item *root_item;
1681 struct btrfs_super_block *super;
1683 super = fs_info->super_copy;
1685 root_item = &fs_info->chunk_root->root_item;
1686 super->chunk_root = root_item->bytenr;
1687 super->chunk_root_generation = root_item->generation;
1688 super->chunk_root_level = root_item->level;
1690 root_item = &fs_info->tree_root->root_item;
1691 super->root = root_item->bytenr;
1692 super->generation = root_item->generation;
1693 super->root_level = root_item->level;
1694 if (btrfs_test_opt(fs_info, SPACE_CACHE))
1695 super->cache_generation = root_item->generation;
1696 if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1697 super->uuid_tree_generation = root_item->generation;
1700 int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1702 struct btrfs_transaction *trans;
1705 spin_lock(&info->trans_lock);
1706 trans = info->running_transaction;
1708 ret = (trans->state >= TRANS_STATE_COMMIT_START);
1709 spin_unlock(&info->trans_lock);
1713 int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1715 struct btrfs_transaction *trans;
1718 spin_lock(&info->trans_lock);
1719 trans = info->running_transaction;
1721 ret = is_transaction_blocked(trans);
1722 spin_unlock(&info->trans_lock);
1727 * wait for the current transaction commit to start and block subsequent
1730 static void wait_current_trans_commit_start(struct btrfs_fs_info *fs_info,
1731 struct btrfs_transaction *trans)
1733 wait_event(fs_info->transaction_blocked_wait,
1734 trans->state >= TRANS_STATE_COMMIT_START || trans->aborted);
1738 * wait for the current transaction to start and then become unblocked.
1741 static void wait_current_trans_commit_start_and_unblock(
1742 struct btrfs_fs_info *fs_info,
1743 struct btrfs_transaction *trans)
1745 wait_event(fs_info->transaction_wait,
1746 trans->state >= TRANS_STATE_UNBLOCKED || trans->aborted);
1750 * commit transactions asynchronously. once btrfs_commit_transaction_async
1751 * returns, any subsequent transaction will not be allowed to join.
1753 struct btrfs_async_commit {
1754 struct btrfs_trans_handle *newtrans;
1755 struct work_struct work;
1758 static void do_async_commit(struct work_struct *work)
1760 struct btrfs_async_commit *ac =
1761 container_of(work, struct btrfs_async_commit, work);
1764 * We've got freeze protection passed with the transaction.
1765 * Tell lockdep about it.
1767 if (ac->newtrans->type & __TRANS_FREEZABLE)
1768 __sb_writers_acquired(ac->newtrans->fs_info->sb, SB_FREEZE_FS);
1770 current->journal_info = ac->newtrans;
1772 btrfs_commit_transaction(ac->newtrans);
1776 int btrfs_commit_transaction_async(struct btrfs_trans_handle *trans,
1777 int wait_for_unblock)
1779 struct btrfs_fs_info *fs_info = trans->fs_info;
1780 struct btrfs_async_commit *ac;
1781 struct btrfs_transaction *cur_trans;
1783 ac = kmalloc(sizeof(*ac), GFP_NOFS);
1787 INIT_WORK(&ac->work, do_async_commit);
1788 ac->newtrans = btrfs_join_transaction(trans->root);
1789 if (IS_ERR(ac->newtrans)) {
1790 int err = PTR_ERR(ac->newtrans);
1795 /* take transaction reference */
1796 cur_trans = trans->transaction;
1797 refcount_inc(&cur_trans->use_count);
1799 btrfs_end_transaction(trans);
1802 * Tell lockdep we've released the freeze rwsem, since the
1803 * async commit thread will be the one to unlock it.
1805 if (ac->newtrans->type & __TRANS_FREEZABLE)
1806 __sb_writers_release(fs_info->sb, SB_FREEZE_FS);
1808 schedule_work(&ac->work);
1810 /* wait for transaction to start and unblock */
1811 if (wait_for_unblock)
1812 wait_current_trans_commit_start_and_unblock(fs_info, cur_trans);
1814 wait_current_trans_commit_start(fs_info, cur_trans);
1816 if (current->journal_info == trans)
1817 current->journal_info = NULL;
1819 btrfs_put_transaction(cur_trans);
1824 static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
1826 struct btrfs_fs_info *fs_info = trans->fs_info;
1827 struct btrfs_transaction *cur_trans = trans->transaction;
1829 WARN_ON(refcount_read(&trans->use_count) > 1);
1831 btrfs_abort_transaction(trans, err);
1833 spin_lock(&fs_info->trans_lock);
1836 * If the transaction is removed from the list, it means this
1837 * transaction has been committed successfully, so it is impossible
1838 * to call the cleanup function.
1840 BUG_ON(list_empty(&cur_trans->list));
1842 list_del_init(&cur_trans->list);
1843 if (cur_trans == fs_info->running_transaction) {
1844 cur_trans->state = TRANS_STATE_COMMIT_DOING;
1845 spin_unlock(&fs_info->trans_lock);
1846 wait_event(cur_trans->writer_wait,
1847 atomic_read(&cur_trans->num_writers) == 1);
1849 spin_lock(&fs_info->trans_lock);
1851 spin_unlock(&fs_info->trans_lock);
1853 btrfs_cleanup_one_transaction(trans->transaction, fs_info);
1855 spin_lock(&fs_info->trans_lock);
1856 if (cur_trans == fs_info->running_transaction)
1857 fs_info->running_transaction = NULL;
1858 spin_unlock(&fs_info->trans_lock);
1860 if (trans->type & __TRANS_FREEZABLE)
1861 sb_end_intwrite(fs_info->sb);
1862 btrfs_put_transaction(cur_trans);
1863 btrfs_put_transaction(cur_trans);
1865 trace_btrfs_transaction_commit(trans->root);
1867 if (current->journal_info == trans)
1868 current->journal_info = NULL;
1869 btrfs_scrub_cancel(fs_info);
1871 kmem_cache_free(btrfs_trans_handle_cachep, trans);
1875 * Release reserved delayed ref space of all pending block groups of the
1876 * transaction and remove them from the list
1878 static void btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle *trans)
1880 struct btrfs_fs_info *fs_info = trans->fs_info;
1881 struct btrfs_block_group_cache *block_group, *tmp;
1883 list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
1884 btrfs_delayed_refs_rsv_release(fs_info, 1);
1885 list_del_init(&block_group->bg_list);
1889 static inline int btrfs_start_delalloc_flush(struct btrfs_fs_info *fs_info)
1892 * We use writeback_inodes_sb here because if we used
1893 * btrfs_start_delalloc_roots we would deadlock with fs freeze.
1894 * Currently are holding the fs freeze lock, if we do an async flush
1895 * we'll do btrfs_join_transaction() and deadlock because we need to
1896 * wait for the fs freeze lock. Using the direct flushing we benefit
1897 * from already being in a transaction and our join_transaction doesn't
1898 * have to re-take the fs freeze lock.
1900 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
1901 writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
1905 static inline void btrfs_wait_delalloc_flush(struct btrfs_fs_info *fs_info)
1907 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
1908 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
1911 int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
1913 struct btrfs_fs_info *fs_info = trans->fs_info;
1914 struct btrfs_transaction *cur_trans = trans->transaction;
1915 struct btrfs_transaction *prev_trans = NULL;
1918 /* Stop the commit early if ->aborted is set */
1919 if (unlikely(READ_ONCE(cur_trans->aborted))) {
1920 ret = cur_trans->aborted;
1921 btrfs_end_transaction(trans);
1925 btrfs_trans_release_metadata(trans);
1926 trans->block_rsv = NULL;
1928 /* make a pass through all the delayed refs we have so far
1929 * any runnings procs may add more while we are here
1931 ret = btrfs_run_delayed_refs(trans, 0);
1933 btrfs_end_transaction(trans);
1937 cur_trans = trans->transaction;
1940 * set the flushing flag so procs in this transaction have to
1941 * start sending their work down.
1943 cur_trans->delayed_refs.flushing = 1;
1946 btrfs_create_pending_block_groups(trans);
1948 ret = btrfs_run_delayed_refs(trans, 0);
1950 btrfs_end_transaction(trans);
1954 if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
1957 /* this mutex is also taken before trying to set
1958 * block groups readonly. We need to make sure
1959 * that nobody has set a block group readonly
1960 * after a extents from that block group have been
1961 * allocated for cache files. btrfs_set_block_group_ro
1962 * will wait for the transaction to commit if it
1963 * finds BTRFS_TRANS_DIRTY_BG_RUN set.
1965 * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
1966 * only one process starts all the block group IO. It wouldn't
1967 * hurt to have more than one go through, but there's no
1968 * real advantage to it either.
1970 mutex_lock(&fs_info->ro_block_group_mutex);
1971 if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
1974 mutex_unlock(&fs_info->ro_block_group_mutex);
1977 ret = btrfs_start_dirty_block_groups(trans);
1979 btrfs_end_transaction(trans);
1985 spin_lock(&fs_info->trans_lock);
1986 if (cur_trans->state >= TRANS_STATE_COMMIT_START) {
1987 spin_unlock(&fs_info->trans_lock);
1988 refcount_inc(&cur_trans->use_count);
1989 ret = btrfs_end_transaction(trans);
1991 wait_for_commit(cur_trans);
1993 if (unlikely(cur_trans->aborted))
1994 ret = cur_trans->aborted;
1996 btrfs_put_transaction(cur_trans);
2001 cur_trans->state = TRANS_STATE_COMMIT_START;
2002 wake_up(&fs_info->transaction_blocked_wait);
2004 if (cur_trans->list.prev != &fs_info->trans_list) {
2005 prev_trans = list_entry(cur_trans->list.prev,
2006 struct btrfs_transaction, list);
2007 if (prev_trans->state != TRANS_STATE_COMPLETED) {
2008 refcount_inc(&prev_trans->use_count);
2009 spin_unlock(&fs_info->trans_lock);
2011 wait_for_commit(prev_trans);
2012 ret = prev_trans->aborted;
2014 btrfs_put_transaction(prev_trans);
2016 goto cleanup_transaction;
2018 spin_unlock(&fs_info->trans_lock);
2021 spin_unlock(&fs_info->trans_lock);
2024 extwriter_counter_dec(cur_trans, trans->type);
2026 ret = btrfs_start_delalloc_flush(fs_info);
2028 goto cleanup_transaction;
2030 ret = btrfs_run_delayed_items(trans);
2032 goto cleanup_transaction;
2034 wait_event(cur_trans->writer_wait,
2035 extwriter_counter_read(cur_trans) == 0);
2037 /* some pending stuffs might be added after the previous flush. */
2038 ret = btrfs_run_delayed_items(trans);
2040 goto cleanup_transaction;
2042 btrfs_wait_delalloc_flush(fs_info);
2044 btrfs_scrub_pause(fs_info);
2046 * Ok now we need to make sure to block out any other joins while we
2047 * commit the transaction. We could have started a join before setting
2048 * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2050 spin_lock(&fs_info->trans_lock);
2051 cur_trans->state = TRANS_STATE_COMMIT_DOING;
2052 spin_unlock(&fs_info->trans_lock);
2053 wait_event(cur_trans->writer_wait,
2054 atomic_read(&cur_trans->num_writers) == 1);
2056 /* ->aborted might be set after the previous check, so check it */
2057 if (unlikely(READ_ONCE(cur_trans->aborted))) {
2058 ret = cur_trans->aborted;
2059 goto scrub_continue;
2062 * the reloc mutex makes sure that we stop
2063 * the balancing code from coming in and moving
2064 * extents around in the middle of the commit
2066 mutex_lock(&fs_info->reloc_mutex);
2069 * We needn't worry about the delayed items because we will
2070 * deal with them in create_pending_snapshot(), which is the
2071 * core function of the snapshot creation.
2073 ret = create_pending_snapshots(trans);
2075 mutex_unlock(&fs_info->reloc_mutex);
2076 goto scrub_continue;
2080 * We insert the dir indexes of the snapshots and update the inode
2081 * of the snapshots' parents after the snapshot creation, so there
2082 * are some delayed items which are not dealt with. Now deal with
2085 * We needn't worry that this operation will corrupt the snapshots,
2086 * because all the tree which are snapshoted will be forced to COW
2087 * the nodes and leaves.
2089 ret = btrfs_run_delayed_items(trans);
2091 mutex_unlock(&fs_info->reloc_mutex);
2092 goto scrub_continue;
2095 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2097 mutex_unlock(&fs_info->reloc_mutex);
2098 goto scrub_continue;
2102 * make sure none of the code above managed to slip in a
2105 btrfs_assert_delayed_root_empty(fs_info);
2107 WARN_ON(cur_trans != trans->transaction);
2109 /* btrfs_commit_tree_roots is responsible for getting the
2110 * various roots consistent with each other. Every pointer
2111 * in the tree of tree roots has to point to the most up to date
2112 * root for every subvolume and other tree. So, we have to keep
2113 * the tree logging code from jumping in and changing any
2116 * At this point in the commit, there can't be any tree-log
2117 * writers, but a little lower down we drop the trans mutex
2118 * and let new people in. By holding the tree_log_mutex
2119 * from now until after the super is written, we avoid races
2120 * with the tree-log code.
2122 mutex_lock(&fs_info->tree_log_mutex);
2124 ret = commit_fs_roots(trans);
2126 mutex_unlock(&fs_info->tree_log_mutex);
2127 mutex_unlock(&fs_info->reloc_mutex);
2128 goto scrub_continue;
2132 * Since the transaction is done, we can apply the pending changes
2133 * before the next transaction.
2135 btrfs_apply_pending_changes(fs_info);
2137 /* commit_fs_roots gets rid of all the tree log roots, it is now
2138 * safe to free the root of tree log roots
2140 btrfs_free_log_root_tree(trans, fs_info);
2143 * commit_fs_roots() can call btrfs_save_ino_cache(), which generates
2144 * new delayed refs. Must handle them or qgroup can be wrong.
2146 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2148 mutex_unlock(&fs_info->tree_log_mutex);
2149 mutex_unlock(&fs_info->reloc_mutex);
2150 goto scrub_continue;
2154 * Since fs roots are all committed, we can get a quite accurate
2155 * new_roots. So let's do quota accounting.
2157 ret = btrfs_qgroup_account_extents(trans);
2159 mutex_unlock(&fs_info->tree_log_mutex);
2160 mutex_unlock(&fs_info->reloc_mutex);
2161 goto scrub_continue;
2164 ret = commit_cowonly_roots(trans);
2166 mutex_unlock(&fs_info->tree_log_mutex);
2167 mutex_unlock(&fs_info->reloc_mutex);
2168 goto scrub_continue;
2172 * The tasks which save the space cache and inode cache may also
2173 * update ->aborted, check it.
2175 if (unlikely(READ_ONCE(cur_trans->aborted))) {
2176 ret = cur_trans->aborted;
2177 mutex_unlock(&fs_info->tree_log_mutex);
2178 mutex_unlock(&fs_info->reloc_mutex);
2179 goto scrub_continue;
2182 btrfs_prepare_extent_commit(fs_info);
2184 cur_trans = fs_info->running_transaction;
2186 btrfs_set_root_node(&fs_info->tree_root->root_item,
2187 fs_info->tree_root->node);
2188 list_add_tail(&fs_info->tree_root->dirty_list,
2189 &cur_trans->switch_commits);
2191 btrfs_set_root_node(&fs_info->chunk_root->root_item,
2192 fs_info->chunk_root->node);
2193 list_add_tail(&fs_info->chunk_root->dirty_list,
2194 &cur_trans->switch_commits);
2196 switch_commit_roots(cur_trans);
2198 ASSERT(list_empty(&cur_trans->dirty_bgs));
2199 ASSERT(list_empty(&cur_trans->io_bgs));
2200 update_super_roots(fs_info);
2202 btrfs_set_super_log_root(fs_info->super_copy, 0);
2203 btrfs_set_super_log_root_level(fs_info->super_copy, 0);
2204 memcpy(fs_info->super_for_commit, fs_info->super_copy,
2205 sizeof(*fs_info->super_copy));
2207 btrfs_update_commit_device_size(fs_info);
2208 btrfs_update_commit_device_bytes_used(cur_trans);
2210 clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2211 clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2213 btrfs_trans_release_chunk_metadata(trans);
2215 spin_lock(&fs_info->trans_lock);
2216 cur_trans->state = TRANS_STATE_UNBLOCKED;
2217 fs_info->running_transaction = NULL;
2218 spin_unlock(&fs_info->trans_lock);
2219 mutex_unlock(&fs_info->reloc_mutex);
2221 wake_up(&fs_info->transaction_wait);
2223 ret = btrfs_write_and_wait_transaction(trans);
2225 btrfs_handle_fs_error(fs_info, ret,
2226 "Error while writing out transaction");
2227 mutex_unlock(&fs_info->tree_log_mutex);
2228 goto scrub_continue;
2231 ret = write_all_supers(fs_info, 0);
2233 * the super is written, we can safely allow the tree-loggers
2234 * to go about their business
2236 mutex_unlock(&fs_info->tree_log_mutex);
2238 goto scrub_continue;
2240 btrfs_finish_extent_commit(trans);
2242 if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
2243 btrfs_clear_space_info_full(fs_info);
2245 fs_info->last_trans_committed = cur_trans->transid;
2247 * We needn't acquire the lock here because there is no other task
2248 * which can change it.
2250 cur_trans->state = TRANS_STATE_COMPLETED;
2251 wake_up(&cur_trans->commit_wait);
2252 clear_bit(BTRFS_FS_NEED_ASYNC_COMMIT, &fs_info->flags);
2254 spin_lock(&fs_info->trans_lock);
2255 list_del_init(&cur_trans->list);
2256 spin_unlock(&fs_info->trans_lock);
2258 btrfs_put_transaction(cur_trans);
2259 btrfs_put_transaction(cur_trans);
2261 if (trans->type & __TRANS_FREEZABLE)
2262 sb_end_intwrite(fs_info->sb);
2264 trace_btrfs_transaction_commit(trans->root);
2266 btrfs_scrub_continue(fs_info);
2268 if (current->journal_info == trans)
2269 current->journal_info = NULL;
2271 kmem_cache_free(btrfs_trans_handle_cachep, trans);
2276 btrfs_scrub_continue(fs_info);
2277 cleanup_transaction:
2278 btrfs_trans_release_metadata(trans);
2279 btrfs_cleanup_pending_block_groups(trans);
2280 btrfs_trans_release_chunk_metadata(trans);
2281 trans->block_rsv = NULL;
2282 btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
2283 if (current->journal_info == trans)
2284 current->journal_info = NULL;
2285 cleanup_transaction(trans, ret);
2291 * return < 0 if error
2292 * 0 if there are no more dead_roots at the time of call
2293 * 1 there are more to be processed, call me again
2295 * The return value indicates there are certainly more snapshots to delete, but
2296 * if there comes a new one during processing, it may return 0. We don't mind,
2297 * because btrfs_commit_super will poke cleaner thread and it will process it a
2298 * few seconds later.
2300 int btrfs_clean_one_deleted_snapshot(struct btrfs_root *root)
2303 struct btrfs_fs_info *fs_info = root->fs_info;
2305 spin_lock(&fs_info->trans_lock);
2306 if (list_empty(&fs_info->dead_roots)) {
2307 spin_unlock(&fs_info->trans_lock);
2310 root = list_first_entry(&fs_info->dead_roots,
2311 struct btrfs_root, root_list);
2312 list_del_init(&root->root_list);
2313 spin_unlock(&fs_info->trans_lock);
2315 btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
2317 btrfs_kill_all_delayed_nodes(root);
2319 if (btrfs_header_backref_rev(root->node) <
2320 BTRFS_MIXED_BACKREF_REV)
2321 ret = btrfs_drop_snapshot(root, NULL, 0, 0);
2323 ret = btrfs_drop_snapshot(root, NULL, 1, 0);
2325 return (ret < 0) ? 0 : 1;
2328 void btrfs_apply_pending_changes(struct btrfs_fs_info *fs_info)
2333 prev = xchg(&fs_info->pending_changes, 0);
2337 bit = 1 << BTRFS_PENDING_SET_INODE_MAP_CACHE;
2339 btrfs_set_opt(fs_info->mount_opt, INODE_MAP_CACHE);
2342 bit = 1 << BTRFS_PENDING_CLEAR_INODE_MAP_CACHE;
2344 btrfs_clear_opt(fs_info->mount_opt, INODE_MAP_CACHE);
2347 bit = 1 << BTRFS_PENDING_COMMIT;
2349 btrfs_debug(fs_info, "pending commit done");
2354 "unknown pending changes left 0x%lx, ignoring", prev);