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