1 // SPDX-License-Identifier: GPL-2.0
5 * Copyright (c) 2012 Samsung Electronics Co., Ltd.
6 * http://www.samsung.com/
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>
24 #include <trace/events/f2fs.h>
26 static struct kmem_cache *victim_entry_slab;
28 static unsigned int count_bits(const unsigned long *addr,
29 unsigned int offset, unsigned int len);
31 static int gc_thread_func(void *data)
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;
39 wait_ms = gc_th->min_sleep_time;
43 bool sync_mode, foreground = false;
45 wait_event_interruptible_timeout(*wq,
46 kthread_should_stop() || freezing(current) ||
47 waitqueue_active(fggc_wq) ||
49 msecs_to_jiffies(wait_ms));
51 if (test_opt(sbi, GC_MERGE) && waitqueue_active(fggc_wq))
54 /* give it a try one time */
58 if (try_to_freeze()) {
59 stat_other_skip_bggc_count(sbi);
62 if (kthread_should_stop())
65 if (sbi->sb->s_writers.frozen >= SB_FREEZE_WRITE) {
66 increase_sleep_time(gc_th, &wait_ms);
67 stat_other_skip_bggc_count(sbi);
71 if (time_to_inject(sbi, FAULT_CHECKPOINT)) {
72 f2fs_show_injection_info(sbi, FAULT_CHECKPOINT);
73 f2fs_stop_checkpoint(sbi, false);
76 if (!sb_start_write_trylock(sbi->sb)) {
77 stat_other_skip_bggc_count(sbi);
82 * [GC triggering condition]
83 * 0. GC is not conducted currently.
84 * 1. There are enough dirty segments.
85 * 2. IO subsystem is idle by checking the # of writeback pages.
86 * 3. IO subsystem is idle by checking the # of requests in
87 * bdev's request list.
89 * Note) We have to avoid triggering GCs frequently.
90 * Because it is possible that some segments can be
91 * invalidated soon after by user update or deletion.
92 * So, I'd like to wait some time to collect dirty segments.
94 if (sbi->gc_mode == GC_URGENT_HIGH) {
95 spin_lock(&sbi->gc_urgent_high_lock);
96 if (sbi->gc_urgent_high_limited) {
97 if (!sbi->gc_urgent_high_remaining) {
98 sbi->gc_urgent_high_limited = false;
99 spin_unlock(&sbi->gc_urgent_high_lock);
100 sbi->gc_mode = GC_NORMAL;
103 sbi->gc_urgent_high_remaining--;
105 spin_unlock(&sbi->gc_urgent_high_lock);
107 wait_ms = gc_th->urgent_sleep_time;
108 down_write(&sbi->gc_lock);
113 down_write(&sbi->gc_lock);
115 } else if (!down_write_trylock(&sbi->gc_lock)) {
116 stat_other_skip_bggc_count(sbi);
120 if (!is_idle(sbi, GC_TIME)) {
121 increase_sleep_time(gc_th, &wait_ms);
122 up_write(&sbi->gc_lock);
123 stat_io_skip_bggc_count(sbi);
127 if (has_enough_invalid_blocks(sbi))
128 decrease_sleep_time(gc_th, &wait_ms);
130 increase_sleep_time(gc_th, &wait_ms);
133 stat_inc_bggc_count(sbi->stat_info);
135 sync_mode = F2FS_OPTION(sbi).bggc_mode == BGGC_MODE_SYNC;
137 /* foreground GC was been triggered via f2fs_balance_fs() */
141 /* if return value is not zero, no victim was selected */
142 if (f2fs_gc(sbi, sync_mode, !foreground, false, NULL_SEGNO))
143 wait_ms = gc_th->no_gc_sleep_time;
146 wake_up_all(&gc_th->fggc_wq);
148 trace_f2fs_background_gc(sbi->sb, wait_ms,
149 prefree_segments(sbi), free_segments(sbi));
151 /* balancing f2fs's metadata periodically */
152 f2fs_balance_fs_bg(sbi, true);
154 sb_end_write(sbi->sb);
156 } while (!kthread_should_stop());
160 int f2fs_start_gc_thread(struct f2fs_sb_info *sbi)
162 struct f2fs_gc_kthread *gc_th;
163 dev_t dev = sbi->sb->s_bdev->bd_dev;
166 gc_th = f2fs_kmalloc(sbi, sizeof(struct f2fs_gc_kthread), GFP_KERNEL);
172 gc_th->urgent_sleep_time = DEF_GC_THREAD_URGENT_SLEEP_TIME;
173 gc_th->min_sleep_time = DEF_GC_THREAD_MIN_SLEEP_TIME;
174 gc_th->max_sleep_time = DEF_GC_THREAD_MAX_SLEEP_TIME;
175 gc_th->no_gc_sleep_time = DEF_GC_THREAD_NOGC_SLEEP_TIME;
179 sbi->gc_thread = gc_th;
180 init_waitqueue_head(&sbi->gc_thread->gc_wait_queue_head);
181 init_waitqueue_head(&sbi->gc_thread->fggc_wq);
182 sbi->gc_thread->f2fs_gc_task = kthread_run(gc_thread_func, sbi,
183 "f2fs_gc-%u:%u", MAJOR(dev), MINOR(dev));
184 if (IS_ERR(gc_th->f2fs_gc_task)) {
185 err = PTR_ERR(gc_th->f2fs_gc_task);
187 sbi->gc_thread = NULL;
193 void f2fs_stop_gc_thread(struct f2fs_sb_info *sbi)
195 struct f2fs_gc_kthread *gc_th = sbi->gc_thread;
199 kthread_stop(gc_th->f2fs_gc_task);
200 wake_up_all(&gc_th->fggc_wq);
202 sbi->gc_thread = NULL;
205 static int select_gc_type(struct f2fs_sb_info *sbi, int gc_type)
209 if (gc_type == BG_GC) {
210 if (sbi->am.atgc_enabled)
218 switch (sbi->gc_mode) {
234 static void select_policy(struct f2fs_sb_info *sbi, int gc_type,
235 int type, struct victim_sel_policy *p)
237 struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
239 if (p->alloc_mode == SSR) {
240 p->gc_mode = GC_GREEDY;
241 p->dirty_bitmap = dirty_i->dirty_segmap[type];
242 p->max_search = dirty_i->nr_dirty[type];
244 } else if (p->alloc_mode == AT_SSR) {
245 p->gc_mode = GC_GREEDY;
246 p->dirty_bitmap = dirty_i->dirty_segmap[type];
247 p->max_search = dirty_i->nr_dirty[type];
250 p->gc_mode = select_gc_type(sbi, gc_type);
251 p->ofs_unit = sbi->segs_per_sec;
252 if (__is_large_section(sbi)) {
253 p->dirty_bitmap = dirty_i->dirty_secmap;
254 p->max_search = count_bits(p->dirty_bitmap,
257 p->dirty_bitmap = dirty_i->dirty_segmap[DIRTY];
258 p->max_search = dirty_i->nr_dirty[DIRTY];
263 * adjust candidates range, should select all dirty segments for
264 * foreground GC and urgent GC cases.
266 if (gc_type != FG_GC &&
267 (sbi->gc_mode != GC_URGENT_HIGH) &&
268 (p->gc_mode != GC_AT && p->alloc_mode != AT_SSR) &&
269 p->max_search > sbi->max_victim_search)
270 p->max_search = sbi->max_victim_search;
272 /* let's select beginning hot/small space first in no_heap mode*/
273 if (f2fs_need_rand_seg(sbi))
274 p->offset = prandom_u32() % (MAIN_SECS(sbi) * sbi->segs_per_sec);
275 else if (test_opt(sbi, NOHEAP) &&
276 (type == CURSEG_HOT_DATA || IS_NODESEG(type)))
279 p->offset = SIT_I(sbi)->last_victim[p->gc_mode];
282 static unsigned int get_max_cost(struct f2fs_sb_info *sbi,
283 struct victim_sel_policy *p)
285 /* SSR allocates in a segment unit */
286 if (p->alloc_mode == SSR)
287 return sbi->blocks_per_seg;
288 else if (p->alloc_mode == AT_SSR)
292 if (p->gc_mode == GC_GREEDY)
293 return 2 * sbi->blocks_per_seg * p->ofs_unit;
294 else if (p->gc_mode == GC_CB)
296 else if (p->gc_mode == GC_AT)
298 else /* No other gc_mode */
302 static unsigned int check_bg_victims(struct f2fs_sb_info *sbi)
304 struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
308 * If the gc_type is FG_GC, we can select victim segments
309 * selected by background GC before.
310 * Those segments guarantee they have small valid blocks.
312 for_each_set_bit(secno, dirty_i->victim_secmap, MAIN_SECS(sbi)) {
313 if (sec_usage_check(sbi, secno))
315 clear_bit(secno, dirty_i->victim_secmap);
316 return GET_SEG_FROM_SEC(sbi, secno);
321 static unsigned int get_cb_cost(struct f2fs_sb_info *sbi, unsigned int segno)
323 struct sit_info *sit_i = SIT_I(sbi);
324 unsigned int secno = GET_SEC_FROM_SEG(sbi, segno);
325 unsigned int start = GET_SEG_FROM_SEC(sbi, secno);
326 unsigned long long mtime = 0;
327 unsigned int vblocks;
328 unsigned char age = 0;
331 unsigned int usable_segs_per_sec = f2fs_usable_segs_in_sec(sbi, segno);
333 for (i = 0; i < usable_segs_per_sec; i++)
334 mtime += get_seg_entry(sbi, start + i)->mtime;
335 vblocks = get_valid_blocks(sbi, segno, true);
337 mtime = div_u64(mtime, usable_segs_per_sec);
338 vblocks = div_u64(vblocks, usable_segs_per_sec);
340 u = (vblocks * 100) >> sbi->log_blocks_per_seg;
342 /* Handle if the system time has changed by the user */
343 if (mtime < sit_i->min_mtime)
344 sit_i->min_mtime = mtime;
345 if (mtime > sit_i->max_mtime)
346 sit_i->max_mtime = mtime;
347 if (sit_i->max_mtime != sit_i->min_mtime)
348 age = 100 - div64_u64(100 * (mtime - sit_i->min_mtime),
349 sit_i->max_mtime - sit_i->min_mtime);
351 return UINT_MAX - ((100 * (100 - u) * age) / (100 + u));
354 static inline unsigned int get_gc_cost(struct f2fs_sb_info *sbi,
355 unsigned int segno, struct victim_sel_policy *p)
357 if (p->alloc_mode == SSR)
358 return get_seg_entry(sbi, segno)->ckpt_valid_blocks;
360 /* alloc_mode == LFS */
361 if (p->gc_mode == GC_GREEDY)
362 return get_valid_blocks(sbi, segno, true);
363 else if (p->gc_mode == GC_CB)
364 return get_cb_cost(sbi, segno);
370 static unsigned int count_bits(const unsigned long *addr,
371 unsigned int offset, unsigned int len)
373 unsigned int end = offset + len, sum = 0;
375 while (offset < end) {
376 if (test_bit(offset++, addr))
382 static struct victim_entry *attach_victim_entry(struct f2fs_sb_info *sbi,
383 unsigned long long mtime, unsigned int segno,
384 struct rb_node *parent, struct rb_node **p,
387 struct atgc_management *am = &sbi->am;
388 struct victim_entry *ve;
390 ve = f2fs_kmem_cache_alloc(victim_entry_slab,
391 GFP_NOFS, true, NULL);
396 rb_link_node(&ve->rb_node, parent, p);
397 rb_insert_color_cached(&ve->rb_node, &am->root, left_most);
399 list_add_tail(&ve->list, &am->victim_list);
406 static void insert_victim_entry(struct f2fs_sb_info *sbi,
407 unsigned long long mtime, unsigned int segno)
409 struct atgc_management *am = &sbi->am;
411 struct rb_node *parent = NULL;
412 bool left_most = true;
414 p = f2fs_lookup_rb_tree_ext(sbi, &am->root, &parent, mtime, &left_most);
415 attach_victim_entry(sbi, mtime, segno, parent, p, left_most);
418 static void add_victim_entry(struct f2fs_sb_info *sbi,
419 struct victim_sel_policy *p, unsigned int segno)
421 struct sit_info *sit_i = SIT_I(sbi);
422 unsigned int secno = GET_SEC_FROM_SEG(sbi, segno);
423 unsigned int start = GET_SEG_FROM_SEC(sbi, secno);
424 unsigned long long mtime = 0;
427 if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) {
428 if (p->gc_mode == GC_AT &&
429 get_valid_blocks(sbi, segno, true) == 0)
433 for (i = 0; i < sbi->segs_per_sec; i++)
434 mtime += get_seg_entry(sbi, start + i)->mtime;
435 mtime = div_u64(mtime, sbi->segs_per_sec);
437 /* Handle if the system time has changed by the user */
438 if (mtime < sit_i->min_mtime)
439 sit_i->min_mtime = mtime;
440 if (mtime > sit_i->max_mtime)
441 sit_i->max_mtime = mtime;
442 if (mtime < sit_i->dirty_min_mtime)
443 sit_i->dirty_min_mtime = mtime;
444 if (mtime > sit_i->dirty_max_mtime)
445 sit_i->dirty_max_mtime = mtime;
447 /* don't choose young section as candidate */
448 if (sit_i->dirty_max_mtime - mtime < p->age_threshold)
451 insert_victim_entry(sbi, mtime, segno);
454 static struct rb_node *lookup_central_victim(struct f2fs_sb_info *sbi,
455 struct victim_sel_policy *p)
457 struct atgc_management *am = &sbi->am;
458 struct rb_node *parent = NULL;
461 f2fs_lookup_rb_tree_ext(sbi, &am->root, &parent, p->age, &left_most);
466 static void atgc_lookup_victim(struct f2fs_sb_info *sbi,
467 struct victim_sel_policy *p)
469 struct sit_info *sit_i = SIT_I(sbi);
470 struct atgc_management *am = &sbi->am;
471 struct rb_root_cached *root = &am->root;
472 struct rb_node *node;
474 struct victim_entry *ve;
475 unsigned long long total_time;
476 unsigned long long age, u, accu;
477 unsigned long long max_mtime = sit_i->dirty_max_mtime;
478 unsigned long long min_mtime = sit_i->dirty_min_mtime;
479 unsigned int sec_blocks = BLKS_PER_SEC(sbi);
480 unsigned int vblocks;
481 unsigned int dirty_threshold = max(am->max_candidate_count,
482 am->candidate_ratio *
483 am->victim_count / 100);
484 unsigned int age_weight = am->age_weight;
486 unsigned int iter = 0;
488 if (max_mtime < min_mtime)
492 total_time = max_mtime - min_mtime;
494 accu = div64_u64(ULLONG_MAX, total_time);
495 accu = min_t(unsigned long long, div_u64(accu, 100),
496 DEFAULT_ACCURACY_CLASS);
498 node = rb_first_cached(root);
500 re = rb_entry_safe(node, struct rb_entry, rb_node);
504 ve = (struct victim_entry *)re;
506 if (ve->mtime >= max_mtime || ve->mtime < min_mtime)
509 /* age = 10000 * x% * 60 */
510 age = div64_u64(accu * (max_mtime - ve->mtime), total_time) *
513 vblocks = get_valid_blocks(sbi, ve->segno, true);
514 f2fs_bug_on(sbi, !vblocks || vblocks == sec_blocks);
516 /* u = 10000 * x% * 40 */
517 u = div64_u64(accu * (sec_blocks - vblocks), sec_blocks) *
520 f2fs_bug_on(sbi, age + u >= UINT_MAX);
522 cost = UINT_MAX - (age + u);
525 if (cost < p->min_cost ||
526 (cost == p->min_cost && age > p->oldest_age)) {
529 p->min_segno = ve->segno;
532 if (iter < dirty_threshold) {
533 node = rb_next(node);
539 * select candidates around source section in range of
540 * [target - dirty_threshold, target + dirty_threshold]
542 static void atssr_lookup_victim(struct f2fs_sb_info *sbi,
543 struct victim_sel_policy *p)
545 struct sit_info *sit_i = SIT_I(sbi);
546 struct atgc_management *am = &sbi->am;
547 struct rb_node *node;
549 struct victim_entry *ve;
550 unsigned long long age;
551 unsigned long long max_mtime = sit_i->dirty_max_mtime;
552 unsigned long long min_mtime = sit_i->dirty_min_mtime;
553 unsigned int seg_blocks = sbi->blocks_per_seg;
554 unsigned int vblocks;
555 unsigned int dirty_threshold = max(am->max_candidate_count,
556 am->candidate_ratio *
557 am->victim_count / 100);
559 unsigned int iter = 0;
562 if (max_mtime < min_mtime)
566 node = lookup_central_victim(sbi, p);
568 re = rb_entry_safe(node, struct rb_entry, rb_node);
575 ve = (struct victim_entry *)re;
577 if (ve->mtime >= max_mtime || ve->mtime < min_mtime)
580 age = max_mtime - ve->mtime;
582 vblocks = get_seg_entry(sbi, ve->segno)->ckpt_valid_blocks;
583 f2fs_bug_on(sbi, !vblocks);
586 if (vblocks == seg_blocks)
591 age = max_mtime - abs(p->age - age);
592 cost = UINT_MAX - vblocks;
594 if (cost < p->min_cost ||
595 (cost == p->min_cost && age > p->oldest_age)) {
598 p->min_segno = ve->segno;
601 if (iter < dirty_threshold) {
603 node = rb_prev(node);
605 node = rb_next(node);
615 static void lookup_victim_by_age(struct f2fs_sb_info *sbi,
616 struct victim_sel_policy *p)
618 f2fs_bug_on(sbi, !f2fs_check_rb_tree_consistence(sbi,
619 &sbi->am.root, true));
621 if (p->gc_mode == GC_AT)
622 atgc_lookup_victim(sbi, p);
623 else if (p->alloc_mode == AT_SSR)
624 atssr_lookup_victim(sbi, p);
629 static void release_victim_entry(struct f2fs_sb_info *sbi)
631 struct atgc_management *am = &sbi->am;
632 struct victim_entry *ve, *tmp;
634 list_for_each_entry_safe(ve, tmp, &am->victim_list, list) {
636 kmem_cache_free(victim_entry_slab, ve);
640 am->root = RB_ROOT_CACHED;
642 f2fs_bug_on(sbi, am->victim_count);
643 f2fs_bug_on(sbi, !list_empty(&am->victim_list));
647 * This function is called from two paths.
648 * One is garbage collection and the other is SSR segment selection.
649 * When it is called during GC, it just gets a victim segment
650 * and it does not remove it from dirty seglist.
651 * When it is called from SSR segment selection, it finds a segment
652 * which has minimum valid blocks and removes it from dirty seglist.
654 static int get_victim_by_default(struct f2fs_sb_info *sbi,
655 unsigned int *result, int gc_type, int type,
656 char alloc_mode, unsigned long long age)
658 struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
659 struct sit_info *sm = SIT_I(sbi);
660 struct victim_sel_policy p;
661 unsigned int secno, last_victim;
662 unsigned int last_segment;
663 unsigned int nsearched;
667 mutex_lock(&dirty_i->seglist_lock);
668 last_segment = MAIN_SECS(sbi) * sbi->segs_per_sec;
670 p.alloc_mode = alloc_mode;
672 p.age_threshold = sbi->am.age_threshold;
675 select_policy(sbi, gc_type, type, &p);
676 p.min_segno = NULL_SEGNO;
678 p.min_cost = get_max_cost(sbi, &p);
680 is_atgc = (p.gc_mode == GC_AT || p.alloc_mode == AT_SSR);
684 SIT_I(sbi)->dirty_min_mtime = ULLONG_MAX;
686 if (*result != NULL_SEGNO) {
687 if (!get_valid_blocks(sbi, *result, false)) {
692 if (sec_usage_check(sbi, GET_SEC_FROM_SEG(sbi, *result)))
695 p.min_segno = *result;
700 if (p.max_search == 0)
703 if (__is_large_section(sbi) && p.alloc_mode == LFS) {
704 if (sbi->next_victim_seg[BG_GC] != NULL_SEGNO) {
705 p.min_segno = sbi->next_victim_seg[BG_GC];
706 *result = p.min_segno;
707 sbi->next_victim_seg[BG_GC] = NULL_SEGNO;
710 if (gc_type == FG_GC &&
711 sbi->next_victim_seg[FG_GC] != NULL_SEGNO) {
712 p.min_segno = sbi->next_victim_seg[FG_GC];
713 *result = p.min_segno;
714 sbi->next_victim_seg[FG_GC] = NULL_SEGNO;
719 last_victim = sm->last_victim[p.gc_mode];
720 if (p.alloc_mode == LFS && gc_type == FG_GC) {
721 p.min_segno = check_bg_victims(sbi);
722 if (p.min_segno != NULL_SEGNO)
727 unsigned long cost, *dirty_bitmap;
728 unsigned int unit_no, segno;
730 dirty_bitmap = p.dirty_bitmap;
731 unit_no = find_next_bit(dirty_bitmap,
732 last_segment / p.ofs_unit,
733 p.offset / p.ofs_unit);
734 segno = unit_no * p.ofs_unit;
735 if (segno >= last_segment) {
736 if (sm->last_victim[p.gc_mode]) {
738 sm->last_victim[p.gc_mode];
739 sm->last_victim[p.gc_mode] = 0;
746 p.offset = segno + p.ofs_unit;
749 #ifdef CONFIG_F2FS_CHECK_FS
751 * skip selecting the invalid segno (that is failed due to block
752 * validity check failure during GC) to avoid endless GC loop in
755 if (test_bit(segno, sm->invalid_segmap))
759 secno = GET_SEC_FROM_SEG(sbi, segno);
761 if (sec_usage_check(sbi, secno))
764 /* Don't touch checkpointed data */
765 if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) {
766 if (p.alloc_mode == LFS) {
768 * LFS is set to find source section during GC.
769 * The victim should have no checkpointed data.
771 if (get_ckpt_valid_blocks(sbi, segno, true))
775 * SSR | AT_SSR are set to find target segment
776 * for writes which can be full by checkpointed
777 * and newly written blocks.
779 if (!f2fs_segment_has_free_slot(sbi, segno))
784 if (gc_type == BG_GC && test_bit(secno, dirty_i->victim_secmap))
788 add_victim_entry(sbi, &p, segno);
792 cost = get_gc_cost(sbi, segno, &p);
794 if (p.min_cost > cost) {
799 if (nsearched >= p.max_search) {
800 if (!sm->last_victim[p.gc_mode] && segno <= last_victim)
801 sm->last_victim[p.gc_mode] =
802 last_victim + p.ofs_unit;
804 sm->last_victim[p.gc_mode] = segno + p.ofs_unit;
805 sm->last_victim[p.gc_mode] %=
806 (MAIN_SECS(sbi) * sbi->segs_per_sec);
811 /* get victim for GC_AT/AT_SSR */
813 lookup_victim_by_age(sbi, &p);
814 release_victim_entry(sbi);
817 if (is_atgc && p.min_segno == NULL_SEGNO &&
818 sm->elapsed_time < p.age_threshold) {
823 if (p.min_segno != NULL_SEGNO) {
825 *result = (p.min_segno / p.ofs_unit) * p.ofs_unit;
827 if (p.alloc_mode == LFS) {
828 secno = GET_SEC_FROM_SEG(sbi, p.min_segno);
829 if (gc_type == FG_GC)
830 sbi->cur_victim_sec = secno;
832 set_bit(secno, dirty_i->victim_secmap);
838 if (p.min_segno != NULL_SEGNO)
839 trace_f2fs_get_victim(sbi->sb, type, gc_type, &p,
841 prefree_segments(sbi), free_segments(sbi));
842 mutex_unlock(&dirty_i->seglist_lock);
847 static const struct victim_selection default_v_ops = {
848 .get_victim = get_victim_by_default,
851 static struct inode *find_gc_inode(struct gc_inode_list *gc_list, nid_t ino)
853 struct inode_entry *ie;
855 ie = radix_tree_lookup(&gc_list->iroot, ino);
861 static void add_gc_inode(struct gc_inode_list *gc_list, struct inode *inode)
863 struct inode_entry *new_ie;
865 if (inode == find_gc_inode(gc_list, inode->i_ino)) {
869 new_ie = f2fs_kmem_cache_alloc(f2fs_inode_entry_slab,
870 GFP_NOFS, true, NULL);
871 new_ie->inode = inode;
873 f2fs_radix_tree_insert(&gc_list->iroot, inode->i_ino, new_ie);
874 list_add_tail(&new_ie->list, &gc_list->ilist);
877 static void put_gc_inode(struct gc_inode_list *gc_list)
879 struct inode_entry *ie, *next_ie;
881 list_for_each_entry_safe(ie, next_ie, &gc_list->ilist, list) {
882 radix_tree_delete(&gc_list->iroot, ie->inode->i_ino);
885 kmem_cache_free(f2fs_inode_entry_slab, ie);
889 static int check_valid_map(struct f2fs_sb_info *sbi,
890 unsigned int segno, int offset)
892 struct sit_info *sit_i = SIT_I(sbi);
893 struct seg_entry *sentry;
896 down_read(&sit_i->sentry_lock);
897 sentry = get_seg_entry(sbi, segno);
898 ret = f2fs_test_bit(offset, sentry->cur_valid_map);
899 up_read(&sit_i->sentry_lock);
904 * This function compares node address got in summary with that in NAT.
905 * On validity, copy that node with cold status, otherwise (invalid node)
908 static int gc_node_segment(struct f2fs_sb_info *sbi,
909 struct f2fs_summary *sum, unsigned int segno, int gc_type)
911 struct f2fs_summary *entry;
915 bool fggc = (gc_type == FG_GC);
917 unsigned int usable_blks_in_seg = f2fs_usable_blks_in_seg(sbi, segno);
919 start_addr = START_BLOCK(sbi, segno);
924 if (fggc && phase == 2)
925 atomic_inc(&sbi->wb_sync_req[NODE]);
927 for (off = 0; off < usable_blks_in_seg; off++, entry++) {
928 nid_t nid = le32_to_cpu(entry->nid);
929 struct page *node_page;
933 /* stop BG_GC if there is not enough free sections. */
934 if (gc_type == BG_GC && has_not_enough_free_secs(sbi, 0, 0))
937 if (check_valid_map(sbi, segno, off) == 0)
941 f2fs_ra_meta_pages(sbi, NAT_BLOCK_OFFSET(nid), 1,
947 f2fs_ra_node_page(sbi, nid);
952 node_page = f2fs_get_node_page(sbi, nid);
953 if (IS_ERR(node_page))
956 /* block may become invalid during f2fs_get_node_page */
957 if (check_valid_map(sbi, segno, off) == 0) {
958 f2fs_put_page(node_page, 1);
962 if (f2fs_get_node_info(sbi, nid, &ni, false)) {
963 f2fs_put_page(node_page, 1);
967 if (ni.blk_addr != start_addr + off) {
968 f2fs_put_page(node_page, 1);
972 err = f2fs_move_node_page(node_page, gc_type);
973 if (!err && gc_type == FG_GC)
975 stat_inc_node_blk_count(sbi, 1, gc_type);
982 atomic_dec(&sbi->wb_sync_req[NODE]);
987 * Calculate start block index indicating the given node offset.
988 * Be careful, caller should give this node offset only indicating direct node
989 * blocks. If any node offsets, which point the other types of node blocks such
990 * as indirect or double indirect node blocks, are given, it must be a caller's
993 block_t f2fs_start_bidx_of_node(unsigned int node_ofs, struct inode *inode)
995 unsigned int indirect_blks = 2 * NIDS_PER_BLOCK + 4;
1001 if (node_ofs <= 2) {
1002 bidx = node_ofs - 1;
1003 } else if (node_ofs <= indirect_blks) {
1004 int dec = (node_ofs - 4) / (NIDS_PER_BLOCK + 1);
1006 bidx = node_ofs - 2 - dec;
1008 int dec = (node_ofs - indirect_blks - 3) / (NIDS_PER_BLOCK + 1);
1010 bidx = node_ofs - 5 - dec;
1012 return bidx * ADDRS_PER_BLOCK(inode) + ADDRS_PER_INODE(inode);
1015 static bool is_alive(struct f2fs_sb_info *sbi, struct f2fs_summary *sum,
1016 struct node_info *dni, block_t blkaddr, unsigned int *nofs)
1018 struct page *node_page;
1020 unsigned int ofs_in_node;
1021 block_t source_blkaddr;
1023 nid = le32_to_cpu(sum->nid);
1024 ofs_in_node = le16_to_cpu(sum->ofs_in_node);
1026 node_page = f2fs_get_node_page(sbi, nid);
1027 if (IS_ERR(node_page))
1030 if (f2fs_get_node_info(sbi, nid, dni, false)) {
1031 f2fs_put_page(node_page, 1);
1035 if (sum->version != dni->version) {
1036 f2fs_warn(sbi, "%s: valid data with mismatched node version.",
1038 set_sbi_flag(sbi, SBI_NEED_FSCK);
1041 if (f2fs_check_nid_range(sbi, dni->ino))
1044 *nofs = ofs_of_node(node_page);
1045 source_blkaddr = data_blkaddr(NULL, node_page, ofs_in_node);
1046 f2fs_put_page(node_page, 1);
1048 if (source_blkaddr != blkaddr) {
1049 #ifdef CONFIG_F2FS_CHECK_FS
1050 unsigned int segno = GET_SEGNO(sbi, blkaddr);
1051 unsigned long offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
1053 if (unlikely(check_valid_map(sbi, segno, offset))) {
1054 if (!test_and_set_bit(segno, SIT_I(sbi)->invalid_segmap)) {
1055 f2fs_err(sbi, "mismatched blkaddr %u (source_blkaddr %u) in seg %u",
1056 blkaddr, source_blkaddr, segno);
1057 set_sbi_flag(sbi, SBI_NEED_FSCK);
1066 static int ra_data_block(struct inode *inode, pgoff_t index)
1068 struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1069 struct address_space *mapping = inode->i_mapping;
1070 struct dnode_of_data dn;
1072 struct extent_info ei = {0, 0, 0};
1073 struct f2fs_io_info fio = {
1075 .ino = inode->i_ino,
1080 .encrypted_page = NULL,
1086 page = f2fs_grab_cache_page(mapping, index, true);
1090 if (f2fs_lookup_extent_cache(inode, index, &ei)) {
1091 dn.data_blkaddr = ei.blk + index - ei.fofs;
1092 if (unlikely(!f2fs_is_valid_blkaddr(sbi, dn.data_blkaddr,
1093 DATA_GENERIC_ENHANCE_READ))) {
1094 err = -EFSCORRUPTED;
1100 set_new_dnode(&dn, inode, NULL, NULL, 0);
1101 err = f2fs_get_dnode_of_data(&dn, index, LOOKUP_NODE);
1104 f2fs_put_dnode(&dn);
1106 if (!__is_valid_data_blkaddr(dn.data_blkaddr)) {
1110 if (unlikely(!f2fs_is_valid_blkaddr(sbi, dn.data_blkaddr,
1111 DATA_GENERIC_ENHANCE))) {
1112 err = -EFSCORRUPTED;
1118 fio.new_blkaddr = fio.old_blkaddr = dn.data_blkaddr;
1121 * don't cache encrypted data into meta inode until previous dirty
1122 * data were writebacked to avoid racing between GC and flush.
1124 f2fs_wait_on_page_writeback(page, DATA, true, true);
1126 f2fs_wait_on_block_writeback(inode, dn.data_blkaddr);
1128 fio.encrypted_page = f2fs_pagecache_get_page(META_MAPPING(sbi),
1130 FGP_LOCK | FGP_CREAT, GFP_NOFS);
1131 if (!fio.encrypted_page) {
1136 err = f2fs_submit_page_bio(&fio);
1138 goto put_encrypted_page;
1139 f2fs_put_page(fio.encrypted_page, 0);
1140 f2fs_put_page(page, 1);
1142 f2fs_update_iostat(sbi, FS_DATA_READ_IO, F2FS_BLKSIZE);
1143 f2fs_update_iostat(sbi, FS_GDATA_READ_IO, F2FS_BLKSIZE);
1147 f2fs_put_page(fio.encrypted_page, 1);
1149 f2fs_put_page(page, 1);
1154 * Move data block via META_MAPPING while keeping locked data page.
1155 * This can be used to move blocks, aka LBAs, directly on disk.
1157 static int move_data_block(struct inode *inode, block_t bidx,
1158 int gc_type, unsigned int segno, int off)
1160 struct f2fs_io_info fio = {
1161 .sbi = F2FS_I_SB(inode),
1162 .ino = inode->i_ino,
1167 .encrypted_page = NULL,
1171 struct dnode_of_data dn;
1172 struct f2fs_summary sum;
1173 struct node_info ni;
1174 struct page *page, *mpage;
1177 bool lfs_mode = f2fs_lfs_mode(fio.sbi);
1178 int type = fio.sbi->am.atgc_enabled && (gc_type == BG_GC) &&
1179 (fio.sbi->gc_mode != GC_URGENT_HIGH) ?
1180 CURSEG_ALL_DATA_ATGC : CURSEG_COLD_DATA;
1182 /* do not read out */
1183 page = f2fs_grab_cache_page(inode->i_mapping, bidx, false);
1187 if (!check_valid_map(F2FS_I_SB(inode), segno, off)) {
1192 if (f2fs_is_atomic_file(inode)) {
1193 F2FS_I(inode)->i_gc_failures[GC_FAILURE_ATOMIC]++;
1194 F2FS_I_SB(inode)->skipped_atomic_files[gc_type]++;
1199 if (f2fs_is_pinned_file(inode)) {
1200 f2fs_pin_file_control(inode, true);
1205 set_new_dnode(&dn, inode, NULL, NULL, 0);
1206 err = f2fs_get_dnode_of_data(&dn, bidx, LOOKUP_NODE);
1210 if (unlikely(dn.data_blkaddr == NULL_ADDR)) {
1211 ClearPageUptodate(page);
1217 * don't cache encrypted data into meta inode until previous dirty
1218 * data were writebacked to avoid racing between GC and flush.
1220 f2fs_wait_on_page_writeback(page, DATA, true, true);
1222 f2fs_wait_on_block_writeback(inode, dn.data_blkaddr);
1224 err = f2fs_get_node_info(fio.sbi, dn.nid, &ni, false);
1230 fio.new_blkaddr = fio.old_blkaddr = dn.data_blkaddr;
1233 down_write(&fio.sbi->io_order_lock);
1235 mpage = f2fs_grab_cache_page(META_MAPPING(fio.sbi),
1236 fio.old_blkaddr, false);
1242 fio.encrypted_page = mpage;
1244 /* read source block in mpage */
1245 if (!PageUptodate(mpage)) {
1246 err = f2fs_submit_page_bio(&fio);
1248 f2fs_put_page(mpage, 1);
1252 f2fs_update_iostat(fio.sbi, FS_DATA_READ_IO, F2FS_BLKSIZE);
1253 f2fs_update_iostat(fio.sbi, FS_GDATA_READ_IO, F2FS_BLKSIZE);
1256 if (unlikely(mpage->mapping != META_MAPPING(fio.sbi) ||
1257 !PageUptodate(mpage))) {
1259 f2fs_put_page(mpage, 1);
1264 set_summary(&sum, dn.nid, dn.ofs_in_node, ni.version);
1266 /* allocate block address */
1267 f2fs_allocate_data_block(fio.sbi, NULL, fio.old_blkaddr, &newaddr,
1270 fio.encrypted_page = f2fs_pagecache_get_page(META_MAPPING(fio.sbi),
1271 newaddr, FGP_LOCK | FGP_CREAT, GFP_NOFS);
1272 if (!fio.encrypted_page) {
1274 f2fs_put_page(mpage, 1);
1278 /* write target block */
1279 f2fs_wait_on_page_writeback(fio.encrypted_page, DATA, true, true);
1280 memcpy(page_address(fio.encrypted_page),
1281 page_address(mpage), PAGE_SIZE);
1282 f2fs_put_page(mpage, 1);
1283 invalidate_mapping_pages(META_MAPPING(fio.sbi),
1284 fio.old_blkaddr, fio.old_blkaddr);
1285 f2fs_invalidate_compress_page(fio.sbi, fio.old_blkaddr);
1287 set_page_dirty(fio.encrypted_page);
1288 if (clear_page_dirty_for_io(fio.encrypted_page))
1289 dec_page_count(fio.sbi, F2FS_DIRTY_META);
1291 set_page_writeback(fio.encrypted_page);
1292 ClearPageError(page);
1294 fio.op = REQ_OP_WRITE;
1295 fio.op_flags = REQ_SYNC;
1296 fio.new_blkaddr = newaddr;
1297 f2fs_submit_page_write(&fio);
1300 if (PageWriteback(fio.encrypted_page))
1301 end_page_writeback(fio.encrypted_page);
1305 f2fs_update_iostat(fio.sbi, FS_GC_DATA_IO, F2FS_BLKSIZE);
1307 f2fs_update_data_blkaddr(&dn, newaddr);
1308 set_inode_flag(inode, FI_APPEND_WRITE);
1309 if (page->index == 0)
1310 set_inode_flag(inode, FI_FIRST_BLOCK_WRITTEN);
1312 f2fs_put_page(fio.encrypted_page, 1);
1315 f2fs_do_replace_block(fio.sbi, &sum, newaddr, fio.old_blkaddr,
1319 up_write(&fio.sbi->io_order_lock);
1321 f2fs_put_dnode(&dn);
1323 f2fs_put_page(page, 1);
1327 static int move_data_page(struct inode *inode, block_t bidx, int gc_type,
1328 unsigned int segno, int off)
1333 page = f2fs_get_lock_data_page(inode, bidx, true);
1335 return PTR_ERR(page);
1337 if (!check_valid_map(F2FS_I_SB(inode), segno, off)) {
1342 if (f2fs_is_atomic_file(inode)) {
1343 F2FS_I(inode)->i_gc_failures[GC_FAILURE_ATOMIC]++;
1344 F2FS_I_SB(inode)->skipped_atomic_files[gc_type]++;
1348 if (f2fs_is_pinned_file(inode)) {
1349 if (gc_type == FG_GC)
1350 f2fs_pin_file_control(inode, true);
1355 if (gc_type == BG_GC) {
1356 if (PageWriteback(page)) {
1360 set_page_dirty(page);
1361 set_page_private_gcing(page);
1363 struct f2fs_io_info fio = {
1364 .sbi = F2FS_I_SB(inode),
1365 .ino = inode->i_ino,
1369 .op_flags = REQ_SYNC,
1370 .old_blkaddr = NULL_ADDR,
1372 .encrypted_page = NULL,
1373 .need_lock = LOCK_REQ,
1374 .io_type = FS_GC_DATA_IO,
1376 bool is_dirty = PageDirty(page);
1379 f2fs_wait_on_page_writeback(page, DATA, true, true);
1381 set_page_dirty(page);
1382 if (clear_page_dirty_for_io(page)) {
1383 inode_dec_dirty_pages(inode);
1384 f2fs_remove_dirty_inode(inode);
1387 set_page_private_gcing(page);
1389 err = f2fs_do_write_data_page(&fio);
1391 clear_page_private_gcing(page);
1392 if (err == -ENOMEM) {
1393 memalloc_retry_wait(GFP_NOFS);
1397 set_page_dirty(page);
1401 f2fs_put_page(page, 1);
1406 * This function tries to get parent node of victim data block, and identifies
1407 * data block validity. If the block is valid, copy that with cold status and
1408 * modify parent node.
1409 * If the parent node is not valid or the data block address is different,
1410 * the victim data block is ignored.
1412 static int gc_data_segment(struct f2fs_sb_info *sbi, struct f2fs_summary *sum,
1413 struct gc_inode_list *gc_list, unsigned int segno, int gc_type,
1416 struct super_block *sb = sbi->sb;
1417 struct f2fs_summary *entry;
1422 unsigned int usable_blks_in_seg = f2fs_usable_blks_in_seg(sbi, segno);
1424 start_addr = START_BLOCK(sbi, segno);
1429 for (off = 0; off < usable_blks_in_seg; off++, entry++) {
1430 struct page *data_page;
1431 struct inode *inode;
1432 struct node_info dni; /* dnode info for the data */
1433 unsigned int ofs_in_node, nofs;
1435 nid_t nid = le32_to_cpu(entry->nid);
1438 * stop BG_GC if there is not enough free sections.
1439 * Or, stop GC if the segment becomes fully valid caused by
1440 * race condition along with SSR block allocation.
1442 if ((gc_type == BG_GC && has_not_enough_free_secs(sbi, 0, 0)) ||
1443 (!force_migrate && get_valid_blocks(sbi, segno, true) ==
1447 if (check_valid_map(sbi, segno, off) == 0)
1451 f2fs_ra_meta_pages(sbi, NAT_BLOCK_OFFSET(nid), 1,
1457 f2fs_ra_node_page(sbi, nid);
1461 /* Get an inode by ino with checking validity */
1462 if (!is_alive(sbi, entry, &dni, start_addr + off, &nofs))
1466 f2fs_ra_node_page(sbi, dni.ino);
1470 ofs_in_node = le16_to_cpu(entry->ofs_in_node);
1473 inode = f2fs_iget(sb, dni.ino);
1474 if (IS_ERR(inode) || is_bad_inode(inode) ||
1475 special_file(inode->i_mode))
1478 if (!down_write_trylock(
1479 &F2FS_I(inode)->i_gc_rwsem[WRITE])) {
1481 sbi->skipped_gc_rwsem++;
1485 start_bidx = f2fs_start_bidx_of_node(nofs, inode) +
1488 if (f2fs_post_read_required(inode)) {
1489 int err = ra_data_block(inode, start_bidx);
1491 up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1496 add_gc_inode(gc_list, inode);
1500 data_page = f2fs_get_read_data_page(inode,
1501 start_bidx, REQ_RAHEAD, true);
1502 up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1503 if (IS_ERR(data_page)) {
1508 f2fs_put_page(data_page, 0);
1509 add_gc_inode(gc_list, inode);
1514 inode = find_gc_inode(gc_list, dni.ino);
1516 struct f2fs_inode_info *fi = F2FS_I(inode);
1517 bool locked = false;
1520 if (S_ISREG(inode->i_mode)) {
1521 if (!down_write_trylock(&fi->i_gc_rwsem[READ])) {
1522 sbi->skipped_gc_rwsem++;
1525 if (!down_write_trylock(
1526 &fi->i_gc_rwsem[WRITE])) {
1527 sbi->skipped_gc_rwsem++;
1528 up_write(&fi->i_gc_rwsem[READ]);
1533 /* wait for all inflight aio data */
1534 inode_dio_wait(inode);
1537 start_bidx = f2fs_start_bidx_of_node(nofs, inode)
1539 if (f2fs_post_read_required(inode))
1540 err = move_data_block(inode, start_bidx,
1541 gc_type, segno, off);
1543 err = move_data_page(inode, start_bidx, gc_type,
1546 if (!err && (gc_type == FG_GC ||
1547 f2fs_post_read_required(inode)))
1551 up_write(&fi->i_gc_rwsem[WRITE]);
1552 up_write(&fi->i_gc_rwsem[READ]);
1555 stat_inc_data_blk_count(sbi, 1, gc_type);
1565 static int __get_victim(struct f2fs_sb_info *sbi, unsigned int *victim,
1568 struct sit_info *sit_i = SIT_I(sbi);
1571 down_write(&sit_i->sentry_lock);
1572 ret = DIRTY_I(sbi)->v_ops->get_victim(sbi, victim, gc_type,
1573 NO_CHECK_TYPE, LFS, 0);
1574 up_write(&sit_i->sentry_lock);
1578 static int do_garbage_collect(struct f2fs_sb_info *sbi,
1579 unsigned int start_segno,
1580 struct gc_inode_list *gc_list, int gc_type,
1583 struct page *sum_page;
1584 struct f2fs_summary_block *sum;
1585 struct blk_plug plug;
1586 unsigned int segno = start_segno;
1587 unsigned int end_segno = start_segno + sbi->segs_per_sec;
1588 int seg_freed = 0, migrated = 0;
1589 unsigned char type = IS_DATASEG(get_seg_entry(sbi, segno)->type) ?
1590 SUM_TYPE_DATA : SUM_TYPE_NODE;
1593 if (__is_large_section(sbi))
1594 end_segno = rounddown(end_segno, sbi->segs_per_sec);
1597 * zone-capacity can be less than zone-size in zoned devices,
1598 * resulting in less than expected usable segments in the zone,
1599 * calculate the end segno in the zone which can be garbage collected
1601 if (f2fs_sb_has_blkzoned(sbi))
1602 end_segno -= sbi->segs_per_sec -
1603 f2fs_usable_segs_in_sec(sbi, segno);
1605 sanity_check_seg_type(sbi, get_seg_entry(sbi, segno)->type);
1607 /* readahead multi ssa blocks those have contiguous address */
1608 if (__is_large_section(sbi))
1609 f2fs_ra_meta_pages(sbi, GET_SUM_BLOCK(sbi, segno),
1610 end_segno - segno, META_SSA, true);
1612 /* reference all summary page */
1613 while (segno < end_segno) {
1614 sum_page = f2fs_get_sum_page(sbi, segno++);
1615 if (IS_ERR(sum_page)) {
1616 int err = PTR_ERR(sum_page);
1618 end_segno = segno - 1;
1619 for (segno = start_segno; segno < end_segno; segno++) {
1620 sum_page = find_get_page(META_MAPPING(sbi),
1621 GET_SUM_BLOCK(sbi, segno));
1622 f2fs_put_page(sum_page, 0);
1623 f2fs_put_page(sum_page, 0);
1627 unlock_page(sum_page);
1630 blk_start_plug(&plug);
1632 for (segno = start_segno; segno < end_segno; segno++) {
1634 /* find segment summary of victim */
1635 sum_page = find_get_page(META_MAPPING(sbi),
1636 GET_SUM_BLOCK(sbi, segno));
1637 f2fs_put_page(sum_page, 0);
1639 if (get_valid_blocks(sbi, segno, false) == 0)
1641 if (gc_type == BG_GC && __is_large_section(sbi) &&
1642 migrated >= sbi->migration_granularity)
1644 if (!PageUptodate(sum_page) || unlikely(f2fs_cp_error(sbi)))
1647 sum = page_address(sum_page);
1648 if (type != GET_SUM_TYPE((&sum->footer))) {
1649 f2fs_err(sbi, "Inconsistent segment (%u) type [%d, %d] in SSA and SIT",
1650 segno, type, GET_SUM_TYPE((&sum->footer)));
1651 set_sbi_flag(sbi, SBI_NEED_FSCK);
1652 f2fs_stop_checkpoint(sbi, false);
1657 * this is to avoid deadlock:
1658 * - lock_page(sum_page) - f2fs_replace_block
1659 * - check_valid_map() - down_write(sentry_lock)
1660 * - down_read(sentry_lock) - change_curseg()
1661 * - lock_page(sum_page)
1663 if (type == SUM_TYPE_NODE)
1664 submitted += gc_node_segment(sbi, sum->entries, segno,
1667 submitted += gc_data_segment(sbi, sum->entries, gc_list,
1671 stat_inc_seg_count(sbi, type, gc_type);
1672 sbi->gc_reclaimed_segs[sbi->gc_mode]++;
1676 if (gc_type == FG_GC &&
1677 get_valid_blocks(sbi, segno, false) == 0)
1680 if (__is_large_section(sbi) && segno + 1 < end_segno)
1681 sbi->next_victim_seg[gc_type] = segno + 1;
1683 f2fs_put_page(sum_page, 0);
1687 f2fs_submit_merged_write(sbi,
1688 (type == SUM_TYPE_NODE) ? NODE : DATA);
1690 blk_finish_plug(&plug);
1692 stat_inc_call_count(sbi->stat_info);
1697 int f2fs_gc(struct f2fs_sb_info *sbi, bool sync,
1698 bool background, bool force, unsigned int segno)
1700 int gc_type = sync ? FG_GC : BG_GC;
1701 int sec_freed = 0, seg_freed = 0, total_freed = 0;
1703 struct cp_control cpc;
1704 unsigned int init_segno = segno;
1705 struct gc_inode_list gc_list = {
1706 .ilist = LIST_HEAD_INIT(gc_list.ilist),
1707 .iroot = RADIX_TREE_INIT(gc_list.iroot, GFP_NOFS),
1709 unsigned long long last_skipped = sbi->skipped_atomic_files[FG_GC];
1710 unsigned long long first_skipped;
1711 unsigned int skipped_round = 0, round = 0;
1713 trace_f2fs_gc_begin(sbi->sb, sync, background,
1714 get_pages(sbi, F2FS_DIRTY_NODES),
1715 get_pages(sbi, F2FS_DIRTY_DENTS),
1716 get_pages(sbi, F2FS_DIRTY_IMETA),
1719 reserved_segments(sbi),
1720 prefree_segments(sbi));
1722 cpc.reason = __get_cp_reason(sbi);
1723 sbi->skipped_gc_rwsem = 0;
1724 first_skipped = last_skipped;
1726 if (unlikely(!(sbi->sb->s_flags & SB_ACTIVE))) {
1730 if (unlikely(f2fs_cp_error(sbi))) {
1735 if (gc_type == BG_GC && has_not_enough_free_secs(sbi, 0, 0)) {
1737 * For example, if there are many prefree_segments below given
1738 * threshold, we can make them free by checkpoint. Then, we
1739 * secure free segments which doesn't need fggc any more.
1741 if (prefree_segments(sbi) &&
1742 !is_sbi_flag_set(sbi, SBI_CP_DISABLED)) {
1743 ret = f2fs_write_checkpoint(sbi, &cpc);
1747 if (has_not_enough_free_secs(sbi, 0, 0))
1751 /* f2fs_balance_fs doesn't need to do BG_GC in critical path. */
1752 if (gc_type == BG_GC && !background) {
1756 ret = __get_victim(sbi, &segno, gc_type);
1760 seg_freed = do_garbage_collect(sbi, segno, &gc_list, gc_type, force);
1761 if (gc_type == FG_GC &&
1762 seg_freed == f2fs_usable_segs_in_sec(sbi, segno))
1764 total_freed += seg_freed;
1766 if (gc_type == FG_GC) {
1767 if (sbi->skipped_atomic_files[FG_GC] > last_skipped ||
1768 sbi->skipped_gc_rwsem)
1770 last_skipped = sbi->skipped_atomic_files[FG_GC];
1774 if (gc_type == FG_GC)
1775 sbi->cur_victim_sec = NULL_SEGNO;
1780 if (has_not_enough_free_secs(sbi, sec_freed, 0)) {
1781 if (skipped_round <= MAX_SKIP_GC_COUNT ||
1782 skipped_round * 2 < round) {
1787 if (first_skipped < last_skipped &&
1788 (last_skipped - first_skipped) >
1789 sbi->skipped_gc_rwsem) {
1790 f2fs_drop_inmem_pages_all(sbi, true);
1794 if (gc_type == FG_GC && !is_sbi_flag_set(sbi, SBI_CP_DISABLED))
1795 ret = f2fs_write_checkpoint(sbi, &cpc);
1798 SIT_I(sbi)->last_victim[ALLOC_NEXT] = 0;
1799 SIT_I(sbi)->last_victim[FLUSH_DEVICE] = init_segno;
1801 trace_f2fs_gc_end(sbi->sb, ret, total_freed, sec_freed,
1802 get_pages(sbi, F2FS_DIRTY_NODES),
1803 get_pages(sbi, F2FS_DIRTY_DENTS),
1804 get_pages(sbi, F2FS_DIRTY_IMETA),
1807 reserved_segments(sbi),
1808 prefree_segments(sbi));
1810 up_write(&sbi->gc_lock);
1812 put_gc_inode(&gc_list);
1815 ret = sec_freed ? 0 : -EAGAIN;
1819 int __init f2fs_create_garbage_collection_cache(void)
1821 victim_entry_slab = f2fs_kmem_cache_create("f2fs_victim_entry",
1822 sizeof(struct victim_entry));
1823 if (!victim_entry_slab)
1828 void f2fs_destroy_garbage_collection_cache(void)
1830 kmem_cache_destroy(victim_entry_slab);
1833 static void init_atgc_management(struct f2fs_sb_info *sbi)
1835 struct atgc_management *am = &sbi->am;
1837 if (test_opt(sbi, ATGC) &&
1838 SIT_I(sbi)->elapsed_time >= DEF_GC_THREAD_AGE_THRESHOLD)
1839 am->atgc_enabled = true;
1841 am->root = RB_ROOT_CACHED;
1842 INIT_LIST_HEAD(&am->victim_list);
1843 am->victim_count = 0;
1845 am->candidate_ratio = DEF_GC_THREAD_CANDIDATE_RATIO;
1846 am->max_candidate_count = DEF_GC_THREAD_MAX_CANDIDATE_COUNT;
1847 am->age_weight = DEF_GC_THREAD_AGE_WEIGHT;
1848 am->age_threshold = DEF_GC_THREAD_AGE_THRESHOLD;
1851 void f2fs_build_gc_manager(struct f2fs_sb_info *sbi)
1853 DIRTY_I(sbi)->v_ops = &default_v_ops;
1855 sbi->gc_pin_file_threshold = DEF_GC_FAILED_PINNED_FILES;
1857 /* give warm/cold data area from slower device */
1858 if (f2fs_is_multi_device(sbi) && !__is_large_section(sbi))
1859 SIT_I(sbi)->last_victim[ALLOC_NEXT] =
1860 GET_SEGNO(sbi, FDEV(0).end_blk) + 1;
1862 init_atgc_management(sbi);
1865 static int free_segment_range(struct f2fs_sb_info *sbi,
1866 unsigned int secs, bool gc_only)
1868 unsigned int segno, next_inuse, start, end;
1869 struct cp_control cpc = { CP_RESIZE, 0, 0, 0 };
1870 int gc_mode, gc_type;
1874 /* Force block allocation for GC */
1875 MAIN_SECS(sbi) -= secs;
1876 start = MAIN_SECS(sbi) * sbi->segs_per_sec;
1877 end = MAIN_SEGS(sbi) - 1;
1879 mutex_lock(&DIRTY_I(sbi)->seglist_lock);
1880 for (gc_mode = 0; gc_mode < MAX_GC_POLICY; gc_mode++)
1881 if (SIT_I(sbi)->last_victim[gc_mode] >= start)
1882 SIT_I(sbi)->last_victim[gc_mode] = 0;
1884 for (gc_type = BG_GC; gc_type <= FG_GC; gc_type++)
1885 if (sbi->next_victim_seg[gc_type] >= start)
1886 sbi->next_victim_seg[gc_type] = NULL_SEGNO;
1887 mutex_unlock(&DIRTY_I(sbi)->seglist_lock);
1889 /* Move out cursegs from the target range */
1890 for (type = CURSEG_HOT_DATA; type < NR_CURSEG_PERSIST_TYPE; type++)
1891 f2fs_allocate_segment_for_resize(sbi, type, start, end);
1893 /* do GC to move out valid blocks in the range */
1894 for (segno = start; segno <= end; segno += sbi->segs_per_sec) {
1895 struct gc_inode_list gc_list = {
1896 .ilist = LIST_HEAD_INIT(gc_list.ilist),
1897 .iroot = RADIX_TREE_INIT(gc_list.iroot, GFP_NOFS),
1900 do_garbage_collect(sbi, segno, &gc_list, FG_GC, true);
1901 put_gc_inode(&gc_list);
1903 if (!gc_only && get_valid_blocks(sbi, segno, true)) {
1907 if (fatal_signal_pending(current)) {
1915 err = f2fs_write_checkpoint(sbi, &cpc);
1919 next_inuse = find_next_inuse(FREE_I(sbi), end + 1, start);
1920 if (next_inuse <= end) {
1921 f2fs_err(sbi, "segno %u should be free but still inuse!",
1923 f2fs_bug_on(sbi, 1);
1926 MAIN_SECS(sbi) += secs;
1930 static void update_sb_metadata(struct f2fs_sb_info *sbi, int secs)
1932 struct f2fs_super_block *raw_sb = F2FS_RAW_SUPER(sbi);
1935 int segment_count_main;
1936 long long block_count;
1937 int segs = secs * sbi->segs_per_sec;
1939 down_write(&sbi->sb_lock);
1941 section_count = le32_to_cpu(raw_sb->section_count);
1942 segment_count = le32_to_cpu(raw_sb->segment_count);
1943 segment_count_main = le32_to_cpu(raw_sb->segment_count_main);
1944 block_count = le64_to_cpu(raw_sb->block_count);
1946 raw_sb->section_count = cpu_to_le32(section_count + secs);
1947 raw_sb->segment_count = cpu_to_le32(segment_count + segs);
1948 raw_sb->segment_count_main = cpu_to_le32(segment_count_main + segs);
1949 raw_sb->block_count = cpu_to_le64(block_count +
1950 (long long)segs * sbi->blocks_per_seg);
1951 if (f2fs_is_multi_device(sbi)) {
1952 int last_dev = sbi->s_ndevs - 1;
1954 le32_to_cpu(raw_sb->devs[last_dev].total_segments);
1956 raw_sb->devs[last_dev].total_segments =
1957 cpu_to_le32(dev_segs + segs);
1960 up_write(&sbi->sb_lock);
1963 static void update_fs_metadata(struct f2fs_sb_info *sbi, int secs)
1965 int segs = secs * sbi->segs_per_sec;
1966 long long blks = (long long)segs * sbi->blocks_per_seg;
1967 long long user_block_count =
1968 le64_to_cpu(F2FS_CKPT(sbi)->user_block_count);
1970 SM_I(sbi)->segment_count = (int)SM_I(sbi)->segment_count + segs;
1971 MAIN_SEGS(sbi) = (int)MAIN_SEGS(sbi) + segs;
1972 MAIN_SECS(sbi) += secs;
1973 FREE_I(sbi)->free_sections = (int)FREE_I(sbi)->free_sections + secs;
1974 FREE_I(sbi)->free_segments = (int)FREE_I(sbi)->free_segments + segs;
1975 F2FS_CKPT(sbi)->user_block_count = cpu_to_le64(user_block_count + blks);
1977 if (f2fs_is_multi_device(sbi)) {
1978 int last_dev = sbi->s_ndevs - 1;
1980 FDEV(last_dev).total_segments =
1981 (int)FDEV(last_dev).total_segments + segs;
1982 FDEV(last_dev).end_blk =
1983 (long long)FDEV(last_dev).end_blk + blks;
1984 #ifdef CONFIG_BLK_DEV_ZONED
1985 FDEV(last_dev).nr_blkz = (int)FDEV(last_dev).nr_blkz +
1986 (int)(blks >> sbi->log_blocks_per_blkz);
1991 int f2fs_resize_fs(struct f2fs_sb_info *sbi, __u64 block_count)
1993 __u64 old_block_count, shrunk_blocks;
1994 struct cp_control cpc = { CP_RESIZE, 0, 0, 0 };
1999 old_block_count = le64_to_cpu(F2FS_RAW_SUPER(sbi)->block_count);
2000 if (block_count > old_block_count)
2003 if (f2fs_is_multi_device(sbi)) {
2004 int last_dev = sbi->s_ndevs - 1;
2005 __u64 last_segs = FDEV(last_dev).total_segments;
2007 if (block_count + last_segs * sbi->blocks_per_seg <=
2012 /* new fs size should align to section size */
2013 div_u64_rem(block_count, BLKS_PER_SEC(sbi), &rem);
2017 if (block_count == old_block_count)
2020 if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) {
2021 f2fs_err(sbi, "Should run fsck to repair first.");
2022 return -EFSCORRUPTED;
2025 if (test_opt(sbi, DISABLE_CHECKPOINT)) {
2026 f2fs_err(sbi, "Checkpoint should be enabled.");
2030 shrunk_blocks = old_block_count - block_count;
2031 secs = div_u64(shrunk_blocks, BLKS_PER_SEC(sbi));
2034 if (!down_write_trylock(&sbi->gc_lock))
2037 /* stop CP to protect MAIN_SEC in free_segment_range */
2040 spin_lock(&sbi->stat_lock);
2041 if (shrunk_blocks + valid_user_blocks(sbi) +
2042 sbi->current_reserved_blocks + sbi->unusable_block_count +
2043 F2FS_OPTION(sbi).root_reserved_blocks > sbi->user_block_count)
2045 spin_unlock(&sbi->stat_lock);
2050 err = free_segment_range(sbi, secs, true);
2053 f2fs_unlock_op(sbi);
2054 up_write(&sbi->gc_lock);
2058 set_sbi_flag(sbi, SBI_IS_RESIZEFS);
2060 freeze_super(sbi->sb);
2061 down_write(&sbi->gc_lock);
2062 down_write(&sbi->cp_global_sem);
2064 spin_lock(&sbi->stat_lock);
2065 if (shrunk_blocks + valid_user_blocks(sbi) +
2066 sbi->current_reserved_blocks + sbi->unusable_block_count +
2067 F2FS_OPTION(sbi).root_reserved_blocks > sbi->user_block_count)
2070 sbi->user_block_count -= shrunk_blocks;
2071 spin_unlock(&sbi->stat_lock);
2075 err = free_segment_range(sbi, secs, false);
2079 update_sb_metadata(sbi, -secs);
2081 err = f2fs_commit_super(sbi, false);
2083 update_sb_metadata(sbi, secs);
2087 update_fs_metadata(sbi, -secs);
2088 clear_sbi_flag(sbi, SBI_IS_RESIZEFS);
2089 set_sbi_flag(sbi, SBI_IS_DIRTY);
2091 err = f2fs_write_checkpoint(sbi, &cpc);
2093 update_fs_metadata(sbi, secs);
2094 update_sb_metadata(sbi, secs);
2095 f2fs_commit_super(sbi, false);
2099 set_sbi_flag(sbi, SBI_NEED_FSCK);
2100 f2fs_err(sbi, "resize_fs failed, should run fsck to repair!");
2102 spin_lock(&sbi->stat_lock);
2103 sbi->user_block_count += shrunk_blocks;
2104 spin_unlock(&sbi->stat_lock);
2107 up_write(&sbi->cp_global_sem);
2108 up_write(&sbi->gc_lock);
2109 thaw_super(sbi->sb);
2110 clear_sbi_flag(sbi, SBI_IS_RESIZEFS);