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