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