1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
7 #include <linux/slab.h>
8 #include <linux/sched.h>
9 #include <linux/writeback.h>
10 #include <linux/pagemap.h>
11 #include <linux/blkdev.h>
12 #include <linux/uuid.h>
15 #include "transaction.h"
18 #include "inode-map.h"
20 #include "dev-replace.h"
23 #define BTRFS_ROOT_TRANS_TAG 0
25 static const unsigned int btrfs_blocked_trans_types[TRANS_STATE_MAX] = {
26 [TRANS_STATE_RUNNING] = 0U,
27 [TRANS_STATE_BLOCKED] = __TRANS_START,
28 [TRANS_STATE_COMMIT_START] = (__TRANS_START | __TRANS_ATTACH),
29 [TRANS_STATE_COMMIT_DOING] = (__TRANS_START |
32 [TRANS_STATE_UNBLOCKED] = (__TRANS_START |
36 [TRANS_STATE_COMPLETED] = (__TRANS_START |
42 void btrfs_put_transaction(struct btrfs_transaction *transaction)
44 WARN_ON(refcount_read(&transaction->use_count) == 0);
45 if (refcount_dec_and_test(&transaction->use_count)) {
46 BUG_ON(!list_empty(&transaction->list));
47 WARN_ON(!RB_EMPTY_ROOT(
48 &transaction->delayed_refs.href_root.rb_root));
49 if (transaction->delayed_refs.pending_csums)
50 btrfs_err(transaction->fs_info,
51 "pending csums is %llu",
52 transaction->delayed_refs.pending_csums);
54 * If any block groups are found in ->deleted_bgs then it's
55 * because the transaction was aborted and a commit did not
56 * happen (things failed before writing the new superblock
57 * and calling btrfs_finish_extent_commit()), so we can not
58 * discard the physical locations of the block groups.
60 while (!list_empty(&transaction->deleted_bgs)) {
61 struct btrfs_block_group_cache *cache;
63 cache = list_first_entry(&transaction->deleted_bgs,
64 struct btrfs_block_group_cache,
66 list_del_init(&cache->bg_list);
67 btrfs_put_block_group_trimming(cache);
68 btrfs_put_block_group(cache);
70 WARN_ON(!list_empty(&transaction->dev_update_list));
75 static noinline void switch_commit_roots(struct btrfs_transaction *trans)
77 struct btrfs_fs_info *fs_info = trans->fs_info;
78 struct btrfs_root *root, *tmp;
80 down_write(&fs_info->commit_root_sem);
81 list_for_each_entry_safe(root, tmp, &trans->switch_commits,
83 list_del_init(&root->dirty_list);
84 free_extent_buffer(root->commit_root);
85 root->commit_root = btrfs_root_node(root);
86 if (is_fstree(root->root_key.objectid))
87 btrfs_unpin_free_ino(root);
88 extent_io_tree_release(&root->dirty_log_pages);
89 btrfs_qgroup_clean_swapped_blocks(root);
92 /* We can free old roots now. */
93 spin_lock(&trans->dropped_roots_lock);
94 while (!list_empty(&trans->dropped_roots)) {
95 root = list_first_entry(&trans->dropped_roots,
96 struct btrfs_root, root_list);
97 list_del_init(&root->root_list);
98 spin_unlock(&trans->dropped_roots_lock);
99 btrfs_drop_and_free_fs_root(fs_info, root);
100 spin_lock(&trans->dropped_roots_lock);
102 spin_unlock(&trans->dropped_roots_lock);
103 up_write(&fs_info->commit_root_sem);
106 static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
109 if (type & TRANS_EXTWRITERS)
110 atomic_inc(&trans->num_extwriters);
113 static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
116 if (type & TRANS_EXTWRITERS)
117 atomic_dec(&trans->num_extwriters);
120 static inline void extwriter_counter_init(struct btrfs_transaction *trans,
123 atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
126 static inline int extwriter_counter_read(struct btrfs_transaction *trans)
128 return atomic_read(&trans->num_extwriters);
132 * To be called after all the new block groups attached to the transaction
133 * handle have been created (btrfs_create_pending_block_groups()).
135 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
137 struct btrfs_fs_info *fs_info = trans->fs_info;
139 if (!trans->chunk_bytes_reserved)
142 WARN_ON_ONCE(!list_empty(&trans->new_bgs));
144 btrfs_block_rsv_release(fs_info, &fs_info->chunk_block_rsv,
145 trans->chunk_bytes_reserved);
146 trans->chunk_bytes_reserved = 0;
150 * either allocate a new transaction or hop into the existing one
152 static noinline int join_transaction(struct btrfs_fs_info *fs_info,
155 struct btrfs_transaction *cur_trans;
157 spin_lock(&fs_info->trans_lock);
159 /* The file system has been taken offline. No new transactions. */
160 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
161 spin_unlock(&fs_info->trans_lock);
165 cur_trans = fs_info->running_transaction;
167 if (cur_trans->aborted) {
168 spin_unlock(&fs_info->trans_lock);
169 return cur_trans->aborted;
171 if (btrfs_blocked_trans_types[cur_trans->state] & type) {
172 spin_unlock(&fs_info->trans_lock);
175 refcount_inc(&cur_trans->use_count);
176 atomic_inc(&cur_trans->num_writers);
177 extwriter_counter_inc(cur_trans, type);
178 spin_unlock(&fs_info->trans_lock);
181 spin_unlock(&fs_info->trans_lock);
184 * If we are ATTACH, we just want to catch the current transaction,
185 * and commit it. If there is no transaction, just return ENOENT.
187 if (type == TRANS_ATTACH)
191 * JOIN_NOLOCK only happens during the transaction commit, so
192 * it is impossible that ->running_transaction is NULL
194 BUG_ON(type == TRANS_JOIN_NOLOCK);
196 cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
200 spin_lock(&fs_info->trans_lock);
201 if (fs_info->running_transaction) {
203 * someone started a transaction after we unlocked. Make sure
204 * to redo the checks above
208 } else if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
209 spin_unlock(&fs_info->trans_lock);
214 cur_trans->fs_info = fs_info;
215 atomic_set(&cur_trans->num_writers, 1);
216 extwriter_counter_init(cur_trans, type);
217 init_waitqueue_head(&cur_trans->writer_wait);
218 init_waitqueue_head(&cur_trans->commit_wait);
219 cur_trans->state = TRANS_STATE_RUNNING;
221 * One for this trans handle, one so it will live on until we
222 * commit the transaction.
224 refcount_set(&cur_trans->use_count, 2);
225 cur_trans->flags = 0;
226 cur_trans->start_time = ktime_get_seconds();
228 memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
230 cur_trans->delayed_refs.href_root = RB_ROOT_CACHED;
231 cur_trans->delayed_refs.dirty_extent_root = RB_ROOT;
232 atomic_set(&cur_trans->delayed_refs.num_entries, 0);
235 * although the tree mod log is per file system and not per transaction,
236 * the log must never go across transaction boundaries.
239 if (!list_empty(&fs_info->tree_mod_seq_list))
240 WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
241 if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
242 WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
243 atomic64_set(&fs_info->tree_mod_seq, 0);
245 spin_lock_init(&cur_trans->delayed_refs.lock);
247 INIT_LIST_HEAD(&cur_trans->pending_snapshots);
248 INIT_LIST_HEAD(&cur_trans->dev_update_list);
249 INIT_LIST_HEAD(&cur_trans->switch_commits);
250 INIT_LIST_HEAD(&cur_trans->dirty_bgs);
251 INIT_LIST_HEAD(&cur_trans->io_bgs);
252 INIT_LIST_HEAD(&cur_trans->dropped_roots);
253 mutex_init(&cur_trans->cache_write_mutex);
254 spin_lock_init(&cur_trans->dirty_bgs_lock);
255 INIT_LIST_HEAD(&cur_trans->deleted_bgs);
256 spin_lock_init(&cur_trans->dropped_roots_lock);
257 list_add_tail(&cur_trans->list, &fs_info->trans_list);
258 extent_io_tree_init(fs_info, &cur_trans->dirty_pages,
259 IO_TREE_TRANS_DIRTY_PAGES, fs_info->btree_inode);
260 fs_info->generation++;
261 cur_trans->transid = fs_info->generation;
262 fs_info->running_transaction = cur_trans;
263 cur_trans->aborted = 0;
264 spin_unlock(&fs_info->trans_lock);
270 * this does all the record keeping required to make sure that a reference
271 * counted root is properly recorded in a given transaction. This is required
272 * to make sure the old root from before we joined the transaction is deleted
273 * when the transaction commits
275 static int record_root_in_trans(struct btrfs_trans_handle *trans,
276 struct btrfs_root *root,
279 struct btrfs_fs_info *fs_info = root->fs_info;
281 if ((test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
282 root->last_trans < trans->transid) || force) {
283 WARN_ON(root == fs_info->extent_root);
284 WARN_ON(!force && root->commit_root != root->node);
287 * see below for IN_TRANS_SETUP usage rules
288 * we have the reloc mutex held now, so there
289 * is only one writer in this function
291 set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
293 /* make sure readers find IN_TRANS_SETUP before
294 * they find our root->last_trans update
298 spin_lock(&fs_info->fs_roots_radix_lock);
299 if (root->last_trans == trans->transid && !force) {
300 spin_unlock(&fs_info->fs_roots_radix_lock);
303 radix_tree_tag_set(&fs_info->fs_roots_radix,
304 (unsigned long)root->root_key.objectid,
305 BTRFS_ROOT_TRANS_TAG);
306 spin_unlock(&fs_info->fs_roots_radix_lock);
307 root->last_trans = trans->transid;
309 /* this is pretty tricky. We don't want to
310 * take the relocation lock in btrfs_record_root_in_trans
311 * unless we're really doing the first setup for this root in
314 * Normally we'd use root->last_trans as a flag to decide
315 * if we want to take the expensive mutex.
317 * But, we have to set root->last_trans before we
318 * init the relocation root, otherwise, we trip over warnings
319 * in ctree.c. The solution used here is to flag ourselves
320 * with root IN_TRANS_SETUP. When this is 1, we're still
321 * fixing up the reloc trees and everyone must wait.
323 * When this is zero, they can trust root->last_trans and fly
324 * through btrfs_record_root_in_trans without having to take the
325 * lock. smp_wmb() makes sure that all the writes above are
326 * done before we pop in the zero below
328 btrfs_init_reloc_root(trans, root);
329 smp_mb__before_atomic();
330 clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
336 void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
337 struct btrfs_root *root)
339 struct btrfs_fs_info *fs_info = root->fs_info;
340 struct btrfs_transaction *cur_trans = trans->transaction;
342 /* Add ourselves to the transaction dropped list */
343 spin_lock(&cur_trans->dropped_roots_lock);
344 list_add_tail(&root->root_list, &cur_trans->dropped_roots);
345 spin_unlock(&cur_trans->dropped_roots_lock);
347 /* Make sure we don't try to update the root at commit time */
348 spin_lock(&fs_info->fs_roots_radix_lock);
349 radix_tree_tag_clear(&fs_info->fs_roots_radix,
350 (unsigned long)root->root_key.objectid,
351 BTRFS_ROOT_TRANS_TAG);
352 spin_unlock(&fs_info->fs_roots_radix_lock);
355 int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
356 struct btrfs_root *root)
358 struct btrfs_fs_info *fs_info = root->fs_info;
360 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
364 * see record_root_in_trans for comments about IN_TRANS_SETUP usage
368 if (root->last_trans == trans->transid &&
369 !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
372 mutex_lock(&fs_info->reloc_mutex);
373 record_root_in_trans(trans, root, 0);
374 mutex_unlock(&fs_info->reloc_mutex);
379 static inline int is_transaction_blocked(struct btrfs_transaction *trans)
381 return (trans->state >= TRANS_STATE_BLOCKED &&
382 trans->state < TRANS_STATE_UNBLOCKED &&
386 /* wait for commit against the current transaction to become unblocked
387 * when this is done, it is safe to start a new transaction, but the current
388 * transaction might not be fully on disk.
390 static void wait_current_trans(struct btrfs_fs_info *fs_info)
392 struct btrfs_transaction *cur_trans;
394 spin_lock(&fs_info->trans_lock);
395 cur_trans = fs_info->running_transaction;
396 if (cur_trans && is_transaction_blocked(cur_trans)) {
397 refcount_inc(&cur_trans->use_count);
398 spin_unlock(&fs_info->trans_lock);
400 wait_event(fs_info->transaction_wait,
401 cur_trans->state >= TRANS_STATE_UNBLOCKED ||
403 btrfs_put_transaction(cur_trans);
405 spin_unlock(&fs_info->trans_lock);
409 static int may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
411 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
414 if (type == TRANS_START)
420 static inline bool need_reserve_reloc_root(struct btrfs_root *root)
422 struct btrfs_fs_info *fs_info = root->fs_info;
424 if (!fs_info->reloc_ctl ||
425 !test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
426 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
433 static struct btrfs_trans_handle *
434 start_transaction(struct btrfs_root *root, unsigned int num_items,
435 unsigned int type, enum btrfs_reserve_flush_enum flush,
436 bool enforce_qgroups)
438 struct btrfs_fs_info *fs_info = root->fs_info;
439 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
440 struct btrfs_trans_handle *h;
441 struct btrfs_transaction *cur_trans;
443 u64 qgroup_reserved = 0;
444 bool reloc_reserved = false;
447 /* Send isn't supposed to start transactions. */
448 ASSERT(current->journal_info != BTRFS_SEND_TRANS_STUB);
450 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
451 return ERR_PTR(-EROFS);
453 if (current->journal_info) {
454 WARN_ON(type & TRANS_EXTWRITERS);
455 h = current->journal_info;
456 refcount_inc(&h->use_count);
457 WARN_ON(refcount_read(&h->use_count) > 2);
458 h->orig_rsv = h->block_rsv;
464 * Do the reservation before we join the transaction so we can do all
465 * the appropriate flushing if need be.
467 if (num_items && root != fs_info->chunk_root) {
468 struct btrfs_block_rsv *rsv = &fs_info->trans_block_rsv;
469 u64 delayed_refs_bytes = 0;
471 qgroup_reserved = num_items * fs_info->nodesize;
472 ret = btrfs_qgroup_reserve_meta_pertrans(root, qgroup_reserved,
478 * We want to reserve all the bytes we may need all at once, so
479 * we only do 1 enospc flushing cycle per transaction start. We
480 * accomplish this by simply assuming we'll do 2 x num_items
481 * worth of delayed refs updates in this trans handle, and
482 * refill that amount for whatever is missing in the reserve.
484 num_bytes = btrfs_calc_trans_metadata_size(fs_info, num_items);
485 if (delayed_refs_rsv->full == 0) {
486 delayed_refs_bytes = num_bytes;
491 * Do the reservation for the relocation root creation
493 if (need_reserve_reloc_root(root)) {
494 num_bytes += fs_info->nodesize;
495 reloc_reserved = true;
498 ret = btrfs_block_rsv_add(root, rsv, num_bytes, flush);
501 if (delayed_refs_bytes) {
502 btrfs_migrate_to_delayed_refs_rsv(fs_info, rsv,
504 num_bytes -= delayed_refs_bytes;
506 } else if (num_items == 0 && flush == BTRFS_RESERVE_FLUSH_ALL &&
507 !delayed_refs_rsv->full) {
509 * Some people call with btrfs_start_transaction(root, 0)
510 * because they can be throttled, but have some other mechanism
511 * for reserving space. We still want these guys to refill the
512 * delayed block_rsv so just add 1 items worth of reservation
515 ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
520 h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
527 * If we are JOIN_NOLOCK we're already committing a transaction and
528 * waiting on this guy, so we don't need to do the sb_start_intwrite
529 * because we're already holding a ref. We need this because we could
530 * have raced in and did an fsync() on a file which can kick a commit
531 * and then we deadlock with somebody doing a freeze.
533 * If we are ATTACH, it means we just want to catch the current
534 * transaction and commit it, so we needn't do sb_start_intwrite().
536 if (type & __TRANS_FREEZABLE)
537 sb_start_intwrite(fs_info->sb);
539 if (may_wait_transaction(fs_info, type))
540 wait_current_trans(fs_info);
543 ret = join_transaction(fs_info, type);
545 wait_current_trans(fs_info);
546 if (unlikely(type == TRANS_ATTACH))
549 } while (ret == -EBUSY);
554 cur_trans = fs_info->running_transaction;
556 h->transid = cur_trans->transid;
557 h->transaction = cur_trans;
559 refcount_set(&h->use_count, 1);
560 h->fs_info = root->fs_info;
563 h->can_flush_pending_bgs = true;
564 INIT_LIST_HEAD(&h->new_bgs);
567 if (cur_trans->state >= TRANS_STATE_BLOCKED &&
568 may_wait_transaction(fs_info, type)) {
569 current->journal_info = h;
570 btrfs_commit_transaction(h);
575 trace_btrfs_space_reservation(fs_info, "transaction",
576 h->transid, num_bytes, 1);
577 h->block_rsv = &fs_info->trans_block_rsv;
578 h->bytes_reserved = num_bytes;
579 h->reloc_reserved = reloc_reserved;
583 btrfs_record_root_in_trans(h, root);
585 if (!current->journal_info)
586 current->journal_info = h;
590 if (type & __TRANS_FREEZABLE)
591 sb_end_intwrite(fs_info->sb);
592 kmem_cache_free(btrfs_trans_handle_cachep, h);
595 btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
598 btrfs_qgroup_free_meta_pertrans(root, qgroup_reserved);
602 struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
603 unsigned int num_items)
605 return start_transaction(root, num_items, TRANS_START,
606 BTRFS_RESERVE_FLUSH_ALL, true);
609 struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
610 struct btrfs_root *root,
611 unsigned int num_items,
614 struct btrfs_fs_info *fs_info = root->fs_info;
615 struct btrfs_trans_handle *trans;
620 * We have two callers: unlink and block group removal. The
621 * former should succeed even if we will temporarily exceed
622 * quota and the latter operates on the extent root so
623 * qgroup enforcement is ignored anyway.
625 trans = start_transaction(root, num_items, TRANS_START,
626 BTRFS_RESERVE_FLUSH_ALL, false);
627 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
630 trans = btrfs_start_transaction(root, 0);
634 num_bytes = btrfs_calc_trans_metadata_size(fs_info, num_items);
635 ret = btrfs_cond_migrate_bytes(fs_info, &fs_info->trans_block_rsv,
636 num_bytes, min_factor);
638 btrfs_end_transaction(trans);
642 trans->block_rsv = &fs_info->trans_block_rsv;
643 trans->bytes_reserved = num_bytes;
644 trace_btrfs_space_reservation(fs_info, "transaction",
645 trans->transid, num_bytes, 1);
650 struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
652 return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
656 struct btrfs_trans_handle *btrfs_join_transaction_nolock(struct btrfs_root *root)
658 return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
659 BTRFS_RESERVE_NO_FLUSH, true);
663 * btrfs_attach_transaction() - catch the running transaction
665 * It is used when we want to commit the current the transaction, but
666 * don't want to start a new one.
668 * Note: If this function return -ENOENT, it just means there is no
669 * running transaction. But it is possible that the inactive transaction
670 * is still in the memory, not fully on disk. If you hope there is no
671 * inactive transaction in the fs when -ENOENT is returned, you should
673 * btrfs_attach_transaction_barrier()
675 struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
677 return start_transaction(root, 0, TRANS_ATTACH,
678 BTRFS_RESERVE_NO_FLUSH, true);
682 * btrfs_attach_transaction_barrier() - catch the running transaction
684 * It is similar to the above function, the difference is this one
685 * will wait for all the inactive transactions until they fully
688 struct btrfs_trans_handle *
689 btrfs_attach_transaction_barrier(struct btrfs_root *root)
691 struct btrfs_trans_handle *trans;
693 trans = start_transaction(root, 0, TRANS_ATTACH,
694 BTRFS_RESERVE_NO_FLUSH, true);
695 if (trans == ERR_PTR(-ENOENT))
696 btrfs_wait_for_commit(root->fs_info, 0);
701 /* wait for a transaction commit to be fully complete */
702 static noinline void wait_for_commit(struct btrfs_transaction *commit)
704 wait_event(commit->commit_wait, commit->state == TRANS_STATE_COMPLETED);
707 int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
709 struct btrfs_transaction *cur_trans = NULL, *t;
713 if (transid <= fs_info->last_trans_committed)
716 /* find specified transaction */
717 spin_lock(&fs_info->trans_lock);
718 list_for_each_entry(t, &fs_info->trans_list, list) {
719 if (t->transid == transid) {
721 refcount_inc(&cur_trans->use_count);
725 if (t->transid > transid) {
730 spin_unlock(&fs_info->trans_lock);
733 * The specified transaction doesn't exist, or we
734 * raced with btrfs_commit_transaction
737 if (transid > fs_info->last_trans_committed)
742 /* find newest transaction that is committing | committed */
743 spin_lock(&fs_info->trans_lock);
744 list_for_each_entry_reverse(t, &fs_info->trans_list,
746 if (t->state >= TRANS_STATE_COMMIT_START) {
747 if (t->state == TRANS_STATE_COMPLETED)
750 refcount_inc(&cur_trans->use_count);
754 spin_unlock(&fs_info->trans_lock);
756 goto out; /* nothing committing|committed */
759 wait_for_commit(cur_trans);
760 btrfs_put_transaction(cur_trans);
765 void btrfs_throttle(struct btrfs_fs_info *fs_info)
767 wait_current_trans(fs_info);
770 static int should_end_transaction(struct btrfs_trans_handle *trans)
772 struct btrfs_fs_info *fs_info = trans->fs_info;
774 if (btrfs_check_space_for_delayed_refs(fs_info))
777 return !!btrfs_block_rsv_check(&fs_info->global_block_rsv, 5);
780 int btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
782 struct btrfs_transaction *cur_trans = trans->transaction;
785 if (cur_trans->state >= TRANS_STATE_BLOCKED ||
786 cur_trans->delayed_refs.flushing)
789 return should_end_transaction(trans);
792 static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
795 struct btrfs_fs_info *fs_info = trans->fs_info;
797 if (!trans->block_rsv) {
798 ASSERT(!trans->bytes_reserved);
802 if (!trans->bytes_reserved)
805 ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
806 trace_btrfs_space_reservation(fs_info, "transaction",
807 trans->transid, trans->bytes_reserved, 0);
808 btrfs_block_rsv_release(fs_info, trans->block_rsv,
809 trans->bytes_reserved);
810 trans->bytes_reserved = 0;
813 static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
816 struct btrfs_fs_info *info = trans->fs_info;
817 struct btrfs_transaction *cur_trans = trans->transaction;
818 int lock = (trans->type != TRANS_JOIN_NOLOCK);
821 if (refcount_read(&trans->use_count) > 1) {
822 refcount_dec(&trans->use_count);
823 trans->block_rsv = trans->orig_rsv;
827 btrfs_trans_release_metadata(trans);
828 trans->block_rsv = NULL;
830 btrfs_create_pending_block_groups(trans);
832 btrfs_trans_release_chunk_metadata(trans);
834 if (lock && READ_ONCE(cur_trans->state) == TRANS_STATE_BLOCKED) {
836 return btrfs_commit_transaction(trans);
838 wake_up_process(info->transaction_kthread);
841 if (trans->type & __TRANS_FREEZABLE)
842 sb_end_intwrite(info->sb);
844 WARN_ON(cur_trans != info->running_transaction);
845 WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
846 atomic_dec(&cur_trans->num_writers);
847 extwriter_counter_dec(cur_trans, trans->type);
849 cond_wake_up(&cur_trans->writer_wait);
850 btrfs_put_transaction(cur_trans);
852 if (current->journal_info == trans)
853 current->journal_info = NULL;
856 btrfs_run_delayed_iputs(info);
858 if (trans->aborted ||
859 test_bit(BTRFS_FS_STATE_ERROR, &info->fs_state)) {
860 wake_up_process(info->transaction_kthread);
864 kmem_cache_free(btrfs_trans_handle_cachep, trans);
868 int btrfs_end_transaction(struct btrfs_trans_handle *trans)
870 return __btrfs_end_transaction(trans, 0);
873 int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
875 return __btrfs_end_transaction(trans, 1);
879 * when btree blocks are allocated, they have some corresponding bits set for
880 * them in one of two extent_io trees. This is used to make sure all of
881 * those extents are sent to disk but does not wait on them
883 int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
884 struct extent_io_tree *dirty_pages, int mark)
888 struct address_space *mapping = fs_info->btree_inode->i_mapping;
889 struct extent_state *cached_state = NULL;
893 atomic_inc(&BTRFS_I(fs_info->btree_inode)->sync_writers);
894 while (!find_first_extent_bit(dirty_pages, start, &start, &end,
895 mark, &cached_state)) {
896 bool wait_writeback = false;
898 err = convert_extent_bit(dirty_pages, start, end,
900 mark, &cached_state);
902 * convert_extent_bit can return -ENOMEM, which is most of the
903 * time a temporary error. So when it happens, ignore the error
904 * and wait for writeback of this range to finish - because we
905 * failed to set the bit EXTENT_NEED_WAIT for the range, a call
906 * to __btrfs_wait_marked_extents() would not know that
907 * writeback for this range started and therefore wouldn't
908 * wait for it to finish - we don't want to commit a
909 * superblock that points to btree nodes/leafs for which
910 * writeback hasn't finished yet (and without errors).
911 * We cleanup any entries left in the io tree when committing
912 * the transaction (through extent_io_tree_release()).
914 if (err == -ENOMEM) {
916 wait_writeback = true;
919 err = filemap_fdatawrite_range(mapping, start, end);
922 else if (wait_writeback)
923 werr = filemap_fdatawait_range(mapping, start, end);
924 free_extent_state(cached_state);
929 atomic_dec(&BTRFS_I(fs_info->btree_inode)->sync_writers);
934 * when btree blocks are allocated, they have some corresponding bits set for
935 * them in one of two extent_io trees. This is used to make sure all of
936 * those extents are on disk for transaction or log commit. We wait
937 * on all the pages and clear them from the dirty pages state tree
939 static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
940 struct extent_io_tree *dirty_pages)
944 struct address_space *mapping = fs_info->btree_inode->i_mapping;
945 struct extent_state *cached_state = NULL;
949 while (!find_first_extent_bit(dirty_pages, start, &start, &end,
950 EXTENT_NEED_WAIT, &cached_state)) {
952 * Ignore -ENOMEM errors returned by clear_extent_bit().
953 * When committing the transaction, we'll remove any entries
954 * left in the io tree. For a log commit, we don't remove them
955 * after committing the log because the tree can be accessed
956 * concurrently - we do it only at transaction commit time when
957 * it's safe to do it (through extent_io_tree_release()).
959 err = clear_extent_bit(dirty_pages, start, end,
960 EXTENT_NEED_WAIT, 0, 0, &cached_state);
964 err = filemap_fdatawait_range(mapping, start, end);
967 free_extent_state(cached_state);
977 int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
978 struct extent_io_tree *dirty_pages)
983 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
984 if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
992 int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
994 struct btrfs_fs_info *fs_info = log_root->fs_info;
995 struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
999 ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
1001 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1002 if ((mark & EXTENT_DIRTY) &&
1003 test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1006 if ((mark & EXTENT_NEW) &&
1007 test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1016 * When btree blocks are allocated the corresponding extents are marked dirty.
1017 * This function ensures such extents are persisted on disk for transaction or
1020 * @trans: transaction whose dirty pages we'd like to write
1022 static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1026 struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
1027 struct btrfs_fs_info *fs_info = trans->fs_info;
1028 struct blk_plug plug;
1030 blk_start_plug(&plug);
1031 ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1032 blk_finish_plug(&plug);
1033 ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1035 extent_io_tree_release(&trans->transaction->dirty_pages);
1046 * this is used to update the root pointer in the tree of tree roots.
1048 * But, in the case of the extent allocation tree, updating the root
1049 * pointer may allocate blocks which may change the root of the extent
1052 * So, this loops and repeats and makes sure the cowonly root didn't
1053 * change while the root pointer was being updated in the metadata.
1055 static int update_cowonly_root(struct btrfs_trans_handle *trans,
1056 struct btrfs_root *root)
1059 u64 old_root_bytenr;
1061 struct btrfs_fs_info *fs_info = root->fs_info;
1062 struct btrfs_root *tree_root = fs_info->tree_root;
1064 old_root_used = btrfs_root_used(&root->root_item);
1067 old_root_bytenr = btrfs_root_bytenr(&root->root_item);
1068 if (old_root_bytenr == root->node->start &&
1069 old_root_used == btrfs_root_used(&root->root_item))
1072 btrfs_set_root_node(&root->root_item, root->node);
1073 ret = btrfs_update_root(trans, tree_root,
1079 old_root_used = btrfs_root_used(&root->root_item);
1086 * update all the cowonly tree roots on disk
1088 * The error handling in this function may not be obvious. Any of the
1089 * failures will cause the file system to go offline. We still need
1090 * to clean up the delayed refs.
1092 static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
1094 struct btrfs_fs_info *fs_info = trans->fs_info;
1095 struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
1096 struct list_head *io_bgs = &trans->transaction->io_bgs;
1097 struct list_head *next;
1098 struct extent_buffer *eb;
1101 eb = btrfs_lock_root_node(fs_info->tree_root);
1102 ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
1104 btrfs_tree_unlock(eb);
1105 free_extent_buffer(eb);
1110 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1114 ret = btrfs_run_dev_stats(trans);
1117 ret = btrfs_run_dev_replace(trans);
1120 ret = btrfs_run_qgroups(trans);
1124 ret = btrfs_setup_space_cache(trans);
1128 /* run_qgroups might have added some more refs */
1129 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1133 while (!list_empty(&fs_info->dirty_cowonly_roots)) {
1134 struct btrfs_root *root;
1135 next = fs_info->dirty_cowonly_roots.next;
1136 list_del_init(next);
1137 root = list_entry(next, struct btrfs_root, dirty_list);
1138 clear_bit(BTRFS_ROOT_DIRTY, &root->state);
1140 if (root != fs_info->extent_root)
1141 list_add_tail(&root->dirty_list,
1142 &trans->transaction->switch_commits);
1143 ret = update_cowonly_root(trans, root);
1146 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1151 while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
1152 ret = btrfs_write_dirty_block_groups(trans);
1155 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1160 if (!list_empty(&fs_info->dirty_cowonly_roots))
1163 list_add_tail(&fs_info->extent_root->dirty_list,
1164 &trans->transaction->switch_commits);
1166 /* Update dev-replace pointer once everything is committed */
1167 fs_info->dev_replace.committed_cursor_left =
1168 fs_info->dev_replace.cursor_left_last_write_of_item;
1174 * dead roots are old snapshots that need to be deleted. This allocates
1175 * a dirty root struct and adds it into the list of dead roots that need to
1178 void btrfs_add_dead_root(struct btrfs_root *root)
1180 struct btrfs_fs_info *fs_info = root->fs_info;
1182 spin_lock(&fs_info->trans_lock);
1183 if (list_empty(&root->root_list))
1184 list_add_tail(&root->root_list, &fs_info->dead_roots);
1185 spin_unlock(&fs_info->trans_lock);
1189 * update all the cowonly tree roots on disk
1191 static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
1193 struct btrfs_fs_info *fs_info = trans->fs_info;
1194 struct btrfs_root *gang[8];
1199 spin_lock(&fs_info->fs_roots_radix_lock);
1201 ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
1204 BTRFS_ROOT_TRANS_TAG);
1207 for (i = 0; i < ret; i++) {
1208 struct btrfs_root *root = gang[i];
1209 radix_tree_tag_clear(&fs_info->fs_roots_radix,
1210 (unsigned long)root->root_key.objectid,
1211 BTRFS_ROOT_TRANS_TAG);
1212 spin_unlock(&fs_info->fs_roots_radix_lock);
1214 btrfs_free_log(trans, root);
1215 btrfs_update_reloc_root(trans, root);
1217 btrfs_save_ino_cache(root, trans);
1219 /* see comments in should_cow_block() */
1220 clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1221 smp_mb__after_atomic();
1223 if (root->commit_root != root->node) {
1224 list_add_tail(&root->dirty_list,
1225 &trans->transaction->switch_commits);
1226 btrfs_set_root_node(&root->root_item,
1230 err = btrfs_update_root(trans, fs_info->tree_root,
1233 spin_lock(&fs_info->fs_roots_radix_lock);
1236 btrfs_qgroup_free_meta_all_pertrans(root);
1239 spin_unlock(&fs_info->fs_roots_radix_lock);
1244 * defrag a given btree.
1245 * Every leaf in the btree is read and defragged.
1247 int btrfs_defrag_root(struct btrfs_root *root)
1249 struct btrfs_fs_info *info = root->fs_info;
1250 struct btrfs_trans_handle *trans;
1253 if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
1257 trans = btrfs_start_transaction(root, 0);
1259 return PTR_ERR(trans);
1261 ret = btrfs_defrag_leaves(trans, root);
1263 btrfs_end_transaction(trans);
1264 btrfs_btree_balance_dirty(info);
1267 if (btrfs_fs_closing(info) || ret != -EAGAIN)
1270 if (btrfs_defrag_cancelled(info)) {
1271 btrfs_debug(info, "defrag_root cancelled");
1276 clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
1281 * Do all special snapshot related qgroup dirty hack.
1283 * Will do all needed qgroup inherit and dirty hack like switch commit
1284 * roots inside one transaction and write all btree into disk, to make
1287 static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
1288 struct btrfs_root *src,
1289 struct btrfs_root *parent,
1290 struct btrfs_qgroup_inherit *inherit,
1293 struct btrfs_fs_info *fs_info = src->fs_info;
1297 * Save some performance in the case that qgroups are not
1298 * enabled. If this check races with the ioctl, rescan will
1301 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1305 * Ensure dirty @src will be committed. Or, after coming
1306 * commit_fs_roots() and switch_commit_roots(), any dirty but not
1307 * recorded root will never be updated again, causing an outdated root
1310 record_root_in_trans(trans, src, 1);
1313 * We are going to commit transaction, see btrfs_commit_transaction()
1314 * comment for reason locking tree_log_mutex
1316 mutex_lock(&fs_info->tree_log_mutex);
1318 ret = commit_fs_roots(trans);
1321 ret = btrfs_qgroup_account_extents(trans);
1325 /* Now qgroup are all updated, we can inherit it to new qgroups */
1326 ret = btrfs_qgroup_inherit(trans, src->root_key.objectid, dst_objectid,
1332 * Now we do a simplified commit transaction, which will:
1333 * 1) commit all subvolume and extent tree
1334 * To ensure all subvolume and extent tree have a valid
1335 * commit_root to accounting later insert_dir_item()
1336 * 2) write all btree blocks onto disk
1337 * This is to make sure later btree modification will be cowed
1338 * Or commit_root can be populated and cause wrong qgroup numbers
1339 * In this simplified commit, we don't really care about other trees
1340 * like chunk and root tree, as they won't affect qgroup.
1341 * And we don't write super to avoid half committed status.
1343 ret = commit_cowonly_roots(trans);
1346 switch_commit_roots(trans->transaction);
1347 ret = btrfs_write_and_wait_transaction(trans);
1349 btrfs_handle_fs_error(fs_info, ret,
1350 "Error while writing out transaction for qgroup");
1353 mutex_unlock(&fs_info->tree_log_mutex);
1356 * Force parent root to be updated, as we recorded it before so its
1357 * last_trans == cur_transid.
1358 * Or it won't be committed again onto disk after later
1362 record_root_in_trans(trans, parent, 1);
1367 * new snapshots need to be created at a very specific time in the
1368 * transaction commit. This does the actual creation.
1371 * If the error which may affect the commitment of the current transaction
1372 * happens, we should return the error number. If the error which just affect
1373 * the creation of the pending snapshots, just return 0.
1375 static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
1376 struct btrfs_pending_snapshot *pending)
1379 struct btrfs_fs_info *fs_info = trans->fs_info;
1380 struct btrfs_key key;
1381 struct btrfs_root_item *new_root_item;
1382 struct btrfs_root *tree_root = fs_info->tree_root;
1383 struct btrfs_root *root = pending->root;
1384 struct btrfs_root *parent_root;
1385 struct btrfs_block_rsv *rsv;
1386 struct inode *parent_inode;
1387 struct btrfs_path *path;
1388 struct btrfs_dir_item *dir_item;
1389 struct dentry *dentry;
1390 struct extent_buffer *tmp;
1391 struct extent_buffer *old;
1392 struct timespec64 cur_time;
1400 ASSERT(pending->path);
1401 path = pending->path;
1403 ASSERT(pending->root_item);
1404 new_root_item = pending->root_item;
1406 pending->error = btrfs_find_free_objectid(tree_root, &objectid);
1408 goto no_free_objectid;
1411 * Make qgroup to skip current new snapshot's qgroupid, as it is
1412 * accounted by later btrfs_qgroup_inherit().
1414 btrfs_set_skip_qgroup(trans, objectid);
1416 btrfs_reloc_pre_snapshot(pending, &to_reserve);
1418 if (to_reserve > 0) {
1419 pending->error = btrfs_block_rsv_add(root,
1420 &pending->block_rsv,
1422 BTRFS_RESERVE_NO_FLUSH);
1424 goto clear_skip_qgroup;
1427 key.objectid = objectid;
1428 key.offset = (u64)-1;
1429 key.type = BTRFS_ROOT_ITEM_KEY;
1431 rsv = trans->block_rsv;
1432 trans->block_rsv = &pending->block_rsv;
1433 trans->bytes_reserved = trans->block_rsv->reserved;
1434 trace_btrfs_space_reservation(fs_info, "transaction",
1436 trans->bytes_reserved, 1);
1437 dentry = pending->dentry;
1438 parent_inode = pending->dir;
1439 parent_root = BTRFS_I(parent_inode)->root;
1440 record_root_in_trans(trans, parent_root, 0);
1442 cur_time = current_time(parent_inode);
1445 * insert the directory item
1447 ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
1448 BUG_ON(ret); /* -ENOMEM */
1450 /* check if there is a file/dir which has the same name. */
1451 dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
1452 btrfs_ino(BTRFS_I(parent_inode)),
1453 dentry->d_name.name,
1454 dentry->d_name.len, 0);
1455 if (dir_item != NULL && !IS_ERR(dir_item)) {
1456 pending->error = -EEXIST;
1457 goto dir_item_existed;
1458 } else if (IS_ERR(dir_item)) {
1459 ret = PTR_ERR(dir_item);
1460 btrfs_abort_transaction(trans, ret);
1463 btrfs_release_path(path);
1466 * pull in the delayed directory update
1467 * and the delayed inode item
1468 * otherwise we corrupt the FS during
1471 ret = btrfs_run_delayed_items(trans);
1472 if (ret) { /* Transaction aborted */
1473 btrfs_abort_transaction(trans, ret);
1477 record_root_in_trans(trans, root, 0);
1478 btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
1479 memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
1480 btrfs_check_and_init_root_item(new_root_item);
1482 root_flags = btrfs_root_flags(new_root_item);
1483 if (pending->readonly)
1484 root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1486 root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1487 btrfs_set_root_flags(new_root_item, root_flags);
1489 btrfs_set_root_generation_v2(new_root_item,
1491 uuid_le_gen(&new_uuid);
1492 memcpy(new_root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
1493 memcpy(new_root_item->parent_uuid, root->root_item.uuid,
1495 if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
1496 memset(new_root_item->received_uuid, 0,
1497 sizeof(new_root_item->received_uuid));
1498 memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
1499 memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
1500 btrfs_set_root_stransid(new_root_item, 0);
1501 btrfs_set_root_rtransid(new_root_item, 0);
1503 btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
1504 btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
1505 btrfs_set_root_otransid(new_root_item, trans->transid);
1507 old = btrfs_lock_root_node(root);
1508 ret = btrfs_cow_block(trans, root, old, NULL, 0, &old);
1510 btrfs_tree_unlock(old);
1511 free_extent_buffer(old);
1512 btrfs_abort_transaction(trans, ret);
1516 btrfs_set_lock_blocking_write(old);
1518 ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
1519 /* clean up in any case */
1520 btrfs_tree_unlock(old);
1521 free_extent_buffer(old);
1523 btrfs_abort_transaction(trans, ret);
1526 /* see comments in should_cow_block() */
1527 set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1530 btrfs_set_root_node(new_root_item, tmp);
1531 /* record when the snapshot was created in key.offset */
1532 key.offset = trans->transid;
1533 ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1534 btrfs_tree_unlock(tmp);
1535 free_extent_buffer(tmp);
1537 btrfs_abort_transaction(trans, ret);
1542 * insert root back/forward references
1544 ret = btrfs_add_root_ref(trans, objectid,
1545 parent_root->root_key.objectid,
1546 btrfs_ino(BTRFS_I(parent_inode)), index,
1547 dentry->d_name.name, dentry->d_name.len);
1549 btrfs_abort_transaction(trans, ret);
1553 key.offset = (u64)-1;
1554 pending->snap = btrfs_read_fs_root_no_name(fs_info, &key);
1555 if (IS_ERR(pending->snap)) {
1556 ret = PTR_ERR(pending->snap);
1557 btrfs_abort_transaction(trans, ret);
1561 ret = btrfs_reloc_post_snapshot(trans, pending);
1563 btrfs_abort_transaction(trans, ret);
1567 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1569 btrfs_abort_transaction(trans, ret);
1574 * Do special qgroup accounting for snapshot, as we do some qgroup
1575 * snapshot hack to do fast snapshot.
1576 * To co-operate with that hack, we do hack again.
1577 * Or snapshot will be greatly slowed down by a subtree qgroup rescan
1579 ret = qgroup_account_snapshot(trans, root, parent_root,
1580 pending->inherit, objectid);
1584 ret = btrfs_insert_dir_item(trans, dentry->d_name.name,
1585 dentry->d_name.len, BTRFS_I(parent_inode),
1586 &key, BTRFS_FT_DIR, index);
1587 /* We have check then name at the beginning, so it is impossible. */
1588 BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
1590 btrfs_abort_transaction(trans, ret);
1594 btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
1595 dentry->d_name.len * 2);
1596 parent_inode->i_mtime = parent_inode->i_ctime =
1597 current_time(parent_inode);
1598 ret = btrfs_update_inode_fallback(trans, parent_root, parent_inode);
1600 btrfs_abort_transaction(trans, ret);
1603 ret = btrfs_uuid_tree_add(trans, new_uuid.b, BTRFS_UUID_KEY_SUBVOL,
1606 btrfs_abort_transaction(trans, ret);
1609 if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1610 ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1611 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1613 if (ret && ret != -EEXIST) {
1614 btrfs_abort_transaction(trans, ret);
1619 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1621 btrfs_abort_transaction(trans, ret);
1626 pending->error = ret;
1628 trans->block_rsv = rsv;
1629 trans->bytes_reserved = 0;
1631 btrfs_clear_skip_qgroup(trans);
1633 kfree(new_root_item);
1634 pending->root_item = NULL;
1635 btrfs_free_path(path);
1636 pending->path = NULL;
1642 * create all the snapshots we've scheduled for creation
1644 static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
1646 struct btrfs_pending_snapshot *pending, *next;
1647 struct list_head *head = &trans->transaction->pending_snapshots;
1650 list_for_each_entry_safe(pending, next, head, list) {
1651 list_del(&pending->list);
1652 ret = create_pending_snapshot(trans, pending);
1659 static void update_super_roots(struct btrfs_fs_info *fs_info)
1661 struct btrfs_root_item *root_item;
1662 struct btrfs_super_block *super;
1664 super = fs_info->super_copy;
1666 root_item = &fs_info->chunk_root->root_item;
1667 super->chunk_root = root_item->bytenr;
1668 super->chunk_root_generation = root_item->generation;
1669 super->chunk_root_level = root_item->level;
1671 root_item = &fs_info->tree_root->root_item;
1672 super->root = root_item->bytenr;
1673 super->generation = root_item->generation;
1674 super->root_level = root_item->level;
1675 if (btrfs_test_opt(fs_info, SPACE_CACHE))
1676 super->cache_generation = root_item->generation;
1677 if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1678 super->uuid_tree_generation = root_item->generation;
1681 int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1683 struct btrfs_transaction *trans;
1686 spin_lock(&info->trans_lock);
1687 trans = info->running_transaction;
1689 ret = (trans->state >= TRANS_STATE_COMMIT_START);
1690 spin_unlock(&info->trans_lock);
1694 int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1696 struct btrfs_transaction *trans;
1699 spin_lock(&info->trans_lock);
1700 trans = info->running_transaction;
1702 ret = is_transaction_blocked(trans);
1703 spin_unlock(&info->trans_lock);
1708 * wait for the current transaction commit to start and block subsequent
1711 static void wait_current_trans_commit_start(struct btrfs_fs_info *fs_info,
1712 struct btrfs_transaction *trans)
1714 wait_event(fs_info->transaction_blocked_wait,
1715 trans->state >= TRANS_STATE_COMMIT_START || trans->aborted);
1719 * wait for the current transaction to start and then become unblocked.
1722 static void wait_current_trans_commit_start_and_unblock(
1723 struct btrfs_fs_info *fs_info,
1724 struct btrfs_transaction *trans)
1726 wait_event(fs_info->transaction_wait,
1727 trans->state >= TRANS_STATE_UNBLOCKED || trans->aborted);
1731 * commit transactions asynchronously. once btrfs_commit_transaction_async
1732 * returns, any subsequent transaction will not be allowed to join.
1734 struct btrfs_async_commit {
1735 struct btrfs_trans_handle *newtrans;
1736 struct work_struct work;
1739 static void do_async_commit(struct work_struct *work)
1741 struct btrfs_async_commit *ac =
1742 container_of(work, struct btrfs_async_commit, work);
1745 * We've got freeze protection passed with the transaction.
1746 * Tell lockdep about it.
1748 if (ac->newtrans->type & __TRANS_FREEZABLE)
1749 __sb_writers_acquired(ac->newtrans->fs_info->sb, SB_FREEZE_FS);
1751 current->journal_info = ac->newtrans;
1753 btrfs_commit_transaction(ac->newtrans);
1757 int btrfs_commit_transaction_async(struct btrfs_trans_handle *trans,
1758 int wait_for_unblock)
1760 struct btrfs_fs_info *fs_info = trans->fs_info;
1761 struct btrfs_async_commit *ac;
1762 struct btrfs_transaction *cur_trans;
1764 ac = kmalloc(sizeof(*ac), GFP_NOFS);
1768 INIT_WORK(&ac->work, do_async_commit);
1769 ac->newtrans = btrfs_join_transaction(trans->root);
1770 if (IS_ERR(ac->newtrans)) {
1771 int err = PTR_ERR(ac->newtrans);
1776 /* take transaction reference */
1777 cur_trans = trans->transaction;
1778 refcount_inc(&cur_trans->use_count);
1780 btrfs_end_transaction(trans);
1783 * Tell lockdep we've released the freeze rwsem, since the
1784 * async commit thread will be the one to unlock it.
1786 if (ac->newtrans->type & __TRANS_FREEZABLE)
1787 __sb_writers_release(fs_info->sb, SB_FREEZE_FS);
1789 schedule_work(&ac->work);
1791 /* wait for transaction to start and unblock */
1792 if (wait_for_unblock)
1793 wait_current_trans_commit_start_and_unblock(fs_info, cur_trans);
1795 wait_current_trans_commit_start(fs_info, cur_trans);
1797 if (current->journal_info == trans)
1798 current->journal_info = NULL;
1800 btrfs_put_transaction(cur_trans);
1805 static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
1807 struct btrfs_fs_info *fs_info = trans->fs_info;
1808 struct btrfs_transaction *cur_trans = trans->transaction;
1810 WARN_ON(refcount_read(&trans->use_count) > 1);
1812 btrfs_abort_transaction(trans, err);
1814 spin_lock(&fs_info->trans_lock);
1817 * If the transaction is removed from the list, it means this
1818 * transaction has been committed successfully, so it is impossible
1819 * to call the cleanup function.
1821 BUG_ON(list_empty(&cur_trans->list));
1823 list_del_init(&cur_trans->list);
1824 if (cur_trans == fs_info->running_transaction) {
1825 cur_trans->state = TRANS_STATE_COMMIT_DOING;
1826 spin_unlock(&fs_info->trans_lock);
1827 wait_event(cur_trans->writer_wait,
1828 atomic_read(&cur_trans->num_writers) == 1);
1830 spin_lock(&fs_info->trans_lock);
1832 spin_unlock(&fs_info->trans_lock);
1834 btrfs_cleanup_one_transaction(trans->transaction, fs_info);
1836 spin_lock(&fs_info->trans_lock);
1837 if (cur_trans == fs_info->running_transaction)
1838 fs_info->running_transaction = NULL;
1839 spin_unlock(&fs_info->trans_lock);
1841 if (trans->type & __TRANS_FREEZABLE)
1842 sb_end_intwrite(fs_info->sb);
1843 btrfs_put_transaction(cur_trans);
1844 btrfs_put_transaction(cur_trans);
1846 trace_btrfs_transaction_commit(trans->root);
1848 if (current->journal_info == trans)
1849 current->journal_info = NULL;
1850 btrfs_scrub_cancel(fs_info);
1852 kmem_cache_free(btrfs_trans_handle_cachep, trans);
1856 * Release reserved delayed ref space of all pending block groups of the
1857 * transaction and remove them from the list
1859 static void btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle *trans)
1861 struct btrfs_fs_info *fs_info = trans->fs_info;
1862 struct btrfs_block_group_cache *block_group, *tmp;
1864 list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
1865 btrfs_delayed_refs_rsv_release(fs_info, 1);
1866 list_del_init(&block_group->bg_list);
1870 static inline int btrfs_start_delalloc_flush(struct btrfs_trans_handle *trans)
1872 struct btrfs_fs_info *fs_info = trans->fs_info;
1875 * We use writeback_inodes_sb here because if we used
1876 * btrfs_start_delalloc_roots we would deadlock with fs freeze.
1877 * Currently are holding the fs freeze lock, if we do an async flush
1878 * we'll do btrfs_join_transaction() and deadlock because we need to
1879 * wait for the fs freeze lock. Using the direct flushing we benefit
1880 * from already being in a transaction and our join_transaction doesn't
1881 * have to re-take the fs freeze lock.
1883 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT)) {
1884 writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
1886 struct btrfs_pending_snapshot *pending;
1887 struct list_head *head = &trans->transaction->pending_snapshots;
1890 * Flush dellaloc for any root that is going to be snapshotted.
1891 * This is done to avoid a corrupted version of files, in the
1892 * snapshots, that had both buffered and direct IO writes (even
1893 * if they were done sequentially) due to an unordered update of
1894 * the inode's size on disk.
1896 list_for_each_entry(pending, head, list) {
1899 ret = btrfs_start_delalloc_snapshot(pending->root);
1907 static inline void btrfs_wait_delalloc_flush(struct btrfs_trans_handle *trans)
1909 struct btrfs_fs_info *fs_info = trans->fs_info;
1911 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT)) {
1912 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
1914 struct btrfs_pending_snapshot *pending;
1915 struct list_head *head = &trans->transaction->pending_snapshots;
1918 * Wait for any dellaloc that we started previously for the roots
1919 * that are going to be snapshotted. This is to avoid a corrupted
1920 * version of files in the snapshots that had both buffered and
1921 * direct IO writes (even if they were done sequentially).
1923 list_for_each_entry(pending, head, list)
1924 btrfs_wait_ordered_extents(pending->root,
1925 U64_MAX, 0, U64_MAX);
1929 int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
1931 struct btrfs_fs_info *fs_info = trans->fs_info;
1932 struct btrfs_transaction *cur_trans = trans->transaction;
1933 struct btrfs_transaction *prev_trans = NULL;
1936 /* Stop the commit early if ->aborted is set */
1937 if (unlikely(READ_ONCE(cur_trans->aborted))) {
1938 ret = cur_trans->aborted;
1939 btrfs_end_transaction(trans);
1943 btrfs_trans_release_metadata(trans);
1944 trans->block_rsv = NULL;
1946 /* make a pass through all the delayed refs we have so far
1947 * any runnings procs may add more while we are here
1949 ret = btrfs_run_delayed_refs(trans, 0);
1951 btrfs_end_transaction(trans);
1955 cur_trans = trans->transaction;
1958 * set the flushing flag so procs in this transaction have to
1959 * start sending their work down.
1961 cur_trans->delayed_refs.flushing = 1;
1964 btrfs_create_pending_block_groups(trans);
1966 ret = btrfs_run_delayed_refs(trans, 0);
1968 btrfs_end_transaction(trans);
1972 if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
1975 /* this mutex is also taken before trying to set
1976 * block groups readonly. We need to make sure
1977 * that nobody has set a block group readonly
1978 * after a extents from that block group have been
1979 * allocated for cache files. btrfs_set_block_group_ro
1980 * will wait for the transaction to commit if it
1981 * finds BTRFS_TRANS_DIRTY_BG_RUN set.
1983 * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
1984 * only one process starts all the block group IO. It wouldn't
1985 * hurt to have more than one go through, but there's no
1986 * real advantage to it either.
1988 mutex_lock(&fs_info->ro_block_group_mutex);
1989 if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
1992 mutex_unlock(&fs_info->ro_block_group_mutex);
1995 ret = btrfs_start_dirty_block_groups(trans);
1997 btrfs_end_transaction(trans);
2003 spin_lock(&fs_info->trans_lock);
2004 if (cur_trans->state >= TRANS_STATE_COMMIT_START) {
2005 spin_unlock(&fs_info->trans_lock);
2006 refcount_inc(&cur_trans->use_count);
2007 ret = btrfs_end_transaction(trans);
2009 wait_for_commit(cur_trans);
2011 if (unlikely(cur_trans->aborted))
2012 ret = cur_trans->aborted;
2014 btrfs_put_transaction(cur_trans);
2019 cur_trans->state = TRANS_STATE_COMMIT_START;
2020 wake_up(&fs_info->transaction_blocked_wait);
2022 if (cur_trans->list.prev != &fs_info->trans_list) {
2023 prev_trans = list_entry(cur_trans->list.prev,
2024 struct btrfs_transaction, list);
2025 if (prev_trans->state != TRANS_STATE_COMPLETED) {
2026 refcount_inc(&prev_trans->use_count);
2027 spin_unlock(&fs_info->trans_lock);
2029 wait_for_commit(prev_trans);
2030 ret = prev_trans->aborted;
2032 btrfs_put_transaction(prev_trans);
2034 goto cleanup_transaction;
2036 spin_unlock(&fs_info->trans_lock);
2039 spin_unlock(&fs_info->trans_lock);
2042 extwriter_counter_dec(cur_trans, trans->type);
2044 ret = btrfs_start_delalloc_flush(trans);
2046 goto cleanup_transaction;
2048 ret = btrfs_run_delayed_items(trans);
2050 goto cleanup_transaction;
2052 wait_event(cur_trans->writer_wait,
2053 extwriter_counter_read(cur_trans) == 0);
2055 /* some pending stuffs might be added after the previous flush. */
2056 ret = btrfs_run_delayed_items(trans);
2058 goto cleanup_transaction;
2060 btrfs_wait_delalloc_flush(trans);
2062 btrfs_scrub_pause(fs_info);
2064 * Ok now we need to make sure to block out any other joins while we
2065 * commit the transaction. We could have started a join before setting
2066 * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2068 spin_lock(&fs_info->trans_lock);
2069 cur_trans->state = TRANS_STATE_COMMIT_DOING;
2070 spin_unlock(&fs_info->trans_lock);
2071 wait_event(cur_trans->writer_wait,
2072 atomic_read(&cur_trans->num_writers) == 1);
2074 /* ->aborted might be set after the previous check, so check it */
2075 if (unlikely(READ_ONCE(cur_trans->aborted))) {
2076 ret = cur_trans->aborted;
2077 goto scrub_continue;
2080 * the reloc mutex makes sure that we stop
2081 * the balancing code from coming in and moving
2082 * extents around in the middle of the commit
2084 mutex_lock(&fs_info->reloc_mutex);
2087 * We needn't worry about the delayed items because we will
2088 * deal with them in create_pending_snapshot(), which is the
2089 * core function of the snapshot creation.
2091 ret = create_pending_snapshots(trans);
2093 mutex_unlock(&fs_info->reloc_mutex);
2094 goto scrub_continue;
2098 * We insert the dir indexes of the snapshots and update the inode
2099 * of the snapshots' parents after the snapshot creation, so there
2100 * are some delayed items which are not dealt with. Now deal with
2103 * We needn't worry that this operation will corrupt the snapshots,
2104 * because all the tree which are snapshoted will be forced to COW
2105 * the nodes and leaves.
2107 ret = btrfs_run_delayed_items(trans);
2109 mutex_unlock(&fs_info->reloc_mutex);
2110 goto scrub_continue;
2113 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2115 mutex_unlock(&fs_info->reloc_mutex);
2116 goto scrub_continue;
2120 * make sure none of the code above managed to slip in a
2123 btrfs_assert_delayed_root_empty(fs_info);
2125 WARN_ON(cur_trans != trans->transaction);
2127 /* btrfs_commit_tree_roots is responsible for getting the
2128 * various roots consistent with each other. Every pointer
2129 * in the tree of tree roots has to point to the most up to date
2130 * root for every subvolume and other tree. So, we have to keep
2131 * the tree logging code from jumping in and changing any
2134 * At this point in the commit, there can't be any tree-log
2135 * writers, but a little lower down we drop the trans mutex
2136 * and let new people in. By holding the tree_log_mutex
2137 * from now until after the super is written, we avoid races
2138 * with the tree-log code.
2140 mutex_lock(&fs_info->tree_log_mutex);
2142 ret = commit_fs_roots(trans);
2144 mutex_unlock(&fs_info->tree_log_mutex);
2145 mutex_unlock(&fs_info->reloc_mutex);
2146 goto scrub_continue;
2150 * Since the transaction is done, we can apply the pending changes
2151 * before the next transaction.
2153 btrfs_apply_pending_changes(fs_info);
2155 /* commit_fs_roots gets rid of all the tree log roots, it is now
2156 * safe to free the root of tree log roots
2158 btrfs_free_log_root_tree(trans, fs_info);
2161 * commit_fs_roots() can call btrfs_save_ino_cache(), which generates
2162 * new delayed refs. Must handle them or qgroup can be wrong.
2164 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2166 mutex_unlock(&fs_info->tree_log_mutex);
2167 mutex_unlock(&fs_info->reloc_mutex);
2168 goto scrub_continue;
2172 * Since fs roots are all committed, we can get a quite accurate
2173 * new_roots. So let's do quota accounting.
2175 ret = btrfs_qgroup_account_extents(trans);
2177 mutex_unlock(&fs_info->tree_log_mutex);
2178 mutex_unlock(&fs_info->reloc_mutex);
2179 goto scrub_continue;
2182 ret = commit_cowonly_roots(trans);
2184 mutex_unlock(&fs_info->tree_log_mutex);
2185 mutex_unlock(&fs_info->reloc_mutex);
2186 goto scrub_continue;
2190 * The tasks which save the space cache and inode cache may also
2191 * update ->aborted, check it.
2193 if (unlikely(READ_ONCE(cur_trans->aborted))) {
2194 ret = cur_trans->aborted;
2195 mutex_unlock(&fs_info->tree_log_mutex);
2196 mutex_unlock(&fs_info->reloc_mutex);
2197 goto scrub_continue;
2200 btrfs_prepare_extent_commit(fs_info);
2202 cur_trans = fs_info->running_transaction;
2204 btrfs_set_root_node(&fs_info->tree_root->root_item,
2205 fs_info->tree_root->node);
2206 list_add_tail(&fs_info->tree_root->dirty_list,
2207 &cur_trans->switch_commits);
2209 btrfs_set_root_node(&fs_info->chunk_root->root_item,
2210 fs_info->chunk_root->node);
2211 list_add_tail(&fs_info->chunk_root->dirty_list,
2212 &cur_trans->switch_commits);
2214 switch_commit_roots(cur_trans);
2216 ASSERT(list_empty(&cur_trans->dirty_bgs));
2217 ASSERT(list_empty(&cur_trans->io_bgs));
2218 update_super_roots(fs_info);
2220 btrfs_set_super_log_root(fs_info->super_copy, 0);
2221 btrfs_set_super_log_root_level(fs_info->super_copy, 0);
2222 memcpy(fs_info->super_for_commit, fs_info->super_copy,
2223 sizeof(*fs_info->super_copy));
2225 btrfs_commit_device_sizes(cur_trans);
2227 clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2228 clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2230 btrfs_trans_release_chunk_metadata(trans);
2232 spin_lock(&fs_info->trans_lock);
2233 cur_trans->state = TRANS_STATE_UNBLOCKED;
2234 fs_info->running_transaction = NULL;
2235 spin_unlock(&fs_info->trans_lock);
2236 mutex_unlock(&fs_info->reloc_mutex);
2238 wake_up(&fs_info->transaction_wait);
2240 ret = btrfs_write_and_wait_transaction(trans);
2242 btrfs_handle_fs_error(fs_info, ret,
2243 "Error while writing out transaction");
2244 mutex_unlock(&fs_info->tree_log_mutex);
2245 goto scrub_continue;
2248 ret = write_all_supers(fs_info, 0);
2250 * the super is written, we can safely allow the tree-loggers
2251 * to go about their business
2253 mutex_unlock(&fs_info->tree_log_mutex);
2255 goto scrub_continue;
2257 btrfs_finish_extent_commit(trans);
2259 if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
2260 btrfs_clear_space_info_full(fs_info);
2262 fs_info->last_trans_committed = cur_trans->transid;
2264 * We needn't acquire the lock here because there is no other task
2265 * which can change it.
2267 cur_trans->state = TRANS_STATE_COMPLETED;
2268 wake_up(&cur_trans->commit_wait);
2269 clear_bit(BTRFS_FS_NEED_ASYNC_COMMIT, &fs_info->flags);
2271 spin_lock(&fs_info->trans_lock);
2272 list_del_init(&cur_trans->list);
2273 spin_unlock(&fs_info->trans_lock);
2275 btrfs_put_transaction(cur_trans);
2276 btrfs_put_transaction(cur_trans);
2278 if (trans->type & __TRANS_FREEZABLE)
2279 sb_end_intwrite(fs_info->sb);
2281 trace_btrfs_transaction_commit(trans->root);
2283 btrfs_scrub_continue(fs_info);
2285 if (current->journal_info == trans)
2286 current->journal_info = NULL;
2288 kmem_cache_free(btrfs_trans_handle_cachep, trans);
2293 btrfs_scrub_continue(fs_info);
2294 cleanup_transaction:
2295 btrfs_trans_release_metadata(trans);
2296 btrfs_cleanup_pending_block_groups(trans);
2297 btrfs_trans_release_chunk_metadata(trans);
2298 trans->block_rsv = NULL;
2299 btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
2300 if (current->journal_info == trans)
2301 current->journal_info = NULL;
2302 cleanup_transaction(trans, ret);
2308 * return < 0 if error
2309 * 0 if there are no more dead_roots at the time of call
2310 * 1 there are more to be processed, call me again
2312 * The return value indicates there are certainly more snapshots to delete, but
2313 * if there comes a new one during processing, it may return 0. We don't mind,
2314 * because btrfs_commit_super will poke cleaner thread and it will process it a
2315 * few seconds later.
2317 int btrfs_clean_one_deleted_snapshot(struct btrfs_root *root)
2320 struct btrfs_fs_info *fs_info = root->fs_info;
2322 spin_lock(&fs_info->trans_lock);
2323 if (list_empty(&fs_info->dead_roots)) {
2324 spin_unlock(&fs_info->trans_lock);
2327 root = list_first_entry(&fs_info->dead_roots,
2328 struct btrfs_root, root_list);
2329 list_del_init(&root->root_list);
2330 spin_unlock(&fs_info->trans_lock);
2332 btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
2334 btrfs_kill_all_delayed_nodes(root);
2336 if (btrfs_header_backref_rev(root->node) <
2337 BTRFS_MIXED_BACKREF_REV)
2338 ret = btrfs_drop_snapshot(root, NULL, 0, 0);
2340 ret = btrfs_drop_snapshot(root, NULL, 1, 0);
2342 return (ret < 0) ? 0 : 1;
2345 void btrfs_apply_pending_changes(struct btrfs_fs_info *fs_info)
2350 prev = xchg(&fs_info->pending_changes, 0);
2354 bit = 1 << BTRFS_PENDING_SET_INODE_MAP_CACHE;
2356 btrfs_set_opt(fs_info->mount_opt, INODE_MAP_CACHE);
2359 bit = 1 << BTRFS_PENDING_CLEAR_INODE_MAP_CACHE;
2361 btrfs_clear_opt(fs_info->mount_opt, INODE_MAP_CACHE);
2364 bit = 1 << BTRFS_PENDING_COMMIT;
2366 btrfs_debug(fs_info, "pending commit done");
2371 "unknown pending changes left 0x%lx, ignoring", prev);