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;
164 struct btrfs_caching_control *caching_ctl, *next;
167 * At this point no one can be using this transaction to modify any tree
168 * and no one can start another transaction to modify any tree either.
170 ASSERT(cur_trans->state == TRANS_STATE_COMMIT_DOING);
172 down_write(&fs_info->commit_root_sem);
174 if (test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
175 fs_info->last_reloc_trans = trans->transid;
177 list_for_each_entry_safe(root, tmp, &cur_trans->switch_commits,
179 list_del_init(&root->dirty_list);
180 free_extent_buffer(root->commit_root);
181 root->commit_root = btrfs_root_node(root);
182 extent_io_tree_release(&root->dirty_log_pages);
183 btrfs_qgroup_clean_swapped_blocks(root);
186 /* We can free old roots now. */
187 spin_lock(&cur_trans->dropped_roots_lock);
188 while (!list_empty(&cur_trans->dropped_roots)) {
189 root = list_first_entry(&cur_trans->dropped_roots,
190 struct btrfs_root, root_list);
191 list_del_init(&root->root_list);
192 spin_unlock(&cur_trans->dropped_roots_lock);
193 btrfs_free_log(trans, root);
194 btrfs_drop_and_free_fs_root(fs_info, root);
195 spin_lock(&cur_trans->dropped_roots_lock);
197 spin_unlock(&cur_trans->dropped_roots_lock);
200 * We have to update the last_byte_to_unpin under the commit_root_sem,
201 * at the same time we swap out the commit roots.
203 * This is because we must have a real view of the last spot the caching
204 * kthreads were while caching. Consider the following views of the
205 * extent tree for a block group
208 * +----+----+----+----+----+----+----+
209 * |\\\\| |\\\\|\\\\| |\\\\|\\\\|
210 * +----+----+----+----+----+----+----+
214 * +----+----+----+----+----+----+----+
215 * | | | |\\\\| | |\\\\|
216 * +----+----+----+----+----+----+----+
219 * If the cache_ctl->progress was at 3, then we are only allowed to
220 * unpin [0,1) and [2,3], because the caching thread has already
221 * processed those extents. We are not allowed to unpin [5,6), because
222 * the caching thread will re-start it's search from 3, and thus find
223 * the hole from [4,6) to add to the free space cache.
225 write_lock(&fs_info->block_group_cache_lock);
226 list_for_each_entry_safe(caching_ctl, next,
227 &fs_info->caching_block_groups, list) {
228 struct btrfs_block_group *cache = caching_ctl->block_group;
230 if (btrfs_block_group_done(cache)) {
231 cache->last_byte_to_unpin = (u64)-1;
232 list_del_init(&caching_ctl->list);
233 btrfs_put_caching_control(caching_ctl);
235 cache->last_byte_to_unpin = caching_ctl->progress;
238 write_unlock(&fs_info->block_group_cache_lock);
239 up_write(&fs_info->commit_root_sem);
242 static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
245 if (type & TRANS_EXTWRITERS)
246 atomic_inc(&trans->num_extwriters);
249 static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
252 if (type & TRANS_EXTWRITERS)
253 atomic_dec(&trans->num_extwriters);
256 static inline void extwriter_counter_init(struct btrfs_transaction *trans,
259 atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
262 static inline int extwriter_counter_read(struct btrfs_transaction *trans)
264 return atomic_read(&trans->num_extwriters);
268 * To be called after doing the chunk btree updates right after allocating a new
269 * chunk (after btrfs_chunk_alloc_add_chunk_item() is called), when removing a
270 * chunk after all chunk btree updates and after finishing the second phase of
271 * chunk allocation (btrfs_create_pending_block_groups()) in case some block
272 * group had its chunk item insertion delayed to the second phase.
274 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
276 struct btrfs_fs_info *fs_info = trans->fs_info;
278 if (!trans->chunk_bytes_reserved)
281 btrfs_block_rsv_release(fs_info, &fs_info->chunk_block_rsv,
282 trans->chunk_bytes_reserved, NULL);
283 trans->chunk_bytes_reserved = 0;
287 * either allocate a new transaction or hop into the existing one
289 static noinline int join_transaction(struct btrfs_fs_info *fs_info,
292 struct btrfs_transaction *cur_trans;
294 spin_lock(&fs_info->trans_lock);
296 /* The file system has been taken offline. No new transactions. */
297 if (BTRFS_FS_ERROR(fs_info)) {
298 spin_unlock(&fs_info->trans_lock);
302 cur_trans = fs_info->running_transaction;
304 if (TRANS_ABORTED(cur_trans)) {
305 spin_unlock(&fs_info->trans_lock);
306 return cur_trans->aborted;
308 if (btrfs_blocked_trans_types[cur_trans->state] & type) {
309 spin_unlock(&fs_info->trans_lock);
312 refcount_inc(&cur_trans->use_count);
313 atomic_inc(&cur_trans->num_writers);
314 extwriter_counter_inc(cur_trans, type);
315 spin_unlock(&fs_info->trans_lock);
318 spin_unlock(&fs_info->trans_lock);
321 * If we are ATTACH, we just want to catch the current transaction,
322 * and commit it. If there is no transaction, just return ENOENT.
324 if (type == TRANS_ATTACH)
328 * JOIN_NOLOCK only happens during the transaction commit, so
329 * it is impossible that ->running_transaction is NULL
331 BUG_ON(type == TRANS_JOIN_NOLOCK);
333 cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
337 spin_lock(&fs_info->trans_lock);
338 if (fs_info->running_transaction) {
340 * someone started a transaction after we unlocked. Make sure
341 * to redo the checks above
345 } else if (BTRFS_FS_ERROR(fs_info)) {
346 spin_unlock(&fs_info->trans_lock);
351 cur_trans->fs_info = fs_info;
352 atomic_set(&cur_trans->pending_ordered, 0);
353 init_waitqueue_head(&cur_trans->pending_wait);
354 atomic_set(&cur_trans->num_writers, 1);
355 extwriter_counter_init(cur_trans, type);
356 init_waitqueue_head(&cur_trans->writer_wait);
357 init_waitqueue_head(&cur_trans->commit_wait);
358 cur_trans->state = TRANS_STATE_RUNNING;
360 * One for this trans handle, one so it will live on until we
361 * commit the transaction.
363 refcount_set(&cur_trans->use_count, 2);
364 cur_trans->flags = 0;
365 cur_trans->start_time = ktime_get_seconds();
367 memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
369 cur_trans->delayed_refs.href_root = RB_ROOT_CACHED;
370 cur_trans->delayed_refs.dirty_extent_root = RB_ROOT;
371 atomic_set(&cur_trans->delayed_refs.num_entries, 0);
374 * although the tree mod log is per file system and not per transaction,
375 * the log must never go across transaction boundaries.
378 if (!list_empty(&fs_info->tree_mod_seq_list))
379 WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
380 if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
381 WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
382 atomic64_set(&fs_info->tree_mod_seq, 0);
384 spin_lock_init(&cur_trans->delayed_refs.lock);
386 INIT_LIST_HEAD(&cur_trans->pending_snapshots);
387 INIT_LIST_HEAD(&cur_trans->dev_update_list);
388 INIT_LIST_HEAD(&cur_trans->switch_commits);
389 INIT_LIST_HEAD(&cur_trans->dirty_bgs);
390 INIT_LIST_HEAD(&cur_trans->io_bgs);
391 INIT_LIST_HEAD(&cur_trans->dropped_roots);
392 mutex_init(&cur_trans->cache_write_mutex);
393 spin_lock_init(&cur_trans->dirty_bgs_lock);
394 INIT_LIST_HEAD(&cur_trans->deleted_bgs);
395 spin_lock_init(&cur_trans->dropped_roots_lock);
396 INIT_LIST_HEAD(&cur_trans->releasing_ebs);
397 spin_lock_init(&cur_trans->releasing_ebs_lock);
398 list_add_tail(&cur_trans->list, &fs_info->trans_list);
399 extent_io_tree_init(fs_info, &cur_trans->dirty_pages,
400 IO_TREE_TRANS_DIRTY_PAGES, fs_info->btree_inode);
401 extent_io_tree_init(fs_info, &cur_trans->pinned_extents,
402 IO_TREE_FS_PINNED_EXTENTS, NULL);
403 fs_info->generation++;
404 cur_trans->transid = fs_info->generation;
405 fs_info->running_transaction = cur_trans;
406 cur_trans->aborted = 0;
407 spin_unlock(&fs_info->trans_lock);
413 * This does all the record keeping required to make sure that a shareable root
414 * is properly recorded in a given transaction. This is required to make sure
415 * the old root from before we joined the transaction is deleted when the
416 * transaction commits.
418 static int record_root_in_trans(struct btrfs_trans_handle *trans,
419 struct btrfs_root *root,
422 struct btrfs_fs_info *fs_info = root->fs_info;
425 if ((test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
426 root->last_trans < trans->transid) || force) {
427 WARN_ON(!force && root->commit_root != root->node);
430 * see below for IN_TRANS_SETUP usage rules
431 * we have the reloc mutex held now, so there
432 * is only one writer in this function
434 set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
436 /* make sure readers find IN_TRANS_SETUP before
437 * they find our root->last_trans update
441 spin_lock(&fs_info->fs_roots_radix_lock);
442 if (root->last_trans == trans->transid && !force) {
443 spin_unlock(&fs_info->fs_roots_radix_lock);
446 radix_tree_tag_set(&fs_info->fs_roots_radix,
447 (unsigned long)root->root_key.objectid,
448 BTRFS_ROOT_TRANS_TAG);
449 spin_unlock(&fs_info->fs_roots_radix_lock);
450 root->last_trans = trans->transid;
452 /* this is pretty tricky. We don't want to
453 * take the relocation lock in btrfs_record_root_in_trans
454 * unless we're really doing the first setup for this root in
457 * Normally we'd use root->last_trans as a flag to decide
458 * if we want to take the expensive mutex.
460 * But, we have to set root->last_trans before we
461 * init the relocation root, otherwise, we trip over warnings
462 * in ctree.c. The solution used here is to flag ourselves
463 * with root IN_TRANS_SETUP. When this is 1, we're still
464 * fixing up the reloc trees and everyone must wait.
466 * When this is zero, they can trust root->last_trans and fly
467 * through btrfs_record_root_in_trans without having to take the
468 * lock. smp_wmb() makes sure that all the writes above are
469 * done before we pop in the zero below
471 ret = btrfs_init_reloc_root(trans, root);
472 smp_mb__before_atomic();
473 clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
479 void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
480 struct btrfs_root *root)
482 struct btrfs_fs_info *fs_info = root->fs_info;
483 struct btrfs_transaction *cur_trans = trans->transaction;
485 /* Add ourselves to the transaction dropped list */
486 spin_lock(&cur_trans->dropped_roots_lock);
487 list_add_tail(&root->root_list, &cur_trans->dropped_roots);
488 spin_unlock(&cur_trans->dropped_roots_lock);
490 /* Make sure we don't try to update the root at commit time */
491 spin_lock(&fs_info->fs_roots_radix_lock);
492 radix_tree_tag_clear(&fs_info->fs_roots_radix,
493 (unsigned long)root->root_key.objectid,
494 BTRFS_ROOT_TRANS_TAG);
495 spin_unlock(&fs_info->fs_roots_radix_lock);
498 int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
499 struct btrfs_root *root)
501 struct btrfs_fs_info *fs_info = root->fs_info;
504 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
508 * see record_root_in_trans for comments about IN_TRANS_SETUP usage
512 if (root->last_trans == trans->transid &&
513 !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
516 mutex_lock(&fs_info->reloc_mutex);
517 ret = record_root_in_trans(trans, root, 0);
518 mutex_unlock(&fs_info->reloc_mutex);
523 static inline int is_transaction_blocked(struct btrfs_transaction *trans)
525 return (trans->state >= TRANS_STATE_COMMIT_START &&
526 trans->state < TRANS_STATE_UNBLOCKED &&
527 !TRANS_ABORTED(trans));
530 /* wait for commit against the current transaction to become unblocked
531 * when this is done, it is safe to start a new transaction, but the current
532 * transaction might not be fully on disk.
534 static void wait_current_trans(struct btrfs_fs_info *fs_info)
536 struct btrfs_transaction *cur_trans;
538 spin_lock(&fs_info->trans_lock);
539 cur_trans = fs_info->running_transaction;
540 if (cur_trans && is_transaction_blocked(cur_trans)) {
541 refcount_inc(&cur_trans->use_count);
542 spin_unlock(&fs_info->trans_lock);
544 wait_event(fs_info->transaction_wait,
545 cur_trans->state >= TRANS_STATE_UNBLOCKED ||
546 TRANS_ABORTED(cur_trans));
547 btrfs_put_transaction(cur_trans);
549 spin_unlock(&fs_info->trans_lock);
553 static int may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
555 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
558 if (type == TRANS_START)
564 static inline bool need_reserve_reloc_root(struct btrfs_root *root)
566 struct btrfs_fs_info *fs_info = root->fs_info;
568 if (!fs_info->reloc_ctl ||
569 !test_bit(BTRFS_ROOT_SHAREABLE, &root->state) ||
570 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
577 static struct btrfs_trans_handle *
578 start_transaction(struct btrfs_root *root, unsigned int num_items,
579 unsigned int type, enum btrfs_reserve_flush_enum flush,
580 bool enforce_qgroups)
582 struct btrfs_fs_info *fs_info = root->fs_info;
583 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
584 struct btrfs_trans_handle *h;
585 struct btrfs_transaction *cur_trans;
587 u64 qgroup_reserved = 0;
588 bool reloc_reserved = false;
589 bool do_chunk_alloc = false;
592 if (BTRFS_FS_ERROR(fs_info))
593 return ERR_PTR(-EROFS);
595 if (current->journal_info) {
596 WARN_ON(type & TRANS_EXTWRITERS);
597 h = current->journal_info;
598 refcount_inc(&h->use_count);
599 WARN_ON(refcount_read(&h->use_count) > 2);
600 h->orig_rsv = h->block_rsv;
606 * Do the reservation before we join the transaction so we can do all
607 * the appropriate flushing if need be.
609 if (num_items && root != fs_info->chunk_root) {
610 struct btrfs_block_rsv *rsv = &fs_info->trans_block_rsv;
611 u64 delayed_refs_bytes = 0;
613 qgroup_reserved = num_items * fs_info->nodesize;
614 ret = btrfs_qgroup_reserve_meta_pertrans(root, qgroup_reserved,
620 * We want to reserve all the bytes we may need all at once, so
621 * we only do 1 enospc flushing cycle per transaction start. We
622 * accomplish this by simply assuming we'll do 2 x num_items
623 * worth of delayed refs updates in this trans handle, and
624 * refill that amount for whatever is missing in the reserve.
626 num_bytes = btrfs_calc_insert_metadata_size(fs_info, num_items);
627 if (flush == BTRFS_RESERVE_FLUSH_ALL &&
628 delayed_refs_rsv->full == 0) {
629 delayed_refs_bytes = num_bytes;
634 * Do the reservation for the relocation root creation
636 if (need_reserve_reloc_root(root)) {
637 num_bytes += fs_info->nodesize;
638 reloc_reserved = true;
641 ret = btrfs_block_rsv_add(fs_info, rsv, num_bytes, flush);
644 if (delayed_refs_bytes) {
645 btrfs_migrate_to_delayed_refs_rsv(fs_info, rsv,
647 num_bytes -= delayed_refs_bytes;
650 if (rsv->space_info->force_alloc)
651 do_chunk_alloc = true;
652 } else if (num_items == 0 && flush == BTRFS_RESERVE_FLUSH_ALL &&
653 !delayed_refs_rsv->full) {
655 * Some people call with btrfs_start_transaction(root, 0)
656 * because they can be throttled, but have some other mechanism
657 * for reserving space. We still want these guys to refill the
658 * delayed block_rsv so just add 1 items worth of reservation
661 ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
666 h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
673 * If we are JOIN_NOLOCK we're already committing a transaction and
674 * waiting on this guy, so we don't need to do the sb_start_intwrite
675 * because we're already holding a ref. We need this because we could
676 * have raced in and did an fsync() on a file which can kick a commit
677 * and then we deadlock with somebody doing a freeze.
679 * If we are ATTACH, it means we just want to catch the current
680 * transaction and commit it, so we needn't do sb_start_intwrite().
682 if (type & __TRANS_FREEZABLE)
683 sb_start_intwrite(fs_info->sb);
685 if (may_wait_transaction(fs_info, type))
686 wait_current_trans(fs_info);
689 ret = join_transaction(fs_info, type);
691 wait_current_trans(fs_info);
692 if (unlikely(type == TRANS_ATTACH ||
693 type == TRANS_JOIN_NOSTART))
696 } while (ret == -EBUSY);
701 cur_trans = fs_info->running_transaction;
703 h->transid = cur_trans->transid;
704 h->transaction = cur_trans;
705 refcount_set(&h->use_count, 1);
706 h->fs_info = root->fs_info;
709 INIT_LIST_HEAD(&h->new_bgs);
712 if (cur_trans->state >= TRANS_STATE_COMMIT_START &&
713 may_wait_transaction(fs_info, type)) {
714 current->journal_info = h;
715 btrfs_commit_transaction(h);
720 trace_btrfs_space_reservation(fs_info, "transaction",
721 h->transid, num_bytes, 1);
722 h->block_rsv = &fs_info->trans_block_rsv;
723 h->bytes_reserved = num_bytes;
724 h->reloc_reserved = reloc_reserved;
728 if (!current->journal_info)
729 current->journal_info = h;
732 * If the space_info is marked ALLOC_FORCE then we'll get upgraded to
733 * ALLOC_FORCE the first run through, and then we won't allocate for
734 * anybody else who races in later. We don't care about the return
737 if (do_chunk_alloc && num_bytes) {
738 u64 flags = h->block_rsv->space_info->flags;
740 btrfs_chunk_alloc(h, btrfs_get_alloc_profile(fs_info, flags),
741 CHUNK_ALLOC_NO_FORCE);
745 * btrfs_record_root_in_trans() needs to alloc new extents, and may
746 * call btrfs_join_transaction() while we're also starting a
749 * Thus it need to be called after current->journal_info initialized,
750 * or we can deadlock.
752 ret = btrfs_record_root_in_trans(h, root);
755 * The transaction handle is fully initialized and linked with
756 * other structures so it needs to be ended in case of errors,
759 btrfs_end_transaction(h);
766 if (type & __TRANS_FREEZABLE)
767 sb_end_intwrite(fs_info->sb);
768 kmem_cache_free(btrfs_trans_handle_cachep, h);
771 btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
774 btrfs_qgroup_free_meta_pertrans(root, qgroup_reserved);
778 struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
779 unsigned int num_items)
781 return start_transaction(root, num_items, TRANS_START,
782 BTRFS_RESERVE_FLUSH_ALL, true);
785 struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
786 struct btrfs_root *root,
787 unsigned int num_items)
789 return start_transaction(root, num_items, TRANS_START,
790 BTRFS_RESERVE_FLUSH_ALL_STEAL, false);
793 struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
795 return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
799 struct btrfs_trans_handle *btrfs_join_transaction_spacecache(struct btrfs_root *root)
801 return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
802 BTRFS_RESERVE_NO_FLUSH, true);
806 * Similar to regular join but it never starts a transaction when none is
807 * running or after waiting for the current one to finish.
809 struct btrfs_trans_handle *btrfs_join_transaction_nostart(struct btrfs_root *root)
811 return start_transaction(root, 0, TRANS_JOIN_NOSTART,
812 BTRFS_RESERVE_NO_FLUSH, true);
816 * btrfs_attach_transaction() - catch the running transaction
818 * It is used when we want to commit the current the transaction, but
819 * don't want to start a new one.
821 * Note: If this function return -ENOENT, it just means there is no
822 * running transaction. But it is possible that the inactive transaction
823 * is still in the memory, not fully on disk. If you hope there is no
824 * inactive transaction in the fs when -ENOENT is returned, you should
826 * btrfs_attach_transaction_barrier()
828 struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
830 return start_transaction(root, 0, TRANS_ATTACH,
831 BTRFS_RESERVE_NO_FLUSH, true);
835 * btrfs_attach_transaction_barrier() - catch the running transaction
837 * It is similar to the above function, the difference is this one
838 * will wait for all the inactive transactions until they fully
841 struct btrfs_trans_handle *
842 btrfs_attach_transaction_barrier(struct btrfs_root *root)
844 struct btrfs_trans_handle *trans;
846 trans = start_transaction(root, 0, TRANS_ATTACH,
847 BTRFS_RESERVE_NO_FLUSH, true);
848 if (trans == ERR_PTR(-ENOENT))
849 btrfs_wait_for_commit(root->fs_info, 0);
854 /* Wait for a transaction commit to reach at least the given state. */
855 static noinline void wait_for_commit(struct btrfs_transaction *commit,
856 const enum btrfs_trans_state min_state)
858 struct btrfs_fs_info *fs_info = commit->fs_info;
859 u64 transid = commit->transid;
863 wait_event(commit->commit_wait, commit->state >= min_state);
865 btrfs_put_transaction(commit);
867 if (min_state < TRANS_STATE_COMPLETED)
871 * A transaction isn't really completed until all of the
872 * previous transactions are completed, but with fsync we can
873 * end up with SUPER_COMMITTED transactions before a COMPLETED
874 * transaction. Wait for those.
877 spin_lock(&fs_info->trans_lock);
878 commit = list_first_entry_or_null(&fs_info->trans_list,
879 struct btrfs_transaction,
881 if (!commit || commit->transid > transid) {
882 spin_unlock(&fs_info->trans_lock);
885 refcount_inc(&commit->use_count);
887 spin_unlock(&fs_info->trans_lock);
891 int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
893 struct btrfs_transaction *cur_trans = NULL, *t;
897 if (transid <= fs_info->last_trans_committed)
900 /* find specified transaction */
901 spin_lock(&fs_info->trans_lock);
902 list_for_each_entry(t, &fs_info->trans_list, list) {
903 if (t->transid == transid) {
905 refcount_inc(&cur_trans->use_count);
909 if (t->transid > transid) {
914 spin_unlock(&fs_info->trans_lock);
917 * The specified transaction doesn't exist, or we
918 * raced with btrfs_commit_transaction
921 if (transid > fs_info->last_trans_committed)
926 /* find newest transaction that is committing | committed */
927 spin_lock(&fs_info->trans_lock);
928 list_for_each_entry_reverse(t, &fs_info->trans_list,
930 if (t->state >= TRANS_STATE_COMMIT_START) {
931 if (t->state == TRANS_STATE_COMPLETED)
934 refcount_inc(&cur_trans->use_count);
938 spin_unlock(&fs_info->trans_lock);
940 goto out; /* nothing committing|committed */
943 wait_for_commit(cur_trans, TRANS_STATE_COMPLETED);
944 btrfs_put_transaction(cur_trans);
949 void btrfs_throttle(struct btrfs_fs_info *fs_info)
951 wait_current_trans(fs_info);
954 static bool should_end_transaction(struct btrfs_trans_handle *trans)
956 struct btrfs_fs_info *fs_info = trans->fs_info;
958 if (btrfs_check_space_for_delayed_refs(fs_info))
961 return !!btrfs_block_rsv_check(&fs_info->global_block_rsv, 5);
964 bool btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
966 struct btrfs_transaction *cur_trans = trans->transaction;
968 if (cur_trans->state >= TRANS_STATE_COMMIT_START ||
969 test_bit(BTRFS_DELAYED_REFS_FLUSHING, &cur_trans->delayed_refs.flags))
972 return should_end_transaction(trans);
975 static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
978 struct btrfs_fs_info *fs_info = trans->fs_info;
980 if (!trans->block_rsv) {
981 ASSERT(!trans->bytes_reserved);
985 if (!trans->bytes_reserved)
988 ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
989 trace_btrfs_space_reservation(fs_info, "transaction",
990 trans->transid, trans->bytes_reserved, 0);
991 btrfs_block_rsv_release(fs_info, trans->block_rsv,
992 trans->bytes_reserved, NULL);
993 trans->bytes_reserved = 0;
996 static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
999 struct btrfs_fs_info *info = trans->fs_info;
1000 struct btrfs_transaction *cur_trans = trans->transaction;
1003 if (refcount_read(&trans->use_count) > 1) {
1004 refcount_dec(&trans->use_count);
1005 trans->block_rsv = trans->orig_rsv;
1009 btrfs_trans_release_metadata(trans);
1010 trans->block_rsv = NULL;
1012 btrfs_create_pending_block_groups(trans);
1014 btrfs_trans_release_chunk_metadata(trans);
1016 if (trans->type & __TRANS_FREEZABLE)
1017 sb_end_intwrite(info->sb);
1019 WARN_ON(cur_trans != info->running_transaction);
1020 WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
1021 atomic_dec(&cur_trans->num_writers);
1022 extwriter_counter_dec(cur_trans, trans->type);
1024 cond_wake_up(&cur_trans->writer_wait);
1025 btrfs_put_transaction(cur_trans);
1027 if (current->journal_info == trans)
1028 current->journal_info = NULL;
1031 btrfs_run_delayed_iputs(info);
1033 if (TRANS_ABORTED(trans) || BTRFS_FS_ERROR(info)) {
1034 wake_up_process(info->transaction_kthread);
1035 if (TRANS_ABORTED(trans))
1036 err = trans->aborted;
1041 kmem_cache_free(btrfs_trans_handle_cachep, trans);
1045 int btrfs_end_transaction(struct btrfs_trans_handle *trans)
1047 return __btrfs_end_transaction(trans, 0);
1050 int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
1052 return __btrfs_end_transaction(trans, 1);
1056 * when btree blocks are allocated, they have some corresponding bits set for
1057 * them in one of two extent_io trees. This is used to make sure all of
1058 * those extents are sent to disk but does not wait on them
1060 int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
1061 struct extent_io_tree *dirty_pages, int mark)
1065 struct address_space *mapping = fs_info->btree_inode->i_mapping;
1066 struct extent_state *cached_state = NULL;
1070 atomic_inc(&BTRFS_I(fs_info->btree_inode)->sync_writers);
1071 while (!find_first_extent_bit(dirty_pages, start, &start, &end,
1072 mark, &cached_state)) {
1073 bool wait_writeback = false;
1075 err = convert_extent_bit(dirty_pages, start, end,
1077 mark, &cached_state);
1079 * convert_extent_bit can return -ENOMEM, which is most of the
1080 * time a temporary error. So when it happens, ignore the error
1081 * and wait for writeback of this range to finish - because we
1082 * failed to set the bit EXTENT_NEED_WAIT for the range, a call
1083 * to __btrfs_wait_marked_extents() would not know that
1084 * writeback for this range started and therefore wouldn't
1085 * wait for it to finish - we don't want to commit a
1086 * superblock that points to btree nodes/leafs for which
1087 * writeback hasn't finished yet (and without errors).
1088 * We cleanup any entries left in the io tree when committing
1089 * the transaction (through extent_io_tree_release()).
1091 if (err == -ENOMEM) {
1093 wait_writeback = true;
1096 err = filemap_fdatawrite_range(mapping, start, end);
1099 else if (wait_writeback)
1100 werr = filemap_fdatawait_range(mapping, start, end);
1101 free_extent_state(cached_state);
1102 cached_state = NULL;
1106 atomic_dec(&BTRFS_I(fs_info->btree_inode)->sync_writers);
1111 * when btree blocks are allocated, they have some corresponding bits set for
1112 * them in one of two extent_io trees. This is used to make sure all of
1113 * those extents are on disk for transaction or log commit. We wait
1114 * on all the pages and clear them from the dirty pages state tree
1116 static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
1117 struct extent_io_tree *dirty_pages)
1121 struct address_space *mapping = fs_info->btree_inode->i_mapping;
1122 struct extent_state *cached_state = NULL;
1126 while (!find_first_extent_bit(dirty_pages, start, &start, &end,
1127 EXTENT_NEED_WAIT, &cached_state)) {
1129 * Ignore -ENOMEM errors returned by clear_extent_bit().
1130 * When committing the transaction, we'll remove any entries
1131 * left in the io tree. For a log commit, we don't remove them
1132 * after committing the log because the tree can be accessed
1133 * concurrently - we do it only at transaction commit time when
1134 * it's safe to do it (through extent_io_tree_release()).
1136 err = clear_extent_bit(dirty_pages, start, end,
1137 EXTENT_NEED_WAIT, 0, 0, &cached_state);
1141 err = filemap_fdatawait_range(mapping, start, end);
1144 free_extent_state(cached_state);
1145 cached_state = NULL;
1154 static int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
1155 struct extent_io_tree *dirty_pages)
1157 bool errors = false;
1160 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1161 if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1169 int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
1171 struct btrfs_fs_info *fs_info = log_root->fs_info;
1172 struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
1173 bool errors = false;
1176 ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
1178 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1179 if ((mark & EXTENT_DIRTY) &&
1180 test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1183 if ((mark & EXTENT_NEW) &&
1184 test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1193 * When btree blocks are allocated the corresponding extents are marked dirty.
1194 * This function ensures such extents are persisted on disk for transaction or
1197 * @trans: transaction whose dirty pages we'd like to write
1199 static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1203 struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
1204 struct btrfs_fs_info *fs_info = trans->fs_info;
1205 struct blk_plug plug;
1207 blk_start_plug(&plug);
1208 ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1209 blk_finish_plug(&plug);
1210 ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1212 extent_io_tree_release(&trans->transaction->dirty_pages);
1223 * this is used to update the root pointer in the tree of tree roots.
1225 * But, in the case of the extent allocation tree, updating the root
1226 * pointer may allocate blocks which may change the root of the extent
1229 * So, this loops and repeats and makes sure the cowonly root didn't
1230 * change while the root pointer was being updated in the metadata.
1232 static int update_cowonly_root(struct btrfs_trans_handle *trans,
1233 struct btrfs_root *root)
1236 u64 old_root_bytenr;
1238 struct btrfs_fs_info *fs_info = root->fs_info;
1239 struct btrfs_root *tree_root = fs_info->tree_root;
1241 old_root_used = btrfs_root_used(&root->root_item);
1244 old_root_bytenr = btrfs_root_bytenr(&root->root_item);
1245 if (old_root_bytenr == root->node->start &&
1246 old_root_used == btrfs_root_used(&root->root_item))
1249 btrfs_set_root_node(&root->root_item, root->node);
1250 ret = btrfs_update_root(trans, tree_root,
1256 old_root_used = btrfs_root_used(&root->root_item);
1263 * update all the cowonly tree roots on disk
1265 * The error handling in this function may not be obvious. Any of the
1266 * failures will cause the file system to go offline. We still need
1267 * to clean up the delayed refs.
1269 static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
1271 struct btrfs_fs_info *fs_info = trans->fs_info;
1272 struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
1273 struct list_head *io_bgs = &trans->transaction->io_bgs;
1274 struct list_head *next;
1275 struct extent_buffer *eb;
1279 * At this point no one can be using this transaction to modify any tree
1280 * and no one can start another transaction to modify any tree either.
1282 ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1284 eb = btrfs_lock_root_node(fs_info->tree_root);
1285 ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
1286 0, &eb, BTRFS_NESTING_COW);
1287 btrfs_tree_unlock(eb);
1288 free_extent_buffer(eb);
1293 ret = btrfs_run_dev_stats(trans);
1296 ret = btrfs_run_dev_replace(trans);
1299 ret = btrfs_run_qgroups(trans);
1303 ret = btrfs_setup_space_cache(trans);
1308 while (!list_empty(&fs_info->dirty_cowonly_roots)) {
1309 struct btrfs_root *root;
1310 next = fs_info->dirty_cowonly_roots.next;
1311 list_del_init(next);
1312 root = list_entry(next, struct btrfs_root, dirty_list);
1313 clear_bit(BTRFS_ROOT_DIRTY, &root->state);
1315 list_add_tail(&root->dirty_list,
1316 &trans->transaction->switch_commits);
1317 ret = update_cowonly_root(trans, root);
1322 /* Now flush any delayed refs generated by updating all of the roots */
1323 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1327 while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
1328 ret = btrfs_write_dirty_block_groups(trans);
1333 * We're writing the dirty block groups, which could generate
1334 * delayed refs, which could generate more dirty block groups,
1335 * so we want to keep this flushing in this loop to make sure
1336 * everything gets run.
1338 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1343 if (!list_empty(&fs_info->dirty_cowonly_roots))
1346 /* Update dev-replace pointer once everything is committed */
1347 fs_info->dev_replace.committed_cursor_left =
1348 fs_info->dev_replace.cursor_left_last_write_of_item;
1354 * If we had a pending drop we need to see if there are any others left in our
1355 * dead roots list, and if not clear our bit and wake any waiters.
1357 void btrfs_maybe_wake_unfinished_drop(struct btrfs_fs_info *fs_info)
1360 * We put the drop in progress roots at the front of the list, so if the
1361 * first entry doesn't have UNFINISHED_DROP set we can wake everybody
1364 spin_lock(&fs_info->trans_lock);
1365 if (!list_empty(&fs_info->dead_roots)) {
1366 struct btrfs_root *root = list_first_entry(&fs_info->dead_roots,
1369 if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state)) {
1370 spin_unlock(&fs_info->trans_lock);
1374 spin_unlock(&fs_info->trans_lock);
1376 btrfs_wake_unfinished_drop(fs_info);
1380 * dead roots are old snapshots that need to be deleted. This allocates
1381 * a dirty root struct and adds it into the list of dead roots that need to
1384 void btrfs_add_dead_root(struct btrfs_root *root)
1386 struct btrfs_fs_info *fs_info = root->fs_info;
1388 spin_lock(&fs_info->trans_lock);
1389 if (list_empty(&root->root_list)) {
1390 btrfs_grab_root(root);
1392 /* We want to process the partially complete drops first. */
1393 if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state))
1394 list_add(&root->root_list, &fs_info->dead_roots);
1396 list_add_tail(&root->root_list, &fs_info->dead_roots);
1398 spin_unlock(&fs_info->trans_lock);
1402 * Update each subvolume root and its relocation root, if it exists, in the tree
1403 * of tree roots. Also free log roots if they exist.
1405 static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
1407 struct btrfs_fs_info *fs_info = trans->fs_info;
1408 struct btrfs_root *gang[8];
1413 * At this point no one can be using this transaction to modify any tree
1414 * and no one can start another transaction to modify any tree either.
1416 ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1418 spin_lock(&fs_info->fs_roots_radix_lock);
1420 ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
1423 BTRFS_ROOT_TRANS_TAG);
1426 for (i = 0; i < ret; i++) {
1427 struct btrfs_root *root = gang[i];
1431 * At this point we can neither have tasks logging inodes
1432 * from a root nor trying to commit a log tree.
1434 ASSERT(atomic_read(&root->log_writers) == 0);
1435 ASSERT(atomic_read(&root->log_commit[0]) == 0);
1436 ASSERT(atomic_read(&root->log_commit[1]) == 0);
1438 radix_tree_tag_clear(&fs_info->fs_roots_radix,
1439 (unsigned long)root->root_key.objectid,
1440 BTRFS_ROOT_TRANS_TAG);
1441 spin_unlock(&fs_info->fs_roots_radix_lock);
1443 btrfs_free_log(trans, root);
1444 ret2 = btrfs_update_reloc_root(trans, root);
1448 /* see comments in should_cow_block() */
1449 clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1450 smp_mb__after_atomic();
1452 if (root->commit_root != root->node) {
1453 list_add_tail(&root->dirty_list,
1454 &trans->transaction->switch_commits);
1455 btrfs_set_root_node(&root->root_item,
1459 ret2 = btrfs_update_root(trans, fs_info->tree_root,
1464 spin_lock(&fs_info->fs_roots_radix_lock);
1465 btrfs_qgroup_free_meta_all_pertrans(root);
1468 spin_unlock(&fs_info->fs_roots_radix_lock);
1473 * defrag a given btree.
1474 * Every leaf in the btree is read and defragged.
1476 int btrfs_defrag_root(struct btrfs_root *root)
1478 struct btrfs_fs_info *info = root->fs_info;
1479 struct btrfs_trans_handle *trans;
1482 if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
1486 trans = btrfs_start_transaction(root, 0);
1487 if (IS_ERR(trans)) {
1488 ret = PTR_ERR(trans);
1492 ret = btrfs_defrag_leaves(trans, root);
1494 btrfs_end_transaction(trans);
1495 btrfs_btree_balance_dirty(info);
1498 if (btrfs_fs_closing(info) || ret != -EAGAIN)
1501 if (btrfs_defrag_cancelled(info)) {
1502 btrfs_debug(info, "defrag_root cancelled");
1507 clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
1512 * Do all special snapshot related qgroup dirty hack.
1514 * Will do all needed qgroup inherit and dirty hack like switch commit
1515 * roots inside one transaction and write all btree into disk, to make
1518 static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
1519 struct btrfs_root *src,
1520 struct btrfs_root *parent,
1521 struct btrfs_qgroup_inherit *inherit,
1524 struct btrfs_fs_info *fs_info = src->fs_info;
1528 * Save some performance in the case that qgroups are not
1529 * enabled. If this check races with the ioctl, rescan will
1532 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1536 * Ensure dirty @src will be committed. Or, after coming
1537 * commit_fs_roots() and switch_commit_roots(), any dirty but not
1538 * recorded root will never be updated again, causing an outdated root
1541 ret = record_root_in_trans(trans, src, 1);
1546 * btrfs_qgroup_inherit relies on a consistent view of the usage for the
1547 * src root, so we must run the delayed refs here.
1549 * However this isn't particularly fool proof, because there's no
1550 * synchronization keeping us from changing the tree after this point
1551 * before we do the qgroup_inherit, or even from making changes while
1552 * we're doing the qgroup_inherit. But that's a problem for the future,
1553 * for now flush the delayed refs to narrow the race window where the
1554 * qgroup counters could end up wrong.
1556 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1558 btrfs_abort_transaction(trans, ret);
1562 ret = commit_fs_roots(trans);
1565 ret = btrfs_qgroup_account_extents(trans);
1569 /* Now qgroup are all updated, we can inherit it to new qgroups */
1570 ret = btrfs_qgroup_inherit(trans, src->root_key.objectid, dst_objectid,
1576 * Now we do a simplified commit transaction, which will:
1577 * 1) commit all subvolume and extent tree
1578 * To ensure all subvolume and extent tree have a valid
1579 * commit_root to accounting later insert_dir_item()
1580 * 2) write all btree blocks onto disk
1581 * This is to make sure later btree modification will be cowed
1582 * Or commit_root can be populated and cause wrong qgroup numbers
1583 * In this simplified commit, we don't really care about other trees
1584 * like chunk and root tree, as they won't affect qgroup.
1585 * And we don't write super to avoid half committed status.
1587 ret = commit_cowonly_roots(trans);
1590 switch_commit_roots(trans);
1591 ret = btrfs_write_and_wait_transaction(trans);
1593 btrfs_handle_fs_error(fs_info, ret,
1594 "Error while writing out transaction for qgroup");
1598 * Force parent root to be updated, as we recorded it before so its
1599 * last_trans == cur_transid.
1600 * Or it won't be committed again onto disk after later
1604 ret = record_root_in_trans(trans, parent, 1);
1609 * new snapshots need to be created at a very specific time in the
1610 * transaction commit. This does the actual creation.
1613 * If the error which may affect the commitment of the current transaction
1614 * happens, we should return the error number. If the error which just affect
1615 * the creation of the pending snapshots, just return 0.
1617 static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
1618 struct btrfs_pending_snapshot *pending)
1621 struct btrfs_fs_info *fs_info = trans->fs_info;
1622 struct btrfs_key key;
1623 struct btrfs_root_item *new_root_item;
1624 struct btrfs_root *tree_root = fs_info->tree_root;
1625 struct btrfs_root *root = pending->root;
1626 struct btrfs_root *parent_root;
1627 struct btrfs_block_rsv *rsv;
1628 struct inode *parent_inode;
1629 struct btrfs_path *path;
1630 struct btrfs_dir_item *dir_item;
1631 struct dentry *dentry;
1632 struct extent_buffer *tmp;
1633 struct extent_buffer *old;
1634 struct timespec64 cur_time;
1641 ASSERT(pending->path);
1642 path = pending->path;
1644 ASSERT(pending->root_item);
1645 new_root_item = pending->root_item;
1647 pending->error = btrfs_get_free_objectid(tree_root, &objectid);
1649 goto no_free_objectid;
1652 * Make qgroup to skip current new snapshot's qgroupid, as it is
1653 * accounted by later btrfs_qgroup_inherit().
1655 btrfs_set_skip_qgroup(trans, objectid);
1657 btrfs_reloc_pre_snapshot(pending, &to_reserve);
1659 if (to_reserve > 0) {
1660 pending->error = btrfs_block_rsv_add(fs_info,
1661 &pending->block_rsv,
1663 BTRFS_RESERVE_NO_FLUSH);
1665 goto clear_skip_qgroup;
1668 key.objectid = objectid;
1669 key.offset = (u64)-1;
1670 key.type = BTRFS_ROOT_ITEM_KEY;
1672 rsv = trans->block_rsv;
1673 trans->block_rsv = &pending->block_rsv;
1674 trans->bytes_reserved = trans->block_rsv->reserved;
1675 trace_btrfs_space_reservation(fs_info, "transaction",
1677 trans->bytes_reserved, 1);
1678 dentry = pending->dentry;
1679 parent_inode = pending->dir;
1680 parent_root = BTRFS_I(parent_inode)->root;
1681 ret = record_root_in_trans(trans, parent_root, 0);
1684 cur_time = current_time(parent_inode);
1687 * insert the directory item
1689 ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
1690 BUG_ON(ret); /* -ENOMEM */
1692 /* check if there is a file/dir which has the same name. */
1693 dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
1694 btrfs_ino(BTRFS_I(parent_inode)),
1695 dentry->d_name.name,
1696 dentry->d_name.len, 0);
1697 if (dir_item != NULL && !IS_ERR(dir_item)) {
1698 pending->error = -EEXIST;
1699 goto dir_item_existed;
1700 } else if (IS_ERR(dir_item)) {
1701 ret = PTR_ERR(dir_item);
1702 btrfs_abort_transaction(trans, ret);
1705 btrfs_release_path(path);
1708 * pull in the delayed directory update
1709 * and the delayed inode item
1710 * otherwise we corrupt the FS during
1713 ret = btrfs_run_delayed_items(trans);
1714 if (ret) { /* Transaction aborted */
1715 btrfs_abort_transaction(trans, ret);
1719 ret = record_root_in_trans(trans, root, 0);
1721 btrfs_abort_transaction(trans, ret);
1724 btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
1725 memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
1726 btrfs_check_and_init_root_item(new_root_item);
1728 root_flags = btrfs_root_flags(new_root_item);
1729 if (pending->readonly)
1730 root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1732 root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1733 btrfs_set_root_flags(new_root_item, root_flags);
1735 btrfs_set_root_generation_v2(new_root_item,
1737 generate_random_guid(new_root_item->uuid);
1738 memcpy(new_root_item->parent_uuid, root->root_item.uuid,
1740 if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
1741 memset(new_root_item->received_uuid, 0,
1742 sizeof(new_root_item->received_uuid));
1743 memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
1744 memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
1745 btrfs_set_root_stransid(new_root_item, 0);
1746 btrfs_set_root_rtransid(new_root_item, 0);
1748 btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
1749 btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
1750 btrfs_set_root_otransid(new_root_item, trans->transid);
1752 old = btrfs_lock_root_node(root);
1753 ret = btrfs_cow_block(trans, root, old, NULL, 0, &old,
1756 btrfs_tree_unlock(old);
1757 free_extent_buffer(old);
1758 btrfs_abort_transaction(trans, ret);
1762 ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
1763 /* clean up in any case */
1764 btrfs_tree_unlock(old);
1765 free_extent_buffer(old);
1767 btrfs_abort_transaction(trans, ret);
1770 /* see comments in should_cow_block() */
1771 set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1774 btrfs_set_root_node(new_root_item, tmp);
1775 /* record when the snapshot was created in key.offset */
1776 key.offset = trans->transid;
1777 ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1778 btrfs_tree_unlock(tmp);
1779 free_extent_buffer(tmp);
1781 btrfs_abort_transaction(trans, ret);
1786 * insert root back/forward references
1788 ret = btrfs_add_root_ref(trans, objectid,
1789 parent_root->root_key.objectid,
1790 btrfs_ino(BTRFS_I(parent_inode)), index,
1791 dentry->d_name.name, dentry->d_name.len);
1793 btrfs_abort_transaction(trans, ret);
1797 key.offset = (u64)-1;
1798 pending->snap = btrfs_get_new_fs_root(fs_info, objectid, pending->anon_dev);
1799 if (IS_ERR(pending->snap)) {
1800 ret = PTR_ERR(pending->snap);
1801 pending->snap = NULL;
1802 btrfs_abort_transaction(trans, ret);
1806 ret = btrfs_reloc_post_snapshot(trans, pending);
1808 btrfs_abort_transaction(trans, ret);
1813 * Do special qgroup accounting for snapshot, as we do some qgroup
1814 * snapshot hack to do fast snapshot.
1815 * To co-operate with that hack, we do hack again.
1816 * Or snapshot will be greatly slowed down by a subtree qgroup rescan
1818 ret = qgroup_account_snapshot(trans, root, parent_root,
1819 pending->inherit, objectid);
1823 ret = btrfs_insert_dir_item(trans, dentry->d_name.name,
1824 dentry->d_name.len, BTRFS_I(parent_inode),
1825 &key, BTRFS_FT_DIR, index);
1826 /* We have check then name at the beginning, so it is impossible. */
1827 BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
1829 btrfs_abort_transaction(trans, ret);
1833 btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
1834 dentry->d_name.len * 2);
1835 parent_inode->i_mtime = current_time(parent_inode);
1836 parent_inode->i_ctime = parent_inode->i_mtime;
1837 ret = btrfs_update_inode_fallback(trans, parent_root, BTRFS_I(parent_inode));
1839 btrfs_abort_transaction(trans, ret);
1842 ret = btrfs_uuid_tree_add(trans, new_root_item->uuid,
1843 BTRFS_UUID_KEY_SUBVOL,
1846 btrfs_abort_transaction(trans, ret);
1849 if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1850 ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1851 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1853 if (ret && ret != -EEXIST) {
1854 btrfs_abort_transaction(trans, ret);
1860 pending->error = ret;
1862 trans->block_rsv = rsv;
1863 trans->bytes_reserved = 0;
1865 btrfs_clear_skip_qgroup(trans);
1867 kfree(new_root_item);
1868 pending->root_item = NULL;
1869 btrfs_free_path(path);
1870 pending->path = NULL;
1876 * create all the snapshots we've scheduled for creation
1878 static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
1880 struct btrfs_pending_snapshot *pending, *next;
1881 struct list_head *head = &trans->transaction->pending_snapshots;
1884 list_for_each_entry_safe(pending, next, head, list) {
1885 list_del(&pending->list);
1886 ret = create_pending_snapshot(trans, pending);
1893 static void update_super_roots(struct btrfs_fs_info *fs_info)
1895 struct btrfs_root_item *root_item;
1896 struct btrfs_super_block *super;
1898 super = fs_info->super_copy;
1900 root_item = &fs_info->chunk_root->root_item;
1901 super->chunk_root = root_item->bytenr;
1902 super->chunk_root_generation = root_item->generation;
1903 super->chunk_root_level = root_item->level;
1905 root_item = &fs_info->tree_root->root_item;
1906 super->root = root_item->bytenr;
1907 super->generation = root_item->generation;
1908 super->root_level = root_item->level;
1909 if (btrfs_test_opt(fs_info, SPACE_CACHE))
1910 super->cache_generation = root_item->generation;
1911 else if (test_bit(BTRFS_FS_CLEANUP_SPACE_CACHE_V1, &fs_info->flags))
1912 super->cache_generation = 0;
1913 if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1914 super->uuid_tree_generation = root_item->generation;
1916 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
1917 root_item = &fs_info->block_group_root->root_item;
1919 super->block_group_root = root_item->bytenr;
1920 super->block_group_root_generation = root_item->generation;
1921 super->block_group_root_level = root_item->level;
1925 int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1927 struct btrfs_transaction *trans;
1930 spin_lock(&info->trans_lock);
1931 trans = info->running_transaction;
1933 ret = (trans->state >= TRANS_STATE_COMMIT_START);
1934 spin_unlock(&info->trans_lock);
1938 int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1940 struct btrfs_transaction *trans;
1943 spin_lock(&info->trans_lock);
1944 trans = info->running_transaction;
1946 ret = is_transaction_blocked(trans);
1947 spin_unlock(&info->trans_lock);
1951 void btrfs_commit_transaction_async(struct btrfs_trans_handle *trans)
1953 struct btrfs_fs_info *fs_info = trans->fs_info;
1954 struct btrfs_transaction *cur_trans;
1956 /* Kick the transaction kthread. */
1957 set_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
1958 wake_up_process(fs_info->transaction_kthread);
1960 /* take transaction reference */
1961 cur_trans = trans->transaction;
1962 refcount_inc(&cur_trans->use_count);
1964 btrfs_end_transaction(trans);
1967 * Wait for the current transaction commit to start and block
1968 * subsequent transaction joins
1970 wait_event(fs_info->transaction_blocked_wait,
1971 cur_trans->state >= TRANS_STATE_COMMIT_START ||
1972 TRANS_ABORTED(cur_trans));
1973 btrfs_put_transaction(cur_trans);
1976 static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
1978 struct btrfs_fs_info *fs_info = trans->fs_info;
1979 struct btrfs_transaction *cur_trans = trans->transaction;
1981 WARN_ON(refcount_read(&trans->use_count) > 1);
1983 btrfs_abort_transaction(trans, err);
1985 spin_lock(&fs_info->trans_lock);
1988 * If the transaction is removed from the list, it means this
1989 * transaction has been committed successfully, so it is impossible
1990 * to call the cleanup function.
1992 BUG_ON(list_empty(&cur_trans->list));
1994 if (cur_trans == fs_info->running_transaction) {
1995 cur_trans->state = TRANS_STATE_COMMIT_DOING;
1996 spin_unlock(&fs_info->trans_lock);
1997 wait_event(cur_trans->writer_wait,
1998 atomic_read(&cur_trans->num_writers) == 1);
2000 spin_lock(&fs_info->trans_lock);
2004 * Now that we know no one else is still using the transaction we can
2005 * remove the transaction from the list of transactions. This avoids
2006 * the transaction kthread from cleaning up the transaction while some
2007 * other task is still using it, which could result in a use-after-free
2008 * on things like log trees, as it forces the transaction kthread to
2009 * wait for this transaction to be cleaned up by us.
2011 list_del_init(&cur_trans->list);
2013 spin_unlock(&fs_info->trans_lock);
2015 btrfs_cleanup_one_transaction(trans->transaction, fs_info);
2017 spin_lock(&fs_info->trans_lock);
2018 if (cur_trans == fs_info->running_transaction)
2019 fs_info->running_transaction = NULL;
2020 spin_unlock(&fs_info->trans_lock);
2022 if (trans->type & __TRANS_FREEZABLE)
2023 sb_end_intwrite(fs_info->sb);
2024 btrfs_put_transaction(cur_trans);
2025 btrfs_put_transaction(cur_trans);
2027 trace_btrfs_transaction_commit(fs_info);
2029 if (current->journal_info == trans)
2030 current->journal_info = NULL;
2031 btrfs_scrub_cancel(fs_info);
2033 kmem_cache_free(btrfs_trans_handle_cachep, trans);
2037 * Release reserved delayed ref space of all pending block groups of the
2038 * transaction and remove them from the list
2040 static void btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle *trans)
2042 struct btrfs_fs_info *fs_info = trans->fs_info;
2043 struct btrfs_block_group *block_group, *tmp;
2045 list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
2046 btrfs_delayed_refs_rsv_release(fs_info, 1);
2047 list_del_init(&block_group->bg_list);
2051 static inline int btrfs_start_delalloc_flush(struct btrfs_fs_info *fs_info)
2054 * We use try_to_writeback_inodes_sb() here because if we used
2055 * btrfs_start_delalloc_roots we would deadlock with fs freeze.
2056 * Currently are holding the fs freeze lock, if we do an async flush
2057 * we'll do btrfs_join_transaction() and deadlock because we need to
2058 * wait for the fs freeze lock. Using the direct flushing we benefit
2059 * from already being in a transaction and our join_transaction doesn't
2060 * have to re-take the fs freeze lock.
2062 * Note that try_to_writeback_inodes_sb() will only trigger writeback
2063 * if it can read lock sb->s_umount. It will always be able to lock it,
2064 * except when the filesystem is being unmounted or being frozen, but in
2065 * those cases sync_filesystem() is called, which results in calling
2066 * writeback_inodes_sb() while holding a write lock on sb->s_umount.
2067 * Note that we don't call writeback_inodes_sb() directly, because it
2068 * will emit a warning if sb->s_umount is not locked.
2070 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2071 try_to_writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
2075 static inline void btrfs_wait_delalloc_flush(struct btrfs_fs_info *fs_info)
2077 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2078 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
2082 * Add a pending snapshot associated with the given transaction handle to the
2083 * respective handle. This must be called after the transaction commit started
2084 * and while holding fs_info->trans_lock.
2085 * This serves to guarantee a caller of btrfs_commit_transaction() that it can
2086 * safely free the pending snapshot pointer in case btrfs_commit_transaction()
2089 static void add_pending_snapshot(struct btrfs_trans_handle *trans)
2091 struct btrfs_transaction *cur_trans = trans->transaction;
2093 if (!trans->pending_snapshot)
2096 lockdep_assert_held(&trans->fs_info->trans_lock);
2097 ASSERT(cur_trans->state >= TRANS_STATE_COMMIT_START);
2099 list_add(&trans->pending_snapshot->list, &cur_trans->pending_snapshots);
2102 static void update_commit_stats(struct btrfs_fs_info *fs_info, ktime_t interval)
2104 fs_info->commit_stats.commit_count++;
2105 fs_info->commit_stats.last_commit_dur = interval;
2106 fs_info->commit_stats.max_commit_dur =
2107 max_t(u64, fs_info->commit_stats.max_commit_dur, interval);
2108 fs_info->commit_stats.total_commit_dur += interval;
2111 int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
2113 struct btrfs_fs_info *fs_info = trans->fs_info;
2114 struct btrfs_transaction *cur_trans = trans->transaction;
2115 struct btrfs_transaction *prev_trans = NULL;
2120 ASSERT(refcount_read(&trans->use_count) == 1);
2122 /* Stop the commit early if ->aborted is set */
2123 if (TRANS_ABORTED(cur_trans)) {
2124 ret = cur_trans->aborted;
2125 btrfs_end_transaction(trans);
2129 btrfs_trans_release_metadata(trans);
2130 trans->block_rsv = NULL;
2133 * We only want one transaction commit doing the flushing so we do not
2134 * waste a bunch of time on lock contention on the extent root node.
2136 if (!test_and_set_bit(BTRFS_DELAYED_REFS_FLUSHING,
2137 &cur_trans->delayed_refs.flags)) {
2139 * Make a pass through all the delayed refs we have so far.
2140 * Any running threads may add more while we are here.
2142 ret = btrfs_run_delayed_refs(trans, 0);
2144 btrfs_end_transaction(trans);
2149 btrfs_create_pending_block_groups(trans);
2151 if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
2154 /* this mutex is also taken before trying to set
2155 * block groups readonly. We need to make sure
2156 * that nobody has set a block group readonly
2157 * after a extents from that block group have been
2158 * allocated for cache files. btrfs_set_block_group_ro
2159 * will wait for the transaction to commit if it
2160 * finds BTRFS_TRANS_DIRTY_BG_RUN set.
2162 * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
2163 * only one process starts all the block group IO. It wouldn't
2164 * hurt to have more than one go through, but there's no
2165 * real advantage to it either.
2167 mutex_lock(&fs_info->ro_block_group_mutex);
2168 if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
2171 mutex_unlock(&fs_info->ro_block_group_mutex);
2174 ret = btrfs_start_dirty_block_groups(trans);
2176 btrfs_end_transaction(trans);
2182 spin_lock(&fs_info->trans_lock);
2183 if (cur_trans->state >= TRANS_STATE_COMMIT_START) {
2184 enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2186 add_pending_snapshot(trans);
2188 spin_unlock(&fs_info->trans_lock);
2189 refcount_inc(&cur_trans->use_count);
2191 if (trans->in_fsync)
2192 want_state = TRANS_STATE_SUPER_COMMITTED;
2193 ret = btrfs_end_transaction(trans);
2194 wait_for_commit(cur_trans, want_state);
2196 if (TRANS_ABORTED(cur_trans))
2197 ret = cur_trans->aborted;
2199 btrfs_put_transaction(cur_trans);
2204 cur_trans->state = TRANS_STATE_COMMIT_START;
2205 wake_up(&fs_info->transaction_blocked_wait);
2207 if (cur_trans->list.prev != &fs_info->trans_list) {
2208 enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2210 if (trans->in_fsync)
2211 want_state = TRANS_STATE_SUPER_COMMITTED;
2213 prev_trans = list_entry(cur_trans->list.prev,
2214 struct btrfs_transaction, list);
2215 if (prev_trans->state < want_state) {
2216 refcount_inc(&prev_trans->use_count);
2217 spin_unlock(&fs_info->trans_lock);
2219 wait_for_commit(prev_trans, want_state);
2221 ret = READ_ONCE(prev_trans->aborted);
2223 btrfs_put_transaction(prev_trans);
2225 goto cleanup_transaction;
2227 spin_unlock(&fs_info->trans_lock);
2230 spin_unlock(&fs_info->trans_lock);
2232 * The previous transaction was aborted and was already removed
2233 * from the list of transactions at fs_info->trans_list. So we
2234 * abort to prevent writing a new superblock that reflects a
2235 * corrupt state (pointing to trees with unwritten nodes/leafs).
2237 if (BTRFS_FS_ERROR(fs_info)) {
2239 goto cleanup_transaction;
2244 * Get the time spent on the work done by the commit thread and not
2245 * the time spent waiting on a previous commit
2247 start_time = ktime_get_ns();
2249 extwriter_counter_dec(cur_trans, trans->type);
2251 ret = btrfs_start_delalloc_flush(fs_info);
2253 goto cleanup_transaction;
2255 ret = btrfs_run_delayed_items(trans);
2257 goto cleanup_transaction;
2259 wait_event(cur_trans->writer_wait,
2260 extwriter_counter_read(cur_trans) == 0);
2262 /* some pending stuffs might be added after the previous flush. */
2263 ret = btrfs_run_delayed_items(trans);
2265 goto cleanup_transaction;
2267 btrfs_wait_delalloc_flush(fs_info);
2270 * Wait for all ordered extents started by a fast fsync that joined this
2271 * transaction. Otherwise if this transaction commits before the ordered
2272 * extents complete we lose logged data after a power failure.
2274 wait_event(cur_trans->pending_wait,
2275 atomic_read(&cur_trans->pending_ordered) == 0);
2277 btrfs_scrub_pause(fs_info);
2279 * Ok now we need to make sure to block out any other joins while we
2280 * commit the transaction. We could have started a join before setting
2281 * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2283 spin_lock(&fs_info->trans_lock);
2284 add_pending_snapshot(trans);
2285 cur_trans->state = TRANS_STATE_COMMIT_DOING;
2286 spin_unlock(&fs_info->trans_lock);
2287 wait_event(cur_trans->writer_wait,
2288 atomic_read(&cur_trans->num_writers) == 1);
2291 * We've started the commit, clear the flag in case we were triggered to
2292 * do an async commit but somebody else started before the transaction
2293 * kthread could do the work.
2295 clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
2297 if (TRANS_ABORTED(cur_trans)) {
2298 ret = cur_trans->aborted;
2299 goto scrub_continue;
2302 * the reloc mutex makes sure that we stop
2303 * the balancing code from coming in and moving
2304 * extents around in the middle of the commit
2306 mutex_lock(&fs_info->reloc_mutex);
2309 * We needn't worry about the delayed items because we will
2310 * deal with them in create_pending_snapshot(), which is the
2311 * core function of the snapshot creation.
2313 ret = create_pending_snapshots(trans);
2318 * We insert the dir indexes of the snapshots and update the inode
2319 * of the snapshots' parents after the snapshot creation, so there
2320 * are some delayed items which are not dealt with. Now deal with
2323 * We needn't worry that this operation will corrupt the snapshots,
2324 * because all the tree which are snapshoted will be forced to COW
2325 * the nodes and leaves.
2327 ret = btrfs_run_delayed_items(trans);
2331 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2336 * make sure none of the code above managed to slip in a
2339 btrfs_assert_delayed_root_empty(fs_info);
2341 WARN_ON(cur_trans != trans->transaction);
2343 ret = commit_fs_roots(trans);
2348 * Since the transaction is done, we can apply the pending changes
2349 * before the next transaction.
2351 btrfs_apply_pending_changes(fs_info);
2353 /* commit_fs_roots gets rid of all the tree log roots, it is now
2354 * safe to free the root of tree log roots
2356 btrfs_free_log_root_tree(trans, fs_info);
2359 * Since fs roots are all committed, we can get a quite accurate
2360 * new_roots. So let's do quota accounting.
2362 ret = btrfs_qgroup_account_extents(trans);
2366 ret = commit_cowonly_roots(trans);
2371 * The tasks which save the space cache and inode cache may also
2372 * update ->aborted, check it.
2374 if (TRANS_ABORTED(cur_trans)) {
2375 ret = cur_trans->aborted;
2379 cur_trans = fs_info->running_transaction;
2381 btrfs_set_root_node(&fs_info->tree_root->root_item,
2382 fs_info->tree_root->node);
2383 list_add_tail(&fs_info->tree_root->dirty_list,
2384 &cur_trans->switch_commits);
2386 btrfs_set_root_node(&fs_info->chunk_root->root_item,
2387 fs_info->chunk_root->node);
2388 list_add_tail(&fs_info->chunk_root->dirty_list,
2389 &cur_trans->switch_commits);
2391 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
2392 btrfs_set_root_node(&fs_info->block_group_root->root_item,
2393 fs_info->block_group_root->node);
2394 list_add_tail(&fs_info->block_group_root->dirty_list,
2395 &cur_trans->switch_commits);
2398 switch_commit_roots(trans);
2400 ASSERT(list_empty(&cur_trans->dirty_bgs));
2401 ASSERT(list_empty(&cur_trans->io_bgs));
2402 update_super_roots(fs_info);
2404 btrfs_set_super_log_root(fs_info->super_copy, 0);
2405 btrfs_set_super_log_root_level(fs_info->super_copy, 0);
2406 memcpy(fs_info->super_for_commit, fs_info->super_copy,
2407 sizeof(*fs_info->super_copy));
2409 btrfs_commit_device_sizes(cur_trans);
2411 clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2412 clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2414 btrfs_trans_release_chunk_metadata(trans);
2417 * Before changing the transaction state to TRANS_STATE_UNBLOCKED and
2418 * setting fs_info->running_transaction to NULL, lock tree_log_mutex to
2419 * make sure that before we commit our superblock, no other task can
2420 * start a new transaction and commit a log tree before we commit our
2421 * superblock. Anyone trying to commit a log tree locks this mutex before
2422 * writing its superblock.
2424 mutex_lock(&fs_info->tree_log_mutex);
2426 spin_lock(&fs_info->trans_lock);
2427 cur_trans->state = TRANS_STATE_UNBLOCKED;
2428 fs_info->running_transaction = NULL;
2429 spin_unlock(&fs_info->trans_lock);
2430 mutex_unlock(&fs_info->reloc_mutex);
2432 wake_up(&fs_info->transaction_wait);
2434 ret = btrfs_write_and_wait_transaction(trans);
2436 btrfs_handle_fs_error(fs_info, ret,
2437 "Error while writing out transaction");
2438 mutex_unlock(&fs_info->tree_log_mutex);
2439 goto scrub_continue;
2443 * At this point, we should have written all the tree blocks allocated
2444 * in this transaction. So it's now safe to free the redirtyied extent
2447 btrfs_free_redirty_list(cur_trans);
2449 ret = write_all_supers(fs_info, 0);
2451 * the super is written, we can safely allow the tree-loggers
2452 * to go about their business
2454 mutex_unlock(&fs_info->tree_log_mutex);
2456 goto scrub_continue;
2459 * We needn't acquire the lock here because there is no other task
2460 * which can change it.
2462 cur_trans->state = TRANS_STATE_SUPER_COMMITTED;
2463 wake_up(&cur_trans->commit_wait);
2465 btrfs_finish_extent_commit(trans);
2467 if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
2468 btrfs_clear_space_info_full(fs_info);
2470 fs_info->last_trans_committed = cur_trans->transid;
2472 * We needn't acquire the lock here because there is no other task
2473 * which can change it.
2475 cur_trans->state = TRANS_STATE_COMPLETED;
2476 wake_up(&cur_trans->commit_wait);
2478 spin_lock(&fs_info->trans_lock);
2479 list_del_init(&cur_trans->list);
2480 spin_unlock(&fs_info->trans_lock);
2482 btrfs_put_transaction(cur_trans);
2483 btrfs_put_transaction(cur_trans);
2485 if (trans->type & __TRANS_FREEZABLE)
2486 sb_end_intwrite(fs_info->sb);
2488 trace_btrfs_transaction_commit(fs_info);
2490 interval = ktime_get_ns() - start_time;
2492 btrfs_scrub_continue(fs_info);
2494 if (current->journal_info == trans)
2495 current->journal_info = NULL;
2497 kmem_cache_free(btrfs_trans_handle_cachep, trans);
2499 update_commit_stats(fs_info, interval);
2504 mutex_unlock(&fs_info->reloc_mutex);
2506 btrfs_scrub_continue(fs_info);
2507 cleanup_transaction:
2508 btrfs_trans_release_metadata(trans);
2509 btrfs_cleanup_pending_block_groups(trans);
2510 btrfs_trans_release_chunk_metadata(trans);
2511 trans->block_rsv = NULL;
2512 btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
2513 if (current->journal_info == trans)
2514 current->journal_info = NULL;
2515 cleanup_transaction(trans, ret);
2521 * return < 0 if error
2522 * 0 if there are no more dead_roots at the time of call
2523 * 1 there are more to be processed, call me again
2525 * The return value indicates there are certainly more snapshots to delete, but
2526 * if there comes a new one during processing, it may return 0. We don't mind,
2527 * because btrfs_commit_super will poke cleaner thread and it will process it a
2528 * few seconds later.
2530 int btrfs_clean_one_deleted_snapshot(struct btrfs_fs_info *fs_info)
2532 struct btrfs_root *root;
2535 spin_lock(&fs_info->trans_lock);
2536 if (list_empty(&fs_info->dead_roots)) {
2537 spin_unlock(&fs_info->trans_lock);
2540 root = list_first_entry(&fs_info->dead_roots,
2541 struct btrfs_root, root_list);
2542 list_del_init(&root->root_list);
2543 spin_unlock(&fs_info->trans_lock);
2545 btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
2547 btrfs_kill_all_delayed_nodes(root);
2549 if (btrfs_header_backref_rev(root->node) <
2550 BTRFS_MIXED_BACKREF_REV)
2551 ret = btrfs_drop_snapshot(root, 0, 0);
2553 ret = btrfs_drop_snapshot(root, 1, 0);
2555 btrfs_put_root(root);
2556 return (ret < 0) ? 0 : 1;
2559 void btrfs_apply_pending_changes(struct btrfs_fs_info *fs_info)
2564 prev = xchg(&fs_info->pending_changes, 0);
2568 bit = 1 << BTRFS_PENDING_COMMIT;
2570 btrfs_debug(fs_info, "pending commit done");
2575 "unknown pending changes left 0x%lx, ignoring", prev);