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