xref: /linux/fs/btrfs/transaction.c (revision 7696286034ac72cf9b46499be1715ac62fd302c3)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/fs.h>
7 #include <linux/slab.h>
8 #include <linux/sched.h>
9 #include <linux/sched/mm.h>
10 #include <linux/writeback.h>
11 #include <linux/pagemap.h>
12 #include <linux/blkdev.h>
13 #include <linux/uuid.h>
14 #include <linux/timekeeping.h>
15 #include "misc.h"
16 #include "ctree.h"
17 #include "disk-io.h"
18 #include "transaction.h"
19 #include "locking.h"
20 #include "tree-log.h"
21 #include "volumes.h"
22 #include "dev-replace.h"
23 #include "qgroup.h"
24 #include "block-group.h"
25 #include "space-info.h"
26 #include "fs.h"
27 #include "accessors.h"
28 #include "extent-tree.h"
29 #include "root-tree.h"
30 #include "dir-item.h"
31 #include "uuid-tree.h"
32 #include "ioctl.h"
33 #include "relocation.h"
34 #include "scrub.h"
35 #include "ordered-data.h"
36 #include "delayed-inode.h"
37 
38 static struct kmem_cache *btrfs_trans_handle_cachep;
39 
40 /*
41  * Transaction states and transitions
42  *
43  * No running transaction (fs tree blocks are not modified)
44  * |
45  * | To next stage:
46  * |  Call start_transaction() variants. Except btrfs_join_transaction_nostart().
47  * V
48  * Transaction N [[TRANS_STATE_RUNNING]]
49  * |
50  * | New trans handles can be attached to transaction N by calling all
51  * | start_transaction() variants.
52  * |
53  * | To next stage:
54  * |  Call btrfs_commit_transaction() on any trans handle attached to
55  * |  transaction N
56  * V
57  * Transaction N [[TRANS_STATE_COMMIT_PREP]]
58  * |
59  * | If there are simultaneous calls to btrfs_commit_transaction() one will win
60  * | the race and the rest will wait for the winner to commit the transaction.
61  * |
62  * | The winner will wait for previous running transaction to completely finish
63  * | if there is one.
64  * |
65  * Transaction N [[TRANS_STATE_COMMIT_START]]
66  * |
67  * | Then one of the following happens:
68  * | - Wait for all other trans handle holders to release.
69  * |   The btrfs_commit_transaction() caller will do the commit work.
70  * | - Wait for current transaction to be committed by others.
71  * |   Other btrfs_commit_transaction() caller will do the commit work.
72  * |
73  * | At this stage, only btrfs_join_transaction*() variants can attach
74  * | to this running transaction.
75  * | All other variants will wait for current one to finish and attach to
76  * | transaction N+1.
77  * |
78  * | To next stage:
79  * |  Caller is chosen to commit transaction N, and all other trans handle
80  * |  haven been released.
81  * V
82  * Transaction N [[TRANS_STATE_COMMIT_DOING]]
83  * |
84  * | The heavy lifting transaction work is started.
85  * | From running delayed refs (modifying extent tree) to creating pending
86  * | snapshots, running qgroups.
87  * | In short, modify supporting trees to reflect modifications of subvolume
88  * | trees.
89  * |
90  * | At this stage, all start_transaction() calls will wait for this
91  * | transaction to finish and attach to transaction N+1.
92  * |
93  * | To next stage:
94  * |  Until all supporting trees are updated.
95  * V
96  * Transaction N [[TRANS_STATE_UNBLOCKED]]
97  * |						    Transaction N+1
98  * | All needed trees are modified, thus we only    [[TRANS_STATE_RUNNING]]
99  * | need to write them back to disk and update	    |
100  * | super blocks.				    |
101  * |						    |
102  * | At this stage, new transaction is allowed to   |
103  * | start.					    |
104  * | All new start_transaction() calls will be	    |
105  * | attached to transid N+1.			    |
106  * |						    |
107  * | To next stage:				    |
108  * |  Until all tree blocks and super blocks are    |
109  * |  written to block devices			    |
110  * V						    |
111  * Transaction N [[TRANS_STATE_COMPLETED]]	    V
112  *   All tree blocks and super blocks are written.  Transaction N+1
113  *   This transaction is finished and all its	    [[TRANS_STATE_COMMIT_START]]
114  *   data structures will be cleaned up.	    | Life goes on
115  */
116 static const unsigned int btrfs_blocked_trans_types[TRANS_STATE_MAX] = {
117 	[TRANS_STATE_RUNNING]		= 0U,
118 	[TRANS_STATE_COMMIT_PREP]	= 0U,
119 	[TRANS_STATE_COMMIT_START]	= (__TRANS_START | __TRANS_ATTACH),
120 	[TRANS_STATE_COMMIT_DOING]	= (__TRANS_START |
121 					   __TRANS_ATTACH |
122 					   __TRANS_JOIN |
123 					   __TRANS_JOIN_NOSTART),
124 	[TRANS_STATE_UNBLOCKED]		= (__TRANS_START |
125 					   __TRANS_ATTACH |
126 					   __TRANS_JOIN |
127 					   __TRANS_JOIN_NOLOCK |
128 					   __TRANS_JOIN_NOSTART),
129 	[TRANS_STATE_SUPER_COMMITTED]	= (__TRANS_START |
130 					   __TRANS_ATTACH |
131 					   __TRANS_JOIN |
132 					   __TRANS_JOIN_NOLOCK |
133 					   __TRANS_JOIN_NOSTART),
134 	[TRANS_STATE_COMPLETED]		= (__TRANS_START |
135 					   __TRANS_ATTACH |
136 					   __TRANS_JOIN |
137 					   __TRANS_JOIN_NOLOCK |
138 					   __TRANS_JOIN_NOSTART),
139 };
140 
141 void btrfs_put_transaction(struct btrfs_transaction *transaction)
142 {
143 	if (refcount_dec_and_test(&transaction->use_count)) {
144 		BUG_ON(!list_empty(&transaction->list));
145 		WARN_ON(!xa_empty(&transaction->delayed_refs.head_refs));
146 		WARN_ON(!xa_empty(&transaction->delayed_refs.dirty_extents));
147 		if (transaction->delayed_refs.pending_csums)
148 			btrfs_err(transaction->fs_info,
149 				  "pending csums is %llu",
150 				  transaction->delayed_refs.pending_csums);
151 		/*
152 		 * If any block groups are found in ->deleted_bgs then it's
153 		 * because the transaction was aborted and a commit did not
154 		 * happen (things failed before writing the new superblock
155 		 * and calling btrfs_finish_extent_commit()), so we can not
156 		 * discard the physical locations of the block groups.
157 		 */
158 		while (!list_empty(&transaction->deleted_bgs)) {
159 			struct btrfs_block_group *cache;
160 
161 			cache = list_first_entry(&transaction->deleted_bgs,
162 						 struct btrfs_block_group,
163 						 bg_list);
164 			/*
165 			 * Not strictly necessary to lock, as no other task will be using a
166 			 * block_group on the deleted_bgs list during a transaction abort.
167 			 */
168 			spin_lock(&transaction->fs_info->unused_bgs_lock);
169 			list_del_init(&cache->bg_list);
170 			spin_unlock(&transaction->fs_info->unused_bgs_lock);
171 			btrfs_unfreeze_block_group(cache);
172 			btrfs_put_block_group(cache);
173 		}
174 		WARN_ON(!list_empty(&transaction->dev_update_list));
175 		kfree(transaction);
176 	}
177 }
178 
179 static noinline void switch_commit_roots(struct btrfs_trans_handle *trans)
180 {
181 	struct btrfs_transaction *cur_trans = trans->transaction;
182 	struct btrfs_fs_info *fs_info = trans->fs_info;
183 	struct btrfs_root *root, *tmp;
184 
185 	/*
186 	 * At this point no one can be using this transaction to modify any tree
187 	 * and no one can start another transaction to modify any tree either.
188 	 */
189 	ASSERT(cur_trans->state == TRANS_STATE_COMMIT_DOING,
190 	       "cur_trans->state=%d", cur_trans->state);
191 
192 	down_write(&fs_info->commit_root_sem);
193 
194 	if (test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
195 		fs_info->last_reloc_trans = trans->transid;
196 
197 	list_for_each_entry_safe(root, tmp, &cur_trans->switch_commits,
198 				 dirty_list) {
199 		list_del_init(&root->dirty_list);
200 		free_extent_buffer(root->commit_root);
201 		root->commit_root = btrfs_root_node(root);
202 		btrfs_extent_io_tree_release(&root->dirty_log_pages);
203 		btrfs_qgroup_clean_swapped_blocks(root);
204 	}
205 
206 	/* We can free old roots now. */
207 	spin_lock(&cur_trans->dropped_roots_lock);
208 	while (!list_empty(&cur_trans->dropped_roots)) {
209 		root = list_first_entry(&cur_trans->dropped_roots,
210 					struct btrfs_root, root_list);
211 		list_del_init(&root->root_list);
212 		spin_unlock(&cur_trans->dropped_roots_lock);
213 		btrfs_free_log(trans, root);
214 		btrfs_drop_and_free_fs_root(fs_info, root);
215 		spin_lock(&cur_trans->dropped_roots_lock);
216 	}
217 	spin_unlock(&cur_trans->dropped_roots_lock);
218 
219 	up_write(&fs_info->commit_root_sem);
220 }
221 
222 static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
223 					 unsigned int type)
224 {
225 	if (type & TRANS_EXTWRITERS)
226 		atomic_inc(&trans->num_extwriters);
227 }
228 
229 static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
230 					 unsigned int type)
231 {
232 	if (type & TRANS_EXTWRITERS)
233 		atomic_dec(&trans->num_extwriters);
234 }
235 
236 static inline void extwriter_counter_init(struct btrfs_transaction *trans,
237 					  unsigned int type)
238 {
239 	atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
240 }
241 
242 static inline int extwriter_counter_read(struct btrfs_transaction *trans)
243 {
244 	return atomic_read(&trans->num_extwriters);
245 }
246 
247 /*
248  * To be called after doing the chunk btree updates right after allocating a new
249  * chunk (after btrfs_chunk_alloc_add_chunk_item() is called), when removing a
250  * chunk after all chunk btree updates and after finishing the second phase of
251  * chunk allocation (btrfs_create_pending_block_groups()) in case some block
252  * group had its chunk item insertion delayed to the second phase.
253  */
254 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
255 {
256 	struct btrfs_fs_info *fs_info = trans->fs_info;
257 
258 	if (!trans->chunk_bytes_reserved)
259 		return;
260 
261 	btrfs_block_rsv_release(fs_info, &fs_info->chunk_block_rsv,
262 				trans->chunk_bytes_reserved, NULL);
263 	trans->chunk_bytes_reserved = 0;
264 }
265 
266 /*
267  * either allocate a new transaction or hop into the existing one
268  */
269 static noinline int join_transaction(struct btrfs_fs_info *fs_info,
270 				     unsigned int type)
271 {
272 	struct btrfs_transaction *cur_trans;
273 
274 	spin_lock(&fs_info->trans_lock);
275 loop:
276 	/* The file system has been taken offline. No new transactions. */
277 	if (BTRFS_FS_ERROR(fs_info)) {
278 		spin_unlock(&fs_info->trans_lock);
279 		return -EROFS;
280 	}
281 
282 	cur_trans = fs_info->running_transaction;
283 	if (cur_trans) {
284 		if (TRANS_ABORTED(cur_trans)) {
285 			const int abort_error = cur_trans->aborted;
286 
287 			spin_unlock(&fs_info->trans_lock);
288 			return abort_error;
289 		}
290 		if (btrfs_blocked_trans_types[cur_trans->state] & type) {
291 			spin_unlock(&fs_info->trans_lock);
292 			return -EBUSY;
293 		}
294 		refcount_inc(&cur_trans->use_count);
295 		atomic_inc(&cur_trans->num_writers);
296 		extwriter_counter_inc(cur_trans, type);
297 		spin_unlock(&fs_info->trans_lock);
298 		btrfs_lockdep_acquire(fs_info, btrfs_trans_num_writers);
299 		btrfs_lockdep_acquire(fs_info, btrfs_trans_num_extwriters);
300 		return 0;
301 	}
302 	spin_unlock(&fs_info->trans_lock);
303 
304 	/*
305 	 * If we are ATTACH or TRANS_JOIN_NOSTART, we just want to catch the
306 	 * current transaction, and commit it. If there is no transaction, just
307 	 * return ENOENT.
308 	 */
309 	if (type == TRANS_ATTACH || type == TRANS_JOIN_NOSTART)
310 		return -ENOENT;
311 
312 	/*
313 	 * JOIN_NOLOCK only happens during the transaction commit, so
314 	 * it is impossible that ->running_transaction is NULL
315 	 */
316 	BUG_ON(type == TRANS_JOIN_NOLOCK);
317 
318 	cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
319 	if (!cur_trans)
320 		return -ENOMEM;
321 
322 	btrfs_lockdep_acquire(fs_info, btrfs_trans_num_writers);
323 	btrfs_lockdep_acquire(fs_info, btrfs_trans_num_extwriters);
324 
325 	spin_lock(&fs_info->trans_lock);
326 	if (fs_info->running_transaction) {
327 		/*
328 		 * someone started a transaction after we unlocked.  Make sure
329 		 * to redo the checks above
330 		 */
331 		btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
332 		btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
333 		kfree(cur_trans);
334 		goto loop;
335 	} else if (BTRFS_FS_ERROR(fs_info)) {
336 		spin_unlock(&fs_info->trans_lock);
337 		btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
338 		btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
339 		kfree(cur_trans);
340 		return -EROFS;
341 	}
342 
343 	cur_trans->fs_info = fs_info;
344 	atomic_set(&cur_trans->pending_ordered, 0);
345 	init_waitqueue_head(&cur_trans->pending_wait);
346 	atomic_set(&cur_trans->num_writers, 1);
347 	extwriter_counter_init(cur_trans, type);
348 	init_waitqueue_head(&cur_trans->writer_wait);
349 	init_waitqueue_head(&cur_trans->commit_wait);
350 	cur_trans->state = TRANS_STATE_RUNNING;
351 	/*
352 	 * One for this trans handle, one so it will live on until we
353 	 * commit the transaction.
354 	 */
355 	refcount_set(&cur_trans->use_count, 2);
356 	cur_trans->flags = 0;
357 	cur_trans->start_time = ktime_get_seconds();
358 
359 	memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
360 
361 	xa_init(&cur_trans->delayed_refs.head_refs);
362 	xa_init(&cur_trans->delayed_refs.dirty_extents);
363 
364 	/*
365 	 * although the tree mod log is per file system and not per transaction,
366 	 * the log must never go across transaction boundaries.
367 	 */
368 	smp_mb();
369 	if (!list_empty(&fs_info->tree_mod_seq_list))
370 		WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
371 	if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
372 		WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
373 	atomic64_set(&fs_info->tree_mod_seq, 0);
374 
375 	spin_lock_init(&cur_trans->delayed_refs.lock);
376 
377 	INIT_LIST_HEAD(&cur_trans->pending_snapshots);
378 	INIT_LIST_HEAD(&cur_trans->dev_update_list);
379 	INIT_LIST_HEAD(&cur_trans->switch_commits);
380 	INIT_LIST_HEAD(&cur_trans->dirty_bgs);
381 	INIT_LIST_HEAD(&cur_trans->io_bgs);
382 	INIT_LIST_HEAD(&cur_trans->dropped_roots);
383 	mutex_init(&cur_trans->cache_write_mutex);
384 	spin_lock_init(&cur_trans->dirty_bgs_lock);
385 	INIT_LIST_HEAD(&cur_trans->deleted_bgs);
386 	spin_lock_init(&cur_trans->dropped_roots_lock);
387 	list_add_tail(&cur_trans->list, &fs_info->trans_list);
388 	btrfs_extent_io_tree_init(fs_info, &cur_trans->dirty_pages,
389 				  IO_TREE_TRANS_DIRTY_PAGES);
390 	btrfs_extent_io_tree_init(fs_info, &cur_trans->pinned_extents,
391 				  IO_TREE_FS_PINNED_EXTENTS);
392 	btrfs_set_fs_generation(fs_info, fs_info->generation + 1);
393 	cur_trans->transid = fs_info->generation;
394 	fs_info->running_transaction = cur_trans;
395 	cur_trans->aborted = 0;
396 	spin_unlock(&fs_info->trans_lock);
397 
398 	return 0;
399 }
400 
401 /*
402  * This does all the record keeping required to make sure that a shareable root
403  * is properly recorded in a given transaction.  This is required to make sure
404  * the old root from before we joined the transaction is deleted when the
405  * transaction commits.
406  */
407 static int record_root_in_trans(struct btrfs_trans_handle *trans,
408 			       struct btrfs_root *root,
409 			       bool force)
410 {
411 	struct btrfs_fs_info *fs_info = root->fs_info;
412 	int ret = 0;
413 
414 	if ((test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
415 	    btrfs_get_root_last_trans(root) < trans->transid) || force) {
416 		WARN_ON(!force && root->commit_root != root->node);
417 
418 		/*
419 		 * see below for IN_TRANS_SETUP usage rules
420 		 * we have the reloc mutex held now, so there
421 		 * is only one writer in this function
422 		 */
423 		set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
424 
425 		/* make sure readers find IN_TRANS_SETUP before
426 		 * they find our root->last_trans update
427 		 */
428 		smp_wmb();
429 
430 		spin_lock(&fs_info->fs_roots_radix_lock);
431 		if (btrfs_get_root_last_trans(root) == trans->transid && !force) {
432 			spin_unlock(&fs_info->fs_roots_radix_lock);
433 			return 0;
434 		}
435 		radix_tree_tag_set(&fs_info->fs_roots_radix,
436 				   (unsigned long)btrfs_root_id(root),
437 				   BTRFS_ROOT_TRANS_TAG);
438 		spin_unlock(&fs_info->fs_roots_radix_lock);
439 		btrfs_set_root_last_trans(root, trans->transid);
440 
441 		/* this is pretty tricky.  We don't want to
442 		 * take the relocation lock in btrfs_record_root_in_trans
443 		 * unless we're really doing the first setup for this root in
444 		 * this transaction.
445 		 *
446 		 * Normally we'd use root->last_trans as a flag to decide
447 		 * if we want to take the expensive mutex.
448 		 *
449 		 * But, we have to set root->last_trans before we
450 		 * init the relocation root, otherwise, we trip over warnings
451 		 * in ctree.c.  The solution used here is to flag ourselves
452 		 * with root IN_TRANS_SETUP.  When this is 1, we're still
453 		 * fixing up the reloc trees and everyone must wait.
454 		 *
455 		 * When this is zero, they can trust root->last_trans and fly
456 		 * through btrfs_record_root_in_trans without having to take the
457 		 * lock.  smp_wmb() makes sure that all the writes above are
458 		 * done before we pop in the zero below
459 		 */
460 		ret = btrfs_init_reloc_root(trans, root);
461 		smp_mb__before_atomic();
462 		clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
463 	}
464 	return ret;
465 }
466 
467 
468 void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
469 			    struct btrfs_root *root)
470 {
471 	struct btrfs_fs_info *fs_info = root->fs_info;
472 	struct btrfs_transaction *cur_trans = trans->transaction;
473 
474 	/* Add ourselves to the transaction dropped list */
475 	spin_lock(&cur_trans->dropped_roots_lock);
476 	list_add_tail(&root->root_list, &cur_trans->dropped_roots);
477 	spin_unlock(&cur_trans->dropped_roots_lock);
478 
479 	/* Make sure we don't try to update the root at commit time */
480 	spin_lock(&fs_info->fs_roots_radix_lock);
481 	radix_tree_tag_clear(&fs_info->fs_roots_radix,
482 			     (unsigned long)btrfs_root_id(root),
483 			     BTRFS_ROOT_TRANS_TAG);
484 	spin_unlock(&fs_info->fs_roots_radix_lock);
485 }
486 
487 int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
488 			       struct btrfs_root *root)
489 {
490 	struct btrfs_fs_info *fs_info = root->fs_info;
491 	int ret;
492 
493 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
494 		return 0;
495 
496 	/*
497 	 * see record_root_in_trans for comments about IN_TRANS_SETUP usage
498 	 * and barriers
499 	 */
500 	smp_rmb();
501 	if (btrfs_get_root_last_trans(root) == trans->transid &&
502 	    !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
503 		return 0;
504 
505 	mutex_lock(&fs_info->reloc_mutex);
506 	ret = record_root_in_trans(trans, root, 0);
507 	mutex_unlock(&fs_info->reloc_mutex);
508 
509 	return ret;
510 }
511 
512 static inline int is_transaction_blocked(struct btrfs_transaction *trans)
513 {
514 	return (trans->state >= TRANS_STATE_COMMIT_START &&
515 		trans->state < TRANS_STATE_UNBLOCKED &&
516 		!TRANS_ABORTED(trans));
517 }
518 
519 /* wait for commit against the current transaction to become unblocked
520  * when this is done, it is safe to start a new transaction, but the current
521  * transaction might not be fully on disk.
522  */
523 static void wait_current_trans(struct btrfs_fs_info *fs_info)
524 {
525 	struct btrfs_transaction *cur_trans;
526 
527 	spin_lock(&fs_info->trans_lock);
528 	cur_trans = fs_info->running_transaction;
529 	if (cur_trans && is_transaction_blocked(cur_trans)) {
530 		refcount_inc(&cur_trans->use_count);
531 		spin_unlock(&fs_info->trans_lock);
532 
533 		btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
534 		wait_event(fs_info->transaction_wait,
535 			   cur_trans->state >= TRANS_STATE_UNBLOCKED ||
536 			   TRANS_ABORTED(cur_trans));
537 		btrfs_put_transaction(cur_trans);
538 	} else {
539 		spin_unlock(&fs_info->trans_lock);
540 	}
541 }
542 
543 static bool may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
544 {
545 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
546 		return false;
547 
548 	if (type == TRANS_START)
549 		return true;
550 
551 	return false;
552 }
553 
554 static inline bool need_reserve_reloc_root(struct btrfs_root *root)
555 {
556 	struct btrfs_fs_info *fs_info = root->fs_info;
557 
558 	if (!fs_info->reloc_ctl ||
559 	    !test_bit(BTRFS_ROOT_SHAREABLE, &root->state) ||
560 	    btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID ||
561 	    root->reloc_root)
562 		return false;
563 
564 	return true;
565 }
566 
567 static int btrfs_reserve_trans_metadata(struct btrfs_fs_info *fs_info,
568 					enum btrfs_reserve_flush_enum flush,
569 					u64 num_bytes,
570 					u64 *delayed_refs_bytes)
571 {
572 	struct btrfs_space_info *si = fs_info->trans_block_rsv.space_info;
573 	u64 bytes = num_bytes + *delayed_refs_bytes;
574 	int ret;
575 
576 	/*
577 	 * We want to reserve all the bytes we may need all at once, so we only
578 	 * do 1 enospc flushing cycle per transaction start.
579 	 */
580 	ret = btrfs_reserve_metadata_bytes(si, bytes, flush);
581 
582 	/*
583 	 * If we are an emergency flush, which can steal from the global block
584 	 * reserve, then attempt to not reserve space for the delayed refs, as
585 	 * we will consume space for them from the global block reserve.
586 	 */
587 	if (ret && flush == BTRFS_RESERVE_FLUSH_ALL_STEAL) {
588 		bytes -= *delayed_refs_bytes;
589 		*delayed_refs_bytes = 0;
590 		ret = btrfs_reserve_metadata_bytes(si, bytes, flush);
591 	}
592 
593 	return ret;
594 }
595 
596 static struct btrfs_trans_handle *
597 start_transaction(struct btrfs_root *root, unsigned int num_items,
598 		  unsigned int type, enum btrfs_reserve_flush_enum flush,
599 		  bool enforce_qgroups)
600 {
601 	struct btrfs_fs_info *fs_info = root->fs_info;
602 	struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
603 	struct btrfs_block_rsv *trans_rsv = &fs_info->trans_block_rsv;
604 	struct btrfs_trans_handle *h;
605 	struct btrfs_transaction *cur_trans;
606 	u64 num_bytes = 0;
607 	u64 qgroup_reserved = 0;
608 	u64 delayed_refs_bytes = 0;
609 	bool reloc_reserved = false;
610 	bool do_chunk_alloc = false;
611 	int ret;
612 
613 	if (BTRFS_FS_ERROR(fs_info))
614 		return ERR_PTR(-EROFS);
615 
616 	if (current->journal_info) {
617 		WARN_ON(type & TRANS_EXTWRITERS);
618 		h = current->journal_info;
619 		refcount_inc(&h->use_count);
620 		WARN_ON(refcount_read(&h->use_count) > 2);
621 		h->orig_rsv = h->block_rsv;
622 		h->block_rsv = NULL;
623 		goto got_it;
624 	}
625 
626 	/*
627 	 * Do the reservation before we join the transaction so we can do all
628 	 * the appropriate flushing if need be.
629 	 */
630 	if (num_items && root != fs_info->chunk_root) {
631 		qgroup_reserved = num_items * fs_info->nodesize;
632 		/*
633 		 * Use prealloc for now, as there might be a currently running
634 		 * transaction that could free this reserved space prematurely
635 		 * by committing.
636 		 */
637 		ret = btrfs_qgroup_reserve_meta_prealloc(root, qgroup_reserved,
638 							 enforce_qgroups, false);
639 		if (ret)
640 			return ERR_PTR(ret);
641 
642 		num_bytes = btrfs_calc_insert_metadata_size(fs_info, num_items);
643 		/*
644 		 * If we plan to insert/update/delete "num_items" from a btree,
645 		 * we will also generate delayed refs for extent buffers in the
646 		 * respective btree paths, so reserve space for the delayed refs
647 		 * that will be generated by the caller as it modifies btrees.
648 		 * Try to reserve them to avoid excessive use of the global
649 		 * block reserve.
650 		 */
651 		delayed_refs_bytes = btrfs_calc_delayed_ref_bytes(fs_info, num_items);
652 
653 		/*
654 		 * Do the reservation for the relocation root creation
655 		 */
656 		if (need_reserve_reloc_root(root)) {
657 			num_bytes += fs_info->nodesize;
658 			reloc_reserved = true;
659 		}
660 
661 		ret = btrfs_reserve_trans_metadata(fs_info, flush, num_bytes,
662 						   &delayed_refs_bytes);
663 		if (ret)
664 			goto reserve_fail;
665 
666 		btrfs_block_rsv_add_bytes(trans_rsv, num_bytes, true);
667 
668 		if (trans_rsv->space_info->force_alloc)
669 			do_chunk_alloc = true;
670 	} else if (num_items == 0 && flush == BTRFS_RESERVE_FLUSH_ALL &&
671 		   !btrfs_block_rsv_full(delayed_refs_rsv)) {
672 		/*
673 		 * Some people call with btrfs_start_transaction(root, 0)
674 		 * because they can be throttled, but have some other mechanism
675 		 * for reserving space.  We still want these guys to refill the
676 		 * delayed block_rsv so just add 1 items worth of reservation
677 		 * here.
678 		 */
679 		ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
680 		if (ret)
681 			goto reserve_fail;
682 	}
683 again:
684 	h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
685 	if (!h) {
686 		ret = -ENOMEM;
687 		goto alloc_fail;
688 	}
689 
690 	/*
691 	 * If we are JOIN_NOLOCK we're already committing a transaction and
692 	 * waiting on this guy, so we don't need to do the sb_start_intwrite
693 	 * because we're already holding a ref.  We need this because we could
694 	 * have raced in and did an fsync() on a file which can kick a commit
695 	 * and then we deadlock with somebody doing a freeze.
696 	 *
697 	 * If we are ATTACH, it means we just want to catch the current
698 	 * transaction and commit it, so we needn't do sb_start_intwrite().
699 	 */
700 	if (type & __TRANS_FREEZABLE)
701 		sb_start_intwrite(fs_info->sb);
702 
703 	if (may_wait_transaction(fs_info, type))
704 		wait_current_trans(fs_info);
705 
706 	do {
707 		ret = join_transaction(fs_info, type);
708 		if (ret == -EBUSY) {
709 			wait_current_trans(fs_info);
710 			if (unlikely(type == TRANS_ATTACH ||
711 				     type == TRANS_JOIN_NOSTART))
712 				ret = -ENOENT;
713 		}
714 	} while (ret == -EBUSY);
715 
716 	if (ret < 0)
717 		goto join_fail;
718 
719 	cur_trans = fs_info->running_transaction;
720 
721 	h->transid = cur_trans->transid;
722 	h->transaction = cur_trans;
723 	refcount_set(&h->use_count, 1);
724 	h->fs_info = root->fs_info;
725 
726 	h->type = type;
727 	INIT_LIST_HEAD(&h->new_bgs);
728 	btrfs_init_metadata_block_rsv(fs_info, &h->delayed_rsv, BTRFS_BLOCK_RSV_DELOPS);
729 
730 	smp_mb();
731 	if (cur_trans->state >= TRANS_STATE_COMMIT_START &&
732 	    may_wait_transaction(fs_info, type)) {
733 		current->journal_info = h;
734 		btrfs_commit_transaction(h);
735 		goto again;
736 	}
737 
738 	if (num_bytes) {
739 		trace_btrfs_space_reservation(fs_info, "transaction",
740 					      h->transid, num_bytes, 1);
741 		h->block_rsv = trans_rsv;
742 		h->bytes_reserved = num_bytes;
743 		if (delayed_refs_bytes > 0) {
744 			trace_btrfs_space_reservation(fs_info,
745 						      "local_delayed_refs_rsv",
746 						      h->transid,
747 						      delayed_refs_bytes, 1);
748 			h->delayed_refs_bytes_reserved = delayed_refs_bytes;
749 			btrfs_block_rsv_add_bytes(&h->delayed_rsv, delayed_refs_bytes, true);
750 			delayed_refs_bytes = 0;
751 		}
752 		h->reloc_reserved = reloc_reserved;
753 	}
754 
755 got_it:
756 	if (!current->journal_info)
757 		current->journal_info = h;
758 
759 	/*
760 	 * If the space_info is marked ALLOC_FORCE then we'll get upgraded to
761 	 * ALLOC_FORCE the first run through, and then we won't allocate for
762 	 * anybody else who races in later.  We don't care about the return
763 	 * value here.
764 	 */
765 	if (do_chunk_alloc && num_bytes) {
766 		struct btrfs_space_info *space_info = h->block_rsv->space_info;
767 		u64 flags = space_info->flags;
768 
769 		btrfs_chunk_alloc(h, space_info, btrfs_get_alloc_profile(fs_info, flags),
770 				  CHUNK_ALLOC_NO_FORCE);
771 	}
772 
773 	/*
774 	 * btrfs_record_root_in_trans() needs to alloc new extents, and may
775 	 * call btrfs_join_transaction() while we're also starting a
776 	 * transaction.
777 	 *
778 	 * Thus it need to be called after current->journal_info initialized,
779 	 * or we can deadlock.
780 	 */
781 	ret = btrfs_record_root_in_trans(h, root);
782 	if (ret) {
783 		/*
784 		 * The transaction handle is fully initialized and linked with
785 		 * other structures so it needs to be ended in case of errors,
786 		 * not just freed.
787 		 */
788 		btrfs_end_transaction(h);
789 		goto reserve_fail;
790 	}
791 	/*
792 	 * Now that we have found a transaction to be a part of, convert the
793 	 * qgroup reservation from prealloc to pertrans. A different transaction
794 	 * can't race in and free our pertrans out from under us.
795 	 */
796 	if (qgroup_reserved)
797 		btrfs_qgroup_convert_reserved_meta(root, qgroup_reserved);
798 
799 	return h;
800 
801 join_fail:
802 	if (type & __TRANS_FREEZABLE)
803 		sb_end_intwrite(fs_info->sb);
804 	kmem_cache_free(btrfs_trans_handle_cachep, h);
805 alloc_fail:
806 	if (num_bytes)
807 		btrfs_block_rsv_release(fs_info, trans_rsv, num_bytes, NULL);
808 	if (delayed_refs_bytes)
809 		btrfs_space_info_free_bytes_may_use(trans_rsv->space_info, delayed_refs_bytes);
810 reserve_fail:
811 	btrfs_qgroup_free_meta_prealloc(root, qgroup_reserved);
812 	return ERR_PTR(ret);
813 }
814 
815 struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
816 						   unsigned int num_items)
817 {
818 	return start_transaction(root, num_items, TRANS_START,
819 				 BTRFS_RESERVE_FLUSH_ALL, true);
820 }
821 
822 struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
823 					struct btrfs_root *root,
824 					unsigned int num_items)
825 {
826 	return start_transaction(root, num_items, TRANS_START,
827 				 BTRFS_RESERVE_FLUSH_ALL_STEAL, false);
828 }
829 
830 struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
831 {
832 	return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
833 				 true);
834 }
835 
836 struct btrfs_trans_handle *btrfs_join_transaction_spacecache(struct btrfs_root *root)
837 {
838 	return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
839 				 BTRFS_RESERVE_NO_FLUSH, true);
840 }
841 
842 /*
843  * Similar to regular join but it never starts a transaction when none is
844  * running or when there's a running one at a state >= TRANS_STATE_UNBLOCKED.
845  * This is similar to btrfs_attach_transaction() but it allows the join to
846  * happen if the transaction commit already started but it's not yet in the
847  * "doing" phase (the state is < TRANS_STATE_COMMIT_DOING).
848  */
849 struct btrfs_trans_handle *btrfs_join_transaction_nostart(struct btrfs_root *root)
850 {
851 	return start_transaction(root, 0, TRANS_JOIN_NOSTART,
852 				 BTRFS_RESERVE_NO_FLUSH, true);
853 }
854 
855 /*
856  * Catch the running transaction.
857  *
858  * It is used when we want to commit the current the transaction, but
859  * don't want to start a new one.
860  *
861  * Note: If this function return -ENOENT, it just means there is no
862  * running transaction. But it is possible that the inactive transaction
863  * is still in the memory, not fully on disk. If you hope there is no
864  * inactive transaction in the fs when -ENOENT is returned, you should
865  * invoke
866  *     btrfs_attach_transaction_barrier()
867  */
868 struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
869 {
870 	return start_transaction(root, 0, TRANS_ATTACH,
871 				 BTRFS_RESERVE_NO_FLUSH, true);
872 }
873 
874 /*
875  * Catch the running transaction.
876  *
877  * It is similar to the above function, the difference is this one
878  * will wait for all the inactive transactions until they fully
879  * complete.
880  */
881 struct btrfs_trans_handle *
882 btrfs_attach_transaction_barrier(struct btrfs_root *root)
883 {
884 	struct btrfs_trans_handle *trans;
885 
886 	trans = start_transaction(root, 0, TRANS_ATTACH,
887 				  BTRFS_RESERVE_NO_FLUSH, true);
888 	if (trans == ERR_PTR(-ENOENT)) {
889 		int ret;
890 
891 		ret = btrfs_wait_for_commit(root->fs_info, 0);
892 		if (ret)
893 			return ERR_PTR(ret);
894 	}
895 
896 	return trans;
897 }
898 
899 /* Wait for a transaction commit to reach at least the given state. */
900 static noinline void wait_for_commit(struct btrfs_transaction *commit,
901 				     const enum btrfs_trans_state min_state)
902 {
903 	struct btrfs_fs_info *fs_info = commit->fs_info;
904 	u64 transid = commit->transid;
905 	bool put = false;
906 
907 	/*
908 	 * At the moment this function is called with min_state either being
909 	 * TRANS_STATE_COMPLETED or TRANS_STATE_SUPER_COMMITTED.
910 	 */
911 	if (min_state == TRANS_STATE_COMPLETED)
912 		btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
913 	else
914 		btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
915 
916 	while (1) {
917 		wait_event(commit->commit_wait, commit->state >= min_state);
918 		if (put)
919 			btrfs_put_transaction(commit);
920 
921 		if (min_state < TRANS_STATE_COMPLETED)
922 			break;
923 
924 		/*
925 		 * A transaction isn't really completed until all of the
926 		 * previous transactions are completed, but with fsync we can
927 		 * end up with SUPER_COMMITTED transactions before a COMPLETED
928 		 * transaction. Wait for those.
929 		 */
930 
931 		spin_lock(&fs_info->trans_lock);
932 		commit = list_first_entry_or_null(&fs_info->trans_list,
933 						  struct btrfs_transaction,
934 						  list);
935 		if (!commit || commit->transid > transid) {
936 			spin_unlock(&fs_info->trans_lock);
937 			break;
938 		}
939 		refcount_inc(&commit->use_count);
940 		put = true;
941 		spin_unlock(&fs_info->trans_lock);
942 	}
943 }
944 
945 int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
946 {
947 	struct btrfs_transaction *cur_trans = NULL, *t;
948 	int ret = 0;
949 
950 	if (transid) {
951 		if (transid <= btrfs_get_last_trans_committed(fs_info))
952 			goto out;
953 
954 		/* find specified transaction */
955 		spin_lock(&fs_info->trans_lock);
956 		list_for_each_entry(t, &fs_info->trans_list, list) {
957 			if (t->transid == transid) {
958 				cur_trans = t;
959 				refcount_inc(&cur_trans->use_count);
960 				ret = 0;
961 				break;
962 			}
963 			if (t->transid > transid) {
964 				ret = 0;
965 				break;
966 			}
967 		}
968 		spin_unlock(&fs_info->trans_lock);
969 
970 		/*
971 		 * The specified transaction doesn't exist, or we
972 		 * raced with btrfs_commit_transaction
973 		 */
974 		if (!cur_trans) {
975 			if (transid > btrfs_get_last_trans_committed(fs_info))
976 				ret = -EINVAL;
977 			goto out;
978 		}
979 	} else {
980 		/* find newest transaction that is committing | committed */
981 		spin_lock(&fs_info->trans_lock);
982 		list_for_each_entry_reverse(t, &fs_info->trans_list,
983 					    list) {
984 			if (t->state >= TRANS_STATE_COMMIT_START) {
985 				if (t->state == TRANS_STATE_COMPLETED)
986 					break;
987 				cur_trans = t;
988 				refcount_inc(&cur_trans->use_count);
989 				break;
990 			}
991 		}
992 		spin_unlock(&fs_info->trans_lock);
993 		if (!cur_trans)
994 			goto out;  /* nothing committing|committed */
995 	}
996 
997 	wait_for_commit(cur_trans, TRANS_STATE_COMPLETED);
998 	ret = cur_trans->aborted;
999 	btrfs_put_transaction(cur_trans);
1000 out:
1001 	return ret;
1002 }
1003 
1004 void btrfs_throttle(struct btrfs_fs_info *fs_info)
1005 {
1006 	wait_current_trans(fs_info);
1007 }
1008 
1009 bool btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
1010 {
1011 	struct btrfs_transaction *cur_trans = trans->transaction;
1012 
1013 	if (cur_trans->state >= TRANS_STATE_COMMIT_START ||
1014 	    test_bit(BTRFS_DELAYED_REFS_FLUSHING, &cur_trans->delayed_refs.flags))
1015 		return true;
1016 
1017 	if (btrfs_check_space_for_delayed_refs(trans->fs_info))
1018 		return true;
1019 
1020 	return !!btrfs_block_rsv_check(&trans->fs_info->global_block_rsv, 50);
1021 }
1022 
1023 static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
1024 
1025 {
1026 	struct btrfs_fs_info *fs_info = trans->fs_info;
1027 
1028 	if (!trans->block_rsv) {
1029 		ASSERT(trans->bytes_reserved == 0,
1030 		       "trans->bytes_reserved=%llu", trans->bytes_reserved);
1031 		ASSERT(trans->delayed_refs_bytes_reserved == 0,
1032 		       "trans->delayed_refs_bytes_reserved=%llu",
1033 		       trans->delayed_refs_bytes_reserved);
1034 		return;
1035 	}
1036 
1037 	if (!trans->bytes_reserved) {
1038 		ASSERT(trans->delayed_refs_bytes_reserved == 0,
1039 		       "trans->delayed_refs_bytes_reserved=%llu",
1040 		       trans->delayed_refs_bytes_reserved);
1041 		return;
1042 	}
1043 
1044 	ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
1045 	trace_btrfs_space_reservation(fs_info, "transaction",
1046 				      trans->transid, trans->bytes_reserved, 0);
1047 	btrfs_block_rsv_release(fs_info, trans->block_rsv,
1048 				trans->bytes_reserved, NULL);
1049 	trans->bytes_reserved = 0;
1050 
1051 	if (!trans->delayed_refs_bytes_reserved)
1052 		return;
1053 
1054 	trace_btrfs_space_reservation(fs_info, "local_delayed_refs_rsv",
1055 				      trans->transid,
1056 				      trans->delayed_refs_bytes_reserved, 0);
1057 	btrfs_block_rsv_release(fs_info, &trans->delayed_rsv,
1058 				trans->delayed_refs_bytes_reserved, NULL);
1059 	trans->delayed_refs_bytes_reserved = 0;
1060 }
1061 
1062 static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
1063 				   int throttle)
1064 {
1065 	struct btrfs_fs_info *info = trans->fs_info;
1066 	struct btrfs_transaction *cur_trans = trans->transaction;
1067 	int ret = 0;
1068 
1069 	if (refcount_read(&trans->use_count) > 1) {
1070 		refcount_dec(&trans->use_count);
1071 		trans->block_rsv = trans->orig_rsv;
1072 		return 0;
1073 	}
1074 
1075 	btrfs_trans_release_metadata(trans);
1076 	trans->block_rsv = NULL;
1077 
1078 	btrfs_create_pending_block_groups(trans);
1079 
1080 	btrfs_trans_release_chunk_metadata(trans);
1081 
1082 	if (trans->type & __TRANS_FREEZABLE)
1083 		sb_end_intwrite(info->sb);
1084 
1085 	WARN_ON(cur_trans != info->running_transaction);
1086 	WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
1087 	atomic_dec(&cur_trans->num_writers);
1088 	extwriter_counter_dec(cur_trans, trans->type);
1089 
1090 	cond_wake_up(&cur_trans->writer_wait);
1091 
1092 	btrfs_lockdep_release(info, btrfs_trans_num_extwriters);
1093 	btrfs_lockdep_release(info, btrfs_trans_num_writers);
1094 
1095 	btrfs_put_transaction(cur_trans);
1096 
1097 	if (current->journal_info == trans)
1098 		current->journal_info = NULL;
1099 
1100 	if (throttle)
1101 		btrfs_run_delayed_iputs(info);
1102 
1103 	if (TRANS_ABORTED(trans) || BTRFS_FS_ERROR(info)) {
1104 		wake_up_process(info->transaction_kthread);
1105 		if (TRANS_ABORTED(trans))
1106 			ret = trans->aborted;
1107 		else
1108 			ret = -EROFS;
1109 	}
1110 
1111 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
1112 	return ret;
1113 }
1114 
1115 int btrfs_end_transaction(struct btrfs_trans_handle *trans)
1116 {
1117 	return __btrfs_end_transaction(trans, 0);
1118 }
1119 
1120 int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
1121 {
1122 	return __btrfs_end_transaction(trans, 1);
1123 }
1124 
1125 /*
1126  * when btree blocks are allocated, they have some corresponding bits set for
1127  * them in one of two extent_io trees.  This is used to make sure all of
1128  * those extents are sent to disk but does not wait on them
1129  */
1130 int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
1131 			       struct extent_io_tree *dirty_pages, int mark)
1132 {
1133 	int ret = 0;
1134 	struct address_space *mapping = fs_info->btree_inode->i_mapping;
1135 	struct extent_state *cached_state = NULL;
1136 	u64 start = 0;
1137 	u64 end;
1138 
1139 	while (btrfs_find_first_extent_bit(dirty_pages, start, &start, &end,
1140 					   mark, &cached_state)) {
1141 		bool wait_writeback = false;
1142 
1143 		ret = btrfs_convert_extent_bit(dirty_pages, start, end,
1144 					       EXTENT_NEED_WAIT,
1145 					       mark, &cached_state);
1146 		/*
1147 		 * convert_extent_bit can return -ENOMEM, which is most of the
1148 		 * time a temporary error. So when it happens, ignore the error
1149 		 * and wait for writeback of this range to finish - because we
1150 		 * failed to set the bit EXTENT_NEED_WAIT for the range, a call
1151 		 * to __btrfs_wait_marked_extents() would not know that
1152 		 * writeback for this range started and therefore wouldn't
1153 		 * wait for it to finish - we don't want to commit a
1154 		 * superblock that points to btree nodes/leafs for which
1155 		 * writeback hasn't finished yet (and without errors).
1156 		 * We cleanup any entries left in the io tree when committing
1157 		 * the transaction (through extent_io_tree_release()).
1158 		 */
1159 		if (ret == -ENOMEM) {
1160 			ret = 0;
1161 			wait_writeback = true;
1162 		}
1163 		if (!ret)
1164 			ret = filemap_fdatawrite_range(mapping, start, end);
1165 		if (!ret && wait_writeback)
1166 			btrfs_btree_wait_writeback_range(fs_info, start, end);
1167 		btrfs_free_extent_state(cached_state);
1168 		if (ret)
1169 			break;
1170 		cached_state = NULL;
1171 		cond_resched();
1172 		start = end + 1;
1173 	}
1174 	return ret;
1175 }
1176 
1177 /*
1178  * when btree blocks are allocated, they have some corresponding bits set for
1179  * them in one of two extent_io trees.  This is used to make sure all of
1180  * those extents are on disk for transaction or log commit.  We wait
1181  * on all the pages and clear them from the dirty pages state tree
1182  */
1183 static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
1184 				       struct extent_io_tree *dirty_pages)
1185 {
1186 	struct extent_state *cached_state = NULL;
1187 	u64 start = 0;
1188 	u64 end;
1189 	int ret = 0;
1190 
1191 	while (btrfs_find_first_extent_bit(dirty_pages, start, &start, &end,
1192 					   EXTENT_NEED_WAIT, &cached_state)) {
1193 		/*
1194 		 * Ignore -ENOMEM errors returned by clear_extent_bit().
1195 		 * When committing the transaction, we'll remove any entries
1196 		 * left in the io tree. For a log commit, we don't remove them
1197 		 * after committing the log because the tree can be accessed
1198 		 * concurrently - we do it only at transaction commit time when
1199 		 * it's safe to do it (through extent_io_tree_release()).
1200 		 */
1201 		ret = btrfs_clear_extent_bit(dirty_pages, start, end,
1202 					     EXTENT_NEED_WAIT, &cached_state);
1203 		if (ret == -ENOMEM)
1204 			ret = 0;
1205 		if (!ret)
1206 			btrfs_btree_wait_writeback_range(fs_info, start, end);
1207 		btrfs_free_extent_state(cached_state);
1208 		if (ret)
1209 			break;
1210 		cached_state = NULL;
1211 		cond_resched();
1212 		start = end + 1;
1213 	}
1214 	return ret;
1215 }
1216 
1217 static int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
1218 		       struct extent_io_tree *dirty_pages)
1219 {
1220 	bool errors = false;
1221 	int ret;
1222 
1223 	ret = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1224 	if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1225 		errors = true;
1226 
1227 	if (errors && !ret)
1228 		ret = -EIO;
1229 	return ret;
1230 }
1231 
1232 int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
1233 {
1234 	struct btrfs_fs_info *fs_info = log_root->fs_info;
1235 	struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
1236 	bool errors = false;
1237 	int ret;
1238 
1239 	ASSERT(btrfs_root_id(log_root) == BTRFS_TREE_LOG_OBJECTID,
1240 	       "root_id(log_root)=%llu", btrfs_root_id(log_root));
1241 
1242 	ret = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1243 	if ((mark & EXTENT_DIRTY_LOG1) &&
1244 	    test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1245 		errors = true;
1246 
1247 	if ((mark & EXTENT_DIRTY_LOG2) &&
1248 	    test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1249 		errors = true;
1250 
1251 	if (errors && !ret)
1252 		ret = -EIO;
1253 	return ret;
1254 }
1255 
1256 /*
1257  * When btree blocks are allocated the corresponding extents are marked dirty.
1258  * This function ensures such extents are persisted on disk for transaction or
1259  * log commit.
1260  *
1261  * @trans: transaction whose dirty pages we'd like to write
1262  */
1263 static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1264 {
1265 	int ret;
1266 	int ret2;
1267 	struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
1268 	struct btrfs_fs_info *fs_info = trans->fs_info;
1269 	struct blk_plug plug;
1270 
1271 	blk_start_plug(&plug);
1272 	ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1273 	blk_finish_plug(&plug);
1274 	ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1275 
1276 	btrfs_extent_io_tree_release(&trans->transaction->dirty_pages);
1277 
1278 	if (ret)
1279 		return ret;
1280 	else if (ret2)
1281 		return ret2;
1282 	else
1283 		return 0;
1284 }
1285 
1286 /*
1287  * this is used to update the root pointer in the tree of tree roots.
1288  *
1289  * But, in the case of the extent allocation tree, updating the root
1290  * pointer may allocate blocks which may change the root of the extent
1291  * allocation tree.
1292  *
1293  * So, this loops and repeats and makes sure the cowonly root didn't
1294  * change while the root pointer was being updated in the metadata.
1295  */
1296 static int update_cowonly_root(struct btrfs_trans_handle *trans,
1297 			       struct btrfs_root *root)
1298 {
1299 	int ret;
1300 	u64 old_root_bytenr;
1301 	u64 old_root_used;
1302 	struct btrfs_fs_info *fs_info = root->fs_info;
1303 	struct btrfs_root *tree_root = fs_info->tree_root;
1304 
1305 	old_root_used = btrfs_root_used(&root->root_item);
1306 
1307 	while (1) {
1308 		old_root_bytenr = btrfs_root_bytenr(&root->root_item);
1309 		if (old_root_bytenr == root->node->start &&
1310 		    old_root_used == btrfs_root_used(&root->root_item))
1311 			break;
1312 
1313 		btrfs_set_root_node(&root->root_item, root->node);
1314 		ret = btrfs_update_root(trans, tree_root,
1315 					&root->root_key,
1316 					&root->root_item);
1317 		if (ret)
1318 			return ret;
1319 
1320 		old_root_used = btrfs_root_used(&root->root_item);
1321 	}
1322 
1323 	return 0;
1324 }
1325 
1326 /*
1327  * update all the cowonly tree roots on disk
1328  *
1329  * The error handling in this function may not be obvious. Any of the
1330  * failures will cause the file system to go offline. We still need
1331  * to clean up the delayed refs.
1332  */
1333 static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
1334 {
1335 	struct btrfs_fs_info *fs_info = trans->fs_info;
1336 	struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
1337 	struct list_head *io_bgs = &trans->transaction->io_bgs;
1338 	struct extent_buffer *eb;
1339 	int ret;
1340 
1341 	/*
1342 	 * At this point no one can be using this transaction to modify any tree
1343 	 * and no one can start another transaction to modify any tree either.
1344 	 */
1345 	ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING,
1346 	       "trans->transaction->state=%d", trans->transaction->state);
1347 
1348 	eb = btrfs_lock_root_node(fs_info->tree_root);
1349 	ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
1350 			      0, &eb, BTRFS_NESTING_COW);
1351 	btrfs_tree_unlock(eb);
1352 	free_extent_buffer(eb);
1353 
1354 	if (ret)
1355 		return ret;
1356 
1357 	ret = btrfs_run_dev_stats(trans);
1358 	if (ret)
1359 		return ret;
1360 	ret = btrfs_run_dev_replace(trans);
1361 	if (ret)
1362 		return ret;
1363 	ret = btrfs_run_qgroups(trans);
1364 	if (ret)
1365 		return ret;
1366 
1367 	ret = btrfs_setup_space_cache(trans);
1368 	if (ret)
1369 		return ret;
1370 
1371 again:
1372 	while (!list_empty(&fs_info->dirty_cowonly_roots)) {
1373 		struct btrfs_root *root;
1374 
1375 		root = list_first_entry(&fs_info->dirty_cowonly_roots,
1376 					struct btrfs_root, dirty_list);
1377 		clear_bit(BTRFS_ROOT_DIRTY, &root->state);
1378 		list_move_tail(&root->dirty_list,
1379 			       &trans->transaction->switch_commits);
1380 
1381 		ret = update_cowonly_root(trans, root);
1382 		if (ret)
1383 			return ret;
1384 	}
1385 
1386 	/* Now flush any delayed refs generated by updating all of the roots */
1387 	ret = btrfs_run_delayed_refs(trans, U64_MAX);
1388 	if (ret)
1389 		return ret;
1390 
1391 	while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
1392 		ret = btrfs_write_dirty_block_groups(trans);
1393 		if (ret)
1394 			return ret;
1395 
1396 		/*
1397 		 * We're writing the dirty block groups, which could generate
1398 		 * delayed refs, which could generate more dirty block groups,
1399 		 * so we want to keep this flushing in this loop to make sure
1400 		 * everything gets run.
1401 		 */
1402 		ret = btrfs_run_delayed_refs(trans, U64_MAX);
1403 		if (ret)
1404 			return ret;
1405 	}
1406 
1407 	if (!list_empty(&fs_info->dirty_cowonly_roots))
1408 		goto again;
1409 
1410 	/* Update dev-replace pointer once everything is committed */
1411 	fs_info->dev_replace.committed_cursor_left =
1412 		fs_info->dev_replace.cursor_left_last_write_of_item;
1413 
1414 	return 0;
1415 }
1416 
1417 /*
1418  * If we had a pending drop we need to see if there are any others left in our
1419  * dead roots list, and if not clear our bit and wake any waiters.
1420  */
1421 void btrfs_maybe_wake_unfinished_drop(struct btrfs_fs_info *fs_info)
1422 {
1423 	/*
1424 	 * We put the drop in progress roots at the front of the list, so if the
1425 	 * first entry doesn't have UNFINISHED_DROP set we can wake everybody
1426 	 * up.
1427 	 */
1428 	spin_lock(&fs_info->trans_lock);
1429 	if (!list_empty(&fs_info->dead_roots)) {
1430 		struct btrfs_root *root = list_first_entry(&fs_info->dead_roots,
1431 							   struct btrfs_root,
1432 							   root_list);
1433 		if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state)) {
1434 			spin_unlock(&fs_info->trans_lock);
1435 			return;
1436 		}
1437 	}
1438 	spin_unlock(&fs_info->trans_lock);
1439 
1440 	btrfs_wake_unfinished_drop(fs_info);
1441 }
1442 
1443 /*
1444  * dead roots are old snapshots that need to be deleted.  This allocates
1445  * a dirty root struct and adds it into the list of dead roots that need to
1446  * be deleted
1447  */
1448 void btrfs_add_dead_root(struct btrfs_root *root)
1449 {
1450 	struct btrfs_fs_info *fs_info = root->fs_info;
1451 
1452 	spin_lock(&fs_info->trans_lock);
1453 	if (list_empty(&root->root_list)) {
1454 		btrfs_grab_root(root);
1455 
1456 		/* We want to process the partially complete drops first. */
1457 		if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state))
1458 			list_add(&root->root_list, &fs_info->dead_roots);
1459 		else
1460 			list_add_tail(&root->root_list, &fs_info->dead_roots);
1461 	}
1462 	spin_unlock(&fs_info->trans_lock);
1463 }
1464 
1465 /*
1466  * Update each subvolume root and its relocation root, if it exists, in the tree
1467  * of tree roots. Also free log roots if they exist.
1468  */
1469 static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
1470 {
1471 	struct btrfs_fs_info *fs_info = trans->fs_info;
1472 	struct btrfs_root *gang[8];
1473 	int i;
1474 	int ret;
1475 
1476 	/*
1477 	 * At this point no one can be using this transaction to modify any tree
1478 	 * and no one can start another transaction to modify any tree either.
1479 	 */
1480 	ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING,
1481 	       "trans->transaction->state=%d", trans->transaction->state);
1482 
1483 	spin_lock(&fs_info->fs_roots_radix_lock);
1484 	while (1) {
1485 		ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
1486 						 (void **)gang, 0,
1487 						 ARRAY_SIZE(gang),
1488 						 BTRFS_ROOT_TRANS_TAG);
1489 		if (ret == 0)
1490 			break;
1491 		for (i = 0; i < ret; i++) {
1492 			struct btrfs_root *root = gang[i];
1493 			int ret2;
1494 
1495 			/*
1496 			 * At this point we can neither have tasks logging inodes
1497 			 * from a root nor trying to commit a log tree.
1498 			 */
1499 			ASSERT(atomic_read(&root->log_writers) == 0,
1500 			       "atomic_read(&root->log_writers)=%d",
1501 			       atomic_read(&root->log_writers));
1502 			ASSERT(atomic_read(&root->log_commit[0]) == 0,
1503 			       "atomic_read(&root->log_commit[0])=%d",
1504 			       atomic_read(&root->log_commit[0]));
1505 			ASSERT(atomic_read(&root->log_commit[1]) == 0,
1506 			       "atomic_read(&root->log_commit[1])=%d",
1507 			       atomic_read(&root->log_commit[1]));
1508 
1509 			radix_tree_tag_clear(&fs_info->fs_roots_radix,
1510 					(unsigned long)btrfs_root_id(root),
1511 					BTRFS_ROOT_TRANS_TAG);
1512 			btrfs_qgroup_free_meta_all_pertrans(root);
1513 			spin_unlock(&fs_info->fs_roots_radix_lock);
1514 
1515 			btrfs_free_log(trans, root);
1516 			ret2 = btrfs_update_reloc_root(trans, root);
1517 			if (ret2)
1518 				return ret2;
1519 
1520 			/* see comments in should_cow_block() */
1521 			clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1522 			smp_mb__after_atomic();
1523 
1524 			if (root->commit_root != root->node) {
1525 				list_add_tail(&root->dirty_list,
1526 					&trans->transaction->switch_commits);
1527 				btrfs_set_root_node(&root->root_item,
1528 						    root->node);
1529 			}
1530 
1531 			ret2 = btrfs_update_root(trans, fs_info->tree_root,
1532 						&root->root_key,
1533 						&root->root_item);
1534 			if (ret2)
1535 				return ret2;
1536 			spin_lock(&fs_info->fs_roots_radix_lock);
1537 		}
1538 	}
1539 	spin_unlock(&fs_info->fs_roots_radix_lock);
1540 	return 0;
1541 }
1542 
1543 /*
1544  * Do all special snapshot related qgroup dirty hack.
1545  *
1546  * Will do all needed qgroup inherit and dirty hack like switch commit
1547  * roots inside one transaction and write all btree into disk, to make
1548  * qgroup works.
1549  */
1550 static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
1551 				   struct btrfs_root *src,
1552 				   struct btrfs_root *parent,
1553 				   struct btrfs_qgroup_inherit *inherit,
1554 				   u64 dst_objectid)
1555 {
1556 	struct btrfs_fs_info *fs_info = src->fs_info;
1557 	int ret;
1558 
1559 	/*
1560 	 * Save some performance in the case that qgroups are not enabled. If
1561 	 * this check races with the ioctl, rescan will kick in anyway.
1562 	 */
1563 	if (!btrfs_qgroup_full_accounting(fs_info))
1564 		return 0;
1565 
1566 	/*
1567 	 * Ensure dirty @src will be committed.  Or, after coming
1568 	 * commit_fs_roots() and switch_commit_roots(), any dirty but not
1569 	 * recorded root will never be updated again, causing an outdated root
1570 	 * item.
1571 	 */
1572 	ret = record_root_in_trans(trans, src, 1);
1573 	if (ret)
1574 		return ret;
1575 
1576 	/*
1577 	 * btrfs_qgroup_inherit relies on a consistent view of the usage for the
1578 	 * src root, so we must run the delayed refs here.
1579 	 *
1580 	 * However this isn't particularly fool proof, because there's no
1581 	 * synchronization keeping us from changing the tree after this point
1582 	 * before we do the qgroup_inherit, or even from making changes while
1583 	 * we're doing the qgroup_inherit.  But that's a problem for the future,
1584 	 * for now flush the delayed refs to narrow the race window where the
1585 	 * qgroup counters could end up wrong.
1586 	 */
1587 	ret = btrfs_run_delayed_refs(trans, U64_MAX);
1588 	if (unlikely(ret)) {
1589 		btrfs_abort_transaction(trans, ret);
1590 		return ret;
1591 	}
1592 
1593 	ret = commit_fs_roots(trans);
1594 	if (ret)
1595 		goto out;
1596 	ret = btrfs_qgroup_account_extents(trans);
1597 	if (ret < 0)
1598 		goto out;
1599 
1600 	/* Now qgroup are all updated, we can inherit it to new qgroups */
1601 	ret = btrfs_qgroup_inherit(trans, btrfs_root_id(src), dst_objectid,
1602 				   btrfs_root_id(parent), inherit);
1603 	if (ret < 0)
1604 		goto out;
1605 
1606 	/*
1607 	 * Now we do a simplified commit transaction, which will:
1608 	 * 1) commit all subvolume and extent tree
1609 	 *    To ensure all subvolume and extent tree have a valid
1610 	 *    commit_root to accounting later insert_dir_item()
1611 	 * 2) write all btree blocks onto disk
1612 	 *    This is to make sure later btree modification will be cowed
1613 	 *    Or commit_root can be populated and cause wrong qgroup numbers
1614 	 * In this simplified commit, we don't really care about other trees
1615 	 * like chunk and root tree, as they won't affect qgroup.
1616 	 * And we don't write super to avoid half committed status.
1617 	 */
1618 	ret = commit_cowonly_roots(trans);
1619 	if (ret)
1620 		goto out;
1621 	switch_commit_roots(trans);
1622 	ret = btrfs_write_and_wait_transaction(trans);
1623 	if (ret)
1624 		btrfs_handle_fs_error(fs_info, ret,
1625 			"Error while writing out transaction for qgroup");
1626 
1627 out:
1628 	/*
1629 	 * Force parent root to be updated, as we recorded it before so its
1630 	 * last_trans == cur_transid.
1631 	 * Or it won't be committed again onto disk after later
1632 	 * insert_dir_item()
1633 	 */
1634 	if (!ret)
1635 		ret = record_root_in_trans(trans, parent, 1);
1636 	return ret;
1637 }
1638 
1639 /*
1640  * new snapshots need to be created at a very specific time in the
1641  * transaction commit.  This does the actual creation.
1642  *
1643  * Note:
1644  * If the error which may affect the commitment of the current transaction
1645  * happens, we should return the error number. If the error which just affect
1646  * the creation of the pending snapshots, just return 0.
1647  */
1648 static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
1649 				   struct btrfs_pending_snapshot *pending)
1650 {
1651 
1652 	struct btrfs_fs_info *fs_info = trans->fs_info;
1653 	struct btrfs_key key;
1654 	struct btrfs_root_item *new_root_item;
1655 	struct btrfs_root *tree_root = fs_info->tree_root;
1656 	struct btrfs_root *root = pending->root;
1657 	struct btrfs_root *parent_root;
1658 	struct btrfs_block_rsv *rsv;
1659 	struct btrfs_inode *parent_inode = pending->dir;
1660 	BTRFS_PATH_AUTO_FREE(path);
1661 	struct btrfs_dir_item *dir_item;
1662 	struct extent_buffer *tmp;
1663 	struct extent_buffer *old;
1664 	struct timespec64 cur_time;
1665 	int ret = 0;
1666 	u64 to_reserve = 0;
1667 	u64 index = 0;
1668 	u64 objectid;
1669 	u64 root_flags;
1670 	unsigned int nofs_flags;
1671 	struct fscrypt_name fname;
1672 
1673 	ASSERT(pending->path);
1674 	path = pending->path;
1675 
1676 	ASSERT(pending->root_item);
1677 	new_root_item = pending->root_item;
1678 
1679 	/*
1680 	 * We're inside a transaction and must make sure that any potential
1681 	 * allocations with GFP_KERNEL in fscrypt won't recurse back to
1682 	 * filesystem.
1683 	 */
1684 	nofs_flags = memalloc_nofs_save();
1685 	pending->error = fscrypt_setup_filename(&parent_inode->vfs_inode,
1686 						&pending->dentry->d_name, 0,
1687 						&fname);
1688 	memalloc_nofs_restore(nofs_flags);
1689 	if (pending->error)
1690 		goto free_pending;
1691 
1692 	pending->error = btrfs_get_free_objectid(tree_root, &objectid);
1693 	if (pending->error)
1694 		goto free_fname;
1695 
1696 	/*
1697 	 * Make qgroup to skip current new snapshot's qgroupid, as it is
1698 	 * accounted by later btrfs_qgroup_inherit().
1699 	 */
1700 	btrfs_set_skip_qgroup(trans, objectid);
1701 
1702 	btrfs_reloc_pre_snapshot(pending, &to_reserve);
1703 
1704 	if (to_reserve > 0) {
1705 		pending->error = btrfs_block_rsv_add(fs_info,
1706 						     &pending->block_rsv,
1707 						     to_reserve,
1708 						     BTRFS_RESERVE_NO_FLUSH);
1709 		if (pending->error)
1710 			goto clear_skip_qgroup;
1711 	}
1712 
1713 	rsv = trans->block_rsv;
1714 	trans->block_rsv = &pending->block_rsv;
1715 	trans->bytes_reserved = trans->block_rsv->reserved;
1716 	trace_btrfs_space_reservation(fs_info, "transaction",
1717 				      trans->transid,
1718 				      trans->bytes_reserved, 1);
1719 	parent_root = parent_inode->root;
1720 	ret = record_root_in_trans(trans, parent_root, 0);
1721 	if (ret)
1722 		goto fail;
1723 	cur_time = current_time(&parent_inode->vfs_inode);
1724 
1725 	/*
1726 	 * insert the directory item
1727 	 */
1728 	ret = btrfs_set_inode_index(parent_inode, &index);
1729 	if (unlikely(ret)) {
1730 		btrfs_abort_transaction(trans, ret);
1731 		goto fail;
1732 	}
1733 
1734 	/* check if there is a file/dir which has the same name. */
1735 	dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
1736 					 btrfs_ino(parent_inode),
1737 					 &fname.disk_name, 0);
1738 	if (dir_item != NULL && !IS_ERR(dir_item)) {
1739 		pending->error = -EEXIST;
1740 		goto dir_item_existed;
1741 	} else if (IS_ERR(dir_item)) {
1742 		ret = PTR_ERR(dir_item);
1743 		btrfs_abort_transaction(trans, ret);
1744 		goto fail;
1745 	}
1746 	btrfs_release_path(path);
1747 
1748 	ret = btrfs_create_qgroup(trans, objectid);
1749 	if (ret && ret != -EEXIST) {
1750 		if (unlikely(ret != -ENOTCONN || btrfs_qgroup_enabled(fs_info))) {
1751 			btrfs_abort_transaction(trans, ret);
1752 			goto fail;
1753 		}
1754 	}
1755 
1756 	/*
1757 	 * pull in the delayed directory update
1758 	 * and the delayed inode item
1759 	 * otherwise we corrupt the FS during
1760 	 * snapshot
1761 	 */
1762 	ret = btrfs_run_delayed_items(trans);
1763 	if (unlikely(ret)) {
1764 		btrfs_abort_transaction(trans, ret);
1765 		goto fail;
1766 	}
1767 
1768 	ret = record_root_in_trans(trans, root, 0);
1769 	if (unlikely(ret)) {
1770 		btrfs_abort_transaction(trans, ret);
1771 		goto fail;
1772 	}
1773 	btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
1774 	memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
1775 	btrfs_check_and_init_root_item(new_root_item);
1776 
1777 	root_flags = btrfs_root_flags(new_root_item);
1778 	if (pending->readonly)
1779 		root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1780 	else
1781 		root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1782 	btrfs_set_root_flags(new_root_item, root_flags);
1783 
1784 	btrfs_set_root_generation_v2(new_root_item,
1785 			trans->transid);
1786 	generate_random_guid(new_root_item->uuid);
1787 	memcpy(new_root_item->parent_uuid, root->root_item.uuid,
1788 			BTRFS_UUID_SIZE);
1789 	if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
1790 		memset(new_root_item->received_uuid, 0,
1791 		       sizeof(new_root_item->received_uuid));
1792 		memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
1793 		memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
1794 		btrfs_set_root_stransid(new_root_item, 0);
1795 		btrfs_set_root_rtransid(new_root_item, 0);
1796 	}
1797 	btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
1798 	btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
1799 	btrfs_set_root_otransid(new_root_item, trans->transid);
1800 
1801 	old = btrfs_lock_root_node(root);
1802 	ret = btrfs_cow_block(trans, root, old, NULL, 0, &old,
1803 			      BTRFS_NESTING_COW);
1804 	if (unlikely(ret)) {
1805 		btrfs_tree_unlock(old);
1806 		free_extent_buffer(old);
1807 		btrfs_abort_transaction(trans, ret);
1808 		goto fail;
1809 	}
1810 
1811 	ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
1812 	/* clean up in any case */
1813 	btrfs_tree_unlock(old);
1814 	free_extent_buffer(old);
1815 	if (unlikely(ret)) {
1816 		btrfs_abort_transaction(trans, ret);
1817 		goto fail;
1818 	}
1819 	/* see comments in should_cow_block() */
1820 	set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1821 	smp_mb__after_atomic();
1822 
1823 	btrfs_set_root_node(new_root_item, tmp);
1824 	/* record when the snapshot was created in key.offset */
1825 	key.objectid = objectid;
1826 	key.type = BTRFS_ROOT_ITEM_KEY;
1827 	key.offset = trans->transid;
1828 	ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1829 	btrfs_tree_unlock(tmp);
1830 	free_extent_buffer(tmp);
1831 	if (unlikely(ret)) {
1832 		btrfs_abort_transaction(trans, ret);
1833 		goto fail;
1834 	}
1835 
1836 	/*
1837 	 * insert root back/forward references
1838 	 */
1839 	ret = btrfs_add_root_ref(trans, objectid,
1840 				 btrfs_root_id(parent_root),
1841 				 btrfs_ino(parent_inode), index,
1842 				 &fname.disk_name);
1843 	if (unlikely(ret)) {
1844 		btrfs_abort_transaction(trans, ret);
1845 		goto fail;
1846 	}
1847 
1848 	key.offset = (u64)-1;
1849 	pending->snap = btrfs_get_new_fs_root(fs_info, objectid, &pending->anon_dev);
1850 	if (IS_ERR(pending->snap)) {
1851 		ret = PTR_ERR(pending->snap);
1852 		pending->snap = NULL;
1853 		btrfs_abort_transaction(trans, ret);
1854 		goto fail;
1855 	}
1856 
1857 	ret = btrfs_reloc_post_snapshot(trans, pending);
1858 	if (unlikely(ret)) {
1859 		btrfs_abort_transaction(trans, ret);
1860 		goto fail;
1861 	}
1862 
1863 	/*
1864 	 * Do special qgroup accounting for snapshot, as we do some qgroup
1865 	 * snapshot hack to do fast snapshot.
1866 	 * To co-operate with that hack, we do hack again.
1867 	 * Or snapshot will be greatly slowed down by a subtree qgroup rescan
1868 	 */
1869 	if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_FULL)
1870 		ret = qgroup_account_snapshot(trans, root, parent_root,
1871 					      pending->inherit, objectid);
1872 	else if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE)
1873 		ret = btrfs_qgroup_inherit(trans, btrfs_root_id(root), objectid,
1874 					   btrfs_root_id(parent_root), pending->inherit);
1875 	if (ret < 0)
1876 		goto fail;
1877 
1878 	ret = btrfs_insert_dir_item(trans, &fname.disk_name,
1879 				    parent_inode, &key, BTRFS_FT_DIR,
1880 				    index);
1881 	if (unlikely(ret)) {
1882 		btrfs_abort_transaction(trans, ret);
1883 		goto fail;
1884 	}
1885 
1886 	btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
1887 						  fname.disk_name.len * 2);
1888 	inode_set_mtime_to_ts(&parent_inode->vfs_inode,
1889 			      inode_set_ctime_current(&parent_inode->vfs_inode));
1890 	ret = btrfs_update_inode_fallback(trans, parent_inode);
1891 	if (unlikely(ret)) {
1892 		btrfs_abort_transaction(trans, ret);
1893 		goto fail;
1894 	}
1895 	ret = btrfs_uuid_tree_add(trans, new_root_item->uuid,
1896 				  BTRFS_UUID_KEY_SUBVOL,
1897 				  objectid);
1898 	if (unlikely(ret)) {
1899 		btrfs_abort_transaction(trans, ret);
1900 		goto fail;
1901 	}
1902 	if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1903 		ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1904 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1905 					  objectid);
1906 		if (unlikely(ret && ret != -EEXIST)) {
1907 			btrfs_abort_transaction(trans, ret);
1908 			goto fail;
1909 		}
1910 	}
1911 
1912 fail:
1913 	pending->error = ret;
1914 dir_item_existed:
1915 	trans->block_rsv = rsv;
1916 	trans->bytes_reserved = 0;
1917 clear_skip_qgroup:
1918 	btrfs_clear_skip_qgroup(trans);
1919 free_fname:
1920 	fscrypt_free_filename(&fname);
1921 free_pending:
1922 	kfree(new_root_item);
1923 	pending->root_item = NULL;
1924 	pending->path = NULL;
1925 
1926 	return ret;
1927 }
1928 
1929 /*
1930  * create all the snapshots we've scheduled for creation
1931  */
1932 static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
1933 {
1934 	struct btrfs_pending_snapshot *pending, *next;
1935 	struct list_head *head = &trans->transaction->pending_snapshots;
1936 	int ret = 0;
1937 
1938 	list_for_each_entry_safe(pending, next, head, list) {
1939 		list_del(&pending->list);
1940 		ret = create_pending_snapshot(trans, pending);
1941 		if (ret)
1942 			break;
1943 	}
1944 	return ret;
1945 }
1946 
1947 static void update_super_roots(struct btrfs_fs_info *fs_info)
1948 {
1949 	struct btrfs_root_item *root_item;
1950 	struct btrfs_super_block *super;
1951 
1952 	super = fs_info->super_copy;
1953 
1954 	root_item = &fs_info->chunk_root->root_item;
1955 	super->chunk_root = root_item->bytenr;
1956 	super->chunk_root_generation = root_item->generation;
1957 	super->chunk_root_level = root_item->level;
1958 
1959 	root_item = &fs_info->tree_root->root_item;
1960 	super->root = root_item->bytenr;
1961 	super->generation = root_item->generation;
1962 	super->root_level = root_item->level;
1963 	if (btrfs_test_opt(fs_info, SPACE_CACHE))
1964 		super->cache_generation = root_item->generation;
1965 	else if (test_bit(BTRFS_FS_CLEANUP_SPACE_CACHE_V1, &fs_info->flags))
1966 		super->cache_generation = 0;
1967 	if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1968 		super->uuid_tree_generation = root_item->generation;
1969 }
1970 
1971 int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1972 {
1973 	struct btrfs_transaction *trans;
1974 	int ret = 0;
1975 
1976 	spin_lock(&info->trans_lock);
1977 	trans = info->running_transaction;
1978 	if (trans)
1979 		ret = is_transaction_blocked(trans);
1980 	spin_unlock(&info->trans_lock);
1981 	return ret;
1982 }
1983 
1984 void btrfs_commit_transaction_async(struct btrfs_trans_handle *trans)
1985 {
1986 	struct btrfs_fs_info *fs_info = trans->fs_info;
1987 	struct btrfs_transaction *cur_trans;
1988 
1989 	/* Kick the transaction kthread. */
1990 	set_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
1991 	wake_up_process(fs_info->transaction_kthread);
1992 
1993 	/* take transaction reference */
1994 	cur_trans = trans->transaction;
1995 	refcount_inc(&cur_trans->use_count);
1996 
1997 	btrfs_end_transaction(trans);
1998 
1999 	/*
2000 	 * Wait for the current transaction commit to start and block
2001 	 * subsequent transaction joins
2002 	 */
2003 	btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2004 	wait_event(fs_info->transaction_blocked_wait,
2005 		   cur_trans->state >= TRANS_STATE_COMMIT_START ||
2006 		   TRANS_ABORTED(cur_trans));
2007 	btrfs_put_transaction(cur_trans);
2008 }
2009 
2010 /*
2011  * If there is a running transaction commit it or if it's already committing,
2012  * wait for its commit to complete. Does not start and commit a new transaction
2013  * if there isn't any running.
2014  */
2015 int btrfs_commit_current_transaction(struct btrfs_root *root)
2016 {
2017 	struct btrfs_trans_handle *trans;
2018 
2019 	trans = btrfs_attach_transaction_barrier(root);
2020 	if (IS_ERR(trans)) {
2021 		int ret = PTR_ERR(trans);
2022 
2023 		return (ret == -ENOENT) ? 0 : ret;
2024 	}
2025 
2026 	return btrfs_commit_transaction(trans);
2027 }
2028 
2029 static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
2030 {
2031 	struct btrfs_fs_info *fs_info = trans->fs_info;
2032 	struct btrfs_transaction *cur_trans = trans->transaction;
2033 
2034 	WARN_ON(refcount_read(&trans->use_count) > 1);
2035 
2036 	btrfs_abort_transaction(trans, err);
2037 
2038 	spin_lock(&fs_info->trans_lock);
2039 
2040 	/*
2041 	 * If the transaction is removed from the list, it means this
2042 	 * transaction has been committed successfully, so it is impossible
2043 	 * to call the cleanup function.
2044 	 */
2045 	BUG_ON(list_empty(&cur_trans->list));
2046 
2047 	if (cur_trans == fs_info->running_transaction) {
2048 		cur_trans->state = TRANS_STATE_COMMIT_DOING;
2049 		spin_unlock(&fs_info->trans_lock);
2050 
2051 		/*
2052 		 * The thread has already released the lockdep map as reader
2053 		 * already in btrfs_commit_transaction().
2054 		 */
2055 		btrfs_might_wait_for_event(fs_info, btrfs_trans_num_writers);
2056 		wait_event(cur_trans->writer_wait,
2057 			   atomic_read(&cur_trans->num_writers) == 1);
2058 
2059 		spin_lock(&fs_info->trans_lock);
2060 	}
2061 
2062 	/*
2063 	 * Now that we know no one else is still using the transaction we can
2064 	 * remove the transaction from the list of transactions. This avoids
2065 	 * the transaction kthread from cleaning up the transaction while some
2066 	 * other task is still using it, which could result in a use-after-free
2067 	 * on things like log trees, as it forces the transaction kthread to
2068 	 * wait for this transaction to be cleaned up by us.
2069 	 */
2070 	list_del_init(&cur_trans->list);
2071 
2072 	spin_unlock(&fs_info->trans_lock);
2073 
2074 	btrfs_cleanup_one_transaction(trans->transaction);
2075 
2076 	spin_lock(&fs_info->trans_lock);
2077 	if (cur_trans == fs_info->running_transaction)
2078 		fs_info->running_transaction = NULL;
2079 	spin_unlock(&fs_info->trans_lock);
2080 
2081 	if (trans->type & __TRANS_FREEZABLE)
2082 		sb_end_intwrite(fs_info->sb);
2083 	btrfs_put_transaction(cur_trans);
2084 	btrfs_put_transaction(cur_trans);
2085 
2086 	trace_btrfs_transaction_commit(fs_info);
2087 
2088 	if (current->journal_info == trans)
2089 		current->journal_info = NULL;
2090 
2091 	/*
2092 	 * If relocation is running, we can't cancel scrub because that will
2093 	 * result in a deadlock. Before relocating a block group, relocation
2094 	 * pauses scrub, then starts and commits a transaction before unpausing
2095 	 * scrub. If the transaction commit is being done by the relocation
2096 	 * task or triggered by another task and the relocation task is waiting
2097 	 * for the commit, and we end up here due to an error in the commit
2098 	 * path, then calling btrfs_scrub_cancel() will deadlock, as we are
2099 	 * asking for scrub to stop while having it asked to be paused higher
2100 	 * above in relocation code.
2101 	 */
2102 	if (!test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
2103 		btrfs_scrub_cancel(fs_info);
2104 
2105 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
2106 }
2107 
2108 /*
2109  * Release reserved delayed ref space of all pending block groups of the
2110  * transaction and remove them from the list
2111  */
2112 static void btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle *trans)
2113 {
2114        struct btrfs_fs_info *fs_info = trans->fs_info;
2115        struct btrfs_block_group *block_group, *tmp;
2116 
2117        list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
2118                btrfs_dec_delayed_refs_rsv_bg_inserts(fs_info);
2119 		/*
2120 		* Not strictly necessary to lock, as no other task will be using a
2121 		* block_group on the new_bgs list during a transaction abort.
2122 		*/
2123 	       spin_lock(&fs_info->unused_bgs_lock);
2124                list_del_init(&block_group->bg_list);
2125 	       btrfs_put_block_group(block_group);
2126 	       spin_unlock(&fs_info->unused_bgs_lock);
2127        }
2128 }
2129 
2130 static inline int btrfs_start_delalloc_flush(struct btrfs_fs_info *fs_info)
2131 {
2132 	/*
2133 	 * We use try_to_writeback_inodes_sb() here because if we used
2134 	 * btrfs_start_delalloc_roots we would deadlock with fs freeze.
2135 	 * Currently are holding the fs freeze lock, if we do an async flush
2136 	 * we'll do btrfs_join_transaction() and deadlock because we need to
2137 	 * wait for the fs freeze lock.  Using the direct flushing we benefit
2138 	 * from already being in a transaction and our join_transaction doesn't
2139 	 * have to re-take the fs freeze lock.
2140 	 *
2141 	 * Note that try_to_writeback_inodes_sb() will only trigger writeback
2142 	 * if it can read lock sb->s_umount. It will always be able to lock it,
2143 	 * except when the filesystem is being unmounted or being frozen, but in
2144 	 * those cases sync_filesystem() is called, which results in calling
2145 	 * writeback_inodes_sb() while holding a write lock on sb->s_umount.
2146 	 * Note that we don't call writeback_inodes_sb() directly, because it
2147 	 * will emit a warning if sb->s_umount is not locked.
2148 	 */
2149 	if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2150 		try_to_writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
2151 	return 0;
2152 }
2153 
2154 static inline void btrfs_wait_delalloc_flush(struct btrfs_fs_info *fs_info)
2155 {
2156 	if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2157 		btrfs_wait_ordered_roots(fs_info, U64_MAX, NULL);
2158 }
2159 
2160 /*
2161  * Add a pending snapshot associated with the given transaction handle to the
2162  * respective handle. This must be called after the transaction commit started
2163  * and while holding fs_info->trans_lock.
2164  * This serves to guarantee a caller of btrfs_commit_transaction() that it can
2165  * safely free the pending snapshot pointer in case btrfs_commit_transaction()
2166  * returns an error.
2167  */
2168 static void add_pending_snapshot(struct btrfs_trans_handle *trans)
2169 {
2170 	struct btrfs_transaction *cur_trans = trans->transaction;
2171 
2172 	if (!trans->pending_snapshot)
2173 		return;
2174 
2175 	lockdep_assert_held(&trans->fs_info->trans_lock);
2176 	ASSERT(cur_trans->state >= TRANS_STATE_COMMIT_PREP,
2177 	       "cur_trans->state=%d", cur_trans->state);
2178 
2179 	list_add(&trans->pending_snapshot->list, &cur_trans->pending_snapshots);
2180 }
2181 
2182 static void update_commit_stats(struct btrfs_fs_info *fs_info)
2183 {
2184 	ktime_t now = ktime_get_ns();
2185 	ktime_t interval = now - fs_info->commit_stats.critical_section_start_time;
2186 
2187 	ASSERT(fs_info->commit_stats.critical_section_start_time);
2188 
2189 	fs_info->commit_stats.commit_count++;
2190 	fs_info->commit_stats.last_commit_dur = interval;
2191 	fs_info->commit_stats.max_commit_dur =
2192 			max_t(u64, fs_info->commit_stats.max_commit_dur, interval);
2193 	fs_info->commit_stats.total_commit_dur += interval;
2194 	fs_info->commit_stats.critical_section_start_time = 0;
2195 }
2196 
2197 int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
2198 {
2199 	struct btrfs_fs_info *fs_info = trans->fs_info;
2200 	struct btrfs_transaction *cur_trans = trans->transaction;
2201 	struct btrfs_transaction *prev_trans = NULL;
2202 	int ret;
2203 
2204 	ASSERT(refcount_read(&trans->use_count) == 1,
2205 	       "refcount_read(&trans->use_count)=%d", refcount_read(&trans->use_count));
2206 	btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2207 
2208 	clear_bit(BTRFS_FS_NEED_TRANS_COMMIT, &fs_info->flags);
2209 
2210 	/* Stop the commit early if ->aborted is set */
2211 	if (TRANS_ABORTED(cur_trans)) {
2212 		ret = cur_trans->aborted;
2213 		goto lockdep_trans_commit_start_release;
2214 	}
2215 
2216 	btrfs_trans_release_metadata(trans);
2217 	trans->block_rsv = NULL;
2218 
2219 	/*
2220 	 * We only want one transaction commit doing the flushing so we do not
2221 	 * waste a bunch of time on lock contention on the extent root node.
2222 	 */
2223 	if (!test_and_set_bit(BTRFS_DELAYED_REFS_FLUSHING,
2224 			      &cur_trans->delayed_refs.flags)) {
2225 		/*
2226 		 * Make a pass through all the delayed refs we have so far.
2227 		 * Any running threads may add more while we are here.
2228 		 */
2229 		ret = btrfs_run_delayed_refs(trans, 0);
2230 		if (ret)
2231 			goto lockdep_trans_commit_start_release;
2232 	}
2233 
2234 	btrfs_create_pending_block_groups(trans);
2235 
2236 	if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
2237 		int run_it = 0;
2238 
2239 		/* this mutex is also taken before trying to set
2240 		 * block groups readonly.  We need to make sure
2241 		 * that nobody has set a block group readonly
2242 		 * after a extents from that block group have been
2243 		 * allocated for cache files.  btrfs_set_block_group_ro
2244 		 * will wait for the transaction to commit if it
2245 		 * finds BTRFS_TRANS_DIRTY_BG_RUN set.
2246 		 *
2247 		 * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
2248 		 * only one process starts all the block group IO.  It wouldn't
2249 		 * hurt to have more than one go through, but there's no
2250 		 * real advantage to it either.
2251 		 */
2252 		mutex_lock(&fs_info->ro_block_group_mutex);
2253 		if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
2254 				      &cur_trans->flags))
2255 			run_it = 1;
2256 		mutex_unlock(&fs_info->ro_block_group_mutex);
2257 
2258 		if (run_it) {
2259 			ret = btrfs_start_dirty_block_groups(trans);
2260 			if (ret)
2261 				goto lockdep_trans_commit_start_release;
2262 		}
2263 	}
2264 
2265 	spin_lock(&fs_info->trans_lock);
2266 	if (cur_trans->state >= TRANS_STATE_COMMIT_PREP) {
2267 		enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2268 
2269 		add_pending_snapshot(trans);
2270 
2271 		spin_unlock(&fs_info->trans_lock);
2272 		refcount_inc(&cur_trans->use_count);
2273 
2274 		if (trans->in_fsync)
2275 			want_state = TRANS_STATE_SUPER_COMMITTED;
2276 
2277 		btrfs_trans_state_lockdep_release(fs_info,
2278 						  BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2279 		ret = btrfs_end_transaction(trans);
2280 		wait_for_commit(cur_trans, want_state);
2281 
2282 		if (TRANS_ABORTED(cur_trans))
2283 			ret = cur_trans->aborted;
2284 
2285 		btrfs_put_transaction(cur_trans);
2286 
2287 		return ret;
2288 	}
2289 
2290 	cur_trans->state = TRANS_STATE_COMMIT_PREP;
2291 	wake_up(&fs_info->transaction_blocked_wait);
2292 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2293 
2294 	if (!list_is_first(&cur_trans->list, &fs_info->trans_list)) {
2295 		enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2296 
2297 		if (trans->in_fsync)
2298 			want_state = TRANS_STATE_SUPER_COMMITTED;
2299 
2300 		prev_trans = list_prev_entry(cur_trans, list);
2301 		if (prev_trans->state < want_state) {
2302 			refcount_inc(&prev_trans->use_count);
2303 			spin_unlock(&fs_info->trans_lock);
2304 
2305 			wait_for_commit(prev_trans, want_state);
2306 
2307 			ret = READ_ONCE(prev_trans->aborted);
2308 
2309 			btrfs_put_transaction(prev_trans);
2310 			if (ret)
2311 				goto lockdep_release;
2312 			spin_lock(&fs_info->trans_lock);
2313 		}
2314 	} else {
2315 		/*
2316 		 * The previous transaction was aborted and was already removed
2317 		 * from the list of transactions at fs_info->trans_list. So we
2318 		 * abort to prevent writing a new superblock that reflects a
2319 		 * corrupt state (pointing to trees with unwritten nodes/leafs).
2320 		 */
2321 		if (BTRFS_FS_ERROR(fs_info)) {
2322 			spin_unlock(&fs_info->trans_lock);
2323 			ret = -EROFS;
2324 			goto lockdep_release;
2325 		}
2326 	}
2327 
2328 	cur_trans->state = TRANS_STATE_COMMIT_START;
2329 	wake_up(&fs_info->transaction_blocked_wait);
2330 	spin_unlock(&fs_info->trans_lock);
2331 
2332 	/*
2333 	 * Get the time spent on the work done by the commit thread and not
2334 	 * the time spent waiting on a previous commit
2335 	 */
2336 	fs_info->commit_stats.critical_section_start_time = ktime_get_ns();
2337 	extwriter_counter_dec(cur_trans, trans->type);
2338 
2339 	ret = btrfs_start_delalloc_flush(fs_info);
2340 	if (ret)
2341 		goto lockdep_release;
2342 
2343 	ret = btrfs_run_delayed_items(trans);
2344 	if (ret)
2345 		goto lockdep_release;
2346 
2347 	/*
2348 	 * The thread has started/joined the transaction thus it holds the
2349 	 * lockdep map as a reader. It has to release it before acquiring the
2350 	 * lockdep map as a writer.
2351 	 */
2352 	btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2353 	btrfs_might_wait_for_event(fs_info, btrfs_trans_num_extwriters);
2354 	wait_event(cur_trans->writer_wait,
2355 		   extwriter_counter_read(cur_trans) == 0);
2356 
2357 	/* some pending stuffs might be added after the previous flush. */
2358 	ret = btrfs_run_delayed_items(trans);
2359 	if (ret) {
2360 		btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2361 		goto cleanup_transaction;
2362 	}
2363 
2364 	btrfs_wait_delalloc_flush(fs_info);
2365 
2366 	/*
2367 	 * Wait for all ordered extents started by a fast fsync that joined this
2368 	 * transaction. Otherwise if this transaction commits before the ordered
2369 	 * extents complete we lose logged data after a power failure.
2370 	 */
2371 	btrfs_might_wait_for_event(fs_info, btrfs_trans_pending_ordered);
2372 	wait_event(cur_trans->pending_wait,
2373 		   atomic_read(&cur_trans->pending_ordered) == 0);
2374 
2375 	btrfs_scrub_pause(fs_info);
2376 	/*
2377 	 * Ok now we need to make sure to block out any other joins while we
2378 	 * commit the transaction.  We could have started a join before setting
2379 	 * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2380 	 */
2381 	spin_lock(&fs_info->trans_lock);
2382 	add_pending_snapshot(trans);
2383 	cur_trans->state = TRANS_STATE_COMMIT_DOING;
2384 	spin_unlock(&fs_info->trans_lock);
2385 
2386 	/*
2387 	 * The thread has started/joined the transaction thus it holds the
2388 	 * lockdep map as a reader. It has to release it before acquiring the
2389 	 * lockdep map as a writer.
2390 	 */
2391 	btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2392 	btrfs_might_wait_for_event(fs_info, btrfs_trans_num_writers);
2393 	wait_event(cur_trans->writer_wait,
2394 		   atomic_read(&cur_trans->num_writers) == 1);
2395 
2396 	/*
2397 	 * Make lockdep happy by acquiring the state locks after
2398 	 * btrfs_trans_num_writers is released. If we acquired the state locks
2399 	 * before releasing the btrfs_trans_num_writers lock then lockdep would
2400 	 * complain because we did not follow the reverse order unlocking rule.
2401 	 */
2402 	btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2403 	btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2404 	btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2405 
2406 	/*
2407 	 * We've started the commit, clear the flag in case we were triggered to
2408 	 * do an async commit but somebody else started before the transaction
2409 	 * kthread could do the work.
2410 	 */
2411 	clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
2412 
2413 	if (TRANS_ABORTED(cur_trans)) {
2414 		ret = cur_trans->aborted;
2415 		btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2416 		goto scrub_continue;
2417 	}
2418 	/*
2419 	 * the reloc mutex makes sure that we stop
2420 	 * the balancing code from coming in and moving
2421 	 * extents around in the middle of the commit
2422 	 */
2423 	mutex_lock(&fs_info->reloc_mutex);
2424 
2425 	/*
2426 	 * We needn't worry about the delayed items because we will
2427 	 * deal with them in create_pending_snapshot(), which is the
2428 	 * core function of the snapshot creation.
2429 	 */
2430 	ret = create_pending_snapshots(trans);
2431 	if (ret)
2432 		goto unlock_reloc;
2433 
2434 	/*
2435 	 * We insert the dir indexes of the snapshots and update the inode
2436 	 * of the snapshots' parents after the snapshot creation, so there
2437 	 * are some delayed items which are not dealt with. Now deal with
2438 	 * them.
2439 	 *
2440 	 * We needn't worry that this operation will corrupt the snapshots,
2441 	 * because all the tree which are snapshotted will be forced to COW
2442 	 * the nodes and leaves.
2443 	 */
2444 	ret = btrfs_run_delayed_items(trans);
2445 	if (ret)
2446 		goto unlock_reloc;
2447 
2448 	ret = btrfs_run_delayed_refs(trans, U64_MAX);
2449 	if (ret)
2450 		goto unlock_reloc;
2451 
2452 	/*
2453 	 * make sure none of the code above managed to slip in a
2454 	 * delayed item
2455 	 */
2456 	btrfs_assert_delayed_root_empty(fs_info);
2457 
2458 	WARN_ON(cur_trans != trans->transaction);
2459 
2460 	ret = commit_fs_roots(trans);
2461 	if (ret)
2462 		goto unlock_reloc;
2463 
2464 	/* commit_fs_roots gets rid of all the tree log roots, it is now
2465 	 * safe to free the root of tree log roots
2466 	 */
2467 	btrfs_free_log_root_tree(trans, fs_info);
2468 
2469 	/*
2470 	 * Since fs roots are all committed, we can get a quite accurate
2471 	 * new_roots. So let's do quota accounting.
2472 	 */
2473 	ret = btrfs_qgroup_account_extents(trans);
2474 	if (ret < 0)
2475 		goto unlock_reloc;
2476 
2477 	ret = commit_cowonly_roots(trans);
2478 	if (ret)
2479 		goto unlock_reloc;
2480 
2481 	/*
2482 	 * The tasks which save the space cache and inode cache may also
2483 	 * update ->aborted, check it.
2484 	 */
2485 	if (TRANS_ABORTED(cur_trans)) {
2486 		ret = cur_trans->aborted;
2487 		goto unlock_reloc;
2488 	}
2489 
2490 	cur_trans = fs_info->running_transaction;
2491 
2492 	btrfs_set_root_node(&fs_info->tree_root->root_item,
2493 			    fs_info->tree_root->node);
2494 	list_add_tail(&fs_info->tree_root->dirty_list,
2495 		      &cur_trans->switch_commits);
2496 
2497 	btrfs_set_root_node(&fs_info->chunk_root->root_item,
2498 			    fs_info->chunk_root->node);
2499 	list_add_tail(&fs_info->chunk_root->dirty_list,
2500 		      &cur_trans->switch_commits);
2501 
2502 	if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
2503 		btrfs_set_root_node(&fs_info->block_group_root->root_item,
2504 				    fs_info->block_group_root->node);
2505 		list_add_tail(&fs_info->block_group_root->dirty_list,
2506 			      &cur_trans->switch_commits);
2507 	}
2508 
2509 	switch_commit_roots(trans);
2510 
2511 	ASSERT(list_empty(&cur_trans->dirty_bgs));
2512 	ASSERT(list_empty(&cur_trans->io_bgs));
2513 	update_super_roots(fs_info);
2514 
2515 	btrfs_set_super_log_root(fs_info->super_copy, 0);
2516 	btrfs_set_super_log_root_level(fs_info->super_copy, 0);
2517 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
2518 	       sizeof(*fs_info->super_copy));
2519 
2520 	btrfs_commit_device_sizes(cur_trans);
2521 
2522 	clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2523 	clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2524 
2525 	btrfs_trans_release_chunk_metadata(trans);
2526 
2527 	/*
2528 	 * Before changing the transaction state to TRANS_STATE_UNBLOCKED and
2529 	 * setting fs_info->running_transaction to NULL, lock tree_log_mutex to
2530 	 * make sure that before we commit our superblock, no other task can
2531 	 * start a new transaction and commit a log tree before we commit our
2532 	 * superblock. Anyone trying to commit a log tree locks this mutex before
2533 	 * writing its superblock.
2534 	 */
2535 	mutex_lock(&fs_info->tree_log_mutex);
2536 
2537 	spin_lock(&fs_info->trans_lock);
2538 	cur_trans->state = TRANS_STATE_UNBLOCKED;
2539 	fs_info->running_transaction = NULL;
2540 	spin_unlock(&fs_info->trans_lock);
2541 	mutex_unlock(&fs_info->reloc_mutex);
2542 
2543 	wake_up(&fs_info->transaction_wait);
2544 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2545 
2546 	/* If we have features changed, wake up the cleaner to update sysfs. */
2547 	if (test_bit(BTRFS_FS_FEATURE_CHANGED, &fs_info->flags) &&
2548 	    fs_info->cleaner_kthread)
2549 		wake_up_process(fs_info->cleaner_kthread);
2550 
2551 	ret = btrfs_write_and_wait_transaction(trans);
2552 	if (ret) {
2553 		btrfs_handle_fs_error(fs_info, ret,
2554 				      "Error while writing out transaction");
2555 		mutex_unlock(&fs_info->tree_log_mutex);
2556 		goto scrub_continue;
2557 	}
2558 
2559 	ret = write_all_supers(fs_info, 0);
2560 	/*
2561 	 * the super is written, we can safely allow the tree-loggers
2562 	 * to go about their business
2563 	 */
2564 	mutex_unlock(&fs_info->tree_log_mutex);
2565 	if (ret)
2566 		goto scrub_continue;
2567 
2568 	update_commit_stats(fs_info);
2569 	/*
2570 	 * We needn't acquire the lock here because there is no other task
2571 	 * which can change it.
2572 	 */
2573 	cur_trans->state = TRANS_STATE_SUPER_COMMITTED;
2574 	wake_up(&cur_trans->commit_wait);
2575 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2576 
2577 	ret = btrfs_finish_extent_commit(trans);
2578 	if (ret)
2579 		goto scrub_continue;
2580 
2581 	if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
2582 		btrfs_clear_space_info_full(fs_info);
2583 
2584 	btrfs_set_last_trans_committed(fs_info, cur_trans->transid);
2585 	/*
2586 	 * We needn't acquire the lock here because there is no other task
2587 	 * which can change it.
2588 	 */
2589 	cur_trans->state = TRANS_STATE_COMPLETED;
2590 	wake_up(&cur_trans->commit_wait);
2591 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2592 
2593 	spin_lock(&fs_info->trans_lock);
2594 	list_del_init(&cur_trans->list);
2595 	spin_unlock(&fs_info->trans_lock);
2596 
2597 	btrfs_put_transaction(cur_trans);
2598 	btrfs_put_transaction(cur_trans);
2599 
2600 	if (trans->type & __TRANS_FREEZABLE)
2601 		sb_end_intwrite(fs_info->sb);
2602 
2603 	trace_btrfs_transaction_commit(fs_info);
2604 
2605 	btrfs_scrub_continue(fs_info);
2606 
2607 	if (current->journal_info == trans)
2608 		current->journal_info = NULL;
2609 
2610 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
2611 
2612 	return ret;
2613 
2614 unlock_reloc:
2615 	mutex_unlock(&fs_info->reloc_mutex);
2616 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2617 scrub_continue:
2618 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2619 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2620 	btrfs_scrub_continue(fs_info);
2621 cleanup_transaction:
2622 	btrfs_trans_release_metadata(trans);
2623 	btrfs_cleanup_pending_block_groups(trans);
2624 	btrfs_trans_release_chunk_metadata(trans);
2625 	trans->block_rsv = NULL;
2626 	btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
2627 	if (current->journal_info == trans)
2628 		current->journal_info = NULL;
2629 	cleanup_transaction(trans, ret);
2630 
2631 	return ret;
2632 
2633 lockdep_release:
2634 	btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2635 	btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2636 	goto cleanup_transaction;
2637 
2638 lockdep_trans_commit_start_release:
2639 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2640 	btrfs_end_transaction(trans);
2641 	return ret;
2642 }
2643 
2644 /*
2645  * return < 0 if error
2646  * 0 if there are no more dead_roots at the time of call
2647  * 1 there are more to be processed, call me again
2648  *
2649  * The return value indicates there are certainly more snapshots to delete, but
2650  * if there comes a new one during processing, it may return 0. We don't mind,
2651  * because btrfs_commit_super will poke cleaner thread and it will process it a
2652  * few seconds later.
2653  */
2654 int btrfs_clean_one_deleted_snapshot(struct btrfs_fs_info *fs_info)
2655 {
2656 	struct btrfs_root *root;
2657 	int ret;
2658 
2659 	spin_lock(&fs_info->trans_lock);
2660 	if (list_empty(&fs_info->dead_roots)) {
2661 		spin_unlock(&fs_info->trans_lock);
2662 		return 0;
2663 	}
2664 	root = list_first_entry(&fs_info->dead_roots,
2665 			struct btrfs_root, root_list);
2666 	list_del_init(&root->root_list);
2667 	spin_unlock(&fs_info->trans_lock);
2668 
2669 	btrfs_debug(fs_info, "cleaner removing %llu", btrfs_root_id(root));
2670 
2671 	btrfs_kill_all_delayed_nodes(root);
2672 
2673 	if (btrfs_header_backref_rev(root->node) <
2674 			BTRFS_MIXED_BACKREF_REV)
2675 		ret = btrfs_drop_snapshot(root, false, false);
2676 	else
2677 		ret = btrfs_drop_snapshot(root, true, false);
2678 
2679 	btrfs_put_root(root);
2680 	return (ret < 0) ? 0 : 1;
2681 }
2682 
2683 /*
2684  * We only mark the transaction aborted and then set the file system read-only.
2685  * This will prevent new transactions from starting or trying to join this
2686  * one.
2687  *
2688  * This means that error recovery at the call site is limited to freeing
2689  * any local memory allocations and passing the error code up without
2690  * further cleanup. The transaction should complete as it normally would
2691  * in the call path but will return -EIO.
2692  *
2693  * We'll complete the cleanup in btrfs_end_transaction and
2694  * btrfs_commit_transaction.
2695  */
2696 void __cold __btrfs_abort_transaction(struct btrfs_trans_handle *trans,
2697 				      const char *function,
2698 				      unsigned int line, int error, bool first_hit)
2699 {
2700 	struct btrfs_fs_info *fs_info = trans->fs_info;
2701 
2702 	WRITE_ONCE(trans->aborted, error);
2703 	WRITE_ONCE(trans->transaction->aborted, error);
2704 	if (first_hit && error == -ENOSPC)
2705 		btrfs_dump_space_info_for_trans_abort(fs_info);
2706 	/* Wake up anybody who may be waiting on this transaction */
2707 	wake_up(&fs_info->transaction_wait);
2708 	wake_up(&fs_info->transaction_blocked_wait);
2709 	__btrfs_handle_fs_error(fs_info, function, line, error, NULL);
2710 }
2711 
2712 int __init btrfs_transaction_init(void)
2713 {
2714 	btrfs_trans_handle_cachep = KMEM_CACHE(btrfs_trans_handle, SLAB_TEMPORARY);
2715 	if (!btrfs_trans_handle_cachep)
2716 		return -ENOMEM;
2717 	return 0;
2718 }
2719 
2720 void __cold btrfs_transaction_exit(void)
2721 {
2722 	kmem_cache_destroy(btrfs_trans_handle_cachep);
2723 }
2724