]> git.ipfire.org Git - thirdparty/linux.git/blame - fs/btrfs/transaction.c
btrfs: add macros for annotating wait events with lockdep
[thirdparty/linux.git] / fs / btrfs / transaction.c
CommitLineData
c1d7c514 1// SPDX-License-Identifier: GPL-2.0
6cbd5570
CM
2/*
3 * Copyright (C) 2007 Oracle. All rights reserved.
6cbd5570
CM
4 */
5
79154b1b 6#include <linux/fs.h>
5a0e3ad6 7#include <linux/slab.h>
34088780 8#include <linux/sched.h>
d3c2fdcf 9#include <linux/writeback.h>
5f39d397 10#include <linux/pagemap.h>
5f2cc086 11#include <linux/blkdev.h>
8ea05e3a 12#include <linux/uuid.h>
e55958c8 13#include <linux/timekeeping.h>
602cbe91 14#include "misc.h"
79154b1b
CM
15#include "ctree.h"
16#include "disk-io.h"
17#include "transaction.h"
925baedd 18#include "locking.h"
e02119d5 19#include "tree-log.h"
733f4fbb 20#include "volumes.h"
8dabb742 21#include "dev-replace.h"
fcebe456 22#include "qgroup.h"
aac0023c 23#include "block-group.h"
9c343784 24#include "space-info.h"
d3575156 25#include "zoned.h"
79154b1b 26
fc7cbcd4 27#define BTRFS_ROOT_TRANS_TAG 0
0f7d52f4 28
61c047b5
QW
29/*
30 * Transaction states and transitions
31 *
32 * No running transaction (fs tree blocks are not modified)
33 * |
34 * | To next stage:
35 * | Call start_transaction() variants. Except btrfs_join_transaction_nostart().
36 * V
37 * Transaction N [[TRANS_STATE_RUNNING]]
38 * |
39 * | New trans handles can be attached to transaction N by calling all
40 * | start_transaction() variants.
41 * |
42 * | To next stage:
43 * | Call btrfs_commit_transaction() on any trans handle attached to
44 * | transaction N
45 * V
46 * Transaction N [[TRANS_STATE_COMMIT_START]]
47 * |
48 * | Will wait for previous running transaction to completely finish if there
49 * | is one
50 * |
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.
56 * |
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
60 * | transaction N+1.
61 * |
62 * | To next stage:
63 * | Caller is chosen to commit transaction N, and all other trans handle
64 * | haven been released.
65 * V
66 * Transaction N [[TRANS_STATE_COMMIT_DOING]]
67 * |
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
72 * | trees.
73 * |
74 * | At this stage, all start_transaction() calls will wait for this
75 * | transaction to finish and attach to transaction N+1.
76 * |
77 * | To next stage:
78 * | Until all supporting trees are updated.
79 * V
80 * Transaction N [[TRANS_STATE_UNBLOCKED]]
81 * | Transaction N+1
82 * | All needed trees are modified, thus we only [[TRANS_STATE_RUNNING]]
83 * | need to write them back to disk and update |
84 * | super blocks. |
85 * | |
86 * | At this stage, new transaction is allowed to |
87 * | start. |
88 * | All new start_transaction() calls will be |
89 * | attached to transid N+1. |
90 * | |
91 * | To next stage: |
92 * | Until all tree blocks are super blocks are |
93 * | written to block devices |
94 * V |
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
99 */
e8c9f186 100static const unsigned int btrfs_blocked_trans_types[TRANS_STATE_MAX] = {
4a9d8bde 101 [TRANS_STATE_RUNNING] = 0U,
bcf3a3e7
NB
102 [TRANS_STATE_COMMIT_START] = (__TRANS_START | __TRANS_ATTACH),
103 [TRANS_STATE_COMMIT_DOING] = (__TRANS_START |
4a9d8bde 104 __TRANS_ATTACH |
a6d155d2
FM
105 __TRANS_JOIN |
106 __TRANS_JOIN_NOSTART),
bcf3a3e7 107 [TRANS_STATE_UNBLOCKED] = (__TRANS_START |
4a9d8bde
MX
108 __TRANS_ATTACH |
109 __TRANS_JOIN |
a6d155d2
FM
110 __TRANS_JOIN_NOLOCK |
111 __TRANS_JOIN_NOSTART),
d0c2f4fa
FM
112 [TRANS_STATE_SUPER_COMMITTED] = (__TRANS_START |
113 __TRANS_ATTACH |
114 __TRANS_JOIN |
115 __TRANS_JOIN_NOLOCK |
116 __TRANS_JOIN_NOSTART),
bcf3a3e7 117 [TRANS_STATE_COMPLETED] = (__TRANS_START |
4a9d8bde
MX
118 __TRANS_ATTACH |
119 __TRANS_JOIN |
a6d155d2
FM
120 __TRANS_JOIN_NOLOCK |
121 __TRANS_JOIN_NOSTART),
4a9d8bde
MX
122};
123
724e2315 124void btrfs_put_transaction(struct btrfs_transaction *transaction)
79154b1b 125{
9b64f57d
ER
126 WARN_ON(refcount_read(&transaction->use_count) == 0);
127 if (refcount_dec_and_test(&transaction->use_count)) {
a4abeea4 128 BUG_ON(!list_empty(&transaction->list));
5c9d028b
LB
129 WARN_ON(!RB_EMPTY_ROOT(
130 &transaction->delayed_refs.href_root.rb_root));
81f7eb00
JM
131 WARN_ON(!RB_EMPTY_ROOT(
132 &transaction->delayed_refs.dirty_extent_root));
1262133b 133 if (transaction->delayed_refs.pending_csums)
ab8d0fc4
JM
134 btrfs_err(transaction->fs_info,
135 "pending csums is %llu",
136 transaction->delayed_refs.pending_csums);
7785a663
FM
137 /*
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.
143 */
144 while (!list_empty(&transaction->deleted_bgs)) {
32da5386 145 struct btrfs_block_group *cache;
7785a663
FM
146
147 cache = list_first_entry(&transaction->deleted_bgs,
32da5386 148 struct btrfs_block_group,
7785a663
FM
149 bg_list);
150 list_del_init(&cache->bg_list);
6b7304af 151 btrfs_unfreeze_block_group(cache);
7785a663
FM
152 btrfs_put_block_group(cache);
153 }
bbbf7243 154 WARN_ON(!list_empty(&transaction->dev_update_list));
4b5faeac 155 kfree(transaction);
78fae27e 156 }
79154b1b
CM
157}
158
889bfa39 159static noinline void switch_commit_roots(struct btrfs_trans_handle *trans)
817d52f8 160{
889bfa39 161 struct btrfs_transaction *cur_trans = trans->transaction;
16916a88 162 struct btrfs_fs_info *fs_info = trans->fs_info;
9e351cc8 163 struct btrfs_root *root, *tmp;
27d56e62 164 struct btrfs_caching_control *caching_ctl, *next;
9e351cc8 165
dfba78dc
FM
166 /*
167 * At this point no one can be using this transaction to modify any tree
168 * and no one can start another transaction to modify any tree either.
169 */
170 ASSERT(cur_trans->state == TRANS_STATE_COMMIT_DOING);
171
9e351cc8 172 down_write(&fs_info->commit_root_sem);
d96b3424
FM
173
174 if (test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
175 fs_info->last_reloc_trans = trans->transid;
176
889bfa39 177 list_for_each_entry_safe(root, tmp, &cur_trans->switch_commits,
9e351cc8
JB
178 dirty_list) {
179 list_del_init(&root->dirty_list);
180 free_extent_buffer(root->commit_root);
181 root->commit_root = btrfs_root_node(root);
41e7acd3 182 extent_io_tree_release(&root->dirty_log_pages);
370a11b8 183 btrfs_qgroup_clean_swapped_blocks(root);
9e351cc8 184 }
2b9dbef2
JB
185
186 /* We can free old roots now. */
889bfa39
JB
187 spin_lock(&cur_trans->dropped_roots_lock);
188 while (!list_empty(&cur_trans->dropped_roots)) {
189 root = list_first_entry(&cur_trans->dropped_roots,
2b9dbef2
JB
190 struct btrfs_root, root_list);
191 list_del_init(&root->root_list);
889bfa39
JB
192 spin_unlock(&cur_trans->dropped_roots_lock);
193 btrfs_free_log(trans, root);
2b9dbef2 194 btrfs_drop_and_free_fs_root(fs_info, root);
889bfa39 195 spin_lock(&cur_trans->dropped_roots_lock);
2b9dbef2 196 }
889bfa39 197 spin_unlock(&cur_trans->dropped_roots_lock);
27d56e62
JB
198
199 /*
200 * We have to update the last_byte_to_unpin under the commit_root_sem,
201 * at the same time we swap out the commit roots.
202 *
203 * This is because we must have a real view of the last spot the caching
204 * kthreads were while caching. Consider the following views of the
205 * extent tree for a block group
206 *
207 * commit root
208 * +----+----+----+----+----+----+----+
209 * |\\\\| |\\\\|\\\\| |\\\\|\\\\|
210 * +----+----+----+----+----+----+----+
211 * 0 1 2 3 4 5 6 7
212 *
213 * new commit root
214 * +----+----+----+----+----+----+----+
215 * | | | |\\\\| | |\\\\|
216 * +----+----+----+----+----+----+----+
217 * 0 1 2 3 4 5 6 7
218 *
219 * If the cache_ctl->progress was at 3, then we are only allowed to
220 * unpin [0,1) and [2,3], because the caching thread has already
221 * processed those extents. We are not allowed to unpin [5,6), because
222 * the caching thread will re-start it's search from 3, and thus find
223 * the hole from [4,6) to add to the free space cache.
224 */
16b0c258 225 write_lock(&fs_info->block_group_cache_lock);
27d56e62
JB
226 list_for_each_entry_safe(caching_ctl, next,
227 &fs_info->caching_block_groups, list) {
228 struct btrfs_block_group *cache = caching_ctl->block_group;
229
230 if (btrfs_block_group_done(cache)) {
231 cache->last_byte_to_unpin = (u64)-1;
232 list_del_init(&caching_ctl->list);
233 btrfs_put_caching_control(caching_ctl);
234 } else {
235 cache->last_byte_to_unpin = caching_ctl->progress;
236 }
237 }
16b0c258 238 write_unlock(&fs_info->block_group_cache_lock);
9e351cc8 239 up_write(&fs_info->commit_root_sem);
817d52f8
JB
240}
241
0860adfd
MX
242static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
243 unsigned int type)
244{
245 if (type & TRANS_EXTWRITERS)
246 atomic_inc(&trans->num_extwriters);
247}
248
249static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
250 unsigned int type)
251{
252 if (type & TRANS_EXTWRITERS)
253 atomic_dec(&trans->num_extwriters);
254}
255
256static inline void extwriter_counter_init(struct btrfs_transaction *trans,
257 unsigned int type)
258{
259 atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
260}
261
262static inline int extwriter_counter_read(struct btrfs_transaction *trans)
263{
264 return atomic_read(&trans->num_extwriters);
178260b2
MX
265}
266
fb6dea26 267/*
79bd3712
FM
268 * To be called after doing the chunk btree updates right after allocating a new
269 * chunk (after btrfs_chunk_alloc_add_chunk_item() is called), when removing a
270 * chunk after all chunk btree updates and after finishing the second phase of
271 * chunk allocation (btrfs_create_pending_block_groups()) in case some block
272 * group had its chunk item insertion delayed to the second phase.
fb6dea26
JB
273 */
274void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
275{
276 struct btrfs_fs_info *fs_info = trans->fs_info;
277
278 if (!trans->chunk_bytes_reserved)
279 return;
280
fb6dea26 281 btrfs_block_rsv_release(fs_info, &fs_info->chunk_block_rsv,
63f018be 282 trans->chunk_bytes_reserved, NULL);
fb6dea26
JB
283 trans->chunk_bytes_reserved = 0;
284}
285
d352ac68
CM
286/*
287 * either allocate a new transaction or hop into the existing one
288 */
2ff7e61e
JM
289static noinline int join_transaction(struct btrfs_fs_info *fs_info,
290 unsigned int type)
79154b1b
CM
291{
292 struct btrfs_transaction *cur_trans;
a4abeea4 293
19ae4e81 294 spin_lock(&fs_info->trans_lock);
d43317dc 295loop:
49b25e05 296 /* The file system has been taken offline. No new transactions. */
84961539 297 if (BTRFS_FS_ERROR(fs_info)) {
19ae4e81 298 spin_unlock(&fs_info->trans_lock);
49b25e05
JM
299 return -EROFS;
300 }
301
19ae4e81 302 cur_trans = fs_info->running_transaction;
a4abeea4 303 if (cur_trans) {
bf31f87f 304 if (TRANS_ABORTED(cur_trans)) {
19ae4e81 305 spin_unlock(&fs_info->trans_lock);
49b25e05 306 return cur_trans->aborted;
871383be 307 }
4a9d8bde 308 if (btrfs_blocked_trans_types[cur_trans->state] & type) {
178260b2
MX
309 spin_unlock(&fs_info->trans_lock);
310 return -EBUSY;
311 }
9b64f57d 312 refcount_inc(&cur_trans->use_count);
13c5a93e 313 atomic_inc(&cur_trans->num_writers);
0860adfd 314 extwriter_counter_inc(cur_trans, type);
19ae4e81 315 spin_unlock(&fs_info->trans_lock);
a4abeea4 316 return 0;
79154b1b 317 }
19ae4e81 318 spin_unlock(&fs_info->trans_lock);
a4abeea4 319
354aa0fb
MX
320 /*
321 * If we are ATTACH, we just want to catch the current transaction,
322 * and commit it. If there is no transaction, just return ENOENT.
323 */
324 if (type == TRANS_ATTACH)
325 return -ENOENT;
326
4a9d8bde
MX
327 /*
328 * JOIN_NOLOCK only happens during the transaction commit, so
329 * it is impossible that ->running_transaction is NULL
330 */
331 BUG_ON(type == TRANS_JOIN_NOLOCK);
332
4b5faeac 333 cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
a4abeea4
JB
334 if (!cur_trans)
335 return -ENOMEM;
d43317dc 336
19ae4e81
JS
337 spin_lock(&fs_info->trans_lock);
338 if (fs_info->running_transaction) {
d43317dc
CM
339 /*
340 * someone started a transaction after we unlocked. Make sure
4a9d8bde 341 * to redo the checks above
d43317dc 342 */
4b5faeac 343 kfree(cur_trans);
d43317dc 344 goto loop;
84961539 345 } else if (BTRFS_FS_ERROR(fs_info)) {
e4b50e14 346 spin_unlock(&fs_info->trans_lock);
4b5faeac 347 kfree(cur_trans);
7b8b92af 348 return -EROFS;
79154b1b 349 }
d43317dc 350
ab8d0fc4 351 cur_trans->fs_info = fs_info;
48778179
FM
352 atomic_set(&cur_trans->pending_ordered, 0);
353 init_waitqueue_head(&cur_trans->pending_wait);
a4abeea4 354 atomic_set(&cur_trans->num_writers, 1);
0860adfd 355 extwriter_counter_init(cur_trans, type);
a4abeea4
JB
356 init_waitqueue_head(&cur_trans->writer_wait);
357 init_waitqueue_head(&cur_trans->commit_wait);
4a9d8bde 358 cur_trans->state = TRANS_STATE_RUNNING;
a4abeea4
JB
359 /*
360 * One for this trans handle, one so it will live on until we
361 * commit the transaction.
362 */
9b64f57d 363 refcount_set(&cur_trans->use_count, 2);
3204d33c 364 cur_trans->flags = 0;
afd48513 365 cur_trans->start_time = ktime_get_seconds();
a4abeea4 366
a099d0fd
AM
367 memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
368
5c9d028b 369 cur_trans->delayed_refs.href_root = RB_ROOT_CACHED;
3368d001 370 cur_trans->delayed_refs.dirty_extent_root = RB_ROOT;
d7df2c79 371 atomic_set(&cur_trans->delayed_refs.num_entries, 0);
20b297d6
JS
372
373 /*
374 * although the tree mod log is per file system and not per transaction,
375 * the log must never go across transaction boundaries.
376 */
377 smp_mb();
31b1a2bd 378 if (!list_empty(&fs_info->tree_mod_seq_list))
5d163e0e 379 WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
31b1a2bd 380 if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
5d163e0e 381 WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
fc36ed7e 382 atomic64_set(&fs_info->tree_mod_seq, 0);
20b297d6 383
a4abeea4
JB
384 spin_lock_init(&cur_trans->delayed_refs.lock);
385
386 INIT_LIST_HEAD(&cur_trans->pending_snapshots);
bbbf7243 387 INIT_LIST_HEAD(&cur_trans->dev_update_list);
9e351cc8 388 INIT_LIST_HEAD(&cur_trans->switch_commits);
ce93ec54 389 INIT_LIST_HEAD(&cur_trans->dirty_bgs);
1bbc621e 390 INIT_LIST_HEAD(&cur_trans->io_bgs);
2b9dbef2 391 INIT_LIST_HEAD(&cur_trans->dropped_roots);
1bbc621e 392 mutex_init(&cur_trans->cache_write_mutex);
ce93ec54 393 spin_lock_init(&cur_trans->dirty_bgs_lock);
e33e17ee 394 INIT_LIST_HEAD(&cur_trans->deleted_bgs);
2b9dbef2 395 spin_lock_init(&cur_trans->dropped_roots_lock);
d3575156
NA
396 INIT_LIST_HEAD(&cur_trans->releasing_ebs);
397 spin_lock_init(&cur_trans->releasing_ebs_lock);
19ae4e81 398 list_add_tail(&cur_trans->list, &fs_info->trans_list);
c258d6e3 399 extent_io_tree_init(fs_info, &cur_trans->dirty_pages,
43eb5f29 400 IO_TREE_TRANS_DIRTY_PAGES, fs_info->btree_inode);
fe119a6e
NB
401 extent_io_tree_init(fs_info, &cur_trans->pinned_extents,
402 IO_TREE_FS_PINNED_EXTENTS, NULL);
19ae4e81
JS
403 fs_info->generation++;
404 cur_trans->transid = fs_info->generation;
405 fs_info->running_transaction = cur_trans;
49b25e05 406 cur_trans->aborted = 0;
19ae4e81 407 spin_unlock(&fs_info->trans_lock);
15ee9bc7 408
79154b1b
CM
409 return 0;
410}
411
d352ac68 412/*
92a7cc42
QW
413 * This does all the record keeping required to make sure that a shareable root
414 * is properly recorded in a given transaction. This is required to make sure
415 * the old root from before we joined the transaction is deleted when the
416 * transaction commits.
d352ac68 417 */
7585717f 418static int record_root_in_trans(struct btrfs_trans_handle *trans,
6426c7ad
QW
419 struct btrfs_root *root,
420 int force)
6702ed49 421{
0b246afa 422 struct btrfs_fs_info *fs_info = root->fs_info;
03a7e111 423 int ret = 0;
0b246afa 424
92a7cc42 425 if ((test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
6426c7ad 426 root->last_trans < trans->transid) || force) {
4d31778a 427 WARN_ON(!force && root->commit_root != root->node);
5d4f98a2 428
7585717f 429 /*
27cdeb70 430 * see below for IN_TRANS_SETUP usage rules
7585717f
CM
431 * we have the reloc mutex held now, so there
432 * is only one writer in this function
433 */
27cdeb70 434 set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
7585717f 435
27cdeb70 436 /* make sure readers find IN_TRANS_SETUP before
7585717f
CM
437 * they find our root->last_trans update
438 */
439 smp_wmb();
440
fc7cbcd4 441 spin_lock(&fs_info->fs_roots_radix_lock);
6426c7ad 442 if (root->last_trans == trans->transid && !force) {
fc7cbcd4 443 spin_unlock(&fs_info->fs_roots_radix_lock);
a4abeea4
JB
444 return 0;
445 }
fc7cbcd4
DS
446 radix_tree_tag_set(&fs_info->fs_roots_radix,
447 (unsigned long)root->root_key.objectid,
448 BTRFS_ROOT_TRANS_TAG);
449 spin_unlock(&fs_info->fs_roots_radix_lock);
7585717f
CM
450 root->last_trans = trans->transid;
451
452 /* this is pretty tricky. We don't want to
453 * take the relocation lock in btrfs_record_root_in_trans
454 * unless we're really doing the first setup for this root in
455 * this transaction.
456 *
457 * Normally we'd use root->last_trans as a flag to decide
458 * if we want to take the expensive mutex.
459 *
460 * But, we have to set root->last_trans before we
461 * init the relocation root, otherwise, we trip over warnings
462 * in ctree.c. The solution used here is to flag ourselves
27cdeb70 463 * with root IN_TRANS_SETUP. When this is 1, we're still
7585717f
CM
464 * fixing up the reloc trees and everyone must wait.
465 *
466 * When this is zero, they can trust root->last_trans and fly
467 * through btrfs_record_root_in_trans without having to take the
468 * lock. smp_wmb() makes sure that all the writes above are
469 * done before we pop in the zero below
470 */
03a7e111 471 ret = btrfs_init_reloc_root(trans, root);
c7548af6 472 smp_mb__before_atomic();
27cdeb70 473 clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
5d4f98a2 474 }
03a7e111 475 return ret;
5d4f98a2 476}
bcc63abb 477
7585717f 478
2b9dbef2
JB
479void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
480 struct btrfs_root *root)
481{
0b246afa 482 struct btrfs_fs_info *fs_info = root->fs_info;
2b9dbef2
JB
483 struct btrfs_transaction *cur_trans = trans->transaction;
484
485 /* Add ourselves to the transaction dropped list */
486 spin_lock(&cur_trans->dropped_roots_lock);
487 list_add_tail(&root->root_list, &cur_trans->dropped_roots);
488 spin_unlock(&cur_trans->dropped_roots_lock);
489
490 /* Make sure we don't try to update the root at commit time */
fc7cbcd4
DS
491 spin_lock(&fs_info->fs_roots_radix_lock);
492 radix_tree_tag_clear(&fs_info->fs_roots_radix,
493 (unsigned long)root->root_key.objectid,
494 BTRFS_ROOT_TRANS_TAG);
495 spin_unlock(&fs_info->fs_roots_radix_lock);
2b9dbef2
JB
496}
497
7585717f
CM
498int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
499 struct btrfs_root *root)
500{
0b246afa 501 struct btrfs_fs_info *fs_info = root->fs_info;
1409e6cc 502 int ret;
0b246afa 503
92a7cc42 504 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
7585717f
CM
505 return 0;
506
507 /*
27cdeb70 508 * see record_root_in_trans for comments about IN_TRANS_SETUP usage
7585717f
CM
509 * and barriers
510 */
511 smp_rmb();
512 if (root->last_trans == trans->transid &&
27cdeb70 513 !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
7585717f
CM
514 return 0;
515
0b246afa 516 mutex_lock(&fs_info->reloc_mutex);
1409e6cc 517 ret = record_root_in_trans(trans, root, 0);
0b246afa 518 mutex_unlock(&fs_info->reloc_mutex);
7585717f 519
1409e6cc 520 return ret;
7585717f
CM
521}
522
4a9d8bde
MX
523static inline int is_transaction_blocked(struct btrfs_transaction *trans)
524{
3296bf56 525 return (trans->state >= TRANS_STATE_COMMIT_START &&
501407aa 526 trans->state < TRANS_STATE_UNBLOCKED &&
bf31f87f 527 !TRANS_ABORTED(trans));
4a9d8bde
MX
528}
529
d352ac68
CM
530/* wait for commit against the current transaction to become unblocked
531 * when this is done, it is safe to start a new transaction, but the current
532 * transaction might not be fully on disk.
533 */
2ff7e61e 534static void wait_current_trans(struct btrfs_fs_info *fs_info)
79154b1b 535{
f9295749 536 struct btrfs_transaction *cur_trans;
79154b1b 537
0b246afa
JM
538 spin_lock(&fs_info->trans_lock);
539 cur_trans = fs_info->running_transaction;
4a9d8bde 540 if (cur_trans && is_transaction_blocked(cur_trans)) {
9b64f57d 541 refcount_inc(&cur_trans->use_count);
0b246afa 542 spin_unlock(&fs_info->trans_lock);
72d63ed6 543
0b246afa 544 wait_event(fs_info->transaction_wait,
501407aa 545 cur_trans->state >= TRANS_STATE_UNBLOCKED ||
bf31f87f 546 TRANS_ABORTED(cur_trans));
724e2315 547 btrfs_put_transaction(cur_trans);
a4abeea4 548 } else {
0b246afa 549 spin_unlock(&fs_info->trans_lock);
f9295749 550 }
37d1aeee
CM
551}
552
2ff7e61e 553static int may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
a22285a6 554{
0b246afa 555 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
a4abeea4
JB
556 return 0;
557
92e2f7e3 558 if (type == TRANS_START)
a22285a6 559 return 1;
a4abeea4 560
a22285a6
YZ
561 return 0;
562}
563
20dd2cbf
MX
564static inline bool need_reserve_reloc_root(struct btrfs_root *root)
565{
0b246afa
JM
566 struct btrfs_fs_info *fs_info = root->fs_info;
567
568 if (!fs_info->reloc_ctl ||
92a7cc42 569 !test_bit(BTRFS_ROOT_SHAREABLE, &root->state) ||
20dd2cbf
MX
570 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
571 root->reloc_root)
572 return false;
573
574 return true;
575}
576
08e007d2 577static struct btrfs_trans_handle *
5aed1dd8 578start_transaction(struct btrfs_root *root, unsigned int num_items,
003d7c59
JM
579 unsigned int type, enum btrfs_reserve_flush_enum flush,
580 bool enforce_qgroups)
37d1aeee 581{
0b246afa 582 struct btrfs_fs_info *fs_info = root->fs_info;
ba2c4d4e 583 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
a22285a6
YZ
584 struct btrfs_trans_handle *h;
585 struct btrfs_transaction *cur_trans;
b5009945 586 u64 num_bytes = 0;
c5567237 587 u64 qgroup_reserved = 0;
20dd2cbf 588 bool reloc_reserved = false;
9c343784 589 bool do_chunk_alloc = false;
20dd2cbf 590 int ret;
acce952b 591
84961539 592 if (BTRFS_FS_ERROR(fs_info))
acce952b 593 return ERR_PTR(-EROFS);
2a1eb461 594
46c4e71e 595 if (current->journal_info) {
0860adfd 596 WARN_ON(type & TRANS_EXTWRITERS);
2a1eb461 597 h = current->journal_info;
b50fff81
DS
598 refcount_inc(&h->use_count);
599 WARN_ON(refcount_read(&h->use_count) > 2);
2a1eb461
JB
600 h->orig_rsv = h->block_rsv;
601 h->block_rsv = NULL;
602 goto got_it;
603 }
b5009945
JB
604
605 /*
606 * Do the reservation before we join the transaction so we can do all
607 * the appropriate flushing if need be.
608 */
003d7c59 609 if (num_items && root != fs_info->chunk_root) {
ba2c4d4e
JB
610 struct btrfs_block_rsv *rsv = &fs_info->trans_block_rsv;
611 u64 delayed_refs_bytes = 0;
612
0b246afa 613 qgroup_reserved = num_items * fs_info->nodesize;
733e03a0
QW
614 ret = btrfs_qgroup_reserve_meta_pertrans(root, qgroup_reserved,
615 enforce_qgroups);
7174109c
QW
616 if (ret)
617 return ERR_PTR(ret);
c5567237 618
ba2c4d4e
JB
619 /*
620 * We want to reserve all the bytes we may need all at once, so
621 * we only do 1 enospc flushing cycle per transaction start. We
622 * accomplish this by simply assuming we'll do 2 x num_items
623 * worth of delayed refs updates in this trans handle, and
624 * refill that amount for whatever is missing in the reserve.
625 */
2bd36e7b 626 num_bytes = btrfs_calc_insert_metadata_size(fs_info, num_items);
7f9fe614
JB
627 if (flush == BTRFS_RESERVE_FLUSH_ALL &&
628 delayed_refs_rsv->full == 0) {
ba2c4d4e
JB
629 delayed_refs_bytes = num_bytes;
630 num_bytes <<= 1;
631 }
632
20dd2cbf
MX
633 /*
634 * Do the reservation for the relocation root creation
635 */
ee39b432 636 if (need_reserve_reloc_root(root)) {
0b246afa 637 num_bytes += fs_info->nodesize;
20dd2cbf
MX
638 reloc_reserved = true;
639 }
640
9270501c 641 ret = btrfs_block_rsv_add(fs_info, rsv, num_bytes, flush);
ba2c4d4e
JB
642 if (ret)
643 goto reserve_fail;
644 if (delayed_refs_bytes) {
645 btrfs_migrate_to_delayed_refs_rsv(fs_info, rsv,
646 delayed_refs_bytes);
647 num_bytes -= delayed_refs_bytes;
648 }
9c343784
JB
649
650 if (rsv->space_info->force_alloc)
651 do_chunk_alloc = true;
ba2c4d4e
JB
652 } else if (num_items == 0 && flush == BTRFS_RESERVE_FLUSH_ALL &&
653 !delayed_refs_rsv->full) {
654 /*
655 * Some people call with btrfs_start_transaction(root, 0)
656 * because they can be throttled, but have some other mechanism
657 * for reserving space. We still want these guys to refill the
658 * delayed block_rsv so just add 1 items worth of reservation
659 * here.
660 */
661 ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
b5009945 662 if (ret)
843fcf35 663 goto reserve_fail;
b5009945 664 }
a22285a6 665again:
f2f767e7 666 h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
843fcf35
MX
667 if (!h) {
668 ret = -ENOMEM;
669 goto alloc_fail;
670 }
37d1aeee 671
98114659
JB
672 /*
673 * If we are JOIN_NOLOCK we're already committing a transaction and
674 * waiting on this guy, so we don't need to do the sb_start_intwrite
675 * because we're already holding a ref. We need this because we could
676 * have raced in and did an fsync() on a file which can kick a commit
677 * and then we deadlock with somebody doing a freeze.
354aa0fb
MX
678 *
679 * If we are ATTACH, it means we just want to catch the current
680 * transaction and commit it, so we needn't do sb_start_intwrite().
98114659 681 */
0860adfd 682 if (type & __TRANS_FREEZABLE)
0b246afa 683 sb_start_intwrite(fs_info->sb);
b2b5ef5c 684
2ff7e61e
JM
685 if (may_wait_transaction(fs_info, type))
686 wait_current_trans(fs_info);
a22285a6 687
a4abeea4 688 do {
2ff7e61e 689 ret = join_transaction(fs_info, type);
178260b2 690 if (ret == -EBUSY) {
2ff7e61e 691 wait_current_trans(fs_info);
a6d155d2
FM
692 if (unlikely(type == TRANS_ATTACH ||
693 type == TRANS_JOIN_NOSTART))
178260b2
MX
694 ret = -ENOENT;
695 }
a4abeea4
JB
696 } while (ret == -EBUSY);
697
a43f7f82 698 if (ret < 0)
843fcf35 699 goto join_fail;
0f7d52f4 700
0b246afa 701 cur_trans = fs_info->running_transaction;
a22285a6
YZ
702
703 h->transid = cur_trans->transid;
704 h->transaction = cur_trans;
b50fff81 705 refcount_set(&h->use_count, 1);
64b63580 706 h->fs_info = root->fs_info;
7174109c 707
a698d075 708 h->type = type;
ea658bad 709 INIT_LIST_HEAD(&h->new_bgs);
b7ec40d7 710
a22285a6 711 smp_mb();
3296bf56 712 if (cur_trans->state >= TRANS_STATE_COMMIT_START &&
2ff7e61e 713 may_wait_transaction(fs_info, type)) {
abdd2e80 714 current->journal_info = h;
3a45bb20 715 btrfs_commit_transaction(h);
a22285a6
YZ
716 goto again;
717 }
718
b5009945 719 if (num_bytes) {
0b246afa 720 trace_btrfs_space_reservation(fs_info, "transaction",
2bcc0328 721 h->transid, num_bytes, 1);
0b246afa 722 h->block_rsv = &fs_info->trans_block_rsv;
b5009945 723 h->bytes_reserved = num_bytes;
20dd2cbf 724 h->reloc_reserved = reloc_reserved;
a22285a6 725 }
9ed74f2d 726
2a1eb461 727got_it:
bcf3a3e7 728 if (!current->journal_info)
a22285a6 729 current->journal_info = h;
fcc99734 730
9c343784
JB
731 /*
732 * If the space_info is marked ALLOC_FORCE then we'll get upgraded to
733 * ALLOC_FORCE the first run through, and then we won't allocate for
734 * anybody else who races in later. We don't care about the return
735 * value here.
736 */
737 if (do_chunk_alloc && num_bytes) {
738 u64 flags = h->block_rsv->space_info->flags;
739
740 btrfs_chunk_alloc(h, btrfs_get_alloc_profile(fs_info, flags),
741 CHUNK_ALLOC_NO_FORCE);
742 }
743
fcc99734
QW
744 /*
745 * btrfs_record_root_in_trans() needs to alloc new extents, and may
746 * call btrfs_join_transaction() while we're also starting a
747 * transaction.
748 *
749 * Thus it need to be called after current->journal_info initialized,
750 * or we can deadlock.
751 */
68075ea8
JB
752 ret = btrfs_record_root_in_trans(h, root);
753 if (ret) {
754 /*
755 * The transaction handle is fully initialized and linked with
756 * other structures so it needs to be ended in case of errors,
757 * not just freed.
758 */
759 btrfs_end_transaction(h);
760 return ERR_PTR(ret);
761 }
fcc99734 762
79154b1b 763 return h;
843fcf35
MX
764
765join_fail:
0860adfd 766 if (type & __TRANS_FREEZABLE)
0b246afa 767 sb_end_intwrite(fs_info->sb);
843fcf35
MX
768 kmem_cache_free(btrfs_trans_handle_cachep, h);
769alloc_fail:
770 if (num_bytes)
2ff7e61e 771 btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
63f018be 772 num_bytes, NULL);
843fcf35 773reserve_fail:
733e03a0 774 btrfs_qgroup_free_meta_pertrans(root, qgroup_reserved);
843fcf35 775 return ERR_PTR(ret);
79154b1b
CM
776}
777
f9295749 778struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
5aed1dd8 779 unsigned int num_items)
f9295749 780{
08e007d2 781 return start_transaction(root, num_items, TRANS_START,
003d7c59 782 BTRFS_RESERVE_FLUSH_ALL, true);
f9295749 783}
003d7c59 784
8eab77ff
FM
785struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
786 struct btrfs_root *root,
7f9fe614 787 unsigned int num_items)
8eab77ff 788{
7f9fe614
JB
789 return start_transaction(root, num_items, TRANS_START,
790 BTRFS_RESERVE_FLUSH_ALL_STEAL, false);
8eab77ff 791}
8407aa46 792
7a7eaa40 793struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
f9295749 794{
003d7c59
JM
795 return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
796 true);
f9295749
CM
797}
798
8d510121 799struct btrfs_trans_handle *btrfs_join_transaction_spacecache(struct btrfs_root *root)
0af3d00b 800{
575a75d6 801 return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
003d7c59 802 BTRFS_RESERVE_NO_FLUSH, true);
0af3d00b
JB
803}
804
a6d155d2
FM
805/*
806 * Similar to regular join but it never starts a transaction when none is
807 * running or after waiting for the current one to finish.
808 */
809struct btrfs_trans_handle *btrfs_join_transaction_nostart(struct btrfs_root *root)
810{
811 return start_transaction(root, 0, TRANS_JOIN_NOSTART,
812 BTRFS_RESERVE_NO_FLUSH, true);
813}
814
d4edf39b
MX
815/*
816 * btrfs_attach_transaction() - catch the running transaction
817 *
818 * It is used when we want to commit the current the transaction, but
819 * don't want to start a new one.
820 *
821 * Note: If this function return -ENOENT, it just means there is no
822 * running transaction. But it is possible that the inactive transaction
823 * is still in the memory, not fully on disk. If you hope there is no
824 * inactive transaction in the fs when -ENOENT is returned, you should
825 * invoke
826 * btrfs_attach_transaction_barrier()
827 */
354aa0fb 828struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
60376ce4 829{
575a75d6 830 return start_transaction(root, 0, TRANS_ATTACH,
003d7c59 831 BTRFS_RESERVE_NO_FLUSH, true);
60376ce4
JB
832}
833
d4edf39b 834/*
90b6d283 835 * btrfs_attach_transaction_barrier() - catch the running transaction
d4edf39b 836 *
52042d8e 837 * It is similar to the above function, the difference is this one
d4edf39b
MX
838 * will wait for all the inactive transactions until they fully
839 * complete.
840 */
841struct btrfs_trans_handle *
842btrfs_attach_transaction_barrier(struct btrfs_root *root)
843{
844 struct btrfs_trans_handle *trans;
845
575a75d6 846 trans = start_transaction(root, 0, TRANS_ATTACH,
003d7c59 847 BTRFS_RESERVE_NO_FLUSH, true);
8d9e220c 848 if (trans == ERR_PTR(-ENOENT))
2ff7e61e 849 btrfs_wait_for_commit(root->fs_info, 0);
d4edf39b
MX
850
851 return trans;
852}
853
d0c2f4fa
FM
854/* Wait for a transaction commit to reach at least the given state. */
855static noinline void wait_for_commit(struct btrfs_transaction *commit,
856 const enum btrfs_trans_state min_state)
89ce8a63 857{
5fd76bf3
OS
858 struct btrfs_fs_info *fs_info = commit->fs_info;
859 u64 transid = commit->transid;
860 bool put = false;
861
862 while (1) {
863 wait_event(commit->commit_wait, commit->state >= min_state);
864 if (put)
865 btrfs_put_transaction(commit);
866
867 if (min_state < TRANS_STATE_COMPLETED)
868 break;
869
870 /*
871 * A transaction isn't really completed until all of the
872 * previous transactions are completed, but with fsync we can
873 * end up with SUPER_COMMITTED transactions before a COMPLETED
874 * transaction. Wait for those.
875 */
876
877 spin_lock(&fs_info->trans_lock);
878 commit = list_first_entry_or_null(&fs_info->trans_list,
879 struct btrfs_transaction,
880 list);
881 if (!commit || commit->transid > transid) {
882 spin_unlock(&fs_info->trans_lock);
883 break;
884 }
885 refcount_inc(&commit->use_count);
886 put = true;
887 spin_unlock(&fs_info->trans_lock);
888 }
89ce8a63
CM
889}
890
2ff7e61e 891int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
46204592
SW
892{
893 struct btrfs_transaction *cur_trans = NULL, *t;
8cd2807f 894 int ret = 0;
46204592 895
46204592 896 if (transid) {
0b246afa 897 if (transid <= fs_info->last_trans_committed)
a4abeea4 898 goto out;
46204592
SW
899
900 /* find specified transaction */
0b246afa
JM
901 spin_lock(&fs_info->trans_lock);
902 list_for_each_entry(t, &fs_info->trans_list, list) {
46204592
SW
903 if (t->transid == transid) {
904 cur_trans = t;
9b64f57d 905 refcount_inc(&cur_trans->use_count);
8cd2807f 906 ret = 0;
46204592
SW
907 break;
908 }
8cd2807f
MX
909 if (t->transid > transid) {
910 ret = 0;
46204592 911 break;
8cd2807f 912 }
46204592 913 }
0b246afa 914 spin_unlock(&fs_info->trans_lock);
42383020
SW
915
916 /*
917 * The specified transaction doesn't exist, or we
918 * raced with btrfs_commit_transaction
919 */
920 if (!cur_trans) {
0b246afa 921 if (transid > fs_info->last_trans_committed)
42383020 922 ret = -EINVAL;
8cd2807f 923 goto out;
42383020 924 }
46204592
SW
925 } else {
926 /* find newest transaction that is committing | committed */
0b246afa
JM
927 spin_lock(&fs_info->trans_lock);
928 list_for_each_entry_reverse(t, &fs_info->trans_list,
46204592 929 list) {
4a9d8bde
MX
930 if (t->state >= TRANS_STATE_COMMIT_START) {
931 if (t->state == TRANS_STATE_COMPLETED)
3473f3c0 932 break;
46204592 933 cur_trans = t;
9b64f57d 934 refcount_inc(&cur_trans->use_count);
46204592
SW
935 break;
936 }
937 }
0b246afa 938 spin_unlock(&fs_info->trans_lock);
46204592 939 if (!cur_trans)
a4abeea4 940 goto out; /* nothing committing|committed */
46204592
SW
941 }
942
d0c2f4fa 943 wait_for_commit(cur_trans, TRANS_STATE_COMPLETED);
724e2315 944 btrfs_put_transaction(cur_trans);
a4abeea4 945out:
46204592
SW
946 return ret;
947}
948
2ff7e61e 949void btrfs_throttle(struct btrfs_fs_info *fs_info)
37d1aeee 950{
92e2f7e3 951 wait_current_trans(fs_info);
37d1aeee
CM
952}
953
8a8f4dea 954static bool should_end_transaction(struct btrfs_trans_handle *trans)
8929ecfa 955{
2ff7e61e 956 struct btrfs_fs_info *fs_info = trans->fs_info;
0b246afa 957
64403612 958 if (btrfs_check_space_for_delayed_refs(fs_info))
8a8f4dea 959 return true;
36ba022a 960
2ff7e61e 961 return !!btrfs_block_rsv_check(&fs_info->global_block_rsv, 5);
8929ecfa
YZ
962}
963
a2633b6a 964bool btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
8929ecfa
YZ
965{
966 struct btrfs_transaction *cur_trans = trans->transaction;
8929ecfa 967
3296bf56 968 if (cur_trans->state >= TRANS_STATE_COMMIT_START ||
e19eb11f 969 test_bit(BTRFS_DELAYED_REFS_FLUSHING, &cur_trans->delayed_refs.flags))
a2633b6a 970 return true;
8929ecfa 971
2ff7e61e 972 return should_end_transaction(trans);
8929ecfa
YZ
973}
974
dc60c525
NB
975static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
976
0e34693f 977{
dc60c525
NB
978 struct btrfs_fs_info *fs_info = trans->fs_info;
979
0e34693f
NB
980 if (!trans->block_rsv) {
981 ASSERT(!trans->bytes_reserved);
982 return;
983 }
984
985 if (!trans->bytes_reserved)
986 return;
987
988 ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
989 trace_btrfs_space_reservation(fs_info, "transaction",
990 trans->transid, trans->bytes_reserved, 0);
991 btrfs_block_rsv_release(fs_info, trans->block_rsv,
63f018be 992 trans->bytes_reserved, NULL);
0e34693f
NB
993 trans->bytes_reserved = 0;
994}
995
89ce8a63 996static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
3a45bb20 997 int throttle)
79154b1b 998{
3a45bb20 999 struct btrfs_fs_info *info = trans->fs_info;
8929ecfa 1000 struct btrfs_transaction *cur_trans = trans->transaction;
4edc2ca3 1001 int err = 0;
c3e69d58 1002
b50fff81
DS
1003 if (refcount_read(&trans->use_count) > 1) {
1004 refcount_dec(&trans->use_count);
2a1eb461
JB
1005 trans->block_rsv = trans->orig_rsv;
1006 return 0;
1007 }
1008
dc60c525 1009 btrfs_trans_release_metadata(trans);
4c13d758 1010 trans->block_rsv = NULL;
c5567237 1011
119e80df 1012 btrfs_create_pending_block_groups(trans);
ea658bad 1013
4fbcdf66
FM
1014 btrfs_trans_release_chunk_metadata(trans);
1015
0860adfd 1016 if (trans->type & __TRANS_FREEZABLE)
0b246afa 1017 sb_end_intwrite(info->sb);
6df7881a 1018
8929ecfa 1019 WARN_ON(cur_trans != info->running_transaction);
13c5a93e
JB
1020 WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
1021 atomic_dec(&cur_trans->num_writers);
0860adfd 1022 extwriter_counter_dec(cur_trans, trans->type);
89ce8a63 1023
093258e6 1024 cond_wake_up(&cur_trans->writer_wait);
724e2315 1025 btrfs_put_transaction(cur_trans);
9ed74f2d
JB
1026
1027 if (current->journal_info == trans)
1028 current->journal_info = NULL;
ab78c84d 1029
24bbcf04 1030 if (throttle)
2ff7e61e 1031 btrfs_run_delayed_iputs(info);
24bbcf04 1032
84961539 1033 if (TRANS_ABORTED(trans) || BTRFS_FS_ERROR(info)) {
4e121c06 1034 wake_up_process(info->transaction_kthread);
fbabd4a3
JB
1035 if (TRANS_ABORTED(trans))
1036 err = trans->aborted;
1037 else
1038 err = -EROFS;
4e121c06 1039 }
49b25e05 1040
4edc2ca3
DJ
1041 kmem_cache_free(btrfs_trans_handle_cachep, trans);
1042 return err;
79154b1b
CM
1043}
1044
3a45bb20 1045int btrfs_end_transaction(struct btrfs_trans_handle *trans)
89ce8a63 1046{
3a45bb20 1047 return __btrfs_end_transaction(trans, 0);
89ce8a63
CM
1048}
1049
3a45bb20 1050int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
89ce8a63 1051{
3a45bb20 1052 return __btrfs_end_transaction(trans, 1);
16cdcec7
MX
1053}
1054
d352ac68
CM
1055/*
1056 * when btree blocks are allocated, they have some corresponding bits set for
1057 * them in one of two extent_io trees. This is used to make sure all of
690587d1 1058 * those extents are sent to disk but does not wait on them
d352ac68 1059 */
2ff7e61e 1060int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
8cef4e16 1061 struct extent_io_tree *dirty_pages, int mark)
79154b1b 1062{
777e6bd7 1063 int err = 0;
7c4452b9 1064 int werr = 0;
0b246afa 1065 struct address_space *mapping = fs_info->btree_inode->i_mapping;
e6138876 1066 struct extent_state *cached_state = NULL;
777e6bd7 1067 u64 start = 0;
5f39d397 1068 u64 end;
7c4452b9 1069
6300463b 1070 atomic_inc(&BTRFS_I(fs_info->btree_inode)->sync_writers);
1728366e 1071 while (!find_first_extent_bit(dirty_pages, start, &start, &end,
e6138876 1072 mark, &cached_state)) {
663dfbb0
FM
1073 bool wait_writeback = false;
1074
1075 err = convert_extent_bit(dirty_pages, start, end,
1076 EXTENT_NEED_WAIT,
210aa277 1077 mark, &cached_state);
663dfbb0
FM
1078 /*
1079 * convert_extent_bit can return -ENOMEM, which is most of the
1080 * time a temporary error. So when it happens, ignore the error
1081 * and wait for writeback of this range to finish - because we
1082 * failed to set the bit EXTENT_NEED_WAIT for the range, a call
bf89d38f
JM
1083 * to __btrfs_wait_marked_extents() would not know that
1084 * writeback for this range started and therefore wouldn't
1085 * wait for it to finish - we don't want to commit a
1086 * superblock that points to btree nodes/leafs for which
1087 * writeback hasn't finished yet (and without errors).
663dfbb0 1088 * We cleanup any entries left in the io tree when committing
41e7acd3 1089 * the transaction (through extent_io_tree_release()).
663dfbb0
FM
1090 */
1091 if (err == -ENOMEM) {
1092 err = 0;
1093 wait_writeback = true;
1094 }
1095 if (!err)
1096 err = filemap_fdatawrite_range(mapping, start, end);
1728366e
JB
1097 if (err)
1098 werr = err;
663dfbb0
FM
1099 else if (wait_writeback)
1100 werr = filemap_fdatawait_range(mapping, start, end);
e38e2ed7 1101 free_extent_state(cached_state);
663dfbb0 1102 cached_state = NULL;
1728366e
JB
1103 cond_resched();
1104 start = end + 1;
7c4452b9 1105 }
6300463b 1106 atomic_dec(&BTRFS_I(fs_info->btree_inode)->sync_writers);
690587d1
CM
1107 return werr;
1108}
1109
1110/*
1111 * when btree blocks are allocated, they have some corresponding bits set for
1112 * them in one of two extent_io trees. This is used to make sure all of
1113 * those extents are on disk for transaction or log commit. We wait
1114 * on all the pages and clear them from the dirty pages state tree
1115 */
bf89d38f
JM
1116static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
1117 struct extent_io_tree *dirty_pages)
690587d1 1118{
690587d1
CM
1119 int err = 0;
1120 int werr = 0;
0b246afa 1121 struct address_space *mapping = fs_info->btree_inode->i_mapping;
e6138876 1122 struct extent_state *cached_state = NULL;
690587d1
CM
1123 u64 start = 0;
1124 u64 end;
777e6bd7 1125
1728366e 1126 while (!find_first_extent_bit(dirty_pages, start, &start, &end,
e6138876 1127 EXTENT_NEED_WAIT, &cached_state)) {
663dfbb0
FM
1128 /*
1129 * Ignore -ENOMEM errors returned by clear_extent_bit().
1130 * When committing the transaction, we'll remove any entries
1131 * left in the io tree. For a log commit, we don't remove them
1132 * after committing the log because the tree can be accessed
1133 * concurrently - we do it only at transaction commit time when
41e7acd3 1134 * it's safe to do it (through extent_io_tree_release()).
663dfbb0
FM
1135 */
1136 err = clear_extent_bit(dirty_pages, start, end,
ae0f1625 1137 EXTENT_NEED_WAIT, 0, 0, &cached_state);
663dfbb0
FM
1138 if (err == -ENOMEM)
1139 err = 0;
1140 if (!err)
1141 err = filemap_fdatawait_range(mapping, start, end);
1728366e
JB
1142 if (err)
1143 werr = err;
e38e2ed7
FM
1144 free_extent_state(cached_state);
1145 cached_state = NULL;
1728366e
JB
1146 cond_resched();
1147 start = end + 1;
777e6bd7 1148 }
7c4452b9
CM
1149 if (err)
1150 werr = err;
bf89d38f
JM
1151 return werr;
1152}
656f30db 1153
b9fae2eb 1154static int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
bf89d38f
JM
1155 struct extent_io_tree *dirty_pages)
1156{
1157 bool errors = false;
1158 int err;
656f30db 1159
bf89d38f
JM
1160 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1161 if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1162 errors = true;
1163
1164 if (errors && !err)
1165 err = -EIO;
1166 return err;
1167}
656f30db 1168
bf89d38f
JM
1169int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
1170{
1171 struct btrfs_fs_info *fs_info = log_root->fs_info;
1172 struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
1173 bool errors = false;
1174 int err;
656f30db 1175
bf89d38f
JM
1176 ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
1177
1178 err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1179 if ((mark & EXTENT_DIRTY) &&
1180 test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1181 errors = true;
1182
1183 if ((mark & EXTENT_NEW) &&
1184 test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1185 errors = true;
1186
1187 if (errors && !err)
1188 err = -EIO;
1189 return err;
79154b1b
CM
1190}
1191
690587d1 1192/*
c9b577c0
NB
1193 * When btree blocks are allocated the corresponding extents are marked dirty.
1194 * This function ensures such extents are persisted on disk for transaction or
1195 * log commit.
1196 *
1197 * @trans: transaction whose dirty pages we'd like to write
690587d1 1198 */
70458a58 1199static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
690587d1
CM
1200{
1201 int ret;
1202 int ret2;
c9b577c0 1203 struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
70458a58 1204 struct btrfs_fs_info *fs_info = trans->fs_info;
c6adc9cc 1205 struct blk_plug plug;
690587d1 1206
c6adc9cc 1207 blk_start_plug(&plug);
c9b577c0 1208 ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
c6adc9cc 1209 blk_finish_plug(&plug);
bf89d38f 1210 ret2 = btrfs_wait_extents(fs_info, dirty_pages);
bf0da8c1 1211
41e7acd3 1212 extent_io_tree_release(&trans->transaction->dirty_pages);
c9b577c0 1213
bf0da8c1
CM
1214 if (ret)
1215 return ret;
c9b577c0 1216 else if (ret2)
bf0da8c1 1217 return ret2;
c9b577c0
NB
1218 else
1219 return 0;
d0c803c4
CM
1220}
1221
d352ac68
CM
1222/*
1223 * this is used to update the root pointer in the tree of tree roots.
1224 *
1225 * But, in the case of the extent allocation tree, updating the root
1226 * pointer may allocate blocks which may change the root of the extent
1227 * allocation tree.
1228 *
1229 * So, this loops and repeats and makes sure the cowonly root didn't
1230 * change while the root pointer was being updated in the metadata.
1231 */
0b86a832
CM
1232static int update_cowonly_root(struct btrfs_trans_handle *trans,
1233 struct btrfs_root *root)
79154b1b
CM
1234{
1235 int ret;
0b86a832 1236 u64 old_root_bytenr;
86b9f2ec 1237 u64 old_root_used;
0b246afa
JM
1238 struct btrfs_fs_info *fs_info = root->fs_info;
1239 struct btrfs_root *tree_root = fs_info->tree_root;
79154b1b 1240
86b9f2ec 1241 old_root_used = btrfs_root_used(&root->root_item);
56bec294 1242
d397712b 1243 while (1) {
0b86a832 1244 old_root_bytenr = btrfs_root_bytenr(&root->root_item);
86b9f2ec 1245 if (old_root_bytenr == root->node->start &&
ea526d18 1246 old_root_used == btrfs_root_used(&root->root_item))
79154b1b 1247 break;
87ef2bb4 1248
5d4f98a2 1249 btrfs_set_root_node(&root->root_item, root->node);
79154b1b 1250 ret = btrfs_update_root(trans, tree_root,
0b86a832
CM
1251 &root->root_key,
1252 &root->root_item);
49b25e05
JM
1253 if (ret)
1254 return ret;
56bec294 1255
86b9f2ec 1256 old_root_used = btrfs_root_used(&root->root_item);
0b86a832 1257 }
276e680d 1258
0b86a832
CM
1259 return 0;
1260}
1261
d352ac68
CM
1262/*
1263 * update all the cowonly tree roots on disk
49b25e05
JM
1264 *
1265 * The error handling in this function may not be obvious. Any of the
1266 * failures will cause the file system to go offline. We still need
1267 * to clean up the delayed refs.
d352ac68 1268 */
9386d8bc 1269static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
0b86a832 1270{
9386d8bc 1271 struct btrfs_fs_info *fs_info = trans->fs_info;
ea526d18 1272 struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
1bbc621e 1273 struct list_head *io_bgs = &trans->transaction->io_bgs;
0b86a832 1274 struct list_head *next;
84234f3a 1275 struct extent_buffer *eb;
56bec294 1276 int ret;
84234f3a 1277
dfba78dc
FM
1278 /*
1279 * At this point no one can be using this transaction to modify any tree
1280 * and no one can start another transaction to modify any tree either.
1281 */
1282 ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1283
84234f3a 1284 eb = btrfs_lock_root_node(fs_info->tree_root);
49b25e05 1285 ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
9631e4cc 1286 0, &eb, BTRFS_NESTING_COW);
84234f3a
YZ
1287 btrfs_tree_unlock(eb);
1288 free_extent_buffer(eb);
0b86a832 1289
49b25e05
JM
1290 if (ret)
1291 return ret;
87ef2bb4 1292
196c9d8d 1293 ret = btrfs_run_dev_stats(trans);
c16ce190
JB
1294 if (ret)
1295 return ret;
2b584c68 1296 ret = btrfs_run_dev_replace(trans);
c16ce190
JB
1297 if (ret)
1298 return ret;
280f8bd2 1299 ret = btrfs_run_qgroups(trans);
c16ce190
JB
1300 if (ret)
1301 return ret;
546adb0d 1302
bbebb3e0 1303 ret = btrfs_setup_space_cache(trans);
dcdf7f6d
JB
1304 if (ret)
1305 return ret;
1306
ea526d18 1307again:
d397712b 1308 while (!list_empty(&fs_info->dirty_cowonly_roots)) {
2ff7e61e 1309 struct btrfs_root *root;
0b86a832
CM
1310 next = fs_info->dirty_cowonly_roots.next;
1311 list_del_init(next);
1312 root = list_entry(next, struct btrfs_root, dirty_list);
e7070be1 1313 clear_bit(BTRFS_ROOT_DIRTY, &root->state);
87ef2bb4 1314
826582ca
JB
1315 list_add_tail(&root->dirty_list,
1316 &trans->transaction->switch_commits);
49b25e05
JM
1317 ret = update_cowonly_root(trans, root);
1318 if (ret)
1319 return ret;
79154b1b 1320 }
276e680d 1321
488bc2a2
JB
1322 /* Now flush any delayed refs generated by updating all of the roots */
1323 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1324 if (ret)
1325 return ret;
1326
1bbc621e 1327 while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
5742d15f 1328 ret = btrfs_write_dirty_block_groups(trans);
ea526d18
JB
1329 if (ret)
1330 return ret;
488bc2a2
JB
1331
1332 /*
1333 * We're writing the dirty block groups, which could generate
1334 * delayed refs, which could generate more dirty block groups,
1335 * so we want to keep this flushing in this loop to make sure
1336 * everything gets run.
1337 */
c79a70b1 1338 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
ea526d18
JB
1339 if (ret)
1340 return ret;
1341 }
1342
1343 if (!list_empty(&fs_info->dirty_cowonly_roots))
1344 goto again;
1345
9f6cbcbb
DS
1346 /* Update dev-replace pointer once everything is committed */
1347 fs_info->dev_replace.committed_cursor_left =
1348 fs_info->dev_replace.cursor_left_last_write_of_item;
8dabb742 1349
79154b1b
CM
1350 return 0;
1351}
1352
b4be6aef
JB
1353/*
1354 * If we had a pending drop we need to see if there are any others left in our
1355 * dead roots list, and if not clear our bit and wake any waiters.
1356 */
1357void btrfs_maybe_wake_unfinished_drop(struct btrfs_fs_info *fs_info)
1358{
1359 /*
1360 * We put the drop in progress roots at the front of the list, so if the
1361 * first entry doesn't have UNFINISHED_DROP set we can wake everybody
1362 * up.
1363 */
1364 spin_lock(&fs_info->trans_lock);
1365 if (!list_empty(&fs_info->dead_roots)) {
1366 struct btrfs_root *root = list_first_entry(&fs_info->dead_roots,
1367 struct btrfs_root,
1368 root_list);
1369 if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state)) {
1370 spin_unlock(&fs_info->trans_lock);
1371 return;
1372 }
1373 }
1374 spin_unlock(&fs_info->trans_lock);
1375
1376 btrfs_wake_unfinished_drop(fs_info);
1377}
1378
d352ac68
CM
1379/*
1380 * dead roots are old snapshots that need to be deleted. This allocates
1381 * a dirty root struct and adds it into the list of dead roots that need to
1382 * be deleted
1383 */
cfad392b 1384void btrfs_add_dead_root(struct btrfs_root *root)
5eda7b5e 1385{
0b246afa
JM
1386 struct btrfs_fs_info *fs_info = root->fs_info;
1387
1388 spin_lock(&fs_info->trans_lock);
dc9492c1
JB
1389 if (list_empty(&root->root_list)) {
1390 btrfs_grab_root(root);
b4be6aef
JB
1391
1392 /* We want to process the partially complete drops first. */
1393 if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state))
1394 list_add(&root->root_list, &fs_info->dead_roots);
1395 else
1396 list_add_tail(&root->root_list, &fs_info->dead_roots);
dc9492c1 1397 }
0b246afa 1398 spin_unlock(&fs_info->trans_lock);
5eda7b5e
CM
1399}
1400
d352ac68 1401/*
dfba78dc
FM
1402 * Update each subvolume root and its relocation root, if it exists, in the tree
1403 * of tree roots. Also free log roots if they exist.
d352ac68 1404 */
7e4443d9 1405static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
0f7d52f4 1406{
7e4443d9 1407 struct btrfs_fs_info *fs_info = trans->fs_info;
fc7cbcd4
DS
1408 struct btrfs_root *gang[8];
1409 int i;
1410 int ret;
54aa1f4d 1411
dfba78dc
FM
1412 /*
1413 * At this point no one can be using this transaction to modify any tree
1414 * and no one can start another transaction to modify any tree either.
1415 */
1416 ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1417
fc7cbcd4
DS
1418 spin_lock(&fs_info->fs_roots_radix_lock);
1419 while (1) {
1420 ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
1421 (void **)gang, 0,
1422 ARRAY_SIZE(gang),
1423 BTRFS_ROOT_TRANS_TAG);
1424 if (ret == 0)
1425 break;
1426 for (i = 0; i < ret; i++) {
1427 struct btrfs_root *root = gang[i];
1428 int ret2;
1429
1430 /*
1431 * At this point we can neither have tasks logging inodes
1432 * from a root nor trying to commit a log tree.
1433 */
1434 ASSERT(atomic_read(&root->log_writers) == 0);
1435 ASSERT(atomic_read(&root->log_commit[0]) == 0);
1436 ASSERT(atomic_read(&root->log_commit[1]) == 0);
1437
1438 radix_tree_tag_clear(&fs_info->fs_roots_radix,
1439 (unsigned long)root->root_key.objectid,
1440 BTRFS_ROOT_TRANS_TAG);
1441 spin_unlock(&fs_info->fs_roots_radix_lock);
1442
1443 btrfs_free_log(trans, root);
1444 ret2 = btrfs_update_reloc_root(trans, root);
1445 if (ret2)
1446 return ret2;
1447
1448 /* see comments in should_cow_block() */
1449 clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1450 smp_mb__after_atomic();
1451
1452 if (root->commit_root != root->node) {
1453 list_add_tail(&root->dirty_list,
1454 &trans->transaction->switch_commits);
1455 btrfs_set_root_node(&root->root_item,
1456 root->node);
1457 }
48b36a60 1458
fc7cbcd4
DS
1459 ret2 = btrfs_update_root(trans, fs_info->tree_root,
1460 &root->root_key,
1461 &root->root_item);
1462 if (ret2)
1463 return ret2;
1464 spin_lock(&fs_info->fs_roots_radix_lock);
1465 btrfs_qgroup_free_meta_all_pertrans(root);
0f7d52f4
CM
1466 }
1467 }
fc7cbcd4 1468 spin_unlock(&fs_info->fs_roots_radix_lock);
4f4317c1 1469 return 0;
0f7d52f4
CM
1470}
1471
d352ac68 1472/*
de78b51a
ES
1473 * defrag a given btree.
1474 * Every leaf in the btree is read and defragged.
d352ac68 1475 */
de78b51a 1476int btrfs_defrag_root(struct btrfs_root *root)
e9d0b13b
CM
1477{
1478 struct btrfs_fs_info *info = root->fs_info;
e9d0b13b 1479 struct btrfs_trans_handle *trans;
8929ecfa 1480 int ret;
e9d0b13b 1481
27cdeb70 1482 if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
e9d0b13b 1483 return 0;
8929ecfa 1484
6b80053d 1485 while (1) {
8929ecfa 1486 trans = btrfs_start_transaction(root, 0);
6819703f
DS
1487 if (IS_ERR(trans)) {
1488 ret = PTR_ERR(trans);
1489 break;
1490 }
8929ecfa 1491
de78b51a 1492 ret = btrfs_defrag_leaves(trans, root);
8929ecfa 1493
3a45bb20 1494 btrfs_end_transaction(trans);
2ff7e61e 1495 btrfs_btree_balance_dirty(info);
e9d0b13b
CM
1496 cond_resched();
1497
ab8d0fc4 1498 if (btrfs_fs_closing(info) || ret != -EAGAIN)
e9d0b13b 1499 break;
210549eb 1500
ab8d0fc4
JM
1501 if (btrfs_defrag_cancelled(info)) {
1502 btrfs_debug(info, "defrag_root cancelled");
210549eb
DS
1503 ret = -EAGAIN;
1504 break;
1505 }
e9d0b13b 1506 }
27cdeb70 1507 clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
8929ecfa 1508 return ret;
e9d0b13b
CM
1509}
1510
6426c7ad
QW
1511/*
1512 * Do all special snapshot related qgroup dirty hack.
1513 *
1514 * Will do all needed qgroup inherit and dirty hack like switch commit
1515 * roots inside one transaction and write all btree into disk, to make
1516 * qgroup works.
1517 */
1518static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
1519 struct btrfs_root *src,
1520 struct btrfs_root *parent,
1521 struct btrfs_qgroup_inherit *inherit,
1522 u64 dst_objectid)
1523{
1524 struct btrfs_fs_info *fs_info = src->fs_info;
1525 int ret;
1526
1527 /*
1528 * Save some performance in the case that qgroups are not
1529 * enabled. If this check races with the ioctl, rescan will
1530 * kick in anyway.
1531 */
9ea6e2b5 1532 if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
6426c7ad 1533 return 0;
6426c7ad 1534
4d31778a 1535 /*
52042d8e 1536 * Ensure dirty @src will be committed. Or, after coming
4d31778a
QW
1537 * commit_fs_roots() and switch_commit_roots(), any dirty but not
1538 * recorded root will never be updated again, causing an outdated root
1539 * item.
1540 */
1c442d22
JB
1541 ret = record_root_in_trans(trans, src, 1);
1542 if (ret)
1543 return ret;
4d31778a 1544
2a4d84c1
JB
1545 /*
1546 * btrfs_qgroup_inherit relies on a consistent view of the usage for the
1547 * src root, so we must run the delayed refs here.
1548 *
1549 * However this isn't particularly fool proof, because there's no
1550 * synchronization keeping us from changing the tree after this point
1551 * before we do the qgroup_inherit, or even from making changes while
1552 * we're doing the qgroup_inherit. But that's a problem for the future,
1553 * for now flush the delayed refs to narrow the race window where the
1554 * qgroup counters could end up wrong.
1555 */
1556 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1557 if (ret) {
1558 btrfs_abort_transaction(trans, ret);
44365827 1559 return ret;
2a4d84c1
JB
1560 }
1561
7e4443d9 1562 ret = commit_fs_roots(trans);
6426c7ad
QW
1563 if (ret)
1564 goto out;
460fb20a 1565 ret = btrfs_qgroup_account_extents(trans);
6426c7ad
QW
1566 if (ret < 0)
1567 goto out;
1568
1569 /* Now qgroup are all updated, we can inherit it to new qgroups */
a9377422 1570 ret = btrfs_qgroup_inherit(trans, src->root_key.objectid, dst_objectid,
6426c7ad
QW
1571 inherit);
1572 if (ret < 0)
1573 goto out;
1574
1575 /*
1576 * Now we do a simplified commit transaction, which will:
1577 * 1) commit all subvolume and extent tree
1578 * To ensure all subvolume and extent tree have a valid
1579 * commit_root to accounting later insert_dir_item()
1580 * 2) write all btree blocks onto disk
1581 * This is to make sure later btree modification will be cowed
1582 * Or commit_root can be populated and cause wrong qgroup numbers
1583 * In this simplified commit, we don't really care about other trees
1584 * like chunk and root tree, as they won't affect qgroup.
1585 * And we don't write super to avoid half committed status.
1586 */
9386d8bc 1587 ret = commit_cowonly_roots(trans);
6426c7ad
QW
1588 if (ret)
1589 goto out;
889bfa39 1590 switch_commit_roots(trans);
70458a58 1591 ret = btrfs_write_and_wait_transaction(trans);
6426c7ad 1592 if (ret)
f7af3934 1593 btrfs_handle_fs_error(fs_info, ret,
6426c7ad
QW
1594 "Error while writing out transaction for qgroup");
1595
1596out:
6426c7ad
QW
1597 /*
1598 * Force parent root to be updated, as we recorded it before so its
1599 * last_trans == cur_transid.
1600 * Or it won't be committed again onto disk after later
1601 * insert_dir_item()
1602 */
1603 if (!ret)
1c442d22 1604 ret = record_root_in_trans(trans, parent, 1);
6426c7ad
QW
1605 return ret;
1606}
1607
d352ac68
CM
1608/*
1609 * new snapshots need to be created at a very specific time in the
aec8030a
MX
1610 * transaction commit. This does the actual creation.
1611 *
1612 * Note:
1613 * If the error which may affect the commitment of the current transaction
1614 * happens, we should return the error number. If the error which just affect
1615 * the creation of the pending snapshots, just return 0.
d352ac68 1616 */
80b6794d 1617static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
3063d29f
CM
1618 struct btrfs_pending_snapshot *pending)
1619{
08d50ca3
NB
1620
1621 struct btrfs_fs_info *fs_info = trans->fs_info;
3063d29f 1622 struct btrfs_key key;
80b6794d 1623 struct btrfs_root_item *new_root_item;
3063d29f
CM
1624 struct btrfs_root *tree_root = fs_info->tree_root;
1625 struct btrfs_root *root = pending->root;
6bdb72de 1626 struct btrfs_root *parent_root;
98c9942a 1627 struct btrfs_block_rsv *rsv;
6bdb72de 1628 struct inode *parent_inode;
42874b3d
MX
1629 struct btrfs_path *path;
1630 struct btrfs_dir_item *dir_item;
a22285a6 1631 struct dentry *dentry;
3063d29f 1632 struct extent_buffer *tmp;
925baedd 1633 struct extent_buffer *old;
95582b00 1634 struct timespec64 cur_time;
aec8030a 1635 int ret = 0;
d68fc57b 1636 u64 to_reserve = 0;
6bdb72de 1637 u64 index = 0;
a22285a6 1638 u64 objectid;
b83cc969 1639 u64 root_flags;
3063d29f 1640
8546b570
DS
1641 ASSERT(pending->path);
1642 path = pending->path;
42874b3d 1643
b0c0ea63
DS
1644 ASSERT(pending->root_item);
1645 new_root_item = pending->root_item;
a22285a6 1646
543068a2 1647 pending->error = btrfs_get_free_objectid(tree_root, &objectid);
aec8030a 1648 if (pending->error)
6fa9700e 1649 goto no_free_objectid;
3063d29f 1650
d6726335
QW
1651 /*
1652 * Make qgroup to skip current new snapshot's qgroupid, as it is
1653 * accounted by later btrfs_qgroup_inherit().
1654 */
1655 btrfs_set_skip_qgroup(trans, objectid);
1656
147d256e 1657 btrfs_reloc_pre_snapshot(pending, &to_reserve);
d68fc57b
YZ
1658
1659 if (to_reserve > 0) {
9270501c 1660 pending->error = btrfs_block_rsv_add(fs_info,
aec8030a
MX
1661 &pending->block_rsv,
1662 to_reserve,
1663 BTRFS_RESERVE_NO_FLUSH);
1664 if (pending->error)
d6726335 1665 goto clear_skip_qgroup;
d68fc57b
YZ
1666 }
1667
3063d29f 1668 key.objectid = objectid;
a22285a6
YZ
1669 key.offset = (u64)-1;
1670 key.type = BTRFS_ROOT_ITEM_KEY;
3063d29f 1671
6fa9700e 1672 rsv = trans->block_rsv;
a22285a6 1673 trans->block_rsv = &pending->block_rsv;
2382c5cc 1674 trans->bytes_reserved = trans->block_rsv->reserved;
0b246afa 1675 trace_btrfs_space_reservation(fs_info, "transaction",
88d3a5aa
JB
1676 trans->transid,
1677 trans->bytes_reserved, 1);
a22285a6 1678 dentry = pending->dentry;
e9662f70 1679 parent_inode = pending->dir;
a22285a6 1680 parent_root = BTRFS_I(parent_inode)->root;
f0118cb6
JB
1681 ret = record_root_in_trans(trans, parent_root, 0);
1682 if (ret)
1683 goto fail;
c2050a45 1684 cur_time = current_time(parent_inode);
04b285f3 1685
3063d29f
CM
1686 /*
1687 * insert the directory item
1688 */
877574e2 1689 ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
49b25e05 1690 BUG_ON(ret); /* -ENOMEM */
42874b3d
MX
1691
1692 /* check if there is a file/dir which has the same name. */
1693 dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
4a0cc7ca 1694 btrfs_ino(BTRFS_I(parent_inode)),
42874b3d
MX
1695 dentry->d_name.name,
1696 dentry->d_name.len, 0);
1697 if (dir_item != NULL && !IS_ERR(dir_item)) {
fe66a05a 1698 pending->error = -EEXIST;
aec8030a 1699 goto dir_item_existed;
42874b3d
MX
1700 } else if (IS_ERR(dir_item)) {
1701 ret = PTR_ERR(dir_item);
66642832 1702 btrfs_abort_transaction(trans, ret);
8732d44f 1703 goto fail;
79787eaa 1704 }
42874b3d 1705 btrfs_release_path(path);
52c26179 1706
e999376f
CM
1707 /*
1708 * pull in the delayed directory update
1709 * and the delayed inode item
1710 * otherwise we corrupt the FS during
1711 * snapshot
1712 */
e5c304e6 1713 ret = btrfs_run_delayed_items(trans);
8732d44f 1714 if (ret) { /* Transaction aborted */
66642832 1715 btrfs_abort_transaction(trans, ret);
8732d44f
MX
1716 goto fail;
1717 }
e999376f 1718
f0118cb6
JB
1719 ret = record_root_in_trans(trans, root, 0);
1720 if (ret) {
1721 btrfs_abort_transaction(trans, ret);
1722 goto fail;
1723 }
6bdb72de
SW
1724 btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
1725 memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
08fe4db1 1726 btrfs_check_and_init_root_item(new_root_item);
6bdb72de 1727
b83cc969
LZ
1728 root_flags = btrfs_root_flags(new_root_item);
1729 if (pending->readonly)
1730 root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1731 else
1732 root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1733 btrfs_set_root_flags(new_root_item, root_flags);
1734
8ea05e3a
AB
1735 btrfs_set_root_generation_v2(new_root_item,
1736 trans->transid);
807fc790 1737 generate_random_guid(new_root_item->uuid);
8ea05e3a
AB
1738 memcpy(new_root_item->parent_uuid, root->root_item.uuid,
1739 BTRFS_UUID_SIZE);
70023da2
SB
1740 if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
1741 memset(new_root_item->received_uuid, 0,
1742 sizeof(new_root_item->received_uuid));
1743 memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
1744 memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
1745 btrfs_set_root_stransid(new_root_item, 0);
1746 btrfs_set_root_rtransid(new_root_item, 0);
1747 }
3cae210f
QW
1748 btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
1749 btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
8ea05e3a 1750 btrfs_set_root_otransid(new_root_item, trans->transid);
8ea05e3a 1751
6bdb72de 1752 old = btrfs_lock_root_node(root);
9631e4cc
JB
1753 ret = btrfs_cow_block(trans, root, old, NULL, 0, &old,
1754 BTRFS_NESTING_COW);
79787eaa
JM
1755 if (ret) {
1756 btrfs_tree_unlock(old);
1757 free_extent_buffer(old);
66642832 1758 btrfs_abort_transaction(trans, ret);
8732d44f 1759 goto fail;
79787eaa 1760 }
49b25e05 1761
49b25e05 1762 ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
79787eaa 1763 /* clean up in any case */
6bdb72de
SW
1764 btrfs_tree_unlock(old);
1765 free_extent_buffer(old);
8732d44f 1766 if (ret) {
66642832 1767 btrfs_abort_transaction(trans, ret);
8732d44f
MX
1768 goto fail;
1769 }
f1ebcc74 1770 /* see comments in should_cow_block() */
27cdeb70 1771 set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
f1ebcc74
LB
1772 smp_wmb();
1773
6bdb72de 1774 btrfs_set_root_node(new_root_item, tmp);
a22285a6
YZ
1775 /* record when the snapshot was created in key.offset */
1776 key.offset = trans->transid;
1777 ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
6bdb72de
SW
1778 btrfs_tree_unlock(tmp);
1779 free_extent_buffer(tmp);
8732d44f 1780 if (ret) {
66642832 1781 btrfs_abort_transaction(trans, ret);
8732d44f
MX
1782 goto fail;
1783 }
6bdb72de 1784
a22285a6
YZ
1785 /*
1786 * insert root back/forward references
1787 */
6025c19f 1788 ret = btrfs_add_root_ref(trans, objectid,
0660b5af 1789 parent_root->root_key.objectid,
4a0cc7ca 1790 btrfs_ino(BTRFS_I(parent_inode)), index,
a22285a6 1791 dentry->d_name.name, dentry->d_name.len);
8732d44f 1792 if (ret) {
66642832 1793 btrfs_abort_transaction(trans, ret);
8732d44f
MX
1794 goto fail;
1795 }
0660b5af 1796
a22285a6 1797 key.offset = (u64)-1;
2dfb1e43 1798 pending->snap = btrfs_get_new_fs_root(fs_info, objectid, pending->anon_dev);
79787eaa
JM
1799 if (IS_ERR(pending->snap)) {
1800 ret = PTR_ERR(pending->snap);
2d892ccd 1801 pending->snap = NULL;
66642832 1802 btrfs_abort_transaction(trans, ret);
8732d44f 1803 goto fail;
79787eaa 1804 }
d68fc57b 1805
49b25e05 1806 ret = btrfs_reloc_post_snapshot(trans, pending);
8732d44f 1807 if (ret) {
66642832 1808 btrfs_abort_transaction(trans, ret);
8732d44f
MX
1809 goto fail;
1810 }
361048f5 1811
6426c7ad
QW
1812 /*
1813 * Do special qgroup accounting for snapshot, as we do some qgroup
1814 * snapshot hack to do fast snapshot.
1815 * To co-operate with that hack, we do hack again.
1816 * Or snapshot will be greatly slowed down by a subtree qgroup rescan
1817 */
1818 ret = qgroup_account_snapshot(trans, root, parent_root,
1819 pending->inherit, objectid);
1820 if (ret < 0)
1821 goto fail;
1822
684572df
LF
1823 ret = btrfs_insert_dir_item(trans, dentry->d_name.name,
1824 dentry->d_name.len, BTRFS_I(parent_inode),
1825 &key, BTRFS_FT_DIR, index);
42874b3d 1826 /* We have check then name at the beginning, so it is impossible. */
9c52057c 1827 BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
8732d44f 1828 if (ret) {
66642832 1829 btrfs_abort_transaction(trans, ret);
8732d44f
MX
1830 goto fail;
1831 }
42874b3d 1832
6ef06d27 1833 btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
42874b3d 1834 dentry->d_name.len * 2);
c1867eb3
DS
1835 parent_inode->i_mtime = current_time(parent_inode);
1836 parent_inode->i_ctime = parent_inode->i_mtime;
729f7961 1837 ret = btrfs_update_inode_fallback(trans, parent_root, BTRFS_I(parent_inode));
dd5f9615 1838 if (ret) {
66642832 1839 btrfs_abort_transaction(trans, ret);
dd5f9615
SB
1840 goto fail;
1841 }
807fc790
AS
1842 ret = btrfs_uuid_tree_add(trans, new_root_item->uuid,
1843 BTRFS_UUID_KEY_SUBVOL,
cdb345a8 1844 objectid);
dd5f9615 1845 if (ret) {
66642832 1846 btrfs_abort_transaction(trans, ret);
dd5f9615
SB
1847 goto fail;
1848 }
1849 if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
cdb345a8 1850 ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
dd5f9615
SB
1851 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1852 objectid);
1853 if (ret && ret != -EEXIST) {
66642832 1854 btrfs_abort_transaction(trans, ret);
dd5f9615
SB
1855 goto fail;
1856 }
1857 }
d6726335 1858
3063d29f 1859fail:
aec8030a
MX
1860 pending->error = ret;
1861dir_item_existed:
98c9942a 1862 trans->block_rsv = rsv;
2382c5cc 1863 trans->bytes_reserved = 0;
d6726335
QW
1864clear_skip_qgroup:
1865 btrfs_clear_skip_qgroup(trans);
6fa9700e
MX
1866no_free_objectid:
1867 kfree(new_root_item);
b0c0ea63 1868 pending->root_item = NULL;
42874b3d 1869 btrfs_free_path(path);
8546b570
DS
1870 pending->path = NULL;
1871
49b25e05 1872 return ret;
3063d29f
CM
1873}
1874
d352ac68
CM
1875/*
1876 * create all the snapshots we've scheduled for creation
1877 */
08d50ca3 1878static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
3de4586c 1879{
aec8030a 1880 struct btrfs_pending_snapshot *pending, *next;
3de4586c 1881 struct list_head *head = &trans->transaction->pending_snapshots;
aec8030a 1882 int ret = 0;
3de4586c 1883
aec8030a
MX
1884 list_for_each_entry_safe(pending, next, head, list) {
1885 list_del(&pending->list);
08d50ca3 1886 ret = create_pending_snapshot(trans, pending);
aec8030a
MX
1887 if (ret)
1888 break;
1889 }
1890 return ret;
3de4586c
CM
1891}
1892
2ff7e61e 1893static void update_super_roots(struct btrfs_fs_info *fs_info)
5d4f98a2
YZ
1894{
1895 struct btrfs_root_item *root_item;
1896 struct btrfs_super_block *super;
1897
0b246afa 1898 super = fs_info->super_copy;
5d4f98a2 1899
0b246afa 1900 root_item = &fs_info->chunk_root->root_item;
093e037c
DS
1901 super->chunk_root = root_item->bytenr;
1902 super->chunk_root_generation = root_item->generation;
1903 super->chunk_root_level = root_item->level;
5d4f98a2 1904
0b246afa 1905 root_item = &fs_info->tree_root->root_item;
093e037c
DS
1906 super->root = root_item->bytenr;
1907 super->generation = root_item->generation;
1908 super->root_level = root_item->level;
0b246afa 1909 if (btrfs_test_opt(fs_info, SPACE_CACHE))
093e037c 1910 super->cache_generation = root_item->generation;
94846229
BB
1911 else if (test_bit(BTRFS_FS_CLEANUP_SPACE_CACHE_V1, &fs_info->flags))
1912 super->cache_generation = 0;
0b246afa 1913 if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
093e037c 1914 super->uuid_tree_generation = root_item->generation;
f7238e50
JB
1915
1916 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
1917 root_item = &fs_info->block_group_root->root_item;
1918
1919 super->block_group_root = root_item->bytenr;
1920 super->block_group_root_generation = root_item->generation;
1921 super->block_group_root_level = root_item->level;
1922 }
5d4f98a2
YZ
1923}
1924
f36f3042
CM
1925int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1926{
4a9d8bde 1927 struct btrfs_transaction *trans;
f36f3042 1928 int ret = 0;
4a9d8bde 1929
a4abeea4 1930 spin_lock(&info->trans_lock);
4a9d8bde
MX
1931 trans = info->running_transaction;
1932 if (trans)
1933 ret = (trans->state >= TRANS_STATE_COMMIT_START);
a4abeea4 1934 spin_unlock(&info->trans_lock);
f36f3042
CM
1935 return ret;
1936}
1937
8929ecfa
YZ
1938int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1939{
4a9d8bde 1940 struct btrfs_transaction *trans;
8929ecfa 1941 int ret = 0;
4a9d8bde 1942
a4abeea4 1943 spin_lock(&info->trans_lock);
4a9d8bde
MX
1944 trans = info->running_transaction;
1945 if (trans)
1946 ret = is_transaction_blocked(trans);
a4abeea4 1947 spin_unlock(&info->trans_lock);
8929ecfa
YZ
1948 return ret;
1949}
1950
fdfbf020 1951void btrfs_commit_transaction_async(struct btrfs_trans_handle *trans)
bb9c12c9 1952{
3a45bb20 1953 struct btrfs_fs_info *fs_info = trans->fs_info;
bb9c12c9
SW
1954 struct btrfs_transaction *cur_trans;
1955
fdfbf020
JB
1956 /* Kick the transaction kthread. */
1957 set_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
1958 wake_up_process(fs_info->transaction_kthread);
bb9c12c9
SW
1959
1960 /* take transaction reference */
bb9c12c9 1961 cur_trans = trans->transaction;
9b64f57d 1962 refcount_inc(&cur_trans->use_count);
bb9c12c9 1963
3a45bb20 1964 btrfs_end_transaction(trans);
6fc4e354 1965
ae5d29d4
DS
1966 /*
1967 * Wait for the current transaction commit to start and block
1968 * subsequent transaction joins
1969 */
1970 wait_event(fs_info->transaction_blocked_wait,
1971 cur_trans->state >= TRANS_STATE_COMMIT_START ||
1972 TRANS_ABORTED(cur_trans));
724e2315 1973 btrfs_put_transaction(cur_trans);
bb9c12c9
SW
1974}
1975
97cb39bb 1976static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
49b25e05 1977{
97cb39bb 1978 struct btrfs_fs_info *fs_info = trans->fs_info;
49b25e05
JM
1979 struct btrfs_transaction *cur_trans = trans->transaction;
1980
b50fff81 1981 WARN_ON(refcount_read(&trans->use_count) > 1);
49b25e05 1982
66642832 1983 btrfs_abort_transaction(trans, err);
7b8b92af 1984
0b246afa 1985 spin_lock(&fs_info->trans_lock);
66b6135b 1986
25d8c284
MX
1987 /*
1988 * If the transaction is removed from the list, it means this
1989 * transaction has been committed successfully, so it is impossible
1990 * to call the cleanup function.
1991 */
1992 BUG_ON(list_empty(&cur_trans->list));
66b6135b 1993
0b246afa 1994 if (cur_trans == fs_info->running_transaction) {
4a9d8bde 1995 cur_trans->state = TRANS_STATE_COMMIT_DOING;
0b246afa 1996 spin_unlock(&fs_info->trans_lock);
f094ac32
LB
1997 wait_event(cur_trans->writer_wait,
1998 atomic_read(&cur_trans->num_writers) == 1);
1999
0b246afa 2000 spin_lock(&fs_info->trans_lock);
d7096fc3 2001 }
061dde82
FM
2002
2003 /*
2004 * Now that we know no one else is still using the transaction we can
2005 * remove the transaction from the list of transactions. This avoids
2006 * the transaction kthread from cleaning up the transaction while some
2007 * other task is still using it, which could result in a use-after-free
2008 * on things like log trees, as it forces the transaction kthread to
2009 * wait for this transaction to be cleaned up by us.
2010 */
2011 list_del_init(&cur_trans->list);
2012
0b246afa 2013 spin_unlock(&fs_info->trans_lock);
49b25e05 2014
2ff7e61e 2015 btrfs_cleanup_one_transaction(trans->transaction, fs_info);
49b25e05 2016
0b246afa
JM
2017 spin_lock(&fs_info->trans_lock);
2018 if (cur_trans == fs_info->running_transaction)
2019 fs_info->running_transaction = NULL;
2020 spin_unlock(&fs_info->trans_lock);
4a9d8bde 2021
e0228285 2022 if (trans->type & __TRANS_FREEZABLE)
0b246afa 2023 sb_end_intwrite(fs_info->sb);
724e2315
JB
2024 btrfs_put_transaction(cur_trans);
2025 btrfs_put_transaction(cur_trans);
49b25e05 2026
2e4e97ab 2027 trace_btrfs_transaction_commit(fs_info);
49b25e05 2028
49b25e05
JM
2029 if (current->journal_info == trans)
2030 current->journal_info = NULL;
0b246afa 2031 btrfs_scrub_cancel(fs_info);
49b25e05
JM
2032
2033 kmem_cache_free(btrfs_trans_handle_cachep, trans);
2034}
2035
c7cc64a9
DS
2036/*
2037 * Release reserved delayed ref space of all pending block groups of the
2038 * transaction and remove them from the list
2039 */
2040static void btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle *trans)
2041{
2042 struct btrfs_fs_info *fs_info = trans->fs_info;
32da5386 2043 struct btrfs_block_group *block_group, *tmp;
c7cc64a9
DS
2044
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);
2048 }
2049}
2050
88090ad3 2051static inline int btrfs_start_delalloc_flush(struct btrfs_fs_info *fs_info)
82436617 2052{
ce8ea7cc 2053 /*
a0f0cf83 2054 * We use try_to_writeback_inodes_sb() here because if we used
ce8ea7cc
JB
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.
a0f0cf83
FM
2061 *
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.
ce8ea7cc 2069 */
88090ad3 2070 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
a0f0cf83 2071 try_to_writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
82436617
MX
2072 return 0;
2073}
2074
88090ad3 2075static inline void btrfs_wait_delalloc_flush(struct btrfs_fs_info *fs_info)
82436617 2076{
88090ad3 2077 if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
6374e57a 2078 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
82436617
MX
2079}
2080
28b21c55
FM
2081/*
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()
2087 * returns an error.
2088 */
2089static void add_pending_snapshot(struct btrfs_trans_handle *trans)
2090{
2091 struct btrfs_transaction *cur_trans = trans->transaction;
2092
2093 if (!trans->pending_snapshot)
2094 return;
2095
2096 lockdep_assert_held(&trans->fs_info->trans_lock);
2097 ASSERT(cur_trans->state >= TRANS_STATE_COMMIT_START);
2098
2099 list_add(&trans->pending_snapshot->list, &cur_trans->pending_snapshots);
2100}
2101
e55958c8
IA
2102static void update_commit_stats(struct btrfs_fs_info *fs_info, ktime_t interval)
2103{
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;
2109}
2110
3a45bb20 2111int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
79154b1b 2112{
3a45bb20 2113 struct btrfs_fs_info *fs_info = trans->fs_info;
49b25e05 2114 struct btrfs_transaction *cur_trans = trans->transaction;
8fd17795 2115 struct btrfs_transaction *prev_trans = NULL;
25287e0a 2116 int ret;
e55958c8
IA
2117 ktime_t start_time;
2118 ktime_t interval;
79154b1b 2119
35b814f3
NB
2120 ASSERT(refcount_read(&trans->use_count) == 1);
2121
8d25a086 2122 /* Stop the commit early if ->aborted is set */
bf31f87f 2123 if (TRANS_ABORTED(cur_trans)) {
25287e0a 2124 ret = cur_trans->aborted;
3a45bb20 2125 btrfs_end_transaction(trans);
e4a2bcac 2126 return ret;
25287e0a 2127 }
49b25e05 2128
f45c752b
JB
2129 btrfs_trans_release_metadata(trans);
2130 trans->block_rsv = NULL;
2131
56bec294 2132 /*
e19eb11f
JB
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.
56bec294 2135 */
e19eb11f
JB
2136 if (!test_and_set_bit(BTRFS_DELAYED_REFS_FLUSHING,
2137 &cur_trans->delayed_refs.flags)) {
2138 /*
2139 * Make a pass through all the delayed refs we have so far.
2140 * Any running threads may add more while we are here.
2141 */
2142 ret = btrfs_run_delayed_refs(trans, 0);
2143 if (ret) {
2144 btrfs_end_transaction(trans);
2145 return ret;
2146 }
2147 }
56bec294 2148
119e80df 2149 btrfs_create_pending_block_groups(trans);
ea658bad 2150
3204d33c 2151 if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
1bbc621e
CM
2152 int run_it = 0;
2153
2154 /* this mutex is also taken before trying to set
2155 * block groups readonly. We need to make sure
2156 * that nobody has set a block group readonly
2157 * after a extents from that block group have been
2158 * allocated for cache files. btrfs_set_block_group_ro
2159 * will wait for the transaction to commit if it
3204d33c 2160 * finds BTRFS_TRANS_DIRTY_BG_RUN set.
1bbc621e 2161 *
3204d33c
JB
2162 * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
2163 * only one process starts all the block group IO. It wouldn't
1bbc621e
CM
2164 * hurt to have more than one go through, but there's no
2165 * real advantage to it either.
2166 */
0b246afa 2167 mutex_lock(&fs_info->ro_block_group_mutex);
3204d33c
JB
2168 if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
2169 &cur_trans->flags))
1bbc621e 2170 run_it = 1;
0b246afa 2171 mutex_unlock(&fs_info->ro_block_group_mutex);
1bbc621e 2172
f9cacae3 2173 if (run_it) {
21217054 2174 ret = btrfs_start_dirty_block_groups(trans);
f9cacae3
NB
2175 if (ret) {
2176 btrfs_end_transaction(trans);
2177 return ret;
2178 }
2179 }
1bbc621e
CM
2180 }
2181
0b246afa 2182 spin_lock(&fs_info->trans_lock);
4a9d8bde 2183 if (cur_trans->state >= TRANS_STATE_COMMIT_START) {
d0c2f4fa
FM
2184 enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2185
28b21c55
FM
2186 add_pending_snapshot(trans);
2187
0b246afa 2188 spin_unlock(&fs_info->trans_lock);
9b64f57d 2189 refcount_inc(&cur_trans->use_count);
ccd467d6 2190
d0c2f4fa
FM
2191 if (trans->in_fsync)
2192 want_state = TRANS_STATE_SUPER_COMMITTED;
2193 ret = btrfs_end_transaction(trans);
2194 wait_for_commit(cur_trans, want_state);
15ee9bc7 2195
bf31f87f 2196 if (TRANS_ABORTED(cur_trans))
b4924a0f
LB
2197 ret = cur_trans->aborted;
2198
724e2315 2199 btrfs_put_transaction(cur_trans);
15ee9bc7 2200
49b25e05 2201 return ret;
79154b1b 2202 }
4313b399 2203
4a9d8bde 2204 cur_trans->state = TRANS_STATE_COMMIT_START;
0b246afa 2205 wake_up(&fs_info->transaction_blocked_wait);
bb9c12c9 2206
0b246afa 2207 if (cur_trans->list.prev != &fs_info->trans_list) {
d0c2f4fa
FM
2208 enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2209
2210 if (trans->in_fsync)
2211 want_state = TRANS_STATE_SUPER_COMMITTED;
2212
ccd467d6
CM
2213 prev_trans = list_entry(cur_trans->list.prev,
2214 struct btrfs_transaction, list);
d0c2f4fa 2215 if (prev_trans->state < want_state) {
9b64f57d 2216 refcount_inc(&prev_trans->use_count);
0b246afa 2217 spin_unlock(&fs_info->trans_lock);
ccd467d6 2218
d0c2f4fa
FM
2219 wait_for_commit(prev_trans, want_state);
2220
bf31f87f 2221 ret = READ_ONCE(prev_trans->aborted);
ccd467d6 2222
724e2315 2223 btrfs_put_transaction(prev_trans);
1f9b8c8f
FM
2224 if (ret)
2225 goto cleanup_transaction;
a4abeea4 2226 } else {
0b246afa 2227 spin_unlock(&fs_info->trans_lock);
ccd467d6 2228 }
a4abeea4 2229 } else {
0b246afa 2230 spin_unlock(&fs_info->trans_lock);
cb2d3dad
FM
2231 /*
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).
2236 */
84961539 2237 if (BTRFS_FS_ERROR(fs_info)) {
cb2d3dad
FM
2238 ret = -EROFS;
2239 goto cleanup_transaction;
2240 }
ccd467d6 2241 }
15ee9bc7 2242
e55958c8
IA
2243 /*
2244 * Get the time spent on the work done by the commit thread and not
2245 * the time spent waiting on a previous commit
2246 */
2247 start_time = ktime_get_ns();
2248
0860adfd
MX
2249 extwriter_counter_dec(cur_trans, trans->type);
2250
88090ad3 2251 ret = btrfs_start_delalloc_flush(fs_info);
82436617
MX
2252 if (ret)
2253 goto cleanup_transaction;
2254
e5c304e6 2255 ret = btrfs_run_delayed_items(trans);
581227d0
MX
2256 if (ret)
2257 goto cleanup_transaction;
15ee9bc7 2258
581227d0
MX
2259 wait_event(cur_trans->writer_wait,
2260 extwriter_counter_read(cur_trans) == 0);
15ee9bc7 2261
581227d0 2262 /* some pending stuffs might be added after the previous flush. */
e5c304e6 2263 ret = btrfs_run_delayed_items(trans);
ca469637
MX
2264 if (ret)
2265 goto cleanup_transaction;
2266
88090ad3 2267 btrfs_wait_delalloc_flush(fs_info);
cb7ab021 2268
48778179
FM
2269 /*
2270 * Wait for all ordered extents started by a fast fsync that joined this
2271 * transaction. Otherwise if this transaction commits before the ordered
2272 * extents complete we lose logged data after a power failure.
2273 */
2274 wait_event(cur_trans->pending_wait,
2275 atomic_read(&cur_trans->pending_ordered) == 0);
2276
2ff7e61e 2277 btrfs_scrub_pause(fs_info);
ed0ca140
JB
2278 /*
2279 * Ok now we need to make sure to block out any other joins while we
2280 * commit the transaction. We could have started a join before setting
4a9d8bde 2281 * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
ed0ca140 2282 */
0b246afa 2283 spin_lock(&fs_info->trans_lock);
28b21c55 2284 add_pending_snapshot(trans);
4a9d8bde 2285 cur_trans->state = TRANS_STATE_COMMIT_DOING;
0b246afa 2286 spin_unlock(&fs_info->trans_lock);
ed0ca140
JB
2287 wait_event(cur_trans->writer_wait,
2288 atomic_read(&cur_trans->num_writers) == 1);
2289
fdfbf020
JB
2290 /*
2291 * We've started the commit, clear the flag in case we were triggered to
2292 * do an async commit but somebody else started before the transaction
2293 * kthread could do the work.
2294 */
2295 clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
2296
bf31f87f 2297 if (TRANS_ABORTED(cur_trans)) {
2cba30f1 2298 ret = cur_trans->aborted;
6cf7f77e 2299 goto scrub_continue;
2cba30f1 2300 }
7585717f
CM
2301 /*
2302 * the reloc mutex makes sure that we stop
2303 * the balancing code from coming in and moving
2304 * extents around in the middle of the commit
2305 */
0b246afa 2306 mutex_lock(&fs_info->reloc_mutex);
7585717f 2307
42874b3d
MX
2308 /*
2309 * We needn't worry about the delayed items because we will
2310 * deal with them in create_pending_snapshot(), which is the
2311 * core function of the snapshot creation.
2312 */
08d50ca3 2313 ret = create_pending_snapshots(trans);
56e9f6ea
DS
2314 if (ret)
2315 goto unlock_reloc;
3063d29f 2316
42874b3d
MX
2317 /*
2318 * We insert the dir indexes of the snapshots and update the inode
2319 * of the snapshots' parents after the snapshot creation, so there
2320 * are some delayed items which are not dealt with. Now deal with
2321 * them.
2322 *
2323 * We needn't worry that this operation will corrupt the snapshots,
2324 * because all the tree which are snapshoted will be forced to COW
2325 * the nodes and leaves.
2326 */
e5c304e6 2327 ret = btrfs_run_delayed_items(trans);
56e9f6ea
DS
2328 if (ret)
2329 goto unlock_reloc;
16cdcec7 2330
c79a70b1 2331 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
56e9f6ea
DS
2332 if (ret)
2333 goto unlock_reloc;
56bec294 2334
e999376f
CM
2335 /*
2336 * make sure none of the code above managed to slip in a
2337 * delayed item
2338 */
ccdf9b30 2339 btrfs_assert_delayed_root_empty(fs_info);
e999376f 2340
2c90e5d6 2341 WARN_ON(cur_trans != trans->transaction);
dc17ff8f 2342
7e4443d9 2343 ret = commit_fs_roots(trans);
56e9f6ea 2344 if (ret)
dfba78dc 2345 goto unlock_reloc;
54aa1f4d 2346
3818aea2 2347 /*
7e1876ac
DS
2348 * Since the transaction is done, we can apply the pending changes
2349 * before the next transaction.
3818aea2 2350 */
0b246afa 2351 btrfs_apply_pending_changes(fs_info);
3818aea2 2352
5d4f98a2 2353 /* commit_fs_roots gets rid of all the tree log roots, it is now
e02119d5
CM
2354 * safe to free the root of tree log roots
2355 */
0b246afa 2356 btrfs_free_log_root_tree(trans, fs_info);
e02119d5 2357
0ed4792a
QW
2358 /*
2359 * Since fs roots are all committed, we can get a quite accurate
2360 * new_roots. So let's do quota accounting.
2361 */
460fb20a 2362 ret = btrfs_qgroup_account_extents(trans);
56e9f6ea 2363 if (ret < 0)
dfba78dc 2364 goto unlock_reloc;
0ed4792a 2365
9386d8bc 2366 ret = commit_cowonly_roots(trans);
56e9f6ea 2367 if (ret)
dfba78dc 2368 goto unlock_reloc;
54aa1f4d 2369
2cba30f1
MX
2370 /*
2371 * The tasks which save the space cache and inode cache may also
2372 * update ->aborted, check it.
2373 */
bf31f87f 2374 if (TRANS_ABORTED(cur_trans)) {
2cba30f1 2375 ret = cur_trans->aborted;
dfba78dc 2376 goto unlock_reloc;
2cba30f1
MX
2377 }
2378
0b246afa 2379 cur_trans = fs_info->running_transaction;
5d4f98a2 2380
0b246afa
JM
2381 btrfs_set_root_node(&fs_info->tree_root->root_item,
2382 fs_info->tree_root->node);
2383 list_add_tail(&fs_info->tree_root->dirty_list,
9e351cc8 2384 &cur_trans->switch_commits);
5d4f98a2 2385
0b246afa
JM
2386 btrfs_set_root_node(&fs_info->chunk_root->root_item,
2387 fs_info->chunk_root->node);
2388 list_add_tail(&fs_info->chunk_root->dirty_list,
9e351cc8
JB
2389 &cur_trans->switch_commits);
2390
f7238e50
JB
2391 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
2392 btrfs_set_root_node(&fs_info->block_group_root->root_item,
2393 fs_info->block_group_root->node);
2394 list_add_tail(&fs_info->block_group_root->dirty_list,
2395 &cur_trans->switch_commits);
2396 }
2397
889bfa39 2398 switch_commit_roots(trans);
5d4f98a2 2399
ce93ec54 2400 ASSERT(list_empty(&cur_trans->dirty_bgs));
1bbc621e 2401 ASSERT(list_empty(&cur_trans->io_bgs));
2ff7e61e 2402 update_super_roots(fs_info);
e02119d5 2403
0b246afa
JM
2404 btrfs_set_super_log_root(fs_info->super_copy, 0);
2405 btrfs_set_super_log_root_level(fs_info->super_copy, 0);
2406 memcpy(fs_info->super_for_commit, fs_info->super_copy,
2407 sizeof(*fs_info->super_copy));
ccd467d6 2408
bbbf7243 2409 btrfs_commit_device_sizes(cur_trans);
935e5cc9 2410
0b246afa
JM
2411 clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2412 clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
656f30db 2413
4fbcdf66
FM
2414 btrfs_trans_release_chunk_metadata(trans);
2415
dfba78dc
FM
2416 /*
2417 * Before changing the transaction state to TRANS_STATE_UNBLOCKED and
2418 * setting fs_info->running_transaction to NULL, lock tree_log_mutex to
2419 * make sure that before we commit our superblock, no other task can
2420 * start a new transaction and commit a log tree before we commit our
2421 * superblock. Anyone trying to commit a log tree locks this mutex before
2422 * writing its superblock.
2423 */
2424 mutex_lock(&fs_info->tree_log_mutex);
2425
0b246afa 2426 spin_lock(&fs_info->trans_lock);
4a9d8bde 2427 cur_trans->state = TRANS_STATE_UNBLOCKED;
0b246afa
JM
2428 fs_info->running_transaction = NULL;
2429 spin_unlock(&fs_info->trans_lock);
2430 mutex_unlock(&fs_info->reloc_mutex);
b7ec40d7 2431
0b246afa 2432 wake_up(&fs_info->transaction_wait);
e6dcd2dc 2433
70458a58 2434 ret = btrfs_write_and_wait_transaction(trans);
49b25e05 2435 if (ret) {
0b246afa
JM
2436 btrfs_handle_fs_error(fs_info, ret,
2437 "Error while writing out transaction");
2438 mutex_unlock(&fs_info->tree_log_mutex);
6cf7f77e 2439 goto scrub_continue;
49b25e05
JM
2440 }
2441
d3575156
NA
2442 /*
2443 * At this point, we should have written all the tree blocks allocated
2444 * in this transaction. So it's now safe to free the redirtyied extent
2445 * buffers.
2446 */
2447 btrfs_free_redirty_list(cur_trans);
2448
eece6a9c 2449 ret = write_all_supers(fs_info, 0);
e02119d5
CM
2450 /*
2451 * the super is written, we can safely allow the tree-loggers
2452 * to go about their business
2453 */
0b246afa 2454 mutex_unlock(&fs_info->tree_log_mutex);
c1f32b7c
AJ
2455 if (ret)
2456 goto scrub_continue;
e02119d5 2457
d0c2f4fa
FM
2458 /*
2459 * We needn't acquire the lock here because there is no other task
2460 * which can change it.
2461 */
2462 cur_trans->state = TRANS_STATE_SUPER_COMMITTED;
2463 wake_up(&cur_trans->commit_wait);
2464
5ead2dd0 2465 btrfs_finish_extent_commit(trans);
4313b399 2466
3204d33c 2467 if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
0b246afa 2468 btrfs_clear_space_info_full(fs_info);
13212b54 2469
0b246afa 2470 fs_info->last_trans_committed = cur_trans->transid;
4a9d8bde
MX
2471 /*
2472 * We needn't acquire the lock here because there is no other task
2473 * which can change it.
2474 */
2475 cur_trans->state = TRANS_STATE_COMPLETED;
2c90e5d6 2476 wake_up(&cur_trans->commit_wait);
3de4586c 2477
0b246afa 2478 spin_lock(&fs_info->trans_lock);
13c5a93e 2479 list_del_init(&cur_trans->list);
0b246afa 2480 spin_unlock(&fs_info->trans_lock);
a4abeea4 2481
724e2315
JB
2482 btrfs_put_transaction(cur_trans);
2483 btrfs_put_transaction(cur_trans);
58176a96 2484
0860adfd 2485 if (trans->type & __TRANS_FREEZABLE)
0b246afa 2486 sb_end_intwrite(fs_info->sb);
b2b5ef5c 2487
2e4e97ab 2488 trace_btrfs_transaction_commit(fs_info);
1abe9b8a 2489
e55958c8
IA
2490 interval = ktime_get_ns() - start_time;
2491
2ff7e61e 2492 btrfs_scrub_continue(fs_info);
a2de733c 2493
9ed74f2d
JB
2494 if (current->journal_info == trans)
2495 current->journal_info = NULL;
2496
2c90e5d6 2497 kmem_cache_free(btrfs_trans_handle_cachep, trans);
24bbcf04 2498
e55958c8
IA
2499 update_commit_stats(fs_info, interval);
2500
79154b1b 2501 return ret;
49b25e05 2502
56e9f6ea
DS
2503unlock_reloc:
2504 mutex_unlock(&fs_info->reloc_mutex);
6cf7f77e 2505scrub_continue:
2ff7e61e 2506 btrfs_scrub_continue(fs_info);
49b25e05 2507cleanup_transaction:
dc60c525 2508 btrfs_trans_release_metadata(trans);
c7cc64a9 2509 btrfs_cleanup_pending_block_groups(trans);
4fbcdf66 2510 btrfs_trans_release_chunk_metadata(trans);
0e721106 2511 trans->block_rsv = NULL;
0b246afa 2512 btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
49b25e05
JM
2513 if (current->journal_info == trans)
2514 current->journal_info = NULL;
97cb39bb 2515 cleanup_transaction(trans, ret);
49b25e05
JM
2516
2517 return ret;
79154b1b
CM
2518}
2519
d352ac68 2520/*
9d1a2a3a
DS
2521 * return < 0 if error
2522 * 0 if there are no more dead_roots at the time of call
2523 * 1 there are more to be processed, call me again
2524 *
2525 * The return value indicates there are certainly more snapshots to delete, but
2526 * if there comes a new one during processing, it may return 0. We don't mind,
2527 * because btrfs_commit_super will poke cleaner thread and it will process it a
2528 * few seconds later.
d352ac68 2529 */
33c44184 2530int btrfs_clean_one_deleted_snapshot(struct btrfs_fs_info *fs_info)
e9d0b13b 2531{
33c44184 2532 struct btrfs_root *root;
9d1a2a3a 2533 int ret;
5d4f98a2 2534
a4abeea4 2535 spin_lock(&fs_info->trans_lock);
9d1a2a3a
DS
2536 if (list_empty(&fs_info->dead_roots)) {
2537 spin_unlock(&fs_info->trans_lock);
2538 return 0;
2539 }
2540 root = list_first_entry(&fs_info->dead_roots,
2541 struct btrfs_root, root_list);
cfad392b 2542 list_del_init(&root->root_list);
a4abeea4 2543 spin_unlock(&fs_info->trans_lock);
e9d0b13b 2544
4fd786e6 2545 btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
76dda93c 2546
9d1a2a3a 2547 btrfs_kill_all_delayed_nodes(root);
16cdcec7 2548
9d1a2a3a
DS
2549 if (btrfs_header_backref_rev(root->node) <
2550 BTRFS_MIXED_BACKREF_REV)
0078a9f9 2551 ret = btrfs_drop_snapshot(root, 0, 0);
9d1a2a3a 2552 else
0078a9f9 2553 ret = btrfs_drop_snapshot(root, 1, 0);
32471dc2 2554
dc9492c1 2555 btrfs_put_root(root);
6596a928 2556 return (ret < 0) ? 0 : 1;
e9d0b13b 2557}
572d9ab7
DS
2558
2559void btrfs_apply_pending_changes(struct btrfs_fs_info *fs_info)
2560{
2561 unsigned long prev;
2562 unsigned long bit;
2563
6c9fe14f 2564 prev = xchg(&fs_info->pending_changes, 0);
572d9ab7
DS
2565 if (!prev)
2566 return;
2567
d51033d0
DS
2568 bit = 1 << BTRFS_PENDING_COMMIT;
2569 if (prev & bit)
2570 btrfs_debug(fs_info, "pending commit done");
2571 prev &= ~bit;
2572
572d9ab7
DS
2573 if (prev)
2574 btrfs_warn(fs_info,
2575 "unknown pending changes left 0x%lx, ignoring", prev);
2576}