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