xref: /linux/fs/ext4/fast_commit.c (revision 97211e479963e7ad808bd3e1f8e08969037c8adc)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 /*
4  * fs/ext4/fast_commit.c
5  *
6  * Written by Harshad Shirwadkar <harshadshirwadkar@gmail.com>
7  *
8  * Ext4 fast commits routines.
9  */
10 #include "ext4.h"
11 #include "ext4_jbd2.h"
12 #include "ext4_extents.h"
13 #include "mballoc.h"
14 
15 #include <linux/lockdep.h>
16 #include <linux/wait_bit.h>
17 #include <kunit/static_stub.h>
18 /*
19  * Ext4 Fast Commits
20  * -----------------
21  *
22  * Ext4 fast commits implement fine grained journalling for Ext4.
23  *
24  * Fast commits are organized as a log of tag-length-value (TLV) structs. (See
25  * struct ext4_fc_tl). Each TLV contains some delta that is replayed TLV by
26  * TLV during the recovery phase. For the scenarios for which we currently
27  * don't have replay code, fast commit falls back to full commits.
28  * Fast commits record delta in one of the following three categories.
29  *
30  * (A) Directory entry updates:
31  *
32  * - EXT4_FC_TAG_UNLINK		- records directory entry unlink
33  * - EXT4_FC_TAG_LINK		- records directory entry link
34  * - EXT4_FC_TAG_CREAT		- records inode and directory entry creation
35  *
36  * (B) File specific data range updates:
37  *
38  * - EXT4_FC_TAG_ADD_RANGE	- records addition of new blocks to an inode
39  * - EXT4_FC_TAG_DEL_RANGE	- records deletion of blocks from an inode
40  *
41  * (C) Inode metadata (mtime / ctime etc):
42  *
43  * - EXT4_FC_TAG_INODE		- record the inode that should be replayed
44  *				  during recovery. Note that iblocks field is
45  *				  not replayed and instead derived during
46  *				  replay.
47  * Commit Operation
48  * ----------------
49  * With fast commits, we maintain all the directory entry operations in the
50  * order in which they are issued in an in-memory queue. This queue is flushed
51  * to disk during the commit operation. We also maintain a list of inodes
52  * that need to be committed during a fast commit in another in memory queue of
53  * inodes. During the commit operation, we commit in the following order:
54  *
55  * [1] Prepare all the inodes to write out their data by setting
56  *     "EXT4_STATE_FC_FLUSHING_DATA". This ensures that inode cannot be
57  *     deleted while it is being flushed.
58  * [2] Flush data buffers to disk and clear "EXT4_STATE_FC_FLUSHING_DATA"
59  *     state.
60  * [3] Lock the journal by calling jbd2_journal_lock_updates(). This ensures
61  *     that all the existing handles finish and no new handles can start.
62  * [4] Mark all the fast commit eligible inodes as undergoing fast commit by
63  *     setting "EXT4_STATE_FC_COMMITTING" state, and snapshot the inode state
64  *     needed for log writing.
65  * [5] Unlock the journal by calling jbd2_journal_unlock_updates(). This allows
66  *     starting of new handles. Updates to inodes being fast committed are
67  *     tracked for requeue rather than blocking.
68  * [6] Commit all the directory entry updates in the fast commit space.
69  * [7] Commit all the changed inodes in the fast commit space.
70  * [8] Write tail tag (this tag ensures the atomicity, please read the following
71  *     section for more details).
72  * [9] Clear "EXT4_STATE_FC_COMMITTING" and wake up waiters in
73  *     ext4_fc_cleanup().
74  *
75  * All the inode updates must be enclosed within jbd2_journal_start()
76  * and jbd2_journal_stop() similar to JBD2 journaling.
77  *
78  * Fast Commit Ineligibility
79  * -------------------------
80  *
81  * Not all operations are supported by fast commits today (e.g extended
82  * attributes). Fast commit ineligibility is marked by calling
83  * ext4_fc_mark_ineligible(): This makes next fast commit operation to fall back
84  * to full commit.
85  *
86  * Atomicity of commits
87  * --------------------
88  * In order to guarantee atomicity during the commit operation, fast commit
89  * uses "EXT4_FC_TAG_TAIL" tag that marks a fast commit as complete. Tail
90  * tag contains CRC of the contents and TID of the transaction after which
91  * this fast commit should be applied. Recovery code replays fast commit
92  * logs only if there's at least 1 valid tail present. For every fast commit
93  * operation, there is 1 tail. This means, we may end up with multiple tails
94  * in the fast commit space. Here's an example:
95  *
96  * - Create a new file A and remove existing file B
97  * - fsync()
98  * - Append contents to file A
99  * - Truncate file A
100  * - fsync()
101  *
102  * The fast commit space at the end of above operations would look like this:
103  *      [HEAD] [CREAT A] [UNLINK B] [TAIL] [ADD_RANGE A] [DEL_RANGE A] [TAIL]
104  *             |<---  Fast Commit 1   --->|<---      Fast Commit 2     ---->|
105  *
106  * Replay code should thus check for all the valid tails in the FC area.
107  *
108  * Fast Commit Replay Idempotence
109  * ------------------------------
110  *
111  * Fast commits tags are idempotent in nature provided the recovery code follows
112  * certain rules. The guiding principle that the commit path follows while
113  * committing is that it stores the result of a particular operation instead of
114  * storing the procedure.
115  *
116  * Let's consider this rename operation: 'mv /a /b'. Let's assume dirent '/a'
117  * was associated with inode 10. During fast commit, instead of storing this
118  * operation as a procedure "rename a to b", we store the resulting file system
119  * state as a "series" of outcomes:
120  *
121  * - Link dirent b to inode 10
122  * - Unlink dirent a
123  * - Inode <10> with valid refcount
124  *
125  * Now when recovery code runs, it needs "enforce" this state on the file
126  * system. This is what guarantees idempotence of fast commit replay.
127  *
128  * Let's take an example of a procedure that is not idempotent and see how fast
129  * commits make it idempotent. Consider following sequence of operations:
130  *
131  *     rm A;    mv B A;    read A
132  *  (x)     (y)        (z)
133  *
134  * (x), (y) and (z) are the points at which we can crash. If we store this
135  * sequence of operations as is then the replay is not idempotent. Let's say
136  * while in replay, we crash at (z). During the second replay, file A (which was
137  * actually created as a result of "mv B A" operation) would get deleted. Thus,
138  * file named A would be absent when we try to read A. So, this sequence of
139  * operations is not idempotent. However, as mentioned above, instead of storing
140  * the procedure fast commits store the outcome of each procedure. Thus the fast
141  * commit log for above procedure would be as follows:
142  *
143  * (Let's assume dirent A was linked to inode 10 and dirent B was linked to
144  * inode 11 before the replay)
145  *
146  *    [Unlink A]   [Link A to inode 11]   [Unlink B]   [Inode 11]
147  * (w)          (x)                    (y)          (z)
148  *
149  * If we crash at (z), we will have file A linked to inode 11. During the second
150  * replay, we will remove file A (inode 11). But we will create it back and make
151  * it point to inode 11. We won't find B, so we'll just skip that step. At this
152  * point, the refcount for inode 11 is not reliable, but that gets fixed by the
153  * replay of last inode 11 tag. Crashes at points (w), (x) and (y) get handled
154  * similarly. Thus, by converting a non-idempotent procedure into a series of
155  * idempotent outcomes, fast commits ensured idempotence during the replay.
156  *
157  * Locking
158  * -------
159  * sbi->s_fc_lock protects the fast commit inodes queue and the fast commit
160  * dentry queue. ei->i_fc_lock protects the fast commit related info in a given
161  * inode. Most of the code avoids acquiring both the locks, but if one must do
162  * that then sbi->s_fc_lock must be acquired before ei->i_fc_lock.
163  *
164  * TODOs
165  * -----
166  *
167  * 0) Fast commit replay path hardening: Fast commit replay code should use
168  *    journal handles to make sure all the updates it does during the replay
169  *    path are atomic. With that if we crash during fast commit replay, after
170  *    trying to do recovery again, we will find a file system where fast commit
171  *    area is invalid (because new full commit would be found). In order to deal
172  *    with that, fast commit replay code should ensure that the "FC_REPLAY"
173  *    superblock state is persisted before starting the replay, so that after
174  *    the crash, fast commit recovery code can look at that flag and perform
175  *    fast commit recovery even if that area is invalidated by later full
176  *    commits.
177  *
178  * 1) Handle more ineligible cases.
179  *
180  * 2) Change ext4_fc_commit() to lookup logical to physical mapping using extent
181  *    status tree. This would get rid of the need to call ext4_fc_track_inode()
182  *    before acquiring i_data_sem. To do that we would need to ensure that
183  *    modified extents from the extent status tree are not evicted from memory.
184  */
185 
186 #include <trace/events/ext4.h>
187 static struct kmem_cache *ext4_fc_dentry_cachep;
188 static struct kmem_cache *ext4_fc_range_cachep;
189 
190 /*
191  * Avoid spending unbounded time/memory snapshotting highly fragmented files
192  * under jbd2_journal_lock_updates(). If we exceed this limit, fall back to
193  * full commit.
194  */
195 #define EXT4_FC_SNAPSHOT_MAX_INODES	1024
196 #define EXT4_FC_SNAPSHOT_MAX_RANGES	2048
197 
198 static inline void ext4_fc_set_snap_err(int *snap_err, int err)
199 {
200 	if (snap_err && *snap_err == EXT4_FC_SNAP_ERR_NONE)
201 		*snap_err = err;
202 }
203 
204 static void ext4_fc_free_inode_snap(struct inode *inode);
205 
206 static inline void ext4_fc_reset_inode(struct inode *inode)
207 {
208 	struct ext4_inode_info *ei = EXT4_I(inode);
209 
210 	ei->i_fc_lblk_start = 0;
211 	ei->i_fc_lblk_len = 0;
212 }
213 
214 void ext4_fc_init_inode(struct inode *inode)
215 {
216 	struct ext4_inode_info *ei = EXT4_I(inode);
217 
218 	ext4_fc_reset_inode(inode);
219 	ext4_clear_inode_state(inode, EXT4_STATE_FC_COMMITTING);
220 	ext4_clear_inode_state(inode, EXT4_STATE_FC_REQUEUE);
221 	INIT_LIST_HEAD(&ei->i_fc_list);
222 	INIT_LIST_HEAD(&ei->i_fc_dilist);
223 	ei->i_fc_snap = NULL;
224 }
225 
226 static bool ext4_fc_disabled(struct super_block *sb)
227 {
228 	return (!test_opt2(sb, JOURNAL_FAST_COMMIT) ||
229 		(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY));
230 }
231 
232 static bool ext4_fc_eligible(struct super_block *sb)
233 {
234 	return !ext4_fc_disabled(sb) &&
235 		!(ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE));
236 }
237 
238 /*
239  * Wait for an inode fast-commit state bit to clear while dropping the
240  * fast-commit lock around schedule().
241  */
242 static void ext4_fc_wait_inode_state(struct inode *inode, int bit,
243 				     int *alloc_ctx)
244 {
245 	wait_queue_head_t *wq;
246 	unsigned long *wait_word = ext4_inode_state_wait_word(inode);
247 	int wait_bit = ext4_inode_state_wait_bit(bit);
248 
249 	while (ext4_test_inode_state(inode, bit)) {
250 		DEFINE_WAIT_BIT(wait, wait_word, wait_bit);
251 
252 		wq = bit_waitqueue(wait_word, wait_bit);
253 		prepare_to_wait(wq, &wait.wq_entry, TASK_UNINTERRUPTIBLE);
254 		if (ext4_test_inode_state(inode, bit)) {
255 			ext4_fc_unlock(inode->i_sb, *alloc_ctx);
256 			schedule();
257 			*alloc_ctx = ext4_fc_lock(inode->i_sb);
258 		}
259 		finish_wait(wq, &wait.wq_entry);
260 	}
261 }
262 
263 static inline void ext4_fc_wake_inode_state(struct inode *inode, int bit)
264 {
265 	wake_up_bit(ext4_inode_state_wait_word(inode),
266 		    ext4_inode_state_wait_bit(bit));
267 }
268 
269 static void ext4_fc_snap_stats_update_max(atomic64_t *stat, u64 value)
270 {
271 	u64 old = atomic64_read(stat);
272 
273 	while (value > old) {
274 		u64 prev = atomic64_cmpxchg(stat, old, value);
275 
276 		if (prev == old)
277 			break;
278 		old = prev;
279 	}
280 }
281 
282 /*
283  * Remove inode from fast commit list. If the inode is being committed
284  * we wait until inode commit is done.
285  */
286 void ext4_fc_del(struct inode *inode)
287 {
288 	struct ext4_inode_info *ei = EXT4_I(inode);
289 	struct ext4_fc_dentry_update *fc_dentry;
290 	int alloc_ctx;
291 
292 	if (ext4_fc_disabled(inode->i_sb))
293 		return;
294 
295 	alloc_ctx = ext4_fc_lock(inode->i_sb);
296 	if (list_empty(&ei->i_fc_list) && list_empty(&ei->i_fc_dilist)) {
297 		ext4_fc_free_inode_snap(inode);
298 		ext4_fc_unlock(inode->i_sb, alloc_ctx);
299 		return;
300 	}
301 
302 	/*
303 	 * Wait for ongoing fast commit to finish. We cannot remove the inode
304 	 * from fast commit lists while it is being committed. If we wake from
305 	 * FC_FLUSHING_DATA, re-check FC_COMMITTING before deleting because the
306 	 * commit thread sets FC_COMMITTING only after clearing FLUSHING_DATA.
307 	 */
308 	for (;;) {
309 		ext4_fc_wait_inode_state(inode, EXT4_STATE_FC_COMMITTING,
310 					 &alloc_ctx);
311 
312 		if (!ext4_test_inode_state(inode, EXT4_STATE_FC_FLUSHING_DATA))
313 			break;
314 
315 		ext4_fc_wait_inode_state(inode, EXT4_STATE_FC_FLUSHING_DATA,
316 					 &alloc_ctx);
317 	}
318 
319 	ext4_fc_free_inode_snap(inode);
320 	list_del_init(&ei->i_fc_list);
321 
322 	/*
323 	 * Since this inode is getting removed, let's also remove all FC dentry
324 	 * create references, since it is not needed to log it anyways.
325 	 */
326 	if (list_empty(&ei->i_fc_dilist)) {
327 		ext4_fc_unlock(inode->i_sb, alloc_ctx);
328 		return;
329 	}
330 
331 	fc_dentry = list_first_entry(&ei->i_fc_dilist,
332 				     struct ext4_fc_dentry_update,
333 				     fcd_dilist);
334 	WARN_ON(fc_dentry->fcd_op != EXT4_FC_TAG_CREAT);
335 	list_del_init(&fc_dentry->fcd_list);
336 	list_del_init(&fc_dentry->fcd_dilist);
337 
338 	WARN_ON(!list_empty(&ei->i_fc_dilist));
339 	ext4_fc_unlock(inode->i_sb, alloc_ctx);
340 
341 	release_dentry_name_snapshot(&fc_dentry->fcd_name);
342 	kmem_cache_free(ext4_fc_dentry_cachep, fc_dentry);
343 }
344 
345 /*
346  * Mark file system as fast commit ineligible, and record latest
347  * ineligible transaction tid. This means until the recorded
348  * transaction, commit operation would result in a full jbd2 commit.
349  */
350 void ext4_fc_mark_ineligible(struct super_block *sb, int reason, handle_t *handle)
351 {
352 	struct ext4_sb_info *sbi = EXT4_SB(sb);
353 	tid_t tid;
354 	bool has_transaction = true;
355 	bool is_ineligible;
356 	int alloc_ctx;
357 
358 	if (ext4_fc_disabled(sb))
359 		return;
360 
361 	if (!IS_ERR_OR_NULL(handle))
362 		tid = handle->h_transaction->t_tid;
363 	else {
364 		read_lock(&sbi->s_journal->j_state_lock);
365 		if (sbi->s_journal->j_running_transaction)
366 			tid = sbi->s_journal->j_running_transaction->t_tid;
367 		else
368 			has_transaction = false;
369 		read_unlock(&sbi->s_journal->j_state_lock);
370 	}
371 	alloc_ctx = ext4_fc_lock(sb);
372 	is_ineligible = ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE);
373 	if (has_transaction && (!is_ineligible || tid_gt(tid, sbi->s_fc_ineligible_tid)))
374 		sbi->s_fc_ineligible_tid = tid;
375 	ext4_set_mount_flag(sb, EXT4_MF_FC_INELIGIBLE);
376 	ext4_fc_unlock(sb, alloc_ctx);
377 	WARN_ON(reason >= EXT4_FC_REASON_MAX);
378 	sbi->s_fc_stats.fc_ineligible_reason_count[reason]++;
379 }
380 
381 /*
382  * Generic fast commit tracking function. If this is the first time this we are
383  * called after a full commit, we initialize fast commit fields and then call
384  * __fc_track_fn() with update = 0. If we have already been called after a full
385  * commit, we pass update = 1. Based on that, the track function can determine
386  * if it needs to track a field for the first time or if it needs to just
387  * update the previously tracked value.
388  *
389  * If enqueue is set, this function enqueues the inode in fast commit list.
390  */
391 static int ext4_fc_track_template(
392 	handle_t *handle, struct inode *inode,
393 	int (*__fc_track_fn)(handle_t *handle, struct inode *, void *, bool),
394 	void *args, int enqueue)
395 {
396 	bool update = false;
397 	struct ext4_inode_info *ei = EXT4_I(inode);
398 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
399 	tid_t tid = 0;
400 	int alloc_ctx;
401 	int ret;
402 
403 	tid = handle->h_transaction->t_tid;
404 	spin_lock(&ei->i_fc_lock);
405 	if (ext4_test_inode_state(inode, EXT4_STATE_FC_COMMITTING))
406 		ext4_set_inode_state(inode, EXT4_STATE_FC_REQUEUE);
407 	if (tid == ei->i_sync_tid) {
408 		update = true;
409 	} else {
410 		ext4_fc_reset_inode(inode);
411 		ei->i_sync_tid = tid;
412 	}
413 	ret = __fc_track_fn(handle, inode, args, update);
414 	spin_unlock(&ei->i_fc_lock);
415 	if (!enqueue)
416 		return ret;
417 
418 	alloc_ctx = ext4_fc_lock(inode->i_sb);
419 	if (list_empty(&EXT4_I(inode)->i_fc_list))
420 		list_add_tail(&EXT4_I(inode)->i_fc_list,
421 				(sbi->s_journal->j_flags & JBD2_FULL_COMMIT_ONGOING ||
422 				 sbi->s_journal->j_flags & JBD2_FAST_COMMIT_ONGOING) ?
423 				&sbi->s_fc_q[FC_Q_STAGING] :
424 				&sbi->s_fc_q[FC_Q_MAIN]);
425 	ext4_fc_unlock(inode->i_sb, alloc_ctx);
426 
427 	return ret;
428 }
429 
430 struct __track_dentry_update_args {
431 	struct dentry *dentry;
432 	int op;
433 };
434 
435 /* __track_fn for directory entry updates. Called with ei->i_fc_lock. */
436 static int __track_dentry_update(handle_t *handle, struct inode *inode,
437 				 void *arg, bool update)
438 {
439 	struct ext4_fc_dentry_update *node;
440 	struct ext4_inode_info *ei = EXT4_I(inode);
441 	struct __track_dentry_update_args *dentry_update =
442 		(struct __track_dentry_update_args *)arg;
443 	struct dentry *dentry = dentry_update->dentry;
444 	struct inode *dir = dentry->d_parent->d_inode;
445 	struct super_block *sb = inode->i_sb;
446 	struct ext4_sb_info *sbi = EXT4_SB(sb);
447 	int alloc_ctx;
448 
449 	spin_unlock(&ei->i_fc_lock);
450 
451 	if (IS_ENCRYPTED(dir)) {
452 		ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_ENCRYPTED_FILENAME,
453 					handle);
454 		spin_lock(&ei->i_fc_lock);
455 		return -EOPNOTSUPP;
456 	}
457 
458 	node = kmem_cache_alloc(ext4_fc_dentry_cachep, GFP_NOFS);
459 	if (!node) {
460 		ext4_fc_mark_ineligible(sb, EXT4_FC_REASON_NOMEM, handle);
461 		spin_lock(&ei->i_fc_lock);
462 		return -ENOMEM;
463 	}
464 
465 	node->fcd_op = dentry_update->op;
466 	node->fcd_parent = dir->i_ino;
467 	node->fcd_ino = inode->i_ino;
468 	take_dentry_name_snapshot(&node->fcd_name, dentry);
469 	INIT_LIST_HEAD(&node->fcd_dilist);
470 	INIT_LIST_HEAD(&node->fcd_list);
471 	alloc_ctx = ext4_fc_lock(sb);
472 	if (sbi->s_journal->j_flags & JBD2_FULL_COMMIT_ONGOING ||
473 		sbi->s_journal->j_flags & JBD2_FAST_COMMIT_ONGOING)
474 		list_add_tail(&node->fcd_list,
475 				&sbi->s_fc_dentry_q[FC_Q_STAGING]);
476 	else
477 		list_add_tail(&node->fcd_list, &sbi->s_fc_dentry_q[FC_Q_MAIN]);
478 
479 	/*
480 	 * This helps us keep a track of all fc_dentry updates which is part of
481 	 * this ext4 inode. So in case the inode is getting unlinked, before
482 	 * even we get a chance to fsync, we could remove all fc_dentry
483 	 * references while evicting the inode in ext4_fc_del().
484 	 * Also with this, we don't need to loop over all the inodes in
485 	 * sbi->s_fc_q to get the corresponding inode in
486 	 * ext4_fc_commit_dentry_updates().
487 	 */
488 	if (dentry_update->op == EXT4_FC_TAG_CREAT) {
489 		WARN_ON(!list_empty(&ei->i_fc_dilist));
490 		list_add_tail(&node->fcd_dilist, &ei->i_fc_dilist);
491 	}
492 	ext4_fc_unlock(sb, alloc_ctx);
493 	spin_lock(&ei->i_fc_lock);
494 
495 	return 0;
496 }
497 
498 void __ext4_fc_track_unlink(handle_t *handle,
499 		struct inode *inode, struct dentry *dentry)
500 {
501 	struct __track_dentry_update_args args;
502 	int ret;
503 
504 	args.dentry = dentry;
505 	args.op = EXT4_FC_TAG_UNLINK;
506 
507 	ret = ext4_fc_track_template(handle, inode, __track_dentry_update,
508 					(void *)&args, 0);
509 	trace_ext4_fc_track_unlink(handle, inode, dentry, ret);
510 }
511 
512 void ext4_fc_track_unlink(handle_t *handle, struct dentry *dentry)
513 {
514 	struct inode *inode = d_inode(dentry);
515 
516 	if (ext4_fc_eligible(inode->i_sb))
517 		__ext4_fc_track_unlink(handle, inode, dentry);
518 }
519 
520 void __ext4_fc_track_link(handle_t *handle,
521 	struct inode *inode, struct dentry *dentry)
522 {
523 	struct __track_dentry_update_args args;
524 	int ret;
525 
526 	args.dentry = dentry;
527 	args.op = EXT4_FC_TAG_LINK;
528 
529 	ret = ext4_fc_track_template(handle, inode, __track_dentry_update,
530 					(void *)&args, 0);
531 	trace_ext4_fc_track_link(handle, inode, dentry, ret);
532 }
533 
534 void ext4_fc_track_link(handle_t *handle, struct inode *inode,
535 			struct dentry *dentry)
536 {
537 	if (ext4_fc_eligible(inode->i_sb))
538 		__ext4_fc_track_link(handle, inode, dentry);
539 }
540 
541 void __ext4_fc_track_create(handle_t *handle, struct inode *inode,
542 			  struct dentry *dentry)
543 {
544 	struct __track_dentry_update_args args;
545 	int ret;
546 
547 	args.dentry = dentry;
548 	args.op = EXT4_FC_TAG_CREAT;
549 
550 	ret = ext4_fc_track_template(handle, inode, __track_dentry_update,
551 					(void *)&args, 0);
552 	trace_ext4_fc_track_create(handle, inode, dentry, ret);
553 }
554 
555 void ext4_fc_track_create(handle_t *handle, struct dentry *dentry)
556 {
557 	struct inode *inode = d_inode(dentry);
558 
559 	if (ext4_fc_eligible(inode->i_sb))
560 		__ext4_fc_track_create(handle, inode, dentry);
561 }
562 
563 /* __track_fn for inode tracking */
564 static int __track_inode(handle_t *handle, struct inode *inode, void *arg,
565 			 bool update)
566 {
567 	if (update)
568 		return -EEXIST;
569 
570 	EXT4_I(inode)->i_fc_lblk_len = 0;
571 
572 	return 0;
573 }
574 
575 void ext4_fc_track_inode(handle_t *handle, struct inode *inode)
576 {
577 	int ret;
578 
579 	if (S_ISDIR(inode->i_mode))
580 		return;
581 
582 	if (ext4_should_journal_data(inode)) {
583 		ext4_fc_mark_ineligible(inode->i_sb,
584 					EXT4_FC_REASON_INODE_JOURNAL_DATA, handle);
585 		return;
586 	}
587 
588 	if (!ext4_fc_eligible(inode->i_sb))
589 		return;
590 
591 	/*
592 	 * Fast commit snapshots inode state at commit time, so there's no need
593 	 * to wait for EXT4_STATE_FC_COMMITTING here. If the inode is already
594 	 * on the commit queue, ext4_fc_cleanup() will requeue it for the new
595 	 * transaction once the current commit finishes.
596 	 */
597 
598 	/*
599 	 * From this point on, this inode will not be committed either
600 	 * by fast or full commit as long as the handle is open.
601 	 */
602 	ret = ext4_fc_track_template(handle, inode, __track_inode, NULL, 1);
603 	trace_ext4_fc_track_inode(handle, inode, ret);
604 }
605 
606 struct __track_range_args {
607 	ext4_lblk_t start, end;
608 };
609 
610 /* __track_fn for tracking data updates */
611 static int __track_range(handle_t *handle, struct inode *inode, void *arg,
612 			 bool update)
613 {
614 	struct ext4_inode_info *ei = EXT4_I(inode);
615 	ext4_lblk_t oldstart;
616 	struct __track_range_args *__arg =
617 		(struct __track_range_args *)arg;
618 
619 	if (inode->i_ino < EXT4_FIRST_INO(inode->i_sb)) {
620 		ext4_debug("Special inode %llu being modified\n", inode->i_ino);
621 		return -ECANCELED;
622 	}
623 
624 	oldstart = ei->i_fc_lblk_start;
625 
626 	if (update && ei->i_fc_lblk_len > 0) {
627 		ei->i_fc_lblk_start = min(ei->i_fc_lblk_start, __arg->start);
628 		ei->i_fc_lblk_len =
629 			max(oldstart + ei->i_fc_lblk_len - 1, __arg->end) -
630 				ei->i_fc_lblk_start + 1;
631 	} else {
632 		ei->i_fc_lblk_start = __arg->start;
633 		ei->i_fc_lblk_len = __arg->end - __arg->start + 1;
634 	}
635 
636 	return 0;
637 }
638 
639 void ext4_fc_track_range(handle_t *handle, struct inode *inode, ext4_lblk_t start,
640 			 ext4_lblk_t end)
641 {
642 	struct __track_range_args args;
643 	int ret;
644 
645 	if (S_ISDIR(inode->i_mode))
646 		return;
647 
648 	if (!ext4_fc_eligible(inode->i_sb))
649 		return;
650 
651 	if (ext4_has_inline_data(inode)) {
652 		ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_XATTR,
653 					handle);
654 		return;
655 	}
656 
657 	args.start = start;
658 	args.end = end;
659 
660 	ret = ext4_fc_track_template(handle, inode,  __track_range, &args, 1);
661 
662 	trace_ext4_fc_track_range(handle, inode, start, end, ret);
663 }
664 
665 int ext4_fc_get_buf(journal_t *journal, struct buffer_head **bh)
666 {
667 	KUNIT_STATIC_STUB_REDIRECT(ext4_fc_get_buf, journal, bh);
668 	return jbd2_fc_get_buf(journal, bh);
669 }
670 
671 int ext4_fc_issue_flush(struct block_device *bdev)
672 {
673 	KUNIT_STATIC_STUB_REDIRECT(ext4_fc_issue_flush, bdev);
674 	return blkdev_issue_flush(bdev);
675 }
676 
677 void ext4_fc_submit_bh(struct super_block *sb, bool is_tail)
678 {
679 	blk_opf_t write_flags = JBD2_JOURNAL_REQ_FLAGS;
680 	struct buffer_head *bh = EXT4_SB(sb)->s_fc_bh;
681 
682 	KUNIT_STATIC_STUB_REDIRECT(ext4_fc_submit_bh, sb, is_tail);
683 
684 	/* Add REQ_FUA | REQ_PREFLUSH only its tail */
685 	if (test_opt(sb, BARRIER) && is_tail)
686 		write_flags |= REQ_FUA | REQ_PREFLUSH;
687 	lock_buffer(bh);
688 	set_buffer_dirty(bh);
689 	set_buffer_uptodate(bh);
690 	bh_submit(bh, REQ_OP_WRITE | write_flags, bh_end_write);
691 	EXT4_SB(sb)->s_fc_bh = NULL;
692 }
693 
694 /* Ext4 commit path routines */
695 
696 /*
697  * Allocate len bytes on a fast commit buffer.
698  *
699  * During the commit time this function is used to manage fast commit
700  * block space. We don't split a fast commit log onto different
701  * blocks. So this function makes sure that if there's not enough space
702  * on the current block, the remaining space in the current block is
703  * marked as unused by adding EXT4_FC_TAG_PAD tag. In that case,
704  * new block is from jbd2 and CRC is updated to reflect the padding
705  * we added.
706  */
707 static u8 *ext4_fc_reserve_space(struct super_block *sb, int len, u32 *crc)
708 {
709 	struct ext4_fc_tl tl;
710 	struct ext4_sb_info *sbi = EXT4_SB(sb);
711 	struct buffer_head *bh;
712 	int bsize = sbi->s_journal->j_blocksize;
713 	int ret, off = sbi->s_fc_bytes % bsize;
714 	int remaining;
715 	u8 *dst;
716 
717 	/*
718 	 * If 'len' is too long to fit in any block alongside a PAD tlv, then we
719 	 * cannot fulfill the request.
720 	 */
721 	if (len > bsize - EXT4_FC_TAG_BASE_LEN)
722 		return NULL;
723 
724 	if (!sbi->s_fc_bh) {
725 		ret = ext4_fc_get_buf(EXT4_SB(sb)->s_journal, &bh);
726 		if (ret)
727 			return NULL;
728 		sbi->s_fc_bh = bh;
729 	}
730 	dst = sbi->s_fc_bh->b_data + off;
731 
732 	/*
733 	 * Allocate the bytes in the current block if we can do so while still
734 	 * leaving enough space for a PAD tlv.
735 	 */
736 	remaining = bsize - EXT4_FC_TAG_BASE_LEN - off;
737 	if (len <= remaining) {
738 		sbi->s_fc_bytes += len;
739 		return dst;
740 	}
741 
742 	/*
743 	 * Else, terminate the current block with a PAD tlv, then allocate a new
744 	 * block and allocate the bytes at the start of that new block.
745 	 */
746 
747 	tl.fc_tag = cpu_to_le16(EXT4_FC_TAG_PAD);
748 	tl.fc_len = cpu_to_le16(remaining);
749 	memcpy(dst, &tl, EXT4_FC_TAG_BASE_LEN);
750 	memset(dst + EXT4_FC_TAG_BASE_LEN, 0, remaining);
751 	*crc = ext4_chksum(*crc, sbi->s_fc_bh->b_data, bsize);
752 
753 	ext4_fc_submit_bh(sb, false);
754 
755 	ret = ext4_fc_get_buf(EXT4_SB(sb)->s_journal, &bh);
756 	if (ret)
757 		return NULL;
758 	sbi->s_fc_bh = bh;
759 	sbi->s_fc_bytes += bsize - off + len;
760 	return sbi->s_fc_bh->b_data;
761 }
762 
763 /*
764  * Complete a fast commit by writing tail tag.
765  *
766  * Writing tail tag marks the end of a fast commit. In order to guarantee
767  * atomicity, after writing tail tag, even if there's space remaining
768  * in the block, next commit shouldn't use it. That's why tail tag
769  * has the length as that of the remaining space on the block.
770  */
771 static int ext4_fc_write_tail(struct super_block *sb, u32 crc)
772 {
773 	struct ext4_sb_info *sbi = EXT4_SB(sb);
774 	struct ext4_fc_tl tl;
775 	struct ext4_fc_tail tail;
776 	int off, bsize = sbi->s_journal->j_blocksize;
777 	u8 *dst;
778 
779 	/*
780 	 * ext4_fc_reserve_space takes care of allocating an extra block if
781 	 * there's no enough space on this block for accommodating this tail.
782 	 */
783 	dst = ext4_fc_reserve_space(sb, EXT4_FC_TAG_BASE_LEN + sizeof(tail), &crc);
784 	if (!dst)
785 		return -ENOSPC;
786 
787 	off = sbi->s_fc_bytes % bsize;
788 
789 	tl.fc_tag = cpu_to_le16(EXT4_FC_TAG_TAIL);
790 	tl.fc_len = cpu_to_le16(bsize - off + sizeof(struct ext4_fc_tail));
791 	sbi->s_fc_bytes = round_up(sbi->s_fc_bytes, bsize);
792 
793 	memcpy(dst, &tl, EXT4_FC_TAG_BASE_LEN);
794 	dst += EXT4_FC_TAG_BASE_LEN;
795 	tail.fc_tid = cpu_to_le32(sbi->s_journal->j_running_transaction->t_tid);
796 	memcpy(dst, &tail.fc_tid, sizeof(tail.fc_tid));
797 	dst += sizeof(tail.fc_tid);
798 	crc = ext4_chksum(crc, sbi->s_fc_bh->b_data,
799 			  dst - (u8 *)sbi->s_fc_bh->b_data);
800 	tail.fc_crc = cpu_to_le32(crc);
801 	memcpy(dst, &tail.fc_crc, sizeof(tail.fc_crc));
802 	dst += sizeof(tail.fc_crc);
803 	memset(dst, 0, bsize - off); /* Don't leak uninitialized memory. */
804 
805 	ext4_fc_submit_bh(sb, true);
806 
807 	return 0;
808 }
809 
810 /*
811  * Adds tag, length, value and updates CRC. Returns true if tlv was added.
812  * Returns false if there's not enough space.
813  */
814 static bool ext4_fc_add_tlv(struct super_block *sb, u16 tag, u16 len, u8 *val,
815 			   u32 *crc)
816 {
817 	struct ext4_fc_tl tl;
818 	u8 *dst;
819 
820 	dst = ext4_fc_reserve_space(sb, EXT4_FC_TAG_BASE_LEN + len, crc);
821 	if (!dst)
822 		return false;
823 
824 	tl.fc_tag = cpu_to_le16(tag);
825 	tl.fc_len = cpu_to_le16(len);
826 
827 	memcpy(dst, &tl, EXT4_FC_TAG_BASE_LEN);
828 	memcpy(dst + EXT4_FC_TAG_BASE_LEN, val, len);
829 
830 	return true;
831 }
832 
833 /* Same as above, but adds dentry tlv. */
834 static bool ext4_fc_add_dentry_tlv(struct super_block *sb, u32 *crc,
835 				   struct ext4_fc_dentry_update *fc_dentry)
836 {
837 	struct ext4_fc_dentry_info fcd;
838 	struct ext4_fc_tl tl;
839 	int dlen = fc_dentry->fcd_name.name.len;
840 	u8 *dst = ext4_fc_reserve_space(sb,
841 			EXT4_FC_TAG_BASE_LEN + sizeof(fcd) + dlen, crc);
842 
843 	if (!dst)
844 		return false;
845 
846 	fcd.fc_parent_ino = cpu_to_le32(fc_dentry->fcd_parent);
847 	fcd.fc_ino = cpu_to_le32(fc_dentry->fcd_ino);
848 	tl.fc_tag = cpu_to_le16(fc_dentry->fcd_op);
849 	tl.fc_len = cpu_to_le16(sizeof(fcd) + dlen);
850 	memcpy(dst, &tl, EXT4_FC_TAG_BASE_LEN);
851 	dst += EXT4_FC_TAG_BASE_LEN;
852 	memcpy(dst, &fcd, sizeof(fcd));
853 	dst += sizeof(fcd);
854 	memcpy(dst, fc_dentry->fcd_name.name.name, dlen);
855 
856 	return true;
857 }
858 
859 struct ext4_fc_range {
860 	struct list_head list;
861 	u16 tag;
862 	ext4_lblk_t lblk;
863 	ext4_lblk_t len;
864 	ext4_fsblk_t pblk;
865 	bool unwritten;
866 };
867 
868 struct ext4_fc_inode_snap {
869 	struct list_head data_list;
870 	unsigned int inode_len;
871 	u8 inode_buf[];
872 };
873 
874 /*
875  * Writes inode in the fast commit space under TLV with tag @tag.
876  * Returns 0 on success, error on failure.
877  */
878 static int ext4_fc_write_inode(struct inode *inode, u32 *crc)
879 {
880 	struct ext4_inode_info *ei = EXT4_I(inode);
881 	struct ext4_fc_inode_snap *snap = ei->i_fc_snap;
882 	struct ext4_fc_snap_stats *stats =
883 		&EXT4_SB(inode->i_sb)->s_fc_snap_stats;
884 	struct ext4_fc_inode fc_inode;
885 	struct ext4_fc_tl tl;
886 	u8 *dst;
887 	u8 *src;
888 	int inode_len;
889 	int ret;
890 
891 	if (!snap) {
892 		atomic64_inc(&stats->snap_fail_no_snap);
893 		return -ECANCELED;
894 	}
895 
896 	src = snap->inode_buf;
897 	inode_len = snap->inode_len;
898 	if (!src || inode_len == 0) {
899 		atomic64_inc(&stats->snap_fail_no_snap);
900 		return -ECANCELED;
901 	}
902 
903 	fc_inode.fc_ino = cpu_to_le32(inode->i_ino);
904 	tl.fc_tag = cpu_to_le16(EXT4_FC_TAG_INODE);
905 	tl.fc_len = cpu_to_le16(inode_len + sizeof(fc_inode.fc_ino));
906 
907 	ret = -ECANCELED;
908 	dst = ext4_fc_reserve_space(inode->i_sb,
909 		EXT4_FC_TAG_BASE_LEN + inode_len + sizeof(fc_inode.fc_ino), crc);
910 	if (!dst)
911 		goto err;
912 
913 	memcpy(dst, &tl, EXT4_FC_TAG_BASE_LEN);
914 	dst += EXT4_FC_TAG_BASE_LEN;
915 	memcpy(dst, &fc_inode, sizeof(fc_inode));
916 	dst += sizeof(fc_inode);
917 	memcpy(dst, src, inode_len);
918 	ret = 0;
919 err:
920 	return ret;
921 }
922 
923 /*
924  * Writes updated data ranges for the inode in question. Updates CRC.
925  * Returns 0 on success, error otherwise.
926  */
927 static int ext4_fc_write_inode_data(struct inode *inode, u32 *crc)
928 {
929 	struct ext4_inode_info *ei = EXT4_I(inode);
930 	struct ext4_fc_inode_snap *snap = ei->i_fc_snap;
931 	struct ext4_fc_snap_stats *stats =
932 		&EXT4_SB(inode->i_sb)->s_fc_snap_stats;
933 	struct ext4_fc_add_range fc_ext;
934 	struct ext4_fc_del_range lrange;
935 	struct ext4_extent *ex;
936 	struct ext4_fc_range *range;
937 
938 	if (!snap) {
939 		atomic64_inc(&stats->snap_fail_no_snap);
940 		return -ECANCELED;
941 	}
942 
943 	list_for_each_entry(range, &snap->data_list, list) {
944 		if (range->tag == EXT4_FC_TAG_DEL_RANGE) {
945 			lrange.fc_ino = cpu_to_le32(inode->i_ino);
946 			lrange.fc_lblk = cpu_to_le32(range->lblk);
947 			lrange.fc_len = cpu_to_le32(range->len);
948 			if (!ext4_fc_add_tlv(inode->i_sb, EXT4_FC_TAG_DEL_RANGE,
949 					     sizeof(lrange), (u8 *)&lrange, crc))
950 				return -ENOSPC;
951 			continue;
952 		}
953 
954 		fc_ext.fc_ino = cpu_to_le32(inode->i_ino);
955 		ex = (struct ext4_extent *)&fc_ext.fc_ex;
956 		ex->ee_block = cpu_to_le32(range->lblk);
957 		ex->ee_len = cpu_to_le16(range->len);
958 		ext4_ext_store_pblock(ex, range->pblk);
959 		if (range->unwritten)
960 			ext4_ext_mark_unwritten(ex);
961 		else
962 			ext4_ext_mark_initialized(ex);
963 
964 		if (!ext4_fc_add_tlv(inode->i_sb, EXT4_FC_TAG_ADD_RANGE,
965 				     sizeof(fc_ext), (u8 *)&fc_ext, crc))
966 			return -ENOSPC;
967 	}
968 
969 	return 0;
970 }
971 
972 static void ext4_fc_free_ranges(struct list_head *head)
973 {
974 	struct ext4_fc_range *range, *range_n;
975 
976 	list_for_each_entry_safe(range, range_n, head, list) {
977 		list_del(&range->list);
978 		kmem_cache_free(ext4_fc_range_cachep, range);
979 	}
980 }
981 
982 static void ext4_fc_free_inode_snap(struct inode *inode)
983 {
984 	struct ext4_inode_info *ei = EXT4_I(inode);
985 	struct ext4_fc_inode_snap *snap = ei->i_fc_snap;
986 
987 	if (!snap)
988 		return;
989 
990 	ext4_fc_free_ranges(&snap->data_list);
991 	kfree(snap);
992 	ei->i_fc_snap = NULL;
993 }
994 
995 static int ext4_fc_snapshot_inode_data(struct inode *inode,
996 				       struct list_head *ranges,
997 				       unsigned int nr_ranges_total,
998 				       unsigned int *nr_rangesp,
999 				       int *snap_err)
1000 {
1001 	struct ext4_inode_info *ei = EXT4_I(inode);
1002 	struct ext4_fc_snap_stats *stats =
1003 		&EXT4_SB(inode->i_sb)->s_fc_snap_stats;
1004 	ext4_lblk_t start_lblk, end_lblk, cur_lblk;
1005 	unsigned int nr_ranges = 0;
1006 
1007 	spin_lock(&ei->i_fc_lock);
1008 	if (ei->i_fc_lblk_len == 0) {
1009 		spin_unlock(&ei->i_fc_lock);
1010 		if (nr_rangesp)
1011 			*nr_rangesp = 0;
1012 		return 0;
1013 	}
1014 	start_lblk = ei->i_fc_lblk_start;
1015 	end_lblk = ei->i_fc_lblk_start + ei->i_fc_lblk_len - 1;
1016 	ei->i_fc_lblk_len = 0;
1017 	spin_unlock(&ei->i_fc_lock);
1018 
1019 	cur_lblk = start_lblk;
1020 	ext4_debug("snapshot data ranges %u-%u for inode %llu\n",
1021 		   start_lblk, end_lblk,
1022 		   (unsigned long long)inode->i_ino);
1023 
1024 	while (cur_lblk <= end_lblk) {
1025 		struct extent_status es;
1026 		struct ext4_fc_range *range;
1027 		ext4_lblk_t len;
1028 		u64 remaining = (u64)end_lblk - cur_lblk + 1;
1029 
1030 		if (!ext4_es_lookup_extent(inode, cur_lblk, NULL, &es, NULL)) {
1031 			atomic64_inc(&stats->snap_fail_es_miss);
1032 			ext4_fc_set_snap_err(snap_err, EXT4_FC_SNAP_ERR_ES_MISS);
1033 			return -EAGAIN;
1034 		}
1035 
1036 		if (ext4_es_is_delayed(&es)) {
1037 			atomic64_inc(&stats->snap_fail_es_delayed);
1038 			ext4_fc_set_snap_err(snap_err,
1039 					     EXT4_FC_SNAP_ERR_ES_DELAYED);
1040 			return -EAGAIN;
1041 		}
1042 
1043 		len = es.es_len - (cur_lblk - es.es_lblk);
1044 		if (len > remaining)
1045 			len = remaining;
1046 		if (len == 0) {
1047 			cur_lblk++;
1048 			continue;
1049 		}
1050 
1051 		if (nr_ranges_total + nr_ranges >= EXT4_FC_SNAPSHOT_MAX_RANGES) {
1052 			atomic64_inc(&stats->snap_fail_ranges_cap);
1053 			ext4_fc_set_snap_err(snap_err,
1054 					     EXT4_FC_SNAP_ERR_RANGES_CAP);
1055 			return -E2BIG;
1056 		}
1057 
1058 		range = kmem_cache_alloc(ext4_fc_range_cachep, GFP_NOFS);
1059 		if (!range) {
1060 			atomic64_inc(&stats->snap_fail_nomem);
1061 			ext4_fc_set_snap_err(snap_err, EXT4_FC_SNAP_ERR_NOMEM);
1062 			return -ENOMEM;
1063 		}
1064 		nr_ranges++;
1065 
1066 		range->lblk = cur_lblk;
1067 		range->len = len;
1068 		range->pblk = 0;
1069 		range->unwritten = false;
1070 
1071 		if (ext4_es_is_hole(&es)) {
1072 			range->tag = EXT4_FC_TAG_DEL_RANGE;
1073 		} else if (ext4_es_is_written(&es) ||
1074 			   ext4_es_is_unwritten(&es)) {
1075 			unsigned int max;
1076 
1077 			range->tag = EXT4_FC_TAG_ADD_RANGE;
1078 			range->pblk = ext4_es_pblock(&es) +
1079 				      (cur_lblk - es.es_lblk);
1080 			range->unwritten = ext4_es_is_unwritten(&es);
1081 
1082 			max = range->unwritten ? EXT_UNWRITTEN_MAX_LEN :
1083 						 EXT_INIT_MAX_LEN;
1084 			if (range->len > max)
1085 				range->len = max;
1086 		} else {
1087 			kmem_cache_free(ext4_fc_range_cachep, range);
1088 			atomic64_inc(&stats->snap_fail_es_other);
1089 			ext4_fc_set_snap_err(snap_err, EXT4_FC_SNAP_ERR_ES_OTHER);
1090 			return -EAGAIN;
1091 		}
1092 
1093 		INIT_LIST_HEAD(&range->list);
1094 		list_add_tail(&range->list, ranges);
1095 
1096 		if ((u64)range->len > (u64)end_lblk - cur_lblk)
1097 			break;
1098 
1099 		cur_lblk += range->len;
1100 	}
1101 
1102 	if (nr_rangesp)
1103 		*nr_rangesp = nr_ranges;
1104 	return 0;
1105 }
1106 
1107 static int ext4_fc_snapshot_inode(struct inode *inode,
1108 				  unsigned int nr_ranges_total,
1109 				  unsigned int *nr_rangesp, int *snap_err)
1110 {
1111 	struct ext4_inode_info *ei = EXT4_I(inode);
1112 	struct ext4_fc_snap_stats *stats =
1113 		&EXT4_SB(inode->i_sb)->s_fc_snap_stats;
1114 	struct ext4_fc_inode_snap *snap;
1115 	int inode_len = EXT4_GOOD_OLD_INODE_SIZE;
1116 	struct ext4_iloc iloc;
1117 	LIST_HEAD(ranges);
1118 	unsigned int nr_ranges = 0;
1119 	int ret;
1120 	int alloc_ctx;
1121 
1122 	ret = ext4_get_inode_loc_noio(inode, &iloc);
1123 	if (ret) {
1124 		atomic64_inc(&stats->snap_fail_inode_loc);
1125 		ext4_fc_set_snap_err(snap_err, EXT4_FC_SNAP_ERR_INODE_LOC);
1126 		return ret;
1127 	}
1128 
1129 	if (ext4_test_inode_flag(inode, EXT4_INODE_INLINE_DATA))
1130 		inode_len = EXT4_INODE_SIZE(inode->i_sb);
1131 	else if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE)
1132 		inode_len += ei->i_extra_isize;
1133 
1134 	snap = kmalloc_flex(*snap, inode_buf, inode_len, GFP_NOFS);
1135 	if (!snap) {
1136 		atomic64_inc(&stats->snap_fail_nomem);
1137 		ext4_fc_set_snap_err(snap_err, EXT4_FC_SNAP_ERR_NOMEM);
1138 		brelse(iloc.bh);
1139 		return -ENOMEM;
1140 	}
1141 	INIT_LIST_HEAD(&snap->data_list);
1142 	snap->inode_len = inode_len;
1143 
1144 	memcpy(snap->inode_buf, (u8 *)ext4_raw_inode(&iloc), inode_len);
1145 	brelse(iloc.bh);
1146 
1147 	ret = ext4_fc_snapshot_inode_data(inode, &ranges, nr_ranges_total,
1148 					  &nr_ranges, snap_err);
1149 	if (ret) {
1150 		kfree(snap);
1151 		ext4_fc_free_ranges(&ranges);
1152 		return ret;
1153 	}
1154 
1155 	alloc_ctx = ext4_fc_lock(inode->i_sb);
1156 	ext4_fc_free_inode_snap(inode);
1157 	ei->i_fc_snap = snap;
1158 	list_splice_tail_init(&ranges, &snap->data_list);
1159 	ext4_fc_unlock(inode->i_sb, alloc_ctx);
1160 
1161 	atomic64_inc(&stats->snap_inodes);
1162 	atomic64_add(nr_ranges, &stats->snap_ranges);
1163 	if (nr_rangesp)
1164 		*nr_rangesp = nr_ranges;
1165 	return 0;
1166 }
1167 
1168 /* Flushes data of all the inodes in the commit queue. */
1169 static int ext4_fc_flush_data(journal_t *journal)
1170 {
1171 	struct super_block *sb = journal->j_private;
1172 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1173 	struct ext4_inode_info *ei;
1174 	int ret = 0;
1175 
1176 	list_for_each_entry(ei, &sbi->s_fc_q[FC_Q_MAIN], i_fc_list) {
1177 		ret = jbd2_submit_inode_data(journal, READ_ONCE(ei->jinode));
1178 		if (ret)
1179 			return ret;
1180 	}
1181 
1182 	list_for_each_entry(ei, &sbi->s_fc_q[FC_Q_MAIN], i_fc_list) {
1183 		ret = jbd2_wait_inode_data(journal, READ_ONCE(ei->jinode));
1184 		if (ret)
1185 			return ret;
1186 	}
1187 
1188 	return 0;
1189 }
1190 
1191 /* Commit all the directory entry updates */
1192 static int ext4_fc_commit_dentry_updates(journal_t *journal, u32 *crc)
1193 {
1194 	struct super_block *sb = journal->j_private;
1195 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1196 	struct ext4_fc_dentry_update *fc_dentry, *fc_dentry_n;
1197 	struct inode *inode;
1198 	struct ext4_inode_info *ei;
1199 	int ret;
1200 
1201 	if (list_empty(&sbi->s_fc_dentry_q[FC_Q_MAIN]))
1202 		return 0;
1203 	list_for_each_entry_safe(fc_dentry, fc_dentry_n,
1204 				 &sbi->s_fc_dentry_q[FC_Q_MAIN], fcd_list) {
1205 		if (fc_dentry->fcd_op != EXT4_FC_TAG_CREAT) {
1206 			if (!ext4_fc_add_dentry_tlv(sb, crc, fc_dentry))
1207 				return -ENOSPC;
1208 			continue;
1209 		}
1210 		/*
1211 		 * With fcd_dilist we need not loop in sbi->s_fc_q to get the
1212 		 * corresponding inode. Also, the corresponding inode could have been
1213 		 * deleted, in which case, we don't need to do anything.
1214 		 */
1215 		if (list_empty(&fc_dentry->fcd_dilist))
1216 			continue;
1217 		/*
1218 		 * For EXT4_FC_TAG_CREAT, fcd_dilist is linked on the created
1219 		 * inode's i_fc_dilist list (kept singular), so we can recover the
1220 		 * inode through it.
1221 		 */
1222 		ei = list_first_entry(&fc_dentry->fcd_dilist,
1223 				struct ext4_inode_info, i_fc_dilist);
1224 		inode = &ei->vfs_inode;
1225 		WARN_ON(inode->i_ino != fc_dentry->fcd_ino);
1226 
1227 		/*
1228 		 * We first write the inode and then the create dirent. This
1229 		 * allows the recovery code to create an unnamed inode first
1230 		 * and then link it to a directory entry. This allows us
1231 		 * to use namei.c routines almost as is and simplifies
1232 		 * the recovery code.
1233 		 */
1234 		ret = ext4_fc_write_inode(inode, crc);
1235 		if (ret)
1236 			return ret;
1237 		ret = ext4_fc_write_inode_data(inode, crc);
1238 		if (ret)
1239 			return ret;
1240 		if (!ext4_fc_add_dentry_tlv(sb, crc, fc_dentry))
1241 			return -ENOSPC;
1242 	}
1243 	return 0;
1244 }
1245 
1246 static int ext4_fc_alloc_snapshot_inodes(struct super_block *sb,
1247 					 struct inode ***inodesp,
1248 					 unsigned int *nr_inodesp);
1249 
1250 static int ext4_fc_snapshot_inodes(journal_t *journal, struct inode **inodes,
1251 				   unsigned int inodes_size,
1252 				   unsigned int *nr_inodesp,
1253 				   unsigned int *nr_rangesp,
1254 				   int *snap_err)
1255 {
1256 	struct super_block *sb = journal->j_private;
1257 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1258 	struct ext4_inode_info *iter;
1259 	struct ext4_fc_dentry_update *fc_dentry;
1260 	unsigned int i = 0;
1261 	unsigned int idx;
1262 	unsigned int nr_ranges = 0;
1263 	int ret = 0;
1264 	int alloc_ctx;
1265 
1266 	alloc_ctx = ext4_fc_lock(sb);
1267 	list_for_each_entry(iter, &sbi->s_fc_q[FC_Q_MAIN], i_fc_list) {
1268 		if (i >= inodes_size) {
1269 			atomic64_inc(&sbi->s_fc_snap_stats.snap_fail_inodes_cap);
1270 			ext4_fc_set_snap_err(snap_err,
1271 					     EXT4_FC_SNAP_ERR_INODES_CAP);
1272 			ret = -E2BIG;
1273 			goto unlock;
1274 		}
1275 		inodes[i++] = &iter->vfs_inode;
1276 	}
1277 
1278 	list_for_each_entry(fc_dentry, &sbi->s_fc_dentry_q[FC_Q_MAIN], fcd_list) {
1279 		struct ext4_inode_info *ei;
1280 		struct inode *inode;
1281 
1282 		if (fc_dentry->fcd_op != EXT4_FC_TAG_CREAT)
1283 			continue;
1284 		if (list_empty(&fc_dentry->fcd_dilist))
1285 			continue;
1286 
1287 		/* See the comment in ext4_fc_commit_dentry_updates(). */
1288 		ei = list_first_entry(&fc_dentry->fcd_dilist,
1289 				      struct ext4_inode_info, i_fc_dilist);
1290 		inode = &ei->vfs_inode;
1291 		if (!list_empty(&ei->i_fc_list))
1292 			continue;
1293 
1294 		if (i >= inodes_size) {
1295 			atomic64_inc(&sbi->s_fc_snap_stats.snap_fail_inodes_cap);
1296 			ext4_fc_set_snap_err(snap_err,
1297 					     EXT4_FC_SNAP_ERR_INODES_CAP);
1298 			ret = -E2BIG;
1299 			goto unlock;
1300 		}
1301 		/*
1302 		 * Create-only inodes may only be referenced via fcd_dilist and
1303 		 * not appear on s_fc_q[MAIN]. They may hit the last iput while
1304 		 * we are snapshotting, but inode eviction calls ext4_fc_del(),
1305 		 * which waits for FC_COMMITTING to clear. Mark them FC_COMMITTING
1306 		 * so the inode stays pinned and the snapshot stays valid until
1307 		 * ext4_fc_cleanup().
1308 		 */
1309 		ext4_set_inode_state(inode, EXT4_STATE_FC_COMMITTING);
1310 		inodes[i++] = inode;
1311 	}
1312 unlock:
1313 	ext4_fc_unlock(sb, alloc_ctx);
1314 
1315 	if (ret)
1316 		return ret;
1317 
1318 	for (idx = 0; idx < i; idx++) {
1319 		unsigned int inode_ranges = 0;
1320 
1321 		ret = ext4_fc_snapshot_inode(inodes[idx], nr_ranges,
1322 					     &inode_ranges, snap_err);
1323 		if (ret)
1324 			break;
1325 		nr_ranges += inode_ranges;
1326 	}
1327 
1328 	if (nr_inodesp)
1329 		*nr_inodesp = idx;
1330 	if (nr_rangesp)
1331 		*nr_rangesp = nr_ranges;
1332 	return ret;
1333 }
1334 
1335 static int ext4_fc_perform_commit(journal_t *journal, tid_t commit_tid)
1336 {
1337 	struct super_block *sb = journal->j_private;
1338 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1339 	struct ext4_fc_snap_stats *snap_stats = &sbi->s_fc_snap_stats;
1340 	struct ext4_inode_info *iter;
1341 	struct ext4_fc_head head;
1342 	struct inode *inode;
1343 	struct inode **inodes;
1344 	unsigned int inodes_size;
1345 	unsigned int snap_inodes = 0;
1346 	unsigned int snap_ranges = 0;
1347 	int snap_err = EXT4_FC_SNAP_ERR_NONE;
1348 	struct blk_plug plug;
1349 	int ret = 0;
1350 	u32 crc = 0;
1351 	int alloc_ctx;
1352 	ktime_t lock_start;
1353 	u64 locked_ns;
1354 
1355 	/*
1356 	 * Step 1: Mark all inodes on s_fc_q[MAIN] with
1357 	 * EXT4_STATE_FC_FLUSHING_DATA. This prevents these inodes from being
1358 	 * freed until the data flush is over.
1359 	 */
1360 	alloc_ctx = ext4_fc_lock(sb);
1361 	list_for_each_entry(iter, &sbi->s_fc_q[FC_Q_MAIN], i_fc_list) {
1362 		ext4_set_inode_state(&iter->vfs_inode,
1363 				     EXT4_STATE_FC_FLUSHING_DATA);
1364 	}
1365 	ext4_fc_unlock(sb, alloc_ctx);
1366 
1367 	/* Step 2: Flush data for all the eligible inodes. */
1368 	ret = ext4_fc_flush_data(journal);
1369 
1370 	/*
1371 	 * Step 3: Clear EXT4_STATE_FC_FLUSHING_DATA flag, before returning
1372 	 * any error from step 2. This ensures that waiters waiting on
1373 	 * EXT4_STATE_FC_FLUSHING_DATA can resume.
1374 	 */
1375 	alloc_ctx = ext4_fc_lock(sb);
1376 	list_for_each_entry(iter, &sbi->s_fc_q[FC_Q_MAIN], i_fc_list) {
1377 		ext4_clear_inode_state(&iter->vfs_inode,
1378 				       EXT4_STATE_FC_FLUSHING_DATA);
1379 		ext4_fc_wake_inode_state(&iter->vfs_inode,
1380 					 EXT4_STATE_FC_FLUSHING_DATA);
1381 	}
1382 
1383 	/*
1384 	 * Make sure clearing of EXT4_STATE_FC_FLUSHING_DATA is visible before
1385 	 * the waiter checks the bit. Pairs with implicit barrier in
1386 	 * prepare_to_wait() in ext4_fc_del().
1387 	 */
1388 	smp_mb();
1389 	ext4_fc_unlock(sb, alloc_ctx);
1390 
1391 	/*
1392 	 * If we encountered error in Step 2, return it now after clearing
1393 	 * EXT4_STATE_FC_FLUSHING_DATA bit.
1394 	 */
1395 	if (ret)
1396 		return ret;
1397 
1398 	ret = ext4_fc_alloc_snapshot_inodes(sb, &inodes, &inodes_size);
1399 	if (ret) {
1400 		if (ret == -E2BIG)
1401 			atomic64_inc(&snap_stats->snap_fail_inodes_cap);
1402 		else if (ret == -ENOMEM)
1403 			atomic64_inc(&snap_stats->snap_fail_nomem);
1404 		return ret;
1405 	}
1406 
1407 	/* Step 4: Mark all inodes as being committed. */
1408 	jbd2_journal_lock_updates(journal);
1409 	lock_start = ktime_get();
1410 	/*
1411 	 * The journal is now locked. No more handles can start and all the
1412 	 * previous handles are now drained. Snapshotting happens in this
1413 	 * window so log writing can consume only stable snapshots without
1414 	 * doing logical-to-physical mapping.
1415 	 */
1416 	alloc_ctx = ext4_fc_lock(sb);
1417 	list_for_each_entry(iter, &sbi->s_fc_q[FC_Q_MAIN], i_fc_list) {
1418 		ext4_set_inode_state(&iter->vfs_inode,
1419 				     EXT4_STATE_FC_COMMITTING);
1420 	}
1421 	ext4_fc_unlock(sb, alloc_ctx);
1422 
1423 	ret = ext4_fc_snapshot_inodes(journal, inodes, inodes_size,
1424 				      &snap_inodes, &snap_ranges, &snap_err);
1425 	jbd2_journal_unlock_updates(journal);
1426 	locked_ns = ktime_to_ns(ktime_sub(ktime_get(), lock_start));
1427 	atomic64_add(locked_ns, &snap_stats->lock_updates_ns_total);
1428 	atomic64_inc(&snap_stats->lock_updates_samples);
1429 	ext4_fc_snap_stats_update_max(&snap_stats->lock_updates_ns_max,
1430 				      locked_ns);
1431 	if (trace_ext4_fc_lock_updates_enabled())
1432 		trace_call__ext4_fc_lock_updates(sb, commit_tid, locked_ns,
1433 						 snap_inodes, snap_ranges,
1434 						 ret, snap_err);
1435 	kvfree(inodes);
1436 	if (ret)
1437 		return ret;
1438 
1439 	/*
1440 	 * Step 5: If file system device is different from journal device,
1441 	 * issue a cache flush before we start writing fast commit blocks.
1442 	 */
1443 	if (journal->j_fs_dev != journal->j_dev &&
1444 	    journal->j_flags & JBD2_BARRIER) {
1445 		ret = ext4_fc_issue_flush(journal->j_fs_dev);
1446 		if (ret)
1447 			return ret;
1448 	}
1449 
1450 	blk_start_plug(&plug);
1451 	alloc_ctx = ext4_fc_lock(sb);
1452 	/* Step 6: Write fast commit blocks to disk. */
1453 	if (sbi->s_fc_bytes == 0) {
1454 		/*
1455 		 * Step 6.1: Add a head tag only if this is the first fast
1456 		 * commit in this TID.
1457 		 */
1458 		head.fc_features = cpu_to_le32(EXT4_FC_SUPPORTED_FEATURES);
1459 		head.fc_tid = cpu_to_le32(
1460 			sbi->s_journal->j_running_transaction->t_tid);
1461 		if (!ext4_fc_add_tlv(sb, EXT4_FC_TAG_HEAD, sizeof(head),
1462 			(u8 *)&head, &crc)) {
1463 			ret = -ENOSPC;
1464 			goto out;
1465 		}
1466 	}
1467 
1468 	/* Step 6.2: Now write all the dentry updates. */
1469 	ret = ext4_fc_commit_dentry_updates(journal, &crc);
1470 	if (ret)
1471 		goto out;
1472 
1473 	/* Step 6.3: Now write all the changed inodes to disk. */
1474 	list_for_each_entry(iter, &sbi->s_fc_q[FC_Q_MAIN], i_fc_list) {
1475 		inode = &iter->vfs_inode;
1476 		if (!ext4_test_inode_state(inode, EXT4_STATE_FC_COMMITTING))
1477 			continue;
1478 
1479 		ret = ext4_fc_write_inode_data(inode, &crc);
1480 		if (ret)
1481 			goto out;
1482 		ret = ext4_fc_write_inode(inode, &crc);
1483 		if (ret)
1484 			goto out;
1485 	}
1486 	/* Step 6.4: Finally write tail tag to conclude this fast commit. */
1487 	ret = ext4_fc_write_tail(sb, crc);
1488 
1489 out:
1490 	ext4_fc_unlock(sb, alloc_ctx);
1491 	blk_finish_plug(&plug);
1492 	return ret;
1493 }
1494 
1495 static unsigned int ext4_fc_count_snapshot_inodes(struct super_block *sb)
1496 {
1497 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1498 	struct ext4_inode_info *iter;
1499 	struct ext4_fc_dentry_update *fc_dentry;
1500 	unsigned int nr_inodes = 0;
1501 	int alloc_ctx;
1502 
1503 	alloc_ctx = ext4_fc_lock(sb);
1504 	list_for_each_entry(iter, &sbi->s_fc_q[FC_Q_MAIN], i_fc_list)
1505 		nr_inodes++;
1506 
1507 	list_for_each_entry(fc_dentry, &sbi->s_fc_dentry_q[FC_Q_MAIN], fcd_list) {
1508 		struct ext4_inode_info *ei;
1509 
1510 		if (fc_dentry->fcd_op != EXT4_FC_TAG_CREAT)
1511 			continue;
1512 		if (list_empty(&fc_dentry->fcd_dilist))
1513 			continue;
1514 
1515 		/* See the comment in ext4_fc_commit_dentry_updates(). */
1516 		ei = list_first_entry(&fc_dentry->fcd_dilist,
1517 				      struct ext4_inode_info, i_fc_dilist);
1518 		if (!list_empty(&ei->i_fc_list))
1519 			continue;
1520 
1521 		nr_inodes++;
1522 	}
1523 	ext4_fc_unlock(sb, alloc_ctx);
1524 
1525 	return nr_inodes;
1526 }
1527 
1528 static int ext4_fc_alloc_snapshot_inodes(struct super_block *sb,
1529 					 struct inode ***inodesp,
1530 					 unsigned int *nr_inodesp)
1531 {
1532 	unsigned int nr_inodes = ext4_fc_count_snapshot_inodes(sb);
1533 	struct inode **inodes;
1534 
1535 	*inodesp = NULL;
1536 	*nr_inodesp = 0;
1537 
1538 	if (!nr_inodes)
1539 		return 0;
1540 
1541 	if (nr_inodes > EXT4_FC_SNAPSHOT_MAX_INODES)
1542 		return -E2BIG;
1543 
1544 	inodes = kvzalloc_objs(*inodes, nr_inodes, GFP_NOFS);
1545 	if (!inodes)
1546 		return -ENOMEM;
1547 
1548 	*inodesp = inodes;
1549 	*nr_inodesp = nr_inodes;
1550 	return 0;
1551 }
1552 
1553 static void ext4_fc_update_stats(struct super_block *sb, int status,
1554 				 u64 commit_time, int nblks, tid_t commit_tid)
1555 {
1556 	struct ext4_fc_stats *stats = &EXT4_SB(sb)->s_fc_stats;
1557 
1558 	ext4_debug("Fast commit ended with status = %d for tid %u",
1559 			status, commit_tid);
1560 	if (status == EXT4_FC_STATUS_OK) {
1561 		stats->fc_num_commits++;
1562 		stats->fc_numblks += nblks;
1563 		if (likely(stats->s_fc_avg_commit_time))
1564 			stats->s_fc_avg_commit_time =
1565 				(commit_time +
1566 				 stats->s_fc_avg_commit_time * 3) / 4;
1567 		else
1568 			stats->s_fc_avg_commit_time = commit_time;
1569 	} else if (status == EXT4_FC_STATUS_FAILED ||
1570 		   status == EXT4_FC_STATUS_INELIGIBLE) {
1571 		if (status == EXT4_FC_STATUS_FAILED)
1572 			stats->fc_failed_commits++;
1573 		stats->fc_ineligible_commits++;
1574 	} else {
1575 		stats->fc_skipped_commits++;
1576 	}
1577 	trace_ext4_fc_commit_stop(sb, nblks, status, commit_tid);
1578 }
1579 
1580 /*
1581  * The main commit entry point. Performs a fast commit for transaction
1582  * commit_tid if needed. If it's not possible to perform a fast commit
1583  * due to various reasons, we fall back to full commit. Returns 0
1584  * on success, error otherwise.
1585  */
1586 int ext4_fc_commit(journal_t *journal, tid_t commit_tid)
1587 {
1588 	struct super_block *sb = journal->j_private;
1589 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1590 	int nblks = 0, ret, bsize = journal->j_blocksize;
1591 	int subtid = atomic_read(&sbi->s_fc_subtid);
1592 	int status = EXT4_FC_STATUS_OK, fc_bufs_before = 0;
1593 	ktime_t start_time, commit_time;
1594 	int old_ioprio, journal_ioprio;
1595 
1596 	if (!test_opt2(sb, JOURNAL_FAST_COMMIT))
1597 		return jbd2_complete_transaction(journal, commit_tid);
1598 
1599 	trace_ext4_fc_commit_start(sb, commit_tid);
1600 
1601 	start_time = ktime_get();
1602 	old_ioprio = get_current_ioprio();
1603 
1604 restart_fc:
1605 	ret = jbd2_fc_begin_commit(journal, commit_tid);
1606 	if (ret == -EALREADY) {
1607 		/* There was an ongoing commit, check if we need to restart */
1608 		if (atomic_read(&sbi->s_fc_subtid) <= subtid &&
1609 		    tid_gt(commit_tid, journal->j_commit_sequence))
1610 			goto restart_fc;
1611 		ext4_fc_update_stats(sb, EXT4_FC_STATUS_SKIPPED, 0, 0,
1612 				commit_tid);
1613 		return 0;
1614 	} else if (ret) {
1615 		/*
1616 		 * Commit couldn't start. Just update stats and perform a
1617 		 * full commit.
1618 		 */
1619 		ext4_fc_update_stats(sb, EXT4_FC_STATUS_FAILED, 0, 0,
1620 				commit_tid);
1621 		return jbd2_complete_transaction(journal, commit_tid);
1622 	}
1623 
1624 	/*
1625 	 * After establishing journal barrier via jbd2_fc_begin_commit(), check
1626 	 * if we are fast commit ineligible.
1627 	 */
1628 	if (ext4_test_mount_flag(sb, EXT4_MF_FC_INELIGIBLE)) {
1629 		status = EXT4_FC_STATUS_INELIGIBLE;
1630 		goto fallback;
1631 	}
1632 
1633 	/*
1634 	 * Now that we know that this thread is going to do a fast commit,
1635 	 * elevate the priority to match that of the journal thread.
1636 	 */
1637 	if (journal->j_task->io_context)
1638 		journal_ioprio = sbi->s_journal->j_task->io_context->ioprio;
1639 	else
1640 		journal_ioprio = EXT4_DEF_JOURNAL_IOPRIO;
1641 	set_task_ioprio(current, journal_ioprio);
1642 	fc_bufs_before = (sbi->s_fc_bytes + bsize - 1) / bsize;
1643 	ret = ext4_fc_perform_commit(journal, commit_tid);
1644 	if (ret < 0) {
1645 		if (ret == -EAGAIN || ret == -E2BIG || ret == -ECANCELED)
1646 			status = EXT4_FC_STATUS_INELIGIBLE;
1647 		else
1648 			status = EXT4_FC_STATUS_FAILED;
1649 		goto fallback;
1650 	}
1651 	nblks = (sbi->s_fc_bytes + bsize - 1) / bsize - fc_bufs_before;
1652 	ret = jbd2_fc_wait_bufs(journal, nblks);
1653 	if (ret < 0) {
1654 		status = EXT4_FC_STATUS_FAILED;
1655 		goto fallback;
1656 	}
1657 	atomic_inc(&sbi->s_fc_subtid);
1658 	ret = jbd2_fc_end_commit(journal);
1659 	set_task_ioprio(current, old_ioprio);
1660 	/*
1661 	 * weight the commit time higher than the average time so we
1662 	 * don't react too strongly to vast changes in the commit time
1663 	 */
1664 	commit_time = ktime_to_ns(ktime_sub(ktime_get(), start_time));
1665 	ext4_fc_update_stats(sb, status, commit_time, nblks, commit_tid);
1666 	return ret;
1667 
1668 fallback:
1669 	set_task_ioprio(current, old_ioprio);
1670 	ret = jbd2_fc_end_commit_fallback(journal);
1671 	ext4_fc_update_stats(sb, status, 0, 0, commit_tid);
1672 	return ret;
1673 }
1674 
1675 /*
1676  * Fast commit cleanup routine. This is called after every fast commit and
1677  * full commit. full is true if we are called after a full commit.
1678  */
1679 static void ext4_fc_cleanup(journal_t *journal, int full, tid_t tid)
1680 {
1681 	struct super_block *sb = journal->j_private;
1682 	struct ext4_sb_info *sbi = EXT4_SB(sb);
1683 	struct ext4_inode_info *ei;
1684 	struct ext4_fc_dentry_update *fc_dentry;
1685 	int alloc_ctx;
1686 
1687 	if (full && sbi->s_fc_bh)
1688 		sbi->s_fc_bh = NULL;
1689 
1690 	trace_ext4_fc_cleanup(journal, full, tid);
1691 	jbd2_fc_release_bufs(journal);
1692 
1693 	alloc_ctx = ext4_fc_lock(sb);
1694 	while (!list_empty(&sbi->s_fc_q[FC_Q_MAIN])) {
1695 		bool requeue;
1696 
1697 		ei = list_first_entry(&sbi->s_fc_q[FC_Q_MAIN],
1698 					struct ext4_inode_info,
1699 					i_fc_list);
1700 		list_del_init(&ei->i_fc_list);
1701 		ext4_fc_free_inode_snap(&ei->vfs_inode);
1702 		spin_lock(&ei->i_fc_lock);
1703 		if (full)
1704 			requeue = !tid_geq(tid, ei->i_sync_tid);
1705 		else
1706 			requeue = ext4_test_inode_state(&ei->vfs_inode,
1707 							EXT4_STATE_FC_REQUEUE);
1708 		if (!requeue)
1709 			ext4_fc_reset_inode(&ei->vfs_inode);
1710 		ext4_clear_inode_state(&ei->vfs_inode, EXT4_STATE_FC_REQUEUE);
1711 		ext4_clear_inode_state(&ei->vfs_inode,
1712 				       EXT4_STATE_FC_COMMITTING);
1713 		spin_unlock(&ei->i_fc_lock);
1714 		if (requeue)
1715 			list_add_tail(&ei->i_fc_list,
1716 				      &sbi->s_fc_q[FC_Q_STAGING]);
1717 		/*
1718 		 * Make sure clearing of EXT4_STATE_FC_COMMITTING is
1719 		 * visible before we send the wakeup. Pairs with implicit
1720 		 * barrier in prepare_to_wait() in ext4_fc_del().
1721 		 */
1722 		smp_mb();
1723 		ext4_fc_wake_inode_state(&ei->vfs_inode,
1724 					 EXT4_STATE_FC_COMMITTING);
1725 	}
1726 
1727 	while (!list_empty(&sbi->s_fc_dentry_q[FC_Q_MAIN])) {
1728 		fc_dentry = list_first_entry(&sbi->s_fc_dentry_q[FC_Q_MAIN],
1729 						 struct ext4_fc_dentry_update,
1730 						 fcd_list);
1731 		list_del_init(&fc_dentry->fcd_list);
1732 		if (fc_dentry->fcd_op == EXT4_FC_TAG_CREAT &&
1733 			!list_empty(&fc_dentry->fcd_dilist)) {
1734 			/* See the comment in ext4_fc_commit_dentry_updates(). */
1735 			ei = list_first_entry(&fc_dentry->fcd_dilist,
1736 						  struct ext4_inode_info,
1737 						  i_fc_dilist);
1738 			ext4_fc_free_inode_snap(&ei->vfs_inode);
1739 			spin_lock(&ei->i_fc_lock);
1740 			ext4_clear_inode_state(&ei->vfs_inode,
1741 						   EXT4_STATE_FC_REQUEUE);
1742 			ext4_clear_inode_state(&ei->vfs_inode,
1743 						   EXT4_STATE_FC_COMMITTING);
1744 			spin_unlock(&ei->i_fc_lock);
1745 			/*
1746 			 * Make sure clearing of EXT4_STATE_FC_COMMITTING is
1747 			 * visible before we send the wakeup. Pairs with
1748 			 * implicit barrier in prepare_to_wait() in
1749 			 * ext4_fc_del().
1750 			 */
1751 			smp_mb();
1752 			ext4_fc_wake_inode_state(&ei->vfs_inode,
1753 						 EXT4_STATE_FC_COMMITTING);
1754 		}
1755 		list_del_init(&fc_dentry->fcd_dilist);
1756 
1757 		release_dentry_name_snapshot(&fc_dentry->fcd_name);
1758 		kmem_cache_free(ext4_fc_dentry_cachep, fc_dentry);
1759 	}
1760 
1761 	list_splice_init(&sbi->s_fc_dentry_q[FC_Q_STAGING],
1762 				&sbi->s_fc_dentry_q[FC_Q_MAIN]);
1763 	list_splice_init(&sbi->s_fc_q[FC_Q_STAGING],
1764 				&sbi->s_fc_q[FC_Q_MAIN]);
1765 
1766 	if (tid_geq(tid, sbi->s_fc_ineligible_tid)) {
1767 		sbi->s_fc_ineligible_tid = 0;
1768 		ext4_clear_mount_flag(sb, EXT4_MF_FC_INELIGIBLE);
1769 	}
1770 
1771 	if (full)
1772 		sbi->s_fc_bytes = 0;
1773 	ext4_fc_unlock(sb, alloc_ctx);
1774 	trace_ext4_fc_stats(sb);
1775 }
1776 
1777 /* Ext4 Replay Path Routines */
1778 
1779 /* Helper struct for dentry replay routines */
1780 struct dentry_info_args {
1781 	int parent_ino, dname_len, ino, inode_len;
1782 	char *dname;
1783 };
1784 
1785 /* Same as struct ext4_fc_tl, but uses native endianness fields */
1786 struct ext4_fc_tl_mem {
1787 	u16 fc_tag;
1788 	u16 fc_len;
1789 };
1790 
1791 static inline void tl_to_darg(struct dentry_info_args *darg,
1792 			      struct ext4_fc_tl_mem *tl, u8 *val)
1793 {
1794 	struct ext4_fc_dentry_info fcd;
1795 
1796 	memcpy(&fcd, val, sizeof(fcd));
1797 
1798 	darg->parent_ino = le32_to_cpu(fcd.fc_parent_ino);
1799 	darg->ino = le32_to_cpu(fcd.fc_ino);
1800 	darg->dname = val + offsetof(struct ext4_fc_dentry_info, fc_dname);
1801 	darg->dname_len = tl->fc_len - sizeof(struct ext4_fc_dentry_info);
1802 }
1803 
1804 static inline void ext4_fc_get_tl(struct ext4_fc_tl_mem *tl, u8 *val)
1805 {
1806 	struct ext4_fc_tl tl_disk;
1807 
1808 	memcpy(&tl_disk, val, EXT4_FC_TAG_BASE_LEN);
1809 	tl->fc_len = le16_to_cpu(tl_disk.fc_len);
1810 	tl->fc_tag = le16_to_cpu(tl_disk.fc_tag);
1811 }
1812 
1813 /* Unlink replay function */
1814 static int ext4_fc_replay_unlink(struct super_block *sb,
1815 				 struct ext4_fc_tl_mem *tl, u8 *val)
1816 {
1817 	struct inode *inode, *old_parent;
1818 	struct qstr entry;
1819 	struct dentry_info_args darg;
1820 	int ret = 0;
1821 
1822 	tl_to_darg(&darg, tl, val);
1823 
1824 	trace_ext4_fc_replay(sb, EXT4_FC_TAG_UNLINK, darg.ino,
1825 			darg.parent_ino, darg.dname_len);
1826 
1827 	entry.name = darg.dname;
1828 	entry.len = darg.dname_len;
1829 	inode = ext4_iget(sb, darg.ino, EXT4_IGET_NORMAL);
1830 
1831 	if (IS_ERR(inode)) {
1832 		ext4_debug("Inode %d not found", darg.ino);
1833 		return 0;
1834 	}
1835 
1836 	old_parent = ext4_iget(sb, darg.parent_ino,
1837 				EXT4_IGET_NORMAL);
1838 	if (IS_ERR(old_parent)) {
1839 		ext4_debug("Dir with inode %d not found", darg.parent_ino);
1840 		iput(inode);
1841 		return 0;
1842 	}
1843 
1844 	ret = __ext4_unlink(old_parent, &entry, inode, NULL);
1845 	/* -ENOENT ok coz it might not exist anymore. */
1846 	if (ret == -ENOENT)
1847 		ret = 0;
1848 	iput(old_parent);
1849 	iput(inode);
1850 	return ret;
1851 }
1852 
1853 static int ext4_fc_replay_link_internal(struct super_block *sb,
1854 				struct dentry_info_args *darg,
1855 				struct inode *inode)
1856 {
1857 	struct inode *dir = NULL;
1858 	struct qstr qstr_dname = QSTR_INIT(darg->dname, darg->dname_len);
1859 	int ret = 0;
1860 
1861 	dir = ext4_iget(sb, darg->parent_ino, EXT4_IGET_NORMAL);
1862 	if (IS_ERR(dir)) {
1863 		ext4_debug("Dir with inode %d not found.", darg->parent_ino);
1864 		dir = NULL;
1865 		goto out;
1866 	}
1867 
1868 	ret = __ext4_link(dir, inode, &qstr_dname, NULL);
1869 	/*
1870 	 * It's possible that link already existed since data blocks
1871 	 * for the dir in question got persisted before we crashed OR
1872 	 * we replayed this tag and crashed before the entire replay
1873 	 * could complete.
1874 	 */
1875 	if (ret && ret != -EEXIST) {
1876 		ext4_debug("Failed to link\n");
1877 		goto out;
1878 	}
1879 
1880 	ret = 0;
1881 out:
1882 	if (dir)
1883 		iput(dir);
1884 
1885 	return ret;
1886 }
1887 
1888 /* Link replay function */
1889 static int ext4_fc_replay_link(struct super_block *sb,
1890 			       struct ext4_fc_tl_mem *tl, u8 *val)
1891 {
1892 	struct inode *inode;
1893 	struct dentry_info_args darg;
1894 	int ret = 0;
1895 
1896 	tl_to_darg(&darg, tl, val);
1897 	trace_ext4_fc_replay(sb, EXT4_FC_TAG_LINK, darg.ino,
1898 			darg.parent_ino, darg.dname_len);
1899 
1900 	inode = ext4_iget(sb, darg.ino, EXT4_IGET_NORMAL);
1901 	if (IS_ERR(inode)) {
1902 		ext4_debug("Inode not found.");
1903 		return 0;
1904 	}
1905 
1906 	ret = ext4_fc_replay_link_internal(sb, &darg, inode);
1907 	iput(inode);
1908 	return ret;
1909 }
1910 
1911 /*
1912  * Record all the modified inodes during replay. We use this later to setup
1913  * block bitmaps correctly.
1914  */
1915 static int ext4_fc_record_modified_inode(struct super_block *sb, int ino)
1916 {
1917 	struct ext4_fc_replay_state *state;
1918 	int i;
1919 
1920 	state = &EXT4_SB(sb)->s_fc_replay_state;
1921 	for (i = 0; i < state->fc_modified_inodes_used; i++)
1922 		if (state->fc_modified_inodes[i] == ino)
1923 			return 0;
1924 	if (state->fc_modified_inodes_used == state->fc_modified_inodes_size) {
1925 		int *fc_modified_inodes;
1926 
1927 		fc_modified_inodes = krealloc(state->fc_modified_inodes,
1928 				sizeof(int) * (state->fc_modified_inodes_size +
1929 				EXT4_FC_REPLAY_REALLOC_INCREMENT),
1930 				GFP_KERNEL);
1931 		if (!fc_modified_inodes)
1932 			return -ENOMEM;
1933 		state->fc_modified_inodes = fc_modified_inodes;
1934 		state->fc_modified_inodes_size +=
1935 			EXT4_FC_REPLAY_REALLOC_INCREMENT;
1936 	}
1937 	state->fc_modified_inodes[state->fc_modified_inodes_used++] = ino;
1938 	return 0;
1939 }
1940 
1941 /*
1942  * Inode replay function
1943  */
1944 static int ext4_fc_replay_inode(struct super_block *sb,
1945 				struct ext4_fc_tl_mem *tl, u8 *val)
1946 {
1947 	struct ext4_fc_inode fc_inode;
1948 	struct ext4_inode *raw_inode;
1949 	struct ext4_inode *raw_fc_inode;
1950 	struct inode *inode = NULL;
1951 	struct ext4_iloc iloc;
1952 	int inode_len, ino, ret, tag = tl->fc_tag;
1953 	struct ext4_extent_header *eh;
1954 	size_t off_gen = offsetof(struct ext4_inode, i_generation);
1955 
1956 	memcpy(&fc_inode, val, sizeof(fc_inode));
1957 
1958 	ino = le32_to_cpu(fc_inode.fc_ino);
1959 	trace_ext4_fc_replay(sb, tag, ino, 0, 0);
1960 
1961 	inode = ext4_iget(sb, ino, EXT4_IGET_NORMAL);
1962 	if (!IS_ERR(inode)) {
1963 		ret = ext4_ext_clear_bb(inode);
1964 		iput(inode);
1965 		inode = NULL;
1966 		if (ret)
1967 			goto out;
1968 	}
1969 	inode = NULL;
1970 
1971 	ret = ext4_fc_record_modified_inode(sb, ino);
1972 	if (ret)
1973 		goto out;
1974 
1975 	raw_fc_inode = (struct ext4_inode *)
1976 		(val + offsetof(struct ext4_fc_inode, fc_raw_inode));
1977 	ret = ext4_get_fc_inode_loc(sb, ino, &iloc);
1978 	if (ret)
1979 		goto out;
1980 
1981 	inode_len = tl->fc_len - sizeof(struct ext4_fc_inode);
1982 	raw_inode = ext4_raw_inode(&iloc);
1983 
1984 	memcpy(raw_inode, raw_fc_inode, offsetof(struct ext4_inode, i_block));
1985 	memcpy((u8 *)raw_inode + off_gen, (u8 *)raw_fc_inode + off_gen,
1986 	       inode_len - off_gen);
1987 	if (le32_to_cpu(raw_inode->i_flags) & EXT4_EXTENTS_FL) {
1988 		eh = (struct ext4_extent_header *)(&raw_inode->i_block[0]);
1989 		if (eh->eh_magic != EXT4_EXT_MAGIC) {
1990 			memset(eh, 0, sizeof(*eh));
1991 			eh->eh_magic = EXT4_EXT_MAGIC;
1992 			eh->eh_max = cpu_to_le16(
1993 				(sizeof(raw_inode->i_block) -
1994 				 sizeof(struct ext4_extent_header))
1995 				 / sizeof(struct ext4_extent));
1996 		}
1997 	} else if (le32_to_cpu(raw_inode->i_flags) & EXT4_INLINE_DATA_FL) {
1998 		memcpy(raw_inode->i_block, raw_fc_inode->i_block,
1999 			sizeof(raw_inode->i_block));
2000 	}
2001 
2002 	/* Immediately update the inode on disk. */
2003 	ret = ext4_handle_dirty_metadata(NULL, NULL, iloc.bh);
2004 	if (ret)
2005 		goto out_brelse;
2006 	ret = sync_dirty_buffer(iloc.bh);
2007 	if (ret)
2008 		goto out_brelse;
2009 	ret = ext4_mark_inode_used(sb, ino);
2010 	if (ret)
2011 		goto out_brelse;
2012 
2013 	/* Given that we just wrote the inode on disk, this SHOULD succeed. */
2014 	inode = ext4_iget(sb, ino, EXT4_IGET_NORMAL);
2015 	if (IS_ERR(inode)) {
2016 		ext4_debug("Inode not found.");
2017 		inode = NULL;
2018 		ret = -EFSCORRUPTED;
2019 		goto out_brelse;
2020 	}
2021 
2022 	/*
2023 	 * Our allocator could have made different decisions than before
2024 	 * crashing. This should be fixed but until then, we calculate
2025 	 * the number of blocks the inode.
2026 	 */
2027 	if (!ext4_test_inode_flag(inode, EXT4_INODE_INLINE_DATA)) {
2028 		ret = ext4_ext_replay_set_iblocks(inode);
2029 		if (ret)
2030 			goto out_brelse;
2031 	}
2032 
2033 	inode->i_generation = le32_to_cpu(ext4_raw_inode(&iloc)->i_generation);
2034 	ext4_reset_inode_seed(inode);
2035 
2036 	ext4_inode_csum_set(inode, ext4_raw_inode(&iloc), EXT4_I(inode));
2037 	ret = ext4_handle_dirty_metadata(NULL, NULL, iloc.bh);
2038 	sync_dirty_buffer(iloc.bh);
2039 out_brelse:
2040 	brelse(iloc.bh);
2041 out:
2042 	iput(inode);
2043 	if (!ret)
2044 		ext4_fc_issue_flush(sb->s_bdev);
2045 
2046 	return ret;
2047 }
2048 
2049 /*
2050  * Dentry create replay function.
2051  *
2052  * EXT4_FC_TAG_CREAT is preceded by EXT4_FC_TAG_INODE_FULL. Which means, the
2053  * inode for which we are trying to create a dentry here, should already have
2054  * been replayed before we start here.
2055  */
2056 static int ext4_fc_replay_create(struct super_block *sb,
2057 				 struct ext4_fc_tl_mem *tl, u8 *val)
2058 {
2059 	int ret = 0;
2060 	struct inode *inode = NULL;
2061 	struct inode *dir = NULL;
2062 	struct dentry_info_args darg;
2063 
2064 	tl_to_darg(&darg, tl, val);
2065 
2066 	trace_ext4_fc_replay(sb, EXT4_FC_TAG_CREAT, darg.ino,
2067 			darg.parent_ino, darg.dname_len);
2068 
2069 	/* This takes care of update group descriptor and other metadata */
2070 	ret = ext4_mark_inode_used(sb, darg.ino);
2071 	if (ret)
2072 		goto out;
2073 
2074 	inode = ext4_iget(sb, darg.ino, EXT4_IGET_NORMAL);
2075 	if (IS_ERR(inode)) {
2076 		ext4_debug("inode %d not found.", darg.ino);
2077 		inode = NULL;
2078 		ret = -EINVAL;
2079 		goto out;
2080 	}
2081 
2082 	if (S_ISDIR(inode->i_mode)) {
2083 		/*
2084 		 * If we are creating a directory, we need to make sure that the
2085 		 * dot and dot dot dirents are setup properly.
2086 		 */
2087 		dir = ext4_iget(sb, darg.parent_ino, EXT4_IGET_NORMAL);
2088 		if (IS_ERR(dir)) {
2089 			ext4_debug("Dir %d not found.", darg.ino);
2090 			ret = PTR_ERR(dir);
2091 			goto out;
2092 		}
2093 		ret = ext4_init_new_dir(NULL, dir, inode);
2094 		iput(dir);
2095 		if (ret) {
2096 			goto out;
2097 		}
2098 	}
2099 	ret = ext4_fc_replay_link_internal(sb, &darg, inode);
2100 	if (ret)
2101 		goto out;
2102 	set_nlink(inode, 1);
2103 	ret = ext4_mark_inode_dirty(NULL, inode);
2104 out:
2105 	iput(inode);
2106 	return ret;
2107 }
2108 
2109 /*
2110  * Record physical disk regions which are in use as per fast commit area,
2111  * and used by inodes during replay phase. Our simple replay phase
2112  * allocator excludes these regions from allocation.
2113  */
2114 int ext4_fc_record_regions(struct super_block *sb, int ino,
2115 		ext4_lblk_t lblk, ext4_fsblk_t pblk, int len, int replay)
2116 {
2117 	struct ext4_fc_replay_state *state;
2118 	struct ext4_fc_alloc_region *region;
2119 
2120 	state = &EXT4_SB(sb)->s_fc_replay_state;
2121 	/*
2122 	 * during replay phase, the fc_regions_valid may not same as
2123 	 * fc_regions_used, update it when do new additions.
2124 	 */
2125 	if (replay && state->fc_regions_used != state->fc_regions_valid)
2126 		state->fc_regions_used = state->fc_regions_valid;
2127 	if (state->fc_regions_used == state->fc_regions_size) {
2128 		struct ext4_fc_alloc_region *fc_regions;
2129 
2130 		fc_regions = krealloc(state->fc_regions,
2131 				      sizeof(struct ext4_fc_alloc_region) *
2132 				      (state->fc_regions_size +
2133 				       EXT4_FC_REPLAY_REALLOC_INCREMENT),
2134 				      GFP_KERNEL);
2135 		if (!fc_regions)
2136 			return -ENOMEM;
2137 		state->fc_regions_size +=
2138 			EXT4_FC_REPLAY_REALLOC_INCREMENT;
2139 		state->fc_regions = fc_regions;
2140 	}
2141 	region = &state->fc_regions[state->fc_regions_used++];
2142 	region->ino = ino;
2143 	region->lblk = lblk;
2144 	region->pblk = pblk;
2145 	region->len = len;
2146 
2147 	if (replay)
2148 		state->fc_regions_valid++;
2149 
2150 	return 0;
2151 }
2152 
2153 /* Replay add range tag */
2154 static int ext4_fc_replay_add_range(struct super_block *sb, u8 *val)
2155 {
2156 	struct ext4_fc_add_range fc_add_ex;
2157 	struct ext4_extent newex, *ex;
2158 	struct inode *inode;
2159 	ext4_lblk_t start, cur;
2160 	int remaining, len;
2161 	ext4_fsblk_t start_pblk;
2162 	struct ext4_map_blocks map;
2163 	struct ext4_ext_path *path = NULL;
2164 	int ret;
2165 
2166 	memcpy(&fc_add_ex, val, sizeof(fc_add_ex));
2167 	ex = (struct ext4_extent *)&fc_add_ex.fc_ex;
2168 
2169 	trace_ext4_fc_replay(sb, EXT4_FC_TAG_ADD_RANGE,
2170 		le32_to_cpu(fc_add_ex.fc_ino), le32_to_cpu(ex->ee_block),
2171 		ext4_ext_get_actual_len(ex));
2172 
2173 	inode = ext4_iget(sb, le32_to_cpu(fc_add_ex.fc_ino), EXT4_IGET_NORMAL);
2174 	if (IS_ERR(inode)) {
2175 		ext4_debug("Inode not found.");
2176 		return 0;
2177 	}
2178 
2179 	ret = ext4_fc_record_modified_inode(sb, inode->i_ino);
2180 	if (ret)
2181 		goto out;
2182 
2183 	start = le32_to_cpu(ex->ee_block);
2184 	start_pblk = ext4_ext_pblock(ex);
2185 	len = ext4_ext_get_actual_len(ex);
2186 
2187 	cur = start;
2188 	remaining = len;
2189 	ext4_debug("ADD_RANGE, lblk %d, pblk %lld, len %d, unwritten %d, inode %llu\n",
2190 		  start, start_pblk, len, ext4_ext_is_unwritten(ex),
2191 		  inode->i_ino);
2192 
2193 	while (remaining > 0) {
2194 		map.m_lblk = cur;
2195 		map.m_len = remaining;
2196 		map.m_pblk = 0;
2197 		ret = ext4_map_blocks(NULL, inode, &map, 0);
2198 
2199 		if (ret < 0)
2200 			goto out;
2201 
2202 		if (ret == 0) {
2203 			/* Range is not mapped */
2204 			path = ext4_find_extent(inode, cur, path, 0);
2205 			if (IS_ERR(path)) {
2206 				ret = PTR_ERR(path);
2207 				path = NULL;
2208 				goto out;
2209 			}
2210 			memset(&newex, 0, sizeof(newex));
2211 			newex.ee_block = cpu_to_le32(cur);
2212 			ext4_ext_store_pblock(
2213 				&newex, start_pblk + cur - start);
2214 			newex.ee_len = cpu_to_le16(map.m_len);
2215 			if (ext4_ext_is_unwritten(ex))
2216 				ext4_ext_mark_unwritten(&newex);
2217 			down_write(&EXT4_I(inode)->i_data_sem);
2218 			path = ext4_ext_insert_extent(NULL, inode,
2219 						      path, &newex, 0);
2220 			up_write((&EXT4_I(inode)->i_data_sem));
2221 			if (IS_ERR(path)) {
2222 				ret = PTR_ERR(path);
2223 				path = NULL;
2224 				goto out;
2225 			}
2226 			goto next;
2227 		}
2228 
2229 		if (start_pblk + cur - start != map.m_pblk) {
2230 			/*
2231 			 * Logical to physical mapping changed. This can happen
2232 			 * if this range was removed and then reallocated to
2233 			 * map to new physical blocks during a fast commit.
2234 			 */
2235 			ret = ext4_ext_replay_update_ex(inode, cur, map.m_len,
2236 					ext4_ext_is_unwritten(ex),
2237 					start_pblk + cur - start);
2238 			if (ret)
2239 				goto out;
2240 			/*
2241 			 * Mark the old blocks as free since they aren't used
2242 			 * anymore. We maintain an array of all the modified
2243 			 * inodes. In case these blocks are still used at either
2244 			 * a different logical range in the same inode or in
2245 			 * some different inode, we will mark them as allocated
2246 			 * at the end of the FC replay using our array of
2247 			 * modified inodes.
2248 			 */
2249 			ext4_mb_mark_bb(inode->i_sb, map.m_pblk, map.m_len, false);
2250 			goto next;
2251 		}
2252 
2253 		/* Range is mapped and needs a state change */
2254 		ext4_debug("Converting from %ld to %d %lld",
2255 				map.m_flags & EXT4_MAP_UNWRITTEN,
2256 			ext4_ext_is_unwritten(ex), map.m_pblk);
2257 		ret = ext4_ext_replay_update_ex(inode, cur, map.m_len,
2258 					ext4_ext_is_unwritten(ex), map.m_pblk);
2259 		if (ret)
2260 			goto out;
2261 		/*
2262 		 * We may have split the extent tree while toggling the state.
2263 		 * Try to shrink the extent tree now.
2264 		 */
2265 		ext4_ext_replay_shrink_inode(inode, start + len);
2266 next:
2267 		cur += map.m_len;
2268 		remaining -= map.m_len;
2269 	}
2270 	ext4_ext_replay_shrink_inode(inode, i_size_read(inode) >>
2271 					sb->s_blocksize_bits);
2272 	ret = 0;
2273 out:
2274 	ext4_free_ext_path(path);
2275 	iput(inode);
2276 	return ret;
2277 }
2278 
2279 /* Replay DEL_RANGE tag */
2280 static int
2281 ext4_fc_replay_del_range(struct super_block *sb, u8 *val)
2282 {
2283 	struct inode *inode;
2284 	struct ext4_fc_del_range lrange;
2285 	struct ext4_map_blocks map;
2286 	ext4_lblk_t cur, remaining;
2287 	int ret;
2288 
2289 	memcpy(&lrange, val, sizeof(lrange));
2290 	cur = le32_to_cpu(lrange.fc_lblk);
2291 	remaining = le32_to_cpu(lrange.fc_len);
2292 
2293 	trace_ext4_fc_replay(sb, EXT4_FC_TAG_DEL_RANGE,
2294 		le32_to_cpu(lrange.fc_ino), cur, remaining);
2295 
2296 	inode = ext4_iget(sb, le32_to_cpu(lrange.fc_ino), EXT4_IGET_NORMAL);
2297 	if (IS_ERR(inode)) {
2298 		ext4_debug("Inode %d not found", le32_to_cpu(lrange.fc_ino));
2299 		return 0;
2300 	}
2301 
2302 	ret = ext4_fc_record_modified_inode(sb, inode->i_ino);
2303 	if (ret)
2304 		goto out;
2305 
2306 	ext4_debug("DEL_RANGE, inode %llu, lblk %d, len %d\n",
2307 			inode->i_ino, le32_to_cpu(lrange.fc_lblk),
2308 			le32_to_cpu(lrange.fc_len));
2309 	while (remaining > 0) {
2310 		map.m_lblk = cur;
2311 		map.m_len = remaining;
2312 
2313 		ret = ext4_map_blocks(NULL, inode, &map, 0);
2314 		if (ret < 0)
2315 			goto out;
2316 		if (ret > 0) {
2317 			remaining -= ret;
2318 			cur += ret;
2319 			ext4_mb_mark_bb(inode->i_sb, map.m_pblk, map.m_len, false);
2320 		} else {
2321 			remaining -= map.m_len;
2322 			cur += map.m_len;
2323 		}
2324 	}
2325 
2326 	down_write(&EXT4_I(inode)->i_data_sem);
2327 	ret = ext4_ext_remove_space(inode, le32_to_cpu(lrange.fc_lblk),
2328 				le32_to_cpu(lrange.fc_lblk) +
2329 				le32_to_cpu(lrange.fc_len) - 1);
2330 	up_write(&EXT4_I(inode)->i_data_sem);
2331 	if (ret)
2332 		goto out;
2333 	ext4_ext_replay_shrink_inode(inode,
2334 		i_size_read(inode) >> sb->s_blocksize_bits);
2335 	ext4_mark_inode_dirty(NULL, inode);
2336 	ret = 0;
2337 out:
2338 	iput(inode);
2339 	return ret;
2340 }
2341 
2342 static int ext4_fc_set_bitmaps_and_counters(struct super_block *sb)
2343 {
2344 	struct ext4_fc_replay_state *state;
2345 	struct inode *inode;
2346 	struct ext4_ext_path *path = NULL;
2347 	struct ext4_map_blocks map;
2348 	int i, ret = 0, j;
2349 	ext4_lblk_t cur, end;
2350 
2351 	state = &EXT4_SB(sb)->s_fc_replay_state;
2352 	for (i = 0; i < state->fc_modified_inodes_used; i++) {
2353 		inode = ext4_iget(sb, state->fc_modified_inodes[i],
2354 			EXT4_IGET_NORMAL);
2355 		if (IS_ERR(inode)) {
2356 			ext4_debug("Inode %d not found.",
2357 				state->fc_modified_inodes[i]);
2358 			continue;
2359 		}
2360 		cur = 0;
2361 		end = EXT_MAX_BLOCKS;
2362 		if (ext4_test_inode_flag(inode, EXT4_INODE_INLINE_DATA)) {
2363 			iput(inode);
2364 			continue;
2365 		}
2366 		while (cur < end) {
2367 			map.m_lblk = cur;
2368 			map.m_len = end - cur;
2369 
2370 			ret = ext4_map_blocks(NULL, inode, &map, 0);
2371 			if (ret < 0)
2372 				break;
2373 
2374 			if (ret > 0) {
2375 				path = ext4_find_extent(inode, map.m_lblk, path, 0);
2376 				if (IS_ERR(path)) {
2377 					ret = PTR_ERR(path);
2378 					path = NULL;
2379 					break;
2380 				}
2381 				for (j = 0; j < path->p_depth; j++)
2382 					ext4_mb_mark_bb(inode->i_sb,
2383 							path[j].p_block, 1, true);
2384 				cur += ret;
2385 				ext4_mb_mark_bb(inode->i_sb, map.m_pblk,
2386 							map.m_len, true);
2387 			} else {
2388 				cur = cur + (map.m_len ? map.m_len : 1);
2389 			}
2390 		}
2391 		iput(inode);
2392 		if (ret < 0)
2393 			goto out;
2394 	}
2395 
2396 	ret = 0;
2397 out:
2398 	ext4_free_ext_path(path);
2399 	return ret;
2400 }
2401 
2402 /*
2403  * Check if block is in excluded regions for block allocation. The simple
2404  * allocator that runs during replay phase is calls this function to see
2405  * if it is okay to use a block.
2406  */
2407 bool ext4_fc_replay_check_excluded(struct super_block *sb, ext4_fsblk_t blk)
2408 {
2409 	int i;
2410 	struct ext4_fc_replay_state *state;
2411 
2412 	state = &EXT4_SB(sb)->s_fc_replay_state;
2413 	for (i = 0; i < state->fc_regions_valid; i++) {
2414 		if (state->fc_regions[i].ino == 0 ||
2415 			state->fc_regions[i].len == 0)
2416 			continue;
2417 		if (in_range(blk, state->fc_regions[i].pblk,
2418 					state->fc_regions[i].len))
2419 			return true;
2420 	}
2421 	return false;
2422 }
2423 
2424 /* Cleanup function called after replay */
2425 void ext4_fc_replay_cleanup(struct super_block *sb)
2426 {
2427 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2428 
2429 	sbi->s_mount_state &= ~EXT4_FC_REPLAY;
2430 	kfree(sbi->s_fc_replay_state.fc_regions);
2431 	sbi->s_fc_replay_state.fc_regions = NULL;
2432 	kfree(sbi->s_fc_replay_state.fc_modified_inodes);
2433 	sbi->s_fc_replay_state.fc_modified_inodes = NULL;
2434 }
2435 
2436 static bool ext4_fc_value_len_isvalid(struct ext4_sb_info *sbi,
2437 				      int tag, int len)
2438 {
2439 	switch (tag) {
2440 	case EXT4_FC_TAG_ADD_RANGE:
2441 		return len == sizeof(struct ext4_fc_add_range);
2442 	case EXT4_FC_TAG_DEL_RANGE:
2443 		return len == sizeof(struct ext4_fc_del_range);
2444 	case EXT4_FC_TAG_CREAT:
2445 	case EXT4_FC_TAG_LINK:
2446 	case EXT4_FC_TAG_UNLINK:
2447 		len -= sizeof(struct ext4_fc_dentry_info);
2448 		return len >= 1 && len <= EXT4_NAME_LEN;
2449 	case EXT4_FC_TAG_INODE:
2450 		len -= sizeof(struct ext4_fc_inode);
2451 		return len >= EXT4_GOOD_OLD_INODE_SIZE &&
2452 			len <= sbi->s_inode_size;
2453 	case EXT4_FC_TAG_PAD:
2454 		return true; /* padding can have any length */
2455 	case EXT4_FC_TAG_TAIL:
2456 		return len >= sizeof(struct ext4_fc_tail);
2457 	case EXT4_FC_TAG_HEAD:
2458 		return len == sizeof(struct ext4_fc_head);
2459 	}
2460 	return false;
2461 }
2462 
2463 /*
2464  * Recovery Scan phase handler
2465  *
2466  * This function is called during the scan phase and is responsible
2467  * for doing following things:
2468  * - Make sure the fast commit area has valid tags for replay
2469  * - Count number of tags that need to be replayed by the replay handler
2470  * - Verify CRC
2471  * - Create a list of excluded blocks for allocation during replay phase
2472  *
2473  * This function returns JBD2_FC_REPLAY_CONTINUE to indicate that SCAN is
2474  * incomplete and JBD2 should send more blocks. It returns JBD2_FC_REPLAY_STOP
2475  * to indicate that scan has finished and JBD2 can now start replay phase.
2476  * It returns a negative error to indicate that there was an error. At the end
2477  * of a successful scan phase, sbi->s_fc_replay_state.fc_replay_num_tags is set
2478  * to indicate the number of tags that need to replayed during the replay phase.
2479  *
2480  * An invalid tag or a tail that does not match ends the scan without an error.
2481  * This is what a fast commit that was only partially written before a crash
2482  * looks like.  Its tail is written last and fsync() does not return before
2483  * the tail is on disk, so such a fast commit was never reported as durable and
2484  * is simply dropped, like jbd2 drops a transaction without a commit block.
2485  */
2486 static int ext4_fc_replay_scan(journal_t *journal,
2487 				struct buffer_head *bh, int off,
2488 				tid_t expected_tid)
2489 {
2490 	struct super_block *sb = journal->j_private;
2491 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2492 	struct ext4_fc_replay_state *state;
2493 	int ret = JBD2_FC_REPLAY_CONTINUE;
2494 	struct ext4_fc_add_range ext;
2495 	struct ext4_fc_tl_mem tl;
2496 	struct ext4_fc_tail tail;
2497 	__u8 *start, *end, *cur, *val;
2498 	struct ext4_fc_head head;
2499 	struct ext4_extent *ex;
2500 
2501 	state = &sbi->s_fc_replay_state;
2502 
2503 	start = (u8 *)bh->b_data;
2504 	end = start + journal->j_blocksize;
2505 
2506 	if (state->fc_replay_expected_off == 0) {
2507 		state->fc_cur_tag = 0;
2508 		state->fc_replay_num_tags = 0;
2509 		state->fc_crc = 0;
2510 		state->fc_regions = NULL;
2511 		state->fc_regions_valid = state->fc_regions_used =
2512 			state->fc_regions_size = 0;
2513 		/* Check if we can stop early */
2514 		if (le16_to_cpu(((struct ext4_fc_tl *)start)->fc_tag)
2515 			!= EXT4_FC_TAG_HEAD)
2516 			return 0;
2517 	}
2518 
2519 	if (off != state->fc_replay_expected_off) {
2520 		ret = -EFSCORRUPTED;
2521 		goto out_err;
2522 	}
2523 
2524 	state->fc_replay_expected_off++;
2525 	for (cur = start; cur <= end - EXT4_FC_TAG_BASE_LEN;
2526 	     cur = cur + EXT4_FC_TAG_BASE_LEN + tl.fc_len) {
2527 		ext4_fc_get_tl(&tl, cur);
2528 		val = cur + EXT4_FC_TAG_BASE_LEN;
2529 		if (tl.fc_len > end - val ||
2530 		    !ext4_fc_value_len_isvalid(sbi, tl.fc_tag, tl.fc_len)) {
2531 			ext4_debug("Scan phase, invalid tag length, blk %lld\n",
2532 				   bh->b_blocknr);
2533 			ret = JBD2_FC_REPLAY_STOP;
2534 			goto out_err;
2535 		}
2536 		ext4_debug("Scan phase, tag:%s, blk %lld\n",
2537 			   tag2str(tl.fc_tag), bh->b_blocknr);
2538 		switch (tl.fc_tag) {
2539 		case EXT4_FC_TAG_ADD_RANGE:
2540 			memcpy(&ext, val, sizeof(ext));
2541 			ex = (struct ext4_extent *)&ext.fc_ex;
2542 			ret = ext4_fc_record_regions(sb,
2543 				le32_to_cpu(ext.fc_ino),
2544 				le32_to_cpu(ex->ee_block), ext4_ext_pblock(ex),
2545 				ext4_ext_get_actual_len(ex), 0);
2546 			if (ret < 0)
2547 				break;
2548 			ret = JBD2_FC_REPLAY_CONTINUE;
2549 			fallthrough;
2550 		case EXT4_FC_TAG_DEL_RANGE:
2551 		case EXT4_FC_TAG_LINK:
2552 		case EXT4_FC_TAG_UNLINK:
2553 		case EXT4_FC_TAG_CREAT:
2554 		case EXT4_FC_TAG_INODE:
2555 		case EXT4_FC_TAG_PAD:
2556 			state->fc_cur_tag++;
2557 			state->fc_crc = ext4_chksum(state->fc_crc, cur,
2558 				EXT4_FC_TAG_BASE_LEN + tl.fc_len);
2559 			break;
2560 		case EXT4_FC_TAG_TAIL:
2561 			state->fc_cur_tag++;
2562 			memcpy(&tail, val, sizeof(tail));
2563 			state->fc_crc = ext4_chksum(state->fc_crc, cur,
2564 						EXT4_FC_TAG_BASE_LEN +
2565 						offsetof(struct ext4_fc_tail,
2566 						fc_crc));
2567 			if (le32_to_cpu(tail.fc_tid) == expected_tid &&
2568 				le32_to_cpu(tail.fc_crc) == state->fc_crc) {
2569 				state->fc_replay_num_tags = state->fc_cur_tag;
2570 				state->fc_regions_valid =
2571 					state->fc_regions_used;
2572 			} else {
2573 				ext4_debug("Scan phase, invalid tail, blk %lld\n",
2574 					   bh->b_blocknr);
2575 				ret = JBD2_FC_REPLAY_STOP;
2576 			}
2577 			state->fc_crc = 0;
2578 			break;
2579 		case EXT4_FC_TAG_HEAD:
2580 			memcpy(&head, val, sizeof(head));
2581 			if (le32_to_cpu(head.fc_features) &
2582 				~EXT4_FC_SUPPORTED_FEATURES) {
2583 				ret = -EOPNOTSUPP;
2584 				break;
2585 			}
2586 			if (le32_to_cpu(head.fc_tid) != expected_tid) {
2587 				ret = JBD2_FC_REPLAY_STOP;
2588 				break;
2589 			}
2590 			state->fc_cur_tag++;
2591 			state->fc_crc = ext4_chksum(state->fc_crc, cur,
2592 				EXT4_FC_TAG_BASE_LEN + tl.fc_len);
2593 			break;
2594 		default:
2595 			ext4_debug("Scan phase, unknown tag %d, blk %lld\n",
2596 				   tl.fc_tag, bh->b_blocknr);
2597 			ret = JBD2_FC_REPLAY_STOP;
2598 		}
2599 		if (ret < 0 || ret == JBD2_FC_REPLAY_STOP)
2600 			break;
2601 	}
2602 
2603 out_err:
2604 	trace_ext4_fc_replay_scan(sb, ret, off);
2605 	return ret;
2606 }
2607 
2608 /*
2609  * Main recovery path entry point.
2610  * The meaning of return codes is similar as above.
2611  */
2612 static int ext4_fc_replay(journal_t *journal, struct buffer_head *bh,
2613 				enum passtype pass, int off, tid_t expected_tid)
2614 {
2615 	struct super_block *sb = journal->j_private;
2616 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2617 	struct ext4_fc_tl_mem tl;
2618 	__u8 *start, *end, *cur, *val;
2619 	int ret = JBD2_FC_REPLAY_CONTINUE;
2620 	struct ext4_fc_replay_state *state = &sbi->s_fc_replay_state;
2621 	struct ext4_fc_tail tail;
2622 
2623 	if (pass == PASS_SCAN) {
2624 		state->fc_current_pass = PASS_SCAN;
2625 		return ext4_fc_replay_scan(journal, bh, off, expected_tid);
2626 	}
2627 
2628 	if (state->fc_current_pass != pass) {
2629 		state->fc_current_pass = pass;
2630 		sbi->s_mount_state |= EXT4_FC_REPLAY;
2631 	}
2632 	if (!sbi->s_fc_replay_state.fc_replay_num_tags) {
2633 		ext4_debug("Replay stops\n");
2634 		return ext4_fc_set_bitmaps_and_counters(sb);
2635 	}
2636 
2637 #ifdef CONFIG_EXT4_DEBUG
2638 	if (sbi->s_fc_debug_max_replay && off >= sbi->s_fc_debug_max_replay) {
2639 		pr_warn("Dropping fc block %d because max_replay set\n", off);
2640 		return JBD2_FC_REPLAY_STOP;
2641 	}
2642 #endif
2643 
2644 	start = (u8 *)bh->b_data;
2645 	end = start + journal->j_blocksize;
2646 
2647 	for (cur = start; cur <= end - EXT4_FC_TAG_BASE_LEN;
2648 	     cur = cur + EXT4_FC_TAG_BASE_LEN + tl.fc_len) {
2649 		ext4_fc_get_tl(&tl, cur);
2650 		val = cur + EXT4_FC_TAG_BASE_LEN;
2651 
2652 		if (state->fc_replay_num_tags == 0) {
2653 			ret = ext4_fc_set_bitmaps_and_counters(sb);
2654 			break;
2655 		}
2656 
2657 		ext4_debug("Replay phase, tag:%s\n", tag2str(tl.fc_tag));
2658 		state->fc_replay_num_tags--;
2659 		switch (tl.fc_tag) {
2660 		case EXT4_FC_TAG_LINK:
2661 			ret = ext4_fc_replay_link(sb, &tl, val);
2662 			break;
2663 		case EXT4_FC_TAG_UNLINK:
2664 			ret = ext4_fc_replay_unlink(sb, &tl, val);
2665 			break;
2666 		case EXT4_FC_TAG_ADD_RANGE:
2667 			ret = ext4_fc_replay_add_range(sb, val);
2668 			break;
2669 		case EXT4_FC_TAG_CREAT:
2670 			ret = ext4_fc_replay_create(sb, &tl, val);
2671 			break;
2672 		case EXT4_FC_TAG_DEL_RANGE:
2673 			ret = ext4_fc_replay_del_range(sb, val);
2674 			break;
2675 		case EXT4_FC_TAG_INODE:
2676 			ret = ext4_fc_replay_inode(sb, &tl, val);
2677 			break;
2678 		case EXT4_FC_TAG_PAD:
2679 			trace_ext4_fc_replay(sb, EXT4_FC_TAG_PAD, 0,
2680 					     tl.fc_len, 0);
2681 			break;
2682 		case EXT4_FC_TAG_TAIL:
2683 			trace_ext4_fc_replay(sb, EXT4_FC_TAG_TAIL,
2684 					     0, tl.fc_len, 0);
2685 			memcpy(&tail, val, sizeof(tail));
2686 			WARN_ON(le32_to_cpu(tail.fc_tid) != expected_tid);
2687 			break;
2688 		case EXT4_FC_TAG_HEAD:
2689 			break;
2690 		default:
2691 			trace_ext4_fc_replay(sb, tl.fc_tag, 0, tl.fc_len, 0);
2692 			ret = -ECANCELED;
2693 			break;
2694 		}
2695 		if (ret < 0)
2696 			break;
2697 		ret = JBD2_FC_REPLAY_CONTINUE;
2698 	}
2699 	return ret;
2700 }
2701 
2702 void ext4_fc_init(struct super_block *sb, journal_t *journal)
2703 {
2704 	/*
2705 	 * We set replay callback even if fast commit disabled because we may
2706 	 * could still have fast commit blocks that need to be replayed even if
2707 	 * fast commit has now been turned off.
2708 	 */
2709 	journal->j_fc_replay_callback = ext4_fc_replay;
2710 	if (!test_opt2(sb, JOURNAL_FAST_COMMIT))
2711 		return;
2712 	journal->j_fc_cleanup_callback = ext4_fc_cleanup;
2713 }
2714 
2715 static const char * const fc_ineligible_reasons[] = {
2716 	[EXT4_FC_REASON_XATTR] = "Extended attributes changed",
2717 	[EXT4_FC_REASON_CROSS_RENAME] = "Cross rename",
2718 	[EXT4_FC_REASON_JOURNAL_FLAG_CHANGE] = "Journal flag changed",
2719 	[EXT4_FC_REASON_NOMEM] = "Insufficient memory",
2720 	[EXT4_FC_REASON_SWAP_BOOT] = "Swap boot",
2721 	[EXT4_FC_REASON_RESIZE] = "Resize",
2722 	[EXT4_FC_REASON_RENAME_DIR] = "Dir renamed",
2723 	[EXT4_FC_REASON_FALLOC_RANGE] = "Falloc range op",
2724 	[EXT4_FC_REASON_INODE_JOURNAL_DATA] = "Data journalling",
2725 	[EXT4_FC_REASON_ENCRYPTED_FILENAME] = "Encrypted filename",
2726 	[EXT4_FC_REASON_MIGRATE] = "Inode format migration",
2727 	[EXT4_FC_REASON_VERITY] = "fs-verity enable",
2728 	[EXT4_FC_REASON_MOVE_EXT] = "Move extents",
2729 };
2730 
2731 int ext4_fc_info_show(struct seq_file *seq, void *v)
2732 {
2733 	struct ext4_sb_info *sbi = EXT4_SB((struct super_block *)seq->private);
2734 	struct ext4_fc_stats *stats = &sbi->s_fc_stats;
2735 	struct ext4_fc_snap_stats *snap_stats = &sbi->s_fc_snap_stats;
2736 	u64 lock_avg_ns = 0;
2737 	u64 lock_updates_samples;
2738 	u64 lock_updates_ns_total;
2739 	u64 lock_updates_ns_max;
2740 	int i;
2741 
2742 	if (v != SEQ_START_TOKEN)
2743 		return 0;
2744 
2745 	lock_updates_samples =
2746 		atomic64_read(&snap_stats->lock_updates_samples);
2747 	lock_updates_ns_total =
2748 		atomic64_read(&snap_stats->lock_updates_ns_total);
2749 	lock_updates_ns_max =
2750 		atomic64_read(&snap_stats->lock_updates_ns_max);
2751 	if (lock_updates_samples)
2752 		lock_avg_ns = div64_u64(lock_updates_ns_total,
2753 					lock_updates_samples);
2754 
2755 	seq_printf(seq,
2756 		"fc stats:\n%ld commits\n%ld ineligible\n%ld numblks\n%lluus avg_commit_time\n",
2757 		   stats->fc_num_commits, stats->fc_ineligible_commits,
2758 		   stats->fc_numblks,
2759 		   div_u64(stats->s_fc_avg_commit_time, 1000));
2760 	seq_puts(seq, "Ineligible reasons:\n");
2761 	for (i = 0; i < EXT4_FC_REASON_MAX; i++)
2762 		seq_printf(seq, "\"%s\":\t%d\n", fc_ineligible_reasons[i],
2763 			stats->fc_ineligible_reason_count[i]);
2764 
2765 	seq_printf(seq,
2766 		   "Snapshot stats:\n%llu inodes\n%llu ranges\n%lluus lock_updates_avg\n%lluus lock_updates_max\n",
2767 		   atomic64_read(&snap_stats->snap_inodes),
2768 		   atomic64_read(&snap_stats->snap_ranges),
2769 		   div_u64(lock_avg_ns, 1000),
2770 		   div_u64(lock_updates_ns_max, 1000));
2771 	seq_printf(seq,
2772 		   "Snapshot failures:\n%llu es_miss\n%llu es_delayed\n%llu es_other\n%llu inodes_cap\n%llu ranges_cap\n%llu nomem\n%llu inode_loc\n%llu no_snap\n",
2773 		   atomic64_read(&snap_stats->snap_fail_es_miss),
2774 		   atomic64_read(&snap_stats->snap_fail_es_delayed),
2775 		   atomic64_read(&snap_stats->snap_fail_es_other),
2776 		   atomic64_read(&snap_stats->snap_fail_inodes_cap),
2777 		   atomic64_read(&snap_stats->snap_fail_ranges_cap),
2778 		   atomic64_read(&snap_stats->snap_fail_nomem),
2779 		   atomic64_read(&snap_stats->snap_fail_inode_loc),
2780 		   atomic64_read(&snap_stats->snap_fail_no_snap));
2781 
2782 	return 0;
2783 }
2784 
2785 int __init ext4_fc_init_dentry_cache(void)
2786 {
2787 	ext4_fc_dentry_cachep = KMEM_CACHE(ext4_fc_dentry_update,
2788 					   SLAB_RECLAIM_ACCOUNT);
2789 
2790 	if (!ext4_fc_dentry_cachep)
2791 		return -ENOMEM;
2792 
2793 	ext4_fc_range_cachep = KMEM_CACHE(ext4_fc_range, SLAB_RECLAIM_ACCOUNT);
2794 	if (!ext4_fc_range_cachep) {
2795 		kmem_cache_destroy(ext4_fc_dentry_cachep);
2796 		return -ENOMEM;
2797 	}
2798 
2799 	return 0;
2800 }
2801 
2802 void ext4_fc_destroy_dentry_cache(void)
2803 {
2804 	kmem_cache_destroy(ext4_fc_range_cachep);
2805 	kmem_cache_destroy(ext4_fc_dentry_cachep);
2806 }
2807 
2808 #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS)
2809 void ext4_fc_set_snap_err_test(int *snap_err, int err)
2810 {
2811 	ext4_fc_set_snap_err(snap_err, err);
2812 }
2813 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_set_snap_err_test);
2814 
2815 bool ext4_fc_disabled_test(struct super_block *sb)
2816 {
2817 	return ext4_fc_disabled(sb);
2818 }
2819 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_disabled_test);
2820 
2821 bool ext4_fc_eligible_test(struct super_block *sb)
2822 {
2823 	return ext4_fc_eligible(sb);
2824 }
2825 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_eligible_test);
2826 
2827 void ext4_fc_snap_stats_update_max_test(atomic64_t *stat, u64 value)
2828 {
2829 	ext4_fc_snap_stats_update_max(stat, value);
2830 }
2831 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_snap_stats_update_max_test);
2832 
2833 void ext4_fc_wake_inode_state_test(struct inode *inode, int bit)
2834 {
2835 	ext4_fc_wake_inode_state(inode, bit);
2836 }
2837 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_wake_inode_state_test);
2838 
2839 u8 *ext4_fc_reserve_space_test(struct super_block *sb, int len, u32 *crc)
2840 {
2841 	return ext4_fc_reserve_space(sb, len, crc);
2842 }
2843 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_reserve_space_test);
2844 
2845 int ext4_fc_write_tail_test(struct super_block *sb, u32 crc)
2846 {
2847 	return ext4_fc_write_tail(sb, crc);
2848 }
2849 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_write_tail_test);
2850 
2851 bool ext4_fc_add_tlv_test(struct super_block *sb, u16 tag, u16 len, u8 *val,
2852 			  u32 *crc)
2853 {
2854 	return ext4_fc_add_tlv(sb, tag, len, val, crc);
2855 }
2856 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_add_tlv_test);
2857 
2858 int ext4_fc_write_inode_test(struct inode *inode, u32 *crc)
2859 {
2860 	return ext4_fc_write_inode(inode, crc);
2861 }
2862 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_write_inode_test);
2863 
2864 int ext4_fc_write_inode_data_test(struct inode *inode, u32 *crc)
2865 {
2866 	return ext4_fc_write_inode_data(inode, crc);
2867 }
2868 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_write_inode_data_test);
2869 
2870 void ext4_fc_free_inode_snap_test(struct inode *inode)
2871 {
2872 	ext4_fc_free_inode_snap(inode);
2873 }
2874 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_free_inode_snap_test);
2875 
2876 int ext4_fc_snapshot_inode_test(struct inode *inode,
2877 				unsigned int nr_ranges_total,
2878 				unsigned int *nr_rangesp, int *snap_err)
2879 {
2880 	return ext4_fc_snapshot_inode(inode, nr_ranges_total, nr_rangesp,
2881 				      snap_err);
2882 }
2883 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_snapshot_inode_test);
2884 
2885 unsigned int ext4_fc_count_snapshot_inodes_test(struct super_block *sb)
2886 {
2887 	return ext4_fc_count_snapshot_inodes(sb);
2888 }
2889 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_count_snapshot_inodes_test);
2890 
2891 int ext4_fc_alloc_snapshot_inodes_test(struct super_block *sb,
2892 				       struct inode ***inodesp,
2893 				       unsigned int *nr_inodesp)
2894 {
2895 	return ext4_fc_alloc_snapshot_inodes(sb, inodesp, nr_inodesp);
2896 }
2897 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_alloc_snapshot_inodes_test);
2898 
2899 int ext4_fc_snapshot_inodes_test(journal_t *journal, struct inode **inodes,
2900 				 unsigned int inodes_size,
2901 				 unsigned int *nr_inodesp,
2902 				 unsigned int *nr_rangesp, int *snap_err)
2903 {
2904 	return ext4_fc_snapshot_inodes(journal, inodes, inodes_size,
2905 				       nr_inodesp, nr_rangesp, snap_err);
2906 }
2907 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_snapshot_inodes_test);
2908 
2909 void ext4_fc_update_stats_test(struct super_block *sb, int status,
2910 			       u64 commit_time, int nblks, tid_t commit_tid)
2911 {
2912 	ext4_fc_update_stats(sb, status, commit_time, nblks, commit_tid);
2913 }
2914 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_update_stats_test);
2915 
2916 void ext4_fc_cleanup_test(journal_t *journal, int full, tid_t tid)
2917 {
2918 	ext4_fc_cleanup(journal, full, tid);
2919 }
2920 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_cleanup_test);
2921 
2922 int ext4_fc_record_modified_inode_test(struct super_block *sb, int ino)
2923 {
2924 	return ext4_fc_record_modified_inode(sb, ino);
2925 }
2926 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_record_modified_inode_test);
2927 
2928 bool ext4_fc_value_len_isvalid_test(struct ext4_sb_info *sbi, int tag, int len)
2929 {
2930 	return ext4_fc_value_len_isvalid(sbi, tag, len);
2931 }
2932 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_value_len_isvalid_test);
2933 
2934 int ext4_fc_replay_test(journal_t *journal, struct buffer_head *bh,
2935 			enum passtype pass, int off, tid_t expected_tid)
2936 {
2937 	return ext4_fc_replay(journal, bh, pass, off, expected_tid);
2938 }
2939 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_replay_test);
2940 
2941 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_get_buf);
2942 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_submit_bh);
2943 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_issue_flush);
2944 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_init_inode);
2945 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_del);
2946 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_mark_ineligible);
2947 EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_fc_track_unlink);
2948 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_track_unlink);
2949 EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_fc_track_link);
2950 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_track_link);
2951 EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_fc_track_create);
2952 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_track_create);
2953 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_track_inode);
2954 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_track_range);
2955 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_commit);
2956 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_record_regions);
2957 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_replay_check_excluded);
2958 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_replay_cleanup);
2959 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_init);
2960 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fc_info_show);
2961 #endif
2962