xref: /openbmc/linux/fs/btrfs/transaction.c (revision da097dcc)
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 got_it:
719 	if (!current->journal_info)
720 		current->journal_info = h;
721 
722 	/*
723 	 * If the space_info is marked ALLOC_FORCE then we'll get upgraded to
724 	 * ALLOC_FORCE the first run through, and then we won't allocate for
725 	 * anybody else who races in later.  We don't care about the return
726 	 * value here.
727 	 */
728 	if (do_chunk_alloc && num_bytes) {
729 		u64 flags = h->block_rsv->space_info->flags;
730 
731 		btrfs_chunk_alloc(h, btrfs_get_alloc_profile(fs_info, flags),
732 				  CHUNK_ALLOC_NO_FORCE);
733 	}
734 
735 	/*
736 	 * btrfs_record_root_in_trans() needs to alloc new extents, and may
737 	 * call btrfs_join_transaction() while we're also starting a
738 	 * transaction.
739 	 *
740 	 * Thus it need to be called after current->journal_info initialized,
741 	 * or we can deadlock.
742 	 */
743 	ret = btrfs_record_root_in_trans(h, root);
744 	if (ret) {
745 		/*
746 		 * The transaction handle is fully initialized and linked with
747 		 * other structures so it needs to be ended in case of errors,
748 		 * not just freed.
749 		 */
750 		btrfs_end_transaction(h);
751 		goto reserve_fail;
752 	}
753 	/*
754 	 * Now that we have found a transaction to be a part of, convert the
755 	 * qgroup reservation from prealloc to pertrans. A different transaction
756 	 * can't race in and free our pertrans out from under us.
757 	 */
758 	if (qgroup_reserved)
759 		btrfs_qgroup_convert_reserved_meta(root, qgroup_reserved);
760 
761 	return h;
762 
763 join_fail:
764 	if (type & __TRANS_FREEZABLE)
765 		sb_end_intwrite(fs_info->sb);
766 	kmem_cache_free(btrfs_trans_handle_cachep, h);
767 alloc_fail:
768 	if (num_bytes)
769 		btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
770 					num_bytes, NULL);
771 reserve_fail:
772 	btrfs_qgroup_free_meta_prealloc(root, qgroup_reserved);
773 	return ERR_PTR(ret);
774 }
775 
776 struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
777 						   unsigned int num_items)
778 {
779 	return start_transaction(root, num_items, TRANS_START,
780 				 BTRFS_RESERVE_FLUSH_ALL, true);
781 }
782 
783 struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
784 					struct btrfs_root *root,
785 					unsigned int num_items)
786 {
787 	return start_transaction(root, num_items, TRANS_START,
788 				 BTRFS_RESERVE_FLUSH_ALL_STEAL, false);
789 }
790 
791 struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
792 {
793 	return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
794 				 true);
795 }
796 
797 struct btrfs_trans_handle *btrfs_join_transaction_spacecache(struct btrfs_root *root)
798 {
799 	return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
800 				 BTRFS_RESERVE_NO_FLUSH, true);
801 }
802 
803 /*
804  * Similar to regular join but it never starts a transaction when none is
805  * running or when there's a running one at a state >= TRANS_STATE_UNBLOCKED.
806  * This is similar to btrfs_attach_transaction() but it allows the join to
807  * happen if the transaction commit already started but it's not yet in the
808  * "doing" phase (the state is < TRANS_STATE_COMMIT_DOING).
809  */
810 struct btrfs_trans_handle *btrfs_join_transaction_nostart(struct btrfs_root *root)
811 {
812 	return start_transaction(root, 0, TRANS_JOIN_NOSTART,
813 				 BTRFS_RESERVE_NO_FLUSH, true);
814 }
815 
816 /*
817  * btrfs_attach_transaction() - catch the running transaction
818  *
819  * It is used when we want to commit the current the transaction, but
820  * don't want to start a new one.
821  *
822  * Note: If this function return -ENOENT, it just means there is no
823  * running transaction. But it is possible that the inactive transaction
824  * is still in the memory, not fully on disk. If you hope there is no
825  * inactive transaction in the fs when -ENOENT is returned, you should
826  * invoke
827  *     btrfs_attach_transaction_barrier()
828  */
829 struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
830 {
831 	return start_transaction(root, 0, TRANS_ATTACH,
832 				 BTRFS_RESERVE_NO_FLUSH, true);
833 }
834 
835 /*
836  * btrfs_attach_transaction_barrier() - catch the running transaction
837  *
838  * It is similar to the above function, the difference is this one
839  * will wait for all the inactive transactions until they fully
840  * complete.
841  */
842 struct btrfs_trans_handle *
843 btrfs_attach_transaction_barrier(struct btrfs_root *root)
844 {
845 	struct btrfs_trans_handle *trans;
846 
847 	trans = start_transaction(root, 0, TRANS_ATTACH,
848 				  BTRFS_RESERVE_NO_FLUSH, true);
849 	if (trans == ERR_PTR(-ENOENT)) {
850 		int ret;
851 
852 		ret = btrfs_wait_for_commit(root->fs_info, 0);
853 		if (ret)
854 			return ERR_PTR(ret);
855 	}
856 
857 	return trans;
858 }
859 
860 /* Wait for a transaction commit to reach at least the given state. */
861 static noinline void wait_for_commit(struct btrfs_transaction *commit,
862 				     const enum btrfs_trans_state min_state)
863 {
864 	struct btrfs_fs_info *fs_info = commit->fs_info;
865 	u64 transid = commit->transid;
866 	bool put = false;
867 
868 	/*
869 	 * At the moment this function is called with min_state either being
870 	 * TRANS_STATE_COMPLETED or TRANS_STATE_SUPER_COMMITTED.
871 	 */
872 	if (min_state == TRANS_STATE_COMPLETED)
873 		btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
874 	else
875 		btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
876 
877 	while (1) {
878 		wait_event(commit->commit_wait, commit->state >= min_state);
879 		if (put)
880 			btrfs_put_transaction(commit);
881 
882 		if (min_state < TRANS_STATE_COMPLETED)
883 			break;
884 
885 		/*
886 		 * A transaction isn't really completed until all of the
887 		 * previous transactions are completed, but with fsync we can
888 		 * end up with SUPER_COMMITTED transactions before a COMPLETED
889 		 * transaction. Wait for those.
890 		 */
891 
892 		spin_lock(&fs_info->trans_lock);
893 		commit = list_first_entry_or_null(&fs_info->trans_list,
894 						  struct btrfs_transaction,
895 						  list);
896 		if (!commit || commit->transid > transid) {
897 			spin_unlock(&fs_info->trans_lock);
898 			break;
899 		}
900 		refcount_inc(&commit->use_count);
901 		put = true;
902 		spin_unlock(&fs_info->trans_lock);
903 	}
904 }
905 
906 int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
907 {
908 	struct btrfs_transaction *cur_trans = NULL, *t;
909 	int ret = 0;
910 
911 	if (transid) {
912 		if (transid <= fs_info->last_trans_committed)
913 			goto out;
914 
915 		/* find specified transaction */
916 		spin_lock(&fs_info->trans_lock);
917 		list_for_each_entry(t, &fs_info->trans_list, list) {
918 			if (t->transid == transid) {
919 				cur_trans = t;
920 				refcount_inc(&cur_trans->use_count);
921 				ret = 0;
922 				break;
923 			}
924 			if (t->transid > transid) {
925 				ret = 0;
926 				break;
927 			}
928 		}
929 		spin_unlock(&fs_info->trans_lock);
930 
931 		/*
932 		 * The specified transaction doesn't exist, or we
933 		 * raced with btrfs_commit_transaction
934 		 */
935 		if (!cur_trans) {
936 			if (transid > fs_info->last_trans_committed)
937 				ret = -EINVAL;
938 			goto out;
939 		}
940 	} else {
941 		/* find newest transaction that is committing | committed */
942 		spin_lock(&fs_info->trans_lock);
943 		list_for_each_entry_reverse(t, &fs_info->trans_list,
944 					    list) {
945 			if (t->state >= TRANS_STATE_COMMIT_START) {
946 				if (t->state == TRANS_STATE_COMPLETED)
947 					break;
948 				cur_trans = t;
949 				refcount_inc(&cur_trans->use_count);
950 				break;
951 			}
952 		}
953 		spin_unlock(&fs_info->trans_lock);
954 		if (!cur_trans)
955 			goto out;  /* nothing committing|committed */
956 	}
957 
958 	wait_for_commit(cur_trans, TRANS_STATE_COMPLETED);
959 	ret = cur_trans->aborted;
960 	btrfs_put_transaction(cur_trans);
961 out:
962 	return ret;
963 }
964 
965 void btrfs_throttle(struct btrfs_fs_info *fs_info)
966 {
967 	wait_current_trans(fs_info);
968 }
969 
970 bool btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
971 {
972 	struct btrfs_transaction *cur_trans = trans->transaction;
973 
974 	if (cur_trans->state >= TRANS_STATE_COMMIT_START ||
975 	    test_bit(BTRFS_DELAYED_REFS_FLUSHING, &cur_trans->delayed_refs.flags))
976 		return true;
977 
978 	if (btrfs_check_space_for_delayed_refs(trans->fs_info))
979 		return true;
980 
981 	return !!btrfs_block_rsv_check(&trans->fs_info->global_block_rsv, 50);
982 }
983 
984 static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
985 
986 {
987 	struct btrfs_fs_info *fs_info = trans->fs_info;
988 
989 	if (!trans->block_rsv) {
990 		ASSERT(!trans->bytes_reserved);
991 		return;
992 	}
993 
994 	if (!trans->bytes_reserved)
995 		return;
996 
997 	ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
998 	trace_btrfs_space_reservation(fs_info, "transaction",
999 				      trans->transid, trans->bytes_reserved, 0);
1000 	btrfs_block_rsv_release(fs_info, trans->block_rsv,
1001 				trans->bytes_reserved, NULL);
1002 	trans->bytes_reserved = 0;
1003 }
1004 
1005 static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
1006 				   int throttle)
1007 {
1008 	struct btrfs_fs_info *info = trans->fs_info;
1009 	struct btrfs_transaction *cur_trans = trans->transaction;
1010 	int err = 0;
1011 
1012 	if (refcount_read(&trans->use_count) > 1) {
1013 		refcount_dec(&trans->use_count);
1014 		trans->block_rsv = trans->orig_rsv;
1015 		return 0;
1016 	}
1017 
1018 	btrfs_trans_release_metadata(trans);
1019 	trans->block_rsv = NULL;
1020 
1021 	btrfs_create_pending_block_groups(trans);
1022 
1023 	btrfs_trans_release_chunk_metadata(trans);
1024 
1025 	if (trans->type & __TRANS_FREEZABLE)
1026 		sb_end_intwrite(info->sb);
1027 
1028 	WARN_ON(cur_trans != info->running_transaction);
1029 	WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
1030 	atomic_dec(&cur_trans->num_writers);
1031 	extwriter_counter_dec(cur_trans, trans->type);
1032 
1033 	cond_wake_up(&cur_trans->writer_wait);
1034 
1035 	btrfs_lockdep_release(info, btrfs_trans_num_extwriters);
1036 	btrfs_lockdep_release(info, btrfs_trans_num_writers);
1037 
1038 	btrfs_put_transaction(cur_trans);
1039 
1040 	if (current->journal_info == trans)
1041 		current->journal_info = NULL;
1042 
1043 	if (throttle)
1044 		btrfs_run_delayed_iputs(info);
1045 
1046 	if (TRANS_ABORTED(trans) || BTRFS_FS_ERROR(info)) {
1047 		wake_up_process(info->transaction_kthread);
1048 		if (TRANS_ABORTED(trans))
1049 			err = trans->aborted;
1050 		else
1051 			err = -EROFS;
1052 	}
1053 
1054 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
1055 	return err;
1056 }
1057 
1058 int btrfs_end_transaction(struct btrfs_trans_handle *trans)
1059 {
1060 	return __btrfs_end_transaction(trans, 0);
1061 }
1062 
1063 int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
1064 {
1065 	return __btrfs_end_transaction(trans, 1);
1066 }
1067 
1068 /*
1069  * when btree blocks are allocated, they have some corresponding bits set for
1070  * them in one of two extent_io trees.  This is used to make sure all of
1071  * those extents are sent to disk but does not wait on them
1072  */
1073 int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
1074 			       struct extent_io_tree *dirty_pages, int mark)
1075 {
1076 	int err = 0;
1077 	int werr = 0;
1078 	struct address_space *mapping = fs_info->btree_inode->i_mapping;
1079 	struct extent_state *cached_state = NULL;
1080 	u64 start = 0;
1081 	u64 end;
1082 
1083 	while (find_first_extent_bit(dirty_pages, start, &start, &end,
1084 				     mark, &cached_state)) {
1085 		bool wait_writeback = false;
1086 
1087 		err = convert_extent_bit(dirty_pages, start, end,
1088 					 EXTENT_NEED_WAIT,
1089 					 mark, &cached_state);
1090 		/*
1091 		 * convert_extent_bit can return -ENOMEM, which is most of the
1092 		 * time a temporary error. So when it happens, ignore the error
1093 		 * and wait for writeback of this range to finish - because we
1094 		 * failed to set the bit EXTENT_NEED_WAIT for the range, a call
1095 		 * to __btrfs_wait_marked_extents() would not know that
1096 		 * writeback for this range started and therefore wouldn't
1097 		 * wait for it to finish - we don't want to commit a
1098 		 * superblock that points to btree nodes/leafs for which
1099 		 * writeback hasn't finished yet (and without errors).
1100 		 * We cleanup any entries left in the io tree when committing
1101 		 * the transaction (through extent_io_tree_release()).
1102 		 */
1103 		if (err == -ENOMEM) {
1104 			err = 0;
1105 			wait_writeback = true;
1106 		}
1107 		if (!err)
1108 			err = filemap_fdatawrite_range(mapping, start, end);
1109 		if (err)
1110 			werr = err;
1111 		else if (wait_writeback)
1112 			werr = filemap_fdatawait_range(mapping, start, end);
1113 		free_extent_state(cached_state);
1114 		cached_state = NULL;
1115 		cond_resched();
1116 		start = end + 1;
1117 	}
1118 	return werr;
1119 }
1120 
1121 /*
1122  * when btree blocks are allocated, they have some corresponding bits set for
1123  * them in one of two extent_io trees.  This is used to make sure all of
1124  * those extents are on disk for transaction or log commit.  We wait
1125  * on all the pages and clear them from the dirty pages state tree
1126  */
1127 static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
1128 				       struct extent_io_tree *dirty_pages)
1129 {
1130 	int err = 0;
1131 	int werr = 0;
1132 	struct address_space *mapping = fs_info->btree_inode->i_mapping;
1133 	struct extent_state *cached_state = NULL;
1134 	u64 start = 0;
1135 	u64 end;
1136 
1137 	while (find_first_extent_bit(dirty_pages, start, &start, &end,
1138 				     EXTENT_NEED_WAIT, &cached_state)) {
1139 		/*
1140 		 * Ignore -ENOMEM errors returned by clear_extent_bit().
1141 		 * When committing the transaction, we'll remove any entries
1142 		 * left in the io tree. For a log commit, we don't remove them
1143 		 * after committing the log because the tree can be accessed
1144 		 * concurrently - we do it only at transaction commit time when
1145 		 * it's safe to do it (through extent_io_tree_release()).
1146 		 */
1147 		err = clear_extent_bit(dirty_pages, start, end,
1148 				       EXTENT_NEED_WAIT, &cached_state);
1149 		if (err == -ENOMEM)
1150 			err = 0;
1151 		if (!err)
1152 			err = filemap_fdatawait_range(mapping, start, end);
1153 		if (err)
1154 			werr = err;
1155 		free_extent_state(cached_state);
1156 		cached_state = NULL;
1157 		cond_resched();
1158 		start = end + 1;
1159 	}
1160 	if (err)
1161 		werr = err;
1162 	return werr;
1163 }
1164 
1165 static int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
1166 		       struct extent_io_tree *dirty_pages)
1167 {
1168 	bool errors = false;
1169 	int err;
1170 
1171 	err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1172 	if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1173 		errors = true;
1174 
1175 	if (errors && !err)
1176 		err = -EIO;
1177 	return err;
1178 }
1179 
1180 int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
1181 {
1182 	struct btrfs_fs_info *fs_info = log_root->fs_info;
1183 	struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
1184 	bool errors = false;
1185 	int err;
1186 
1187 	ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
1188 
1189 	err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1190 	if ((mark & EXTENT_DIRTY) &&
1191 	    test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1192 		errors = true;
1193 
1194 	if ((mark & EXTENT_NEW) &&
1195 	    test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1196 		errors = true;
1197 
1198 	if (errors && !err)
1199 		err = -EIO;
1200 	return err;
1201 }
1202 
1203 /*
1204  * When btree blocks are allocated the corresponding extents are marked dirty.
1205  * This function ensures such extents are persisted on disk for transaction or
1206  * log commit.
1207  *
1208  * @trans: transaction whose dirty pages we'd like to write
1209  */
1210 static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1211 {
1212 	int ret;
1213 	int ret2;
1214 	struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
1215 	struct btrfs_fs_info *fs_info = trans->fs_info;
1216 	struct blk_plug plug;
1217 
1218 	blk_start_plug(&plug);
1219 	ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1220 	blk_finish_plug(&plug);
1221 	ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1222 
1223 	extent_io_tree_release(&trans->transaction->dirty_pages);
1224 
1225 	if (ret)
1226 		return ret;
1227 	else if (ret2)
1228 		return ret2;
1229 	else
1230 		return 0;
1231 }
1232 
1233 /*
1234  * this is used to update the root pointer in the tree of tree roots.
1235  *
1236  * But, in the case of the extent allocation tree, updating the root
1237  * pointer may allocate blocks which may change the root of the extent
1238  * allocation tree.
1239  *
1240  * So, this loops and repeats and makes sure the cowonly root didn't
1241  * change while the root pointer was being updated in the metadata.
1242  */
1243 static int update_cowonly_root(struct btrfs_trans_handle *trans,
1244 			       struct btrfs_root *root)
1245 {
1246 	int ret;
1247 	u64 old_root_bytenr;
1248 	u64 old_root_used;
1249 	struct btrfs_fs_info *fs_info = root->fs_info;
1250 	struct btrfs_root *tree_root = fs_info->tree_root;
1251 
1252 	old_root_used = btrfs_root_used(&root->root_item);
1253 
1254 	while (1) {
1255 		old_root_bytenr = btrfs_root_bytenr(&root->root_item);
1256 		if (old_root_bytenr == root->node->start &&
1257 		    old_root_used == btrfs_root_used(&root->root_item))
1258 			break;
1259 
1260 		btrfs_set_root_node(&root->root_item, root->node);
1261 		ret = btrfs_update_root(trans, tree_root,
1262 					&root->root_key,
1263 					&root->root_item);
1264 		if (ret)
1265 			return ret;
1266 
1267 		old_root_used = btrfs_root_used(&root->root_item);
1268 	}
1269 
1270 	return 0;
1271 }
1272 
1273 /*
1274  * update all the cowonly tree roots on disk
1275  *
1276  * The error handling in this function may not be obvious. Any of the
1277  * failures will cause the file system to go offline. We still need
1278  * to clean up the delayed refs.
1279  */
1280 static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
1281 {
1282 	struct btrfs_fs_info *fs_info = trans->fs_info;
1283 	struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
1284 	struct list_head *io_bgs = &trans->transaction->io_bgs;
1285 	struct list_head *next;
1286 	struct extent_buffer *eb;
1287 	int ret;
1288 
1289 	/*
1290 	 * At this point no one can be using this transaction to modify any tree
1291 	 * and no one can start another transaction to modify any tree either.
1292 	 */
1293 	ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1294 
1295 	eb = btrfs_lock_root_node(fs_info->tree_root);
1296 	ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
1297 			      0, &eb, BTRFS_NESTING_COW);
1298 	btrfs_tree_unlock(eb);
1299 	free_extent_buffer(eb);
1300 
1301 	if (ret)
1302 		return ret;
1303 
1304 	ret = btrfs_run_dev_stats(trans);
1305 	if (ret)
1306 		return ret;
1307 	ret = btrfs_run_dev_replace(trans);
1308 	if (ret)
1309 		return ret;
1310 	ret = btrfs_run_qgroups(trans);
1311 	if (ret)
1312 		return ret;
1313 
1314 	ret = btrfs_setup_space_cache(trans);
1315 	if (ret)
1316 		return ret;
1317 
1318 again:
1319 	while (!list_empty(&fs_info->dirty_cowonly_roots)) {
1320 		struct btrfs_root *root;
1321 		next = fs_info->dirty_cowonly_roots.next;
1322 		list_del_init(next);
1323 		root = list_entry(next, struct btrfs_root, dirty_list);
1324 		clear_bit(BTRFS_ROOT_DIRTY, &root->state);
1325 
1326 		list_add_tail(&root->dirty_list,
1327 			      &trans->transaction->switch_commits);
1328 		ret = update_cowonly_root(trans, root);
1329 		if (ret)
1330 			return ret;
1331 	}
1332 
1333 	/* Now flush any delayed refs generated by updating all of the roots */
1334 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1335 	if (ret)
1336 		return ret;
1337 
1338 	while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
1339 		ret = btrfs_write_dirty_block_groups(trans);
1340 		if (ret)
1341 			return ret;
1342 
1343 		/*
1344 		 * We're writing the dirty block groups, which could generate
1345 		 * delayed refs, which could generate more dirty block groups,
1346 		 * so we want to keep this flushing in this loop to make sure
1347 		 * everything gets run.
1348 		 */
1349 		ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1350 		if (ret)
1351 			return ret;
1352 	}
1353 
1354 	if (!list_empty(&fs_info->dirty_cowonly_roots))
1355 		goto again;
1356 
1357 	/* Update dev-replace pointer once everything is committed */
1358 	fs_info->dev_replace.committed_cursor_left =
1359 		fs_info->dev_replace.cursor_left_last_write_of_item;
1360 
1361 	return 0;
1362 }
1363 
1364 /*
1365  * If we had a pending drop we need to see if there are any others left in our
1366  * dead roots list, and if not clear our bit and wake any waiters.
1367  */
1368 void btrfs_maybe_wake_unfinished_drop(struct btrfs_fs_info *fs_info)
1369 {
1370 	/*
1371 	 * We put the drop in progress roots at the front of the list, so if the
1372 	 * first entry doesn't have UNFINISHED_DROP set we can wake everybody
1373 	 * up.
1374 	 */
1375 	spin_lock(&fs_info->trans_lock);
1376 	if (!list_empty(&fs_info->dead_roots)) {
1377 		struct btrfs_root *root = list_first_entry(&fs_info->dead_roots,
1378 							   struct btrfs_root,
1379 							   root_list);
1380 		if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state)) {
1381 			spin_unlock(&fs_info->trans_lock);
1382 			return;
1383 		}
1384 	}
1385 	spin_unlock(&fs_info->trans_lock);
1386 
1387 	btrfs_wake_unfinished_drop(fs_info);
1388 }
1389 
1390 /*
1391  * dead roots are old snapshots that need to be deleted.  This allocates
1392  * a dirty root struct and adds it into the list of dead roots that need to
1393  * be deleted
1394  */
1395 void btrfs_add_dead_root(struct btrfs_root *root)
1396 {
1397 	struct btrfs_fs_info *fs_info = root->fs_info;
1398 
1399 	spin_lock(&fs_info->trans_lock);
1400 	if (list_empty(&root->root_list)) {
1401 		btrfs_grab_root(root);
1402 
1403 		/* We want to process the partially complete drops first. */
1404 		if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state))
1405 			list_add(&root->root_list, &fs_info->dead_roots);
1406 		else
1407 			list_add_tail(&root->root_list, &fs_info->dead_roots);
1408 	}
1409 	spin_unlock(&fs_info->trans_lock);
1410 }
1411 
1412 /*
1413  * Update each subvolume root and its relocation root, if it exists, in the tree
1414  * of tree roots. Also free log roots if they exist.
1415  */
1416 static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
1417 {
1418 	struct btrfs_fs_info *fs_info = trans->fs_info;
1419 	struct btrfs_root *gang[8];
1420 	int i;
1421 	int ret;
1422 
1423 	/*
1424 	 * At this point no one can be using this transaction to modify any tree
1425 	 * and no one can start another transaction to modify any tree either.
1426 	 */
1427 	ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING);
1428 
1429 	spin_lock(&fs_info->fs_roots_radix_lock);
1430 	while (1) {
1431 		ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
1432 						 (void **)gang, 0,
1433 						 ARRAY_SIZE(gang),
1434 						 BTRFS_ROOT_TRANS_TAG);
1435 		if (ret == 0)
1436 			break;
1437 		for (i = 0; i < ret; i++) {
1438 			struct btrfs_root *root = gang[i];
1439 			int ret2;
1440 
1441 			/*
1442 			 * At this point we can neither have tasks logging inodes
1443 			 * from a root nor trying to commit a log tree.
1444 			 */
1445 			ASSERT(atomic_read(&root->log_writers) == 0);
1446 			ASSERT(atomic_read(&root->log_commit[0]) == 0);
1447 			ASSERT(atomic_read(&root->log_commit[1]) == 0);
1448 
1449 			radix_tree_tag_clear(&fs_info->fs_roots_radix,
1450 					(unsigned long)root->root_key.objectid,
1451 					BTRFS_ROOT_TRANS_TAG);
1452 			btrfs_qgroup_free_meta_all_pertrans(root);
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 		}
1478 	}
1479 	spin_unlock(&fs_info->fs_roots_radix_lock);
1480 	return 0;
1481 }
1482 
1483 /*
1484  * defrag a given btree.
1485  * Every leaf in the btree is read and defragged.
1486  */
1487 int btrfs_defrag_root(struct btrfs_root *root)
1488 {
1489 	struct btrfs_fs_info *info = root->fs_info;
1490 	struct btrfs_trans_handle *trans;
1491 	int ret;
1492 
1493 	if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
1494 		return 0;
1495 
1496 	while (1) {
1497 		trans = btrfs_start_transaction(root, 0);
1498 		if (IS_ERR(trans)) {
1499 			ret = PTR_ERR(trans);
1500 			break;
1501 		}
1502 
1503 		ret = btrfs_defrag_leaves(trans, root);
1504 
1505 		btrfs_end_transaction(trans);
1506 		btrfs_btree_balance_dirty(info);
1507 		cond_resched();
1508 
1509 		if (btrfs_fs_closing(info) || ret != -EAGAIN)
1510 			break;
1511 
1512 		if (btrfs_defrag_cancelled(info)) {
1513 			btrfs_debug(info, "defrag_root cancelled");
1514 			ret = -EAGAIN;
1515 			break;
1516 		}
1517 	}
1518 	clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
1519 	return ret;
1520 }
1521 
1522 /*
1523  * Do all special snapshot related qgroup dirty hack.
1524  *
1525  * Will do all needed qgroup inherit and dirty hack like switch commit
1526  * roots inside one transaction and write all btree into disk, to make
1527  * qgroup works.
1528  */
1529 static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
1530 				   struct btrfs_root *src,
1531 				   struct btrfs_root *parent,
1532 				   struct btrfs_qgroup_inherit *inherit,
1533 				   u64 dst_objectid)
1534 {
1535 	struct btrfs_fs_info *fs_info = src->fs_info;
1536 	int ret;
1537 
1538 	/*
1539 	 * Save some performance in the case that qgroups are not
1540 	 * enabled. If this check races with the ioctl, rescan will
1541 	 * kick in anyway.
1542 	 */
1543 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1544 		return 0;
1545 
1546 	/*
1547 	 * Ensure dirty @src will be committed.  Or, after coming
1548 	 * commit_fs_roots() and switch_commit_roots(), any dirty but not
1549 	 * recorded root will never be updated again, causing an outdated root
1550 	 * item.
1551 	 */
1552 	ret = record_root_in_trans(trans, src, 1);
1553 	if (ret)
1554 		return ret;
1555 
1556 	/*
1557 	 * btrfs_qgroup_inherit relies on a consistent view of the usage for the
1558 	 * src root, so we must run the delayed refs here.
1559 	 *
1560 	 * However this isn't particularly fool proof, because there's no
1561 	 * synchronization keeping us from changing the tree after this point
1562 	 * before we do the qgroup_inherit, or even from making changes while
1563 	 * we're doing the qgroup_inherit.  But that's a problem for the future,
1564 	 * for now flush the delayed refs to narrow the race window where the
1565 	 * qgroup counters could end up wrong.
1566 	 */
1567 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1568 	if (ret) {
1569 		btrfs_abort_transaction(trans, ret);
1570 		return ret;
1571 	}
1572 
1573 	ret = commit_fs_roots(trans);
1574 	if (ret)
1575 		goto out;
1576 	ret = btrfs_qgroup_account_extents(trans);
1577 	if (ret < 0)
1578 		goto out;
1579 
1580 	/* Now qgroup are all updated, we can inherit it to new qgroups */
1581 	ret = btrfs_qgroup_inherit(trans, src->root_key.objectid, dst_objectid,
1582 				   inherit);
1583 	if (ret < 0)
1584 		goto out;
1585 
1586 	/*
1587 	 * Now we do a simplified commit transaction, which will:
1588 	 * 1) commit all subvolume and extent tree
1589 	 *    To ensure all subvolume and extent tree have a valid
1590 	 *    commit_root to accounting later insert_dir_item()
1591 	 * 2) write all btree blocks onto disk
1592 	 *    This is to make sure later btree modification will be cowed
1593 	 *    Or commit_root can be populated and cause wrong qgroup numbers
1594 	 * In this simplified commit, we don't really care about other trees
1595 	 * like chunk and root tree, as they won't affect qgroup.
1596 	 * And we don't write super to avoid half committed status.
1597 	 */
1598 	ret = commit_cowonly_roots(trans);
1599 	if (ret)
1600 		goto out;
1601 	switch_commit_roots(trans);
1602 	ret = btrfs_write_and_wait_transaction(trans);
1603 	if (ret)
1604 		btrfs_handle_fs_error(fs_info, ret,
1605 			"Error while writing out transaction for qgroup");
1606 
1607 out:
1608 	/*
1609 	 * Force parent root to be updated, as we recorded it before so its
1610 	 * last_trans == cur_transid.
1611 	 * Or it won't be committed again onto disk after later
1612 	 * insert_dir_item()
1613 	 */
1614 	if (!ret)
1615 		ret = record_root_in_trans(trans, parent, 1);
1616 	return ret;
1617 }
1618 
1619 /*
1620  * new snapshots need to be created at a very specific time in the
1621  * transaction commit.  This does the actual creation.
1622  *
1623  * Note:
1624  * If the error which may affect the commitment of the current transaction
1625  * happens, we should return the error number. If the error which just affect
1626  * the creation of the pending snapshots, just return 0.
1627  */
1628 static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
1629 				   struct btrfs_pending_snapshot *pending)
1630 {
1631 
1632 	struct btrfs_fs_info *fs_info = trans->fs_info;
1633 	struct btrfs_key key;
1634 	struct btrfs_root_item *new_root_item;
1635 	struct btrfs_root *tree_root = fs_info->tree_root;
1636 	struct btrfs_root *root = pending->root;
1637 	struct btrfs_root *parent_root;
1638 	struct btrfs_block_rsv *rsv;
1639 	struct inode *parent_inode = pending->dir;
1640 	struct btrfs_path *path;
1641 	struct btrfs_dir_item *dir_item;
1642 	struct extent_buffer *tmp;
1643 	struct extent_buffer *old;
1644 	struct timespec64 cur_time;
1645 	int ret = 0;
1646 	u64 to_reserve = 0;
1647 	u64 index = 0;
1648 	u64 objectid;
1649 	u64 root_flags;
1650 	unsigned int nofs_flags;
1651 	struct fscrypt_name fname;
1652 
1653 	ASSERT(pending->path);
1654 	path = pending->path;
1655 
1656 	ASSERT(pending->root_item);
1657 	new_root_item = pending->root_item;
1658 
1659 	/*
1660 	 * We're inside a transaction and must make sure that any potential
1661 	 * allocations with GFP_KERNEL in fscrypt won't recurse back to
1662 	 * filesystem.
1663 	 */
1664 	nofs_flags = memalloc_nofs_save();
1665 	pending->error = fscrypt_setup_filename(parent_inode,
1666 						&pending->dentry->d_name, 0,
1667 						&fname);
1668 	memalloc_nofs_restore(nofs_flags);
1669 	if (pending->error)
1670 		goto free_pending;
1671 
1672 	pending->error = btrfs_get_free_objectid(tree_root, &objectid);
1673 	if (pending->error)
1674 		goto free_fname;
1675 
1676 	/*
1677 	 * Make qgroup to skip current new snapshot's qgroupid, as it is
1678 	 * accounted by later btrfs_qgroup_inherit().
1679 	 */
1680 	btrfs_set_skip_qgroup(trans, objectid);
1681 
1682 	btrfs_reloc_pre_snapshot(pending, &to_reserve);
1683 
1684 	if (to_reserve > 0) {
1685 		pending->error = btrfs_block_rsv_add(fs_info,
1686 						     &pending->block_rsv,
1687 						     to_reserve,
1688 						     BTRFS_RESERVE_NO_FLUSH);
1689 		if (pending->error)
1690 			goto clear_skip_qgroup;
1691 	}
1692 
1693 	key.objectid = objectid;
1694 	key.offset = (u64)-1;
1695 	key.type = BTRFS_ROOT_ITEM_KEY;
1696 
1697 	rsv = trans->block_rsv;
1698 	trans->block_rsv = &pending->block_rsv;
1699 	trans->bytes_reserved = trans->block_rsv->reserved;
1700 	trace_btrfs_space_reservation(fs_info, "transaction",
1701 				      trans->transid,
1702 				      trans->bytes_reserved, 1);
1703 	parent_root = BTRFS_I(parent_inode)->root;
1704 	ret = record_root_in_trans(trans, parent_root, 0);
1705 	if (ret)
1706 		goto fail;
1707 	cur_time = current_time(parent_inode);
1708 
1709 	/*
1710 	 * insert the directory item
1711 	 */
1712 	ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
1713 	if (ret) {
1714 		btrfs_abort_transaction(trans, ret);
1715 		goto fail;
1716 	}
1717 
1718 	/* check if there is a file/dir which has the same name. */
1719 	dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
1720 					 btrfs_ino(BTRFS_I(parent_inode)),
1721 					 &fname.disk_name, 0);
1722 	if (dir_item != NULL && !IS_ERR(dir_item)) {
1723 		pending->error = -EEXIST;
1724 		goto dir_item_existed;
1725 	} else if (IS_ERR(dir_item)) {
1726 		ret = PTR_ERR(dir_item);
1727 		btrfs_abort_transaction(trans, ret);
1728 		goto fail;
1729 	}
1730 	btrfs_release_path(path);
1731 
1732 	/*
1733 	 * pull in the delayed directory update
1734 	 * and the delayed inode item
1735 	 * otherwise we corrupt the FS during
1736 	 * snapshot
1737 	 */
1738 	ret = btrfs_run_delayed_items(trans);
1739 	if (ret) {	/* Transaction aborted */
1740 		btrfs_abort_transaction(trans, ret);
1741 		goto fail;
1742 	}
1743 
1744 	ret = record_root_in_trans(trans, root, 0);
1745 	if (ret) {
1746 		btrfs_abort_transaction(trans, ret);
1747 		goto fail;
1748 	}
1749 	btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
1750 	memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
1751 	btrfs_check_and_init_root_item(new_root_item);
1752 
1753 	root_flags = btrfs_root_flags(new_root_item);
1754 	if (pending->readonly)
1755 		root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1756 	else
1757 		root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1758 	btrfs_set_root_flags(new_root_item, root_flags);
1759 
1760 	btrfs_set_root_generation_v2(new_root_item,
1761 			trans->transid);
1762 	generate_random_guid(new_root_item->uuid);
1763 	memcpy(new_root_item->parent_uuid, root->root_item.uuid,
1764 			BTRFS_UUID_SIZE);
1765 	if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
1766 		memset(new_root_item->received_uuid, 0,
1767 		       sizeof(new_root_item->received_uuid));
1768 		memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
1769 		memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
1770 		btrfs_set_root_stransid(new_root_item, 0);
1771 		btrfs_set_root_rtransid(new_root_item, 0);
1772 	}
1773 	btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
1774 	btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
1775 	btrfs_set_root_otransid(new_root_item, trans->transid);
1776 
1777 	old = btrfs_lock_root_node(root);
1778 	ret = btrfs_cow_block(trans, root, old, NULL, 0, &old,
1779 			      BTRFS_NESTING_COW);
1780 	if (ret) {
1781 		btrfs_tree_unlock(old);
1782 		free_extent_buffer(old);
1783 		btrfs_abort_transaction(trans, ret);
1784 		goto fail;
1785 	}
1786 
1787 	ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
1788 	/* clean up in any case */
1789 	btrfs_tree_unlock(old);
1790 	free_extent_buffer(old);
1791 	if (ret) {
1792 		btrfs_abort_transaction(trans, ret);
1793 		goto fail;
1794 	}
1795 	/* see comments in should_cow_block() */
1796 	set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1797 	smp_wmb();
1798 
1799 	btrfs_set_root_node(new_root_item, tmp);
1800 	/* record when the snapshot was created in key.offset */
1801 	key.offset = trans->transid;
1802 	ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1803 	btrfs_tree_unlock(tmp);
1804 	free_extent_buffer(tmp);
1805 	if (ret) {
1806 		btrfs_abort_transaction(trans, ret);
1807 		goto fail;
1808 	}
1809 
1810 	/*
1811 	 * insert root back/forward references
1812 	 */
1813 	ret = btrfs_add_root_ref(trans, objectid,
1814 				 parent_root->root_key.objectid,
1815 				 btrfs_ino(BTRFS_I(parent_inode)), index,
1816 				 &fname.disk_name);
1817 	if (ret) {
1818 		btrfs_abort_transaction(trans, ret);
1819 		goto fail;
1820 	}
1821 
1822 	key.offset = (u64)-1;
1823 	pending->snap = btrfs_get_new_fs_root(fs_info, objectid, &pending->anon_dev);
1824 	if (IS_ERR(pending->snap)) {
1825 		ret = PTR_ERR(pending->snap);
1826 		pending->snap = NULL;
1827 		btrfs_abort_transaction(trans, ret);
1828 		goto fail;
1829 	}
1830 
1831 	ret = btrfs_reloc_post_snapshot(trans, pending);
1832 	if (ret) {
1833 		btrfs_abort_transaction(trans, ret);
1834 		goto fail;
1835 	}
1836 
1837 	/*
1838 	 * Do special qgroup accounting for snapshot, as we do some qgroup
1839 	 * snapshot hack to do fast snapshot.
1840 	 * To co-operate with that hack, we do hack again.
1841 	 * Or snapshot will be greatly slowed down by a subtree qgroup rescan
1842 	 */
1843 	ret = qgroup_account_snapshot(trans, root, parent_root,
1844 				      pending->inherit, objectid);
1845 	if (ret < 0)
1846 		goto fail;
1847 
1848 	ret = btrfs_insert_dir_item(trans, &fname.disk_name,
1849 				    BTRFS_I(parent_inode), &key, BTRFS_FT_DIR,
1850 				    index);
1851 	/* We have check then name at the beginning, so it is impossible. */
1852 	BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
1853 	if (ret) {
1854 		btrfs_abort_transaction(trans, ret);
1855 		goto fail;
1856 	}
1857 
1858 	btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
1859 						  fname.disk_name.len * 2);
1860 	parent_inode->i_mtime = inode_set_ctime_current(parent_inode);
1861 	ret = btrfs_update_inode_fallback(trans, parent_root, BTRFS_I(parent_inode));
1862 	if (ret) {
1863 		btrfs_abort_transaction(trans, ret);
1864 		goto fail;
1865 	}
1866 	ret = btrfs_uuid_tree_add(trans, new_root_item->uuid,
1867 				  BTRFS_UUID_KEY_SUBVOL,
1868 				  objectid);
1869 	if (ret) {
1870 		btrfs_abort_transaction(trans, ret);
1871 		goto fail;
1872 	}
1873 	if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1874 		ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1875 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1876 					  objectid);
1877 		if (ret && ret != -EEXIST) {
1878 			btrfs_abort_transaction(trans, ret);
1879 			goto fail;
1880 		}
1881 	}
1882 
1883 fail:
1884 	pending->error = ret;
1885 dir_item_existed:
1886 	trans->block_rsv = rsv;
1887 	trans->bytes_reserved = 0;
1888 clear_skip_qgroup:
1889 	btrfs_clear_skip_qgroup(trans);
1890 free_fname:
1891 	fscrypt_free_filename(&fname);
1892 free_pending:
1893 	kfree(new_root_item);
1894 	pending->root_item = NULL;
1895 	btrfs_free_path(path);
1896 	pending->path = NULL;
1897 
1898 	return ret;
1899 }
1900 
1901 /*
1902  * create all the snapshots we've scheduled for creation
1903  */
1904 static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
1905 {
1906 	struct btrfs_pending_snapshot *pending, *next;
1907 	struct list_head *head = &trans->transaction->pending_snapshots;
1908 	int ret = 0;
1909 
1910 	list_for_each_entry_safe(pending, next, head, list) {
1911 		list_del(&pending->list);
1912 		ret = create_pending_snapshot(trans, pending);
1913 		if (ret)
1914 			break;
1915 	}
1916 	return ret;
1917 }
1918 
1919 static void update_super_roots(struct btrfs_fs_info *fs_info)
1920 {
1921 	struct btrfs_root_item *root_item;
1922 	struct btrfs_super_block *super;
1923 
1924 	super = fs_info->super_copy;
1925 
1926 	root_item = &fs_info->chunk_root->root_item;
1927 	super->chunk_root = root_item->bytenr;
1928 	super->chunk_root_generation = root_item->generation;
1929 	super->chunk_root_level = root_item->level;
1930 
1931 	root_item = &fs_info->tree_root->root_item;
1932 	super->root = root_item->bytenr;
1933 	super->generation = root_item->generation;
1934 	super->root_level = root_item->level;
1935 	if (btrfs_test_opt(fs_info, SPACE_CACHE))
1936 		super->cache_generation = root_item->generation;
1937 	else if (test_bit(BTRFS_FS_CLEANUP_SPACE_CACHE_V1, &fs_info->flags))
1938 		super->cache_generation = 0;
1939 	if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1940 		super->uuid_tree_generation = root_item->generation;
1941 }
1942 
1943 int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1944 {
1945 	struct btrfs_transaction *trans;
1946 	int ret = 0;
1947 
1948 	spin_lock(&info->trans_lock);
1949 	trans = info->running_transaction;
1950 	if (trans)
1951 		ret = (trans->state >= TRANS_STATE_COMMIT_START);
1952 	spin_unlock(&info->trans_lock);
1953 	return ret;
1954 }
1955 
1956 int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1957 {
1958 	struct btrfs_transaction *trans;
1959 	int ret = 0;
1960 
1961 	spin_lock(&info->trans_lock);
1962 	trans = info->running_transaction;
1963 	if (trans)
1964 		ret = is_transaction_blocked(trans);
1965 	spin_unlock(&info->trans_lock);
1966 	return ret;
1967 }
1968 
1969 void btrfs_commit_transaction_async(struct btrfs_trans_handle *trans)
1970 {
1971 	struct btrfs_fs_info *fs_info = trans->fs_info;
1972 	struct btrfs_transaction *cur_trans;
1973 
1974 	/* Kick the transaction kthread. */
1975 	set_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
1976 	wake_up_process(fs_info->transaction_kthread);
1977 
1978 	/* take transaction reference */
1979 	cur_trans = trans->transaction;
1980 	refcount_inc(&cur_trans->use_count);
1981 
1982 	btrfs_end_transaction(trans);
1983 
1984 	/*
1985 	 * Wait for the current transaction commit to start and block
1986 	 * subsequent transaction joins
1987 	 */
1988 	btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
1989 	wait_event(fs_info->transaction_blocked_wait,
1990 		   cur_trans->state >= TRANS_STATE_COMMIT_START ||
1991 		   TRANS_ABORTED(cur_trans));
1992 	btrfs_put_transaction(cur_trans);
1993 }
1994 
1995 static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
1996 {
1997 	struct btrfs_fs_info *fs_info = trans->fs_info;
1998 	struct btrfs_transaction *cur_trans = trans->transaction;
1999 
2000 	WARN_ON(refcount_read(&trans->use_count) > 1);
2001 
2002 	btrfs_abort_transaction(trans, err);
2003 
2004 	spin_lock(&fs_info->trans_lock);
2005 
2006 	/*
2007 	 * If the transaction is removed from the list, it means this
2008 	 * transaction has been committed successfully, so it is impossible
2009 	 * to call the cleanup function.
2010 	 */
2011 	BUG_ON(list_empty(&cur_trans->list));
2012 
2013 	if (cur_trans == fs_info->running_transaction) {
2014 		cur_trans->state = TRANS_STATE_COMMIT_DOING;
2015 		spin_unlock(&fs_info->trans_lock);
2016 
2017 		/*
2018 		 * The thread has already released the lockdep map as reader
2019 		 * already in btrfs_commit_transaction().
2020 		 */
2021 		btrfs_might_wait_for_event(fs_info, btrfs_trans_num_writers);
2022 		wait_event(cur_trans->writer_wait,
2023 			   atomic_read(&cur_trans->num_writers) == 1);
2024 
2025 		spin_lock(&fs_info->trans_lock);
2026 	}
2027 
2028 	/*
2029 	 * Now that we know no one else is still using the transaction we can
2030 	 * remove the transaction from the list of transactions. This avoids
2031 	 * the transaction kthread from cleaning up the transaction while some
2032 	 * other task is still using it, which could result in a use-after-free
2033 	 * on things like log trees, as it forces the transaction kthread to
2034 	 * wait for this transaction to be cleaned up by us.
2035 	 */
2036 	list_del_init(&cur_trans->list);
2037 
2038 	spin_unlock(&fs_info->trans_lock);
2039 
2040 	btrfs_cleanup_one_transaction(trans->transaction, fs_info);
2041 
2042 	spin_lock(&fs_info->trans_lock);
2043 	if (cur_trans == fs_info->running_transaction)
2044 		fs_info->running_transaction = NULL;
2045 	spin_unlock(&fs_info->trans_lock);
2046 
2047 	if (trans->type & __TRANS_FREEZABLE)
2048 		sb_end_intwrite(fs_info->sb);
2049 	btrfs_put_transaction(cur_trans);
2050 	btrfs_put_transaction(cur_trans);
2051 
2052 	trace_btrfs_transaction_commit(fs_info);
2053 
2054 	if (current->journal_info == trans)
2055 		current->journal_info = NULL;
2056 
2057 	/*
2058 	 * If relocation is running, we can't cancel scrub because that will
2059 	 * result in a deadlock. Before relocating a block group, relocation
2060 	 * pauses scrub, then starts and commits a transaction before unpausing
2061 	 * scrub. If the transaction commit is being done by the relocation
2062 	 * task or triggered by another task and the relocation task is waiting
2063 	 * for the commit, and we end up here due to an error in the commit
2064 	 * path, then calling btrfs_scrub_cancel() will deadlock, as we are
2065 	 * asking for scrub to stop while having it asked to be paused higher
2066 	 * above in relocation code.
2067 	 */
2068 	if (!test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
2069 		btrfs_scrub_cancel(fs_info);
2070 
2071 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
2072 }
2073 
2074 /*
2075  * Release reserved delayed ref space of all pending block groups of the
2076  * transaction and remove them from the list
2077  */
2078 static void btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle *trans)
2079 {
2080        struct btrfs_fs_info *fs_info = trans->fs_info;
2081        struct btrfs_block_group *block_group, *tmp;
2082 
2083        list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
2084                btrfs_delayed_refs_rsv_release(fs_info, 1);
2085                list_del_init(&block_group->bg_list);
2086        }
2087 }
2088 
2089 static inline int btrfs_start_delalloc_flush(struct btrfs_fs_info *fs_info)
2090 {
2091 	/*
2092 	 * We use try_to_writeback_inodes_sb() here because if we used
2093 	 * btrfs_start_delalloc_roots we would deadlock with fs freeze.
2094 	 * Currently are holding the fs freeze lock, if we do an async flush
2095 	 * we'll do btrfs_join_transaction() and deadlock because we need to
2096 	 * wait for the fs freeze lock.  Using the direct flushing we benefit
2097 	 * from already being in a transaction and our join_transaction doesn't
2098 	 * have to re-take the fs freeze lock.
2099 	 *
2100 	 * Note that try_to_writeback_inodes_sb() will only trigger writeback
2101 	 * if it can read lock sb->s_umount. It will always be able to lock it,
2102 	 * except when the filesystem is being unmounted or being frozen, but in
2103 	 * those cases sync_filesystem() is called, which results in calling
2104 	 * writeback_inodes_sb() while holding a write lock on sb->s_umount.
2105 	 * Note that we don't call writeback_inodes_sb() directly, because it
2106 	 * will emit a warning if sb->s_umount is not locked.
2107 	 */
2108 	if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2109 		try_to_writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
2110 	return 0;
2111 }
2112 
2113 static inline void btrfs_wait_delalloc_flush(struct btrfs_fs_info *fs_info)
2114 {
2115 	if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2116 		btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
2117 }
2118 
2119 /*
2120  * Add a pending snapshot associated with the given transaction handle to the
2121  * respective handle. This must be called after the transaction commit started
2122  * and while holding fs_info->trans_lock.
2123  * This serves to guarantee a caller of btrfs_commit_transaction() that it can
2124  * safely free the pending snapshot pointer in case btrfs_commit_transaction()
2125  * returns an error.
2126  */
2127 static void add_pending_snapshot(struct btrfs_trans_handle *trans)
2128 {
2129 	struct btrfs_transaction *cur_trans = trans->transaction;
2130 
2131 	if (!trans->pending_snapshot)
2132 		return;
2133 
2134 	lockdep_assert_held(&trans->fs_info->trans_lock);
2135 	ASSERT(cur_trans->state >= TRANS_STATE_COMMIT_PREP);
2136 
2137 	list_add(&trans->pending_snapshot->list, &cur_trans->pending_snapshots);
2138 }
2139 
2140 static void update_commit_stats(struct btrfs_fs_info *fs_info, ktime_t interval)
2141 {
2142 	fs_info->commit_stats.commit_count++;
2143 	fs_info->commit_stats.last_commit_dur = interval;
2144 	fs_info->commit_stats.max_commit_dur =
2145 			max_t(u64, fs_info->commit_stats.max_commit_dur, interval);
2146 	fs_info->commit_stats.total_commit_dur += interval;
2147 }
2148 
2149 int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
2150 {
2151 	struct btrfs_fs_info *fs_info = trans->fs_info;
2152 	struct btrfs_transaction *cur_trans = trans->transaction;
2153 	struct btrfs_transaction *prev_trans = NULL;
2154 	int ret;
2155 	ktime_t start_time;
2156 	ktime_t interval;
2157 
2158 	ASSERT(refcount_read(&trans->use_count) == 1);
2159 	btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2160 
2161 	clear_bit(BTRFS_FS_NEED_TRANS_COMMIT, &fs_info->flags);
2162 
2163 	/* Stop the commit early if ->aborted is set */
2164 	if (TRANS_ABORTED(cur_trans)) {
2165 		ret = cur_trans->aborted;
2166 		goto lockdep_trans_commit_start_release;
2167 	}
2168 
2169 	btrfs_trans_release_metadata(trans);
2170 	trans->block_rsv = NULL;
2171 
2172 	/*
2173 	 * We only want one transaction commit doing the flushing so we do not
2174 	 * waste a bunch of time on lock contention on the extent root node.
2175 	 */
2176 	if (!test_and_set_bit(BTRFS_DELAYED_REFS_FLUSHING,
2177 			      &cur_trans->delayed_refs.flags)) {
2178 		/*
2179 		 * Make a pass through all the delayed refs we have so far.
2180 		 * Any running threads may add more while we are here.
2181 		 */
2182 		ret = btrfs_run_delayed_refs(trans, 0);
2183 		if (ret)
2184 			goto lockdep_trans_commit_start_release;
2185 	}
2186 
2187 	btrfs_create_pending_block_groups(trans);
2188 
2189 	if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
2190 		int run_it = 0;
2191 
2192 		/* this mutex is also taken before trying to set
2193 		 * block groups readonly.  We need to make sure
2194 		 * that nobody has set a block group readonly
2195 		 * after a extents from that block group have been
2196 		 * allocated for cache files.  btrfs_set_block_group_ro
2197 		 * will wait for the transaction to commit if it
2198 		 * finds BTRFS_TRANS_DIRTY_BG_RUN set.
2199 		 *
2200 		 * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
2201 		 * only one process starts all the block group IO.  It wouldn't
2202 		 * hurt to have more than one go through, but there's no
2203 		 * real advantage to it either.
2204 		 */
2205 		mutex_lock(&fs_info->ro_block_group_mutex);
2206 		if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
2207 				      &cur_trans->flags))
2208 			run_it = 1;
2209 		mutex_unlock(&fs_info->ro_block_group_mutex);
2210 
2211 		if (run_it) {
2212 			ret = btrfs_start_dirty_block_groups(trans);
2213 			if (ret)
2214 				goto lockdep_trans_commit_start_release;
2215 		}
2216 	}
2217 
2218 	spin_lock(&fs_info->trans_lock);
2219 	if (cur_trans->state >= TRANS_STATE_COMMIT_PREP) {
2220 		enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2221 
2222 		add_pending_snapshot(trans);
2223 
2224 		spin_unlock(&fs_info->trans_lock);
2225 		refcount_inc(&cur_trans->use_count);
2226 
2227 		if (trans->in_fsync)
2228 			want_state = TRANS_STATE_SUPER_COMMITTED;
2229 
2230 		btrfs_trans_state_lockdep_release(fs_info,
2231 						  BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2232 		ret = btrfs_end_transaction(trans);
2233 		wait_for_commit(cur_trans, want_state);
2234 
2235 		if (TRANS_ABORTED(cur_trans))
2236 			ret = cur_trans->aborted;
2237 
2238 		btrfs_put_transaction(cur_trans);
2239 
2240 		return ret;
2241 	}
2242 
2243 	cur_trans->state = TRANS_STATE_COMMIT_PREP;
2244 	wake_up(&fs_info->transaction_blocked_wait);
2245 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2246 
2247 	if (cur_trans->list.prev != &fs_info->trans_list) {
2248 		enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2249 
2250 		if (trans->in_fsync)
2251 			want_state = TRANS_STATE_SUPER_COMMITTED;
2252 
2253 		prev_trans = list_entry(cur_trans->list.prev,
2254 					struct btrfs_transaction, list);
2255 		if (prev_trans->state < want_state) {
2256 			refcount_inc(&prev_trans->use_count);
2257 			spin_unlock(&fs_info->trans_lock);
2258 
2259 			wait_for_commit(prev_trans, want_state);
2260 
2261 			ret = READ_ONCE(prev_trans->aborted);
2262 
2263 			btrfs_put_transaction(prev_trans);
2264 			if (ret)
2265 				goto lockdep_release;
2266 			spin_lock(&fs_info->trans_lock);
2267 		}
2268 	} else {
2269 		/*
2270 		 * The previous transaction was aborted and was already removed
2271 		 * from the list of transactions at fs_info->trans_list. So we
2272 		 * abort to prevent writing a new superblock that reflects a
2273 		 * corrupt state (pointing to trees with unwritten nodes/leafs).
2274 		 */
2275 		if (BTRFS_FS_ERROR(fs_info)) {
2276 			spin_unlock(&fs_info->trans_lock);
2277 			ret = -EROFS;
2278 			goto lockdep_release;
2279 		}
2280 	}
2281 
2282 	cur_trans->state = TRANS_STATE_COMMIT_START;
2283 	wake_up(&fs_info->transaction_blocked_wait);
2284 	spin_unlock(&fs_info->trans_lock);
2285 
2286 	/*
2287 	 * Get the time spent on the work done by the commit thread and not
2288 	 * the time spent waiting on a previous commit
2289 	 */
2290 	start_time = ktime_get_ns();
2291 
2292 	extwriter_counter_dec(cur_trans, trans->type);
2293 
2294 	ret = btrfs_start_delalloc_flush(fs_info);
2295 	if (ret)
2296 		goto lockdep_release;
2297 
2298 	ret = btrfs_run_delayed_items(trans);
2299 	if (ret)
2300 		goto lockdep_release;
2301 
2302 	/*
2303 	 * The thread has started/joined the transaction thus it holds the
2304 	 * lockdep map as a reader. It has to release it before acquiring the
2305 	 * lockdep map as a writer.
2306 	 */
2307 	btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2308 	btrfs_might_wait_for_event(fs_info, btrfs_trans_num_extwriters);
2309 	wait_event(cur_trans->writer_wait,
2310 		   extwriter_counter_read(cur_trans) == 0);
2311 
2312 	/* some pending stuffs might be added after the previous flush. */
2313 	ret = btrfs_run_delayed_items(trans);
2314 	if (ret) {
2315 		btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2316 		goto cleanup_transaction;
2317 	}
2318 
2319 	btrfs_wait_delalloc_flush(fs_info);
2320 
2321 	/*
2322 	 * Wait for all ordered extents started by a fast fsync that joined this
2323 	 * transaction. Otherwise if this transaction commits before the ordered
2324 	 * extents complete we lose logged data after a power failure.
2325 	 */
2326 	btrfs_might_wait_for_event(fs_info, btrfs_trans_pending_ordered);
2327 	wait_event(cur_trans->pending_wait,
2328 		   atomic_read(&cur_trans->pending_ordered) == 0);
2329 
2330 	btrfs_scrub_pause(fs_info);
2331 	/*
2332 	 * Ok now we need to make sure to block out any other joins while we
2333 	 * commit the transaction.  We could have started a join before setting
2334 	 * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2335 	 */
2336 	spin_lock(&fs_info->trans_lock);
2337 	add_pending_snapshot(trans);
2338 	cur_trans->state = TRANS_STATE_COMMIT_DOING;
2339 	spin_unlock(&fs_info->trans_lock);
2340 
2341 	/*
2342 	 * The thread has started/joined the transaction thus it holds the
2343 	 * lockdep map as a reader. It has to release it before acquiring the
2344 	 * lockdep map as a writer.
2345 	 */
2346 	btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2347 	btrfs_might_wait_for_event(fs_info, btrfs_trans_num_writers);
2348 	wait_event(cur_trans->writer_wait,
2349 		   atomic_read(&cur_trans->num_writers) == 1);
2350 
2351 	/*
2352 	 * Make lockdep happy by acquiring the state locks after
2353 	 * btrfs_trans_num_writers is released. If we acquired the state locks
2354 	 * before releasing the btrfs_trans_num_writers lock then lockdep would
2355 	 * complain because we did not follow the reverse order unlocking rule.
2356 	 */
2357 	btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2358 	btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2359 	btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2360 
2361 	/*
2362 	 * We've started the commit, clear the flag in case we were triggered to
2363 	 * do an async commit but somebody else started before the transaction
2364 	 * kthread could do the work.
2365 	 */
2366 	clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
2367 
2368 	if (TRANS_ABORTED(cur_trans)) {
2369 		ret = cur_trans->aborted;
2370 		btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2371 		goto scrub_continue;
2372 	}
2373 	/*
2374 	 * the reloc mutex makes sure that we stop
2375 	 * the balancing code from coming in and moving
2376 	 * extents around in the middle of the commit
2377 	 */
2378 	mutex_lock(&fs_info->reloc_mutex);
2379 
2380 	/*
2381 	 * We needn't worry about the delayed items because we will
2382 	 * deal with them in create_pending_snapshot(), which is the
2383 	 * core function of the snapshot creation.
2384 	 */
2385 	ret = create_pending_snapshots(trans);
2386 	if (ret)
2387 		goto unlock_reloc;
2388 
2389 	/*
2390 	 * We insert the dir indexes of the snapshots and update the inode
2391 	 * of the snapshots' parents after the snapshot creation, so there
2392 	 * are some delayed items which are not dealt with. Now deal with
2393 	 * them.
2394 	 *
2395 	 * We needn't worry that this operation will corrupt the snapshots,
2396 	 * because all the tree which are snapshoted will be forced to COW
2397 	 * the nodes and leaves.
2398 	 */
2399 	ret = btrfs_run_delayed_items(trans);
2400 	if (ret)
2401 		goto unlock_reloc;
2402 
2403 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2404 	if (ret)
2405 		goto unlock_reloc;
2406 
2407 	/*
2408 	 * make sure none of the code above managed to slip in a
2409 	 * delayed item
2410 	 */
2411 	btrfs_assert_delayed_root_empty(fs_info);
2412 
2413 	WARN_ON(cur_trans != trans->transaction);
2414 
2415 	ret = commit_fs_roots(trans);
2416 	if (ret)
2417 		goto unlock_reloc;
2418 
2419 	/* commit_fs_roots gets rid of all the tree log roots, it is now
2420 	 * safe to free the root of tree log roots
2421 	 */
2422 	btrfs_free_log_root_tree(trans, fs_info);
2423 
2424 	/*
2425 	 * Since fs roots are all committed, we can get a quite accurate
2426 	 * new_roots. So let's do quota accounting.
2427 	 */
2428 	ret = btrfs_qgroup_account_extents(trans);
2429 	if (ret < 0)
2430 		goto unlock_reloc;
2431 
2432 	ret = commit_cowonly_roots(trans);
2433 	if (ret)
2434 		goto unlock_reloc;
2435 
2436 	/*
2437 	 * The tasks which save the space cache and inode cache may also
2438 	 * update ->aborted, check it.
2439 	 */
2440 	if (TRANS_ABORTED(cur_trans)) {
2441 		ret = cur_trans->aborted;
2442 		goto unlock_reloc;
2443 	}
2444 
2445 	cur_trans = fs_info->running_transaction;
2446 
2447 	btrfs_set_root_node(&fs_info->tree_root->root_item,
2448 			    fs_info->tree_root->node);
2449 	list_add_tail(&fs_info->tree_root->dirty_list,
2450 		      &cur_trans->switch_commits);
2451 
2452 	btrfs_set_root_node(&fs_info->chunk_root->root_item,
2453 			    fs_info->chunk_root->node);
2454 	list_add_tail(&fs_info->chunk_root->dirty_list,
2455 		      &cur_trans->switch_commits);
2456 
2457 	if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
2458 		btrfs_set_root_node(&fs_info->block_group_root->root_item,
2459 				    fs_info->block_group_root->node);
2460 		list_add_tail(&fs_info->block_group_root->dirty_list,
2461 			      &cur_trans->switch_commits);
2462 	}
2463 
2464 	switch_commit_roots(trans);
2465 
2466 	ASSERT(list_empty(&cur_trans->dirty_bgs));
2467 	ASSERT(list_empty(&cur_trans->io_bgs));
2468 	update_super_roots(fs_info);
2469 
2470 	btrfs_set_super_log_root(fs_info->super_copy, 0);
2471 	btrfs_set_super_log_root_level(fs_info->super_copy, 0);
2472 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
2473 	       sizeof(*fs_info->super_copy));
2474 
2475 	btrfs_commit_device_sizes(cur_trans);
2476 
2477 	clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2478 	clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2479 
2480 	btrfs_trans_release_chunk_metadata(trans);
2481 
2482 	/*
2483 	 * Before changing the transaction state to TRANS_STATE_UNBLOCKED and
2484 	 * setting fs_info->running_transaction to NULL, lock tree_log_mutex to
2485 	 * make sure that before we commit our superblock, no other task can
2486 	 * start a new transaction and commit a log tree before we commit our
2487 	 * superblock. Anyone trying to commit a log tree locks this mutex before
2488 	 * writing its superblock.
2489 	 */
2490 	mutex_lock(&fs_info->tree_log_mutex);
2491 
2492 	spin_lock(&fs_info->trans_lock);
2493 	cur_trans->state = TRANS_STATE_UNBLOCKED;
2494 	fs_info->running_transaction = NULL;
2495 	spin_unlock(&fs_info->trans_lock);
2496 	mutex_unlock(&fs_info->reloc_mutex);
2497 
2498 	wake_up(&fs_info->transaction_wait);
2499 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2500 
2501 	/* If we have features changed, wake up the cleaner to update sysfs. */
2502 	if (test_bit(BTRFS_FS_FEATURE_CHANGED, &fs_info->flags) &&
2503 	    fs_info->cleaner_kthread)
2504 		wake_up_process(fs_info->cleaner_kthread);
2505 
2506 	ret = btrfs_write_and_wait_transaction(trans);
2507 	if (ret) {
2508 		btrfs_handle_fs_error(fs_info, ret,
2509 				      "Error while writing out transaction");
2510 		mutex_unlock(&fs_info->tree_log_mutex);
2511 		goto scrub_continue;
2512 	}
2513 
2514 	ret = write_all_supers(fs_info, 0);
2515 	/*
2516 	 * the super is written, we can safely allow the tree-loggers
2517 	 * to go about their business
2518 	 */
2519 	mutex_unlock(&fs_info->tree_log_mutex);
2520 	if (ret)
2521 		goto scrub_continue;
2522 
2523 	/*
2524 	 * We needn't acquire the lock here because there is no other task
2525 	 * which can change it.
2526 	 */
2527 	cur_trans->state = TRANS_STATE_SUPER_COMMITTED;
2528 	wake_up(&cur_trans->commit_wait);
2529 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2530 
2531 	btrfs_finish_extent_commit(trans);
2532 
2533 	if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
2534 		btrfs_clear_space_info_full(fs_info);
2535 
2536 	fs_info->last_trans_committed = cur_trans->transid;
2537 	/*
2538 	 * We needn't acquire the lock here because there is no other task
2539 	 * which can change it.
2540 	 */
2541 	cur_trans->state = TRANS_STATE_COMPLETED;
2542 	wake_up(&cur_trans->commit_wait);
2543 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2544 
2545 	spin_lock(&fs_info->trans_lock);
2546 	list_del_init(&cur_trans->list);
2547 	spin_unlock(&fs_info->trans_lock);
2548 
2549 	btrfs_put_transaction(cur_trans);
2550 	btrfs_put_transaction(cur_trans);
2551 
2552 	if (trans->type & __TRANS_FREEZABLE)
2553 		sb_end_intwrite(fs_info->sb);
2554 
2555 	trace_btrfs_transaction_commit(fs_info);
2556 
2557 	interval = ktime_get_ns() - start_time;
2558 
2559 	btrfs_scrub_continue(fs_info);
2560 
2561 	if (current->journal_info == trans)
2562 		current->journal_info = NULL;
2563 
2564 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
2565 
2566 	update_commit_stats(fs_info, interval);
2567 
2568 	return ret;
2569 
2570 unlock_reloc:
2571 	mutex_unlock(&fs_info->reloc_mutex);
2572 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2573 scrub_continue:
2574 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2575 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2576 	btrfs_scrub_continue(fs_info);
2577 cleanup_transaction:
2578 	btrfs_trans_release_metadata(trans);
2579 	btrfs_cleanup_pending_block_groups(trans);
2580 	btrfs_trans_release_chunk_metadata(trans);
2581 	trans->block_rsv = NULL;
2582 	btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
2583 	if (current->journal_info == trans)
2584 		current->journal_info = NULL;
2585 	cleanup_transaction(trans, ret);
2586 
2587 	return ret;
2588 
2589 lockdep_release:
2590 	btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2591 	btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2592 	goto cleanup_transaction;
2593 
2594 lockdep_trans_commit_start_release:
2595 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2596 	btrfs_end_transaction(trans);
2597 	return ret;
2598 }
2599 
2600 /*
2601  * return < 0 if error
2602  * 0 if there are no more dead_roots at the time of call
2603  * 1 there are more to be processed, call me again
2604  *
2605  * The return value indicates there are certainly more snapshots to delete, but
2606  * if there comes a new one during processing, it may return 0. We don't mind,
2607  * because btrfs_commit_super will poke cleaner thread and it will process it a
2608  * few seconds later.
2609  */
2610 int btrfs_clean_one_deleted_snapshot(struct btrfs_fs_info *fs_info)
2611 {
2612 	struct btrfs_root *root;
2613 	int ret;
2614 
2615 	spin_lock(&fs_info->trans_lock);
2616 	if (list_empty(&fs_info->dead_roots)) {
2617 		spin_unlock(&fs_info->trans_lock);
2618 		return 0;
2619 	}
2620 	root = list_first_entry(&fs_info->dead_roots,
2621 			struct btrfs_root, root_list);
2622 	list_del_init(&root->root_list);
2623 	spin_unlock(&fs_info->trans_lock);
2624 
2625 	btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
2626 
2627 	btrfs_kill_all_delayed_nodes(root);
2628 
2629 	if (btrfs_header_backref_rev(root->node) <
2630 			BTRFS_MIXED_BACKREF_REV)
2631 		ret = btrfs_drop_snapshot(root, 0, 0);
2632 	else
2633 		ret = btrfs_drop_snapshot(root, 1, 0);
2634 
2635 	btrfs_put_root(root);
2636 	return (ret < 0) ? 0 : 1;
2637 }
2638 
2639 /*
2640  * We only mark the transaction aborted and then set the file system read-only.
2641  * This will prevent new transactions from starting or trying to join this
2642  * one.
2643  *
2644  * This means that error recovery at the call site is limited to freeing
2645  * any local memory allocations and passing the error code up without
2646  * further cleanup. The transaction should complete as it normally would
2647  * in the call path but will return -EIO.
2648  *
2649  * We'll complete the cleanup in btrfs_end_transaction and
2650  * btrfs_commit_transaction.
2651  */
2652 void __cold __btrfs_abort_transaction(struct btrfs_trans_handle *trans,
2653 				      const char *function,
2654 				      unsigned int line, int errno, bool first_hit)
2655 {
2656 	struct btrfs_fs_info *fs_info = trans->fs_info;
2657 
2658 	WRITE_ONCE(trans->aborted, errno);
2659 	WRITE_ONCE(trans->transaction->aborted, errno);
2660 	if (first_hit && errno == -ENOSPC)
2661 		btrfs_dump_space_info_for_trans_abort(fs_info);
2662 	/* Wake up anybody who may be waiting on this transaction */
2663 	wake_up(&fs_info->transaction_wait);
2664 	wake_up(&fs_info->transaction_blocked_wait);
2665 	__btrfs_handle_fs_error(fs_info, function, line, errno, NULL);
2666 }
2667 
2668 int __init btrfs_transaction_init(void)
2669 {
2670 	btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
2671 			sizeof(struct btrfs_trans_handle), 0,
2672 			SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
2673 	if (!btrfs_trans_handle_cachep)
2674 		return -ENOMEM;
2675 	return 0;
2676 }
2677 
2678 void __cold btrfs_transaction_exit(void)
2679 {
2680 	kmem_cache_destroy(btrfs_trans_handle_cachep);
2681 }
2682