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