1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
7 #include <linux/slab.h>
8 #include <linux/sched.h>
9 #include <linux/writeback.h>
10 #include <linux/pagemap.h>
11 #include <linux/blkdev.h>
12 #include <linux/uuid.h>
13 #include <linux/timekeeping.h>
17 #include "transaction.h"
21 #include "dev-replace.h"
23 #include "block-group.h"
24 #include "space-info.h"
27 #define BTRFS_ROOT_TRANS_TAG 0
30 * Transaction states and transitions
32 * No running transaction (fs tree blocks are not modified)
35 * | Call start_transaction() variants. Except btrfs_join_transaction_nostart().
37 * Transaction N [[TRANS_STATE_RUNNING]]
39 * | New trans handles can be attached to transaction N by calling all
40 * | start_transaction() variants.
43 * | Call btrfs_commit_transaction() on any trans handle attached to
46 * Transaction N [[TRANS_STATE_COMMIT_START]]
48 * | Will wait for previous running transaction to completely finish if there
51 * | Then one of the following happes:
52 * | - Wait for all other trans handle holders to release.
53 * | The btrfs_commit_transaction() caller will do the commit work.
54 * | - Wait for current transaction to be committed by others.
55 * | Other btrfs_commit_transaction() caller will do the commit work.
57 * | At this stage, only btrfs_join_transaction*() variants can attach
58 * | to this running transaction.
59 * | All other variants will wait for current one to finish and attach to
63 * | Caller is chosen to commit transaction N, and all other trans handle
64 * | haven been released.
66 * Transaction N [[TRANS_STATE_COMMIT_DOING]]
68 * | The heavy lifting transaction work is started.
69 * | From running delayed refs (modifying extent tree) to creating pending
70 * | snapshots, running qgroups.
71 * | In short, modify supporting trees to reflect modifications of subvolume
74 * | At this stage, all start_transaction() calls will wait for this
75 * | transaction to finish and attach to transaction N+1.
78 * | Until all supporting trees are updated.
80 * Transaction N [[TRANS_STATE_UNBLOCKED]]
82 * | All needed trees are modified, thus we only [[TRANS_STATE_RUNNING]]
83 * | need to write them back to disk and update |
86 * | At this stage, new transaction is allowed to |
88 * | All new start_transaction() calls will be |
89 * | attached to transid N+1. |
92 * | Until all tree blocks are super blocks are |
93 * | written to block devices |
95 * Transaction N [[TRANS_STATE_COMPLETED]] V
96 * All tree blocks and super blocks are written. Transaction N+1
97 * This transaction is finished and all its [[TRANS_STATE_COMMIT_START]]
98 * data structures will be cleaned up. | Life goes on
100 static const unsigned int btrfs_blocked_trans_types[TRANS_STATE_MAX] = {
101 [TRANS_STATE_RUNNING] = 0U,
102 [TRANS_STATE_COMMIT_START] = (__TRANS_START | __TRANS_ATTACH),
103 [TRANS_STATE_COMMIT_DOING] = (__TRANS_START |
106 __TRANS_JOIN_NOSTART),
107 [TRANS_STATE_UNBLOCKED] = (__TRANS_START |
110 __TRANS_JOIN_NOLOCK |
111 __TRANS_JOIN_NOSTART),
112 [TRANS_STATE_SUPER_COMMITTED] = (__TRANS_START |
115 __TRANS_JOIN_NOLOCK |
116 __TRANS_JOIN_NOSTART),
117 [TRANS_STATE_COMPLETED] = (__TRANS_START |
120 __TRANS_JOIN_NOLOCK |
121 __TRANS_JOIN_NOSTART),
124 void btrfs_put_transaction(struct btrfs_transaction *transaction)
126 WARN_ON(refcount_read(&transaction->use_count) == 0);
127 if (refcount_dec_and_test(&transaction->use_count)) {
128 BUG_ON(!list_empty(&transaction->list));
129 WARN_ON(!RB_EMPTY_ROOT(
130 &transaction->delayed_refs.href_root.rb_root));
131 WARN_ON(!RB_EMPTY_ROOT(
132 &transaction->delayed_refs.dirty_extent_root));
133 if (transaction->delayed_refs.pending_csums)
134 btrfs_err(transaction->fs_info,
135 "pending csums is %llu",
136 transaction->delayed_refs.pending_csums);
138 * If any block groups are found in ->deleted_bgs then it's
139 * because the transaction was aborted and a commit did not
140 * happen (things failed before writing the new superblock
141 * and calling btrfs_finish_extent_commit()), so we can not
142 * discard the physical locations of the block groups.
144 while (!list_empty(&transaction->deleted_bgs)) {
145 struct btrfs_block_group *cache;
147 cache = list_first_entry(&transaction->deleted_bgs,
148 struct btrfs_block_group,
150 list_del_init(&cache->bg_list);
151 btrfs_unfreeze_block_group(cache);
152 btrfs_put_block_group(cache);
154 WARN_ON(!list_empty(&transaction->dev_update_list));
159 static noinline void switch_commit_roots(struct btrfs_trans_handle *trans)
161 struct btrfs_transaction *cur_trans = trans->transaction;
162 struct btrfs_fs_info *fs_info = trans->fs_info;
163 struct btrfs_root *root, *tmp;
166 * At this point no one can be using this transaction to modify any tree
167 * and no one can start another transaction to modify any tree either.
169 ASSERT(cur_trans->state == TRANS_STATE_COMMIT_DOING);
171 down_write(&fs_info->commit_root_sem);
173 if (test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
174 fs_info->last_reloc_trans = trans->transid;
176 list_for_each_entry_safe(root, tmp, &cur_trans->switch_commits,
178 list_del_init(&root->dirty_list);
179 free_extent_buffer(root->commit_root);
180 root->commit_root = btrfs_root_node(root);
181 extent_io_tree_release(&root->dirty_log_pages);
182 btrfs_qgroup_clean_swapped_blocks(root);
185 /* We can free old roots now. */
186 spin_lock(&cur_trans->dropped_roots_lock);
187 while (!list_empty(&cur_trans->dropped_roots)) {
188 root = list_first_entry(&cur_trans->dropped_roots,
189 struct btrfs_root, root_list);
190 list_del_init(&root->root_list);
191 spin_unlock(&cur_trans->dropped_roots_lock);
192 btrfs_free_log(trans, root);
193 btrfs_drop_and_free_fs_root(fs_info, root);
194 spin_lock(&cur_trans->dropped_roots_lock);
196 spin_unlock(&cur_trans->dropped_roots_lock);
198 up_write(&fs_info->commit_root_sem);
201 static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
204 if (type & TRANS_EXTWRITERS)
205 atomic_inc(&trans->num_extwriters);
208 static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
211 if (type & TRANS_EXTWRITERS)
212 atomic_dec(&trans->num_extwriters);
215 static inline void extwriter_counter_init(struct btrfs_transaction *trans,
218 atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
221 static inline int extwriter_counter_read(struct btrfs_transaction *trans)
223 return atomic_read(&trans->num_extwriters);
227 * To be called after doing the chunk btree updates right after allocating a new
228 * chunk (after btrfs_chunk_alloc_add_chunk_item() is called), when removing a
229 * chunk after all chunk btree updates and after finishing the second phase of
230 * chunk allocation (btrfs_create_pending_block_groups()) in case some block
231 * group had its chunk item insertion delayed to the second phase.
233 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
235 struct btrfs_fs_info *fs_info = trans->fs_info;
237 if (!trans->chunk_bytes_reserved)
240 btrfs_block_rsv_release(fs_info, &fs_info->chunk_block_rsv,
241 trans->chunk_bytes_reserved, NULL);
242 trans->chunk_bytes_reserved = 0;
246 * either allocate a new transaction or hop into the existing one
248 static noinline int join_transaction(struct btrfs_fs_info *fs_info,
251 struct btrfs_transaction *cur_trans;
253 spin_lock(&fs_info->trans_lock);
255 /* The file system has been taken offline. No new transactions. */
256 if (BTRFS_FS_ERROR(fs_info)) {
257 spin_unlock(&fs_info->trans_lock);
261 cur_trans = fs_info->running_transaction;
263 if (TRANS_ABORTED(cur_trans)) {
264 spin_unlock(&fs_info->trans_lock);
265 return cur_trans->aborted;
267 if (btrfs_blocked_trans_types[cur_trans->state] & type) {
268 spin_unlock(&fs_info->trans_lock);
271 refcount_inc(&cur_trans->use_count);
272 atomic_inc(&cur_trans->num_writers);
273 extwriter_counter_inc(cur_trans, type);
274 spin_unlock(&fs_info->trans_lock);
275 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_writers);
276 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_extwriters);
279 spin_unlock(&fs_info->trans_lock);
282 * If we are ATTACH, we just want to catch the current transaction,
283 * and commit it. If there is no transaction, just return ENOENT.
285 if (type == TRANS_ATTACH)
289 * JOIN_NOLOCK only happens during the transaction commit, so
290 * it is impossible that ->running_transaction is NULL
292 BUG_ON(type == TRANS_JOIN_NOLOCK);
294 cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
298 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_writers);
299 btrfs_lockdep_acquire(fs_info, btrfs_trans_num_extwriters);
301 spin_lock(&fs_info->trans_lock);
302 if (fs_info->running_transaction) {
304 * someone started a transaction after we unlocked. Make sure
305 * to redo the checks above
307 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
308 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
311 } else if (BTRFS_FS_ERROR(fs_info)) {
312 spin_unlock(&fs_info->trans_lock);
313 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
314 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
319 cur_trans->fs_info = fs_info;
320 atomic_set(&cur_trans->pending_ordered, 0);
321 init_waitqueue_head(&cur_trans->pending_wait);
322 atomic_set(&cur_trans->num_writers, 1);
323 extwriter_counter_init(cur_trans, type);
324 init_waitqueue_head(&cur_trans->writer_wait);
325 init_waitqueue_head(&cur_trans->commit_wait);
326 cur_trans->state = TRANS_STATE_RUNNING;
328 * One for this trans handle, one so it will live on until we
329 * commit the transaction.
331 refcount_set(&cur_trans->use_count, 2);
332 cur_trans->flags = 0;
333 cur_trans->start_time = ktime_get_seconds();
335 memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
337 cur_trans->delayed_refs.href_root = RB_ROOT_CACHED;
338 cur_trans->delayed_refs.dirty_extent_root = RB_ROOT;
339 atomic_set(&cur_trans->delayed_refs.num_entries, 0);
342 * although the tree mod log is per file system and not per transaction,
343 * the log must never go across transaction boundaries.
346 if (!list_empty(&fs_info->tree_mod_seq_list))
347 WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
348 if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
349 WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
350 atomic64_set(&fs_info->tree_mod_seq, 0);
352 spin_lock_init(&cur_trans->delayed_refs.lock);
354 INIT_LIST_HEAD(&cur_trans->pending_snapshots);
355 INIT_LIST_HEAD(&cur_trans->dev_update_list);
356 INIT_LIST_HEAD(&cur_trans->switch_commits);
357 INIT_LIST_HEAD(&cur_trans->dirty_bgs);
358 INIT_LIST_HEAD(&cur_trans->io_bgs);
359 INIT_LIST_HEAD(&cur_trans->dropped_roots);
360 mutex_init(&cur_trans->cache_write_mutex);
361 spin_lock_init(&cur_trans->dirty_bgs_lock);
362 INIT_LIST_HEAD(&cur_trans->deleted_bgs);
363 spin_lock_init(&cur_trans->dropped_roots_lock);
364 INIT_LIST_HEAD(&cur_trans->releasing_ebs);
365 spin_lock_init(&cur_trans->releasing_ebs_lock);
366 list_add_tail(&cur_trans->list, &fs_info->trans_list);
367 extent_io_tree_init(fs_info, &cur_trans->dirty_pages,
368 IO_TREE_TRANS_DIRTY_PAGES, NULL);
369 extent_io_tree_init(fs_info, &cur_trans->pinned_extents,
370 IO_TREE_FS_PINNED_EXTENTS, NULL);
371 fs_info->generation++;
372 cur_trans->transid = fs_info->generation;
373 fs_info->running_transaction = cur_trans;
374 cur_trans->aborted = 0;
375 spin_unlock(&fs_info->trans_lock);
381 * This does all the record keeping required to make sure that a shareable root
382 * is properly recorded in a given transaction. This is required to make sure
383 * the old root from before we joined the transaction is deleted when the
384 * transaction commits.
386 static int record_root_in_trans(struct btrfs_trans_handle *trans,
387 struct btrfs_root *root,
390 struct btrfs_fs_info *fs_info = root->fs_info;
393 if ((test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
394 root->last_trans < trans->transid) || force) {
395 WARN_ON(!force && root->commit_root != root->node);
398 * see below for IN_TRANS_SETUP usage rules
399 * we have the reloc mutex held now, so there
400 * is only one writer in this function
402 set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
404 /* make sure readers find IN_TRANS_SETUP before
405 * they find our root->last_trans update
409 spin_lock(&fs_info->fs_roots_radix_lock);
410 if (root->last_trans == trans->transid && !force) {
411 spin_unlock(&fs_info->fs_roots_radix_lock);
414 radix_tree_tag_set(&fs_info->fs_roots_radix,
415 (unsigned long)root->root_key.objectid,
416 BTRFS_ROOT_TRANS_TAG);
417 spin_unlock(&fs_info->fs_roots_radix_lock);
418 root->last_trans = trans->transid;
420 /* this is pretty tricky. We don't want to
421 * take the relocation lock in btrfs_record_root_in_trans
422 * unless we're really doing the first setup for this root in
425 * Normally we'd use root->last_trans as a flag to decide
426 * if we want to take the expensive mutex.
428 * But, we have to set root->last_trans before we
429 * init the relocation root, otherwise, we trip over warnings
430 * in ctree.c. The solution used here is to flag ourselves
431 * with root IN_TRANS_SETUP. When this is 1, we're still
432 * fixing up the reloc trees and everyone must wait.
434 * When this is zero, they can trust root->last_trans and fly
435 * through btrfs_record_root_in_trans without having to take the
436 * lock. smp_wmb() makes sure that all the writes above are
437 * done before we pop in the zero below
439 ret = btrfs_init_reloc_root(trans, root);
440 smp_mb__before_atomic();
441 clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
447 void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
448 struct btrfs_root *root)
450 struct btrfs_fs_info *fs_info = root->fs_info;
451 struct btrfs_transaction *cur_trans = trans->transaction;
453 /* Add ourselves to the transaction dropped list */
454 spin_lock(&cur_trans->dropped_roots_lock);
455 list_add_tail(&root->root_list, &cur_trans->dropped_roots);
456 spin_unlock(&cur_trans->dropped_roots_lock);
458 /* Make sure we don't try to update the root at commit time */
459 spin_lock(&fs_info->fs_roots_radix_lock);
460 radix_tree_tag_clear(&fs_info->fs_roots_radix,
461 (unsigned long)root->root_key.objectid,
462 BTRFS_ROOT_TRANS_TAG);
463 spin_unlock(&fs_info->fs_roots_radix_lock);
466 int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
467 struct btrfs_root *root)
469 struct btrfs_fs_info *fs_info = root->fs_info;
472 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
476 * see record_root_in_trans for comments about IN_TRANS_SETUP usage
480 if (root->last_trans == trans->transid &&
481 !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
484 mutex_lock(&fs_info->reloc_mutex);
485 ret = record_root_in_trans(trans, root, 0);
486 mutex_unlock(&fs_info->reloc_mutex);
491 static inline int is_transaction_blocked(struct btrfs_transaction *trans)
493 return (trans->state >= TRANS_STATE_COMMIT_START &&
494 trans->state < TRANS_STATE_UNBLOCKED &&
495 !TRANS_ABORTED(trans));
498 /* wait for commit against the current transaction to become unblocked
499 * when this is done, it is safe to start a new transaction, but the current
500 * transaction might not be fully on disk.
502 static void wait_current_trans(struct btrfs_fs_info *fs_info)
504 struct btrfs_transaction *cur_trans;
506 spin_lock(&fs_info->trans_lock);
507 cur_trans = fs_info->running_transaction;
508 if (cur_trans && is_transaction_blocked(cur_trans)) {
509 refcount_inc(&cur_trans->use_count);
510 spin_unlock(&fs_info->trans_lock);
512 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
513 wait_event(fs_info->transaction_wait,
514 cur_trans->state >= TRANS_STATE_UNBLOCKED ||
515 TRANS_ABORTED(cur_trans));
516 btrfs_put_transaction(cur_trans);
518 spin_unlock(&fs_info->trans_lock);
522 static int may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
524 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
527 if (type == TRANS_START)
533 static inline bool need_reserve_reloc_root(struct btrfs_root *root)
535 struct btrfs_fs_info *fs_info = root->fs_info;
537 if (!fs_info->reloc_ctl ||
538 !test_bit(BTRFS_ROOT_SHAREABLE, &root->state) ||
539 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
546 static struct btrfs_trans_handle *
547 start_transaction(struct btrfs_root *root, unsigned int num_items,
548 unsigned int type, enum btrfs_reserve_flush_enum flush,
549 bool enforce_qgroups)
551 struct btrfs_fs_info *fs_info = root->fs_info;
552 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
553 struct btrfs_trans_handle *h;
554 struct btrfs_transaction *cur_trans;
556 u64 qgroup_reserved = 0;
557 bool reloc_reserved = false;
558 bool do_chunk_alloc = false;
561 if (BTRFS_FS_ERROR(fs_info))
562 return ERR_PTR(-EROFS);
564 if (current->journal_info) {
565 WARN_ON(type & TRANS_EXTWRITERS);
566 h = current->journal_info;
567 refcount_inc(&h->use_count);
568 WARN_ON(refcount_read(&h->use_count) > 2);
569 h->orig_rsv = h->block_rsv;
575 * Do the reservation before we join the transaction so we can do all
576 * the appropriate flushing if need be.
578 if (num_items && root != fs_info->chunk_root) {
579 struct btrfs_block_rsv *rsv = &fs_info->trans_block_rsv;
580 u64 delayed_refs_bytes = 0;
582 qgroup_reserved = num_items * fs_info->nodesize;
583 ret = btrfs_qgroup_reserve_meta_pertrans(root, qgroup_reserved,
589 * We want to reserve all the bytes we may need all at once, so
590 * we only do 1 enospc flushing cycle per transaction start. We
591 * accomplish this by simply assuming we'll do 2 x num_items
592 * worth of delayed refs updates in this trans handle, and
593 * refill that amount for whatever is missing in the reserve.
595 num_bytes = btrfs_calc_insert_metadata_size(fs_info, num_items);
596 if (flush == BTRFS_RESERVE_FLUSH_ALL &&
597 btrfs_block_rsv_full(delayed_refs_rsv) == 0) {
598 delayed_refs_bytes = num_bytes;
603 * Do the reservation for the relocation root creation
605 if (need_reserve_reloc_root(root)) {
606 num_bytes += fs_info->nodesize;
607 reloc_reserved = true;
610 ret = btrfs_block_rsv_add(fs_info, rsv, num_bytes, flush);
613 if (delayed_refs_bytes) {
614 btrfs_migrate_to_delayed_refs_rsv(fs_info, rsv,
616 num_bytes -= delayed_refs_bytes;
619 if (rsv->space_info->force_alloc)
620 do_chunk_alloc = true;
621 } else if (num_items == 0 && flush == BTRFS_RESERVE_FLUSH_ALL &&
622 !btrfs_block_rsv_full(delayed_refs_rsv)) {
624 * Some people call with btrfs_start_transaction(root, 0)
625 * because they can be throttled, but have some other mechanism
626 * for reserving space. We still want these guys to refill the
627 * delayed block_rsv so just add 1 items worth of reservation
630 ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
635 h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
642 * If we are JOIN_NOLOCK we're already committing a transaction and
643 * waiting on this guy, so we don't need to do the sb_start_intwrite
644 * because we're already holding a ref. We need this because we could
645 * have raced in and did an fsync() on a file which can kick a commit
646 * and then we deadlock with somebody doing a freeze.
648 * If we are ATTACH, it means we just want to catch the current
649 * transaction and commit it, so we needn't do sb_start_intwrite().
651 if (type & __TRANS_FREEZABLE)
652 sb_start_intwrite(fs_info->sb);
654 if (may_wait_transaction(fs_info, type))
655 wait_current_trans(fs_info);
658 ret = join_transaction(fs_info, type);
660 wait_current_trans(fs_info);
661 if (unlikely(type == TRANS_ATTACH ||
662 type == TRANS_JOIN_NOSTART))
665 } while (ret == -EBUSY);
670 cur_trans = fs_info->running_transaction;
672 h->transid = cur_trans->transid;
673 h->transaction = cur_trans;
674 refcount_set(&h->use_count, 1);
675 h->fs_info = root->fs_info;
678 INIT_LIST_HEAD(&h->new_bgs);
681 if (cur_trans->state >= TRANS_STATE_COMMIT_START &&
682 may_wait_transaction(fs_info, type)) {
683 current->journal_info = h;
684 btrfs_commit_transaction(h);
689 trace_btrfs_space_reservation(fs_info, "transaction",
690 h->transid, num_bytes, 1);
691 h->block_rsv = &fs_info->trans_block_rsv;
692 h->bytes_reserved = num_bytes;
693 h->reloc_reserved = reloc_reserved;
697 if (!current->journal_info)
698 current->journal_info = h;
701 * If the space_info is marked ALLOC_FORCE then we'll get upgraded to
702 * ALLOC_FORCE the first run through, and then we won't allocate for
703 * anybody else who races in later. We don't care about the return
706 if (do_chunk_alloc && num_bytes) {
707 u64 flags = h->block_rsv->space_info->flags;
709 btrfs_chunk_alloc(h, btrfs_get_alloc_profile(fs_info, flags),
710 CHUNK_ALLOC_NO_FORCE);
714 * btrfs_record_root_in_trans() needs to alloc new extents, and may
715 * call btrfs_join_transaction() while we're also starting a
718 * Thus it need to be called after current->journal_info initialized,
719 * or we can deadlock.
721 ret = btrfs_record_root_in_trans(h, root);
724 * The transaction handle is fully initialized and linked with
725 * other structures so it needs to be ended in case of errors,
728 btrfs_end_transaction(h);
735 if (type & __TRANS_FREEZABLE)
736 sb_end_intwrite(fs_info->sb);
737 kmem_cache_free(btrfs_trans_handle_cachep, h);
740 btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
743 btrfs_qgroup_free_meta_pertrans(root, qgroup_reserved);
747 struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
748 unsigned int num_items)
750 return start_transaction(root, num_items, TRANS_START,
751 BTRFS_RESERVE_FLUSH_ALL, true);
754 struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
755 struct btrfs_root *root,
756 unsigned int num_items)
758 return start_transaction(root, num_items, TRANS_START,
759 BTRFS_RESERVE_FLUSH_ALL_STEAL, false);
762 struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
764 return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
768 struct btrfs_trans_handle *btrfs_join_transaction_spacecache(struct btrfs_root *root)
770 return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
771 BTRFS_RESERVE_NO_FLUSH, true);
775 * Similar to regular join but it never starts a transaction when none is
776 * running or after waiting for the current one to finish.
778 struct btrfs_trans_handle *btrfs_join_transaction_nostart(struct btrfs_root *root)
780 return start_transaction(root, 0, TRANS_JOIN_NOSTART,
781 BTRFS_RESERVE_NO_FLUSH, true);
785 * btrfs_attach_transaction() - catch the running transaction
787 * It is used when we want to commit the current the transaction, but
788 * don't want to start a new one.
790 * Note: If this function return -ENOENT, it just means there is no
791 * running transaction. But it is possible that the inactive transaction
792 * is still in the memory, not fully on disk. If you hope there is no
793 * inactive transaction in the fs when -ENOENT is returned, you should
795 * btrfs_attach_transaction_barrier()
797 struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
799 return start_transaction(root, 0, TRANS_ATTACH,
800 BTRFS_RESERVE_NO_FLUSH, true);
804 * btrfs_attach_transaction_barrier() - catch the running transaction
806 * It is similar to the above function, the difference is this one
807 * will wait for all the inactive transactions until they fully
810 struct btrfs_trans_handle *
811 btrfs_attach_transaction_barrier(struct btrfs_root *root)
813 struct btrfs_trans_handle *trans;
815 trans = start_transaction(root, 0, TRANS_ATTACH,
816 BTRFS_RESERVE_NO_FLUSH, true);
817 if (trans == ERR_PTR(-ENOENT)) {
820 ret = btrfs_wait_for_commit(root->fs_info, 0);
828 /* Wait for a transaction commit to reach at least the given state. */
829 static noinline void wait_for_commit(struct btrfs_transaction *commit,
830 const enum btrfs_trans_state min_state)
832 struct btrfs_fs_info *fs_info = commit->fs_info;
833 u64 transid = commit->transid;
837 * At the moment this function is called with min_state either being
838 * TRANS_STATE_COMPLETED or TRANS_STATE_SUPER_COMMITTED.
840 if (min_state == TRANS_STATE_COMPLETED)
841 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
843 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
846 wait_event(commit->commit_wait, commit->state >= min_state);
848 btrfs_put_transaction(commit);
850 if (min_state < TRANS_STATE_COMPLETED)
854 * A transaction isn't really completed until all of the
855 * previous transactions are completed, but with fsync we can
856 * end up with SUPER_COMMITTED transactions before a COMPLETED
857 * transaction. Wait for those.
860 spin_lock(&fs_info->trans_lock);
861 commit = list_first_entry_or_null(&fs_info->trans_list,
862 struct btrfs_transaction,
864 if (!commit || commit->transid > transid) {
865 spin_unlock(&fs_info->trans_lock);
868 refcount_inc(&commit->use_count);
870 spin_unlock(&fs_info->trans_lock);
874 int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
876 struct btrfs_transaction *cur_trans = NULL, *t;
880 if (transid <= fs_info->last_trans_committed)
883 /* find specified transaction */
884 spin_lock(&fs_info->trans_lock);
885 list_for_each_entry(t, &fs_info->trans_list, list) {
886 if (t->transid == transid) {
888 refcount_inc(&cur_trans->use_count);
892 if (t->transid > transid) {
897 spin_unlock(&fs_info->trans_lock);
900 * The specified transaction doesn't exist, or we
901 * raced with btrfs_commit_transaction
904 if (transid > fs_info->last_trans_committed)
909 /* find newest transaction that is committing | committed */
910 spin_lock(&fs_info->trans_lock);
911 list_for_each_entry_reverse(t, &fs_info->trans_list,
913 if (t->state >= TRANS_STATE_COMMIT_START) {
914 if (t->state == TRANS_STATE_COMPLETED)
917 refcount_inc(&cur_trans->use_count);
921 spin_unlock(&fs_info->trans_lock);
923 goto out; /* nothing committing|committed */
926 wait_for_commit(cur_trans, TRANS_STATE_COMPLETED);
927 ret = cur_trans->aborted;
928 btrfs_put_transaction(cur_trans);
933 void btrfs_throttle(struct btrfs_fs_info *fs_info)
935 wait_current_trans(fs_info);
938 static bool should_end_transaction(struct btrfs_trans_handle *trans)
940 struct btrfs_fs_info *fs_info = trans->fs_info;
942 if (btrfs_check_space_for_delayed_refs(fs_info))
945 return !!btrfs_block_rsv_check(&fs_info->global_block_rsv, 5);
948 bool btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
950 struct btrfs_transaction *cur_trans = trans->transaction;
952 if (cur_trans->state >= TRANS_STATE_COMMIT_START ||
953 test_bit(BTRFS_DELAYED_REFS_FLUSHING, &cur_trans->delayed_refs.flags))
956 return should_end_transaction(trans);
959 static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
962 struct btrfs_fs_info *fs_info = trans->fs_info;
964 if (!trans->block_rsv) {
965 ASSERT(!trans->bytes_reserved);
969 if (!trans->bytes_reserved)
972 ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
973 trace_btrfs_space_reservation(fs_info, "transaction",
974 trans->transid, trans->bytes_reserved, 0);
975 btrfs_block_rsv_release(fs_info, trans->block_rsv,
976 trans->bytes_reserved, NULL);
977 trans->bytes_reserved = 0;
980 static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
983 struct btrfs_fs_info *info = trans->fs_info;
984 struct btrfs_transaction *cur_trans = trans->transaction;
987 if (refcount_read(&trans->use_count) > 1) {
988 refcount_dec(&trans->use_count);
989 trans->block_rsv = trans->orig_rsv;
993 btrfs_trans_release_metadata(trans);
994 trans->block_rsv = NULL;
996 btrfs_create_pending_block_groups(trans);
998 btrfs_trans_release_chunk_metadata(trans);
1000 if (trans->type & __TRANS_FREEZABLE)
1001 sb_end_intwrite(info->sb);
1003 WARN_ON(cur_trans != info->running_transaction);
1004 WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
1005 atomic_dec(&cur_trans->num_writers);
1006 extwriter_counter_dec(cur_trans, trans->type);
1008 cond_wake_up(&cur_trans->writer_wait);
1010 btrfs_lockdep_release(info, btrfs_trans_num_extwriters);
1011 btrfs_lockdep_release(info, btrfs_trans_num_writers);
1013 btrfs_put_transaction(cur_trans);
1015 if (current->journal_info == trans)
1016 current->journal_info = NULL;
1019 btrfs_run_delayed_iputs(info);
1021 if (TRANS_ABORTED(trans) || BTRFS_FS_ERROR(info)) {
1022 wake_up_process(info->transaction_kthread);
1023 if (TRANS_ABORTED(trans))
1024 err = trans->aborted;
1029 kmem_cache_free(btrfs_trans_handle_cachep, trans);
1033 int btrfs_end_transaction(struct btrfs_trans_handle *trans)
1035 return __btrfs_end_transaction(trans, 0);
1038 int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
1040 return __btrfs_end_transaction(trans, 1);
1044 * when btree blocks are allocated, they have some corresponding bits set for
1045 * them in one of two extent_io trees. This is used to make sure all of
1046 * those extents are sent to disk but does not wait on them
1048 int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
1049 struct extent_io_tree *dirty_pages, int mark)
1053 struct address_space *mapping = fs_info->btree_inode->i_mapping;
1054 struct extent_state *cached_state = NULL;
1058 atomic_inc(&BTRFS_I(fs_info->btree_inode)->sync_writers);
1059 while (!find_first_extent_bit(dirty_pages, start, &start, &end,
1060 mark, &cached_state)) {
1061 bool wait_writeback = false;
1063 err = convert_extent_bit(dirty_pages, start, end,
1065 mark, &cached_state);
1067 * convert_extent_bit can return -ENOMEM, which is most of the
1068 * time a temporary error. So when it happens, ignore the error
1069 * and wait for writeback of this range to finish - because we
1070 * failed to set the bit EXTENT_NEED_WAIT for the range, a call
1071 * to __btrfs_wait_marked_extents() would not know that
1072 * writeback for this range started and therefore wouldn't
1073 * wait for it to finish - we don't want to commit a
1074 * superblock that points to btree nodes/leafs for which
1075 * writeback hasn't finished yet (and without errors).
1076 * We cleanup any entries left in the io tree when committing
1077 * the transaction (through extent_io_tree_release()).
1079 if (err == -ENOMEM) {
1081 wait_writeback = true;
1084 err = filemap_fdatawrite_range(mapping, start, end);
1087 else if (wait_writeback)
1088 werr = filemap_fdatawait_range(mapping, start, end);
1089 free_extent_state(cached_state);
1090 cached_state = NULL;
1094 atomic_dec(&BTRFS_I(fs_info->btree_inode)->sync_writers);
1099 * when btree blocks are allocated, they have some corresponding bits set for
1100 * them in one of two extent_io trees. This is used to make sure all of
1101 * those extents are on disk for transaction or log commit. We wait
1102 * on all the pages and clear them from the dirty pages state tree
1104 static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
1105 struct extent_io_tree *dirty_pages)
1109 struct address_space *mapping = fs_info->btree_inode->i_mapping;
1110 struct extent_state *cached_state = NULL;
1114 while (!find_first_extent_bit(dirty_pages, start, &start, &end,
1115 EXTENT_NEED_WAIT, &cached_state)) {
1117 * Ignore -ENOMEM errors returned by clear_extent_bit().
1118 * When committing the transaction, we'll remove any entries
1119 * left in the io tree. For a log commit, we don't remove them
1120 * after committing the log because the tree can be accessed
1121 * concurrently - we do it only at transaction commit time when
1122 * it's safe to do it (through extent_io_tree_release()).
1124 err = clear_extent_bit(dirty_pages, start, end,
1125 EXTENT_NEED_WAIT, &cached_state);
1129 err = filemap_fdatawait_range(mapping, start, end);
1132 free_extent_state(cached_state);
1133 cached_state = NULL;
1142 static int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
1143 struct extent_io_tree *dirty_pages)
1145 bool errors = false;
1148 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1149 if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1157 int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
1159 struct btrfs_fs_info *fs_info = log_root->fs_info;
1160 struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
1161 bool errors = false;
1164 ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
1166 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1167 if ((mark & EXTENT_DIRTY) &&
1168 test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1171 if ((mark & EXTENT_NEW) &&
1172 test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1181 * When btree blocks are allocated the corresponding extents are marked dirty.
1182 * This function ensures such extents are persisted on disk for transaction or
1185 * @trans: transaction whose dirty pages we'd like to write
1187 static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1191 struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
1192 struct btrfs_fs_info *fs_info = trans->fs_info;
1193 struct blk_plug plug;
1195 blk_start_plug(&plug);
1196 ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1197 blk_finish_plug(&plug);
1198 ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1200 extent_io_tree_release(&trans->transaction->dirty_pages);
1211 * this is used to update the root pointer in the tree of tree roots.
1213 * But, in the case of the extent allocation tree, updating the root
1214 * pointer may allocate blocks which may change the root of the extent
1217 * So, this loops and repeats and makes sure the cowonly root didn't
1218 * change while the root pointer was being updated in the metadata.
1220 static int update_cowonly_root(struct btrfs_trans_handle *trans,
1221 struct btrfs_root *root)
1224 u64 old_root_bytenr;
1226 struct btrfs_fs_info *fs_info = root->fs_info;
1227 struct btrfs_root *tree_root = fs_info->tree_root;
1229 old_root_used = btrfs_root_used(&root->root_item);
1232 old_root_bytenr = btrfs_root_bytenr(&root->root_item);
1233 if (old_root_bytenr == root->node->start &&
1234 old_root_used == btrfs_root_used(&root->root_item))
1237 btrfs_set_root_node(&root->root_item, root->node);
1238 ret = btrfs_update_root(trans, tree_root,
1244 old_root_used = btrfs_root_used(&root->root_item);
1251 * update all the cowonly tree roots on disk
1253 * The error handling in this function may not be obvious. Any of the
1254 * failures will cause the file system to go offline. We still need
1255 * to clean up the delayed refs.
1257 static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
1259 struct btrfs_fs_info *fs_info = trans->fs_info;
1260 struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
1261 struct list_head *io_bgs = &trans->transaction->io_bgs;
1262 struct list_head *next;
1263 struct extent_buffer *eb;
1267 * At this point no one can be using this transaction to modify any tree
1268 * and no one can start another transaction to modify any tree either.
1270 ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1272 eb = btrfs_lock_root_node(fs_info->tree_root);
1273 ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
1274 0, &eb, BTRFS_NESTING_COW);
1275 btrfs_tree_unlock(eb);
1276 free_extent_buffer(eb);
1281 ret = btrfs_run_dev_stats(trans);
1284 ret = btrfs_run_dev_replace(trans);
1287 ret = btrfs_run_qgroups(trans);
1291 ret = btrfs_setup_space_cache(trans);
1296 while (!list_empty(&fs_info->dirty_cowonly_roots)) {
1297 struct btrfs_root *root;
1298 next = fs_info->dirty_cowonly_roots.next;
1299 list_del_init(next);
1300 root = list_entry(next, struct btrfs_root, dirty_list);
1301 clear_bit(BTRFS_ROOT_DIRTY, &root->state);
1303 list_add_tail(&root->dirty_list,
1304 &trans->transaction->switch_commits);
1305 ret = update_cowonly_root(trans, root);
1310 /* Now flush any delayed refs generated by updating all of the roots */
1311 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1315 while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
1316 ret = btrfs_write_dirty_block_groups(trans);
1321 * We're writing the dirty block groups, which could generate
1322 * delayed refs, which could generate more dirty block groups,
1323 * so we want to keep this flushing in this loop to make sure
1324 * everything gets run.
1326 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1331 if (!list_empty(&fs_info->dirty_cowonly_roots))
1334 /* Update dev-replace pointer once everything is committed */
1335 fs_info->dev_replace.committed_cursor_left =
1336 fs_info->dev_replace.cursor_left_last_write_of_item;
1342 * If we had a pending drop we need to see if there are any others left in our
1343 * dead roots list, and if not clear our bit and wake any waiters.
1345 void btrfs_maybe_wake_unfinished_drop(struct btrfs_fs_info *fs_info)
1348 * We put the drop in progress roots at the front of the list, so if the
1349 * first entry doesn't have UNFINISHED_DROP set we can wake everybody
1352 spin_lock(&fs_info->trans_lock);
1353 if (!list_empty(&fs_info->dead_roots)) {
1354 struct btrfs_root *root = list_first_entry(&fs_info->dead_roots,
1357 if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state)) {
1358 spin_unlock(&fs_info->trans_lock);
1362 spin_unlock(&fs_info->trans_lock);
1364 btrfs_wake_unfinished_drop(fs_info);
1368 * dead roots are old snapshots that need to be deleted. This allocates
1369 * a dirty root struct and adds it into the list of dead roots that need to
1372 void btrfs_add_dead_root(struct btrfs_root *root)
1374 struct btrfs_fs_info *fs_info = root->fs_info;
1376 spin_lock(&fs_info->trans_lock);
1377 if (list_empty(&root->root_list)) {
1378 btrfs_grab_root(root);
1380 /* We want to process the partially complete drops first. */
1381 if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state))
1382 list_add(&root->root_list, &fs_info->dead_roots);
1384 list_add_tail(&root->root_list, &fs_info->dead_roots);
1386 spin_unlock(&fs_info->trans_lock);
1390 * Update each subvolume root and its relocation root, if it exists, in the tree
1391 * of tree roots. Also free log roots if they exist.
1393 static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
1395 struct btrfs_fs_info *fs_info = trans->fs_info;
1396 struct btrfs_root *gang[8];
1401 * At this point no one can be using this transaction to modify any tree
1402 * and no one can start another transaction to modify any tree either.
1404 ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1406 spin_lock(&fs_info->fs_roots_radix_lock);
1408 ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
1411 BTRFS_ROOT_TRANS_TAG);
1414 for (i = 0; i < ret; i++) {
1415 struct btrfs_root *root = gang[i];
1419 * At this point we can neither have tasks logging inodes
1420 * from a root nor trying to commit a log tree.
1422 ASSERT(atomic_read(&root->log_writers) == 0);
1423 ASSERT(atomic_read(&root->log_commit[0]) == 0);
1424 ASSERT(atomic_read(&root->log_commit[1]) == 0);
1426 radix_tree_tag_clear(&fs_info->fs_roots_radix,
1427 (unsigned long)root->root_key.objectid,
1428 BTRFS_ROOT_TRANS_TAG);
1429 spin_unlock(&fs_info->fs_roots_radix_lock);
1431 btrfs_free_log(trans, root);
1432 ret2 = btrfs_update_reloc_root(trans, root);
1436 /* see comments in should_cow_block() */
1437 clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1438 smp_mb__after_atomic();
1440 if (root->commit_root != root->node) {
1441 list_add_tail(&root->dirty_list,
1442 &trans->transaction->switch_commits);
1443 btrfs_set_root_node(&root->root_item,
1447 ret2 = btrfs_update_root(trans, fs_info->tree_root,
1452 spin_lock(&fs_info->fs_roots_radix_lock);
1453 btrfs_qgroup_free_meta_all_pertrans(root);
1456 spin_unlock(&fs_info->fs_roots_radix_lock);
1461 * defrag a given btree.
1462 * Every leaf in the btree is read and defragged.
1464 int btrfs_defrag_root(struct btrfs_root *root)
1466 struct btrfs_fs_info *info = root->fs_info;
1467 struct btrfs_trans_handle *trans;
1470 if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
1474 trans = btrfs_start_transaction(root, 0);
1475 if (IS_ERR(trans)) {
1476 ret = PTR_ERR(trans);
1480 ret = btrfs_defrag_leaves(trans, root);
1482 btrfs_end_transaction(trans);
1483 btrfs_btree_balance_dirty(info);
1486 if (btrfs_fs_closing(info) || ret != -EAGAIN)
1489 if (btrfs_defrag_cancelled(info)) {
1490 btrfs_debug(info, "defrag_root cancelled");
1495 clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
1500 * Do all special snapshot related qgroup dirty hack.
1502 * Will do all needed qgroup inherit and dirty hack like switch commit
1503 * roots inside one transaction and write all btree into disk, to make
1506 static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
1507 struct btrfs_root *src,
1508 struct btrfs_root *parent,
1509 struct btrfs_qgroup_inherit *inherit,
1512 struct btrfs_fs_info *fs_info = src->fs_info;
1516 * Save some performance in the case that qgroups are not
1517 * enabled. If this check races with the ioctl, rescan will
1520 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1524 * Ensure dirty @src will be committed. Or, after coming
1525 * commit_fs_roots() and switch_commit_roots(), any dirty but not
1526 * recorded root will never be updated again, causing an outdated root
1529 ret = record_root_in_trans(trans, src, 1);
1534 * btrfs_qgroup_inherit relies on a consistent view of the usage for the
1535 * src root, so we must run the delayed refs here.
1537 * However this isn't particularly fool proof, because there's no
1538 * synchronization keeping us from changing the tree after this point
1539 * before we do the qgroup_inherit, or even from making changes while
1540 * we're doing the qgroup_inherit. But that's a problem for the future,
1541 * for now flush the delayed refs to narrow the race window where the
1542 * qgroup counters could end up wrong.
1544 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1546 btrfs_abort_transaction(trans, ret);
1550 ret = commit_fs_roots(trans);
1553 ret = btrfs_qgroup_account_extents(trans);
1557 /* Now qgroup are all updated, we can inherit it to new qgroups */
1558 ret = btrfs_qgroup_inherit(trans, src->root_key.objectid, dst_objectid,
1564 * Now we do a simplified commit transaction, which will:
1565 * 1) commit all subvolume and extent tree
1566 * To ensure all subvolume and extent tree have a valid
1567 * commit_root to accounting later insert_dir_item()
1568 * 2) write all btree blocks onto disk
1569 * This is to make sure later btree modification will be cowed
1570 * Or commit_root can be populated and cause wrong qgroup numbers
1571 * In this simplified commit, we don't really care about other trees
1572 * like chunk and root tree, as they won't affect qgroup.
1573 * And we don't write super to avoid half committed status.
1575 ret = commit_cowonly_roots(trans);
1578 switch_commit_roots(trans);
1579 ret = btrfs_write_and_wait_transaction(trans);
1581 btrfs_handle_fs_error(fs_info, ret,
1582 "Error while writing out transaction for qgroup");
1586 * Force parent root to be updated, as we recorded it before so its
1587 * last_trans == cur_transid.
1588 * Or it won't be committed again onto disk after later
1592 ret = record_root_in_trans(trans, parent, 1);
1597 * new snapshots need to be created at a very specific time in the
1598 * transaction commit. This does the actual creation.
1601 * If the error which may affect the commitment of the current transaction
1602 * happens, we should return the error number. If the error which just affect
1603 * the creation of the pending snapshots, just return 0.
1605 static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
1606 struct btrfs_pending_snapshot *pending)
1609 struct btrfs_fs_info *fs_info = trans->fs_info;
1610 struct btrfs_key key;
1611 struct btrfs_root_item *new_root_item;
1612 struct btrfs_root *tree_root = fs_info->tree_root;
1613 struct btrfs_root *root = pending->root;
1614 struct btrfs_root *parent_root;
1615 struct btrfs_block_rsv *rsv;
1616 struct inode *parent_inode;
1617 struct btrfs_path *path;
1618 struct btrfs_dir_item *dir_item;
1619 struct dentry *dentry;
1620 struct extent_buffer *tmp;
1621 struct extent_buffer *old;
1622 struct timespec64 cur_time;
1629 ASSERT(pending->path);
1630 path = pending->path;
1632 ASSERT(pending->root_item);
1633 new_root_item = pending->root_item;
1635 pending->error = btrfs_get_free_objectid(tree_root, &objectid);
1637 goto no_free_objectid;
1640 * Make qgroup to skip current new snapshot's qgroupid, as it is
1641 * accounted by later btrfs_qgroup_inherit().
1643 btrfs_set_skip_qgroup(trans, objectid);
1645 btrfs_reloc_pre_snapshot(pending, &to_reserve);
1647 if (to_reserve > 0) {
1648 pending->error = btrfs_block_rsv_add(fs_info,
1649 &pending->block_rsv,
1651 BTRFS_RESERVE_NO_FLUSH);
1653 goto clear_skip_qgroup;
1656 key.objectid = objectid;
1657 key.offset = (u64)-1;
1658 key.type = BTRFS_ROOT_ITEM_KEY;
1660 rsv = trans->block_rsv;
1661 trans->block_rsv = &pending->block_rsv;
1662 trans->bytes_reserved = trans->block_rsv->reserved;
1663 trace_btrfs_space_reservation(fs_info, "transaction",
1665 trans->bytes_reserved, 1);
1666 dentry = pending->dentry;
1667 parent_inode = pending->dir;
1668 parent_root = BTRFS_I(parent_inode)->root;
1669 ret = record_root_in_trans(trans, parent_root, 0);
1672 cur_time = current_time(parent_inode);
1675 * insert the directory item
1677 ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
1678 BUG_ON(ret); /* -ENOMEM */
1680 /* check if there is a file/dir which has the same name. */
1681 dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
1682 btrfs_ino(BTRFS_I(parent_inode)),
1683 dentry->d_name.name,
1684 dentry->d_name.len, 0);
1685 if (dir_item != NULL && !IS_ERR(dir_item)) {
1686 pending->error = -EEXIST;
1687 goto dir_item_existed;
1688 } else if (IS_ERR(dir_item)) {
1689 ret = PTR_ERR(dir_item);
1690 btrfs_abort_transaction(trans, ret);
1693 btrfs_release_path(path);
1696 * pull in the delayed directory update
1697 * and the delayed inode item
1698 * otherwise we corrupt the FS during
1701 ret = btrfs_run_delayed_items(trans);
1702 if (ret) { /* Transaction aborted */
1703 btrfs_abort_transaction(trans, ret);
1707 ret = record_root_in_trans(trans, root, 0);
1709 btrfs_abort_transaction(trans, ret);
1712 btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
1713 memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
1714 btrfs_check_and_init_root_item(new_root_item);
1716 root_flags = btrfs_root_flags(new_root_item);
1717 if (pending->readonly)
1718 root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1720 root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1721 btrfs_set_root_flags(new_root_item, root_flags);
1723 btrfs_set_root_generation_v2(new_root_item,
1725 generate_random_guid(new_root_item->uuid);
1726 memcpy(new_root_item->parent_uuid, root->root_item.uuid,
1728 if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
1729 memset(new_root_item->received_uuid, 0,
1730 sizeof(new_root_item->received_uuid));
1731 memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
1732 memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
1733 btrfs_set_root_stransid(new_root_item, 0);
1734 btrfs_set_root_rtransid(new_root_item, 0);
1736 btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
1737 btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
1738 btrfs_set_root_otransid(new_root_item, trans->transid);
1740 old = btrfs_lock_root_node(root);
1741 ret = btrfs_cow_block(trans, root, old, NULL, 0, &old,
1744 btrfs_tree_unlock(old);
1745 free_extent_buffer(old);
1746 btrfs_abort_transaction(trans, ret);
1750 ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
1751 /* clean up in any case */
1752 btrfs_tree_unlock(old);
1753 free_extent_buffer(old);
1755 btrfs_abort_transaction(trans, ret);
1758 /* see comments in should_cow_block() */
1759 set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1762 btrfs_set_root_node(new_root_item, tmp);
1763 /* record when the snapshot was created in key.offset */
1764 key.offset = trans->transid;
1765 ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1766 btrfs_tree_unlock(tmp);
1767 free_extent_buffer(tmp);
1769 btrfs_abort_transaction(trans, ret);
1774 * insert root back/forward references
1776 ret = btrfs_add_root_ref(trans, objectid,
1777 parent_root->root_key.objectid,
1778 btrfs_ino(BTRFS_I(parent_inode)), index,
1779 dentry->d_name.name, dentry->d_name.len);
1781 btrfs_abort_transaction(trans, ret);
1785 key.offset = (u64)-1;
1786 pending->snap = btrfs_get_new_fs_root(fs_info, objectid, pending->anon_dev);
1787 if (IS_ERR(pending->snap)) {
1788 ret = PTR_ERR(pending->snap);
1789 pending->snap = NULL;
1790 btrfs_abort_transaction(trans, ret);
1794 ret = btrfs_reloc_post_snapshot(trans, pending);
1796 btrfs_abort_transaction(trans, ret);
1801 * Do special qgroup accounting for snapshot, as we do some qgroup
1802 * snapshot hack to do fast snapshot.
1803 * To co-operate with that hack, we do hack again.
1804 * Or snapshot will be greatly slowed down by a subtree qgroup rescan
1806 ret = qgroup_account_snapshot(trans, root, parent_root,
1807 pending->inherit, objectid);
1811 ret = btrfs_insert_dir_item(trans, dentry->d_name.name,
1812 dentry->d_name.len, BTRFS_I(parent_inode),
1813 &key, BTRFS_FT_DIR, index);
1814 /* We have check then name at the beginning, so it is impossible. */
1815 BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
1817 btrfs_abort_transaction(trans, ret);
1821 btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
1822 dentry->d_name.len * 2);
1823 parent_inode->i_mtime = current_time(parent_inode);
1824 parent_inode->i_ctime = parent_inode->i_mtime;
1825 ret = btrfs_update_inode_fallback(trans, parent_root, BTRFS_I(parent_inode));
1827 btrfs_abort_transaction(trans, ret);
1830 ret = btrfs_uuid_tree_add(trans, new_root_item->uuid,
1831 BTRFS_UUID_KEY_SUBVOL,
1834 btrfs_abort_transaction(trans, ret);
1837 if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1838 ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1839 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1841 if (ret && ret != -EEXIST) {
1842 btrfs_abort_transaction(trans, ret);
1848 pending->error = ret;
1850 trans->block_rsv = rsv;
1851 trans->bytes_reserved = 0;
1853 btrfs_clear_skip_qgroup(trans);
1855 kfree(new_root_item);
1856 pending->root_item = NULL;
1857 btrfs_free_path(path);
1858 pending->path = NULL;
1864 * create all the snapshots we've scheduled for creation
1866 static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
1868 struct btrfs_pending_snapshot *pending, *next;
1869 struct list_head *head = &trans->transaction->pending_snapshots;
1872 list_for_each_entry_safe(pending, next, head, list) {
1873 list_del(&pending->list);
1874 ret = create_pending_snapshot(trans, pending);
1881 static void update_super_roots(struct btrfs_fs_info *fs_info)
1883 struct btrfs_root_item *root_item;
1884 struct btrfs_super_block *super;
1886 super = fs_info->super_copy;
1888 root_item = &fs_info->chunk_root->root_item;
1889 super->chunk_root = root_item->bytenr;
1890 super->chunk_root_generation = root_item->generation;
1891 super->chunk_root_level = root_item->level;
1893 root_item = &fs_info->tree_root->root_item;
1894 super->root = root_item->bytenr;
1895 super->generation = root_item->generation;
1896 super->root_level = root_item->level;
1897 if (btrfs_test_opt(fs_info, SPACE_CACHE))
1898 super->cache_generation = root_item->generation;
1899 else if (test_bit(BTRFS_FS_CLEANUP_SPACE_CACHE_V1, &fs_info->flags))
1900 super->cache_generation = 0;
1901 if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1902 super->uuid_tree_generation = root_item->generation;
1905 int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1907 struct btrfs_transaction *trans;
1910 spin_lock(&info->trans_lock);
1911 trans = info->running_transaction;
1913 ret = (trans->state >= TRANS_STATE_COMMIT_START);
1914 spin_unlock(&info->trans_lock);
1918 int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1920 struct btrfs_transaction *trans;
1923 spin_lock(&info->trans_lock);
1924 trans = info->running_transaction;
1926 ret = is_transaction_blocked(trans);
1927 spin_unlock(&info->trans_lock);
1931 void btrfs_commit_transaction_async(struct btrfs_trans_handle *trans)
1933 struct btrfs_fs_info *fs_info = trans->fs_info;
1934 struct btrfs_transaction *cur_trans;
1936 /* Kick the transaction kthread. */
1937 set_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
1938 wake_up_process(fs_info->transaction_kthread);
1940 /* take transaction reference */
1941 cur_trans = trans->transaction;
1942 refcount_inc(&cur_trans->use_count);
1944 btrfs_end_transaction(trans);
1947 * Wait for the current transaction commit to start and block
1948 * subsequent transaction joins
1950 btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_START);
1951 wait_event(fs_info->transaction_blocked_wait,
1952 cur_trans->state >= TRANS_STATE_COMMIT_START ||
1953 TRANS_ABORTED(cur_trans));
1954 btrfs_put_transaction(cur_trans);
1957 static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
1959 struct btrfs_fs_info *fs_info = trans->fs_info;
1960 struct btrfs_transaction *cur_trans = trans->transaction;
1962 WARN_ON(refcount_read(&trans->use_count) > 1);
1964 btrfs_abort_transaction(trans, err);
1966 spin_lock(&fs_info->trans_lock);
1969 * If the transaction is removed from the list, it means this
1970 * transaction has been committed successfully, so it is impossible
1971 * to call the cleanup function.
1973 BUG_ON(list_empty(&cur_trans->list));
1975 if (cur_trans == fs_info->running_transaction) {
1976 cur_trans->state = TRANS_STATE_COMMIT_DOING;
1977 spin_unlock(&fs_info->trans_lock);
1980 * The thread has already released the lockdep map as reader
1981 * already in btrfs_commit_transaction().
1983 btrfs_might_wait_for_event(fs_info, btrfs_trans_num_writers);
1984 wait_event(cur_trans->writer_wait,
1985 atomic_read(&cur_trans->num_writers) == 1);
1987 spin_lock(&fs_info->trans_lock);
1991 * Now that we know no one else is still using the transaction we can
1992 * remove the transaction from the list of transactions. This avoids
1993 * the transaction kthread from cleaning up the transaction while some
1994 * other task is still using it, which could result in a use-after-free
1995 * on things like log trees, as it forces the transaction kthread to
1996 * wait for this transaction to be cleaned up by us.
1998 list_del_init(&cur_trans->list);
2000 spin_unlock(&fs_info->trans_lock);
2002 btrfs_cleanup_one_transaction(trans->transaction, fs_info);
2004 spin_lock(&fs_info->trans_lock);
2005 if (cur_trans == fs_info->running_transaction)
2006 fs_info->running_transaction = NULL;
2007 spin_unlock(&fs_info->trans_lock);
2009 if (trans->type & __TRANS_FREEZABLE)
2010 sb_end_intwrite(fs_info->sb);
2011 btrfs_put_transaction(cur_trans);
2012 btrfs_put_transaction(cur_trans);
2014 trace_btrfs_transaction_commit(fs_info);
2016 if (current->journal_info == trans)
2017 current->journal_info = NULL;
2020 * If relocation is running, we can't cancel scrub because that will
2021 * result in a deadlock. Before relocating a block group, relocation
2022 * pauses scrub, then starts and commits a transaction before unpausing
2023 * scrub. If the transaction commit is being done by the relocation
2024 * task or triggered by another task and the relocation task is waiting
2025 * for the commit, and we end up here due to an error in the commit
2026 * path, then calling btrfs_scrub_cancel() will deadlock, as we are
2027 * asking for scrub to stop while having it asked to be paused higher
2028 * above in relocation code.
2030 if (!test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
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);
2121 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_START);
2123 /* Stop the commit early if ->aborted is set */
2124 if (TRANS_ABORTED(cur_trans)) {
2125 ret = cur_trans->aborted;
2126 goto lockdep_trans_commit_start_release;
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 goto lockdep_trans_commit_start_release;
2147 btrfs_create_pending_block_groups(trans);
2149 if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
2152 /* this mutex is also taken before trying to set
2153 * block groups readonly. We need to make sure
2154 * that nobody has set a block group readonly
2155 * after a extents from that block group have been
2156 * allocated for cache files. btrfs_set_block_group_ro
2157 * will wait for the transaction to commit if it
2158 * finds BTRFS_TRANS_DIRTY_BG_RUN set.
2160 * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
2161 * only one process starts all the block group IO. It wouldn't
2162 * hurt to have more than one go through, but there's no
2163 * real advantage to it either.
2165 mutex_lock(&fs_info->ro_block_group_mutex);
2166 if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
2169 mutex_unlock(&fs_info->ro_block_group_mutex);
2172 ret = btrfs_start_dirty_block_groups(trans);
2174 goto lockdep_trans_commit_start_release;
2178 spin_lock(&fs_info->trans_lock);
2179 if (cur_trans->state >= TRANS_STATE_COMMIT_START) {
2180 enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2182 add_pending_snapshot(trans);
2184 spin_unlock(&fs_info->trans_lock);
2185 refcount_inc(&cur_trans->use_count);
2187 if (trans->in_fsync)
2188 want_state = TRANS_STATE_SUPER_COMMITTED;
2190 btrfs_trans_state_lockdep_release(fs_info,
2191 BTRFS_LOCKDEP_TRANS_COMMIT_START);
2192 ret = btrfs_end_transaction(trans);
2193 wait_for_commit(cur_trans, want_state);
2195 if (TRANS_ABORTED(cur_trans))
2196 ret = cur_trans->aborted;
2198 btrfs_put_transaction(cur_trans);
2203 cur_trans->state = TRANS_STATE_COMMIT_START;
2204 wake_up(&fs_info->transaction_blocked_wait);
2205 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_START);
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 lockdep_release;
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 lockdep_release;
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 lockdep_release;
2255 ret = btrfs_run_delayed_items(trans);
2257 goto lockdep_release;
2260 * The thread has started/joined the transaction thus it holds the
2261 * lockdep map as a reader. It has to release it before acquiring the
2262 * lockdep map as a writer.
2264 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2265 btrfs_might_wait_for_event(fs_info, btrfs_trans_num_extwriters);
2266 wait_event(cur_trans->writer_wait,
2267 extwriter_counter_read(cur_trans) == 0);
2269 /* some pending stuffs might be added after the previous flush. */
2270 ret = btrfs_run_delayed_items(trans);
2272 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2273 goto cleanup_transaction;
2276 btrfs_wait_delalloc_flush(fs_info);
2279 * Wait for all ordered extents started by a fast fsync that joined this
2280 * transaction. Otherwise if this transaction commits before the ordered
2281 * extents complete we lose logged data after a power failure.
2283 btrfs_might_wait_for_event(fs_info, btrfs_trans_pending_ordered);
2284 wait_event(cur_trans->pending_wait,
2285 atomic_read(&cur_trans->pending_ordered) == 0);
2287 btrfs_scrub_pause(fs_info);
2289 * Ok now we need to make sure to block out any other joins while we
2290 * commit the transaction. We could have started a join before setting
2291 * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2293 spin_lock(&fs_info->trans_lock);
2294 add_pending_snapshot(trans);
2295 cur_trans->state = TRANS_STATE_COMMIT_DOING;
2296 spin_unlock(&fs_info->trans_lock);
2299 * The thread has started/joined the transaction thus it holds the
2300 * lockdep map as a reader. It has to release it before acquiring the
2301 * lockdep map as a writer.
2303 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2304 btrfs_might_wait_for_event(fs_info, btrfs_trans_num_writers);
2305 wait_event(cur_trans->writer_wait,
2306 atomic_read(&cur_trans->num_writers) == 1);
2309 * Make lockdep happy by acquiring the state locks after
2310 * btrfs_trans_num_writers is released. If we acquired the state locks
2311 * before releasing the btrfs_trans_num_writers lock then lockdep would
2312 * complain because we did not follow the reverse order unlocking rule.
2314 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2315 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2316 btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2319 * We've started the commit, clear the flag in case we were triggered to
2320 * do an async commit but somebody else started before the transaction
2321 * kthread could do the work.
2323 clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
2325 if (TRANS_ABORTED(cur_trans)) {
2326 ret = cur_trans->aborted;
2327 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2328 goto scrub_continue;
2331 * the reloc mutex makes sure that we stop
2332 * the balancing code from coming in and moving
2333 * extents around in the middle of the commit
2335 mutex_lock(&fs_info->reloc_mutex);
2338 * We needn't worry about the delayed items because we will
2339 * deal with them in create_pending_snapshot(), which is the
2340 * core function of the snapshot creation.
2342 ret = create_pending_snapshots(trans);
2347 * We insert the dir indexes of the snapshots and update the inode
2348 * of the snapshots' parents after the snapshot creation, so there
2349 * are some delayed items which are not dealt with. Now deal with
2352 * We needn't worry that this operation will corrupt the snapshots,
2353 * because all the tree which are snapshoted will be forced to COW
2354 * the nodes and leaves.
2356 ret = btrfs_run_delayed_items(trans);
2360 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2365 * make sure none of the code above managed to slip in a
2368 btrfs_assert_delayed_root_empty(fs_info);
2370 WARN_ON(cur_trans != trans->transaction);
2372 ret = commit_fs_roots(trans);
2377 * Since the transaction is done, we can apply the pending changes
2378 * before the next transaction.
2380 btrfs_apply_pending_changes(fs_info);
2382 /* commit_fs_roots gets rid of all the tree log roots, it is now
2383 * safe to free the root of tree log roots
2385 btrfs_free_log_root_tree(trans, fs_info);
2388 * Since fs roots are all committed, we can get a quite accurate
2389 * new_roots. So let's do quota accounting.
2391 ret = btrfs_qgroup_account_extents(trans);
2395 ret = commit_cowonly_roots(trans);
2400 * The tasks which save the space cache and inode cache may also
2401 * update ->aborted, check it.
2403 if (TRANS_ABORTED(cur_trans)) {
2404 ret = cur_trans->aborted;
2408 cur_trans = fs_info->running_transaction;
2410 btrfs_set_root_node(&fs_info->tree_root->root_item,
2411 fs_info->tree_root->node);
2412 list_add_tail(&fs_info->tree_root->dirty_list,
2413 &cur_trans->switch_commits);
2415 btrfs_set_root_node(&fs_info->chunk_root->root_item,
2416 fs_info->chunk_root->node);
2417 list_add_tail(&fs_info->chunk_root->dirty_list,
2418 &cur_trans->switch_commits);
2420 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
2421 btrfs_set_root_node(&fs_info->block_group_root->root_item,
2422 fs_info->block_group_root->node);
2423 list_add_tail(&fs_info->block_group_root->dirty_list,
2424 &cur_trans->switch_commits);
2427 switch_commit_roots(trans);
2429 ASSERT(list_empty(&cur_trans->dirty_bgs));
2430 ASSERT(list_empty(&cur_trans->io_bgs));
2431 update_super_roots(fs_info);
2433 btrfs_set_super_log_root(fs_info->super_copy, 0);
2434 btrfs_set_super_log_root_level(fs_info->super_copy, 0);
2435 memcpy(fs_info->super_for_commit, fs_info->super_copy,
2436 sizeof(*fs_info->super_copy));
2438 btrfs_commit_device_sizes(cur_trans);
2440 clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2441 clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2443 btrfs_trans_release_chunk_metadata(trans);
2446 * Before changing the transaction state to TRANS_STATE_UNBLOCKED and
2447 * setting fs_info->running_transaction to NULL, lock tree_log_mutex to
2448 * make sure that before we commit our superblock, no other task can
2449 * start a new transaction and commit a log tree before we commit our
2450 * superblock. Anyone trying to commit a log tree locks this mutex before
2451 * writing its superblock.
2453 mutex_lock(&fs_info->tree_log_mutex);
2455 spin_lock(&fs_info->trans_lock);
2456 cur_trans->state = TRANS_STATE_UNBLOCKED;
2457 fs_info->running_transaction = NULL;
2458 spin_unlock(&fs_info->trans_lock);
2459 mutex_unlock(&fs_info->reloc_mutex);
2461 wake_up(&fs_info->transaction_wait);
2462 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2464 ret = btrfs_write_and_wait_transaction(trans);
2466 btrfs_handle_fs_error(fs_info, ret,
2467 "Error while writing out transaction");
2468 mutex_unlock(&fs_info->tree_log_mutex);
2469 goto scrub_continue;
2473 * At this point, we should have written all the tree blocks allocated
2474 * in this transaction. So it's now safe to free the redirtyied extent
2477 btrfs_free_redirty_list(cur_trans);
2479 ret = write_all_supers(fs_info, 0);
2481 * the super is written, we can safely allow the tree-loggers
2482 * to go about their business
2484 mutex_unlock(&fs_info->tree_log_mutex);
2486 goto scrub_continue;
2489 * We needn't acquire the lock here because there is no other task
2490 * which can change it.
2492 cur_trans->state = TRANS_STATE_SUPER_COMMITTED;
2493 wake_up(&cur_trans->commit_wait);
2494 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2496 btrfs_finish_extent_commit(trans);
2498 if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
2499 btrfs_clear_space_info_full(fs_info);
2501 fs_info->last_trans_committed = cur_trans->transid;
2503 * We needn't acquire the lock here because there is no other task
2504 * which can change it.
2506 cur_trans->state = TRANS_STATE_COMPLETED;
2507 wake_up(&cur_trans->commit_wait);
2508 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2510 spin_lock(&fs_info->trans_lock);
2511 list_del_init(&cur_trans->list);
2512 spin_unlock(&fs_info->trans_lock);
2514 btrfs_put_transaction(cur_trans);
2515 btrfs_put_transaction(cur_trans);
2517 if (trans->type & __TRANS_FREEZABLE)
2518 sb_end_intwrite(fs_info->sb);
2520 trace_btrfs_transaction_commit(fs_info);
2522 interval = ktime_get_ns() - start_time;
2524 btrfs_scrub_continue(fs_info);
2526 if (current->journal_info == trans)
2527 current->journal_info = NULL;
2529 kmem_cache_free(btrfs_trans_handle_cachep, trans);
2531 update_commit_stats(fs_info, interval);
2536 mutex_unlock(&fs_info->reloc_mutex);
2537 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2539 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2540 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2541 btrfs_scrub_continue(fs_info);
2542 cleanup_transaction:
2543 btrfs_trans_release_metadata(trans);
2544 btrfs_cleanup_pending_block_groups(trans);
2545 btrfs_trans_release_chunk_metadata(trans);
2546 trans->block_rsv = NULL;
2547 btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
2548 if (current->journal_info == trans)
2549 current->journal_info = NULL;
2550 cleanup_transaction(trans, ret);
2555 btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2556 btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2557 goto cleanup_transaction;
2559 lockdep_trans_commit_start_release:
2560 btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_START);
2561 btrfs_end_transaction(trans);
2566 * return < 0 if error
2567 * 0 if there are no more dead_roots at the time of call
2568 * 1 there are more to be processed, call me again
2570 * The return value indicates there are certainly more snapshots to delete, but
2571 * if there comes a new one during processing, it may return 0. We don't mind,
2572 * because btrfs_commit_super will poke cleaner thread and it will process it a
2573 * few seconds later.
2575 int btrfs_clean_one_deleted_snapshot(struct btrfs_fs_info *fs_info)
2577 struct btrfs_root *root;
2580 spin_lock(&fs_info->trans_lock);
2581 if (list_empty(&fs_info->dead_roots)) {
2582 spin_unlock(&fs_info->trans_lock);
2585 root = list_first_entry(&fs_info->dead_roots,
2586 struct btrfs_root, root_list);
2587 list_del_init(&root->root_list);
2588 spin_unlock(&fs_info->trans_lock);
2590 btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
2592 btrfs_kill_all_delayed_nodes(root);
2594 if (btrfs_header_backref_rev(root->node) <
2595 BTRFS_MIXED_BACKREF_REV)
2596 ret = btrfs_drop_snapshot(root, 0, 0);
2598 ret = btrfs_drop_snapshot(root, 1, 0);
2600 btrfs_put_root(root);
2601 return (ret < 0) ? 0 : 1;
2604 void btrfs_apply_pending_changes(struct btrfs_fs_info *fs_info)
2609 prev = xchg(&fs_info->pending_changes, 0);
2613 bit = 1 << BTRFS_PENDING_COMMIT;
2615 btrfs_debug(fs_info, "pending commit done");
2620 "unknown pending changes left 0x%lx, ignoring", prev);