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