xref: /linux/fs/f2fs/checkpoint.c (revision a45c9a0055f5ccff0c5c546e0478604b990f23ab)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * fs/f2fs/checkpoint.c
4  *
5  * Copyright (c) 2012 Samsung Electronics Co., Ltd.
6  *             http://www.samsung.com/
7  */
8 #include <linux/fs.h>
9 #include <linux/bio.h>
10 #include <linux/writeback.h>
11 #include <linux/blkdev.h>
12 #include <linux/f2fs_fs.h>
13 #include <linux/folio_batch.h>
14 #include <linux/swap.h>
15 #include <linux/kthread.h>
16 #include <linux/delayacct.h>
17 #include <linux/ioprio.h>
18 #include <linux/math64.h>
19 #include <linux/freezer.h>
20 
21 #include "f2fs.h"
22 #include "node.h"
23 #include "segment.h"
24 #include "iostat.h"
25 #include <trace/events/f2fs.h>
26 
27 static inline void get_lock_elapsed_time(struct f2fs_time_stat *ts)
28 {
29 	ts->total_time = ktime_get();
30 #ifdef CONFIG_64BIT
31 	ts->running_time = current->se.sum_exec_runtime;
32 #endif
33 #if defined(CONFIG_SCHED_INFO) && defined(CONFIG_SCHEDSTATS)
34 	ts->runnable_time = current->sched_info.run_delay;
35 #endif
36 #ifdef CONFIG_TASK_DELAY_ACCT
37 	if (current->delays)
38 		ts->io_sleep_time = current->delays->blkio_delay;
39 #endif
40 }
41 
42 static inline void trace_lock_elapsed_time_start(struct f2fs_rwsem *sem,
43 						struct f2fs_lock_context *lc)
44 {
45 	lc->lock_trace = trace_f2fs_lock_elapsed_time_enabled();
46 	if (!lc->lock_trace)
47 		return;
48 
49 	get_lock_elapsed_time(&lc->ts);
50 }
51 
52 static inline void trace_lock_elapsed_time_end(struct f2fs_rwsem *sem,
53 				struct f2fs_lock_context *lc, bool is_write)
54 {
55 	struct f2fs_time_stat tts;
56 	unsigned long long total_time;
57 	unsigned long long running_time = 0;
58 	unsigned long long runnable_time = 0;
59 	unsigned long long io_sleep_time = 0;
60 	unsigned long long other_time = 0;
61 	unsigned npm = NSEC_PER_MSEC;
62 
63 	if (!lc->lock_trace)
64 		return;
65 
66 	if (time_to_inject(sem->sbi, FAULT_LOCK_TIMEOUT))
67 		f2fs_schedule_timeout_killable(DEFAULT_FAULT_TIMEOUT, true);
68 
69 	get_lock_elapsed_time(&tts);
70 
71 	total_time = div_u64(tts.total_time - lc->ts.total_time, npm);
72 	if (total_time <= sem->sbi->max_lock_elapsed_time)
73 		return;
74 
75 #ifdef CONFIG_64BIT
76 	running_time = div_u64(tts.running_time - lc->ts.running_time, npm);
77 #endif
78 #if defined(CONFIG_SCHED_INFO) && defined(CONFIG_SCHEDSTATS)
79 	runnable_time = div_u64(tts.runnable_time - lc->ts.runnable_time, npm);
80 #endif
81 #ifdef CONFIG_TASK_DELAY_ACCT
82 	io_sleep_time = div_u64(tts.io_sleep_time - lc->ts.io_sleep_time, npm);
83 #endif
84 	if (total_time > running_time + io_sleep_time + runnable_time)
85 		other_time = total_time - running_time -
86 				io_sleep_time - runnable_time;
87 
88 	trace_f2fs_lock_elapsed_time(sem->sbi, sem->name, is_write, current,
89 			get_current_ioprio(), total_time, running_time,
90 			runnable_time, io_sleep_time, other_time);
91 }
92 
93 static bool need_uplift_priority(struct f2fs_rwsem *sem, bool is_write)
94 {
95 	if (!(sem->sbi->adjust_lock_priority & BIT(sem->name - 1)))
96 		return false;
97 
98 	switch (sem->name) {
99 	/*
100 	 * writer is checkpoint which has high priority, let's just uplift
101 	 * priority for reader
102 	 */
103 	case LOCK_NAME_CP_RWSEM:
104 	case LOCK_NAME_NODE_CHANGE:
105 	case LOCK_NAME_NODE_WRITE:
106 		return !is_write;
107 	case LOCK_NAME_GC_LOCK:
108 	case LOCK_NAME_CP_GLOBAL:
109 	case LOCK_NAME_IO_RWSEM:
110 	case LOCK_NAME_NAT_TREE_LOCK:
111 		return true;
112 	default:
113 		f2fs_bug_on(sem->sbi, 1);
114 	}
115 	return false;
116 }
117 
118 static void uplift_priority(struct f2fs_rwsem *sem, struct f2fs_lock_context *lc,
119 						bool is_write)
120 {
121 	lc->need_restore = false;
122 	if (!sem->sbi->adjust_lock_priority)
123 		return;
124 	if (rt_task(current))
125 		return;
126 	if (!need_uplift_priority(sem, is_write))
127 		return;
128 	lc->orig_nice = task_nice(current);
129 	lc->new_nice = PRIO_TO_NICE(sem->sbi->lock_duration_priority);
130 	if (lc->orig_nice <= lc->new_nice)
131 		return;
132 	set_user_nice(current, lc->new_nice);
133 	lc->need_restore = true;
134 
135 	trace_f2fs_priority_uplift(sem->sbi, sem->name, is_write, current,
136 		NICE_TO_PRIO(lc->orig_nice), NICE_TO_PRIO(lc->new_nice));
137 }
138 
139 static void restore_priority(struct f2fs_rwsem *sem, struct f2fs_lock_context *lc,
140 						bool is_write)
141 {
142 	if (!lc->need_restore)
143 		return;
144 	/* someone has updated the priority */
145 	if (task_nice(current) != lc->new_nice)
146 		return;
147 	set_user_nice(current, lc->orig_nice);
148 
149 	trace_f2fs_priority_restore(sem->sbi, sem->name, is_write, current,
150 		NICE_TO_PRIO(lc->orig_nice), NICE_TO_PRIO(lc->new_nice));
151 }
152 
153 void f2fs_down_read_trace(struct f2fs_rwsem *sem, struct f2fs_lock_context *lc)
154 {
155 	uplift_priority(sem, lc, false);
156 	f2fs_down_read(sem);
157 	trace_lock_elapsed_time_start(sem, lc);
158 }
159 
160 int f2fs_down_read_trylock_trace(struct f2fs_rwsem *sem, struct f2fs_lock_context *lc)
161 {
162 	uplift_priority(sem, lc, false);
163 	if (!f2fs_down_read_trylock(sem)) {
164 		restore_priority(sem, lc, false);
165 		return 0;
166 	}
167 	trace_lock_elapsed_time_start(sem, lc);
168 	return 1;
169 }
170 
171 void f2fs_up_read_trace(struct f2fs_rwsem *sem, struct f2fs_lock_context *lc)
172 {
173 	f2fs_up_read(sem);
174 	restore_priority(sem, lc, false);
175 	trace_lock_elapsed_time_end(sem, lc, false);
176 }
177 
178 void f2fs_down_write_trace(struct f2fs_rwsem *sem, struct f2fs_lock_context *lc)
179 {
180 	uplift_priority(sem, lc, true);
181 	f2fs_down_write(sem);
182 	trace_lock_elapsed_time_start(sem, lc);
183 }
184 
185 int f2fs_down_write_trylock_trace(struct f2fs_rwsem *sem, struct f2fs_lock_context *lc)
186 {
187 	uplift_priority(sem, lc, true);
188 	if (!f2fs_down_write_trylock(sem)) {
189 		restore_priority(sem, lc, true);
190 		return 0;
191 	}
192 	trace_lock_elapsed_time_start(sem, lc);
193 	return 1;
194 }
195 
196 void f2fs_up_write_trace(struct f2fs_rwsem *sem, struct f2fs_lock_context *lc)
197 {
198 	f2fs_up_write(sem);
199 	restore_priority(sem, lc, true);
200 	trace_lock_elapsed_time_end(sem, lc, true);
201 }
202 
203 void f2fs_lock_op(struct f2fs_sb_info *sbi, struct f2fs_lock_context *lc)
204 {
205 	f2fs_down_read_trace(&sbi->cp_rwsem, lc);
206 }
207 
208 int f2fs_trylock_op(struct f2fs_sb_info *sbi, struct f2fs_lock_context *lc)
209 {
210 	if (time_to_inject(sbi, FAULT_LOCK_OP))
211 		return 0;
212 
213 	return f2fs_down_read_trylock_trace(&sbi->cp_rwsem, lc);
214 }
215 
216 void f2fs_unlock_op(struct f2fs_sb_info *sbi, struct f2fs_lock_context *lc)
217 {
218 	f2fs_up_read_trace(&sbi->cp_rwsem, lc);
219 }
220 
221 static inline void f2fs_lock_all(struct f2fs_sb_info *sbi)
222 {
223 	f2fs_down_write(&sbi->cp_rwsem);
224 }
225 
226 static inline void f2fs_unlock_all(struct f2fs_sb_info *sbi)
227 {
228 	f2fs_up_write(&sbi->cp_rwsem);
229 }
230 
231 #define DEFAULT_CHECKPOINT_IOPRIO (IOPRIO_PRIO_VALUE(IOPRIO_CLASS_RT, 3))
232 
233 static struct kmem_cache *ino_entry_slab;
234 struct kmem_cache *f2fs_inode_entry_slab;
235 
236 /*
237  * We guarantee no failure on the returned cache.
238  */
239 struct f2fs_cached_block *f2fs_grab_meta_cache(struct f2fs_sb_info *sbi,
240 							pgoff_t index)
241 {
242 	struct f2fs_cached_block *entry;
243 repeat:
244 	entry = f2fs_grab_cache(META_CACHE(sbi), index,
245 					F2FS_CACHE_LOCK_CREATE);
246 	if (IS_ERR(entry)) {
247 		cond_resched();
248 		goto repeat;
249 	}
250 	f2fs_cache_wait_writeback(entry);
251 	if (!f2fs_cache_test_uptodate(entry))
252 		f2fs_cache_set_uptodate(entry);
253 	return entry;
254 }
255 
256 static struct f2fs_cached_block *__get_meta_cache(struct f2fs_sb_info *sbi,
257 					pgoff_t index, bool is_meta)
258 {
259 	struct f2fs_cached_block *entry;
260 	struct f2fs_io_info fio = {
261 		.sbi = sbi,
262 		.type = META,
263 		.op = REQ_OP_READ,
264 		.op_flags = REQ_META | REQ_PRIO,
265 		.old_blkaddr = index,
266 		.new_blkaddr = index,
267 		.encrypted_page = NULL,
268 		.is_por = !is_meta ? 1 : 0,
269 		.is_cache = 1,
270 	};
271 	int err;
272 
273 	if (unlikely(!is_meta))
274 		fio.op_flags &= ~REQ_META;
275 repeat:
276 	entry = f2fs_grab_cache(META_CACHE(sbi), index,
277 					F2FS_CACHE_LOCK_CREATE);
278 	if (IS_ERR(entry)) {
279 		cond_resched();
280 		goto repeat;
281 	}
282 	if (f2fs_cache_test_uptodate(entry))
283 		goto out;
284 
285 	fio.cache_entry = entry;
286 
287 	err = f2fs_submit_cache_read(&fio);
288 	if (err) {
289 		f2fs_put_cache(entry, true);
290 		return ERR_PTR(err);
291 	}
292 
293 	f2fs_update_iostat(sbi, NULL, FS_META_READ_IO, F2FS_BLKSIZE(sbi));
294 
295 	f2fs_lock_cache(entry);
296 	if (unlikely(!f2fs_is_meta_cache(entry))) {
297 		f2fs_put_cache(entry, true);
298 		goto repeat;
299 	}
300 
301 	if (unlikely(!f2fs_cache_test_uptodate(entry))) {
302 		f2fs_handle_page_eio(sbi, entry->index, META);
303 		f2fs_put_cache(entry, true);
304 		return ERR_PTR(-EIO);
305 	}
306 out:
307 	return entry;
308 }
309 
310 struct f2fs_cached_block *f2fs_get_meta_cache(struct f2fs_sb_info *sbi,
311 							pgoff_t index)
312 {
313 	return __get_meta_cache(sbi, index, true);
314 }
315 
316 struct f2fs_cached_block *f2fs_get_meta_cache_retry(struct f2fs_sb_info *sbi,
317 							pgoff_t index)
318 {
319 	struct f2fs_cached_block *entry;
320 	int count = 0;
321 
322 retry:
323 	entry = __get_meta_cache(sbi, index, true);
324 	if (IS_ERR(entry)) {
325 		if (PTR_ERR(entry) == -EIO &&
326 				++count <= DEFAULT_RETRY_IO_COUNT)
327 			goto retry;
328 		f2fs_stop_checkpoint(sbi, false, STOP_CP_REASON_META_PAGE);
329 	}
330 	return entry;
331 }
332 
333 /* for POR only */
334 struct f2fs_cached_block *f2fs_get_tmp_cache(struct f2fs_sb_info *sbi,
335 							pgoff_t index)
336 {
337 	return __get_meta_cache(sbi, index, false);
338 }
339 
340 static bool __is_bitmap_valid(struct f2fs_sb_info *sbi, block_t blkaddr,
341 							int type)
342 {
343 	struct seg_entry *se;
344 	unsigned int segno, offset;
345 	bool exist;
346 
347 	if (type == DATA_GENERIC)
348 		return true;
349 
350 	segno = GET_SEGNO(sbi, blkaddr);
351 	offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
352 	se = get_seg_entry(sbi, segno);
353 
354 	exist = f2fs_test_bit(offset, se->cur_valid_map);
355 
356 	/* skip data, if we already have an error in checkpoint. */
357 	if (unlikely(f2fs_cp_error(sbi)))
358 		return exist;
359 
360 	if ((exist && type == DATA_GENERIC_ENHANCE_UPDATE) ||
361 		(!exist && type == DATA_GENERIC_ENHANCE))
362 		goto out_err;
363 	if (!exist && type != DATA_GENERIC_ENHANCE_UPDATE)
364 		goto out_handle;
365 	return exist;
366 
367 out_err:
368 	f2fs_err(sbi, "Inconsistent error blkaddr:%u, sit bitmap:%d",
369 		 blkaddr, exist);
370 	set_sbi_flag(sbi, SBI_NEED_FSCK);
371 	dump_stack();
372 out_handle:
373 	f2fs_handle_error(sbi, ERROR_INVALID_BLKADDR);
374 	return exist;
375 }
376 
377 static bool __f2fs_is_valid_blkaddr(struct f2fs_sb_info *sbi,
378 					block_t blkaddr, int type)
379 {
380 	switch (type) {
381 	case META_NAT:
382 		break;
383 	case META_SIT:
384 		if (unlikely(blkaddr >= SIT_BLK_CNT(sbi)))
385 			goto check_only;
386 		break;
387 	case META_SSA:
388 		if (unlikely(blkaddr >= MAIN_BLKADDR(sbi) ||
389 			blkaddr < SM_I(sbi)->ssa_blkaddr))
390 			goto check_only;
391 		break;
392 	case META_CP:
393 		if (unlikely(blkaddr >= SIT_I(sbi)->sit_base_addr ||
394 			blkaddr < __start_cp_addr(sbi)))
395 			goto check_only;
396 		break;
397 	case META_POR:
398 		if (unlikely(blkaddr >= MAX_BLKADDR(sbi) ||
399 			blkaddr < MAIN_BLKADDR(sbi)))
400 			goto check_only;
401 		break;
402 	case DATA_GENERIC:
403 	case DATA_GENERIC_ENHANCE:
404 	case DATA_GENERIC_ENHANCE_READ:
405 	case DATA_GENERIC_ENHANCE_UPDATE:
406 		if (unlikely(blkaddr >= MAX_BLKADDR(sbi) ||
407 				blkaddr < MAIN_BLKADDR(sbi))) {
408 
409 			/* Skip to emit an error message. */
410 			if (unlikely(f2fs_cp_error(sbi)))
411 				return false;
412 
413 			f2fs_warn(sbi, "access invalid blkaddr:%u",
414 				  blkaddr);
415 			set_sbi_flag(sbi, SBI_NEED_FSCK);
416 			dump_stack();
417 			goto err;
418 		} else {
419 			return __is_bitmap_valid(sbi, blkaddr, type);
420 		}
421 		break;
422 	case META_GENERIC:
423 		if (unlikely(blkaddr < SEG0_BLKADDR(sbi) ||
424 			blkaddr >= MAIN_BLKADDR(sbi)))
425 			goto err;
426 		break;
427 	default:
428 		BUG();
429 	}
430 
431 	return true;
432 err:
433 	f2fs_handle_error(sbi, ERROR_INVALID_BLKADDR);
434 check_only:
435 	return false;
436 }
437 
438 bool f2fs_is_valid_blkaddr(struct f2fs_sb_info *sbi,
439 					block_t blkaddr, int type)
440 {
441 	if (time_to_inject(sbi, FAULT_BLKADDR_VALIDITY))
442 		return false;
443 	return __f2fs_is_valid_blkaddr(sbi, blkaddr, type);
444 }
445 
446 bool f2fs_is_valid_blkaddr_raw(struct f2fs_sb_info *sbi,
447 					block_t blkaddr, int type)
448 {
449 	return __f2fs_is_valid_blkaddr(sbi, blkaddr, type);
450 }
451 
452 /*
453  * Readahead CP/NAT/SIT/SSA/POR blocks
454  */
455 int f2fs_ra_meta_caches(struct f2fs_sb_info *sbi, block_t start,
456 				int nrblocks, int type, bool sync)
457 {
458 	struct f2fs_cached_block_list *cache = META_CACHE(sbi);
459 	block_t blkno = start;
460 	struct f2fs_io_info fio = {
461 		.sbi = sbi,
462 		.type = META,
463 		.op = REQ_OP_READ,
464 		.op_flags = sync ? (REQ_META | REQ_PRIO) : REQ_RAHEAD,
465 		.encrypted_page = NULL,
466 		.in_list = 0,
467 		.is_por = (type == META_POR) ? 1 : 0,
468 		.is_cache = 1,
469 	};
470 	struct blk_plug plug;
471 	int err;
472 
473 	if (unlikely(type == META_POR))
474 		fio.op_flags &= ~REQ_META;
475 
476 	blk_start_plug(&plug);
477 	for (; nrblocks-- > 0; blkno++) {
478 		struct f2fs_cached_block *entry;
479 
480 		if (!f2fs_is_valid_blkaddr(sbi, blkno, type))
481 			goto out;
482 
483 		switch (type) {
484 		case META_NAT:
485 			if (unlikely(blkno >=
486 					NAT_BLOCK_OFFSET(sbi, NM_I(sbi)->max_nid)))
487 				blkno = 0;
488 			/* get nat block addr */
489 			fio.new_blkaddr = current_nat_addr(sbi,
490 					blkno * NAT_ENTRY_PER_BLOCK(sbi));
491 			break;
492 		case META_SIT:
493 			if (unlikely(blkno >= TOTAL_SEGS(sbi)))
494 				goto out;
495 			/* get sit block addr */
496 			fio.new_blkaddr = current_sit_addr(sbi,
497 					blkno * SIT_ENTRY_PER_BLOCK(sbi));
498 			break;
499 		case META_SSA:
500 		case META_CP:
501 		case META_POR:
502 			fio.new_blkaddr = blkno;
503 			break;
504 		default:
505 			f2fs_bug_on(sbi, 1);
506 		}
507 
508 		entry = f2fs_grab_cache(cache, fio.new_blkaddr,
509 						F2FS_CACHE_LOCK_CREATE);
510 		if (IS_ERR(entry))
511 			continue;
512 		if (f2fs_cache_test_uptodate(entry)) {
513 			f2fs_put_cache(entry, true);
514 			continue;
515 		}
516 
517 		fio.cache_entry = entry;
518 		err = f2fs_submit_cache_read(&fio);
519 		f2fs_put_cache(entry, err ? true : false);
520 
521 		if (!err)
522 			f2fs_update_iostat(sbi, NULL, FS_META_READ_IO,
523 							F2FS_BLKSIZE(sbi));
524 	}
525 out:
526 	blk_finish_plug(&plug);
527 	return blkno - start;
528 }
529 
530 void f2fs_ra_meta_caches_cond(struct f2fs_sb_info *sbi, pgoff_t index,
531 						unsigned int ra_blocks)
532 {
533 	struct f2fs_cached_block *entry;
534 	bool readahead = false;
535 
536 	if (ra_blocks == RECOVERY_MIN_RA_BLOCKS)
537 		return;
538 
539 	entry = f2fs_find_cache(META_CACHE(sbi), index, 0);
540 	if (IS_ERR(entry) || !f2fs_cache_test_uptodate(entry))
541 		readahead = true;
542 	f2fs_put_cache(entry, false);
543 
544 	if (readahead)
545 		f2fs_ra_meta_caches(sbi, index, ra_blocks, META_POR, true);
546 }
547 
548 static bool __f2fs_write_meta_cache(struct f2fs_cached_block *entry,
549 				enum iostat_type io_type)
550 {
551 	struct f2fs_sb_info *sbi = entry->cache->sbi;
552 
553 	trace_f2fs_write_cache(entry, META);
554 
555 	if (unlikely(f2fs_cp_error(sbi))) {
556 		if (is_sbi_flag_set(sbi, SBI_IS_CLOSE)) {
557 			f2fs_cache_clear_uptodate(entry);
558 			dec_cache_count(sbi, F2FS_DIRTY_META);
559 			f2fs_cache_update_tag(entry, F2FS_CACHE_TAG_DIRTY,
560 						F2FS_CACHE_TAG_NONE);
561 			f2fs_unlock_cache(entry);
562 			return true;
563 		}
564 		goto redirty_out;
565 	}
566 	if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
567 		goto redirty_out;
568 
569 	f2fs_do_write_meta_cache(sbi, entry, io_type);
570 	dec_cache_count(sbi, F2FS_DIRTY_META);
571 
572 	f2fs_unlock_cache(entry);
573 
574 	if (unlikely(f2fs_cp_error(sbi)))
575 		f2fs_submit_merged_write(sbi, META);
576 
577 	return true;
578 
579 redirty_out:
580 	f2fs_cache_set_dirty(entry);
581 	return false;
582 }
583 
584 void f2fs_write_meta_caches(struct f2fs_sb_info *sbi, long *nr_written)
585 {
586 	struct f2fs_lock_context lc;
587 	long nr_to_write = LONG_MAX;
588 	long nwritten;
589 
590 	if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
591 		return;
592 
593 	/* collect a number of dirty meta caches and write together */
594 	if (get_nr_caches(sbi, F2FS_DIRTY_META) <
595 	    nr_caches_to_skip(sbi, META))
596 		return;
597 
598 	/* if locked failed, cp will flush dirty caches instead */
599 	if (!f2fs_down_write_trylock_trace(&sbi->cp_global_sem, &lc))
600 		return;
601 
602 	nr_to_write = adjust_flush_cache_number(sbi, META);
603 	nwritten = f2fs_sync_meta_caches(sbi, nr_to_write, false, FS_META_IO);
604 	f2fs_up_write_trace(&sbi->cp_global_sem, &lc);
605 
606 	if (nr_written)
607 		*nr_written = nwritten;
608 }
609 
610 long f2fs_sync_meta_caches(struct f2fs_sb_info *sbi, long nr_to_write,
611 				bool sync, enum iostat_type io_type)
612 {
613 	pgoff_t index = 0, next = ULONG_MAX;
614 	struct f2fs_cached_block *entries[F2FS_ONSTACK_CACHES];
615 	long nwritten = 0;
616 	int nr;
617 	struct blk_plug plug;
618 	bool background = nr_to_write != LONG_MAX;
619 
620 	trace_f2fs_write_caches(sbi, nr_to_write, 0, META);
621 
622 	blk_start_plug(&plug);
623 
624 	while ((nr = f2fs_cache_gang_lookup_tag(META_CACHE(sbi), entries,
625 			&index, F2FS_ONSTACK_CACHES, F2FS_CACHE_TAG_DIRTY))) {
626 		int i;
627 
628 		for (i = 0; i < nr; i++) {
629 			struct f2fs_cached_block *entry = entries[i];
630 
631 			if (background && unlikely(freezing(current))) {
632 				f2fs_cache_gang_release(entries, nr);
633 				goto stop;
634 			}
635 
636 			if (background && next != ULONG_MAX &&
637 					entry->index != next) {
638 				f2fs_cache_gang_release(entries, nr);
639 				goto stop;
640 			}
641 
642 			f2fs_lock_cache(entry);
643 
644 			if (unlikely(!f2fs_is_meta_cache(entry))) {
645 continue_unlock:
646 				f2fs_unlock_cache(entry);
647 				continue;
648 			}
649 			if (!f2fs_cache_test_dirty(entry)) {
650 				/* someone wrote it for us */
651 				goto continue_unlock;
652 			}
653 
654 			f2fs_cache_wait_writeback(entry);
655 
656 			if (!f2fs_cache_test_and_clear_dirty(entry))
657 				goto continue_unlock;
658 
659 			if (!__f2fs_write_meta_cache(entry, io_type)) {
660 				f2fs_unlock_cache(entry);
661 				f2fs_cache_gang_release(entries, nr);
662 				goto stop;
663 			}
664 			nwritten++;
665 			next = entry->index + 1;
666 			if (unlikely(nwritten >= nr_to_write))
667 				break;
668 		}
669 		f2fs_cache_gang_release(entries, nr);
670 		cond_resched();
671 
672 		if (unlikely(nwritten >= nr_to_write))
673 			break;
674 	}
675 stop:
676 	if (nwritten)
677 		f2fs_submit_merged_write(sbi, META);
678 
679 	blk_finish_plug(&plug);
680 
681 	trace_f2fs_write_caches(sbi, nr_to_write, nwritten, META);
682 
683 	return nwritten;
684 }
685 
686 static void __add_ino_entry(struct f2fs_sb_info *sbi, nid_t ino,
687 						unsigned int devidx, int type)
688 {
689 	struct inode_management *im = &sbi->im[type];
690 	struct ino_entry *e = NULL, *new = NULL;
691 	int ret;
692 
693 	if (type == FLUSH_INO) {
694 		rcu_read_lock();
695 		e = radix_tree_lookup(&im->ino_root, ino);
696 		rcu_read_unlock();
697 	}
698 
699 retry:
700 	if (!e)
701 		new = f2fs_kmem_cache_alloc(ino_entry_slab,
702 						GFP_NOFS, true, NULL);
703 
704 	ret = radix_tree_preload(GFP_NOFS | __GFP_NOFAIL);
705 	f2fs_bug_on(sbi, ret);
706 
707 	spin_lock(&im->ino_lock);
708 	e = radix_tree_lookup(&im->ino_root, ino);
709 	if (!e) {
710 		if (!new) {
711 			spin_unlock(&im->ino_lock);
712 			radix_tree_preload_end();
713 			goto retry;
714 		}
715 		e = new;
716 		if (unlikely(radix_tree_insert(&im->ino_root, ino, e)))
717 			f2fs_bug_on(sbi, 1);
718 
719 		memset(e, 0, sizeof(struct ino_entry));
720 		e->ino = ino;
721 
722 		list_add_tail(&e->list, &im->ino_list);
723 		if (type != ORPHAN_INO)
724 			im->ino_num++;
725 	}
726 
727 	if (type == FLUSH_INO)
728 		f2fs_set_bit(devidx, (char *)&e->dirty_device);
729 
730 	spin_unlock(&im->ino_lock);
731 	radix_tree_preload_end();
732 
733 	if (new && e != new)
734 		kmem_cache_free(ino_entry_slab, new);
735 }
736 
737 static void __remove_ino_entry(struct f2fs_sb_info *sbi, nid_t ino, int type)
738 {
739 	struct inode_management *im = &sbi->im[type];
740 	struct ino_entry *e;
741 
742 	spin_lock(&im->ino_lock);
743 	e = radix_tree_lookup(&im->ino_root, ino);
744 	if (e) {
745 		list_del(&e->list);
746 		radix_tree_delete(&im->ino_root, ino);
747 		im->ino_num--;
748 		spin_unlock(&im->ino_lock);
749 		kmem_cache_free(ino_entry_slab, e);
750 		return;
751 	}
752 	spin_unlock(&im->ino_lock);
753 }
754 
755 static void __set_ino_bitmap(struct f2fs_sb_info *sbi, nid_t ino, int type)
756 {
757 	struct inode_management *im = &sbi->im[type];
758 	unsigned long index = INO_SLOT_INDEX(ino);
759 	unsigned int ofs = INO_BIT_OFFSET(ino);
760 	void **slot, *entry;
761 	unsigned long bitmap = 0;
762 	int ret;
763 
764 	ret = radix_tree_preload(GFP_NOFS | __GFP_NOFAIL);
765 	f2fs_bug_on(sbi, ret);
766 
767 	spin_lock(&im->ino_lock);
768 	slot = radix_tree_lookup_slot(&im->ino_root, index);
769 	if (slot) {
770 		entry = radix_tree_deref_slot_protected(slot, &im->ino_lock);
771 		bitmap = xa_to_value(entry);
772 		if (!(bitmap & (1UL << ofs))) {
773 			bitmap |= (1UL << ofs);
774 			entry = xa_mk_value(bitmap);
775 			radix_tree_replace_slot(&im->ino_root, slot, entry);
776 		}
777 	} else {
778 		bitmap |= (1UL << ofs);
779 		entry = xa_mk_value(bitmap);
780 		if (unlikely(radix_tree_insert(&im->ino_root, index, entry)))
781 			f2fs_bug_on(sbi, 1);
782 	}
783 	spin_unlock(&im->ino_lock);
784 	radix_tree_preload_end();
785 }
786 
787 static void __clear_ino_bitmap(struct f2fs_sb_info *sbi, nid_t ino, int type)
788 {
789 	struct inode_management *im = &sbi->im[type];
790 	unsigned long index = INO_SLOT_INDEX(ino);
791 	unsigned int ofs = INO_BIT_OFFSET(ino);
792 	void **slot, *entry;
793 	unsigned long bitmap;
794 
795 	spin_lock(&im->ino_lock);
796 	slot = radix_tree_lookup_slot(&im->ino_root, index);
797 	if (slot) {
798 		entry = radix_tree_deref_slot_protected(slot, &im->ino_lock);
799 		bitmap = xa_to_value(entry);
800 		if (bitmap & (1UL << ofs))
801 			bitmap &= ~(1UL << ofs);
802 
803 		if (bitmap) {
804 			entry = xa_mk_value(bitmap);
805 			radix_tree_replace_slot(&im->ino_root, slot, entry);
806 		} else {
807 			radix_tree_delete(&im->ino_root, index);
808 		}
809 	}
810 	spin_unlock(&im->ino_lock);
811 }
812 
813 static void __f2fs_add_ino_entry(struct f2fs_sb_info *sbi, nid_t ino,
814 					unsigned int devidx, int type)
815 {
816 	if (type <= FLUSH_INO)
817 		__add_ino_entry(sbi, ino, devidx, type);
818 	else
819 		__set_ino_bitmap(sbi, ino, type);
820 }
821 
822 void f2fs_add_ino_entry(struct f2fs_sb_info *sbi, nid_t ino, int type)
823 {
824 	__f2fs_add_ino_entry(sbi, ino, 0, type);
825 }
826 
827 void f2fs_remove_ino_entry(struct f2fs_sb_info *sbi, nid_t ino, int type)
828 {
829 	if (type <= FLUSH_INO)
830 		__remove_ino_entry(sbi, ino, type);
831 	else
832 		__clear_ino_bitmap(sbi, ino, type);
833 }
834 
835 /* mode should be APPEND_INO, UPDATE_INO, TRANS_DIR_INO and XATTR_DIR_INO */
836 bool f2fs_exist_written_data(struct f2fs_sb_info *sbi, nid_t ino, int mode)
837 {
838 	struct inode_management *im = &sbi->im[mode];
839 	unsigned long index = INO_SLOT_INDEX(ino);
840 	unsigned int ofs = INO_BIT_OFFSET(ino);
841 	void *entry;
842 	unsigned long bitmap;
843 
844 	f2fs_bug_on(sbi, mode <= FLUSH_INO);
845 
846 	spin_lock(&im->ino_lock);
847 	entry = radix_tree_lookup(&im->ino_root, index);
848 	if (!entry) {
849 		spin_unlock(&im->ino_lock);
850 		return false;
851 	}
852 	bitmap = xa_to_value(entry);
853 	spin_unlock(&im->ino_lock);
854 
855 	return bitmap & (1UL << ofs);
856 }
857 
858 void f2fs_release_ino_entry(struct f2fs_sb_info *sbi, bool all)
859 {
860 	struct ino_entry *e, *tmp;
861 	int i;
862 
863 	for (i = all ? ORPHAN_INO : FLUSH_INO; i <= FLUSH_INO; i++) {
864 		struct inode_management *im = &sbi->im[i];
865 
866 		spin_lock(&im->ino_lock);
867 		list_for_each_entry_safe(e, tmp, &im->ino_list, list) {
868 			list_del(&e->list);
869 			radix_tree_delete(&im->ino_root, e->ino);
870 			kmem_cache_free(ino_entry_slab, e);
871 			im->ino_num--;
872 		}
873 		spin_unlock(&im->ino_lock);
874 	}
875 
876 	/* Wait for pending APPEND/UPDATE inode state updates. */
877 	flush_workqueue(sbi->evict_wq);
878 
879 	for (i = APPEND_INO; i < MAX_INO_ENTRY; i++) {
880 		struct inode_management *im = &sbi->im[i];
881 
882 		spin_lock(&im->ino_lock);
883 		xa_destroy(&im->ino_root);
884 		spin_unlock(&im->ino_lock);
885 	}
886 }
887 
888 void f2fs_set_dirty_device(struct f2fs_sb_info *sbi, nid_t ino,
889 					unsigned int devidx, int type)
890 {
891 	__f2fs_add_ino_entry(sbi, ino, devidx, type);
892 }
893 
894 bool f2fs_is_dirty_device(struct f2fs_sb_info *sbi, nid_t ino,
895 					unsigned int devidx, int type)
896 {
897 	struct inode_management *im = &sbi->im[type];
898 	struct ino_entry *e;
899 	bool is_dirty = false;
900 
901 	spin_lock(&im->ino_lock);
902 	e = radix_tree_lookup(&im->ino_root, ino);
903 	if (e && f2fs_test_bit(devidx, (char *)&e->dirty_device))
904 		is_dirty = true;
905 	spin_unlock(&im->ino_lock);
906 	return is_dirty;
907 }
908 
909 int f2fs_acquire_orphan_inode(struct f2fs_sb_info *sbi)
910 {
911 	struct inode_management *im = &sbi->im[ORPHAN_INO];
912 	int err = 0;
913 
914 	spin_lock(&im->ino_lock);
915 
916 	if (time_to_inject(sbi, FAULT_ORPHAN)) {
917 		spin_unlock(&im->ino_lock);
918 		return -ENOSPC;
919 	}
920 
921 	if (unlikely(im->ino_num >= sbi->max_orphans))
922 		err = -ENOSPC;
923 	else
924 		im->ino_num++;
925 	spin_unlock(&im->ino_lock);
926 
927 	return err;
928 }
929 
930 void f2fs_release_orphan_inode(struct f2fs_sb_info *sbi)
931 {
932 	struct inode_management *im = &sbi->im[ORPHAN_INO];
933 
934 	spin_lock(&im->ino_lock);
935 	f2fs_bug_on(sbi, im->ino_num == 0);
936 	im->ino_num--;
937 	spin_unlock(&im->ino_lock);
938 }
939 
940 void f2fs_add_orphan_inode(struct inode *inode)
941 {
942 	/* add new orphan ino entry into list */
943 	f2fs_add_ino_entry(F2FS_I_SB(inode), inode->i_ino, ORPHAN_INO);
944 	f2fs_update_inode_cache(inode);
945 }
946 
947 void f2fs_remove_orphan_inode(struct f2fs_sb_info *sbi, nid_t ino)
948 {
949 	/* remove orphan entry from orphan list */
950 	f2fs_remove_ino_entry(sbi, ino, ORPHAN_INO);
951 }
952 
953 static int recover_orphan_inode(struct f2fs_sb_info *sbi, nid_t ino)
954 {
955 	struct inode *inode;
956 	struct node_info ni;
957 	int err;
958 
959 	inode = f2fs_iget_retry(sbi->sb, ino);
960 	if (IS_ERR(inode)) {
961 		/*
962 		 * there should be a bug that we can't find the entry
963 		 * to orphan inode.
964 		 */
965 		f2fs_bug_on(sbi, PTR_ERR(inode) == -ENOENT);
966 		return PTR_ERR(inode);
967 	}
968 
969 	err = f2fs_dquot_initialize(inode);
970 	if (err) {
971 		iput(inode);
972 		goto err_out;
973 	}
974 
975 	clear_nlink(inode);
976 
977 	/* truncate all the data during iput */
978 	iput(inode);
979 
980 	err = f2fs_get_node_info(sbi, ino, &ni, false);
981 	if (err)
982 		goto err_out;
983 
984 	/* ENOMEM was fully retried in f2fs_evict_inode. */
985 	if (ni.blk_addr != NULL_ADDR) {
986 		err = -EIO;
987 		goto err_out;
988 	}
989 	return 0;
990 
991 err_out:
992 	set_sbi_flag(sbi, SBI_NEED_FSCK);
993 	f2fs_warn(sbi, "%s: orphan failed (ino=%x), run fsck to fix.",
994 		  __func__, ino);
995 	return err;
996 }
997 
998 int f2fs_recover_orphan_inodes(struct f2fs_sb_info *sbi)
999 {
1000 	block_t start_blk, orphan_blocks, i, j;
1001 	int err = 0;
1002 
1003 	if (!is_set_ckpt_flags(sbi, CP_ORPHAN_PRESENT_FLAG))
1004 		return 0;
1005 
1006 	if (f2fs_hw_is_readonly(sbi)) {
1007 		f2fs_info(sbi, "write access unavailable, skipping orphan cleanup");
1008 		return 0;
1009 	}
1010 
1011 	if (is_sbi_flag_set(sbi, SBI_IS_WRITABLE))
1012 		f2fs_info(sbi, "orphan cleanup on readonly fs");
1013 
1014 	start_blk = __start_cp_addr(sbi) + 1 + __cp_payload(sbi);
1015 	orphan_blocks = __start_sum_addr(sbi) - 1 - __cp_payload(sbi);
1016 
1017 	f2fs_ra_meta_caches(sbi, start_blk, orphan_blocks, META_CP, true);
1018 
1019 	for (i = 0; i < orphan_blocks; i++) {
1020 		struct f2fs_cached_block *entry;
1021 		struct f2fs_orphan_block *orphan_blk;
1022 		struct f2fs_orphan_footer *footer;
1023 		unsigned int entry_count;
1024 
1025 		entry = f2fs_get_meta_cache(sbi, start_blk + i);
1026 		if (IS_ERR(entry)) {
1027 			err = PTR_ERR(entry);
1028 			goto out;
1029 		}
1030 
1031 		orphan_blk = cache_address(entry);
1032 		footer = f2fs_orphan_footer(orphan_blk, sbi);
1033 		entry_count = le32_to_cpu(footer->entry_count);
1034 		if (entry_count > F2FS_ORPHANS_PER_BLOCK(sbi)) {
1035 			f2fs_err(sbi, "invalid orphan inode entry count %u",
1036 				 entry_count);
1037 			set_sbi_flag(sbi, SBI_NEED_FSCK);
1038 			f2fs_handle_error(sbi, ERROR_INCONSISTENT_ORPHAN);
1039 			err = -EFSCORRUPTED;
1040 			f2fs_put_cache(entry, true);
1041 			goto out;
1042 		}
1043 
1044 		for (j = 0; j < entry_count; j++) {
1045 			nid_t ino = le32_to_cpu(orphan_blk->ino[j]);
1046 
1047 			err = recover_orphan_inode(sbi, ino);
1048 			if (err) {
1049 				f2fs_put_cache(entry, true);
1050 				goto out;
1051 			}
1052 		}
1053 		f2fs_put_cache(entry, true);
1054 	}
1055 	/* clear Orphan Flag */
1056 	clear_ckpt_flags(sbi, CP_ORPHAN_PRESENT_FLAG);
1057 out:
1058 	set_sbi_flag(sbi, SBI_IS_RECOVERED);
1059 
1060 	return err;
1061 }
1062 
1063 static void write_orphan_inodes(struct f2fs_sb_info *sbi, block_t start_blk)
1064 {
1065 	struct list_head *head;
1066 	struct f2fs_orphan_block *orphan_blk = NULL;
1067 	struct f2fs_orphan_footer *footer = NULL;
1068 	unsigned int nentries = 0;
1069 	unsigned short index = 1;
1070 	unsigned short orphan_blocks;
1071 	struct ino_entry *orphan = NULL;
1072 	struct inode_management *im = &sbi->im[ORPHAN_INO];
1073 	struct f2fs_cached_block *entry = NULL;
1074 
1075 	orphan_blocks = GET_ORPHAN_BLOCKS(sbi, im->ino_num);
1076 
1077 	/*
1078 	 * we don't need to do spin_lock(&im->ino_lock) here, since all the
1079 	 * orphan inode operations are covered under f2fs_lock_op().
1080 	 * And, spin_lock should be avoided due to cache operations below.
1081 	 */
1082 	head = &im->ino_list;
1083 
1084 	/* loop for each orphan inode entry and write them in journal block */
1085 	list_for_each_entry(orphan, head, list) {
1086 		if (!entry) {
1087 			entry = f2fs_grab_meta_cache(sbi, start_blk++);
1088 			orphan_blk = cache_address(entry);
1089 			footer = f2fs_orphan_footer(orphan_blk, sbi);
1090 			memset(orphan_blk, 0, sbi->blocksize);
1091 		}
1092 
1093 		orphan_blk->ino[nentries++] = cpu_to_le32(orphan->ino);
1094 
1095 		if (nentries == F2FS_ORPHANS_PER_BLOCK(sbi)) {
1096 			/*
1097 			 * an orphan block is full,
1098 			 * then we need to flush current orphan blocks
1099 			 * and bring another one in memory
1100 			 */
1101 			footer->blk_addr = cpu_to_le16(index);
1102 			footer->blk_count = cpu_to_le16(orphan_blocks);
1103 			footer->entry_count = cpu_to_le32(nentries);
1104 			f2fs_mark_cache_dirty(entry);
1105 			f2fs_put_cache(entry, true);
1106 			index++;
1107 			nentries = 0;
1108 			entry = NULL;
1109 		}
1110 	}
1111 
1112 	if (entry) {
1113 		footer->blk_addr = cpu_to_le16(index);
1114 		footer->blk_count = cpu_to_le16(orphan_blocks);
1115 		footer->entry_count = cpu_to_le32(nentries);
1116 		f2fs_mark_cache_dirty(entry);
1117 		f2fs_put_cache(entry, true);
1118 	}
1119 }
1120 
1121 static __u32 f2fs_checkpoint_chksum(struct f2fs_sb_info *sbi,
1122 				     struct f2fs_checkpoint *ckpt)
1123 {
1124 	unsigned int chksum_ofs = le32_to_cpu(ckpt->checksum_offset);
1125 	__u32 chksum;
1126 
1127 	chksum = f2fs_crc32(ckpt, chksum_ofs);
1128 	if (chksum_ofs < CP_CHKSUM_OFFSET(sbi)) {
1129 		chksum_ofs += sizeof(chksum);
1130 		chksum = f2fs_chksum(chksum, (__u8 *)ckpt + chksum_ofs,
1131 					F2FS_BLKSIZE(sbi) - chksum_ofs);
1132 	}
1133 	return chksum;
1134 }
1135 
1136 static int get_checkpoint_version(struct f2fs_sb_info *sbi, block_t cp_addr,
1137 		struct f2fs_checkpoint **cp_block, struct f2fs_cached_block **cp_entry,
1138 		unsigned long long *version)
1139 {
1140 	size_t crc_offset = 0;
1141 	__u32 crc;
1142 
1143 	*cp_entry = f2fs_get_meta_cache(sbi, cp_addr);
1144 	if (IS_ERR(*cp_entry))
1145 		return PTR_ERR(*cp_entry);
1146 
1147 	*cp_block = cache_address(*cp_entry);
1148 
1149 	crc_offset = le32_to_cpu((*cp_block)->checksum_offset);
1150 	if (crc_offset < CP_MIN_CHKSUM_OFFSET ||
1151 			crc_offset > CP_CHKSUM_OFFSET(sbi)) {
1152 		f2fs_put_cache(*cp_entry, true);
1153 		f2fs_warn(sbi, "invalid crc_offset: %zu", crc_offset);
1154 		return -EINVAL;
1155 	}
1156 
1157 	crc = f2fs_checkpoint_chksum(sbi, *cp_block);
1158 	if (crc != cur_cp_crc(*cp_block)) {
1159 		f2fs_put_cache(*cp_entry, true);
1160 		f2fs_warn(sbi, "invalid crc value");
1161 		return -EINVAL;
1162 	}
1163 
1164 	*version = cur_cp_version(*cp_block);
1165 	return 0;
1166 }
1167 
1168 static struct f2fs_cached_block *validate_checkpoint(struct f2fs_sb_info *sbi,
1169 				block_t cp_addr, unsigned long long *version)
1170 {
1171 	struct f2fs_cached_block *cp_entry_1 = NULL, *cp_entry_2 = NULL;
1172 	struct f2fs_checkpoint *cp_block = NULL;
1173 	unsigned long long cur_version = 0, pre_version = 0;
1174 	unsigned int cp_blocks;
1175 	int err;
1176 
1177 	err = get_checkpoint_version(sbi, cp_addr, &cp_block,
1178 					&cp_entry_1, version);
1179 	if (err)
1180 		return NULL;
1181 
1182 	cp_blocks = le32_to_cpu(cp_block->cp_pack_total_block_count);
1183 
1184 	if (cp_blocks > BLKS_PER_SEG(sbi) || cp_blocks <= F2FS_CP_PACKS) {
1185 		f2fs_warn(sbi, "invalid cp_pack_total_block_count:%u",
1186 			  le32_to_cpu(cp_block->cp_pack_total_block_count));
1187 		goto invalid_cp;
1188 	}
1189 	pre_version = *version;
1190 
1191 	cp_addr += cp_blocks - 1;
1192 	err = get_checkpoint_version(sbi, cp_addr, &cp_block,
1193 					&cp_entry_2, version);
1194 	if (err)
1195 		goto invalid_cp;
1196 	cur_version = *version;
1197 
1198 	if (cur_version == pre_version) {
1199 		*version = cur_version;
1200 		f2fs_put_cache(cp_entry_2, true);
1201 		return cp_entry_1;
1202 	}
1203 	f2fs_put_cache(cp_entry_2, true);
1204 invalid_cp:
1205 	f2fs_put_cache(cp_entry_1, true);
1206 	return NULL;
1207 }
1208 
1209 int f2fs_get_valid_checkpoint(struct f2fs_sb_info *sbi)
1210 {
1211 	struct f2fs_checkpoint *cp_block;
1212 	struct f2fs_super_block *fsb = sbi->raw_super;
1213 	struct f2fs_cached_block *cp1 = NULL, *cp2 = NULL, *cur_entry;
1214 	unsigned long blk_size = sbi->blocksize;
1215 	unsigned long long cp1_version = 0, cp2_version = 0;
1216 	unsigned long long cp_start_blk_no;
1217 	unsigned int cp_blks = 1 + __cp_payload(sbi);
1218 	block_t cp_blk_no;
1219 	int i;
1220 	int err;
1221 
1222 	sbi->ckpt = f2fs_kvzalloc(sbi, array_size(blk_size, cp_blks),
1223 				  GFP_KERNEL);
1224 	if (!sbi->ckpt)
1225 		return -ENOMEM;
1226 	/*
1227 	 * Finding out valid cp block involves read both
1228 	 * sets( cp pack 1 and cp pack 2)
1229 	 */
1230 	cp_start_blk_no = le32_to_cpu(fsb->cp_blkaddr);
1231 	cp1 = validate_checkpoint(sbi, cp_start_blk_no, &cp1_version);
1232 
1233 	/* The second checkpoint pack should start at the next segment */
1234 	cp_start_blk_no += ((unsigned long long)1) <<
1235 				le32_to_cpu(fsb->log_blocks_per_seg);
1236 	cp2 = validate_checkpoint(sbi, cp_start_blk_no, &cp2_version);
1237 
1238 	if (cp1 && cp2) {
1239 		if (ver_after(cp2_version, cp1_version))
1240 			cur_entry = cp2;
1241 		else
1242 			cur_entry = cp1;
1243 	} else if (cp1) {
1244 		cur_entry = cp1;
1245 	} else if (cp2) {
1246 		cur_entry = cp2;
1247 	} else {
1248 		err = -EFSCORRUPTED;
1249 		goto fail_no_cp;
1250 	}
1251 
1252 	cp_block = cache_address(cur_entry);
1253 	memcpy(sbi->ckpt, cp_block, blk_size);
1254 
1255 	if (cur_entry == cp1)
1256 		sbi->cur_cp_pack = 1;
1257 	else
1258 		sbi->cur_cp_pack = 2;
1259 
1260 	/* Sanity checking of checkpoint */
1261 	if (f2fs_sanity_check_ckpt(sbi)) {
1262 		err = -EFSCORRUPTED;
1263 		goto free_fail_no_cp;
1264 	}
1265 
1266 	if (cp_blks <= 1)
1267 		goto done;
1268 
1269 	cp_blk_no = le32_to_cpu(fsb->cp_blkaddr);
1270 	if (cur_entry == cp2)
1271 		cp_blk_no += BIT(le32_to_cpu(fsb->log_blocks_per_seg));
1272 
1273 	for (i = 1; i < cp_blks; i++) {
1274 		struct f2fs_cached_block *cur_entry_payload;
1275 		void *sit_bitmap_ptr;
1276 		unsigned char *ckpt = (unsigned char *)sbi->ckpt;
1277 
1278 		cur_entry_payload = f2fs_get_meta_cache(sbi, cp_blk_no + i);
1279 		if (IS_ERR(cur_entry_payload)) {
1280 			err = PTR_ERR(cur_entry_payload);
1281 			goto free_fail_no_cp;
1282 		}
1283 		sit_bitmap_ptr = cache_address(cur_entry_payload);
1284 		memcpy(ckpt + i * blk_size, sit_bitmap_ptr, blk_size);
1285 		f2fs_put_cache(cur_entry_payload, true);
1286 	}
1287 done:
1288 	f2fs_put_cache(cp1, true);
1289 	f2fs_put_cache(cp2, true);
1290 	return 0;
1291 
1292 free_fail_no_cp:
1293 	f2fs_put_cache(cp1, true);
1294 	f2fs_put_cache(cp2, true);
1295 fail_no_cp:
1296 	kvfree(sbi->ckpt);
1297 	return err;
1298 }
1299 
1300 static void __add_dirty_inode(struct inode *inode, enum inode_type type)
1301 {
1302 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1303 	int flag = (type == DIR_INODE) ? FI_DIRTY_DIR : FI_DIRTY_FILE;
1304 
1305 	if (is_inode_flag_set(inode, flag))
1306 		return;
1307 
1308 	set_inode_flag(inode, flag);
1309 	list_add_tail(&F2FS_I(inode)->dirty_list, &sbi->inode_list[type]);
1310 	stat_inc_dirty_inode(sbi, type);
1311 }
1312 
1313 static void __remove_dirty_inode(struct inode *inode, enum inode_type type)
1314 {
1315 	int flag = (type == DIR_INODE) ? FI_DIRTY_DIR : FI_DIRTY_FILE;
1316 
1317 	if (get_dirty_pages(inode) || !is_inode_flag_set(inode, flag))
1318 		return;
1319 
1320 	list_del_init(&F2FS_I(inode)->dirty_list);
1321 	clear_inode_flag(inode, flag);
1322 	stat_dec_dirty_inode(F2FS_I_SB(inode), type);
1323 }
1324 
1325 void f2fs_update_dirty_folio(struct inode *inode, struct folio *folio)
1326 {
1327 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1328 	enum inode_type type = S_ISDIR(inode->i_mode) ? DIR_INODE : FILE_INODE;
1329 
1330 	if (!S_ISDIR(inode->i_mode) && !S_ISREG(inode->i_mode) &&
1331 			!S_ISLNK(inode->i_mode))
1332 		return;
1333 
1334 	spin_lock(&sbi->inode_lock[type]);
1335 	if (type != FILE_INODE || test_opt(sbi, DATA_FLUSH))
1336 		__add_dirty_inode(inode, type);
1337 	inode_inc_dirty_pages(inode);
1338 	spin_unlock(&sbi->inode_lock[type]);
1339 
1340 	folio_set_f2fs_reference(folio);
1341 }
1342 
1343 void f2fs_remove_dirty_inode(struct inode *inode)
1344 {
1345 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1346 	enum inode_type type = S_ISDIR(inode->i_mode) ? DIR_INODE : FILE_INODE;
1347 
1348 	if (!S_ISDIR(inode->i_mode) && !S_ISREG(inode->i_mode) &&
1349 			!S_ISLNK(inode->i_mode))
1350 		return;
1351 
1352 	if (type == FILE_INODE && !test_opt(sbi, DATA_FLUSH))
1353 		return;
1354 
1355 	spin_lock(&sbi->inode_lock[type]);
1356 	__remove_dirty_inode(inode, type);
1357 	spin_unlock(&sbi->inode_lock[type]);
1358 }
1359 
1360 int f2fs_sync_dirty_inodes(struct f2fs_sb_info *sbi, enum inode_type type,
1361 						bool from_cp)
1362 {
1363 	struct list_head *head;
1364 	struct inode *inode;
1365 	struct f2fs_inode_info *fi;
1366 	bool is_dir = (type == DIR_INODE);
1367 	unsigned long ino = 0;
1368 
1369 	trace_f2fs_sync_dirty_inodes_enter(sbi->sb, is_dir,
1370 				get_nr_caches(sbi, is_dir ?
1371 				F2FS_DIRTY_DENTS : F2FS_DIRTY_DATA));
1372 retry:
1373 	if (unlikely(f2fs_cp_error(sbi))) {
1374 		trace_f2fs_sync_dirty_inodes_exit(sbi->sb, is_dir,
1375 				get_nr_caches(sbi, is_dir ?
1376 				F2FS_DIRTY_DENTS : F2FS_DIRTY_DATA));
1377 		return -EIO;
1378 	}
1379 
1380 	spin_lock(&sbi->inode_lock[type]);
1381 
1382 	head = &sbi->inode_list[type];
1383 	if (list_empty(head)) {
1384 		spin_unlock(&sbi->inode_lock[type]);
1385 		trace_f2fs_sync_dirty_inodes_exit(sbi->sb, is_dir,
1386 				get_nr_caches(sbi, is_dir ?
1387 				F2FS_DIRTY_DENTS : F2FS_DIRTY_DATA));
1388 		return 0;
1389 	}
1390 	fi = list_first_entry(head, struct f2fs_inode_info, dirty_list);
1391 	list_move_tail(&fi->dirty_list, head);
1392 	inode = igrab(&fi->vfs_inode);
1393 	spin_unlock(&sbi->inode_lock[type]);
1394 	if (inode) {
1395 		unsigned long cur_ino = inode->i_ino;
1396 
1397 		if (from_cp)
1398 			F2FS_I(inode)->cp_task = current;
1399 		F2FS_I(inode)->wb_task = current;
1400 
1401 		filemap_fdatawrite(inode->i_mapping);
1402 
1403 		F2FS_I(inode)->wb_task = NULL;
1404 		if (from_cp)
1405 			F2FS_I(inode)->cp_task = NULL;
1406 
1407 		iput(inode);
1408 		/* We need to give cpu to another writers. */
1409 		if (ino == cur_ino)
1410 			cond_resched();
1411 		else
1412 			ino = cur_ino;
1413 	} else {
1414 		cond_resched();
1415 	}
1416 	goto retry;
1417 }
1418 
1419 static int f2fs_sync_inode_meta(struct f2fs_sb_info *sbi)
1420 {
1421 	struct list_head *head = &sbi->inode_list[DIRTY_META];
1422 	struct inode *inode;
1423 	struct f2fs_inode_info *fi;
1424 	s64 total = get_nr_caches(sbi, F2FS_DIRTY_IMETA);
1425 
1426 	while (total--) {
1427 		if (unlikely(f2fs_cp_error(sbi)))
1428 			return -EIO;
1429 
1430 		spin_lock(&sbi->inode_lock[DIRTY_META]);
1431 		if (list_empty(head)) {
1432 			spin_unlock(&sbi->inode_lock[DIRTY_META]);
1433 			return 0;
1434 		}
1435 		fi = list_first_entry(head, struct f2fs_inode_info,
1436 							gdirty_list);
1437 		list_move_tail(&fi->gdirty_list, head);
1438 		inode = igrab(&fi->vfs_inode);
1439 		spin_unlock(&sbi->inode_lock[DIRTY_META]);
1440 		if (inode) {
1441 			sync_inode_metadata(inode, 0);
1442 
1443 			/* it's on eviction */
1444 			if (is_inode_flag_set(inode, FI_DIRTY_INODE))
1445 				f2fs_update_inode_cache(inode);
1446 			iput(inode);
1447 		} else {
1448 			cond_resched();
1449 		}
1450 	}
1451 	return 0;
1452 }
1453 
1454 static void __prepare_cp_block(struct f2fs_sb_info *sbi)
1455 {
1456 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
1457 	struct f2fs_nm_info *nm_i = NM_I(sbi);
1458 	nid_t last_nid = nm_i->next_scan_nid;
1459 
1460 	next_free_nid(sbi, &last_nid);
1461 	ckpt->valid_block_count = cpu_to_le64(valid_user_blocks(sbi));
1462 	ckpt->valid_node_count = cpu_to_le32(valid_node_count(sbi));
1463 	ckpt->valid_inode_count = cpu_to_le32(valid_inode_count(sbi));
1464 	ckpt->next_free_nid = cpu_to_le32(last_nid);
1465 
1466 	/* update user_block_counts */
1467 	sbi->last_valid_block_count = sbi->total_valid_block_count;
1468 	percpu_counter_set(&sbi->alloc_valid_block_count, 0);
1469 	percpu_counter_set(&sbi->rf_node_block_count, 0);
1470 }
1471 
1472 static bool __need_flush_quota(struct f2fs_sb_info *sbi)
1473 {
1474 	bool ret = false;
1475 
1476 	if (!is_journalled_quota(sbi))
1477 		return false;
1478 
1479 	if (!f2fs_down_write_trylock(&sbi->quota_sem))
1480 		return true;
1481 	if (is_sbi_flag_set(sbi, SBI_QUOTA_SKIP_FLUSH)) {
1482 		ret = false;
1483 	} else if (is_sbi_flag_set(sbi, SBI_QUOTA_NEED_REPAIR)) {
1484 		ret = false;
1485 	} else if (is_sbi_flag_set(sbi, SBI_QUOTA_NEED_FLUSH)) {
1486 		clear_sbi_flag(sbi, SBI_QUOTA_NEED_FLUSH);
1487 		ret = true;
1488 	} else if (get_nr_caches(sbi, F2FS_DIRTY_QDATA)) {
1489 		ret = true;
1490 	}
1491 	f2fs_up_write(&sbi->quota_sem);
1492 	return ret;
1493 }
1494 
1495 /*
1496  * Freeze all the FS-operations for checkpoint.
1497  */
1498 static int block_operations(struct f2fs_sb_info *sbi)
1499 {
1500 	int err = 0, cnt = 0;
1501 
1502 	/*
1503 	 * Let's flush inline_data in dirty node caches.
1504 	 */
1505 	f2fs_flush_inline_data(sbi);
1506 
1507 retry_flush_quotas:
1508 	f2fs_lock_all(sbi);
1509 	if (__need_flush_quota(sbi)) {
1510 		bool need_lock = sbi->umount_lock_holder != current;
1511 
1512 		if (++cnt > DEFAULT_RETRY_QUOTA_FLUSH_COUNT) {
1513 			set_sbi_flag(sbi, SBI_QUOTA_SKIP_FLUSH);
1514 			set_sbi_flag(sbi, SBI_QUOTA_NEED_FLUSH);
1515 			goto retry_flush_dents;
1516 		}
1517 		f2fs_unlock_all(sbi);
1518 
1519 		/* don't grab s_umount lock during mount/umount/remount/freeze/quotactl */
1520 		if (!need_lock) {
1521 			f2fs_do_quota_sync(sbi->sb, -1);
1522 		} else if (down_read_trylock(&sbi->sb->s_umount)) {
1523 			f2fs_do_quota_sync(sbi->sb, -1);
1524 			up_read(&sbi->sb->s_umount);
1525 		}
1526 		cond_resched();
1527 		goto retry_flush_quotas;
1528 	}
1529 
1530 retry_flush_dents:
1531 	/* write all the dirty dentry pages */
1532 	if (get_nr_caches(sbi, F2FS_DIRTY_DENTS)) {
1533 		f2fs_unlock_all(sbi);
1534 		err = f2fs_sync_dirty_inodes(sbi, DIR_INODE, true);
1535 		if (err)
1536 			return err;
1537 		cond_resched();
1538 		goto retry_flush_quotas;
1539 	}
1540 
1541 	/*
1542 	 * POR: we should ensure that there are no dirty node caches
1543 	 * until finishing nat/sit flush. inode->i_blocks can be updated.
1544 	 */
1545 	f2fs_down_write(&sbi->node_change);
1546 
1547 	if (get_nr_caches(sbi, F2FS_DIRTY_IMETA)) {
1548 		f2fs_up_write(&sbi->node_change);
1549 		f2fs_unlock_all(sbi);
1550 		err = f2fs_sync_inode_meta(sbi);
1551 		if (err)
1552 			return err;
1553 		cond_resched();
1554 		goto retry_flush_quotas;
1555 	}
1556 
1557 retry_flush_nodes:
1558 	f2fs_down_write(&sbi->node_write);
1559 
1560 	if (get_nr_caches(sbi, F2FS_DIRTY_NODES)) {
1561 		f2fs_up_write(&sbi->node_write);
1562 		atomic_inc(&sbi->wb_sync_req[NODE]);
1563 		err = f2fs_writeback_node_caches(sbi, LONG_MAX,
1564 			true, false, FS_CP_NODE_IO, NULL);
1565 		atomic_dec(&sbi->wb_sync_req[NODE]);
1566 		if (err) {
1567 			f2fs_up_write(&sbi->node_change);
1568 			f2fs_unlock_all(sbi);
1569 			return err;
1570 		}
1571 		cond_resched();
1572 		goto retry_flush_nodes;
1573 	}
1574 
1575 	/*
1576 	 * sbi->node_change is used only for AIO write_begin path which produces
1577 	 * dirty node blocks and some checkpoint values by block allocation.
1578 	 */
1579 	__prepare_cp_block(sbi);
1580 	f2fs_up_write(&sbi->node_change);
1581 	return err;
1582 }
1583 
1584 static void unblock_operations(struct f2fs_sb_info *sbi)
1585 {
1586 	f2fs_up_write(&sbi->node_write);
1587 	f2fs_unlock_all(sbi);
1588 }
1589 
1590 void f2fs_sync_dirty_data(struct f2fs_sb_info *sbi, int type)
1591 {
1592 	DEFINE_WAIT(wait);
1593 
1594 	for (;;) {
1595 		if (!get_nr_caches(sbi, type))
1596 			break;
1597 
1598 		if (unlikely(f2fs_cp_error(sbi) &&
1599 			!is_sbi_flag_set(sbi, SBI_IS_CLOSE)))
1600 			break;
1601 
1602 		if (type == F2FS_DIRTY_META)
1603 			f2fs_sync_meta_caches(sbi, LONG_MAX, true, FS_META_IO);
1604 		else if (type == F2FS_WB_CP_DATA)
1605 			f2fs_submit_merged_write(sbi, DATA);
1606 
1607 		prepare_to_wait(&sbi->cp_wait, &wait, TASK_UNINTERRUPTIBLE);
1608 		io_schedule_timeout(DEFAULT_SCHEDULE_TIMEOUT);
1609 	}
1610 	finish_wait(&sbi->cp_wait, &wait);
1611 }
1612 
1613 static void update_ckpt_flags(struct f2fs_sb_info *sbi, struct cp_control *cpc)
1614 {
1615 	unsigned long orphan_num = sbi->im[ORPHAN_INO].ino_num;
1616 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
1617 	unsigned long flags;
1618 
1619 	spin_lock_irqsave(&sbi->cp_lock, flags);
1620 
1621 	if ((cpc->reason & CP_UMOUNT) &&
1622 			le32_to_cpu(ckpt->cp_pack_total_block_count) >
1623 			sbi->blocks_per_seg - NM_I(sbi)->nat_bits_blocks)
1624 		disable_nat_bits(sbi, false);
1625 
1626 	if (cpc->reason & CP_TRIMMED)
1627 		__set_ckpt_flags(ckpt, CP_TRIMMED_FLAG);
1628 	else
1629 		__clear_ckpt_flags(ckpt, CP_TRIMMED_FLAG);
1630 
1631 	if (cpc->reason & CP_UMOUNT)
1632 		__set_ckpt_flags(ckpt, CP_UMOUNT_FLAG);
1633 	else
1634 		__clear_ckpt_flags(ckpt, CP_UMOUNT_FLAG);
1635 
1636 	if (cpc->reason & CP_FASTBOOT)
1637 		__set_ckpt_flags(ckpt, CP_FASTBOOT_FLAG);
1638 	else
1639 		__clear_ckpt_flags(ckpt, CP_FASTBOOT_FLAG);
1640 
1641 	if (orphan_num)
1642 		__set_ckpt_flags(ckpt, CP_ORPHAN_PRESENT_FLAG);
1643 	else
1644 		__clear_ckpt_flags(ckpt, CP_ORPHAN_PRESENT_FLAG);
1645 
1646 	if (is_sbi_flag_set(sbi, SBI_NEED_FSCK))
1647 		__set_ckpt_flags(ckpt, CP_FSCK_FLAG);
1648 
1649 	if (is_sbi_flag_set(sbi, SBI_IS_RESIZEFS))
1650 		__set_ckpt_flags(ckpt, CP_RESIZEFS_FLAG);
1651 	else
1652 		__clear_ckpt_flags(ckpt, CP_RESIZEFS_FLAG);
1653 
1654 	if (is_sbi_flag_set(sbi, SBI_CP_DISABLED))
1655 		__set_ckpt_flags(ckpt, CP_DISABLED_FLAG);
1656 	else
1657 		__clear_ckpt_flags(ckpt, CP_DISABLED_FLAG);
1658 
1659 	if (is_sbi_flag_set(sbi, SBI_CP_DISABLED_QUICK))
1660 		__set_ckpt_flags(ckpt, CP_DISABLED_QUICK_FLAG);
1661 	else
1662 		__clear_ckpt_flags(ckpt, CP_DISABLED_QUICK_FLAG);
1663 
1664 	if (is_sbi_flag_set(sbi, SBI_QUOTA_SKIP_FLUSH))
1665 		__set_ckpt_flags(ckpt, CP_QUOTA_NEED_FSCK_FLAG);
1666 	else
1667 		__clear_ckpt_flags(ckpt, CP_QUOTA_NEED_FSCK_FLAG);
1668 
1669 	if (is_sbi_flag_set(sbi, SBI_QUOTA_NEED_REPAIR))
1670 		__set_ckpt_flags(ckpt, CP_QUOTA_NEED_FSCK_FLAG);
1671 
1672 	/* set this flag to activate crc|cp_ver for recovery */
1673 	__set_ckpt_flags(ckpt, CP_CRC_RECOVERY_FLAG);
1674 	__clear_ckpt_flags(ckpt, CP_NOCRC_RECOVERY_FLAG);
1675 
1676 	spin_unlock_irqrestore(&sbi->cp_lock, flags);
1677 }
1678 
1679 static void commit_checkpoint(struct f2fs_sb_info *sbi,
1680 	void *src, block_t blk_addr)
1681 {
1682 	struct f2fs_cached_block *entry = f2fs_grab_meta_cache(sbi, blk_addr);
1683 
1684 	memcpy(cache_address(entry), src, F2FS_BLKSIZE(sbi));
1685 
1686 	f2fs_mark_cache_dirty(entry);
1687 	if (unlikely(!f2fs_cache_test_and_clear_dirty(entry)))
1688 		f2fs_bug_on(sbi, 1);
1689 
1690 	/* writeout cp pack 2 cache */
1691 	if (unlikely(!__f2fs_write_meta_cache(entry, FS_CP_META_IO))) {
1692 		if (f2fs_cp_error(sbi)) {
1693 			f2fs_put_cache(entry, true);
1694 			return;
1695 		}
1696 		f2fs_bug_on(sbi, true);
1697 	}
1698 
1699 	f2fs_put_cache(entry, false);
1700 
1701 	/* submit checkpoint (with barrier if NOBARRIER is not set) */
1702 	f2fs_submit_merged_write(sbi, META_FLUSH);
1703 }
1704 
1705 static inline u64 get_sectors_written(struct block_device *bdev)
1706 {
1707 	return (u64)part_stat_read(bdev, sectors[STAT_WRITE]);
1708 }
1709 
1710 u64 f2fs_get_sectors_written(struct f2fs_sb_info *sbi)
1711 {
1712 	if (f2fs_is_multi_device(sbi)) {
1713 		u64 sectors = 0;
1714 		int i;
1715 
1716 		for (i = 0; i < sbi->s_ndevs; i++)
1717 			sectors += get_sectors_written(FDEV(i).bdev);
1718 
1719 		return sectors;
1720 	}
1721 
1722 	return get_sectors_written(sbi->sb->s_bdev);
1723 }
1724 
1725 static inline void stat_cp_time(struct cp_control *cpc, enum cp_time type)
1726 {
1727 	cpc->stats.times[type] = ktime_get();
1728 }
1729 
1730 static inline void check_cp_time(struct f2fs_sb_info *sbi, struct cp_control *cpc)
1731 {
1732 	unsigned long long sb_diff, cur_diff;
1733 	enum cp_time ct;
1734 
1735 	sb_diff = (u64)ktime_ms_delta(sbi->cp_stats.times[CP_TIME_END],
1736 					sbi->cp_stats.times[CP_TIME_START]);
1737 	cur_diff = (u64)ktime_ms_delta(cpc->stats.times[CP_TIME_END],
1738 					cpc->stats.times[CP_TIME_START]);
1739 
1740 	if (cur_diff > sb_diff) {
1741 		sbi->cp_stats = cpc->stats;
1742 		if (cur_diff < CP_LONG_LATENCY_THRESHOLD)
1743 			return;
1744 
1745 		f2fs_warn(sbi, "checkpoint was blocked for %llu ms", cur_diff);
1746 		for (ct = CP_TIME_START; ct < CP_TIME_MAX - 1; ct++)
1747 			f2fs_warn(sbi, "Step#%d: %llu ms", ct,
1748 				(u64)ktime_ms_delta(cpc->stats.times[ct + 1],
1749 						cpc->stats.times[ct]));
1750 	}
1751 }
1752 
1753 static int do_checkpoint(struct f2fs_sb_info *sbi, struct cp_control *cpc)
1754 {
1755 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
1756 	struct f2fs_nm_info *nm_i = NM_I(sbi);
1757 	unsigned long orphan_num = sbi->im[ORPHAN_INO].ino_num, flags;
1758 	block_t start_blk;
1759 	unsigned int data_sum_blocks, orphan_blocks;
1760 	__u32 crc32 = 0;
1761 	int i;
1762 	int cp_payload_blks = __cp_payload(sbi);
1763 	struct curseg_info *seg_i = CURSEG_I(sbi, CURSEG_HOT_NODE);
1764 	u64 kbytes_written;
1765 	int err;
1766 
1767 	/* Flush all the NAT/SIT caches */
1768 	f2fs_sync_meta_caches(sbi, LONG_MAX, true, FS_CP_META_IO);
1769 
1770 	stat_cp_time(cpc, CP_TIME_SYNC_META);
1771 
1772 	/* start to update checkpoint, cp ver is already updated previously */
1773 	ckpt->elapsed_time = cpu_to_le64(get_mtime(sbi, true));
1774 	ckpt->free_segment_count = cpu_to_le32(free_segments(sbi));
1775 	for (i = 0; i < NR_CURSEG_NODE_TYPE; i++) {
1776 		struct curseg_info *curseg = CURSEG_I(sbi, i + CURSEG_HOT_NODE);
1777 
1778 		ckpt->cur_node_segno[i] = cpu_to_le32(curseg->segno);
1779 		ckpt->cur_node_blkoff[i] = cpu_to_le16(curseg->next_blkoff);
1780 		ckpt->alloc_type[i + CURSEG_HOT_NODE] = curseg->alloc_type;
1781 	}
1782 	for (i = 0; i < NR_CURSEG_DATA_TYPE; i++) {
1783 		struct curseg_info *curseg = CURSEG_I(sbi, i + CURSEG_HOT_DATA);
1784 
1785 		ckpt->cur_data_segno[i] = cpu_to_le32(curseg->segno);
1786 		ckpt->cur_data_blkoff[i] = cpu_to_le16(curseg->next_blkoff);
1787 		ckpt->alloc_type[i + CURSEG_HOT_DATA] = curseg->alloc_type;
1788 	}
1789 
1790 	/* 2 cp + n data seg summary + orphan inode blocks */
1791 	data_sum_blocks = f2fs_nblocks_for_summary_flush(sbi, false);
1792 	spin_lock_irqsave(&sbi->cp_lock, flags);
1793 	if (data_sum_blocks < NR_CURSEG_DATA_TYPE)
1794 		__set_ckpt_flags(ckpt, CP_COMPACT_SUM_FLAG);
1795 	else
1796 		__clear_ckpt_flags(ckpt, CP_COMPACT_SUM_FLAG);
1797 	spin_unlock_irqrestore(&sbi->cp_lock, flags);
1798 
1799 	orphan_blocks = GET_ORPHAN_BLOCKS(sbi, orphan_num);
1800 	ckpt->cp_pack_start_sum = cpu_to_le32(1 + cp_payload_blks +
1801 			orphan_blocks);
1802 
1803 	if (__remain_node_summaries(cpc->reason))
1804 		ckpt->cp_pack_total_block_count = cpu_to_le32(F2FS_CP_PACKS +
1805 				cp_payload_blks + data_sum_blocks +
1806 				orphan_blocks + NR_CURSEG_NODE_TYPE);
1807 	else
1808 		ckpt->cp_pack_total_block_count = cpu_to_le32(F2FS_CP_PACKS +
1809 				cp_payload_blks + data_sum_blocks +
1810 				orphan_blocks);
1811 
1812 	/* update ckpt flag for checkpoint */
1813 	update_ckpt_flags(sbi, cpc);
1814 
1815 	/* update SIT/NAT bitmap */
1816 	get_sit_bitmap(sbi, __bitmap_ptr(sbi, SIT_BITMAP));
1817 	get_nat_bitmap(sbi, __bitmap_ptr(sbi, NAT_BITMAP));
1818 
1819 	crc32 = f2fs_checkpoint_chksum(sbi, ckpt);
1820 	*((__le32 *)((unsigned char *)ckpt +
1821 				le32_to_cpu(ckpt->checksum_offset)))
1822 				= cpu_to_le32(crc32);
1823 
1824 	start_blk = __start_cp_next_addr(sbi);
1825 
1826 	/* write nat bits */
1827 	if (enabled_nat_bits(sbi, cpc)) {
1828 		__u64 cp_ver = cur_cp_version(ckpt);
1829 		block_t blk;
1830 
1831 		cp_ver |= ((__u64)crc32 << 32);
1832 		*(__le64 *)nm_i->nat_bits = cpu_to_le64(cp_ver);
1833 
1834 		blk = start_blk + BLKS_PER_SEG(sbi) - nm_i->nat_bits_blocks;
1835 		for (i = 0; i < nm_i->nat_bits_blocks; i++)
1836 			f2fs_update_meta_block(sbi, nm_i->nat_bits +
1837 					F2FS_BLK_TO_BYTES(sbi, i), blk + i);
1838 	}
1839 
1840 	/* write out checkpoint buffer at block 0 */
1841 	f2fs_update_meta_block(sbi, ckpt, start_blk++);
1842 
1843 	for (i = 1; i < 1 + cp_payload_blks; i++)
1844 		f2fs_update_meta_block(sbi, (char *)ckpt +
1845 				i * F2FS_BLKSIZE(sbi), start_blk++);
1846 
1847 	if (orphan_num) {
1848 		write_orphan_inodes(sbi, start_blk);
1849 		start_blk += orphan_blocks;
1850 	}
1851 
1852 	f2fs_write_data_summaries(sbi, start_blk);
1853 	start_blk += data_sum_blocks;
1854 
1855 	/* Record write statistics in the hot node summary */
1856 	kbytes_written = sbi->kbytes_written;
1857 	kbytes_written += (f2fs_get_sectors_written(sbi) -
1858 				sbi->sectors_written_start) >> 1;
1859 	seg_i->journal->info.kbytes_written = cpu_to_le64(kbytes_written);
1860 
1861 	if (__remain_node_summaries(cpc->reason)) {
1862 		f2fs_write_node_summaries(sbi, start_blk);
1863 		start_blk += NR_CURSEG_NODE_TYPE;
1864 	}
1865 
1866 	/* Here, we have one bio having CP pack except cp pack 2 blocks */
1867 	f2fs_sync_meta_caches(sbi, LONG_MAX, true, FS_CP_META_IO);
1868 	stat_cp_time(cpc, CP_TIME_SYNC_CP_META);
1869 
1870 	/* Wait for all dirty meta blocks to be submitted for IO */
1871 	f2fs_sync_dirty_data(sbi, F2FS_DIRTY_META);
1872 	stat_cp_time(cpc, CP_TIME_WAIT_DIRTY_META);
1873 
1874 	/* wait for previous submitted meta blocks writeback */
1875 	f2fs_sync_dirty_data(sbi, F2FS_WB_CP_DATA);
1876 	stat_cp_time(cpc, CP_TIME_WAIT_CP_DATA);
1877 
1878 	/* flush all device cache */
1879 	err = f2fs_flush_device_cache(sbi);
1880 	if (err)
1881 		return err;
1882 	stat_cp_time(cpc, CP_TIME_FLUSH_DEVICE);
1883 
1884 	/* barrier and flush checkpoint cp pack 2 blocks if it can */
1885 	commit_checkpoint(sbi, ckpt, start_blk);
1886 	f2fs_sync_dirty_data(sbi, F2FS_WB_CP_DATA);
1887 	stat_cp_time(cpc, CP_TIME_WAIT_LAST_CP);
1888 
1889 	/*
1890 	 * invalidate intermediate meta cache used for migration of
1891 	 * encrypted, verity or compressed inode's blocks.
1892 	 */
1893 	if (f2fs_sb_has_encrypt(sbi) || f2fs_sb_has_verity(sbi) ||
1894 		f2fs_sb_has_compression(sbi)) {
1895 		f2fs_truncate_meta_caches(sbi, MAIN_BLKADDR(sbi),
1896 				MAX_BLKADDR(sbi) - MAIN_BLKADDR(sbi));
1897 	}
1898 
1899 	f2fs_release_ino_entry(sbi, false);
1900 
1901 	f2fs_reset_fsync_node_info(sbi);
1902 
1903 	clear_sbi_flag(sbi, SBI_IS_DIRTY);
1904 	clear_sbi_flag(sbi, SBI_NEED_CP);
1905 	clear_sbi_flag(sbi, SBI_QUOTA_SKIP_FLUSH);
1906 
1907 	spin_lock(&sbi->stat_lock);
1908 	sbi->unusable_block_count = 0;
1909 	spin_unlock(&sbi->stat_lock);
1910 
1911 	__set_cp_next_pack(sbi);
1912 
1913 	/*
1914 	 * redirty superblock if metadata like node caches or inode cache is
1915 	 * updated during writing checkpoint.
1916 	 */
1917 	if (get_nr_caches(sbi, F2FS_DIRTY_NODES) ||
1918 			get_nr_caches(sbi, F2FS_DIRTY_IMETA))
1919 		set_sbi_flag(sbi, SBI_IS_DIRTY);
1920 
1921 	f2fs_bug_on(sbi, get_nr_caches(sbi, F2FS_DIRTY_DENTS));
1922 
1923 	return unlikely(f2fs_cp_error(sbi)) ? -EIO : 0;
1924 }
1925 
1926 int f2fs_write_checkpoint(struct f2fs_sb_info *sbi, struct cp_control *cpc)
1927 {
1928 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
1929 	struct f2fs_lock_context lc;
1930 	unsigned long long ckpt_ver;
1931 	int err = 0;
1932 
1933 	stat_cp_time(cpc, CP_TIME_START);
1934 
1935 	if (f2fs_readonly(sbi->sb) || f2fs_hw_is_readonly(sbi))
1936 		return -EROFS;
1937 
1938 	if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) {
1939 		if (cpc->reason != CP_PAUSE)
1940 			return 0;
1941 		f2fs_warn(sbi, "Start checkpoint disabled!");
1942 	}
1943 	if (cpc->reason != CP_RESIZE)
1944 		f2fs_down_write_trace(&sbi->cp_global_sem, &lc);
1945 
1946 	stat_cp_time(cpc, CP_TIME_LOCK);
1947 
1948 	if (!is_sbi_flag_set(sbi, SBI_IS_DIRTY) &&
1949 		((cpc->reason & CP_FASTBOOT) || (cpc->reason & CP_SYNC) ||
1950 		((cpc->reason & CP_DISCARD) && !sbi->discard_blks)))
1951 		goto out;
1952 	if (unlikely(f2fs_cp_error(sbi))) {
1953 		err = -EIO;
1954 		goto out;
1955 	}
1956 
1957 	trace_f2fs_write_checkpoint(sbi->sb, cpc->reason, CP_PHASE_START_BLOCK_OPS);
1958 
1959 	err = block_operations(sbi);
1960 	if (err)
1961 		goto out;
1962 
1963 	stat_cp_time(cpc, CP_TIME_OP_LOCK);
1964 
1965 	trace_f2fs_write_checkpoint(sbi->sb, cpc->reason, CP_PHASE_FINISH_BLOCK_OPS);
1966 
1967 	f2fs_flush_merged_writes(sbi);
1968 
1969 	/* this is the case of multiple fstrims without any changes */
1970 	if (cpc->reason & CP_DISCARD) {
1971 		if (!f2fs_exist_trim_candidates(sbi, cpc)) {
1972 			unblock_operations(sbi);
1973 			goto out;
1974 		}
1975 
1976 		if (NM_I(sbi)->nat_cnt[DIRTY_NAT] == 0 &&
1977 				SIT_I(sbi)->dirty_sentries == 0 &&
1978 				prefree_segments(sbi) == 0) {
1979 			f2fs_flush_sit_entries(sbi, cpc);
1980 			f2fs_clear_prefree_segments(sbi, cpc);
1981 			unblock_operations(sbi);
1982 			goto out;
1983 		}
1984 	}
1985 	stat_cp_time(cpc, CP_TIME_MERGE_WRITE);
1986 
1987 	/*
1988 	 * update checkpoint pack index
1989 	 * Increase the version number so that
1990 	 * SIT entries and seg summaries are written at correct place
1991 	 */
1992 	ckpt_ver = cur_cp_version(ckpt);
1993 	ckpt->checkpoint_ver = cpu_to_le64(++ckpt_ver);
1994 
1995 	/* write cached NAT/SIT entries to NAT/SIT area */
1996 	err = f2fs_flush_nat_entries(sbi, cpc);
1997 	if (err) {
1998 		f2fs_err(sbi, "f2fs_flush_nat_entries failed err:%d, stop checkpoint", err);
1999 		f2fs_bug_on(sbi, !f2fs_cp_error(sbi));
2000 		goto stop;
2001 	}
2002 	stat_cp_time(cpc, CP_TIME_FLUSH_NAT);
2003 
2004 	f2fs_flush_sit_entries(sbi, cpc);
2005 
2006 	stat_cp_time(cpc, CP_TIME_FLUSH_SIT);
2007 
2008 	/* save inmem log status */
2009 	f2fs_save_inmem_curseg(sbi);
2010 
2011 	err = do_checkpoint(sbi, cpc);
2012 	if (err) {
2013 		f2fs_err(sbi, "do_checkpoint failed err:%d, stop checkpoint", err);
2014 		f2fs_bug_on(sbi, !f2fs_cp_error(sbi));
2015 		f2fs_release_discard_addrs(sbi);
2016 	} else {
2017 		f2fs_clear_prefree_segments(sbi, cpc);
2018 	}
2019 
2020 	f2fs_restore_inmem_curseg(sbi);
2021 	f2fs_reinit_atgc_curseg(sbi);
2022 	stat_inc_cp_count(sbi);
2023 stop:
2024 	unblock_operations(sbi);
2025 	stat_cp_time(cpc, CP_TIME_END);
2026 	check_cp_time(sbi, cpc);
2027 
2028 	if (cpc->reason & CP_RECOVERY)
2029 		f2fs_notice(sbi, "checkpoint: version = %llx", ckpt_ver);
2030 
2031 	/* update CP_TIME to trigger checkpoint periodically */
2032 	f2fs_update_time(sbi, CP_TIME);
2033 	trace_f2fs_write_checkpoint(sbi->sb, cpc->reason, CP_PHASE_FINISH_CHECKPOINT);
2034 out:
2035 	if (cpc->reason != CP_RESIZE)
2036 		f2fs_up_write_trace(&sbi->cp_global_sem, &lc);
2037 	return err;
2038 }
2039 
2040 void f2fs_init_ino_entry_info(struct f2fs_sb_info *sbi)
2041 {
2042 	int i;
2043 
2044 	for (i = 0; i < MAX_INO_ENTRY; i++) {
2045 		struct inode_management *im = &sbi->im[i];
2046 
2047 		INIT_RADIX_TREE(&im->ino_root, GFP_ATOMIC);
2048 		spin_lock_init(&im->ino_lock);
2049 		INIT_LIST_HEAD(&im->ino_list);
2050 		im->ino_num = 0;
2051 	}
2052 
2053 	sbi->max_orphans = (BLKS_PER_SEG(sbi) - F2FS_CP_PACKS -
2054 			NR_CURSEG_PERSIST_TYPE - __cp_payload(sbi)) *
2055 			F2FS_ORPHANS_PER_BLOCK(sbi);
2056 }
2057 
2058 int __init f2fs_create_checkpoint_caches(void)
2059 {
2060 	ino_entry_slab = f2fs_kmem_cache_create("f2fs_ino_entry",
2061 			sizeof(struct ino_entry));
2062 	if (!ino_entry_slab)
2063 		return -ENOMEM;
2064 	f2fs_inode_entry_slab = f2fs_kmem_cache_create("f2fs_inode_entry",
2065 			sizeof(struct inode_entry));
2066 	if (!f2fs_inode_entry_slab) {
2067 		kmem_cache_destroy(ino_entry_slab);
2068 		return -ENOMEM;
2069 	}
2070 	return 0;
2071 }
2072 
2073 void f2fs_destroy_checkpoint_caches(void)
2074 {
2075 	kmem_cache_destroy(ino_entry_slab);
2076 	kmem_cache_destroy(f2fs_inode_entry_slab);
2077 }
2078 
2079 static int __write_checkpoint_sync(struct f2fs_sb_info *sbi)
2080 {
2081 	struct cp_control cpc = { .reason = CP_SYNC, };
2082 	struct f2fs_lock_context lc;
2083 	int err;
2084 
2085 	f2fs_down_write_trace(&sbi->gc_lock, &lc);
2086 	err = f2fs_write_checkpoint(sbi, &cpc);
2087 	f2fs_up_write_trace(&sbi->gc_lock, &lc);
2088 
2089 	return err;
2090 }
2091 
2092 static void __checkpoint_and_complete_reqs(struct f2fs_sb_info *sbi)
2093 {
2094 	struct ckpt_req_control *cprc = &sbi->cprc_info;
2095 	struct ckpt_req *req, *next;
2096 	struct llist_node *dispatch_list;
2097 	u64 sum_diff = 0, diff, count = 0;
2098 	int ret;
2099 
2100 	dispatch_list = llist_del_all(&cprc->issue_list);
2101 	if (!dispatch_list)
2102 		return;
2103 	dispatch_list = llist_reverse_order(dispatch_list);
2104 
2105 	ret = __write_checkpoint_sync(sbi);
2106 	atomic_inc(&cprc->issued_ckpt);
2107 
2108 	llist_for_each_entry_safe(req, next, dispatch_list, llnode) {
2109 		diff = (u64)ktime_ms_delta(ktime_get(), req->queue_time);
2110 		req->ret = ret;
2111 		req->delta_time = diff;
2112 		complete(&req->wait);
2113 
2114 		sum_diff += diff;
2115 		count++;
2116 	}
2117 	atomic_sub(count, &cprc->queued_ckpt);
2118 	atomic_add(count, &cprc->total_ckpt);
2119 
2120 	spin_lock(&cprc->stat_lock);
2121 	cprc->cur_time = (unsigned int)div64_u64(sum_diff, count);
2122 	if (cprc->peak_time < cprc->cur_time)
2123 		cprc->peak_time = cprc->cur_time;
2124 	spin_unlock(&cprc->stat_lock);
2125 }
2126 
2127 static int issue_checkpoint_thread(void *data)
2128 {
2129 	struct f2fs_sb_info *sbi = data;
2130 	struct ckpt_req_control *cprc = &sbi->cprc_info;
2131 	wait_queue_head_t *q = &cprc->ckpt_wait_queue;
2132 repeat:
2133 	if (kthread_should_stop())
2134 		return 0;
2135 
2136 	if (!llist_empty(&cprc->issue_list))
2137 		__checkpoint_and_complete_reqs(sbi);
2138 
2139 	wait_event_interruptible(*q,
2140 		kthread_should_stop() || !llist_empty(&cprc->issue_list));
2141 	goto repeat;
2142 }
2143 
2144 static void flush_remained_ckpt_reqs(struct f2fs_sb_info *sbi,
2145 		struct ckpt_req *wait_req)
2146 {
2147 	struct ckpt_req_control *cprc = &sbi->cprc_info;
2148 
2149 	if (!llist_empty(&cprc->issue_list)) {
2150 		__checkpoint_and_complete_reqs(sbi);
2151 	} else {
2152 		/* already dispatched by issue_checkpoint_thread */
2153 		if (wait_req)
2154 			wait_for_completion(&wait_req->wait);
2155 	}
2156 }
2157 
2158 static void init_ckpt_req(struct ckpt_req *req)
2159 {
2160 	memset(req, 0, sizeof(struct ckpt_req));
2161 
2162 	init_completion(&req->wait);
2163 	req->queue_time = ktime_get();
2164 }
2165 
2166 int f2fs_issue_checkpoint(struct f2fs_sb_info *sbi)
2167 {
2168 	struct ckpt_req_control *cprc = &sbi->cprc_info;
2169 	struct ckpt_req req;
2170 	struct cp_control cpc;
2171 
2172 	cpc.reason = __get_cp_reason(sbi);
2173 	if (!test_opt(sbi, MERGE_CHECKPOINT) || cpc.reason != CP_SYNC ||
2174 		sbi->umount_lock_holder == current) {
2175 		struct f2fs_lock_context lc;
2176 		int ret;
2177 
2178 		f2fs_down_write_trace(&sbi->gc_lock, &lc);
2179 		ret = f2fs_write_checkpoint(sbi, &cpc);
2180 		f2fs_up_write_trace(&sbi->gc_lock, &lc);
2181 
2182 		return ret;
2183 	}
2184 
2185 	if (!cprc->f2fs_issue_ckpt)
2186 		return __write_checkpoint_sync(sbi);
2187 
2188 	init_ckpt_req(&req);
2189 
2190 	llist_add(&req.llnode, &cprc->issue_list);
2191 	atomic_inc(&cprc->queued_ckpt);
2192 
2193 	/*
2194 	 * update issue_list before we wake up issue_checkpoint thread,
2195 	 * this smp_mb() pairs with another barrier in ___wait_event(),
2196 	 * see more details in comments of waitqueue_active().
2197 	 */
2198 	smp_mb();
2199 
2200 	if (waitqueue_active(&cprc->ckpt_wait_queue))
2201 		wake_up(&cprc->ckpt_wait_queue);
2202 
2203 	if (cprc->f2fs_issue_ckpt)
2204 		wait_for_completion(&req.wait);
2205 	else
2206 		flush_remained_ckpt_reqs(sbi, &req);
2207 
2208 	if (unlikely(req.delta_time >= CP_LONG_LATENCY_THRESHOLD)) {
2209 		f2fs_warn_ratelimited(sbi,
2210 			"blocked on checkpoint for %u ms", cprc->peak_time);
2211 		dump_stack();
2212 	}
2213 
2214 	return req.ret;
2215 }
2216 
2217 int f2fs_start_ckpt_thread(struct f2fs_sb_info *sbi)
2218 {
2219 	dev_t dev = sbi->sb->s_bdev->bd_dev;
2220 	struct ckpt_req_control *cprc = &sbi->cprc_info;
2221 
2222 	if (cprc->f2fs_issue_ckpt)
2223 		return 0;
2224 
2225 	cprc->f2fs_issue_ckpt = kthread_run(issue_checkpoint_thread, sbi,
2226 			"f2fs_ckpt-%u:%u", MAJOR(dev), MINOR(dev));
2227 	if (IS_ERR(cprc->f2fs_issue_ckpt)) {
2228 		int err = PTR_ERR(cprc->f2fs_issue_ckpt);
2229 
2230 		cprc->f2fs_issue_ckpt = NULL;
2231 		return err;
2232 	}
2233 
2234 	set_task_ioprio(cprc->f2fs_issue_ckpt, cprc->ckpt_thread_ioprio);
2235 	set_user_nice(cprc->f2fs_issue_ckpt,
2236 			PRIO_TO_NICE(sbi->critical_task_priority));
2237 
2238 	return 0;
2239 }
2240 
2241 void f2fs_stop_ckpt_thread(struct f2fs_sb_info *sbi)
2242 {
2243 	struct ckpt_req_control *cprc = &sbi->cprc_info;
2244 	struct task_struct *ckpt_task;
2245 
2246 	if (!cprc->f2fs_issue_ckpt)
2247 		return;
2248 
2249 	ckpt_task = cprc->f2fs_issue_ckpt;
2250 	cprc->f2fs_issue_ckpt = NULL;
2251 	kthread_stop(ckpt_task);
2252 
2253 	f2fs_flush_ckpt_thread(sbi);
2254 }
2255 
2256 void f2fs_flush_ckpt_thread(struct f2fs_sb_info *sbi)
2257 {
2258 	struct ckpt_req_control *cprc = &sbi->cprc_info;
2259 
2260 	flush_remained_ckpt_reqs(sbi, NULL);
2261 
2262 	/* Let's wait for the previous dispatched checkpoint. */
2263 	while (atomic_read(&cprc->queued_ckpt))
2264 		io_schedule_timeout(DEFAULT_SCHEDULE_TIMEOUT);
2265 }
2266 
2267 void f2fs_init_ckpt_req_control(struct f2fs_sb_info *sbi)
2268 {
2269 	struct ckpt_req_control *cprc = &sbi->cprc_info;
2270 
2271 	atomic_set(&cprc->issued_ckpt, 0);
2272 	atomic_set(&cprc->total_ckpt, 0);
2273 	atomic_set(&cprc->queued_ckpt, 0);
2274 	cprc->ckpt_thread_ioprio = DEFAULT_CHECKPOINT_IOPRIO;
2275 	init_waitqueue_head(&cprc->ckpt_wait_queue);
2276 	init_llist_head(&cprc->issue_list);
2277 	spin_lock_init(&cprc->stat_lock);
2278 }
2279