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