xref: /linux/fs/f2fs/gc.c (revision c532de5a67a70f8533d495f8f2aaa9a0491c3ad0)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * fs/f2fs/gc.c
4  *
5  * Copyright (c) 2012 Samsung Electronics Co., Ltd.
6  *             http://www.samsung.com/
7  */
8 #include <linux/fs.h>
9 #include <linux/module.h>
10 #include <linux/init.h>
11 #include <linux/f2fs_fs.h>
12 #include <linux/kthread.h>
13 #include <linux/delay.h>
14 #include <linux/freezer.h>
15 #include <linux/sched/signal.h>
16 #include <linux/random.h>
17 #include <linux/sched/mm.h>
18 
19 #include "f2fs.h"
20 #include "node.h"
21 #include "segment.h"
22 #include "gc.h"
23 #include "iostat.h"
24 #include <trace/events/f2fs.h>
25 
26 static struct kmem_cache *victim_entry_slab;
27 
28 static unsigned int count_bits(const unsigned long *addr,
29 				unsigned int offset, unsigned int len);
30 
31 static int gc_thread_func(void *data)
32 {
33 	struct f2fs_sb_info *sbi = data;
34 	struct f2fs_gc_kthread *gc_th = sbi->gc_thread;
35 	wait_queue_head_t *wq = &sbi->gc_thread->gc_wait_queue_head;
36 	wait_queue_head_t *fggc_wq = &sbi->gc_thread->fggc_wq;
37 	unsigned int wait_ms;
38 	struct f2fs_gc_control gc_control = {
39 		.victim_segno = NULL_SEGNO,
40 		.should_migrate_blocks = false,
41 		.err_gc_skipped = false };
42 
43 	wait_ms = gc_th->min_sleep_time;
44 
45 	set_freezable();
46 	do {
47 		bool sync_mode, foreground = false;
48 
49 		wait_event_freezable_timeout(*wq,
50 				kthread_should_stop() ||
51 				waitqueue_active(fggc_wq) ||
52 				gc_th->gc_wake,
53 				msecs_to_jiffies(wait_ms));
54 
55 		if (test_opt(sbi, GC_MERGE) && waitqueue_active(fggc_wq))
56 			foreground = true;
57 
58 		/* give it a try one time */
59 		if (gc_th->gc_wake)
60 			gc_th->gc_wake = false;
61 
62 		if (f2fs_readonly(sbi->sb)) {
63 			stat_other_skip_bggc_count(sbi);
64 			continue;
65 		}
66 		if (kthread_should_stop())
67 			break;
68 
69 		if (sbi->sb->s_writers.frozen >= SB_FREEZE_WRITE) {
70 			increase_sleep_time(gc_th, &wait_ms);
71 			stat_other_skip_bggc_count(sbi);
72 			continue;
73 		}
74 
75 		if (time_to_inject(sbi, FAULT_CHECKPOINT))
76 			f2fs_stop_checkpoint(sbi, false,
77 					STOP_CP_REASON_FAULT_INJECT);
78 
79 		if (!sb_start_write_trylock(sbi->sb)) {
80 			stat_other_skip_bggc_count(sbi);
81 			continue;
82 		}
83 
84 		gc_control.one_time = false;
85 
86 		/*
87 		 * [GC triggering condition]
88 		 * 0. GC is not conducted currently.
89 		 * 1. There are enough dirty segments.
90 		 * 2. IO subsystem is idle by checking the # of writeback pages.
91 		 * 3. IO subsystem is idle by checking the # of requests in
92 		 *    bdev's request list.
93 		 *
94 		 * Note) We have to avoid triggering GCs frequently.
95 		 * Because it is possible that some segments can be
96 		 * invalidated soon after by user update or deletion.
97 		 * So, I'd like to wait some time to collect dirty segments.
98 		 */
99 		if (sbi->gc_mode == GC_URGENT_HIGH ||
100 				sbi->gc_mode == GC_URGENT_MID) {
101 			wait_ms = gc_th->urgent_sleep_time;
102 			f2fs_down_write(&sbi->gc_lock);
103 			goto do_gc;
104 		}
105 
106 		if (foreground) {
107 			f2fs_down_write(&sbi->gc_lock);
108 			goto do_gc;
109 		} else if (!f2fs_down_write_trylock(&sbi->gc_lock)) {
110 			stat_other_skip_bggc_count(sbi);
111 			goto next;
112 		}
113 
114 		if (!is_idle(sbi, GC_TIME)) {
115 			increase_sleep_time(gc_th, &wait_ms);
116 			f2fs_up_write(&sbi->gc_lock);
117 			stat_io_skip_bggc_count(sbi);
118 			goto next;
119 		}
120 
121 		if (f2fs_sb_has_blkzoned(sbi)) {
122 			if (has_enough_free_blocks(sbi,
123 				gc_th->no_zoned_gc_percent)) {
124 				wait_ms = gc_th->no_gc_sleep_time;
125 				f2fs_up_write(&sbi->gc_lock);
126 				goto next;
127 			}
128 			if (wait_ms == gc_th->no_gc_sleep_time)
129 				wait_ms = gc_th->max_sleep_time;
130 		}
131 
132 		if (need_to_boost_gc(sbi)) {
133 			decrease_sleep_time(gc_th, &wait_ms);
134 			if (f2fs_sb_has_blkzoned(sbi))
135 				gc_control.one_time = true;
136 		} else {
137 			increase_sleep_time(gc_th, &wait_ms);
138 		}
139 do_gc:
140 		stat_inc_gc_call_count(sbi, foreground ?
141 					FOREGROUND : BACKGROUND);
142 
143 		sync_mode = (F2FS_OPTION(sbi).bggc_mode == BGGC_MODE_SYNC) ||
144 				gc_control.one_time;
145 
146 		/* foreground GC was been triggered via f2fs_balance_fs() */
147 		if (foreground)
148 			sync_mode = false;
149 
150 		gc_control.init_gc_type = sync_mode ? FG_GC : BG_GC;
151 		gc_control.no_bg_gc = foreground;
152 		gc_control.nr_free_secs = foreground ? 1 : 0;
153 
154 		/* if return value is not zero, no victim was selected */
155 		if (f2fs_gc(sbi, &gc_control)) {
156 			/* don't bother wait_ms by foreground gc */
157 			if (!foreground)
158 				wait_ms = gc_th->no_gc_sleep_time;
159 		} else {
160 			/* reset wait_ms to default sleep time */
161 			if (wait_ms == gc_th->no_gc_sleep_time)
162 				wait_ms = gc_th->min_sleep_time;
163 		}
164 
165 		if (foreground)
166 			wake_up_all(&gc_th->fggc_wq);
167 
168 		trace_f2fs_background_gc(sbi->sb, wait_ms,
169 				prefree_segments(sbi), free_segments(sbi));
170 
171 		/* balancing f2fs's metadata periodically */
172 		f2fs_balance_fs_bg(sbi, true);
173 next:
174 		if (sbi->gc_mode != GC_NORMAL) {
175 			spin_lock(&sbi->gc_remaining_trials_lock);
176 			if (sbi->gc_remaining_trials) {
177 				sbi->gc_remaining_trials--;
178 				if (!sbi->gc_remaining_trials)
179 					sbi->gc_mode = GC_NORMAL;
180 			}
181 			spin_unlock(&sbi->gc_remaining_trials_lock);
182 		}
183 		sb_end_write(sbi->sb);
184 
185 	} while (!kthread_should_stop());
186 	return 0;
187 }
188 
189 int f2fs_start_gc_thread(struct f2fs_sb_info *sbi)
190 {
191 	struct f2fs_gc_kthread *gc_th;
192 	dev_t dev = sbi->sb->s_bdev->bd_dev;
193 
194 	gc_th = f2fs_kmalloc(sbi, sizeof(struct f2fs_gc_kthread), GFP_KERNEL);
195 	if (!gc_th)
196 		return -ENOMEM;
197 
198 	gc_th->urgent_sleep_time = DEF_GC_THREAD_URGENT_SLEEP_TIME;
199 	gc_th->valid_thresh_ratio = DEF_GC_THREAD_VALID_THRESH_RATIO;
200 
201 	if (f2fs_sb_has_blkzoned(sbi)) {
202 		gc_th->min_sleep_time = DEF_GC_THREAD_MIN_SLEEP_TIME_ZONED;
203 		gc_th->max_sleep_time = DEF_GC_THREAD_MAX_SLEEP_TIME_ZONED;
204 		gc_th->no_gc_sleep_time = DEF_GC_THREAD_NOGC_SLEEP_TIME_ZONED;
205 		gc_th->no_zoned_gc_percent = LIMIT_NO_ZONED_GC;
206 		gc_th->boost_zoned_gc_percent = LIMIT_BOOST_ZONED_GC;
207 	} else {
208 		gc_th->min_sleep_time = DEF_GC_THREAD_MIN_SLEEP_TIME;
209 		gc_th->max_sleep_time = DEF_GC_THREAD_MAX_SLEEP_TIME;
210 		gc_th->no_gc_sleep_time = DEF_GC_THREAD_NOGC_SLEEP_TIME;
211 		gc_th->no_zoned_gc_percent = 0;
212 		gc_th->boost_zoned_gc_percent = 0;
213 	}
214 
215 	gc_th->gc_wake = false;
216 
217 	sbi->gc_thread = gc_th;
218 	init_waitqueue_head(&sbi->gc_thread->gc_wait_queue_head);
219 	init_waitqueue_head(&sbi->gc_thread->fggc_wq);
220 	sbi->gc_thread->f2fs_gc_task = kthread_run(gc_thread_func, sbi,
221 			"f2fs_gc-%u:%u", MAJOR(dev), MINOR(dev));
222 	if (IS_ERR(gc_th->f2fs_gc_task)) {
223 		int err = PTR_ERR(gc_th->f2fs_gc_task);
224 
225 		kfree(gc_th);
226 		sbi->gc_thread = NULL;
227 		return err;
228 	}
229 
230 	return 0;
231 }
232 
233 void f2fs_stop_gc_thread(struct f2fs_sb_info *sbi)
234 {
235 	struct f2fs_gc_kthread *gc_th = sbi->gc_thread;
236 
237 	if (!gc_th)
238 		return;
239 	kthread_stop(gc_th->f2fs_gc_task);
240 	wake_up_all(&gc_th->fggc_wq);
241 	kfree(gc_th);
242 	sbi->gc_thread = NULL;
243 }
244 
245 static int select_gc_type(struct f2fs_sb_info *sbi, int gc_type)
246 {
247 	int gc_mode;
248 
249 	if (gc_type == BG_GC) {
250 		if (sbi->am.atgc_enabled)
251 			gc_mode = GC_AT;
252 		else
253 			gc_mode = GC_CB;
254 	} else {
255 		gc_mode = GC_GREEDY;
256 	}
257 
258 	switch (sbi->gc_mode) {
259 	case GC_IDLE_CB:
260 		gc_mode = GC_CB;
261 		break;
262 	case GC_IDLE_GREEDY:
263 	case GC_URGENT_HIGH:
264 		gc_mode = GC_GREEDY;
265 		break;
266 	case GC_IDLE_AT:
267 		gc_mode = GC_AT;
268 		break;
269 	}
270 
271 	return gc_mode;
272 }
273 
274 static void select_policy(struct f2fs_sb_info *sbi, int gc_type,
275 			int type, struct victim_sel_policy *p)
276 {
277 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
278 
279 	if (p->alloc_mode == SSR) {
280 		p->gc_mode = GC_GREEDY;
281 		p->dirty_bitmap = dirty_i->dirty_segmap[type];
282 		p->max_search = dirty_i->nr_dirty[type];
283 		p->ofs_unit = 1;
284 	} else if (p->alloc_mode == AT_SSR) {
285 		p->gc_mode = GC_GREEDY;
286 		p->dirty_bitmap = dirty_i->dirty_segmap[type];
287 		p->max_search = dirty_i->nr_dirty[type];
288 		p->ofs_unit = 1;
289 	} else {
290 		p->gc_mode = select_gc_type(sbi, gc_type);
291 		p->ofs_unit = SEGS_PER_SEC(sbi);
292 		if (__is_large_section(sbi)) {
293 			p->dirty_bitmap = dirty_i->dirty_secmap;
294 			p->max_search = count_bits(p->dirty_bitmap,
295 						0, MAIN_SECS(sbi));
296 		} else {
297 			p->dirty_bitmap = dirty_i->dirty_segmap[DIRTY];
298 			p->max_search = dirty_i->nr_dirty[DIRTY];
299 		}
300 	}
301 
302 	/*
303 	 * adjust candidates range, should select all dirty segments for
304 	 * foreground GC and urgent GC cases.
305 	 */
306 	if (gc_type != FG_GC &&
307 			(sbi->gc_mode != GC_URGENT_HIGH) &&
308 			(p->gc_mode != GC_AT && p->alloc_mode != AT_SSR) &&
309 			p->max_search > sbi->max_victim_search)
310 		p->max_search = sbi->max_victim_search;
311 
312 	/* let's select beginning hot/small space first. */
313 	if (f2fs_need_rand_seg(sbi))
314 		p->offset = get_random_u32_below(MAIN_SECS(sbi) *
315 						SEGS_PER_SEC(sbi));
316 	else if (type == CURSEG_HOT_DATA || IS_NODESEG(type))
317 		p->offset = 0;
318 	else
319 		p->offset = SIT_I(sbi)->last_victim[p->gc_mode];
320 }
321 
322 static unsigned int get_max_cost(struct f2fs_sb_info *sbi,
323 				struct victim_sel_policy *p)
324 {
325 	/* SSR allocates in a segment unit */
326 	if (p->alloc_mode == SSR)
327 		return BLKS_PER_SEG(sbi);
328 	else if (p->alloc_mode == AT_SSR)
329 		return UINT_MAX;
330 
331 	/* LFS */
332 	if (p->gc_mode == GC_GREEDY)
333 		return SEGS_TO_BLKS(sbi, 2 * p->ofs_unit);
334 	else if (p->gc_mode == GC_CB)
335 		return UINT_MAX;
336 	else if (p->gc_mode == GC_AT)
337 		return UINT_MAX;
338 	else /* No other gc_mode */
339 		return 0;
340 }
341 
342 static unsigned int check_bg_victims(struct f2fs_sb_info *sbi)
343 {
344 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
345 	unsigned int secno;
346 
347 	/*
348 	 * If the gc_type is FG_GC, we can select victim segments
349 	 * selected by background GC before.
350 	 * Those segments guarantee they have small valid blocks.
351 	 */
352 	for_each_set_bit(secno, dirty_i->victim_secmap, MAIN_SECS(sbi)) {
353 		if (sec_usage_check(sbi, secno))
354 			continue;
355 		clear_bit(secno, dirty_i->victim_secmap);
356 		return GET_SEG_FROM_SEC(sbi, secno);
357 	}
358 	return NULL_SEGNO;
359 }
360 
361 static unsigned int get_cb_cost(struct f2fs_sb_info *sbi, unsigned int segno)
362 {
363 	struct sit_info *sit_i = SIT_I(sbi);
364 	unsigned int secno = GET_SEC_FROM_SEG(sbi, segno);
365 	unsigned int start = GET_SEG_FROM_SEC(sbi, secno);
366 	unsigned long long mtime = 0;
367 	unsigned int vblocks;
368 	unsigned char age = 0;
369 	unsigned char u;
370 	unsigned int i;
371 	unsigned int usable_segs_per_sec = f2fs_usable_segs_in_sec(sbi);
372 
373 	for (i = 0; i < usable_segs_per_sec; i++)
374 		mtime += get_seg_entry(sbi, start + i)->mtime;
375 	vblocks = get_valid_blocks(sbi, segno, true);
376 
377 	mtime = div_u64(mtime, usable_segs_per_sec);
378 	vblocks = div_u64(vblocks, usable_segs_per_sec);
379 
380 	u = BLKS_TO_SEGS(sbi, vblocks * 100);
381 
382 	/* Handle if the system time has changed by the user */
383 	if (mtime < sit_i->min_mtime)
384 		sit_i->min_mtime = mtime;
385 	if (mtime > sit_i->max_mtime)
386 		sit_i->max_mtime = mtime;
387 	if (sit_i->max_mtime != sit_i->min_mtime)
388 		age = 100 - div64_u64(100 * (mtime - sit_i->min_mtime),
389 				sit_i->max_mtime - sit_i->min_mtime);
390 
391 	return UINT_MAX - ((100 * (100 - u) * age) / (100 + u));
392 }
393 
394 static inline unsigned int get_gc_cost(struct f2fs_sb_info *sbi,
395 			unsigned int segno, struct victim_sel_policy *p)
396 {
397 	if (p->alloc_mode == SSR)
398 		return get_seg_entry(sbi, segno)->ckpt_valid_blocks;
399 
400 	if (p->one_time_gc && (get_valid_blocks(sbi, segno, true) >=
401 		CAP_BLKS_PER_SEC(sbi) * sbi->gc_thread->valid_thresh_ratio /
402 		100))
403 		return UINT_MAX;
404 
405 	/* alloc_mode == LFS */
406 	if (p->gc_mode == GC_GREEDY)
407 		return get_valid_blocks(sbi, segno, true);
408 	else if (p->gc_mode == GC_CB)
409 		return get_cb_cost(sbi, segno);
410 
411 	f2fs_bug_on(sbi, 1);
412 	return 0;
413 }
414 
415 static unsigned int count_bits(const unsigned long *addr,
416 				unsigned int offset, unsigned int len)
417 {
418 	unsigned int end = offset + len, sum = 0;
419 
420 	while (offset < end) {
421 		if (test_bit(offset++, addr))
422 			++sum;
423 	}
424 	return sum;
425 }
426 
427 static bool f2fs_check_victim_tree(struct f2fs_sb_info *sbi,
428 				struct rb_root_cached *root)
429 {
430 #ifdef CONFIG_F2FS_CHECK_FS
431 	struct rb_node *cur = rb_first_cached(root), *next;
432 	struct victim_entry *cur_ve, *next_ve;
433 
434 	while (cur) {
435 		next = rb_next(cur);
436 		if (!next)
437 			return true;
438 
439 		cur_ve = rb_entry(cur, struct victim_entry, rb_node);
440 		next_ve = rb_entry(next, struct victim_entry, rb_node);
441 
442 		if (cur_ve->mtime > next_ve->mtime) {
443 			f2fs_info(sbi, "broken victim_rbtree, "
444 				"cur_mtime(%llu) next_mtime(%llu)",
445 				cur_ve->mtime, next_ve->mtime);
446 			return false;
447 		}
448 		cur = next;
449 	}
450 #endif
451 	return true;
452 }
453 
454 static struct victim_entry *__lookup_victim_entry(struct f2fs_sb_info *sbi,
455 					unsigned long long mtime)
456 {
457 	struct atgc_management *am = &sbi->am;
458 	struct rb_node *node = am->root.rb_root.rb_node;
459 	struct victim_entry *ve = NULL;
460 
461 	while (node) {
462 		ve = rb_entry(node, struct victim_entry, rb_node);
463 
464 		if (mtime < ve->mtime)
465 			node = node->rb_left;
466 		else
467 			node = node->rb_right;
468 	}
469 	return ve;
470 }
471 
472 static struct victim_entry *__create_victim_entry(struct f2fs_sb_info *sbi,
473 		unsigned long long mtime, unsigned int segno)
474 {
475 	struct atgc_management *am = &sbi->am;
476 	struct victim_entry *ve;
477 
478 	ve =  f2fs_kmem_cache_alloc(victim_entry_slab, GFP_NOFS, true, NULL);
479 
480 	ve->mtime = mtime;
481 	ve->segno = segno;
482 
483 	list_add_tail(&ve->list, &am->victim_list);
484 	am->victim_count++;
485 
486 	return ve;
487 }
488 
489 static void __insert_victim_entry(struct f2fs_sb_info *sbi,
490 				unsigned long long mtime, unsigned int segno)
491 {
492 	struct atgc_management *am = &sbi->am;
493 	struct rb_root_cached *root = &am->root;
494 	struct rb_node **p = &root->rb_root.rb_node;
495 	struct rb_node *parent = NULL;
496 	struct victim_entry *ve;
497 	bool left_most = true;
498 
499 	/* look up rb tree to find parent node */
500 	while (*p) {
501 		parent = *p;
502 		ve = rb_entry(parent, struct victim_entry, rb_node);
503 
504 		if (mtime < ve->mtime) {
505 			p = &(*p)->rb_left;
506 		} else {
507 			p = &(*p)->rb_right;
508 			left_most = false;
509 		}
510 	}
511 
512 	ve = __create_victim_entry(sbi, mtime, segno);
513 
514 	rb_link_node(&ve->rb_node, parent, p);
515 	rb_insert_color_cached(&ve->rb_node, root, left_most);
516 }
517 
518 static void add_victim_entry(struct f2fs_sb_info *sbi,
519 				struct victim_sel_policy *p, unsigned int segno)
520 {
521 	struct sit_info *sit_i = SIT_I(sbi);
522 	unsigned int secno = GET_SEC_FROM_SEG(sbi, segno);
523 	unsigned int start = GET_SEG_FROM_SEC(sbi, secno);
524 	unsigned long long mtime = 0;
525 	unsigned int i;
526 
527 	if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) {
528 		if (p->gc_mode == GC_AT &&
529 			get_valid_blocks(sbi, segno, true) == 0)
530 			return;
531 	}
532 
533 	for (i = 0; i < SEGS_PER_SEC(sbi); i++)
534 		mtime += get_seg_entry(sbi, start + i)->mtime;
535 	mtime = div_u64(mtime, SEGS_PER_SEC(sbi));
536 
537 	/* Handle if the system time has changed by the user */
538 	if (mtime < sit_i->min_mtime)
539 		sit_i->min_mtime = mtime;
540 	if (mtime > sit_i->max_mtime)
541 		sit_i->max_mtime = mtime;
542 	if (mtime < sit_i->dirty_min_mtime)
543 		sit_i->dirty_min_mtime = mtime;
544 	if (mtime > sit_i->dirty_max_mtime)
545 		sit_i->dirty_max_mtime = mtime;
546 
547 	/* don't choose young section as candidate */
548 	if (sit_i->dirty_max_mtime - mtime < p->age_threshold)
549 		return;
550 
551 	__insert_victim_entry(sbi, mtime, segno);
552 }
553 
554 static void atgc_lookup_victim(struct f2fs_sb_info *sbi,
555 						struct victim_sel_policy *p)
556 {
557 	struct sit_info *sit_i = SIT_I(sbi);
558 	struct atgc_management *am = &sbi->am;
559 	struct rb_root_cached *root = &am->root;
560 	struct rb_node *node;
561 	struct victim_entry *ve;
562 	unsigned long long total_time;
563 	unsigned long long age, u, accu;
564 	unsigned long long max_mtime = sit_i->dirty_max_mtime;
565 	unsigned long long min_mtime = sit_i->dirty_min_mtime;
566 	unsigned int sec_blocks = CAP_BLKS_PER_SEC(sbi);
567 	unsigned int vblocks;
568 	unsigned int dirty_threshold = max(am->max_candidate_count,
569 					am->candidate_ratio *
570 					am->victim_count / 100);
571 	unsigned int age_weight = am->age_weight;
572 	unsigned int cost;
573 	unsigned int iter = 0;
574 
575 	if (max_mtime < min_mtime)
576 		return;
577 
578 	max_mtime += 1;
579 	total_time = max_mtime - min_mtime;
580 
581 	accu = div64_u64(ULLONG_MAX, total_time);
582 	accu = min_t(unsigned long long, div_u64(accu, 100),
583 					DEFAULT_ACCURACY_CLASS);
584 
585 	node = rb_first_cached(root);
586 next:
587 	ve = rb_entry_safe(node, struct victim_entry, rb_node);
588 	if (!ve)
589 		return;
590 
591 	if (ve->mtime >= max_mtime || ve->mtime < min_mtime)
592 		goto skip;
593 
594 	/* age = 10000 * x% * 60 */
595 	age = div64_u64(accu * (max_mtime - ve->mtime), total_time) *
596 								age_weight;
597 
598 	vblocks = get_valid_blocks(sbi, ve->segno, true);
599 	f2fs_bug_on(sbi, !vblocks || vblocks == sec_blocks);
600 
601 	/* u = 10000 * x% * 40 */
602 	u = div64_u64(accu * (sec_blocks - vblocks), sec_blocks) *
603 							(100 - age_weight);
604 
605 	f2fs_bug_on(sbi, age + u >= UINT_MAX);
606 
607 	cost = UINT_MAX - (age + u);
608 	iter++;
609 
610 	if (cost < p->min_cost ||
611 			(cost == p->min_cost && age > p->oldest_age)) {
612 		p->min_cost = cost;
613 		p->oldest_age = age;
614 		p->min_segno = ve->segno;
615 	}
616 skip:
617 	if (iter < dirty_threshold) {
618 		node = rb_next(node);
619 		goto next;
620 	}
621 }
622 
623 /*
624  * select candidates around source section in range of
625  * [target - dirty_threshold, target + dirty_threshold]
626  */
627 static void atssr_lookup_victim(struct f2fs_sb_info *sbi,
628 						struct victim_sel_policy *p)
629 {
630 	struct sit_info *sit_i = SIT_I(sbi);
631 	struct atgc_management *am = &sbi->am;
632 	struct victim_entry *ve;
633 	unsigned long long age;
634 	unsigned long long max_mtime = sit_i->dirty_max_mtime;
635 	unsigned long long min_mtime = sit_i->dirty_min_mtime;
636 	unsigned int vblocks;
637 	unsigned int dirty_threshold = max(am->max_candidate_count,
638 					am->candidate_ratio *
639 					am->victim_count / 100);
640 	unsigned int cost, iter;
641 	int stage = 0;
642 
643 	if (max_mtime < min_mtime)
644 		return;
645 	max_mtime += 1;
646 next_stage:
647 	iter = 0;
648 	ve = __lookup_victim_entry(sbi, p->age);
649 next_node:
650 	if (!ve) {
651 		if (stage++ == 0)
652 			goto next_stage;
653 		return;
654 	}
655 
656 	if (ve->mtime >= max_mtime || ve->mtime < min_mtime)
657 		goto skip_node;
658 
659 	age = max_mtime - ve->mtime;
660 
661 	vblocks = get_seg_entry(sbi, ve->segno)->ckpt_valid_blocks;
662 	f2fs_bug_on(sbi, !vblocks);
663 
664 	/* rare case */
665 	if (vblocks == BLKS_PER_SEG(sbi))
666 		goto skip_node;
667 
668 	iter++;
669 
670 	age = max_mtime - abs(p->age - age);
671 	cost = UINT_MAX - vblocks;
672 
673 	if (cost < p->min_cost ||
674 			(cost == p->min_cost && age > p->oldest_age)) {
675 		p->min_cost = cost;
676 		p->oldest_age = age;
677 		p->min_segno = ve->segno;
678 	}
679 skip_node:
680 	if (iter < dirty_threshold) {
681 		ve = rb_entry(stage == 0 ? rb_prev(&ve->rb_node) :
682 					rb_next(&ve->rb_node),
683 					struct victim_entry, rb_node);
684 		goto next_node;
685 	}
686 
687 	if (stage++ == 0)
688 		goto next_stage;
689 }
690 
691 static void lookup_victim_by_age(struct f2fs_sb_info *sbi,
692 						struct victim_sel_policy *p)
693 {
694 	f2fs_bug_on(sbi, !f2fs_check_victim_tree(sbi, &sbi->am.root));
695 
696 	if (p->gc_mode == GC_AT)
697 		atgc_lookup_victim(sbi, p);
698 	else if (p->alloc_mode == AT_SSR)
699 		atssr_lookup_victim(sbi, p);
700 	else
701 		f2fs_bug_on(sbi, 1);
702 }
703 
704 static void release_victim_entry(struct f2fs_sb_info *sbi)
705 {
706 	struct atgc_management *am = &sbi->am;
707 	struct victim_entry *ve, *tmp;
708 
709 	list_for_each_entry_safe(ve, tmp, &am->victim_list, list) {
710 		list_del(&ve->list);
711 		kmem_cache_free(victim_entry_slab, ve);
712 		am->victim_count--;
713 	}
714 
715 	am->root = RB_ROOT_CACHED;
716 
717 	f2fs_bug_on(sbi, am->victim_count);
718 	f2fs_bug_on(sbi, !list_empty(&am->victim_list));
719 }
720 
721 static bool f2fs_pin_section(struct f2fs_sb_info *sbi, unsigned int segno)
722 {
723 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
724 	unsigned int secno = GET_SEC_FROM_SEG(sbi, segno);
725 
726 	if (!dirty_i->enable_pin_section)
727 		return false;
728 	if (!test_and_set_bit(secno, dirty_i->pinned_secmap))
729 		dirty_i->pinned_secmap_cnt++;
730 	return true;
731 }
732 
733 static bool f2fs_pinned_section_exists(struct dirty_seglist_info *dirty_i)
734 {
735 	return dirty_i->pinned_secmap_cnt;
736 }
737 
738 static bool f2fs_section_is_pinned(struct dirty_seglist_info *dirty_i,
739 						unsigned int secno)
740 {
741 	return dirty_i->enable_pin_section &&
742 		f2fs_pinned_section_exists(dirty_i) &&
743 		test_bit(secno, dirty_i->pinned_secmap);
744 }
745 
746 static void f2fs_unpin_all_sections(struct f2fs_sb_info *sbi, bool enable)
747 {
748 	unsigned int bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
749 
750 	if (f2fs_pinned_section_exists(DIRTY_I(sbi))) {
751 		memset(DIRTY_I(sbi)->pinned_secmap, 0, bitmap_size);
752 		DIRTY_I(sbi)->pinned_secmap_cnt = 0;
753 	}
754 	DIRTY_I(sbi)->enable_pin_section = enable;
755 }
756 
757 static int f2fs_gc_pinned_control(struct inode *inode, int gc_type,
758 							unsigned int segno)
759 {
760 	if (!f2fs_is_pinned_file(inode))
761 		return 0;
762 	if (gc_type != FG_GC)
763 		return -EBUSY;
764 	if (!f2fs_pin_section(F2FS_I_SB(inode), segno))
765 		f2fs_pin_file_control(inode, true);
766 	return -EAGAIN;
767 }
768 
769 /*
770  * This function is called from two paths.
771  * One is garbage collection and the other is SSR segment selection.
772  * When it is called during GC, it just gets a victim segment
773  * and it does not remove it from dirty seglist.
774  * When it is called from SSR segment selection, it finds a segment
775  * which has minimum valid blocks and removes it from dirty seglist.
776  */
777 int f2fs_get_victim(struct f2fs_sb_info *sbi, unsigned int *result,
778 			int gc_type, int type, char alloc_mode,
779 			unsigned long long age, bool one_time)
780 {
781 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
782 	struct sit_info *sm = SIT_I(sbi);
783 	struct victim_sel_policy p;
784 	unsigned int secno, last_victim;
785 	unsigned int last_segment;
786 	unsigned int nsearched;
787 	bool is_atgc;
788 	int ret = 0;
789 
790 	mutex_lock(&dirty_i->seglist_lock);
791 	last_segment = MAIN_SECS(sbi) * SEGS_PER_SEC(sbi);
792 
793 	p.alloc_mode = alloc_mode;
794 	p.age = age;
795 	p.age_threshold = sbi->am.age_threshold;
796 	p.one_time_gc = one_time;
797 
798 retry:
799 	select_policy(sbi, gc_type, type, &p);
800 	p.min_segno = NULL_SEGNO;
801 	p.oldest_age = 0;
802 	p.min_cost = get_max_cost(sbi, &p);
803 
804 	is_atgc = (p.gc_mode == GC_AT || p.alloc_mode == AT_SSR);
805 	nsearched = 0;
806 
807 	if (is_atgc)
808 		SIT_I(sbi)->dirty_min_mtime = ULLONG_MAX;
809 
810 	if (*result != NULL_SEGNO) {
811 		if (!get_valid_blocks(sbi, *result, false)) {
812 			ret = -ENODATA;
813 			goto out;
814 		}
815 
816 		if (sec_usage_check(sbi, GET_SEC_FROM_SEG(sbi, *result)))
817 			ret = -EBUSY;
818 		else
819 			p.min_segno = *result;
820 		goto out;
821 	}
822 
823 	ret = -ENODATA;
824 	if (p.max_search == 0)
825 		goto out;
826 
827 	if (__is_large_section(sbi) && p.alloc_mode == LFS) {
828 		if (sbi->next_victim_seg[BG_GC] != NULL_SEGNO) {
829 			p.min_segno = sbi->next_victim_seg[BG_GC];
830 			*result = p.min_segno;
831 			sbi->next_victim_seg[BG_GC] = NULL_SEGNO;
832 			goto got_result;
833 		}
834 		if (gc_type == FG_GC &&
835 				sbi->next_victim_seg[FG_GC] != NULL_SEGNO) {
836 			p.min_segno = sbi->next_victim_seg[FG_GC];
837 			*result = p.min_segno;
838 			sbi->next_victim_seg[FG_GC] = NULL_SEGNO;
839 			goto got_result;
840 		}
841 	}
842 
843 	last_victim = sm->last_victim[p.gc_mode];
844 	if (p.alloc_mode == LFS && gc_type == FG_GC) {
845 		p.min_segno = check_bg_victims(sbi);
846 		if (p.min_segno != NULL_SEGNO)
847 			goto got_it;
848 	}
849 
850 	while (1) {
851 		unsigned long cost, *dirty_bitmap;
852 		unsigned int unit_no, segno;
853 
854 		dirty_bitmap = p.dirty_bitmap;
855 		unit_no = find_next_bit(dirty_bitmap,
856 				last_segment / p.ofs_unit,
857 				p.offset / p.ofs_unit);
858 		segno = unit_no * p.ofs_unit;
859 		if (segno >= last_segment) {
860 			if (sm->last_victim[p.gc_mode]) {
861 				last_segment =
862 					sm->last_victim[p.gc_mode];
863 				sm->last_victim[p.gc_mode] = 0;
864 				p.offset = 0;
865 				continue;
866 			}
867 			break;
868 		}
869 
870 		p.offset = segno + p.ofs_unit;
871 		nsearched++;
872 
873 #ifdef CONFIG_F2FS_CHECK_FS
874 		/*
875 		 * skip selecting the invalid segno (that is failed due to block
876 		 * validity check failure during GC) to avoid endless GC loop in
877 		 * such cases.
878 		 */
879 		if (test_bit(segno, sm->invalid_segmap))
880 			goto next;
881 #endif
882 
883 		secno = GET_SEC_FROM_SEG(sbi, segno);
884 
885 		if (sec_usage_check(sbi, secno))
886 			goto next;
887 
888 		/* Don't touch checkpointed data */
889 		if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) {
890 			if (p.alloc_mode == LFS) {
891 				/*
892 				 * LFS is set to find source section during GC.
893 				 * The victim should have no checkpointed data.
894 				 */
895 				if (get_ckpt_valid_blocks(sbi, segno, true))
896 					goto next;
897 			} else {
898 				/*
899 				 * SSR | AT_SSR are set to find target segment
900 				 * for writes which can be full by checkpointed
901 				 * and newly written blocks.
902 				 */
903 				if (!f2fs_segment_has_free_slot(sbi, segno))
904 					goto next;
905 			}
906 		}
907 
908 		if (gc_type == BG_GC && test_bit(secno, dirty_i->victim_secmap))
909 			goto next;
910 
911 		if (gc_type == FG_GC && f2fs_section_is_pinned(dirty_i, secno))
912 			goto next;
913 
914 		if (is_atgc) {
915 			add_victim_entry(sbi, &p, segno);
916 			goto next;
917 		}
918 
919 		cost = get_gc_cost(sbi, segno, &p);
920 
921 		if (p.min_cost > cost) {
922 			p.min_segno = segno;
923 			p.min_cost = cost;
924 		}
925 next:
926 		if (nsearched >= p.max_search) {
927 			if (!sm->last_victim[p.gc_mode] && segno <= last_victim)
928 				sm->last_victim[p.gc_mode] =
929 					last_victim + p.ofs_unit;
930 			else
931 				sm->last_victim[p.gc_mode] = segno + p.ofs_unit;
932 			sm->last_victim[p.gc_mode] %=
933 				(MAIN_SECS(sbi) * SEGS_PER_SEC(sbi));
934 			break;
935 		}
936 	}
937 
938 	/* get victim for GC_AT/AT_SSR */
939 	if (is_atgc) {
940 		lookup_victim_by_age(sbi, &p);
941 		release_victim_entry(sbi);
942 	}
943 
944 	if (is_atgc && p.min_segno == NULL_SEGNO &&
945 			sm->elapsed_time < p.age_threshold) {
946 		p.age_threshold = 0;
947 		goto retry;
948 	}
949 
950 	if (p.min_segno != NULL_SEGNO) {
951 got_it:
952 		*result = (p.min_segno / p.ofs_unit) * p.ofs_unit;
953 got_result:
954 		if (p.alloc_mode == LFS) {
955 			secno = GET_SEC_FROM_SEG(sbi, p.min_segno);
956 			if (gc_type == FG_GC)
957 				sbi->cur_victim_sec = secno;
958 			else
959 				set_bit(secno, dirty_i->victim_secmap);
960 		}
961 		ret = 0;
962 
963 	}
964 out:
965 	if (p.min_segno != NULL_SEGNO)
966 		trace_f2fs_get_victim(sbi->sb, type, gc_type, &p,
967 				sbi->cur_victim_sec,
968 				prefree_segments(sbi), free_segments(sbi));
969 	mutex_unlock(&dirty_i->seglist_lock);
970 
971 	return ret;
972 }
973 
974 static struct inode *find_gc_inode(struct gc_inode_list *gc_list, nid_t ino)
975 {
976 	struct inode_entry *ie;
977 
978 	ie = radix_tree_lookup(&gc_list->iroot, ino);
979 	if (ie)
980 		return ie->inode;
981 	return NULL;
982 }
983 
984 static void add_gc_inode(struct gc_inode_list *gc_list, struct inode *inode)
985 {
986 	struct inode_entry *new_ie;
987 
988 	if (inode == find_gc_inode(gc_list, inode->i_ino)) {
989 		iput(inode);
990 		return;
991 	}
992 	new_ie = f2fs_kmem_cache_alloc(f2fs_inode_entry_slab,
993 					GFP_NOFS, true, NULL);
994 	new_ie->inode = inode;
995 
996 	f2fs_radix_tree_insert(&gc_list->iroot, inode->i_ino, new_ie);
997 	list_add_tail(&new_ie->list, &gc_list->ilist);
998 }
999 
1000 static void put_gc_inode(struct gc_inode_list *gc_list)
1001 {
1002 	struct inode_entry *ie, *next_ie;
1003 
1004 	list_for_each_entry_safe(ie, next_ie, &gc_list->ilist, list) {
1005 		radix_tree_delete(&gc_list->iroot, ie->inode->i_ino);
1006 		iput(ie->inode);
1007 		list_del(&ie->list);
1008 		kmem_cache_free(f2fs_inode_entry_slab, ie);
1009 	}
1010 }
1011 
1012 static int check_valid_map(struct f2fs_sb_info *sbi,
1013 				unsigned int segno, int offset)
1014 {
1015 	struct sit_info *sit_i = SIT_I(sbi);
1016 	struct seg_entry *sentry;
1017 	int ret;
1018 
1019 	down_read(&sit_i->sentry_lock);
1020 	sentry = get_seg_entry(sbi, segno);
1021 	ret = f2fs_test_bit(offset, sentry->cur_valid_map);
1022 	up_read(&sit_i->sentry_lock);
1023 	return ret;
1024 }
1025 
1026 /*
1027  * This function compares node address got in summary with that in NAT.
1028  * On validity, copy that node with cold status, otherwise (invalid node)
1029  * ignore that.
1030  */
1031 static int gc_node_segment(struct f2fs_sb_info *sbi,
1032 		struct f2fs_summary *sum, unsigned int segno, int gc_type)
1033 {
1034 	struct f2fs_summary *entry;
1035 	block_t start_addr;
1036 	int off;
1037 	int phase = 0;
1038 	bool fggc = (gc_type == FG_GC);
1039 	int submitted = 0;
1040 	unsigned int usable_blks_in_seg = f2fs_usable_blks_in_seg(sbi, segno);
1041 
1042 	start_addr = START_BLOCK(sbi, segno);
1043 
1044 next_step:
1045 	entry = sum;
1046 
1047 	if (fggc && phase == 2)
1048 		atomic_inc(&sbi->wb_sync_req[NODE]);
1049 
1050 	for (off = 0; off < usable_blks_in_seg; off++, entry++) {
1051 		nid_t nid = le32_to_cpu(entry->nid);
1052 		struct page *node_page;
1053 		struct node_info ni;
1054 		int err;
1055 
1056 		/* stop BG_GC if there is not enough free sections. */
1057 		if (gc_type == BG_GC && has_not_enough_free_secs(sbi, 0, 0))
1058 			return submitted;
1059 
1060 		if (check_valid_map(sbi, segno, off) == 0)
1061 			continue;
1062 
1063 		if (phase == 0) {
1064 			f2fs_ra_meta_pages(sbi, NAT_BLOCK_OFFSET(nid), 1,
1065 							META_NAT, true);
1066 			continue;
1067 		}
1068 
1069 		if (phase == 1) {
1070 			f2fs_ra_node_page(sbi, nid);
1071 			continue;
1072 		}
1073 
1074 		/* phase == 2 */
1075 		node_page = f2fs_get_node_page(sbi, nid);
1076 		if (IS_ERR(node_page))
1077 			continue;
1078 
1079 		/* block may become invalid during f2fs_get_node_page */
1080 		if (check_valid_map(sbi, segno, off) == 0) {
1081 			f2fs_put_page(node_page, 1);
1082 			continue;
1083 		}
1084 
1085 		if (f2fs_get_node_info(sbi, nid, &ni, false)) {
1086 			f2fs_put_page(node_page, 1);
1087 			continue;
1088 		}
1089 
1090 		if (ni.blk_addr != start_addr + off) {
1091 			f2fs_put_page(node_page, 1);
1092 			continue;
1093 		}
1094 
1095 		err = f2fs_move_node_page(node_page, gc_type);
1096 		if (!err && gc_type == FG_GC)
1097 			submitted++;
1098 		stat_inc_node_blk_count(sbi, 1, gc_type);
1099 	}
1100 
1101 	if (++phase < 3)
1102 		goto next_step;
1103 
1104 	if (fggc)
1105 		atomic_dec(&sbi->wb_sync_req[NODE]);
1106 	return submitted;
1107 }
1108 
1109 /*
1110  * Calculate start block index indicating the given node offset.
1111  * Be careful, caller should give this node offset only indicating direct node
1112  * blocks. If any node offsets, which point the other types of node blocks such
1113  * as indirect or double indirect node blocks, are given, it must be a caller's
1114  * bug.
1115  */
1116 block_t f2fs_start_bidx_of_node(unsigned int node_ofs, struct inode *inode)
1117 {
1118 	unsigned int indirect_blks = 2 * NIDS_PER_BLOCK + 4;
1119 	unsigned int bidx;
1120 
1121 	if (node_ofs == 0)
1122 		return 0;
1123 
1124 	if (node_ofs <= 2) {
1125 		bidx = node_ofs - 1;
1126 	} else if (node_ofs <= indirect_blks) {
1127 		int dec = (node_ofs - 4) / (NIDS_PER_BLOCK + 1);
1128 
1129 		bidx = node_ofs - 2 - dec;
1130 	} else {
1131 		int dec = (node_ofs - indirect_blks - 3) / (NIDS_PER_BLOCK + 1);
1132 
1133 		bidx = node_ofs - 5 - dec;
1134 	}
1135 	return bidx * ADDRS_PER_BLOCK(inode) + ADDRS_PER_INODE(inode);
1136 }
1137 
1138 static bool is_alive(struct f2fs_sb_info *sbi, struct f2fs_summary *sum,
1139 		struct node_info *dni, block_t blkaddr, unsigned int *nofs)
1140 {
1141 	struct page *node_page;
1142 	nid_t nid;
1143 	unsigned int ofs_in_node, max_addrs, base;
1144 	block_t source_blkaddr;
1145 
1146 	nid = le32_to_cpu(sum->nid);
1147 	ofs_in_node = le16_to_cpu(sum->ofs_in_node);
1148 
1149 	node_page = f2fs_get_node_page(sbi, nid);
1150 	if (IS_ERR(node_page))
1151 		return false;
1152 
1153 	if (f2fs_get_node_info(sbi, nid, dni, false)) {
1154 		f2fs_put_page(node_page, 1);
1155 		return false;
1156 	}
1157 
1158 	if (sum->version != dni->version) {
1159 		f2fs_warn(sbi, "%s: valid data with mismatched node version.",
1160 			  __func__);
1161 		set_sbi_flag(sbi, SBI_NEED_FSCK);
1162 	}
1163 
1164 	if (f2fs_check_nid_range(sbi, dni->ino)) {
1165 		f2fs_put_page(node_page, 1);
1166 		return false;
1167 	}
1168 
1169 	if (IS_INODE(node_page)) {
1170 		base = offset_in_addr(F2FS_INODE(node_page));
1171 		max_addrs = DEF_ADDRS_PER_INODE;
1172 	} else {
1173 		base = 0;
1174 		max_addrs = DEF_ADDRS_PER_BLOCK;
1175 	}
1176 
1177 	if (base + ofs_in_node >= max_addrs) {
1178 		f2fs_err(sbi, "Inconsistent blkaddr offset: base:%u, ofs_in_node:%u, max:%u, ino:%u, nid:%u",
1179 			base, ofs_in_node, max_addrs, dni->ino, dni->nid);
1180 		f2fs_put_page(node_page, 1);
1181 		return false;
1182 	}
1183 
1184 	*nofs = ofs_of_node(node_page);
1185 	source_blkaddr = data_blkaddr(NULL, node_page, ofs_in_node);
1186 	f2fs_put_page(node_page, 1);
1187 
1188 	if (source_blkaddr != blkaddr) {
1189 #ifdef CONFIG_F2FS_CHECK_FS
1190 		unsigned int segno = GET_SEGNO(sbi, blkaddr);
1191 		unsigned long offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
1192 
1193 		if (unlikely(check_valid_map(sbi, segno, offset))) {
1194 			if (!test_and_set_bit(segno, SIT_I(sbi)->invalid_segmap)) {
1195 				f2fs_err(sbi, "mismatched blkaddr %u (source_blkaddr %u) in seg %u",
1196 					 blkaddr, source_blkaddr, segno);
1197 				set_sbi_flag(sbi, SBI_NEED_FSCK);
1198 			}
1199 		}
1200 #endif
1201 		return false;
1202 	}
1203 	return true;
1204 }
1205 
1206 static int ra_data_block(struct inode *inode, pgoff_t index)
1207 {
1208 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1209 	struct address_space *mapping = f2fs_is_cow_file(inode) ?
1210 				F2FS_I(inode)->atomic_inode->i_mapping : inode->i_mapping;
1211 	struct dnode_of_data dn;
1212 	struct page *page;
1213 	struct f2fs_io_info fio = {
1214 		.sbi = sbi,
1215 		.ino = inode->i_ino,
1216 		.type = DATA,
1217 		.temp = COLD,
1218 		.op = REQ_OP_READ,
1219 		.op_flags = 0,
1220 		.encrypted_page = NULL,
1221 		.in_list = 0,
1222 	};
1223 	int err;
1224 
1225 	page = f2fs_grab_cache_page(mapping, index, true);
1226 	if (!page)
1227 		return -ENOMEM;
1228 
1229 	if (f2fs_lookup_read_extent_cache_block(inode, index,
1230 						&dn.data_blkaddr)) {
1231 		if (unlikely(!f2fs_is_valid_blkaddr(sbi, dn.data_blkaddr,
1232 						DATA_GENERIC_ENHANCE_READ))) {
1233 			err = -EFSCORRUPTED;
1234 			goto put_page;
1235 		}
1236 		goto got_it;
1237 	}
1238 
1239 	set_new_dnode(&dn, inode, NULL, NULL, 0);
1240 	err = f2fs_get_dnode_of_data(&dn, index, LOOKUP_NODE);
1241 	if (err)
1242 		goto put_page;
1243 	f2fs_put_dnode(&dn);
1244 
1245 	if (!__is_valid_data_blkaddr(dn.data_blkaddr)) {
1246 		err = -ENOENT;
1247 		goto put_page;
1248 	}
1249 	if (unlikely(!f2fs_is_valid_blkaddr(sbi, dn.data_blkaddr,
1250 						DATA_GENERIC_ENHANCE))) {
1251 		err = -EFSCORRUPTED;
1252 		goto put_page;
1253 	}
1254 got_it:
1255 	/* read page */
1256 	fio.page = page;
1257 	fio.new_blkaddr = fio.old_blkaddr = dn.data_blkaddr;
1258 
1259 	/*
1260 	 * don't cache encrypted data into meta inode until previous dirty
1261 	 * data were writebacked to avoid racing between GC and flush.
1262 	 */
1263 	f2fs_wait_on_page_writeback(page, DATA, true, true);
1264 
1265 	f2fs_wait_on_block_writeback(inode, dn.data_blkaddr);
1266 
1267 	fio.encrypted_page = f2fs_pagecache_get_page(META_MAPPING(sbi),
1268 					dn.data_blkaddr,
1269 					FGP_LOCK | FGP_CREAT, GFP_NOFS);
1270 	if (!fio.encrypted_page) {
1271 		err = -ENOMEM;
1272 		goto put_page;
1273 	}
1274 
1275 	err = f2fs_submit_page_bio(&fio);
1276 	if (err)
1277 		goto put_encrypted_page;
1278 	f2fs_put_page(fio.encrypted_page, 0);
1279 	f2fs_put_page(page, 1);
1280 
1281 	f2fs_update_iostat(sbi, inode, FS_DATA_READ_IO, F2FS_BLKSIZE);
1282 	f2fs_update_iostat(sbi, NULL, FS_GDATA_READ_IO, F2FS_BLKSIZE);
1283 
1284 	return 0;
1285 put_encrypted_page:
1286 	f2fs_put_page(fio.encrypted_page, 1);
1287 put_page:
1288 	f2fs_put_page(page, 1);
1289 	return err;
1290 }
1291 
1292 /*
1293  * Move data block via META_MAPPING while keeping locked data page.
1294  * This can be used to move blocks, aka LBAs, directly on disk.
1295  */
1296 static int move_data_block(struct inode *inode, block_t bidx,
1297 				int gc_type, unsigned int segno, int off)
1298 {
1299 	struct address_space *mapping = f2fs_is_cow_file(inode) ?
1300 				F2FS_I(inode)->atomic_inode->i_mapping : inode->i_mapping;
1301 	struct f2fs_io_info fio = {
1302 		.sbi = F2FS_I_SB(inode),
1303 		.ino = inode->i_ino,
1304 		.type = DATA,
1305 		.temp = COLD,
1306 		.op = REQ_OP_READ,
1307 		.op_flags = 0,
1308 		.encrypted_page = NULL,
1309 		.in_list = 0,
1310 	};
1311 	struct dnode_of_data dn;
1312 	struct f2fs_summary sum;
1313 	struct node_info ni;
1314 	struct page *page, *mpage;
1315 	block_t newaddr;
1316 	int err = 0;
1317 	bool lfs_mode = f2fs_lfs_mode(fio.sbi);
1318 	int type = fio.sbi->am.atgc_enabled && (gc_type == BG_GC) &&
1319 				(fio.sbi->gc_mode != GC_URGENT_HIGH) ?
1320 				CURSEG_ALL_DATA_ATGC : CURSEG_COLD_DATA;
1321 
1322 	/* do not read out */
1323 	page = f2fs_grab_cache_page(mapping, bidx, false);
1324 	if (!page)
1325 		return -ENOMEM;
1326 
1327 	if (!check_valid_map(F2FS_I_SB(inode), segno, off)) {
1328 		err = -ENOENT;
1329 		goto out;
1330 	}
1331 
1332 	err = f2fs_gc_pinned_control(inode, gc_type, segno);
1333 	if (err)
1334 		goto out;
1335 
1336 	set_new_dnode(&dn, inode, NULL, NULL, 0);
1337 	err = f2fs_get_dnode_of_data(&dn, bidx, LOOKUP_NODE);
1338 	if (err)
1339 		goto out;
1340 
1341 	if (unlikely(dn.data_blkaddr == NULL_ADDR)) {
1342 		ClearPageUptodate(page);
1343 		err = -ENOENT;
1344 		goto put_out;
1345 	}
1346 
1347 	/*
1348 	 * don't cache encrypted data into meta inode until previous dirty
1349 	 * data were writebacked to avoid racing between GC and flush.
1350 	 */
1351 	f2fs_wait_on_page_writeback(page, DATA, true, true);
1352 
1353 	f2fs_wait_on_block_writeback(inode, dn.data_blkaddr);
1354 
1355 	err = f2fs_get_node_info(fio.sbi, dn.nid, &ni, false);
1356 	if (err)
1357 		goto put_out;
1358 
1359 	/* read page */
1360 	fio.page = page;
1361 	fio.new_blkaddr = fio.old_blkaddr = dn.data_blkaddr;
1362 
1363 	if (lfs_mode)
1364 		f2fs_down_write(&fio.sbi->io_order_lock);
1365 
1366 	mpage = f2fs_grab_cache_page(META_MAPPING(fio.sbi),
1367 					fio.old_blkaddr, false);
1368 	if (!mpage) {
1369 		err = -ENOMEM;
1370 		goto up_out;
1371 	}
1372 
1373 	fio.encrypted_page = mpage;
1374 
1375 	/* read source block in mpage */
1376 	if (!PageUptodate(mpage)) {
1377 		err = f2fs_submit_page_bio(&fio);
1378 		if (err) {
1379 			f2fs_put_page(mpage, 1);
1380 			goto up_out;
1381 		}
1382 
1383 		f2fs_update_iostat(fio.sbi, inode, FS_DATA_READ_IO,
1384 							F2FS_BLKSIZE);
1385 		f2fs_update_iostat(fio.sbi, NULL, FS_GDATA_READ_IO,
1386 							F2FS_BLKSIZE);
1387 
1388 		lock_page(mpage);
1389 		if (unlikely(mpage->mapping != META_MAPPING(fio.sbi) ||
1390 						!PageUptodate(mpage))) {
1391 			err = -EIO;
1392 			f2fs_put_page(mpage, 1);
1393 			goto up_out;
1394 		}
1395 	}
1396 
1397 	set_summary(&sum, dn.nid, dn.ofs_in_node, ni.version);
1398 
1399 	/* allocate block address */
1400 	err = f2fs_allocate_data_block(fio.sbi, NULL, fio.old_blkaddr, &newaddr,
1401 				&sum, type, NULL);
1402 	if (err) {
1403 		f2fs_put_page(mpage, 1);
1404 		/* filesystem should shutdown, no need to recovery block */
1405 		goto up_out;
1406 	}
1407 
1408 	fio.encrypted_page = f2fs_pagecache_get_page(META_MAPPING(fio.sbi),
1409 				newaddr, FGP_LOCK | FGP_CREAT, GFP_NOFS);
1410 	if (!fio.encrypted_page) {
1411 		err = -ENOMEM;
1412 		f2fs_put_page(mpage, 1);
1413 		goto recover_block;
1414 	}
1415 
1416 	/* write target block */
1417 	f2fs_wait_on_page_writeback(fio.encrypted_page, DATA, true, true);
1418 	memcpy(page_address(fio.encrypted_page),
1419 				page_address(mpage), PAGE_SIZE);
1420 	f2fs_put_page(mpage, 1);
1421 
1422 	f2fs_invalidate_internal_cache(fio.sbi, fio.old_blkaddr);
1423 
1424 	set_page_dirty(fio.encrypted_page);
1425 	if (clear_page_dirty_for_io(fio.encrypted_page))
1426 		dec_page_count(fio.sbi, F2FS_DIRTY_META);
1427 
1428 	set_page_writeback(fio.encrypted_page);
1429 
1430 	fio.op = REQ_OP_WRITE;
1431 	fio.op_flags = REQ_SYNC;
1432 	fio.new_blkaddr = newaddr;
1433 	f2fs_submit_page_write(&fio);
1434 
1435 	f2fs_update_iostat(fio.sbi, NULL, FS_GC_DATA_IO, F2FS_BLKSIZE);
1436 
1437 	f2fs_update_data_blkaddr(&dn, newaddr);
1438 	set_inode_flag(inode, FI_APPEND_WRITE);
1439 
1440 	f2fs_put_page(fio.encrypted_page, 1);
1441 recover_block:
1442 	if (err)
1443 		f2fs_do_replace_block(fio.sbi, &sum, newaddr, fio.old_blkaddr,
1444 							true, true, true);
1445 up_out:
1446 	if (lfs_mode)
1447 		f2fs_up_write(&fio.sbi->io_order_lock);
1448 put_out:
1449 	f2fs_put_dnode(&dn);
1450 out:
1451 	f2fs_put_page(page, 1);
1452 	return err;
1453 }
1454 
1455 static int move_data_page(struct inode *inode, block_t bidx, int gc_type,
1456 							unsigned int segno, int off)
1457 {
1458 	struct page *page;
1459 	int err = 0;
1460 
1461 	page = f2fs_get_lock_data_page(inode, bidx, true);
1462 	if (IS_ERR(page))
1463 		return PTR_ERR(page);
1464 
1465 	if (!check_valid_map(F2FS_I_SB(inode), segno, off)) {
1466 		err = -ENOENT;
1467 		goto out;
1468 	}
1469 
1470 	err = f2fs_gc_pinned_control(inode, gc_type, segno);
1471 	if (err)
1472 		goto out;
1473 
1474 	if (gc_type == BG_GC) {
1475 		if (folio_test_writeback(page_folio(page))) {
1476 			err = -EAGAIN;
1477 			goto out;
1478 		}
1479 		set_page_dirty(page);
1480 		set_page_private_gcing(page);
1481 	} else {
1482 		struct f2fs_io_info fio = {
1483 			.sbi = F2FS_I_SB(inode),
1484 			.ino = inode->i_ino,
1485 			.type = DATA,
1486 			.temp = COLD,
1487 			.op = REQ_OP_WRITE,
1488 			.op_flags = REQ_SYNC,
1489 			.old_blkaddr = NULL_ADDR,
1490 			.page = page,
1491 			.encrypted_page = NULL,
1492 			.need_lock = LOCK_REQ,
1493 			.io_type = FS_GC_DATA_IO,
1494 		};
1495 		bool is_dirty = PageDirty(page);
1496 
1497 retry:
1498 		f2fs_wait_on_page_writeback(page, DATA, true, true);
1499 
1500 		set_page_dirty(page);
1501 		if (clear_page_dirty_for_io(page)) {
1502 			inode_dec_dirty_pages(inode);
1503 			f2fs_remove_dirty_inode(inode);
1504 		}
1505 
1506 		set_page_private_gcing(page);
1507 
1508 		err = f2fs_do_write_data_page(&fio);
1509 		if (err) {
1510 			clear_page_private_gcing(page);
1511 			if (err == -ENOMEM) {
1512 				memalloc_retry_wait(GFP_NOFS);
1513 				goto retry;
1514 			}
1515 			if (is_dirty)
1516 				set_page_dirty(page);
1517 		}
1518 	}
1519 out:
1520 	f2fs_put_page(page, 1);
1521 	return err;
1522 }
1523 
1524 /*
1525  * This function tries to get parent node of victim data block, and identifies
1526  * data block validity. If the block is valid, copy that with cold status and
1527  * modify parent node.
1528  * If the parent node is not valid or the data block address is different,
1529  * the victim data block is ignored.
1530  */
1531 static int gc_data_segment(struct f2fs_sb_info *sbi, struct f2fs_summary *sum,
1532 		struct gc_inode_list *gc_list, unsigned int segno, int gc_type,
1533 		bool force_migrate)
1534 {
1535 	struct super_block *sb = sbi->sb;
1536 	struct f2fs_summary *entry;
1537 	block_t start_addr;
1538 	int off;
1539 	int phase = 0;
1540 	int submitted = 0;
1541 	unsigned int usable_blks_in_seg = f2fs_usable_blks_in_seg(sbi, segno);
1542 
1543 	start_addr = START_BLOCK(sbi, segno);
1544 
1545 next_step:
1546 	entry = sum;
1547 
1548 	for (off = 0; off < usable_blks_in_seg; off++, entry++) {
1549 		struct page *data_page;
1550 		struct inode *inode;
1551 		struct node_info dni; /* dnode info for the data */
1552 		unsigned int ofs_in_node, nofs;
1553 		block_t start_bidx;
1554 		nid_t nid = le32_to_cpu(entry->nid);
1555 
1556 		/*
1557 		 * stop BG_GC if there is not enough free sections.
1558 		 * Or, stop GC if the segment becomes fully valid caused by
1559 		 * race condition along with SSR block allocation.
1560 		 */
1561 		if ((gc_type == BG_GC && has_not_enough_free_secs(sbi, 0, 0)) ||
1562 			(!force_migrate && get_valid_blocks(sbi, segno, true) ==
1563 							CAP_BLKS_PER_SEC(sbi)))
1564 			return submitted;
1565 
1566 		if (check_valid_map(sbi, segno, off) == 0)
1567 			continue;
1568 
1569 		if (phase == 0) {
1570 			f2fs_ra_meta_pages(sbi, NAT_BLOCK_OFFSET(nid), 1,
1571 							META_NAT, true);
1572 			continue;
1573 		}
1574 
1575 		if (phase == 1) {
1576 			f2fs_ra_node_page(sbi, nid);
1577 			continue;
1578 		}
1579 
1580 		/* Get an inode by ino with checking validity */
1581 		if (!is_alive(sbi, entry, &dni, start_addr + off, &nofs))
1582 			continue;
1583 
1584 		if (phase == 2) {
1585 			f2fs_ra_node_page(sbi, dni.ino);
1586 			continue;
1587 		}
1588 
1589 		ofs_in_node = le16_to_cpu(entry->ofs_in_node);
1590 
1591 		if (phase == 3) {
1592 			int err;
1593 
1594 			inode = f2fs_iget(sb, dni.ino);
1595 			if (IS_ERR(inode))
1596 				continue;
1597 
1598 			if (is_bad_inode(inode) ||
1599 					special_file(inode->i_mode)) {
1600 				iput(inode);
1601 				continue;
1602 			}
1603 
1604 			if (f2fs_has_inline_data(inode)) {
1605 				iput(inode);
1606 				set_sbi_flag(sbi, SBI_NEED_FSCK);
1607 				f2fs_err_ratelimited(sbi,
1608 					"inode %lx has both inline_data flag and "
1609 					"data block, nid=%u, ofs_in_node=%u",
1610 					inode->i_ino, dni.nid, ofs_in_node);
1611 				continue;
1612 			}
1613 
1614 			err = f2fs_gc_pinned_control(inode, gc_type, segno);
1615 			if (err == -EAGAIN) {
1616 				iput(inode);
1617 				return submitted;
1618 			}
1619 
1620 			if (!f2fs_down_write_trylock(
1621 				&F2FS_I(inode)->i_gc_rwsem[WRITE])) {
1622 				iput(inode);
1623 				sbi->skipped_gc_rwsem++;
1624 				continue;
1625 			}
1626 
1627 			start_bidx = f2fs_start_bidx_of_node(nofs, inode) +
1628 								ofs_in_node;
1629 
1630 			if (f2fs_meta_inode_gc_required(inode)) {
1631 				int err = ra_data_block(inode, start_bidx);
1632 
1633 				f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1634 				if (err) {
1635 					iput(inode);
1636 					continue;
1637 				}
1638 				add_gc_inode(gc_list, inode);
1639 				continue;
1640 			}
1641 
1642 			data_page = f2fs_get_read_data_page(inode, start_bidx,
1643 							REQ_RAHEAD, true, NULL);
1644 			f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1645 			if (IS_ERR(data_page)) {
1646 				iput(inode);
1647 				continue;
1648 			}
1649 
1650 			f2fs_put_page(data_page, 0);
1651 			add_gc_inode(gc_list, inode);
1652 			continue;
1653 		}
1654 
1655 		/* phase 4 */
1656 		inode = find_gc_inode(gc_list, dni.ino);
1657 		if (inode) {
1658 			struct f2fs_inode_info *fi = F2FS_I(inode);
1659 			bool locked = false;
1660 			int err;
1661 
1662 			if (S_ISREG(inode->i_mode)) {
1663 				if (!f2fs_down_write_trylock(&fi->i_gc_rwsem[WRITE])) {
1664 					sbi->skipped_gc_rwsem++;
1665 					continue;
1666 				}
1667 				if (!f2fs_down_write_trylock(
1668 						&fi->i_gc_rwsem[READ])) {
1669 					sbi->skipped_gc_rwsem++;
1670 					f2fs_up_write(&fi->i_gc_rwsem[WRITE]);
1671 					continue;
1672 				}
1673 				locked = true;
1674 
1675 				/* wait for all inflight aio data */
1676 				inode_dio_wait(inode);
1677 			}
1678 
1679 			start_bidx = f2fs_start_bidx_of_node(nofs, inode)
1680 								+ ofs_in_node;
1681 			if (f2fs_meta_inode_gc_required(inode))
1682 				err = move_data_block(inode, start_bidx,
1683 							gc_type, segno, off);
1684 			else
1685 				err = move_data_page(inode, start_bidx, gc_type,
1686 								segno, off);
1687 
1688 			if (!err && (gc_type == FG_GC ||
1689 					f2fs_meta_inode_gc_required(inode)))
1690 				submitted++;
1691 
1692 			if (locked) {
1693 				f2fs_up_write(&fi->i_gc_rwsem[READ]);
1694 				f2fs_up_write(&fi->i_gc_rwsem[WRITE]);
1695 			}
1696 
1697 			stat_inc_data_blk_count(sbi, 1, gc_type);
1698 		}
1699 	}
1700 
1701 	if (++phase < 5)
1702 		goto next_step;
1703 
1704 	return submitted;
1705 }
1706 
1707 static int __get_victim(struct f2fs_sb_info *sbi, unsigned int *victim,
1708 			int gc_type, bool one_time)
1709 {
1710 	struct sit_info *sit_i = SIT_I(sbi);
1711 	int ret;
1712 
1713 	down_write(&sit_i->sentry_lock);
1714 	ret = f2fs_get_victim(sbi, victim, gc_type, NO_CHECK_TYPE,
1715 			LFS, 0, one_time);
1716 	up_write(&sit_i->sentry_lock);
1717 	return ret;
1718 }
1719 
1720 static int do_garbage_collect(struct f2fs_sb_info *sbi,
1721 				unsigned int start_segno,
1722 				struct gc_inode_list *gc_list, int gc_type,
1723 				bool force_migrate, bool one_time)
1724 {
1725 	struct page *sum_page;
1726 	struct f2fs_summary_block *sum;
1727 	struct blk_plug plug;
1728 	unsigned int segno = start_segno;
1729 	unsigned int end_segno = start_segno + SEGS_PER_SEC(sbi);
1730 	unsigned int sec_end_segno;
1731 	int seg_freed = 0, migrated = 0;
1732 	unsigned char type = IS_DATASEG(get_seg_entry(sbi, segno)->type) ?
1733 						SUM_TYPE_DATA : SUM_TYPE_NODE;
1734 	unsigned char data_type = (type == SUM_TYPE_DATA) ? DATA : NODE;
1735 	int submitted = 0;
1736 
1737 	if (__is_large_section(sbi)) {
1738 		sec_end_segno = rounddown(end_segno, SEGS_PER_SEC(sbi));
1739 
1740 		/*
1741 		 * zone-capacity can be less than zone-size in zoned devices,
1742 		 * resulting in less than expected usable segments in the zone,
1743 		 * calculate the end segno in the zone which can be garbage
1744 		 * collected
1745 		 */
1746 		if (f2fs_sb_has_blkzoned(sbi))
1747 			sec_end_segno -= SEGS_PER_SEC(sbi) -
1748 					f2fs_usable_segs_in_sec(sbi);
1749 
1750 		if (gc_type == BG_GC || one_time) {
1751 			unsigned int window_granularity =
1752 				sbi->migration_window_granularity;
1753 
1754 			if (f2fs_sb_has_blkzoned(sbi) &&
1755 					!has_enough_free_blocks(sbi,
1756 					sbi->gc_thread->boost_zoned_gc_percent))
1757 				window_granularity *=
1758 					BOOST_GC_MULTIPLE;
1759 
1760 			end_segno = start_segno + window_granularity;
1761 		}
1762 
1763 		if (end_segno > sec_end_segno)
1764 			end_segno = sec_end_segno;
1765 	}
1766 
1767 	sanity_check_seg_type(sbi, get_seg_entry(sbi, segno)->type);
1768 
1769 	/* readahead multi ssa blocks those have contiguous address */
1770 	if (__is_large_section(sbi))
1771 		f2fs_ra_meta_pages(sbi, GET_SUM_BLOCK(sbi, segno),
1772 					end_segno - segno, META_SSA, true);
1773 
1774 	/* reference all summary page */
1775 	while (segno < end_segno) {
1776 		sum_page = f2fs_get_sum_page(sbi, segno++);
1777 		if (IS_ERR(sum_page)) {
1778 			int err = PTR_ERR(sum_page);
1779 
1780 			end_segno = segno - 1;
1781 			for (segno = start_segno; segno < end_segno; segno++) {
1782 				sum_page = find_get_page(META_MAPPING(sbi),
1783 						GET_SUM_BLOCK(sbi, segno));
1784 				f2fs_put_page(sum_page, 0);
1785 				f2fs_put_page(sum_page, 0);
1786 			}
1787 			return err;
1788 		}
1789 		unlock_page(sum_page);
1790 	}
1791 
1792 	blk_start_plug(&plug);
1793 
1794 	for (segno = start_segno; segno < end_segno; segno++) {
1795 
1796 		/* find segment summary of victim */
1797 		sum_page = find_get_page(META_MAPPING(sbi),
1798 					GET_SUM_BLOCK(sbi, segno));
1799 		f2fs_put_page(sum_page, 0);
1800 
1801 		if (get_valid_blocks(sbi, segno, false) == 0)
1802 			goto freed;
1803 		if (gc_type == BG_GC && __is_large_section(sbi) &&
1804 				migrated >= sbi->migration_granularity)
1805 			goto skip;
1806 		if (!PageUptodate(sum_page) || unlikely(f2fs_cp_error(sbi)))
1807 			goto skip;
1808 
1809 		sum = page_address(sum_page);
1810 		if (type != GET_SUM_TYPE((&sum->footer))) {
1811 			f2fs_err(sbi, "Inconsistent segment (%u) type [%d, %d] in SSA and SIT",
1812 				 segno, type, GET_SUM_TYPE((&sum->footer)));
1813 			f2fs_stop_checkpoint(sbi, false,
1814 				STOP_CP_REASON_CORRUPTED_SUMMARY);
1815 			goto skip;
1816 		}
1817 
1818 		/*
1819 		 * this is to avoid deadlock:
1820 		 * - lock_page(sum_page)         - f2fs_replace_block
1821 		 *  - check_valid_map()            - down_write(sentry_lock)
1822 		 *   - down_read(sentry_lock)     - change_curseg()
1823 		 *                                  - lock_page(sum_page)
1824 		 */
1825 		if (type == SUM_TYPE_NODE)
1826 			submitted += gc_node_segment(sbi, sum->entries, segno,
1827 								gc_type);
1828 		else
1829 			submitted += gc_data_segment(sbi, sum->entries, gc_list,
1830 							segno, gc_type,
1831 							force_migrate);
1832 
1833 		stat_inc_gc_seg_count(sbi, data_type, gc_type);
1834 		sbi->gc_reclaimed_segs[sbi->gc_mode]++;
1835 		migrated++;
1836 
1837 freed:
1838 		if (gc_type == FG_GC &&
1839 				get_valid_blocks(sbi, segno, false) == 0)
1840 			seg_freed++;
1841 
1842 		if (__is_large_section(sbi))
1843 			sbi->next_victim_seg[gc_type] =
1844 				(segno + 1 < sec_end_segno) ?
1845 					segno + 1 : NULL_SEGNO;
1846 skip:
1847 		f2fs_put_page(sum_page, 0);
1848 	}
1849 
1850 	if (submitted)
1851 		f2fs_submit_merged_write(sbi, data_type);
1852 
1853 	blk_finish_plug(&plug);
1854 
1855 	if (migrated)
1856 		stat_inc_gc_sec_count(sbi, data_type, gc_type);
1857 
1858 	return seg_freed;
1859 }
1860 
1861 int f2fs_gc(struct f2fs_sb_info *sbi, struct f2fs_gc_control *gc_control)
1862 {
1863 	int gc_type = gc_control->init_gc_type;
1864 	unsigned int segno = gc_control->victim_segno;
1865 	int sec_freed = 0, seg_freed = 0, total_freed = 0, total_sec_freed = 0;
1866 	int ret = 0;
1867 	struct cp_control cpc;
1868 	struct gc_inode_list gc_list = {
1869 		.ilist = LIST_HEAD_INIT(gc_list.ilist),
1870 		.iroot = RADIX_TREE_INIT(gc_list.iroot, GFP_NOFS),
1871 	};
1872 	unsigned int skipped_round = 0, round = 0;
1873 	unsigned int upper_secs;
1874 
1875 	trace_f2fs_gc_begin(sbi->sb, gc_type, gc_control->no_bg_gc,
1876 				gc_control->nr_free_secs,
1877 				get_pages(sbi, F2FS_DIRTY_NODES),
1878 				get_pages(sbi, F2FS_DIRTY_DENTS),
1879 				get_pages(sbi, F2FS_DIRTY_IMETA),
1880 				free_sections(sbi),
1881 				free_segments(sbi),
1882 				reserved_segments(sbi),
1883 				prefree_segments(sbi));
1884 
1885 	cpc.reason = __get_cp_reason(sbi);
1886 gc_more:
1887 	sbi->skipped_gc_rwsem = 0;
1888 	if (unlikely(!(sbi->sb->s_flags & SB_ACTIVE))) {
1889 		ret = -EINVAL;
1890 		goto stop;
1891 	}
1892 	if (unlikely(f2fs_cp_error(sbi))) {
1893 		ret = -EIO;
1894 		goto stop;
1895 	}
1896 
1897 	/* Let's run FG_GC, if we don't have enough space. */
1898 	if (has_not_enough_free_secs(sbi, 0, 0)) {
1899 		gc_type = FG_GC;
1900 
1901 		/*
1902 		 * For example, if there are many prefree_segments below given
1903 		 * threshold, we can make them free by checkpoint. Then, we
1904 		 * secure free segments which doesn't need fggc any more.
1905 		 */
1906 		if (prefree_segments(sbi)) {
1907 			stat_inc_cp_call_count(sbi, TOTAL_CALL);
1908 			ret = f2fs_write_checkpoint(sbi, &cpc);
1909 			if (ret)
1910 				goto stop;
1911 			/* Reset due to checkpoint */
1912 			sec_freed = 0;
1913 		}
1914 	}
1915 
1916 	/* f2fs_balance_fs doesn't need to do BG_GC in critical path. */
1917 	if (gc_type == BG_GC && gc_control->no_bg_gc) {
1918 		ret = -EINVAL;
1919 		goto stop;
1920 	}
1921 retry:
1922 	ret = __get_victim(sbi, &segno, gc_type, gc_control->one_time);
1923 	if (ret) {
1924 		/* allow to search victim from sections has pinned data */
1925 		if (ret == -ENODATA && gc_type == FG_GC &&
1926 				f2fs_pinned_section_exists(DIRTY_I(sbi))) {
1927 			f2fs_unpin_all_sections(sbi, false);
1928 			goto retry;
1929 		}
1930 		goto stop;
1931 	}
1932 
1933 	seg_freed = do_garbage_collect(sbi, segno, &gc_list, gc_type,
1934 				gc_control->should_migrate_blocks,
1935 				gc_control->one_time);
1936 	if (seg_freed < 0)
1937 		goto stop;
1938 
1939 	total_freed += seg_freed;
1940 
1941 	if (seg_freed == f2fs_usable_segs_in_sec(sbi)) {
1942 		sec_freed++;
1943 		total_sec_freed++;
1944 	}
1945 
1946 	if (gc_control->one_time)
1947 		goto stop;
1948 
1949 	if (gc_type == FG_GC) {
1950 		sbi->cur_victim_sec = NULL_SEGNO;
1951 
1952 		if (has_enough_free_secs(sbi, sec_freed, 0)) {
1953 			if (!gc_control->no_bg_gc &&
1954 			    total_sec_freed < gc_control->nr_free_secs)
1955 				goto go_gc_more;
1956 			goto stop;
1957 		}
1958 		if (sbi->skipped_gc_rwsem)
1959 			skipped_round++;
1960 		round++;
1961 		if (skipped_round > MAX_SKIP_GC_COUNT &&
1962 				skipped_round * 2 >= round) {
1963 			stat_inc_cp_call_count(sbi, TOTAL_CALL);
1964 			ret = f2fs_write_checkpoint(sbi, &cpc);
1965 			goto stop;
1966 		}
1967 	} else if (has_enough_free_secs(sbi, 0, 0)) {
1968 		goto stop;
1969 	}
1970 
1971 	__get_secs_required(sbi, NULL, &upper_secs, NULL);
1972 
1973 	/*
1974 	 * Write checkpoint to reclaim prefree segments.
1975 	 * We need more three extra sections for writer's data/node/dentry.
1976 	 */
1977 	if (free_sections(sbi) <= upper_secs + NR_GC_CHECKPOINT_SECS &&
1978 				prefree_segments(sbi)) {
1979 		stat_inc_cp_call_count(sbi, TOTAL_CALL);
1980 		ret = f2fs_write_checkpoint(sbi, &cpc);
1981 		if (ret)
1982 			goto stop;
1983 		/* Reset due to checkpoint */
1984 		sec_freed = 0;
1985 	}
1986 go_gc_more:
1987 	segno = NULL_SEGNO;
1988 	goto gc_more;
1989 
1990 stop:
1991 	SIT_I(sbi)->last_victim[ALLOC_NEXT] = 0;
1992 	SIT_I(sbi)->last_victim[FLUSH_DEVICE] = gc_control->victim_segno;
1993 
1994 	if (gc_type == FG_GC)
1995 		f2fs_unpin_all_sections(sbi, true);
1996 
1997 	trace_f2fs_gc_end(sbi->sb, ret, total_freed, total_sec_freed,
1998 				get_pages(sbi, F2FS_DIRTY_NODES),
1999 				get_pages(sbi, F2FS_DIRTY_DENTS),
2000 				get_pages(sbi, F2FS_DIRTY_IMETA),
2001 				free_sections(sbi),
2002 				free_segments(sbi),
2003 				reserved_segments(sbi),
2004 				prefree_segments(sbi));
2005 
2006 	f2fs_up_write(&sbi->gc_lock);
2007 
2008 	put_gc_inode(&gc_list);
2009 
2010 	if (gc_control->err_gc_skipped && !ret)
2011 		ret = total_sec_freed ? 0 : -EAGAIN;
2012 	return ret;
2013 }
2014 
2015 int __init f2fs_create_garbage_collection_cache(void)
2016 {
2017 	victim_entry_slab = f2fs_kmem_cache_create("f2fs_victim_entry",
2018 					sizeof(struct victim_entry));
2019 	return victim_entry_slab ? 0 : -ENOMEM;
2020 }
2021 
2022 void f2fs_destroy_garbage_collection_cache(void)
2023 {
2024 	kmem_cache_destroy(victim_entry_slab);
2025 }
2026 
2027 static void init_atgc_management(struct f2fs_sb_info *sbi)
2028 {
2029 	struct atgc_management *am = &sbi->am;
2030 
2031 	if (test_opt(sbi, ATGC) &&
2032 		SIT_I(sbi)->elapsed_time >= DEF_GC_THREAD_AGE_THRESHOLD)
2033 		am->atgc_enabled = true;
2034 
2035 	am->root = RB_ROOT_CACHED;
2036 	INIT_LIST_HEAD(&am->victim_list);
2037 	am->victim_count = 0;
2038 
2039 	am->candidate_ratio = DEF_GC_THREAD_CANDIDATE_RATIO;
2040 	am->max_candidate_count = DEF_GC_THREAD_MAX_CANDIDATE_COUNT;
2041 	am->age_weight = DEF_GC_THREAD_AGE_WEIGHT;
2042 	am->age_threshold = DEF_GC_THREAD_AGE_THRESHOLD;
2043 }
2044 
2045 void f2fs_build_gc_manager(struct f2fs_sb_info *sbi)
2046 {
2047 	sbi->gc_pin_file_threshold = DEF_GC_FAILED_PINNED_FILES;
2048 
2049 	/* give warm/cold data area from slower device */
2050 	if (f2fs_is_multi_device(sbi) && !__is_large_section(sbi))
2051 		SIT_I(sbi)->last_victim[ALLOC_NEXT] =
2052 				GET_SEGNO(sbi, FDEV(0).end_blk) + 1;
2053 
2054 	init_atgc_management(sbi);
2055 }
2056 
2057 int f2fs_gc_range(struct f2fs_sb_info *sbi,
2058 		unsigned int start_seg, unsigned int end_seg,
2059 		bool dry_run, unsigned int dry_run_sections)
2060 {
2061 	unsigned int segno;
2062 	unsigned int gc_secs = dry_run_sections;
2063 
2064 	if (unlikely(f2fs_cp_error(sbi)))
2065 		return -EIO;
2066 
2067 	for (segno = start_seg; segno <= end_seg; segno += SEGS_PER_SEC(sbi)) {
2068 		struct gc_inode_list gc_list = {
2069 			.ilist = LIST_HEAD_INIT(gc_list.ilist),
2070 			.iroot = RADIX_TREE_INIT(gc_list.iroot, GFP_NOFS),
2071 		};
2072 
2073 		do_garbage_collect(sbi, segno, &gc_list, FG_GC, true, false);
2074 		put_gc_inode(&gc_list);
2075 
2076 		if (!dry_run && get_valid_blocks(sbi, segno, true))
2077 			return -EAGAIN;
2078 		if (dry_run && dry_run_sections &&
2079 		    !get_valid_blocks(sbi, segno, true) && --gc_secs == 0)
2080 			break;
2081 
2082 		if (fatal_signal_pending(current))
2083 			return -ERESTARTSYS;
2084 	}
2085 
2086 	return 0;
2087 }
2088 
2089 static int free_segment_range(struct f2fs_sb_info *sbi,
2090 				unsigned int secs, bool dry_run)
2091 {
2092 	unsigned int next_inuse, start, end;
2093 	struct cp_control cpc = { CP_RESIZE, 0, 0, 0 };
2094 	int gc_mode, gc_type;
2095 	int err = 0;
2096 	int type;
2097 
2098 	/* Force block allocation for GC */
2099 	MAIN_SECS(sbi) -= secs;
2100 	start = MAIN_SECS(sbi) * SEGS_PER_SEC(sbi);
2101 	end = MAIN_SEGS(sbi) - 1;
2102 
2103 	mutex_lock(&DIRTY_I(sbi)->seglist_lock);
2104 	for (gc_mode = 0; gc_mode < MAX_GC_POLICY; gc_mode++)
2105 		if (SIT_I(sbi)->last_victim[gc_mode] >= start)
2106 			SIT_I(sbi)->last_victim[gc_mode] = 0;
2107 
2108 	for (gc_type = BG_GC; gc_type <= FG_GC; gc_type++)
2109 		if (sbi->next_victim_seg[gc_type] >= start)
2110 			sbi->next_victim_seg[gc_type] = NULL_SEGNO;
2111 	mutex_unlock(&DIRTY_I(sbi)->seglist_lock);
2112 
2113 	/* Move out cursegs from the target range */
2114 	for (type = CURSEG_HOT_DATA; type < NR_CURSEG_PERSIST_TYPE; type++) {
2115 		err = f2fs_allocate_segment_for_resize(sbi, type, start, end);
2116 		if (err)
2117 			goto out;
2118 	}
2119 
2120 	/* do GC to move out valid blocks in the range */
2121 	err = f2fs_gc_range(sbi, start, end, dry_run, 0);
2122 	if (err || dry_run)
2123 		goto out;
2124 
2125 	stat_inc_cp_call_count(sbi, TOTAL_CALL);
2126 	err = f2fs_write_checkpoint(sbi, &cpc);
2127 	if (err)
2128 		goto out;
2129 
2130 	next_inuse = find_next_inuse(FREE_I(sbi), end + 1, start);
2131 	if (next_inuse <= end) {
2132 		f2fs_err(sbi, "segno %u should be free but still inuse!",
2133 			 next_inuse);
2134 		f2fs_bug_on(sbi, 1);
2135 	}
2136 out:
2137 	MAIN_SECS(sbi) += secs;
2138 	return err;
2139 }
2140 
2141 static void update_sb_metadata(struct f2fs_sb_info *sbi, int secs)
2142 {
2143 	struct f2fs_super_block *raw_sb = F2FS_RAW_SUPER(sbi);
2144 	int section_count;
2145 	int segment_count;
2146 	int segment_count_main;
2147 	long long block_count;
2148 	int segs = secs * SEGS_PER_SEC(sbi);
2149 
2150 	f2fs_down_write(&sbi->sb_lock);
2151 
2152 	section_count = le32_to_cpu(raw_sb->section_count);
2153 	segment_count = le32_to_cpu(raw_sb->segment_count);
2154 	segment_count_main = le32_to_cpu(raw_sb->segment_count_main);
2155 	block_count = le64_to_cpu(raw_sb->block_count);
2156 
2157 	raw_sb->section_count = cpu_to_le32(section_count + secs);
2158 	raw_sb->segment_count = cpu_to_le32(segment_count + segs);
2159 	raw_sb->segment_count_main = cpu_to_le32(segment_count_main + segs);
2160 	raw_sb->block_count = cpu_to_le64(block_count +
2161 			(long long)SEGS_TO_BLKS(sbi, segs));
2162 	if (f2fs_is_multi_device(sbi)) {
2163 		int last_dev = sbi->s_ndevs - 1;
2164 		int dev_segs =
2165 			le32_to_cpu(raw_sb->devs[last_dev].total_segments);
2166 
2167 		raw_sb->devs[last_dev].total_segments =
2168 						cpu_to_le32(dev_segs + segs);
2169 	}
2170 
2171 	f2fs_up_write(&sbi->sb_lock);
2172 }
2173 
2174 static void update_fs_metadata(struct f2fs_sb_info *sbi, int secs)
2175 {
2176 	int segs = secs * SEGS_PER_SEC(sbi);
2177 	long long blks = SEGS_TO_BLKS(sbi, segs);
2178 	long long user_block_count =
2179 				le64_to_cpu(F2FS_CKPT(sbi)->user_block_count);
2180 
2181 	SM_I(sbi)->segment_count = (int)SM_I(sbi)->segment_count + segs;
2182 	MAIN_SEGS(sbi) = (int)MAIN_SEGS(sbi) + segs;
2183 	MAIN_SECS(sbi) += secs;
2184 	FREE_I(sbi)->free_sections = (int)FREE_I(sbi)->free_sections + secs;
2185 	FREE_I(sbi)->free_segments = (int)FREE_I(sbi)->free_segments + segs;
2186 	F2FS_CKPT(sbi)->user_block_count = cpu_to_le64(user_block_count + blks);
2187 
2188 	if (f2fs_is_multi_device(sbi)) {
2189 		int last_dev = sbi->s_ndevs - 1;
2190 
2191 		FDEV(last_dev).total_segments =
2192 				(int)FDEV(last_dev).total_segments + segs;
2193 		FDEV(last_dev).end_blk =
2194 				(long long)FDEV(last_dev).end_blk + blks;
2195 #ifdef CONFIG_BLK_DEV_ZONED
2196 		FDEV(last_dev).nr_blkz = FDEV(last_dev).nr_blkz +
2197 					div_u64(blks, sbi->blocks_per_blkz);
2198 #endif
2199 	}
2200 }
2201 
2202 int f2fs_resize_fs(struct file *filp, __u64 block_count)
2203 {
2204 	struct f2fs_sb_info *sbi = F2FS_I_SB(file_inode(filp));
2205 	__u64 old_block_count, shrunk_blocks;
2206 	struct cp_control cpc = { CP_RESIZE, 0, 0, 0 };
2207 	unsigned int secs;
2208 	int err = 0;
2209 	__u32 rem;
2210 
2211 	old_block_count = le64_to_cpu(F2FS_RAW_SUPER(sbi)->block_count);
2212 	if (block_count > old_block_count)
2213 		return -EINVAL;
2214 
2215 	if (f2fs_is_multi_device(sbi)) {
2216 		int last_dev = sbi->s_ndevs - 1;
2217 		__u64 last_segs = FDEV(last_dev).total_segments;
2218 
2219 		if (block_count + SEGS_TO_BLKS(sbi, last_segs) <=
2220 								old_block_count)
2221 			return -EINVAL;
2222 	}
2223 
2224 	/* new fs size should align to section size */
2225 	div_u64_rem(block_count, BLKS_PER_SEC(sbi), &rem);
2226 	if (rem)
2227 		return -EINVAL;
2228 
2229 	if (block_count == old_block_count)
2230 		return 0;
2231 
2232 	if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) {
2233 		f2fs_err(sbi, "Should run fsck to repair first.");
2234 		return -EFSCORRUPTED;
2235 	}
2236 
2237 	if (test_opt(sbi, DISABLE_CHECKPOINT)) {
2238 		f2fs_err(sbi, "Checkpoint should be enabled.");
2239 		return -EINVAL;
2240 	}
2241 
2242 	err = mnt_want_write_file(filp);
2243 	if (err)
2244 		return err;
2245 
2246 	shrunk_blocks = old_block_count - block_count;
2247 	secs = div_u64(shrunk_blocks, BLKS_PER_SEC(sbi));
2248 
2249 	/* stop other GC */
2250 	if (!f2fs_down_write_trylock(&sbi->gc_lock)) {
2251 		err = -EAGAIN;
2252 		goto out_drop_write;
2253 	}
2254 
2255 	/* stop CP to protect MAIN_SEC in free_segment_range */
2256 	f2fs_lock_op(sbi);
2257 
2258 	spin_lock(&sbi->stat_lock);
2259 	if (shrunk_blocks + valid_user_blocks(sbi) +
2260 		sbi->current_reserved_blocks + sbi->unusable_block_count +
2261 		F2FS_OPTION(sbi).root_reserved_blocks > sbi->user_block_count)
2262 		err = -ENOSPC;
2263 	spin_unlock(&sbi->stat_lock);
2264 
2265 	if (err)
2266 		goto out_unlock;
2267 
2268 	err = free_segment_range(sbi, secs, true);
2269 
2270 out_unlock:
2271 	f2fs_unlock_op(sbi);
2272 	f2fs_up_write(&sbi->gc_lock);
2273 out_drop_write:
2274 	mnt_drop_write_file(filp);
2275 	if (err)
2276 		return err;
2277 
2278 	err = freeze_super(sbi->sb, FREEZE_HOLDER_USERSPACE);
2279 	if (err)
2280 		return err;
2281 
2282 	if (f2fs_readonly(sbi->sb)) {
2283 		err = thaw_super(sbi->sb, FREEZE_HOLDER_USERSPACE);
2284 		if (err)
2285 			return err;
2286 		return -EROFS;
2287 	}
2288 
2289 	f2fs_down_write(&sbi->gc_lock);
2290 	f2fs_down_write(&sbi->cp_global_sem);
2291 
2292 	spin_lock(&sbi->stat_lock);
2293 	if (shrunk_blocks + valid_user_blocks(sbi) +
2294 		sbi->current_reserved_blocks + sbi->unusable_block_count +
2295 		F2FS_OPTION(sbi).root_reserved_blocks > sbi->user_block_count)
2296 		err = -ENOSPC;
2297 	else
2298 		sbi->user_block_count -= shrunk_blocks;
2299 	spin_unlock(&sbi->stat_lock);
2300 	if (err)
2301 		goto out_err;
2302 
2303 	set_sbi_flag(sbi, SBI_IS_RESIZEFS);
2304 	err = free_segment_range(sbi, secs, false);
2305 	if (err)
2306 		goto recover_out;
2307 
2308 	update_sb_metadata(sbi, -secs);
2309 
2310 	err = f2fs_commit_super(sbi, false);
2311 	if (err) {
2312 		update_sb_metadata(sbi, secs);
2313 		goto recover_out;
2314 	}
2315 
2316 	update_fs_metadata(sbi, -secs);
2317 	clear_sbi_flag(sbi, SBI_IS_RESIZEFS);
2318 	set_sbi_flag(sbi, SBI_IS_DIRTY);
2319 
2320 	stat_inc_cp_call_count(sbi, TOTAL_CALL);
2321 	err = f2fs_write_checkpoint(sbi, &cpc);
2322 	if (err) {
2323 		update_fs_metadata(sbi, secs);
2324 		update_sb_metadata(sbi, secs);
2325 		f2fs_commit_super(sbi, false);
2326 	}
2327 recover_out:
2328 	clear_sbi_flag(sbi, SBI_IS_RESIZEFS);
2329 	if (err) {
2330 		set_sbi_flag(sbi, SBI_NEED_FSCK);
2331 		f2fs_err(sbi, "resize_fs failed, should run fsck to repair!");
2332 
2333 		spin_lock(&sbi->stat_lock);
2334 		sbi->user_block_count += shrunk_blocks;
2335 		spin_unlock(&sbi->stat_lock);
2336 	}
2337 out_err:
2338 	f2fs_up_write(&sbi->cp_global_sem);
2339 	f2fs_up_write(&sbi->gc_lock);
2340 	thaw_super(sbi->sb, FREEZE_HOLDER_USERSPACE);
2341 	return err;
2342 }
2343