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