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