7a4f7c88b8b9f357691967b22dfc47302c0b7b0d
[platform/kernel/linux-starfive.git] / fs / f2fs / segment.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * fs/f2fs/segment.c
4  *
5  * Copyright (c) 2012 Samsung Electronics Co., Ltd.
6  *             http://www.samsung.com/
7  */
8 #include <linux/fs.h>
9 #include <linux/f2fs_fs.h>
10 #include <linux/bio.h>
11 #include <linux/blkdev.h>
12 #include <linux/sched/mm.h>
13 #include <linux/prefetch.h>
14 #include <linux/kthread.h>
15 #include <linux/swap.h>
16 #include <linux/timer.h>
17 #include <linux/freezer.h>
18 #include <linux/sched/signal.h>
19 #include <linux/random.h>
20
21 #include "f2fs.h"
22 #include "segment.h"
23 #include "node.h"
24 #include "gc.h"
25 #include "iostat.h"
26 #include <trace/events/f2fs.h>
27
28 #define __reverse_ffz(x) __reverse_ffs(~(x))
29
30 static struct kmem_cache *discard_entry_slab;
31 static struct kmem_cache *discard_cmd_slab;
32 static struct kmem_cache *sit_entry_set_slab;
33 static struct kmem_cache *revoke_entry_slab;
34
35 static unsigned long __reverse_ulong(unsigned char *str)
36 {
37         unsigned long tmp = 0;
38         int shift = 24, idx = 0;
39
40 #if BITS_PER_LONG == 64
41         shift = 56;
42 #endif
43         while (shift >= 0) {
44                 tmp |= (unsigned long)str[idx++] << shift;
45                 shift -= BITS_PER_BYTE;
46         }
47         return tmp;
48 }
49
50 /*
51  * __reverse_ffs is copied from include/asm-generic/bitops/__ffs.h since
52  * MSB and LSB are reversed in a byte by f2fs_set_bit.
53  */
54 static inline unsigned long __reverse_ffs(unsigned long word)
55 {
56         int num = 0;
57
58 #if BITS_PER_LONG == 64
59         if ((word & 0xffffffff00000000UL) == 0)
60                 num += 32;
61         else
62                 word >>= 32;
63 #endif
64         if ((word & 0xffff0000) == 0)
65                 num += 16;
66         else
67                 word >>= 16;
68
69         if ((word & 0xff00) == 0)
70                 num += 8;
71         else
72                 word >>= 8;
73
74         if ((word & 0xf0) == 0)
75                 num += 4;
76         else
77                 word >>= 4;
78
79         if ((word & 0xc) == 0)
80                 num += 2;
81         else
82                 word >>= 2;
83
84         if ((word & 0x2) == 0)
85                 num += 1;
86         return num;
87 }
88
89 /*
90  * __find_rev_next(_zero)_bit is copied from lib/find_next_bit.c because
91  * f2fs_set_bit makes MSB and LSB reversed in a byte.
92  * @size must be integral times of unsigned long.
93  * Example:
94  *                             MSB <--> LSB
95  *   f2fs_set_bit(0, bitmap) => 1000 0000
96  *   f2fs_set_bit(7, bitmap) => 0000 0001
97  */
98 static unsigned long __find_rev_next_bit(const unsigned long *addr,
99                         unsigned long size, unsigned long offset)
100 {
101         const unsigned long *p = addr + BIT_WORD(offset);
102         unsigned long result = size;
103         unsigned long tmp;
104
105         if (offset >= size)
106                 return size;
107
108         size -= (offset & ~(BITS_PER_LONG - 1));
109         offset %= BITS_PER_LONG;
110
111         while (1) {
112                 if (*p == 0)
113                         goto pass;
114
115                 tmp = __reverse_ulong((unsigned char *)p);
116
117                 tmp &= ~0UL >> offset;
118                 if (size < BITS_PER_LONG)
119                         tmp &= (~0UL << (BITS_PER_LONG - size));
120                 if (tmp)
121                         goto found;
122 pass:
123                 if (size <= BITS_PER_LONG)
124                         break;
125                 size -= BITS_PER_LONG;
126                 offset = 0;
127                 p++;
128         }
129         return result;
130 found:
131         return result - size + __reverse_ffs(tmp);
132 }
133
134 static unsigned long __find_rev_next_zero_bit(const unsigned long *addr,
135                         unsigned long size, unsigned long offset)
136 {
137         const unsigned long *p = addr + BIT_WORD(offset);
138         unsigned long result = size;
139         unsigned long tmp;
140
141         if (offset >= size)
142                 return size;
143
144         size -= (offset & ~(BITS_PER_LONG - 1));
145         offset %= BITS_PER_LONG;
146
147         while (1) {
148                 if (*p == ~0UL)
149                         goto pass;
150
151                 tmp = __reverse_ulong((unsigned char *)p);
152
153                 if (offset)
154                         tmp |= ~0UL << (BITS_PER_LONG - offset);
155                 if (size < BITS_PER_LONG)
156                         tmp |= ~0UL >> size;
157                 if (tmp != ~0UL)
158                         goto found;
159 pass:
160                 if (size <= BITS_PER_LONG)
161                         break;
162                 size -= BITS_PER_LONG;
163                 offset = 0;
164                 p++;
165         }
166         return result;
167 found:
168         return result - size + __reverse_ffz(tmp);
169 }
170
171 bool f2fs_need_SSR(struct f2fs_sb_info *sbi)
172 {
173         int node_secs = get_blocktype_secs(sbi, F2FS_DIRTY_NODES);
174         int dent_secs = get_blocktype_secs(sbi, F2FS_DIRTY_DENTS);
175         int imeta_secs = get_blocktype_secs(sbi, F2FS_DIRTY_IMETA);
176
177         if (f2fs_lfs_mode(sbi))
178                 return false;
179         if (sbi->gc_mode == GC_URGENT_HIGH)
180                 return true;
181         if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED)))
182                 return true;
183
184         return free_sections(sbi) <= (node_secs + 2 * dent_secs + imeta_secs +
185                         SM_I(sbi)->min_ssr_sections + reserved_sections(sbi));
186 }
187
188 void f2fs_abort_atomic_write(struct inode *inode, bool clean)
189 {
190         struct f2fs_inode_info *fi = F2FS_I(inode);
191
192         if (!f2fs_is_atomic_file(inode))
193                 return;
194
195         if (clean)
196                 truncate_inode_pages_final(inode->i_mapping);
197         clear_inode_flag(fi->cow_inode, FI_COW_FILE);
198         iput(fi->cow_inode);
199         fi->cow_inode = NULL;
200         release_atomic_write_cnt(inode);
201         clear_inode_flag(inode, FI_ATOMIC_FILE);
202         stat_dec_atomic_inode(inode);
203 }
204
205 static int __replace_atomic_write_block(struct inode *inode, pgoff_t index,
206                         block_t new_addr, block_t *old_addr, bool recover)
207 {
208         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
209         struct dnode_of_data dn;
210         struct node_info ni;
211         int err;
212
213 retry:
214         set_new_dnode(&dn, inode, NULL, NULL, 0);
215         err = f2fs_get_dnode_of_data(&dn, index, LOOKUP_NODE_RA);
216         if (err) {
217                 if (err == -ENOMEM) {
218                         f2fs_io_schedule_timeout(DEFAULT_IO_TIMEOUT);
219                         goto retry;
220                 }
221                 return err;
222         }
223
224         err = f2fs_get_node_info(sbi, dn.nid, &ni, false);
225         if (err) {
226                 f2fs_put_dnode(&dn);
227                 return err;
228         }
229
230         if (recover) {
231                 /* dn.data_blkaddr is always valid */
232                 if (!__is_valid_data_blkaddr(new_addr)) {
233                         if (new_addr == NULL_ADDR)
234                                 dec_valid_block_count(sbi, inode, 1);
235                         f2fs_invalidate_blocks(sbi, dn.data_blkaddr);
236                         f2fs_update_data_blkaddr(&dn, new_addr);
237                 } else {
238                         f2fs_replace_block(sbi, &dn, dn.data_blkaddr,
239                                 new_addr, ni.version, true, true);
240                 }
241         } else {
242                 blkcnt_t count = 1;
243
244                 *old_addr = dn.data_blkaddr;
245                 f2fs_truncate_data_blocks_range(&dn, 1);
246                 dec_valid_block_count(sbi, F2FS_I(inode)->cow_inode, count);
247                 inc_valid_block_count(sbi, inode, &count);
248                 f2fs_replace_block(sbi, &dn, dn.data_blkaddr, new_addr,
249                                         ni.version, true, false);
250         }
251
252         f2fs_put_dnode(&dn);
253         return 0;
254 }
255
256 static void __complete_revoke_list(struct inode *inode, struct list_head *head,
257                                         bool revoke)
258 {
259         struct revoke_entry *cur, *tmp;
260
261         list_for_each_entry_safe(cur, tmp, head, list) {
262                 if (revoke)
263                         __replace_atomic_write_block(inode, cur->index,
264                                                 cur->old_addr, NULL, true);
265                 list_del(&cur->list);
266                 kmem_cache_free(revoke_entry_slab, cur);
267         }
268 }
269
270 static int __f2fs_commit_atomic_write(struct inode *inode)
271 {
272         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
273         struct f2fs_inode_info *fi = F2FS_I(inode);
274         struct inode *cow_inode = fi->cow_inode;
275         struct revoke_entry *new;
276         struct list_head revoke_list;
277         block_t blkaddr;
278         struct dnode_of_data dn;
279         pgoff_t len = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
280         pgoff_t off = 0, blen, index;
281         int ret = 0, i;
282
283         INIT_LIST_HEAD(&revoke_list);
284
285         while (len) {
286                 blen = min_t(pgoff_t, ADDRS_PER_BLOCK(cow_inode), len);
287
288                 set_new_dnode(&dn, cow_inode, NULL, NULL, 0);
289                 ret = f2fs_get_dnode_of_data(&dn, off, LOOKUP_NODE_RA);
290                 if (ret && ret != -ENOENT) {
291                         goto out;
292                 } else if (ret == -ENOENT) {
293                         ret = 0;
294                         if (dn.max_level == 0)
295                                 goto out;
296                         goto next;
297                 }
298
299                 blen = min((pgoff_t)ADDRS_PER_PAGE(dn.node_page, cow_inode),
300                                 len);
301                 index = off;
302                 for (i = 0; i < blen; i++, dn.ofs_in_node++, index++) {
303                         blkaddr = f2fs_data_blkaddr(&dn);
304
305                         if (!__is_valid_data_blkaddr(blkaddr)) {
306                                 continue;
307                         } else if (!f2fs_is_valid_blkaddr(sbi, blkaddr,
308                                         DATA_GENERIC_ENHANCE)) {
309                                 f2fs_put_dnode(&dn);
310                                 ret = -EFSCORRUPTED;
311                                 f2fs_handle_error(sbi,
312                                                 ERROR_INVALID_BLKADDR);
313                                 goto out;
314                         }
315
316                         new = f2fs_kmem_cache_alloc(revoke_entry_slab, GFP_NOFS,
317                                                         true, NULL);
318
319                         ret = __replace_atomic_write_block(inode, index, blkaddr,
320                                                         &new->old_addr, false);
321                         if (ret) {
322                                 f2fs_put_dnode(&dn);
323                                 kmem_cache_free(revoke_entry_slab, new);
324                                 goto out;
325                         }
326
327                         f2fs_update_data_blkaddr(&dn, NULL_ADDR);
328                         new->index = index;
329                         list_add_tail(&new->list, &revoke_list);
330                 }
331                 f2fs_put_dnode(&dn);
332 next:
333                 off += blen;
334                 len -= blen;
335         }
336
337 out:
338         if (ret)
339                 sbi->revoked_atomic_block += fi->atomic_write_cnt;
340         else
341                 sbi->committed_atomic_block += fi->atomic_write_cnt;
342
343         __complete_revoke_list(inode, &revoke_list, ret ? true : false);
344
345         return ret;
346 }
347
348 int f2fs_commit_atomic_write(struct inode *inode)
349 {
350         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
351         struct f2fs_inode_info *fi = F2FS_I(inode);
352         int err;
353
354         err = filemap_write_and_wait_range(inode->i_mapping, 0, LLONG_MAX);
355         if (err)
356                 return err;
357
358         f2fs_down_write(&fi->i_gc_rwsem[WRITE]);
359         f2fs_lock_op(sbi);
360
361         err = __f2fs_commit_atomic_write(inode);
362
363         f2fs_unlock_op(sbi);
364         f2fs_up_write(&fi->i_gc_rwsem[WRITE]);
365
366         return err;
367 }
368
369 /*
370  * This function balances dirty node and dentry pages.
371  * In addition, it controls garbage collection.
372  */
373 void f2fs_balance_fs(struct f2fs_sb_info *sbi, bool need)
374 {
375         if (time_to_inject(sbi, FAULT_CHECKPOINT)) {
376                 f2fs_show_injection_info(sbi, FAULT_CHECKPOINT);
377                 f2fs_stop_checkpoint(sbi, false, STOP_CP_REASON_FAULT_INJECT);
378         }
379
380         /* balance_fs_bg is able to be pending */
381         if (need && excess_cached_nats(sbi))
382                 f2fs_balance_fs_bg(sbi, false);
383
384         if (!f2fs_is_checkpoint_ready(sbi))
385                 return;
386
387         /*
388          * We should do GC or end up with checkpoint, if there are so many dirty
389          * dir/node pages without enough free segments.
390          */
391         if (has_not_enough_free_secs(sbi, 0, 0)) {
392                 if (test_opt(sbi, GC_MERGE) && sbi->gc_thread &&
393                                         sbi->gc_thread->f2fs_gc_task) {
394                         DEFINE_WAIT(wait);
395
396                         prepare_to_wait(&sbi->gc_thread->fggc_wq, &wait,
397                                                 TASK_UNINTERRUPTIBLE);
398                         wake_up(&sbi->gc_thread->gc_wait_queue_head);
399                         io_schedule();
400                         finish_wait(&sbi->gc_thread->fggc_wq, &wait);
401                 } else {
402                         struct f2fs_gc_control gc_control = {
403                                 .victim_segno = NULL_SEGNO,
404                                 .init_gc_type = BG_GC,
405                                 .no_bg_gc = true,
406                                 .should_migrate_blocks = false,
407                                 .err_gc_skipped = false,
408                                 .nr_free_secs = 1 };
409                         f2fs_down_write(&sbi->gc_lock);
410                         f2fs_gc(sbi, &gc_control);
411                 }
412         }
413 }
414
415 static inline bool excess_dirty_threshold(struct f2fs_sb_info *sbi)
416 {
417         int factor = f2fs_rwsem_is_locked(&sbi->cp_rwsem) ? 3 : 2;
418         unsigned int dents = get_pages(sbi, F2FS_DIRTY_DENTS);
419         unsigned int qdata = get_pages(sbi, F2FS_DIRTY_QDATA);
420         unsigned int nodes = get_pages(sbi, F2FS_DIRTY_NODES);
421         unsigned int meta = get_pages(sbi, F2FS_DIRTY_META);
422         unsigned int imeta = get_pages(sbi, F2FS_DIRTY_IMETA);
423         unsigned int threshold = sbi->blocks_per_seg * factor *
424                                         DEFAULT_DIRTY_THRESHOLD;
425         unsigned int global_threshold = threshold * 3 / 2;
426
427         if (dents >= threshold || qdata >= threshold ||
428                 nodes >= threshold || meta >= threshold ||
429                 imeta >= threshold)
430                 return true;
431         return dents + qdata + nodes + meta + imeta >  global_threshold;
432 }
433
434 void f2fs_balance_fs_bg(struct f2fs_sb_info *sbi, bool from_bg)
435 {
436         if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
437                 return;
438
439         /* try to shrink extent cache when there is no enough memory */
440         if (!f2fs_available_free_memory(sbi, EXTENT_CACHE))
441                 f2fs_shrink_extent_tree(sbi, EXTENT_CACHE_SHRINK_NUMBER);
442
443         /* check the # of cached NAT entries */
444         if (!f2fs_available_free_memory(sbi, NAT_ENTRIES))
445                 f2fs_try_to_free_nats(sbi, NAT_ENTRY_PER_BLOCK);
446
447         if (!f2fs_available_free_memory(sbi, FREE_NIDS))
448                 f2fs_try_to_free_nids(sbi, MAX_FREE_NIDS);
449         else
450                 f2fs_build_free_nids(sbi, false, false);
451
452         if (excess_dirty_nats(sbi) || excess_dirty_threshold(sbi) ||
453                 excess_prefree_segs(sbi) || !f2fs_space_for_roll_forward(sbi))
454                 goto do_sync;
455
456         /* there is background inflight IO or foreground operation recently */
457         if (is_inflight_io(sbi, REQ_TIME) ||
458                 (!f2fs_time_over(sbi, REQ_TIME) && f2fs_rwsem_is_locked(&sbi->cp_rwsem)))
459                 return;
460
461         /* exceed periodical checkpoint timeout threshold */
462         if (f2fs_time_over(sbi, CP_TIME))
463                 goto do_sync;
464
465         /* checkpoint is the only way to shrink partial cached entries */
466         if (f2fs_available_free_memory(sbi, NAT_ENTRIES) &&
467                 f2fs_available_free_memory(sbi, INO_ENTRIES))
468                 return;
469
470 do_sync:
471         if (test_opt(sbi, DATA_FLUSH) && from_bg) {
472                 struct blk_plug plug;
473
474                 mutex_lock(&sbi->flush_lock);
475
476                 blk_start_plug(&plug);
477                 f2fs_sync_dirty_inodes(sbi, FILE_INODE, false);
478                 blk_finish_plug(&plug);
479
480                 mutex_unlock(&sbi->flush_lock);
481         }
482         f2fs_sync_fs(sbi->sb, 1);
483         stat_inc_bg_cp_count(sbi->stat_info);
484 }
485
486 static int __submit_flush_wait(struct f2fs_sb_info *sbi,
487                                 struct block_device *bdev)
488 {
489         int ret = blkdev_issue_flush(bdev);
490
491         trace_f2fs_issue_flush(bdev, test_opt(sbi, NOBARRIER),
492                                 test_opt(sbi, FLUSH_MERGE), ret);
493         return ret;
494 }
495
496 static int submit_flush_wait(struct f2fs_sb_info *sbi, nid_t ino)
497 {
498         int ret = 0;
499         int i;
500
501         if (!f2fs_is_multi_device(sbi))
502                 return __submit_flush_wait(sbi, sbi->sb->s_bdev);
503
504         for (i = 0; i < sbi->s_ndevs; i++) {
505                 if (!f2fs_is_dirty_device(sbi, ino, i, FLUSH_INO))
506                         continue;
507                 ret = __submit_flush_wait(sbi, FDEV(i).bdev);
508                 if (ret)
509                         break;
510         }
511         return ret;
512 }
513
514 static int issue_flush_thread(void *data)
515 {
516         struct f2fs_sb_info *sbi = data;
517         struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
518         wait_queue_head_t *q = &fcc->flush_wait_queue;
519 repeat:
520         if (kthread_should_stop())
521                 return 0;
522
523         if (!llist_empty(&fcc->issue_list)) {
524                 struct flush_cmd *cmd, *next;
525                 int ret;
526
527                 fcc->dispatch_list = llist_del_all(&fcc->issue_list);
528                 fcc->dispatch_list = llist_reverse_order(fcc->dispatch_list);
529
530                 cmd = llist_entry(fcc->dispatch_list, struct flush_cmd, llnode);
531
532                 ret = submit_flush_wait(sbi, cmd->ino);
533                 atomic_inc(&fcc->issued_flush);
534
535                 llist_for_each_entry_safe(cmd, next,
536                                           fcc->dispatch_list, llnode) {
537                         cmd->ret = ret;
538                         complete(&cmd->wait);
539                 }
540                 fcc->dispatch_list = NULL;
541         }
542
543         wait_event_interruptible(*q,
544                 kthread_should_stop() || !llist_empty(&fcc->issue_list));
545         goto repeat;
546 }
547
548 int f2fs_issue_flush(struct f2fs_sb_info *sbi, nid_t ino)
549 {
550         struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
551         struct flush_cmd cmd;
552         int ret;
553
554         if (test_opt(sbi, NOBARRIER))
555                 return 0;
556
557         if (!test_opt(sbi, FLUSH_MERGE)) {
558                 atomic_inc(&fcc->queued_flush);
559                 ret = submit_flush_wait(sbi, ino);
560                 atomic_dec(&fcc->queued_flush);
561                 atomic_inc(&fcc->issued_flush);
562                 return ret;
563         }
564
565         if (atomic_inc_return(&fcc->queued_flush) == 1 ||
566             f2fs_is_multi_device(sbi)) {
567                 ret = submit_flush_wait(sbi, ino);
568                 atomic_dec(&fcc->queued_flush);
569
570                 atomic_inc(&fcc->issued_flush);
571                 return ret;
572         }
573
574         cmd.ino = ino;
575         init_completion(&cmd.wait);
576
577         llist_add(&cmd.llnode, &fcc->issue_list);
578
579         /*
580          * update issue_list before we wake up issue_flush thread, this
581          * smp_mb() pairs with another barrier in ___wait_event(), see
582          * more details in comments of waitqueue_active().
583          */
584         smp_mb();
585
586         if (waitqueue_active(&fcc->flush_wait_queue))
587                 wake_up(&fcc->flush_wait_queue);
588
589         if (fcc->f2fs_issue_flush) {
590                 wait_for_completion(&cmd.wait);
591                 atomic_dec(&fcc->queued_flush);
592         } else {
593                 struct llist_node *list;
594
595                 list = llist_del_all(&fcc->issue_list);
596                 if (!list) {
597                         wait_for_completion(&cmd.wait);
598                         atomic_dec(&fcc->queued_flush);
599                 } else {
600                         struct flush_cmd *tmp, *next;
601
602                         ret = submit_flush_wait(sbi, ino);
603
604                         llist_for_each_entry_safe(tmp, next, list, llnode) {
605                                 if (tmp == &cmd) {
606                                         cmd.ret = ret;
607                                         atomic_dec(&fcc->queued_flush);
608                                         continue;
609                                 }
610                                 tmp->ret = ret;
611                                 complete(&tmp->wait);
612                         }
613                 }
614         }
615
616         return cmd.ret;
617 }
618
619 int f2fs_create_flush_cmd_control(struct f2fs_sb_info *sbi)
620 {
621         dev_t dev = sbi->sb->s_bdev->bd_dev;
622         struct flush_cmd_control *fcc;
623         int err = 0;
624
625         if (SM_I(sbi)->fcc_info) {
626                 fcc = SM_I(sbi)->fcc_info;
627                 if (fcc->f2fs_issue_flush)
628                         return err;
629                 goto init_thread;
630         }
631
632         fcc = f2fs_kzalloc(sbi, sizeof(struct flush_cmd_control), GFP_KERNEL);
633         if (!fcc)
634                 return -ENOMEM;
635         atomic_set(&fcc->issued_flush, 0);
636         atomic_set(&fcc->queued_flush, 0);
637         init_waitqueue_head(&fcc->flush_wait_queue);
638         init_llist_head(&fcc->issue_list);
639         SM_I(sbi)->fcc_info = fcc;
640         if (!test_opt(sbi, FLUSH_MERGE))
641                 return err;
642
643 init_thread:
644         fcc->f2fs_issue_flush = kthread_run(issue_flush_thread, sbi,
645                                 "f2fs_flush-%u:%u", MAJOR(dev), MINOR(dev));
646         if (IS_ERR(fcc->f2fs_issue_flush)) {
647                 err = PTR_ERR(fcc->f2fs_issue_flush);
648                 kfree(fcc);
649                 SM_I(sbi)->fcc_info = NULL;
650                 return err;
651         }
652
653         return err;
654 }
655
656 void f2fs_destroy_flush_cmd_control(struct f2fs_sb_info *sbi, bool free)
657 {
658         struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
659
660         if (fcc && fcc->f2fs_issue_flush) {
661                 struct task_struct *flush_thread = fcc->f2fs_issue_flush;
662
663                 fcc->f2fs_issue_flush = NULL;
664                 kthread_stop(flush_thread);
665         }
666         if (free) {
667                 kfree(fcc);
668                 SM_I(sbi)->fcc_info = NULL;
669         }
670 }
671
672 int f2fs_flush_device_cache(struct f2fs_sb_info *sbi)
673 {
674         int ret = 0, i;
675
676         if (!f2fs_is_multi_device(sbi))
677                 return 0;
678
679         if (test_opt(sbi, NOBARRIER))
680                 return 0;
681
682         for (i = 1; i < sbi->s_ndevs; i++) {
683                 int count = DEFAULT_RETRY_IO_COUNT;
684
685                 if (!f2fs_test_bit(i, (char *)&sbi->dirty_device))
686                         continue;
687
688                 do {
689                         ret = __submit_flush_wait(sbi, FDEV(i).bdev);
690                         if (ret)
691                                 f2fs_io_schedule_timeout(DEFAULT_IO_TIMEOUT);
692                 } while (ret && --count);
693
694                 if (ret) {
695                         f2fs_stop_checkpoint(sbi, false,
696                                         STOP_CP_REASON_FLUSH_FAIL);
697                         break;
698                 }
699
700                 spin_lock(&sbi->dev_lock);
701                 f2fs_clear_bit(i, (char *)&sbi->dirty_device);
702                 spin_unlock(&sbi->dev_lock);
703         }
704
705         return ret;
706 }
707
708 static void __locate_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno,
709                 enum dirty_type dirty_type)
710 {
711         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
712
713         /* need not be added */
714         if (IS_CURSEG(sbi, segno))
715                 return;
716
717         if (!test_and_set_bit(segno, dirty_i->dirty_segmap[dirty_type]))
718                 dirty_i->nr_dirty[dirty_type]++;
719
720         if (dirty_type == DIRTY) {
721                 struct seg_entry *sentry = get_seg_entry(sbi, segno);
722                 enum dirty_type t = sentry->type;
723
724                 if (unlikely(t >= DIRTY)) {
725                         f2fs_bug_on(sbi, 1);
726                         return;
727                 }
728                 if (!test_and_set_bit(segno, dirty_i->dirty_segmap[t]))
729                         dirty_i->nr_dirty[t]++;
730
731                 if (__is_large_section(sbi)) {
732                         unsigned int secno = GET_SEC_FROM_SEG(sbi, segno);
733                         block_t valid_blocks =
734                                 get_valid_blocks(sbi, segno, true);
735
736                         f2fs_bug_on(sbi, unlikely(!valid_blocks ||
737                                         valid_blocks == CAP_BLKS_PER_SEC(sbi)));
738
739                         if (!IS_CURSEC(sbi, secno))
740                                 set_bit(secno, dirty_i->dirty_secmap);
741                 }
742         }
743 }
744
745 static void __remove_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno,
746                 enum dirty_type dirty_type)
747 {
748         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
749         block_t valid_blocks;
750
751         if (test_and_clear_bit(segno, dirty_i->dirty_segmap[dirty_type]))
752                 dirty_i->nr_dirty[dirty_type]--;
753
754         if (dirty_type == DIRTY) {
755                 struct seg_entry *sentry = get_seg_entry(sbi, segno);
756                 enum dirty_type t = sentry->type;
757
758                 if (test_and_clear_bit(segno, dirty_i->dirty_segmap[t]))
759                         dirty_i->nr_dirty[t]--;
760
761                 valid_blocks = get_valid_blocks(sbi, segno, true);
762                 if (valid_blocks == 0) {
763                         clear_bit(GET_SEC_FROM_SEG(sbi, segno),
764                                                 dirty_i->victim_secmap);
765 #ifdef CONFIG_F2FS_CHECK_FS
766                         clear_bit(segno, SIT_I(sbi)->invalid_segmap);
767 #endif
768                 }
769                 if (__is_large_section(sbi)) {
770                         unsigned int secno = GET_SEC_FROM_SEG(sbi, segno);
771
772                         if (!valid_blocks ||
773                                         valid_blocks == CAP_BLKS_PER_SEC(sbi)) {
774                                 clear_bit(secno, dirty_i->dirty_secmap);
775                                 return;
776                         }
777
778                         if (!IS_CURSEC(sbi, secno))
779                                 set_bit(secno, dirty_i->dirty_secmap);
780                 }
781         }
782 }
783
784 /*
785  * Should not occur error such as -ENOMEM.
786  * Adding dirty entry into seglist is not critical operation.
787  * If a given segment is one of current working segments, it won't be added.
788  */
789 static void locate_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno)
790 {
791         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
792         unsigned short valid_blocks, ckpt_valid_blocks;
793         unsigned int usable_blocks;
794
795         if (segno == NULL_SEGNO || IS_CURSEG(sbi, segno))
796                 return;
797
798         usable_blocks = f2fs_usable_blks_in_seg(sbi, segno);
799         mutex_lock(&dirty_i->seglist_lock);
800
801         valid_blocks = get_valid_blocks(sbi, segno, false);
802         ckpt_valid_blocks = get_ckpt_valid_blocks(sbi, segno, false);
803
804         if (valid_blocks == 0 && (!is_sbi_flag_set(sbi, SBI_CP_DISABLED) ||
805                 ckpt_valid_blocks == usable_blocks)) {
806                 __locate_dirty_segment(sbi, segno, PRE);
807                 __remove_dirty_segment(sbi, segno, DIRTY);
808         } else if (valid_blocks < usable_blocks) {
809                 __locate_dirty_segment(sbi, segno, DIRTY);
810         } else {
811                 /* Recovery routine with SSR needs this */
812                 __remove_dirty_segment(sbi, segno, DIRTY);
813         }
814
815         mutex_unlock(&dirty_i->seglist_lock);
816 }
817
818 /* This moves currently empty dirty blocks to prefree. Must hold seglist_lock */
819 void f2fs_dirty_to_prefree(struct f2fs_sb_info *sbi)
820 {
821         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
822         unsigned int segno;
823
824         mutex_lock(&dirty_i->seglist_lock);
825         for_each_set_bit(segno, dirty_i->dirty_segmap[DIRTY], MAIN_SEGS(sbi)) {
826                 if (get_valid_blocks(sbi, segno, false))
827                         continue;
828                 if (IS_CURSEG(sbi, segno))
829                         continue;
830                 __locate_dirty_segment(sbi, segno, PRE);
831                 __remove_dirty_segment(sbi, segno, DIRTY);
832         }
833         mutex_unlock(&dirty_i->seglist_lock);
834 }
835
836 block_t f2fs_get_unusable_blocks(struct f2fs_sb_info *sbi)
837 {
838         int ovp_hole_segs =
839                 (overprovision_segments(sbi) - reserved_segments(sbi));
840         block_t ovp_holes = ovp_hole_segs << sbi->log_blocks_per_seg;
841         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
842         block_t holes[2] = {0, 0};      /* DATA and NODE */
843         block_t unusable;
844         struct seg_entry *se;
845         unsigned int segno;
846
847         mutex_lock(&dirty_i->seglist_lock);
848         for_each_set_bit(segno, dirty_i->dirty_segmap[DIRTY], MAIN_SEGS(sbi)) {
849                 se = get_seg_entry(sbi, segno);
850                 if (IS_NODESEG(se->type))
851                         holes[NODE] += f2fs_usable_blks_in_seg(sbi, segno) -
852                                                         se->valid_blocks;
853                 else
854                         holes[DATA] += f2fs_usable_blks_in_seg(sbi, segno) -
855                                                         se->valid_blocks;
856         }
857         mutex_unlock(&dirty_i->seglist_lock);
858
859         unusable = holes[DATA] > holes[NODE] ? holes[DATA] : holes[NODE];
860         if (unusable > ovp_holes)
861                 return unusable - ovp_holes;
862         return 0;
863 }
864
865 int f2fs_disable_cp_again(struct f2fs_sb_info *sbi, block_t unusable)
866 {
867         int ovp_hole_segs =
868                 (overprovision_segments(sbi) - reserved_segments(sbi));
869         if (unusable > F2FS_OPTION(sbi).unusable_cap)
870                 return -EAGAIN;
871         if (is_sbi_flag_set(sbi, SBI_CP_DISABLED_QUICK) &&
872                 dirty_segments(sbi) > ovp_hole_segs)
873                 return -EAGAIN;
874         return 0;
875 }
876
877 /* This is only used by SBI_CP_DISABLED */
878 static unsigned int get_free_segment(struct f2fs_sb_info *sbi)
879 {
880         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
881         unsigned int segno = 0;
882
883         mutex_lock(&dirty_i->seglist_lock);
884         for_each_set_bit(segno, dirty_i->dirty_segmap[DIRTY], MAIN_SEGS(sbi)) {
885                 if (get_valid_blocks(sbi, segno, false))
886                         continue;
887                 if (get_ckpt_valid_blocks(sbi, segno, false))
888                         continue;
889                 mutex_unlock(&dirty_i->seglist_lock);
890                 return segno;
891         }
892         mutex_unlock(&dirty_i->seglist_lock);
893         return NULL_SEGNO;
894 }
895
896 static struct discard_cmd *__create_discard_cmd(struct f2fs_sb_info *sbi,
897                 struct block_device *bdev, block_t lstart,
898                 block_t start, block_t len)
899 {
900         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
901         struct list_head *pend_list;
902         struct discard_cmd *dc;
903
904         f2fs_bug_on(sbi, !len);
905
906         pend_list = &dcc->pend_list[plist_idx(len)];
907
908         dc = f2fs_kmem_cache_alloc(discard_cmd_slab, GFP_NOFS, true, NULL);
909         INIT_LIST_HEAD(&dc->list);
910         dc->bdev = bdev;
911         dc->lstart = lstart;
912         dc->start = start;
913         dc->len = len;
914         dc->ref = 0;
915         dc->state = D_PREP;
916         dc->queued = 0;
917         dc->error = 0;
918         init_completion(&dc->wait);
919         list_add_tail(&dc->list, pend_list);
920         spin_lock_init(&dc->lock);
921         dc->bio_ref = 0;
922         atomic_inc(&dcc->discard_cmd_cnt);
923         dcc->undiscard_blks += len;
924
925         return dc;
926 }
927
928 static struct discard_cmd *__attach_discard_cmd(struct f2fs_sb_info *sbi,
929                                 struct block_device *bdev, block_t lstart,
930                                 block_t start, block_t len,
931                                 struct rb_node *parent, struct rb_node **p,
932                                 bool leftmost)
933 {
934         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
935         struct discard_cmd *dc;
936
937         dc = __create_discard_cmd(sbi, bdev, lstart, start, len);
938
939         rb_link_node(&dc->rb_node, parent, p);
940         rb_insert_color_cached(&dc->rb_node, &dcc->root, leftmost);
941
942         return dc;
943 }
944
945 static void __detach_discard_cmd(struct discard_cmd_control *dcc,
946                                                         struct discard_cmd *dc)
947 {
948         if (dc->state == D_DONE)
949                 atomic_sub(dc->queued, &dcc->queued_discard);
950
951         list_del(&dc->list);
952         rb_erase_cached(&dc->rb_node, &dcc->root);
953         dcc->undiscard_blks -= dc->len;
954
955         kmem_cache_free(discard_cmd_slab, dc);
956
957         atomic_dec(&dcc->discard_cmd_cnt);
958 }
959
960 static void __remove_discard_cmd(struct f2fs_sb_info *sbi,
961                                                         struct discard_cmd *dc)
962 {
963         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
964         unsigned long flags;
965
966         trace_f2fs_remove_discard(dc->bdev, dc->start, dc->len);
967
968         spin_lock_irqsave(&dc->lock, flags);
969         if (dc->bio_ref) {
970                 spin_unlock_irqrestore(&dc->lock, flags);
971                 return;
972         }
973         spin_unlock_irqrestore(&dc->lock, flags);
974
975         f2fs_bug_on(sbi, dc->ref);
976
977         if (dc->error == -EOPNOTSUPP)
978                 dc->error = 0;
979
980         if (dc->error)
981                 printk_ratelimited(
982                         "%sF2FS-fs (%s): Issue discard(%u, %u, %u) failed, ret: %d",
983                         KERN_INFO, sbi->sb->s_id,
984                         dc->lstart, dc->start, dc->len, dc->error);
985         __detach_discard_cmd(dcc, dc);
986 }
987
988 static void f2fs_submit_discard_endio(struct bio *bio)
989 {
990         struct discard_cmd *dc = (struct discard_cmd *)bio->bi_private;
991         unsigned long flags;
992
993         spin_lock_irqsave(&dc->lock, flags);
994         if (!dc->error)
995                 dc->error = blk_status_to_errno(bio->bi_status);
996         dc->bio_ref--;
997         if (!dc->bio_ref && dc->state == D_SUBMIT) {
998                 dc->state = D_DONE;
999                 complete_all(&dc->wait);
1000         }
1001         spin_unlock_irqrestore(&dc->lock, flags);
1002         bio_put(bio);
1003 }
1004
1005 static void __check_sit_bitmap(struct f2fs_sb_info *sbi,
1006                                 block_t start, block_t end)
1007 {
1008 #ifdef CONFIG_F2FS_CHECK_FS
1009         struct seg_entry *sentry;
1010         unsigned int segno;
1011         block_t blk = start;
1012         unsigned long offset, size, max_blocks = sbi->blocks_per_seg;
1013         unsigned long *map;
1014
1015         while (blk < end) {
1016                 segno = GET_SEGNO(sbi, blk);
1017                 sentry = get_seg_entry(sbi, segno);
1018                 offset = GET_BLKOFF_FROM_SEG0(sbi, blk);
1019
1020                 if (end < START_BLOCK(sbi, segno + 1))
1021                         size = GET_BLKOFF_FROM_SEG0(sbi, end);
1022                 else
1023                         size = max_blocks;
1024                 map = (unsigned long *)(sentry->cur_valid_map);
1025                 offset = __find_rev_next_bit(map, size, offset);
1026                 f2fs_bug_on(sbi, offset != size);
1027                 blk = START_BLOCK(sbi, segno + 1);
1028         }
1029 #endif
1030 }
1031
1032 static void __init_discard_policy(struct f2fs_sb_info *sbi,
1033                                 struct discard_policy *dpolicy,
1034                                 int discard_type, unsigned int granularity)
1035 {
1036         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1037
1038         /* common policy */
1039         dpolicy->type = discard_type;
1040         dpolicy->sync = true;
1041         dpolicy->ordered = false;
1042         dpolicy->granularity = granularity;
1043
1044         dpolicy->max_requests = dcc->max_discard_request;
1045         dpolicy->io_aware_gran = MAX_PLIST_NUM;
1046         dpolicy->timeout = false;
1047
1048         if (discard_type == DPOLICY_BG) {
1049                 dpolicy->min_interval = dcc->min_discard_issue_time;
1050                 dpolicy->mid_interval = dcc->mid_discard_issue_time;
1051                 dpolicy->max_interval = dcc->max_discard_issue_time;
1052                 dpolicy->io_aware = true;
1053                 dpolicy->sync = false;
1054                 dpolicy->ordered = true;
1055                 if (utilization(sbi) > DEF_DISCARD_URGENT_UTIL) {
1056                         dpolicy->granularity = 1;
1057                         if (atomic_read(&dcc->discard_cmd_cnt))
1058                                 dpolicy->max_interval =
1059                                         dcc->min_discard_issue_time;
1060                 }
1061         } else if (discard_type == DPOLICY_FORCE) {
1062                 dpolicy->min_interval = dcc->min_discard_issue_time;
1063                 dpolicy->mid_interval = dcc->mid_discard_issue_time;
1064                 dpolicy->max_interval = dcc->max_discard_issue_time;
1065                 dpolicy->io_aware = false;
1066         } else if (discard_type == DPOLICY_FSTRIM) {
1067                 dpolicy->io_aware = false;
1068         } else if (discard_type == DPOLICY_UMOUNT) {
1069                 dpolicy->io_aware = false;
1070                 /* we need to issue all to keep CP_TRIMMED_FLAG */
1071                 dpolicy->granularity = 1;
1072                 dpolicy->timeout = true;
1073         }
1074 }
1075
1076 static void __update_discard_tree_range(struct f2fs_sb_info *sbi,
1077                                 struct block_device *bdev, block_t lstart,
1078                                 block_t start, block_t len);
1079 /* this function is copied from blkdev_issue_discard from block/blk-lib.c */
1080 static int __submit_discard_cmd(struct f2fs_sb_info *sbi,
1081                                                 struct discard_policy *dpolicy,
1082                                                 struct discard_cmd *dc,
1083                                                 unsigned int *issued)
1084 {
1085         struct block_device *bdev = dc->bdev;
1086         unsigned int max_discard_blocks =
1087                         SECTOR_TO_BLOCK(bdev_max_discard_sectors(bdev));
1088         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1089         struct list_head *wait_list = (dpolicy->type == DPOLICY_FSTRIM) ?
1090                                         &(dcc->fstrim_list) : &(dcc->wait_list);
1091         blk_opf_t flag = dpolicy->sync ? REQ_SYNC : 0;
1092         block_t lstart, start, len, total_len;
1093         int err = 0;
1094
1095         if (dc->state != D_PREP)
1096                 return 0;
1097
1098         if (is_sbi_flag_set(sbi, SBI_NEED_FSCK))
1099                 return 0;
1100
1101         trace_f2fs_issue_discard(bdev, dc->start, dc->len);
1102
1103         lstart = dc->lstart;
1104         start = dc->start;
1105         len = dc->len;
1106         total_len = len;
1107
1108         dc->len = 0;
1109
1110         while (total_len && *issued < dpolicy->max_requests && !err) {
1111                 struct bio *bio = NULL;
1112                 unsigned long flags;
1113                 bool last = true;
1114
1115                 if (len > max_discard_blocks) {
1116                         len = max_discard_blocks;
1117                         last = false;
1118                 }
1119
1120                 (*issued)++;
1121                 if (*issued == dpolicy->max_requests)
1122                         last = true;
1123
1124                 dc->len += len;
1125
1126                 if (time_to_inject(sbi, FAULT_DISCARD)) {
1127                         f2fs_show_injection_info(sbi, FAULT_DISCARD);
1128                         err = -EIO;
1129                         goto submit;
1130                 }
1131                 err = __blkdev_issue_discard(bdev,
1132                                         SECTOR_FROM_BLOCK(start),
1133                                         SECTOR_FROM_BLOCK(len),
1134                                         GFP_NOFS, &bio);
1135 submit:
1136                 if (err) {
1137                         spin_lock_irqsave(&dc->lock, flags);
1138                         if (dc->state == D_PARTIAL)
1139                                 dc->state = D_SUBMIT;
1140                         spin_unlock_irqrestore(&dc->lock, flags);
1141
1142                         break;
1143                 }
1144
1145                 f2fs_bug_on(sbi, !bio);
1146
1147                 /*
1148                  * should keep before submission to avoid D_DONE
1149                  * right away
1150                  */
1151                 spin_lock_irqsave(&dc->lock, flags);
1152                 if (last)
1153                         dc->state = D_SUBMIT;
1154                 else
1155                         dc->state = D_PARTIAL;
1156                 dc->bio_ref++;
1157                 spin_unlock_irqrestore(&dc->lock, flags);
1158
1159                 atomic_inc(&dcc->queued_discard);
1160                 dc->queued++;
1161                 list_move_tail(&dc->list, wait_list);
1162
1163                 /* sanity check on discard range */
1164                 __check_sit_bitmap(sbi, lstart, lstart + len);
1165
1166                 bio->bi_private = dc;
1167                 bio->bi_end_io = f2fs_submit_discard_endio;
1168                 bio->bi_opf |= flag;
1169                 submit_bio(bio);
1170
1171                 atomic_inc(&dcc->issued_discard);
1172
1173                 f2fs_update_iostat(sbi, NULL, FS_DISCARD, 1);
1174
1175                 lstart += len;
1176                 start += len;
1177                 total_len -= len;
1178                 len = total_len;
1179         }
1180
1181         if (!err && len) {
1182                 dcc->undiscard_blks -= len;
1183                 __update_discard_tree_range(sbi, bdev, lstart, start, len);
1184         }
1185         return err;
1186 }
1187
1188 static void __insert_discard_tree(struct f2fs_sb_info *sbi,
1189                                 struct block_device *bdev, block_t lstart,
1190                                 block_t start, block_t len,
1191                                 struct rb_node **insert_p,
1192                                 struct rb_node *insert_parent)
1193 {
1194         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1195         struct rb_node **p;
1196         struct rb_node *parent = NULL;
1197         bool leftmost = true;
1198
1199         if (insert_p && insert_parent) {
1200                 parent = insert_parent;
1201                 p = insert_p;
1202                 goto do_insert;
1203         }
1204
1205         p = f2fs_lookup_rb_tree_for_insert(sbi, &dcc->root, &parent,
1206                                                         lstart, &leftmost);
1207 do_insert:
1208         __attach_discard_cmd(sbi, bdev, lstart, start, len, parent,
1209                                                                 p, leftmost);
1210 }
1211
1212 static void __relocate_discard_cmd(struct discard_cmd_control *dcc,
1213                                                 struct discard_cmd *dc)
1214 {
1215         list_move_tail(&dc->list, &dcc->pend_list[plist_idx(dc->len)]);
1216 }
1217
1218 static void __punch_discard_cmd(struct f2fs_sb_info *sbi,
1219                                 struct discard_cmd *dc, block_t blkaddr)
1220 {
1221         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1222         struct discard_info di = dc->di;
1223         bool modified = false;
1224
1225         if (dc->state == D_DONE || dc->len == 1) {
1226                 __remove_discard_cmd(sbi, dc);
1227                 return;
1228         }
1229
1230         dcc->undiscard_blks -= di.len;
1231
1232         if (blkaddr > di.lstart) {
1233                 dc->len = blkaddr - dc->lstart;
1234                 dcc->undiscard_blks += dc->len;
1235                 __relocate_discard_cmd(dcc, dc);
1236                 modified = true;
1237         }
1238
1239         if (blkaddr < di.lstart + di.len - 1) {
1240                 if (modified) {
1241                         __insert_discard_tree(sbi, dc->bdev, blkaddr + 1,
1242                                         di.start + blkaddr + 1 - di.lstart,
1243                                         di.lstart + di.len - 1 - blkaddr,
1244                                         NULL, NULL);
1245                 } else {
1246                         dc->lstart++;
1247                         dc->len--;
1248                         dc->start++;
1249                         dcc->undiscard_blks += dc->len;
1250                         __relocate_discard_cmd(dcc, dc);
1251                 }
1252         }
1253 }
1254
1255 static void __update_discard_tree_range(struct f2fs_sb_info *sbi,
1256                                 struct block_device *bdev, block_t lstart,
1257                                 block_t start, block_t len)
1258 {
1259         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1260         struct discard_cmd *prev_dc = NULL, *next_dc = NULL;
1261         struct discard_cmd *dc;
1262         struct discard_info di = {0};
1263         struct rb_node **insert_p = NULL, *insert_parent = NULL;
1264         unsigned int max_discard_blocks =
1265                         SECTOR_TO_BLOCK(bdev_max_discard_sectors(bdev));
1266         block_t end = lstart + len;
1267
1268         dc = (struct discard_cmd *)f2fs_lookup_rb_tree_ret(&dcc->root,
1269                                         NULL, lstart,
1270                                         (struct rb_entry **)&prev_dc,
1271                                         (struct rb_entry **)&next_dc,
1272                                         &insert_p, &insert_parent, true, NULL);
1273         if (dc)
1274                 prev_dc = dc;
1275
1276         if (!prev_dc) {
1277                 di.lstart = lstart;
1278                 di.len = next_dc ? next_dc->lstart - lstart : len;
1279                 di.len = min(di.len, len);
1280                 di.start = start;
1281         }
1282
1283         while (1) {
1284                 struct rb_node *node;
1285                 bool merged = false;
1286                 struct discard_cmd *tdc = NULL;
1287
1288                 if (prev_dc) {
1289                         di.lstart = prev_dc->lstart + prev_dc->len;
1290                         if (di.lstart < lstart)
1291                                 di.lstart = lstart;
1292                         if (di.lstart >= end)
1293                                 break;
1294
1295                         if (!next_dc || next_dc->lstart > end)
1296                                 di.len = end - di.lstart;
1297                         else
1298                                 di.len = next_dc->lstart - di.lstart;
1299                         di.start = start + di.lstart - lstart;
1300                 }
1301
1302                 if (!di.len)
1303                         goto next;
1304
1305                 if (prev_dc && prev_dc->state == D_PREP &&
1306                         prev_dc->bdev == bdev &&
1307                         __is_discard_back_mergeable(&di, &prev_dc->di,
1308                                                         max_discard_blocks)) {
1309                         prev_dc->di.len += di.len;
1310                         dcc->undiscard_blks += di.len;
1311                         __relocate_discard_cmd(dcc, prev_dc);
1312                         di = prev_dc->di;
1313                         tdc = prev_dc;
1314                         merged = true;
1315                 }
1316
1317                 if (next_dc && next_dc->state == D_PREP &&
1318                         next_dc->bdev == bdev &&
1319                         __is_discard_front_mergeable(&di, &next_dc->di,
1320                                                         max_discard_blocks)) {
1321                         next_dc->di.lstart = di.lstart;
1322                         next_dc->di.len += di.len;
1323                         next_dc->di.start = di.start;
1324                         dcc->undiscard_blks += di.len;
1325                         __relocate_discard_cmd(dcc, next_dc);
1326                         if (tdc)
1327                                 __remove_discard_cmd(sbi, tdc);
1328                         merged = true;
1329                 }
1330
1331                 if (!merged) {
1332                         __insert_discard_tree(sbi, bdev, di.lstart, di.start,
1333                                                         di.len, NULL, NULL);
1334                 }
1335  next:
1336                 prev_dc = next_dc;
1337                 if (!prev_dc)
1338                         break;
1339
1340                 node = rb_next(&prev_dc->rb_node);
1341                 next_dc = rb_entry_safe(node, struct discard_cmd, rb_node);
1342         }
1343 }
1344
1345 static int __queue_discard_cmd(struct f2fs_sb_info *sbi,
1346                 struct block_device *bdev, block_t blkstart, block_t blklen)
1347 {
1348         block_t lblkstart = blkstart;
1349
1350         if (!f2fs_bdev_support_discard(bdev))
1351                 return 0;
1352
1353         trace_f2fs_queue_discard(bdev, blkstart, blklen);
1354
1355         if (f2fs_is_multi_device(sbi)) {
1356                 int devi = f2fs_target_device_index(sbi, blkstart);
1357
1358                 blkstart -= FDEV(devi).start_blk;
1359         }
1360         mutex_lock(&SM_I(sbi)->dcc_info->cmd_lock);
1361         __update_discard_tree_range(sbi, bdev, lblkstart, blkstart, blklen);
1362         mutex_unlock(&SM_I(sbi)->dcc_info->cmd_lock);
1363         return 0;
1364 }
1365
1366 static unsigned int __issue_discard_cmd_orderly(struct f2fs_sb_info *sbi,
1367                                         struct discard_policy *dpolicy)
1368 {
1369         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1370         struct discard_cmd *prev_dc = NULL, *next_dc = NULL;
1371         struct rb_node **insert_p = NULL, *insert_parent = NULL;
1372         struct discard_cmd *dc;
1373         struct blk_plug plug;
1374         unsigned int pos = dcc->next_pos;
1375         unsigned int issued = 0;
1376         bool io_interrupted = false;
1377
1378         mutex_lock(&dcc->cmd_lock);
1379         dc = (struct discard_cmd *)f2fs_lookup_rb_tree_ret(&dcc->root,
1380                                         NULL, pos,
1381                                         (struct rb_entry **)&prev_dc,
1382                                         (struct rb_entry **)&next_dc,
1383                                         &insert_p, &insert_parent, true, NULL);
1384         if (!dc)
1385                 dc = next_dc;
1386
1387         blk_start_plug(&plug);
1388
1389         while (dc) {
1390                 struct rb_node *node;
1391                 int err = 0;
1392
1393                 if (dc->state != D_PREP)
1394                         goto next;
1395
1396                 if (dpolicy->io_aware && !is_idle(sbi, DISCARD_TIME)) {
1397                         io_interrupted = true;
1398                         break;
1399                 }
1400
1401                 dcc->next_pos = dc->lstart + dc->len;
1402                 err = __submit_discard_cmd(sbi, dpolicy, dc, &issued);
1403
1404                 if (issued >= dpolicy->max_requests)
1405                         break;
1406 next:
1407                 node = rb_next(&dc->rb_node);
1408                 if (err)
1409                         __remove_discard_cmd(sbi, dc);
1410                 dc = rb_entry_safe(node, struct discard_cmd, rb_node);
1411         }
1412
1413         blk_finish_plug(&plug);
1414
1415         if (!dc)
1416                 dcc->next_pos = 0;
1417
1418         mutex_unlock(&dcc->cmd_lock);
1419
1420         if (!issued && io_interrupted)
1421                 issued = -1;
1422
1423         return issued;
1424 }
1425 static unsigned int __wait_all_discard_cmd(struct f2fs_sb_info *sbi,
1426                                         struct discard_policy *dpolicy);
1427
1428 static int __issue_discard_cmd(struct f2fs_sb_info *sbi,
1429                                         struct discard_policy *dpolicy)
1430 {
1431         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1432         struct list_head *pend_list;
1433         struct discard_cmd *dc, *tmp;
1434         struct blk_plug plug;
1435         int i, issued;
1436         bool io_interrupted = false;
1437
1438         if (dpolicy->timeout)
1439                 f2fs_update_time(sbi, UMOUNT_DISCARD_TIMEOUT);
1440
1441 retry:
1442         issued = 0;
1443         for (i = MAX_PLIST_NUM - 1; i >= 0; i--) {
1444                 if (dpolicy->timeout &&
1445                                 f2fs_time_over(sbi, UMOUNT_DISCARD_TIMEOUT))
1446                         break;
1447
1448                 if (i + 1 < dpolicy->granularity)
1449                         break;
1450
1451                 if (i < DEFAULT_DISCARD_GRANULARITY && dpolicy->ordered)
1452                         return __issue_discard_cmd_orderly(sbi, dpolicy);
1453
1454                 pend_list = &dcc->pend_list[i];
1455
1456                 mutex_lock(&dcc->cmd_lock);
1457                 if (list_empty(pend_list))
1458                         goto next;
1459                 if (unlikely(dcc->rbtree_check))
1460                         f2fs_bug_on(sbi, !f2fs_check_rb_tree_consistence(sbi,
1461                                                         &dcc->root, false));
1462                 blk_start_plug(&plug);
1463                 list_for_each_entry_safe(dc, tmp, pend_list, list) {
1464                         f2fs_bug_on(sbi, dc->state != D_PREP);
1465
1466                         if (dpolicy->timeout &&
1467                                 f2fs_time_over(sbi, UMOUNT_DISCARD_TIMEOUT))
1468                                 break;
1469
1470                         if (dpolicy->io_aware && i < dpolicy->io_aware_gran &&
1471                                                 !is_idle(sbi, DISCARD_TIME)) {
1472                                 io_interrupted = true;
1473                                 break;
1474                         }
1475
1476                         __submit_discard_cmd(sbi, dpolicy, dc, &issued);
1477
1478                         if (issued >= dpolicy->max_requests)
1479                                 break;
1480                 }
1481                 blk_finish_plug(&plug);
1482 next:
1483                 mutex_unlock(&dcc->cmd_lock);
1484
1485                 if (issued >= dpolicy->max_requests || io_interrupted)
1486                         break;
1487         }
1488
1489         if (dpolicy->type == DPOLICY_UMOUNT && issued) {
1490                 __wait_all_discard_cmd(sbi, dpolicy);
1491                 goto retry;
1492         }
1493
1494         if (!issued && io_interrupted)
1495                 issued = -1;
1496
1497         return issued;
1498 }
1499
1500 static bool __drop_discard_cmd(struct f2fs_sb_info *sbi)
1501 {
1502         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1503         struct list_head *pend_list;
1504         struct discard_cmd *dc, *tmp;
1505         int i;
1506         bool dropped = false;
1507
1508         mutex_lock(&dcc->cmd_lock);
1509         for (i = MAX_PLIST_NUM - 1; i >= 0; i--) {
1510                 pend_list = &dcc->pend_list[i];
1511                 list_for_each_entry_safe(dc, tmp, pend_list, list) {
1512                         f2fs_bug_on(sbi, dc->state != D_PREP);
1513                         __remove_discard_cmd(sbi, dc);
1514                         dropped = true;
1515                 }
1516         }
1517         mutex_unlock(&dcc->cmd_lock);
1518
1519         return dropped;
1520 }
1521
1522 void f2fs_drop_discard_cmd(struct f2fs_sb_info *sbi)
1523 {
1524         __drop_discard_cmd(sbi);
1525 }
1526
1527 static unsigned int __wait_one_discard_bio(struct f2fs_sb_info *sbi,
1528                                                         struct discard_cmd *dc)
1529 {
1530         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1531         unsigned int len = 0;
1532
1533         wait_for_completion_io(&dc->wait);
1534         mutex_lock(&dcc->cmd_lock);
1535         f2fs_bug_on(sbi, dc->state != D_DONE);
1536         dc->ref--;
1537         if (!dc->ref) {
1538                 if (!dc->error)
1539                         len = dc->len;
1540                 __remove_discard_cmd(sbi, dc);
1541         }
1542         mutex_unlock(&dcc->cmd_lock);
1543
1544         return len;
1545 }
1546
1547 static unsigned int __wait_discard_cmd_range(struct f2fs_sb_info *sbi,
1548                                                 struct discard_policy *dpolicy,
1549                                                 block_t start, block_t end)
1550 {
1551         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1552         struct list_head *wait_list = (dpolicy->type == DPOLICY_FSTRIM) ?
1553                                         &(dcc->fstrim_list) : &(dcc->wait_list);
1554         struct discard_cmd *dc = NULL, *iter, *tmp;
1555         unsigned int trimmed = 0;
1556
1557 next:
1558         dc = NULL;
1559
1560         mutex_lock(&dcc->cmd_lock);
1561         list_for_each_entry_safe(iter, tmp, wait_list, list) {
1562                 if (iter->lstart + iter->len <= start || end <= iter->lstart)
1563                         continue;
1564                 if (iter->len < dpolicy->granularity)
1565                         continue;
1566                 if (iter->state == D_DONE && !iter->ref) {
1567                         wait_for_completion_io(&iter->wait);
1568                         if (!iter->error)
1569                                 trimmed += iter->len;
1570                         __remove_discard_cmd(sbi, iter);
1571                 } else {
1572                         iter->ref++;
1573                         dc = iter;
1574                         break;
1575                 }
1576         }
1577         mutex_unlock(&dcc->cmd_lock);
1578
1579         if (dc) {
1580                 trimmed += __wait_one_discard_bio(sbi, dc);
1581                 goto next;
1582         }
1583
1584         return trimmed;
1585 }
1586
1587 static unsigned int __wait_all_discard_cmd(struct f2fs_sb_info *sbi,
1588                                                 struct discard_policy *dpolicy)
1589 {
1590         struct discard_policy dp;
1591         unsigned int discard_blks;
1592
1593         if (dpolicy)
1594                 return __wait_discard_cmd_range(sbi, dpolicy, 0, UINT_MAX);
1595
1596         /* wait all */
1597         __init_discard_policy(sbi, &dp, DPOLICY_FSTRIM, 1);
1598         discard_blks = __wait_discard_cmd_range(sbi, &dp, 0, UINT_MAX);
1599         __init_discard_policy(sbi, &dp, DPOLICY_UMOUNT, 1);
1600         discard_blks += __wait_discard_cmd_range(sbi, &dp, 0, UINT_MAX);
1601
1602         return discard_blks;
1603 }
1604
1605 /* This should be covered by global mutex, &sit_i->sentry_lock */
1606 static void f2fs_wait_discard_bio(struct f2fs_sb_info *sbi, block_t blkaddr)
1607 {
1608         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1609         struct discard_cmd *dc;
1610         bool need_wait = false;
1611
1612         mutex_lock(&dcc->cmd_lock);
1613         dc = (struct discard_cmd *)f2fs_lookup_rb_tree(&dcc->root,
1614                                                         NULL, blkaddr);
1615         if (dc) {
1616                 if (dc->state == D_PREP) {
1617                         __punch_discard_cmd(sbi, dc, blkaddr);
1618                 } else {
1619                         dc->ref++;
1620                         need_wait = true;
1621                 }
1622         }
1623         mutex_unlock(&dcc->cmd_lock);
1624
1625         if (need_wait)
1626                 __wait_one_discard_bio(sbi, dc);
1627 }
1628
1629 void f2fs_stop_discard_thread(struct f2fs_sb_info *sbi)
1630 {
1631         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1632
1633         if (dcc && dcc->f2fs_issue_discard) {
1634                 struct task_struct *discard_thread = dcc->f2fs_issue_discard;
1635
1636                 dcc->f2fs_issue_discard = NULL;
1637                 kthread_stop(discard_thread);
1638         }
1639 }
1640
1641 /* This comes from f2fs_put_super */
1642 bool f2fs_issue_discard_timeout(struct f2fs_sb_info *sbi)
1643 {
1644         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1645         struct discard_policy dpolicy;
1646         bool dropped;
1647
1648         __init_discard_policy(sbi, &dpolicy, DPOLICY_UMOUNT,
1649                                         dcc->discard_granularity);
1650         __issue_discard_cmd(sbi, &dpolicy);
1651         dropped = __drop_discard_cmd(sbi);
1652
1653         /* just to make sure there is no pending discard commands */
1654         __wait_all_discard_cmd(sbi, NULL);
1655
1656         f2fs_bug_on(sbi, atomic_read(&dcc->discard_cmd_cnt));
1657         return dropped;
1658 }
1659
1660 static int issue_discard_thread(void *data)
1661 {
1662         struct f2fs_sb_info *sbi = data;
1663         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1664         wait_queue_head_t *q = &dcc->discard_wait_queue;
1665         struct discard_policy dpolicy;
1666         unsigned int wait_ms = dcc->min_discard_issue_time;
1667         int issued;
1668
1669         set_freezable();
1670
1671         do {
1672                 if (sbi->gc_mode == GC_URGENT_HIGH ||
1673                         !f2fs_available_free_memory(sbi, DISCARD_CACHE))
1674                         __init_discard_policy(sbi, &dpolicy, DPOLICY_FORCE, 1);
1675                 else
1676                         __init_discard_policy(sbi, &dpolicy, DPOLICY_BG,
1677                                                 dcc->discard_granularity);
1678
1679                 if (!atomic_read(&dcc->discard_cmd_cnt))
1680                        wait_ms = dpolicy.max_interval;
1681
1682                 wait_event_interruptible_timeout(*q,
1683                                 kthread_should_stop() || freezing(current) ||
1684                                 dcc->discard_wake,
1685                                 msecs_to_jiffies(wait_ms));
1686
1687                 if (dcc->discard_wake)
1688                         dcc->discard_wake = 0;
1689
1690                 /* clean up pending candidates before going to sleep */
1691                 if (atomic_read(&dcc->queued_discard))
1692                         __wait_all_discard_cmd(sbi, NULL);
1693
1694                 if (try_to_freeze())
1695                         continue;
1696                 if (f2fs_readonly(sbi->sb))
1697                         continue;
1698                 if (kthread_should_stop())
1699                         return 0;
1700                 if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) {
1701                         wait_ms = dpolicy.max_interval;
1702                         continue;
1703                 }
1704                 if (!atomic_read(&dcc->discard_cmd_cnt))
1705                         continue;
1706
1707                 sb_start_intwrite(sbi->sb);
1708
1709                 issued = __issue_discard_cmd(sbi, &dpolicy);
1710                 if (issued > 0) {
1711                         __wait_all_discard_cmd(sbi, &dpolicy);
1712                         wait_ms = dpolicy.min_interval;
1713                 } else if (issued == -1) {
1714                         wait_ms = f2fs_time_to_wait(sbi, DISCARD_TIME);
1715                         if (!wait_ms)
1716                                 wait_ms = dpolicy.mid_interval;
1717                 } else {
1718                         wait_ms = dpolicy.max_interval;
1719                 }
1720
1721                 sb_end_intwrite(sbi->sb);
1722
1723         } while (!kthread_should_stop());
1724         return 0;
1725 }
1726
1727 #ifdef CONFIG_BLK_DEV_ZONED
1728 static int __f2fs_issue_discard_zone(struct f2fs_sb_info *sbi,
1729                 struct block_device *bdev, block_t blkstart, block_t blklen)
1730 {
1731         sector_t sector, nr_sects;
1732         block_t lblkstart = blkstart;
1733         int devi = 0;
1734
1735         if (f2fs_is_multi_device(sbi)) {
1736                 devi = f2fs_target_device_index(sbi, blkstart);
1737                 if (blkstart < FDEV(devi).start_blk ||
1738                     blkstart > FDEV(devi).end_blk) {
1739                         f2fs_err(sbi, "Invalid block %x", blkstart);
1740                         return -EIO;
1741                 }
1742                 blkstart -= FDEV(devi).start_blk;
1743         }
1744
1745         /* For sequential zones, reset the zone write pointer */
1746         if (f2fs_blkz_is_seq(sbi, devi, blkstart)) {
1747                 sector = SECTOR_FROM_BLOCK(blkstart);
1748                 nr_sects = SECTOR_FROM_BLOCK(blklen);
1749
1750                 if (sector & (bdev_zone_sectors(bdev) - 1) ||
1751                                 nr_sects != bdev_zone_sectors(bdev)) {
1752                         f2fs_err(sbi, "(%d) %s: Unaligned zone reset attempted (block %x + %x)",
1753                                  devi, sbi->s_ndevs ? FDEV(devi).path : "",
1754                                  blkstart, blklen);
1755                         return -EIO;
1756                 }
1757                 trace_f2fs_issue_reset_zone(bdev, blkstart);
1758                 return blkdev_zone_mgmt(bdev, REQ_OP_ZONE_RESET,
1759                                         sector, nr_sects, GFP_NOFS);
1760         }
1761
1762         /* For conventional zones, use regular discard if supported */
1763         return __queue_discard_cmd(sbi, bdev, lblkstart, blklen);
1764 }
1765 #endif
1766
1767 static int __issue_discard_async(struct f2fs_sb_info *sbi,
1768                 struct block_device *bdev, block_t blkstart, block_t blklen)
1769 {
1770 #ifdef CONFIG_BLK_DEV_ZONED
1771         if (f2fs_sb_has_blkzoned(sbi) && bdev_is_zoned(bdev))
1772                 return __f2fs_issue_discard_zone(sbi, bdev, blkstart, blklen);
1773 #endif
1774         return __queue_discard_cmd(sbi, bdev, blkstart, blklen);
1775 }
1776
1777 static int f2fs_issue_discard(struct f2fs_sb_info *sbi,
1778                                 block_t blkstart, block_t blklen)
1779 {
1780         sector_t start = blkstart, len = 0;
1781         struct block_device *bdev;
1782         struct seg_entry *se;
1783         unsigned int offset;
1784         block_t i;
1785         int err = 0;
1786
1787         bdev = f2fs_target_device(sbi, blkstart, NULL);
1788
1789         for (i = blkstart; i < blkstart + blklen; i++, len++) {
1790                 if (i != start) {
1791                         struct block_device *bdev2 =
1792                                 f2fs_target_device(sbi, i, NULL);
1793
1794                         if (bdev2 != bdev) {
1795                                 err = __issue_discard_async(sbi, bdev,
1796                                                 start, len);
1797                                 if (err)
1798                                         return err;
1799                                 bdev = bdev2;
1800                                 start = i;
1801                                 len = 0;
1802                         }
1803                 }
1804
1805                 se = get_seg_entry(sbi, GET_SEGNO(sbi, i));
1806                 offset = GET_BLKOFF_FROM_SEG0(sbi, i);
1807
1808                 if (f2fs_block_unit_discard(sbi) &&
1809                                 !f2fs_test_and_set_bit(offset, se->discard_map))
1810                         sbi->discard_blks--;
1811         }
1812
1813         if (len)
1814                 err = __issue_discard_async(sbi, bdev, start, len);
1815         return err;
1816 }
1817
1818 static bool add_discard_addrs(struct f2fs_sb_info *sbi, struct cp_control *cpc,
1819                                                         bool check_only)
1820 {
1821         int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
1822         int max_blocks = sbi->blocks_per_seg;
1823         struct seg_entry *se = get_seg_entry(sbi, cpc->trim_start);
1824         unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
1825         unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
1826         unsigned long *discard_map = (unsigned long *)se->discard_map;
1827         unsigned long *dmap = SIT_I(sbi)->tmp_map;
1828         unsigned int start = 0, end = -1;
1829         bool force = (cpc->reason & CP_DISCARD);
1830         struct discard_entry *de = NULL;
1831         struct list_head *head = &SM_I(sbi)->dcc_info->entry_list;
1832         int i;
1833
1834         if (se->valid_blocks == max_blocks || !f2fs_hw_support_discard(sbi) ||
1835                         !f2fs_block_unit_discard(sbi))
1836                 return false;
1837
1838         if (!force) {
1839                 if (!f2fs_realtime_discard_enable(sbi) || !se->valid_blocks ||
1840                         SM_I(sbi)->dcc_info->nr_discards >=
1841                                 SM_I(sbi)->dcc_info->max_discards)
1842                         return false;
1843         }
1844
1845         /* SIT_VBLOCK_MAP_SIZE should be multiple of sizeof(unsigned long) */
1846         for (i = 0; i < entries; i++)
1847                 dmap[i] = force ? ~ckpt_map[i] & ~discard_map[i] :
1848                                 (cur_map[i] ^ ckpt_map[i]) & ckpt_map[i];
1849
1850         while (force || SM_I(sbi)->dcc_info->nr_discards <=
1851                                 SM_I(sbi)->dcc_info->max_discards) {
1852                 start = __find_rev_next_bit(dmap, max_blocks, end + 1);
1853                 if (start >= max_blocks)
1854                         break;
1855
1856                 end = __find_rev_next_zero_bit(dmap, max_blocks, start + 1);
1857                 if (force && start && end != max_blocks
1858                                         && (end - start) < cpc->trim_minlen)
1859                         continue;
1860
1861                 if (check_only)
1862                         return true;
1863
1864                 if (!de) {
1865                         de = f2fs_kmem_cache_alloc(discard_entry_slab,
1866                                                 GFP_F2FS_ZERO, true, NULL);
1867                         de->start_blkaddr = START_BLOCK(sbi, cpc->trim_start);
1868                         list_add_tail(&de->list, head);
1869                 }
1870
1871                 for (i = start; i < end; i++)
1872                         __set_bit_le(i, (void *)de->discard_map);
1873
1874                 SM_I(sbi)->dcc_info->nr_discards += end - start;
1875         }
1876         return false;
1877 }
1878
1879 static void release_discard_addr(struct discard_entry *entry)
1880 {
1881         list_del(&entry->list);
1882         kmem_cache_free(discard_entry_slab, entry);
1883 }
1884
1885 void f2fs_release_discard_addrs(struct f2fs_sb_info *sbi)
1886 {
1887         struct list_head *head = &(SM_I(sbi)->dcc_info->entry_list);
1888         struct discard_entry *entry, *this;
1889
1890         /* drop caches */
1891         list_for_each_entry_safe(entry, this, head, list)
1892                 release_discard_addr(entry);
1893 }
1894
1895 /*
1896  * Should call f2fs_clear_prefree_segments after checkpoint is done.
1897  */
1898 static void set_prefree_as_free_segments(struct f2fs_sb_info *sbi)
1899 {
1900         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
1901         unsigned int segno;
1902
1903         mutex_lock(&dirty_i->seglist_lock);
1904         for_each_set_bit(segno, dirty_i->dirty_segmap[PRE], MAIN_SEGS(sbi))
1905                 __set_test_and_free(sbi, segno, false);
1906         mutex_unlock(&dirty_i->seglist_lock);
1907 }
1908
1909 void f2fs_clear_prefree_segments(struct f2fs_sb_info *sbi,
1910                                                 struct cp_control *cpc)
1911 {
1912         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1913         struct list_head *head = &dcc->entry_list;
1914         struct discard_entry *entry, *this;
1915         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
1916         unsigned long *prefree_map = dirty_i->dirty_segmap[PRE];
1917         unsigned int start = 0, end = -1;
1918         unsigned int secno, start_segno;
1919         bool force = (cpc->reason & CP_DISCARD);
1920         bool section_alignment = F2FS_OPTION(sbi).discard_unit ==
1921                                                 DISCARD_UNIT_SECTION;
1922
1923         if (f2fs_lfs_mode(sbi) && __is_large_section(sbi))
1924                 section_alignment = true;
1925
1926         mutex_lock(&dirty_i->seglist_lock);
1927
1928         while (1) {
1929                 int i;
1930
1931                 if (section_alignment && end != -1)
1932                         end--;
1933                 start = find_next_bit(prefree_map, MAIN_SEGS(sbi), end + 1);
1934                 if (start >= MAIN_SEGS(sbi))
1935                         break;
1936                 end = find_next_zero_bit(prefree_map, MAIN_SEGS(sbi),
1937                                                                 start + 1);
1938
1939                 if (section_alignment) {
1940                         start = rounddown(start, sbi->segs_per_sec);
1941                         end = roundup(end, sbi->segs_per_sec);
1942                 }
1943
1944                 for (i = start; i < end; i++) {
1945                         if (test_and_clear_bit(i, prefree_map))
1946                                 dirty_i->nr_dirty[PRE]--;
1947                 }
1948
1949                 if (!f2fs_realtime_discard_enable(sbi))
1950                         continue;
1951
1952                 if (force && start >= cpc->trim_start &&
1953                                         (end - 1) <= cpc->trim_end)
1954                                 continue;
1955
1956                 if (!f2fs_lfs_mode(sbi) || !__is_large_section(sbi)) {
1957                         f2fs_issue_discard(sbi, START_BLOCK(sbi, start),
1958                                 (end - start) << sbi->log_blocks_per_seg);
1959                         continue;
1960                 }
1961 next:
1962                 secno = GET_SEC_FROM_SEG(sbi, start);
1963                 start_segno = GET_SEG_FROM_SEC(sbi, secno);
1964                 if (!IS_CURSEC(sbi, secno) &&
1965                         !get_valid_blocks(sbi, start, true))
1966                         f2fs_issue_discard(sbi, START_BLOCK(sbi, start_segno),
1967                                 sbi->segs_per_sec << sbi->log_blocks_per_seg);
1968
1969                 start = start_segno + sbi->segs_per_sec;
1970                 if (start < end)
1971                         goto next;
1972                 else
1973                         end = start - 1;
1974         }
1975         mutex_unlock(&dirty_i->seglist_lock);
1976
1977         if (!f2fs_block_unit_discard(sbi))
1978                 goto wakeup;
1979
1980         /* send small discards */
1981         list_for_each_entry_safe(entry, this, head, list) {
1982                 unsigned int cur_pos = 0, next_pos, len, total_len = 0;
1983                 bool is_valid = test_bit_le(0, entry->discard_map);
1984
1985 find_next:
1986                 if (is_valid) {
1987                         next_pos = find_next_zero_bit_le(entry->discard_map,
1988                                         sbi->blocks_per_seg, cur_pos);
1989                         len = next_pos - cur_pos;
1990
1991                         if (f2fs_sb_has_blkzoned(sbi) ||
1992                             (force && len < cpc->trim_minlen))
1993                                 goto skip;
1994
1995                         f2fs_issue_discard(sbi, entry->start_blkaddr + cur_pos,
1996                                                                         len);
1997                         total_len += len;
1998                 } else {
1999                         next_pos = find_next_bit_le(entry->discard_map,
2000                                         sbi->blocks_per_seg, cur_pos);
2001                 }
2002 skip:
2003                 cur_pos = next_pos;
2004                 is_valid = !is_valid;
2005
2006                 if (cur_pos < sbi->blocks_per_seg)
2007                         goto find_next;
2008
2009                 release_discard_addr(entry);
2010                 dcc->nr_discards -= total_len;
2011         }
2012
2013 wakeup:
2014         wake_up_discard_thread(sbi, false);
2015 }
2016
2017 int f2fs_start_discard_thread(struct f2fs_sb_info *sbi)
2018 {
2019         dev_t dev = sbi->sb->s_bdev->bd_dev;
2020         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
2021         int err = 0;
2022
2023         if (!f2fs_realtime_discard_enable(sbi))
2024                 return 0;
2025
2026         dcc->f2fs_issue_discard = kthread_run(issue_discard_thread, sbi,
2027                                 "f2fs_discard-%u:%u", MAJOR(dev), MINOR(dev));
2028         if (IS_ERR(dcc->f2fs_issue_discard)) {
2029                 err = PTR_ERR(dcc->f2fs_issue_discard);
2030                 dcc->f2fs_issue_discard = NULL;
2031         }
2032
2033         return err;
2034 }
2035
2036 static int create_discard_cmd_control(struct f2fs_sb_info *sbi)
2037 {
2038         struct discard_cmd_control *dcc;
2039         int err = 0, i;
2040
2041         if (SM_I(sbi)->dcc_info) {
2042                 dcc = SM_I(sbi)->dcc_info;
2043                 goto init_thread;
2044         }
2045
2046         dcc = f2fs_kzalloc(sbi, sizeof(struct discard_cmd_control), GFP_KERNEL);
2047         if (!dcc)
2048                 return -ENOMEM;
2049
2050         dcc->discard_granularity = DEFAULT_DISCARD_GRANULARITY;
2051         if (F2FS_OPTION(sbi).discard_unit == DISCARD_UNIT_SEGMENT)
2052                 dcc->discard_granularity = sbi->blocks_per_seg;
2053         else if (F2FS_OPTION(sbi).discard_unit == DISCARD_UNIT_SECTION)
2054                 dcc->discard_granularity = BLKS_PER_SEC(sbi);
2055
2056         INIT_LIST_HEAD(&dcc->entry_list);
2057         for (i = 0; i < MAX_PLIST_NUM; i++)
2058                 INIT_LIST_HEAD(&dcc->pend_list[i]);
2059         INIT_LIST_HEAD(&dcc->wait_list);
2060         INIT_LIST_HEAD(&dcc->fstrim_list);
2061         mutex_init(&dcc->cmd_lock);
2062         atomic_set(&dcc->issued_discard, 0);
2063         atomic_set(&dcc->queued_discard, 0);
2064         atomic_set(&dcc->discard_cmd_cnt, 0);
2065         dcc->nr_discards = 0;
2066         dcc->max_discards = MAIN_SEGS(sbi) << sbi->log_blocks_per_seg;
2067         dcc->max_discard_request = DEF_MAX_DISCARD_REQUEST;
2068         dcc->min_discard_issue_time = DEF_MIN_DISCARD_ISSUE_TIME;
2069         dcc->mid_discard_issue_time = DEF_MID_DISCARD_ISSUE_TIME;
2070         dcc->max_discard_issue_time = DEF_MAX_DISCARD_ISSUE_TIME;
2071         dcc->undiscard_blks = 0;
2072         dcc->next_pos = 0;
2073         dcc->root = RB_ROOT_CACHED;
2074         dcc->rbtree_check = false;
2075
2076         init_waitqueue_head(&dcc->discard_wait_queue);
2077         SM_I(sbi)->dcc_info = dcc;
2078 init_thread:
2079         err = f2fs_start_discard_thread(sbi);
2080         if (err) {
2081                 kfree(dcc);
2082                 SM_I(sbi)->dcc_info = NULL;
2083         }
2084
2085         return err;
2086 }
2087
2088 static void destroy_discard_cmd_control(struct f2fs_sb_info *sbi)
2089 {
2090         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
2091
2092         if (!dcc)
2093                 return;
2094
2095         f2fs_stop_discard_thread(sbi);
2096
2097         /*
2098          * Recovery can cache discard commands, so in error path of
2099          * fill_super(), it needs to give a chance to handle them.
2100          */
2101         if (unlikely(atomic_read(&dcc->discard_cmd_cnt)))
2102                 f2fs_issue_discard_timeout(sbi);
2103
2104         kfree(dcc);
2105         SM_I(sbi)->dcc_info = NULL;
2106 }
2107
2108 static bool __mark_sit_entry_dirty(struct f2fs_sb_info *sbi, unsigned int segno)
2109 {
2110         struct sit_info *sit_i = SIT_I(sbi);
2111
2112         if (!__test_and_set_bit(segno, sit_i->dirty_sentries_bitmap)) {
2113                 sit_i->dirty_sentries++;
2114                 return false;
2115         }
2116
2117         return true;
2118 }
2119
2120 static void __set_sit_entry_type(struct f2fs_sb_info *sbi, int type,
2121                                         unsigned int segno, int modified)
2122 {
2123         struct seg_entry *se = get_seg_entry(sbi, segno);
2124
2125         se->type = type;
2126         if (modified)
2127                 __mark_sit_entry_dirty(sbi, segno);
2128 }
2129
2130 static inline unsigned long long get_segment_mtime(struct f2fs_sb_info *sbi,
2131                                                                 block_t blkaddr)
2132 {
2133         unsigned int segno = GET_SEGNO(sbi, blkaddr);
2134
2135         if (segno == NULL_SEGNO)
2136                 return 0;
2137         return get_seg_entry(sbi, segno)->mtime;
2138 }
2139
2140 static void update_segment_mtime(struct f2fs_sb_info *sbi, block_t blkaddr,
2141                                                 unsigned long long old_mtime)
2142 {
2143         struct seg_entry *se;
2144         unsigned int segno = GET_SEGNO(sbi, blkaddr);
2145         unsigned long long ctime = get_mtime(sbi, false);
2146         unsigned long long mtime = old_mtime ? old_mtime : ctime;
2147
2148         if (segno == NULL_SEGNO)
2149                 return;
2150
2151         se = get_seg_entry(sbi, segno);
2152
2153         if (!se->mtime)
2154                 se->mtime = mtime;
2155         else
2156                 se->mtime = div_u64(se->mtime * se->valid_blocks + mtime,
2157                                                 se->valid_blocks + 1);
2158
2159         if (ctime > SIT_I(sbi)->max_mtime)
2160                 SIT_I(sbi)->max_mtime = ctime;
2161 }
2162
2163 static void update_sit_entry(struct f2fs_sb_info *sbi, block_t blkaddr, int del)
2164 {
2165         struct seg_entry *se;
2166         unsigned int segno, offset;
2167         long int new_vblocks;
2168         bool exist;
2169 #ifdef CONFIG_F2FS_CHECK_FS
2170         bool mir_exist;
2171 #endif
2172
2173         segno = GET_SEGNO(sbi, blkaddr);
2174
2175         se = get_seg_entry(sbi, segno);
2176         new_vblocks = se->valid_blocks + del;
2177         offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
2178
2179         f2fs_bug_on(sbi, (new_vblocks < 0 ||
2180                         (new_vblocks > f2fs_usable_blks_in_seg(sbi, segno))));
2181
2182         se->valid_blocks = new_vblocks;
2183
2184         /* Update valid block bitmap */
2185         if (del > 0) {
2186                 exist = f2fs_test_and_set_bit(offset, se->cur_valid_map);
2187 #ifdef CONFIG_F2FS_CHECK_FS
2188                 mir_exist = f2fs_test_and_set_bit(offset,
2189                                                 se->cur_valid_map_mir);
2190                 if (unlikely(exist != mir_exist)) {
2191                         f2fs_err(sbi, "Inconsistent error when setting bitmap, blk:%u, old bit:%d",
2192                                  blkaddr, exist);
2193                         f2fs_bug_on(sbi, 1);
2194                 }
2195 #endif
2196                 if (unlikely(exist)) {
2197                         f2fs_err(sbi, "Bitmap was wrongly set, blk:%u",
2198                                  blkaddr);
2199                         f2fs_bug_on(sbi, 1);
2200                         se->valid_blocks--;
2201                         del = 0;
2202                 }
2203
2204                 if (f2fs_block_unit_discard(sbi) &&
2205                                 !f2fs_test_and_set_bit(offset, se->discard_map))
2206                         sbi->discard_blks--;
2207
2208                 /*
2209                  * SSR should never reuse block which is checkpointed
2210                  * or newly invalidated.
2211                  */
2212                 if (!is_sbi_flag_set(sbi, SBI_CP_DISABLED)) {
2213                         if (!f2fs_test_and_set_bit(offset, se->ckpt_valid_map))
2214                                 se->ckpt_valid_blocks++;
2215                 }
2216         } else {
2217                 exist = f2fs_test_and_clear_bit(offset, se->cur_valid_map);
2218 #ifdef CONFIG_F2FS_CHECK_FS
2219                 mir_exist = f2fs_test_and_clear_bit(offset,
2220                                                 se->cur_valid_map_mir);
2221                 if (unlikely(exist != mir_exist)) {
2222                         f2fs_err(sbi, "Inconsistent error when clearing bitmap, blk:%u, old bit:%d",
2223                                  blkaddr, exist);
2224                         f2fs_bug_on(sbi, 1);
2225                 }
2226 #endif
2227                 if (unlikely(!exist)) {
2228                         f2fs_err(sbi, "Bitmap was wrongly cleared, blk:%u",
2229                                  blkaddr);
2230                         f2fs_bug_on(sbi, 1);
2231                         se->valid_blocks++;
2232                         del = 0;
2233                 } else if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) {
2234                         /*
2235                          * If checkpoints are off, we must not reuse data that
2236                          * was used in the previous checkpoint. If it was used
2237                          * before, we must track that to know how much space we
2238                          * really have.
2239                          */
2240                         if (f2fs_test_bit(offset, se->ckpt_valid_map)) {
2241                                 spin_lock(&sbi->stat_lock);
2242                                 sbi->unusable_block_count++;
2243                                 spin_unlock(&sbi->stat_lock);
2244                         }
2245                 }
2246
2247                 if (f2fs_block_unit_discard(sbi) &&
2248                         f2fs_test_and_clear_bit(offset, se->discard_map))
2249                         sbi->discard_blks++;
2250         }
2251         if (!f2fs_test_bit(offset, se->ckpt_valid_map))
2252                 se->ckpt_valid_blocks += del;
2253
2254         __mark_sit_entry_dirty(sbi, segno);
2255
2256         /* update total number of valid blocks to be written in ckpt area */
2257         SIT_I(sbi)->written_valid_blocks += del;
2258
2259         if (__is_large_section(sbi))
2260                 get_sec_entry(sbi, segno)->valid_blocks += del;
2261 }
2262
2263 void f2fs_invalidate_blocks(struct f2fs_sb_info *sbi, block_t addr)
2264 {
2265         unsigned int segno = GET_SEGNO(sbi, addr);
2266         struct sit_info *sit_i = SIT_I(sbi);
2267
2268         f2fs_bug_on(sbi, addr == NULL_ADDR);
2269         if (addr == NEW_ADDR || addr == COMPRESS_ADDR)
2270                 return;
2271
2272         invalidate_mapping_pages(META_MAPPING(sbi), addr, addr);
2273         f2fs_invalidate_compress_page(sbi, addr);
2274
2275         /* add it into sit main buffer */
2276         down_write(&sit_i->sentry_lock);
2277
2278         update_segment_mtime(sbi, addr, 0);
2279         update_sit_entry(sbi, addr, -1);
2280
2281         /* add it into dirty seglist */
2282         locate_dirty_segment(sbi, segno);
2283
2284         up_write(&sit_i->sentry_lock);
2285 }
2286
2287 bool f2fs_is_checkpointed_data(struct f2fs_sb_info *sbi, block_t blkaddr)
2288 {
2289         struct sit_info *sit_i = SIT_I(sbi);
2290         unsigned int segno, offset;
2291         struct seg_entry *se;
2292         bool is_cp = false;
2293
2294         if (!__is_valid_data_blkaddr(blkaddr))
2295                 return true;
2296
2297         down_read(&sit_i->sentry_lock);
2298
2299         segno = GET_SEGNO(sbi, blkaddr);
2300         se = get_seg_entry(sbi, segno);
2301         offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
2302
2303         if (f2fs_test_bit(offset, se->ckpt_valid_map))
2304                 is_cp = true;
2305
2306         up_read(&sit_i->sentry_lock);
2307
2308         return is_cp;
2309 }
2310
2311 /*
2312  * This function should be resided under the curseg_mutex lock
2313  */
2314 static void __add_sum_entry(struct f2fs_sb_info *sbi, int type,
2315                                         struct f2fs_summary *sum)
2316 {
2317         struct curseg_info *curseg = CURSEG_I(sbi, type);
2318         void *addr = curseg->sum_blk;
2319
2320         addr += curseg->next_blkoff * sizeof(struct f2fs_summary);
2321         memcpy(addr, sum, sizeof(struct f2fs_summary));
2322 }
2323
2324 /*
2325  * Calculate the number of current summary pages for writing
2326  */
2327 int f2fs_npages_for_summary_flush(struct f2fs_sb_info *sbi, bool for_ra)
2328 {
2329         int valid_sum_count = 0;
2330         int i, sum_in_page;
2331
2332         for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
2333                 if (sbi->ckpt->alloc_type[i] == SSR)
2334                         valid_sum_count += sbi->blocks_per_seg;
2335                 else {
2336                         if (for_ra)
2337                                 valid_sum_count += le16_to_cpu(
2338                                         F2FS_CKPT(sbi)->cur_data_blkoff[i]);
2339                         else
2340                                 valid_sum_count += curseg_blkoff(sbi, i);
2341                 }
2342         }
2343
2344         sum_in_page = (PAGE_SIZE - 2 * SUM_JOURNAL_SIZE -
2345                         SUM_FOOTER_SIZE) / SUMMARY_SIZE;
2346         if (valid_sum_count <= sum_in_page)
2347                 return 1;
2348         else if ((valid_sum_count - sum_in_page) <=
2349                 (PAGE_SIZE - SUM_FOOTER_SIZE) / SUMMARY_SIZE)
2350                 return 2;
2351         return 3;
2352 }
2353
2354 /*
2355  * Caller should put this summary page
2356  */
2357 struct page *f2fs_get_sum_page(struct f2fs_sb_info *sbi, unsigned int segno)
2358 {
2359         if (unlikely(f2fs_cp_error(sbi)))
2360                 return ERR_PTR(-EIO);
2361         return f2fs_get_meta_page_retry(sbi, GET_SUM_BLOCK(sbi, segno));
2362 }
2363
2364 void f2fs_update_meta_page(struct f2fs_sb_info *sbi,
2365                                         void *src, block_t blk_addr)
2366 {
2367         struct page *page = f2fs_grab_meta_page(sbi, blk_addr);
2368
2369         memcpy(page_address(page), src, PAGE_SIZE);
2370         set_page_dirty(page);
2371         f2fs_put_page(page, 1);
2372 }
2373
2374 static void write_sum_page(struct f2fs_sb_info *sbi,
2375                         struct f2fs_summary_block *sum_blk, block_t blk_addr)
2376 {
2377         f2fs_update_meta_page(sbi, (void *)sum_blk, blk_addr);
2378 }
2379
2380 static void write_current_sum_page(struct f2fs_sb_info *sbi,
2381                                                 int type, block_t blk_addr)
2382 {
2383         struct curseg_info *curseg = CURSEG_I(sbi, type);
2384         struct page *page = f2fs_grab_meta_page(sbi, blk_addr);
2385         struct f2fs_summary_block *src = curseg->sum_blk;
2386         struct f2fs_summary_block *dst;
2387
2388         dst = (struct f2fs_summary_block *)page_address(page);
2389         memset(dst, 0, PAGE_SIZE);
2390
2391         mutex_lock(&curseg->curseg_mutex);
2392
2393         down_read(&curseg->journal_rwsem);
2394         memcpy(&dst->journal, curseg->journal, SUM_JOURNAL_SIZE);
2395         up_read(&curseg->journal_rwsem);
2396
2397         memcpy(dst->entries, src->entries, SUM_ENTRY_SIZE);
2398         memcpy(&dst->footer, &src->footer, SUM_FOOTER_SIZE);
2399
2400         mutex_unlock(&curseg->curseg_mutex);
2401
2402         set_page_dirty(page);
2403         f2fs_put_page(page, 1);
2404 }
2405
2406 static int is_next_segment_free(struct f2fs_sb_info *sbi,
2407                                 struct curseg_info *curseg, int type)
2408 {
2409         unsigned int segno = curseg->segno + 1;
2410         struct free_segmap_info *free_i = FREE_I(sbi);
2411
2412         if (segno < MAIN_SEGS(sbi) && segno % sbi->segs_per_sec)
2413                 return !test_bit(segno, free_i->free_segmap);
2414         return 0;
2415 }
2416
2417 /*
2418  * Find a new segment from the free segments bitmap to right order
2419  * This function should be returned with success, otherwise BUG
2420  */
2421 static void get_new_segment(struct f2fs_sb_info *sbi,
2422                         unsigned int *newseg, bool new_sec, int dir)
2423 {
2424         struct free_segmap_info *free_i = FREE_I(sbi);
2425         unsigned int segno, secno, zoneno;
2426         unsigned int total_zones = MAIN_SECS(sbi) / sbi->secs_per_zone;
2427         unsigned int hint = GET_SEC_FROM_SEG(sbi, *newseg);
2428         unsigned int old_zoneno = GET_ZONE_FROM_SEG(sbi, *newseg);
2429         unsigned int left_start = hint;
2430         bool init = true;
2431         int go_left = 0;
2432         int i;
2433
2434         spin_lock(&free_i->segmap_lock);
2435
2436         if (!new_sec && ((*newseg + 1) % sbi->segs_per_sec)) {
2437                 segno = find_next_zero_bit(free_i->free_segmap,
2438                         GET_SEG_FROM_SEC(sbi, hint + 1), *newseg + 1);
2439                 if (segno < GET_SEG_FROM_SEC(sbi, hint + 1))
2440                         goto got_it;
2441         }
2442 find_other_zone:
2443         secno = find_next_zero_bit(free_i->free_secmap, MAIN_SECS(sbi), hint);
2444         if (secno >= MAIN_SECS(sbi)) {
2445                 if (dir == ALLOC_RIGHT) {
2446                         secno = find_first_zero_bit(free_i->free_secmap,
2447                                                         MAIN_SECS(sbi));
2448                         f2fs_bug_on(sbi, secno >= MAIN_SECS(sbi));
2449                 } else {
2450                         go_left = 1;
2451                         left_start = hint - 1;
2452                 }
2453         }
2454         if (go_left == 0)
2455                 goto skip_left;
2456
2457         while (test_bit(left_start, free_i->free_secmap)) {
2458                 if (left_start > 0) {
2459                         left_start--;
2460                         continue;
2461                 }
2462                 left_start = find_first_zero_bit(free_i->free_secmap,
2463                                                         MAIN_SECS(sbi));
2464                 f2fs_bug_on(sbi, left_start >= MAIN_SECS(sbi));
2465                 break;
2466         }
2467         secno = left_start;
2468 skip_left:
2469         segno = GET_SEG_FROM_SEC(sbi, secno);
2470         zoneno = GET_ZONE_FROM_SEC(sbi, secno);
2471
2472         /* give up on finding another zone */
2473         if (!init)
2474                 goto got_it;
2475         if (sbi->secs_per_zone == 1)
2476                 goto got_it;
2477         if (zoneno == old_zoneno)
2478                 goto got_it;
2479         if (dir == ALLOC_LEFT) {
2480                 if (!go_left && zoneno + 1 >= total_zones)
2481                         goto got_it;
2482                 if (go_left && zoneno == 0)
2483                         goto got_it;
2484         }
2485         for (i = 0; i < NR_CURSEG_TYPE; i++)
2486                 if (CURSEG_I(sbi, i)->zone == zoneno)
2487                         break;
2488
2489         if (i < NR_CURSEG_TYPE) {
2490                 /* zone is in user, try another */
2491                 if (go_left)
2492                         hint = zoneno * sbi->secs_per_zone - 1;
2493                 else if (zoneno + 1 >= total_zones)
2494                         hint = 0;
2495                 else
2496                         hint = (zoneno + 1) * sbi->secs_per_zone;
2497                 init = false;
2498                 goto find_other_zone;
2499         }
2500 got_it:
2501         /* set it as dirty segment in free segmap */
2502         f2fs_bug_on(sbi, test_bit(segno, free_i->free_segmap));
2503         __set_inuse(sbi, segno);
2504         *newseg = segno;
2505         spin_unlock(&free_i->segmap_lock);
2506 }
2507
2508 static void reset_curseg(struct f2fs_sb_info *sbi, int type, int modified)
2509 {
2510         struct curseg_info *curseg = CURSEG_I(sbi, type);
2511         struct summary_footer *sum_footer;
2512         unsigned short seg_type = curseg->seg_type;
2513
2514         curseg->inited = true;
2515         curseg->segno = curseg->next_segno;
2516         curseg->zone = GET_ZONE_FROM_SEG(sbi, curseg->segno);
2517         curseg->next_blkoff = 0;
2518         curseg->next_segno = NULL_SEGNO;
2519
2520         sum_footer = &(curseg->sum_blk->footer);
2521         memset(sum_footer, 0, sizeof(struct summary_footer));
2522
2523         sanity_check_seg_type(sbi, seg_type);
2524
2525         if (IS_DATASEG(seg_type))
2526                 SET_SUM_TYPE(sum_footer, SUM_TYPE_DATA);
2527         if (IS_NODESEG(seg_type))
2528                 SET_SUM_TYPE(sum_footer, SUM_TYPE_NODE);
2529         __set_sit_entry_type(sbi, seg_type, curseg->segno, modified);
2530 }
2531
2532 static unsigned int __get_next_segno(struct f2fs_sb_info *sbi, int type)
2533 {
2534         struct curseg_info *curseg = CURSEG_I(sbi, type);
2535         unsigned short seg_type = curseg->seg_type;
2536
2537         sanity_check_seg_type(sbi, seg_type);
2538         if (f2fs_need_rand_seg(sbi))
2539                 return prandom_u32_max(MAIN_SECS(sbi) * sbi->segs_per_sec);
2540
2541         /* if segs_per_sec is large than 1, we need to keep original policy. */
2542         if (__is_large_section(sbi))
2543                 return curseg->segno;
2544
2545         /* inmem log may not locate on any segment after mount */
2546         if (!curseg->inited)
2547                 return 0;
2548
2549         if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED)))
2550                 return 0;
2551
2552         if (test_opt(sbi, NOHEAP) &&
2553                 (seg_type == CURSEG_HOT_DATA || IS_NODESEG(seg_type)))
2554                 return 0;
2555
2556         if (SIT_I(sbi)->last_victim[ALLOC_NEXT])
2557                 return SIT_I(sbi)->last_victim[ALLOC_NEXT];
2558
2559         /* find segments from 0 to reuse freed segments */
2560         if (F2FS_OPTION(sbi).alloc_mode == ALLOC_MODE_REUSE)
2561                 return 0;
2562
2563         return curseg->segno;
2564 }
2565
2566 /*
2567  * Allocate a current working segment.
2568  * This function always allocates a free segment in LFS manner.
2569  */
2570 static void new_curseg(struct f2fs_sb_info *sbi, int type, bool new_sec)
2571 {
2572         struct curseg_info *curseg = CURSEG_I(sbi, type);
2573         unsigned short seg_type = curseg->seg_type;
2574         unsigned int segno = curseg->segno;
2575         int dir = ALLOC_LEFT;
2576
2577         if (curseg->inited)
2578                 write_sum_page(sbi, curseg->sum_blk,
2579                                 GET_SUM_BLOCK(sbi, segno));
2580         if (seg_type == CURSEG_WARM_DATA || seg_type == CURSEG_COLD_DATA)
2581                 dir = ALLOC_RIGHT;
2582
2583         if (test_opt(sbi, NOHEAP))
2584                 dir = ALLOC_RIGHT;
2585
2586         segno = __get_next_segno(sbi, type);
2587         get_new_segment(sbi, &segno, new_sec, dir);
2588         curseg->next_segno = segno;
2589         reset_curseg(sbi, type, 1);
2590         curseg->alloc_type = LFS;
2591         if (F2FS_OPTION(sbi).fs_mode == FS_MODE_FRAGMENT_BLK)
2592                 curseg->fragment_remained_chunk =
2593                                 prandom_u32_max(sbi->max_fragment_chunk) + 1;
2594 }
2595
2596 static int __next_free_blkoff(struct f2fs_sb_info *sbi,
2597                                         int segno, block_t start)
2598 {
2599         struct seg_entry *se = get_seg_entry(sbi, segno);
2600         int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
2601         unsigned long *target_map = SIT_I(sbi)->tmp_map;
2602         unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
2603         unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
2604         int i;
2605
2606         for (i = 0; i < entries; i++)
2607                 target_map[i] = ckpt_map[i] | cur_map[i];
2608
2609         return __find_rev_next_zero_bit(target_map, sbi->blocks_per_seg, start);
2610 }
2611
2612 /*
2613  * If a segment is written by LFS manner, next block offset is just obtained
2614  * by increasing the current block offset. However, if a segment is written by
2615  * SSR manner, next block offset obtained by calling __next_free_blkoff
2616  */
2617 static void __refresh_next_blkoff(struct f2fs_sb_info *sbi,
2618                                 struct curseg_info *seg)
2619 {
2620         if (seg->alloc_type == SSR) {
2621                 seg->next_blkoff =
2622                         __next_free_blkoff(sbi, seg->segno,
2623                                                 seg->next_blkoff + 1);
2624         } else {
2625                 seg->next_blkoff++;
2626                 if (F2FS_OPTION(sbi).fs_mode == FS_MODE_FRAGMENT_BLK) {
2627                         /* To allocate block chunks in different sizes, use random number */
2628                         if (--seg->fragment_remained_chunk <= 0) {
2629                                 seg->fragment_remained_chunk =
2630                                    prandom_u32_max(sbi->max_fragment_chunk) + 1;
2631                                 seg->next_blkoff +=
2632                                    prandom_u32_max(sbi->max_fragment_hole) + 1;
2633                         }
2634                 }
2635         }
2636 }
2637
2638 bool f2fs_segment_has_free_slot(struct f2fs_sb_info *sbi, int segno)
2639 {
2640         return __next_free_blkoff(sbi, segno, 0) < sbi->blocks_per_seg;
2641 }
2642
2643 /*
2644  * This function always allocates a used segment(from dirty seglist) by SSR
2645  * manner, so it should recover the existing segment information of valid blocks
2646  */
2647 static void change_curseg(struct f2fs_sb_info *sbi, int type, bool flush)
2648 {
2649         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
2650         struct curseg_info *curseg = CURSEG_I(sbi, type);
2651         unsigned int new_segno = curseg->next_segno;
2652         struct f2fs_summary_block *sum_node;
2653         struct page *sum_page;
2654
2655         if (flush)
2656                 write_sum_page(sbi, curseg->sum_blk,
2657                                         GET_SUM_BLOCK(sbi, curseg->segno));
2658
2659         __set_test_and_inuse(sbi, new_segno);
2660
2661         mutex_lock(&dirty_i->seglist_lock);
2662         __remove_dirty_segment(sbi, new_segno, PRE);
2663         __remove_dirty_segment(sbi, new_segno, DIRTY);
2664         mutex_unlock(&dirty_i->seglist_lock);
2665
2666         reset_curseg(sbi, type, 1);
2667         curseg->alloc_type = SSR;
2668         curseg->next_blkoff = __next_free_blkoff(sbi, curseg->segno, 0);
2669
2670         sum_page = f2fs_get_sum_page(sbi, new_segno);
2671         if (IS_ERR(sum_page)) {
2672                 /* GC won't be able to use stale summary pages by cp_error */
2673                 memset(curseg->sum_blk, 0, SUM_ENTRY_SIZE);
2674                 return;
2675         }
2676         sum_node = (struct f2fs_summary_block *)page_address(sum_page);
2677         memcpy(curseg->sum_blk, sum_node, SUM_ENTRY_SIZE);
2678         f2fs_put_page(sum_page, 1);
2679 }
2680
2681 static int get_ssr_segment(struct f2fs_sb_info *sbi, int type,
2682                                 int alloc_mode, unsigned long long age);
2683
2684 static void get_atssr_segment(struct f2fs_sb_info *sbi, int type,
2685                                         int target_type, int alloc_mode,
2686                                         unsigned long long age)
2687 {
2688         struct curseg_info *curseg = CURSEG_I(sbi, type);
2689
2690         curseg->seg_type = target_type;
2691
2692         if (get_ssr_segment(sbi, type, alloc_mode, age)) {
2693                 struct seg_entry *se = get_seg_entry(sbi, curseg->next_segno);
2694
2695                 curseg->seg_type = se->type;
2696                 change_curseg(sbi, type, true);
2697         } else {
2698                 /* allocate cold segment by default */
2699                 curseg->seg_type = CURSEG_COLD_DATA;
2700                 new_curseg(sbi, type, true);
2701         }
2702         stat_inc_seg_type(sbi, curseg);
2703 }
2704
2705 static void __f2fs_init_atgc_curseg(struct f2fs_sb_info *sbi)
2706 {
2707         struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_ALL_DATA_ATGC);
2708
2709         if (!sbi->am.atgc_enabled)
2710                 return;
2711
2712         f2fs_down_read(&SM_I(sbi)->curseg_lock);
2713
2714         mutex_lock(&curseg->curseg_mutex);
2715         down_write(&SIT_I(sbi)->sentry_lock);
2716
2717         get_atssr_segment(sbi, CURSEG_ALL_DATA_ATGC, CURSEG_COLD_DATA, SSR, 0);
2718
2719         up_write(&SIT_I(sbi)->sentry_lock);
2720         mutex_unlock(&curseg->curseg_mutex);
2721
2722         f2fs_up_read(&SM_I(sbi)->curseg_lock);
2723
2724 }
2725 void f2fs_init_inmem_curseg(struct f2fs_sb_info *sbi)
2726 {
2727         __f2fs_init_atgc_curseg(sbi);
2728 }
2729
2730 static void __f2fs_save_inmem_curseg(struct f2fs_sb_info *sbi, int type)
2731 {
2732         struct curseg_info *curseg = CURSEG_I(sbi, type);
2733
2734         mutex_lock(&curseg->curseg_mutex);
2735         if (!curseg->inited)
2736                 goto out;
2737
2738         if (get_valid_blocks(sbi, curseg->segno, false)) {
2739                 write_sum_page(sbi, curseg->sum_blk,
2740                                 GET_SUM_BLOCK(sbi, curseg->segno));
2741         } else {
2742                 mutex_lock(&DIRTY_I(sbi)->seglist_lock);
2743                 __set_test_and_free(sbi, curseg->segno, true);
2744                 mutex_unlock(&DIRTY_I(sbi)->seglist_lock);
2745         }
2746 out:
2747         mutex_unlock(&curseg->curseg_mutex);
2748 }
2749
2750 void f2fs_save_inmem_curseg(struct f2fs_sb_info *sbi)
2751 {
2752         __f2fs_save_inmem_curseg(sbi, CURSEG_COLD_DATA_PINNED);
2753
2754         if (sbi->am.atgc_enabled)
2755                 __f2fs_save_inmem_curseg(sbi, CURSEG_ALL_DATA_ATGC);
2756 }
2757
2758 static void __f2fs_restore_inmem_curseg(struct f2fs_sb_info *sbi, int type)
2759 {
2760         struct curseg_info *curseg = CURSEG_I(sbi, type);
2761
2762         mutex_lock(&curseg->curseg_mutex);
2763         if (!curseg->inited)
2764                 goto out;
2765         if (get_valid_blocks(sbi, curseg->segno, false))
2766                 goto out;
2767
2768         mutex_lock(&DIRTY_I(sbi)->seglist_lock);
2769         __set_test_and_inuse(sbi, curseg->segno);
2770         mutex_unlock(&DIRTY_I(sbi)->seglist_lock);
2771 out:
2772         mutex_unlock(&curseg->curseg_mutex);
2773 }
2774
2775 void f2fs_restore_inmem_curseg(struct f2fs_sb_info *sbi)
2776 {
2777         __f2fs_restore_inmem_curseg(sbi, CURSEG_COLD_DATA_PINNED);
2778
2779         if (sbi->am.atgc_enabled)
2780                 __f2fs_restore_inmem_curseg(sbi, CURSEG_ALL_DATA_ATGC);
2781 }
2782
2783 static int get_ssr_segment(struct f2fs_sb_info *sbi, int type,
2784                                 int alloc_mode, unsigned long long age)
2785 {
2786         struct curseg_info *curseg = CURSEG_I(sbi, type);
2787         const struct victim_selection *v_ops = DIRTY_I(sbi)->v_ops;
2788         unsigned segno = NULL_SEGNO;
2789         unsigned short seg_type = curseg->seg_type;
2790         int i, cnt;
2791         bool reversed = false;
2792
2793         sanity_check_seg_type(sbi, seg_type);
2794
2795         /* f2fs_need_SSR() already forces to do this */
2796         if (!v_ops->get_victim(sbi, &segno, BG_GC, seg_type, alloc_mode, age)) {
2797                 curseg->next_segno = segno;
2798                 return 1;
2799         }
2800
2801         /* For node segments, let's do SSR more intensively */
2802         if (IS_NODESEG(seg_type)) {
2803                 if (seg_type >= CURSEG_WARM_NODE) {
2804                         reversed = true;
2805                         i = CURSEG_COLD_NODE;
2806                 } else {
2807                         i = CURSEG_HOT_NODE;
2808                 }
2809                 cnt = NR_CURSEG_NODE_TYPE;
2810         } else {
2811                 if (seg_type >= CURSEG_WARM_DATA) {
2812                         reversed = true;
2813                         i = CURSEG_COLD_DATA;
2814                 } else {
2815                         i = CURSEG_HOT_DATA;
2816                 }
2817                 cnt = NR_CURSEG_DATA_TYPE;
2818         }
2819
2820         for (; cnt-- > 0; reversed ? i-- : i++) {
2821                 if (i == seg_type)
2822                         continue;
2823                 if (!v_ops->get_victim(sbi, &segno, BG_GC, i, alloc_mode, age)) {
2824                         curseg->next_segno = segno;
2825                         return 1;
2826                 }
2827         }
2828
2829         /* find valid_blocks=0 in dirty list */
2830         if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) {
2831                 segno = get_free_segment(sbi);
2832                 if (segno != NULL_SEGNO) {
2833                         curseg->next_segno = segno;
2834                         return 1;
2835                 }
2836         }
2837         return 0;
2838 }
2839
2840 /*
2841  * flush out current segment and replace it with new segment
2842  * This function should be returned with success, otherwise BUG
2843  */
2844 static void allocate_segment_by_default(struct f2fs_sb_info *sbi,
2845                                                 int type, bool force)
2846 {
2847         struct curseg_info *curseg = CURSEG_I(sbi, type);
2848
2849         if (force)
2850                 new_curseg(sbi, type, true);
2851         else if (!is_set_ckpt_flags(sbi, CP_CRC_RECOVERY_FLAG) &&
2852                                         curseg->seg_type == CURSEG_WARM_NODE)
2853                 new_curseg(sbi, type, false);
2854         else if (curseg->alloc_type == LFS &&
2855                         is_next_segment_free(sbi, curseg, type) &&
2856                         likely(!is_sbi_flag_set(sbi, SBI_CP_DISABLED)))
2857                 new_curseg(sbi, type, false);
2858         else if (f2fs_need_SSR(sbi) &&
2859                         get_ssr_segment(sbi, type, SSR, 0))
2860                 change_curseg(sbi, type, true);
2861         else
2862                 new_curseg(sbi, type, false);
2863
2864         stat_inc_seg_type(sbi, curseg);
2865 }
2866
2867 void f2fs_allocate_segment_for_resize(struct f2fs_sb_info *sbi, int type,
2868                                         unsigned int start, unsigned int end)
2869 {
2870         struct curseg_info *curseg = CURSEG_I(sbi, type);
2871         unsigned int segno;
2872
2873         f2fs_down_read(&SM_I(sbi)->curseg_lock);
2874         mutex_lock(&curseg->curseg_mutex);
2875         down_write(&SIT_I(sbi)->sentry_lock);
2876
2877         segno = CURSEG_I(sbi, type)->segno;
2878         if (segno < start || segno > end)
2879                 goto unlock;
2880
2881         if (f2fs_need_SSR(sbi) && get_ssr_segment(sbi, type, SSR, 0))
2882                 change_curseg(sbi, type, true);
2883         else
2884                 new_curseg(sbi, type, true);
2885
2886         stat_inc_seg_type(sbi, curseg);
2887
2888         locate_dirty_segment(sbi, segno);
2889 unlock:
2890         up_write(&SIT_I(sbi)->sentry_lock);
2891
2892         if (segno != curseg->segno)
2893                 f2fs_notice(sbi, "For resize: curseg of type %d: %u ==> %u",
2894                             type, segno, curseg->segno);
2895
2896         mutex_unlock(&curseg->curseg_mutex);
2897         f2fs_up_read(&SM_I(sbi)->curseg_lock);
2898 }
2899
2900 static void __allocate_new_segment(struct f2fs_sb_info *sbi, int type,
2901                                                 bool new_sec, bool force)
2902 {
2903         struct curseg_info *curseg = CURSEG_I(sbi, type);
2904         unsigned int old_segno;
2905
2906         if (!curseg->inited)
2907                 goto alloc;
2908
2909         if (force || curseg->next_blkoff ||
2910                 get_valid_blocks(sbi, curseg->segno, new_sec))
2911                 goto alloc;
2912
2913         if (!get_ckpt_valid_blocks(sbi, curseg->segno, new_sec))
2914                 return;
2915 alloc:
2916         old_segno = curseg->segno;
2917         SIT_I(sbi)->s_ops->allocate_segment(sbi, type, true);
2918         locate_dirty_segment(sbi, old_segno);
2919 }
2920
2921 static void __allocate_new_section(struct f2fs_sb_info *sbi,
2922                                                 int type, bool force)
2923 {
2924         __allocate_new_segment(sbi, type, true, force);
2925 }
2926
2927 void f2fs_allocate_new_section(struct f2fs_sb_info *sbi, int type, bool force)
2928 {
2929         f2fs_down_read(&SM_I(sbi)->curseg_lock);
2930         down_write(&SIT_I(sbi)->sentry_lock);
2931         __allocate_new_section(sbi, type, force);
2932         up_write(&SIT_I(sbi)->sentry_lock);
2933         f2fs_up_read(&SM_I(sbi)->curseg_lock);
2934 }
2935
2936 void f2fs_allocate_new_segments(struct f2fs_sb_info *sbi)
2937 {
2938         int i;
2939
2940         f2fs_down_read(&SM_I(sbi)->curseg_lock);
2941         down_write(&SIT_I(sbi)->sentry_lock);
2942         for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++)
2943                 __allocate_new_segment(sbi, i, false, false);
2944         up_write(&SIT_I(sbi)->sentry_lock);
2945         f2fs_up_read(&SM_I(sbi)->curseg_lock);
2946 }
2947
2948 static const struct segment_allocation default_salloc_ops = {
2949         .allocate_segment = allocate_segment_by_default,
2950 };
2951
2952 bool f2fs_exist_trim_candidates(struct f2fs_sb_info *sbi,
2953                                                 struct cp_control *cpc)
2954 {
2955         __u64 trim_start = cpc->trim_start;
2956         bool has_candidate = false;
2957
2958         down_write(&SIT_I(sbi)->sentry_lock);
2959         for (; cpc->trim_start <= cpc->trim_end; cpc->trim_start++) {
2960                 if (add_discard_addrs(sbi, cpc, true)) {
2961                         has_candidate = true;
2962                         break;
2963                 }
2964         }
2965         up_write(&SIT_I(sbi)->sentry_lock);
2966
2967         cpc->trim_start = trim_start;
2968         return has_candidate;
2969 }
2970
2971 static unsigned int __issue_discard_cmd_range(struct f2fs_sb_info *sbi,
2972                                         struct discard_policy *dpolicy,
2973                                         unsigned int start, unsigned int end)
2974 {
2975         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
2976         struct discard_cmd *prev_dc = NULL, *next_dc = NULL;
2977         struct rb_node **insert_p = NULL, *insert_parent = NULL;
2978         struct discard_cmd *dc;
2979         struct blk_plug plug;
2980         int issued;
2981         unsigned int trimmed = 0;
2982
2983 next:
2984         issued = 0;
2985
2986         mutex_lock(&dcc->cmd_lock);
2987         if (unlikely(dcc->rbtree_check))
2988                 f2fs_bug_on(sbi, !f2fs_check_rb_tree_consistence(sbi,
2989                                                         &dcc->root, false));
2990
2991         dc = (struct discard_cmd *)f2fs_lookup_rb_tree_ret(&dcc->root,
2992                                         NULL, start,
2993                                         (struct rb_entry **)&prev_dc,
2994                                         (struct rb_entry **)&next_dc,
2995                                         &insert_p, &insert_parent, true, NULL);
2996         if (!dc)
2997                 dc = next_dc;
2998
2999         blk_start_plug(&plug);
3000
3001         while (dc && dc->lstart <= end) {
3002                 struct rb_node *node;
3003                 int err = 0;
3004
3005                 if (dc->len < dpolicy->granularity)
3006                         goto skip;
3007
3008                 if (dc->state != D_PREP) {
3009                         list_move_tail(&dc->list, &dcc->fstrim_list);
3010                         goto skip;
3011                 }
3012
3013                 err = __submit_discard_cmd(sbi, dpolicy, dc, &issued);
3014
3015                 if (issued >= dpolicy->max_requests) {
3016                         start = dc->lstart + dc->len;
3017
3018                         if (err)
3019                                 __remove_discard_cmd(sbi, dc);
3020
3021                         blk_finish_plug(&plug);
3022                         mutex_unlock(&dcc->cmd_lock);
3023                         trimmed += __wait_all_discard_cmd(sbi, NULL);
3024                         f2fs_io_schedule_timeout(DEFAULT_IO_TIMEOUT);
3025                         goto next;
3026                 }
3027 skip:
3028                 node = rb_next(&dc->rb_node);
3029                 if (err)
3030                         __remove_discard_cmd(sbi, dc);
3031                 dc = rb_entry_safe(node, struct discard_cmd, rb_node);
3032
3033                 if (fatal_signal_pending(current))
3034                         break;
3035         }
3036
3037         blk_finish_plug(&plug);
3038         mutex_unlock(&dcc->cmd_lock);
3039
3040         return trimmed;
3041 }
3042
3043 int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range)
3044 {
3045         __u64 start = F2FS_BYTES_TO_BLK(range->start);
3046         __u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1;
3047         unsigned int start_segno, end_segno;
3048         block_t start_block, end_block;
3049         struct cp_control cpc;
3050         struct discard_policy dpolicy;
3051         unsigned long long trimmed = 0;
3052         int err = 0;
3053         bool need_align = f2fs_lfs_mode(sbi) && __is_large_section(sbi);
3054
3055         if (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize)
3056                 return -EINVAL;
3057
3058         if (end < MAIN_BLKADDR(sbi))
3059                 goto out;
3060
3061         if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) {
3062                 f2fs_warn(sbi, "Found FS corruption, run fsck to fix.");
3063                 return -EFSCORRUPTED;
3064         }
3065
3066         /* start/end segment number in main_area */
3067         start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start);
3068         end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 :
3069                                                 GET_SEGNO(sbi, end);
3070         if (need_align) {
3071                 start_segno = rounddown(start_segno, sbi->segs_per_sec);
3072                 end_segno = roundup(end_segno + 1, sbi->segs_per_sec) - 1;
3073         }
3074
3075         cpc.reason = CP_DISCARD;
3076         cpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen));
3077         cpc.trim_start = start_segno;
3078         cpc.trim_end = end_segno;
3079
3080         if (sbi->discard_blks == 0)
3081                 goto out;
3082
3083         f2fs_down_write(&sbi->gc_lock);
3084         err = f2fs_write_checkpoint(sbi, &cpc);
3085         f2fs_up_write(&sbi->gc_lock);
3086         if (err)
3087                 goto out;
3088
3089         /*
3090          * We filed discard candidates, but actually we don't need to wait for
3091          * all of them, since they'll be issued in idle time along with runtime
3092          * discard option. User configuration looks like using runtime discard
3093          * or periodic fstrim instead of it.
3094          */
3095         if (f2fs_realtime_discard_enable(sbi))
3096                 goto out;
3097
3098         start_block = START_BLOCK(sbi, start_segno);
3099         end_block = START_BLOCK(sbi, end_segno + 1);
3100
3101         __init_discard_policy(sbi, &dpolicy, DPOLICY_FSTRIM, cpc.trim_minlen);
3102         trimmed = __issue_discard_cmd_range(sbi, &dpolicy,
3103                                         start_block, end_block);
3104
3105         trimmed += __wait_discard_cmd_range(sbi, &dpolicy,
3106                                         start_block, end_block);
3107 out:
3108         if (!err)
3109                 range->len = F2FS_BLK_TO_BYTES(trimmed);
3110         return err;
3111 }
3112
3113 static bool __has_curseg_space(struct f2fs_sb_info *sbi,
3114                                         struct curseg_info *curseg)
3115 {
3116         return curseg->next_blkoff < f2fs_usable_blks_in_seg(sbi,
3117                                                         curseg->segno);
3118 }
3119
3120 int f2fs_rw_hint_to_seg_type(enum rw_hint hint)
3121 {
3122         switch (hint) {
3123         case WRITE_LIFE_SHORT:
3124                 return CURSEG_HOT_DATA;
3125         case WRITE_LIFE_EXTREME:
3126                 return CURSEG_COLD_DATA;
3127         default:
3128                 return CURSEG_WARM_DATA;
3129         }
3130 }
3131
3132 static int __get_segment_type_2(struct f2fs_io_info *fio)
3133 {
3134         if (fio->type == DATA)
3135                 return CURSEG_HOT_DATA;
3136         else
3137                 return CURSEG_HOT_NODE;
3138 }
3139
3140 static int __get_segment_type_4(struct f2fs_io_info *fio)
3141 {
3142         if (fio->type == DATA) {
3143                 struct inode *inode = fio->page->mapping->host;
3144
3145                 if (S_ISDIR(inode->i_mode))
3146                         return CURSEG_HOT_DATA;
3147                 else
3148                         return CURSEG_COLD_DATA;
3149         } else {
3150                 if (IS_DNODE(fio->page) && is_cold_node(fio->page))
3151                         return CURSEG_WARM_NODE;
3152                 else
3153                         return CURSEG_COLD_NODE;
3154         }
3155 }
3156
3157 static int __get_segment_type_6(struct f2fs_io_info *fio)
3158 {
3159         if (fio->type == DATA) {
3160                 struct inode *inode = fio->page->mapping->host;
3161
3162                 if (is_inode_flag_set(inode, FI_ALIGNED_WRITE))
3163                         return CURSEG_COLD_DATA_PINNED;
3164
3165                 if (page_private_gcing(fio->page)) {
3166                         if (fio->sbi->am.atgc_enabled &&
3167                                 (fio->io_type == FS_DATA_IO) &&
3168                                 (fio->sbi->gc_mode != GC_URGENT_HIGH))
3169                                 return CURSEG_ALL_DATA_ATGC;
3170                         else
3171                                 return CURSEG_COLD_DATA;
3172                 }
3173                 if (file_is_cold(inode) || f2fs_need_compress_data(inode))
3174                         return CURSEG_COLD_DATA;
3175                 if (file_is_hot(inode) ||
3176                                 is_inode_flag_set(inode, FI_HOT_DATA) ||
3177                                 f2fs_is_cow_file(inode))
3178                         return CURSEG_HOT_DATA;
3179                 return f2fs_rw_hint_to_seg_type(inode->i_write_hint);
3180         } else {
3181                 if (IS_DNODE(fio->page))
3182                         return is_cold_node(fio->page) ? CURSEG_WARM_NODE :
3183                                                 CURSEG_HOT_NODE;
3184                 return CURSEG_COLD_NODE;
3185         }
3186 }
3187
3188 static int __get_segment_type(struct f2fs_io_info *fio)
3189 {
3190         int type = 0;
3191
3192         switch (F2FS_OPTION(fio->sbi).active_logs) {
3193         case 2:
3194                 type = __get_segment_type_2(fio);
3195                 break;
3196         case 4:
3197                 type = __get_segment_type_4(fio);
3198                 break;
3199         case 6:
3200                 type = __get_segment_type_6(fio);
3201                 break;
3202         default:
3203                 f2fs_bug_on(fio->sbi, true);
3204         }
3205
3206         if (IS_HOT(type))
3207                 fio->temp = HOT;
3208         else if (IS_WARM(type))
3209                 fio->temp = WARM;
3210         else
3211                 fio->temp = COLD;
3212         return type;
3213 }
3214
3215 void f2fs_allocate_data_block(struct f2fs_sb_info *sbi, struct page *page,
3216                 block_t old_blkaddr, block_t *new_blkaddr,
3217                 struct f2fs_summary *sum, int type,
3218                 struct f2fs_io_info *fio)
3219 {
3220         struct sit_info *sit_i = SIT_I(sbi);
3221         struct curseg_info *curseg = CURSEG_I(sbi, type);
3222         unsigned long long old_mtime;
3223         bool from_gc = (type == CURSEG_ALL_DATA_ATGC);
3224         struct seg_entry *se = NULL;
3225
3226         f2fs_down_read(&SM_I(sbi)->curseg_lock);
3227
3228         mutex_lock(&curseg->curseg_mutex);
3229         down_write(&sit_i->sentry_lock);
3230
3231         if (from_gc) {
3232                 f2fs_bug_on(sbi, GET_SEGNO(sbi, old_blkaddr) == NULL_SEGNO);
3233                 se = get_seg_entry(sbi, GET_SEGNO(sbi, old_blkaddr));
3234                 sanity_check_seg_type(sbi, se->type);
3235                 f2fs_bug_on(sbi, IS_NODESEG(se->type));
3236         }
3237         *new_blkaddr = NEXT_FREE_BLKADDR(sbi, curseg);
3238
3239         f2fs_bug_on(sbi, curseg->next_blkoff >= sbi->blocks_per_seg);
3240
3241         f2fs_wait_discard_bio(sbi, *new_blkaddr);
3242
3243         /*
3244          * __add_sum_entry should be resided under the curseg_mutex
3245          * because, this function updates a summary entry in the
3246          * current summary block.
3247          */
3248         __add_sum_entry(sbi, type, sum);
3249
3250         __refresh_next_blkoff(sbi, curseg);
3251
3252         stat_inc_block_count(sbi, curseg);
3253
3254         if (from_gc) {
3255                 old_mtime = get_segment_mtime(sbi, old_blkaddr);
3256         } else {
3257                 update_segment_mtime(sbi, old_blkaddr, 0);
3258                 old_mtime = 0;
3259         }
3260         update_segment_mtime(sbi, *new_blkaddr, old_mtime);
3261
3262         /*
3263          * SIT information should be updated before segment allocation,
3264          * since SSR needs latest valid block information.
3265          */
3266         update_sit_entry(sbi, *new_blkaddr, 1);
3267         if (GET_SEGNO(sbi, old_blkaddr) != NULL_SEGNO)
3268                 update_sit_entry(sbi, old_blkaddr, -1);
3269
3270         if (!__has_curseg_space(sbi, curseg)) {
3271                 if (from_gc)
3272                         get_atssr_segment(sbi, type, se->type,
3273                                                 AT_SSR, se->mtime);
3274                 else
3275                         sit_i->s_ops->allocate_segment(sbi, type, false);
3276         }
3277         /*
3278          * segment dirty status should be updated after segment allocation,
3279          * so we just need to update status only one time after previous
3280          * segment being closed.
3281          */
3282         locate_dirty_segment(sbi, GET_SEGNO(sbi, old_blkaddr));
3283         locate_dirty_segment(sbi, GET_SEGNO(sbi, *new_blkaddr));
3284
3285         up_write(&sit_i->sentry_lock);
3286
3287         if (page && IS_NODESEG(type)) {
3288                 fill_node_footer_blkaddr(page, NEXT_FREE_BLKADDR(sbi, curseg));
3289
3290                 f2fs_inode_chksum_set(sbi, page);
3291         }
3292
3293         if (fio) {
3294                 struct f2fs_bio_info *io;
3295
3296                 if (F2FS_IO_ALIGNED(sbi))
3297                         fio->retry = false;
3298
3299                 INIT_LIST_HEAD(&fio->list);
3300                 fio->in_list = true;
3301                 io = sbi->write_io[fio->type] + fio->temp;
3302                 spin_lock(&io->io_lock);
3303                 list_add_tail(&fio->list, &io->io_list);
3304                 spin_unlock(&io->io_lock);
3305         }
3306
3307         mutex_unlock(&curseg->curseg_mutex);
3308
3309         f2fs_up_read(&SM_I(sbi)->curseg_lock);
3310 }
3311
3312 void f2fs_update_device_state(struct f2fs_sb_info *sbi, nid_t ino,
3313                                         block_t blkaddr, unsigned int blkcnt)
3314 {
3315         if (!f2fs_is_multi_device(sbi))
3316                 return;
3317
3318         while (1) {
3319                 unsigned int devidx = f2fs_target_device_index(sbi, blkaddr);
3320                 unsigned int blks = FDEV(devidx).end_blk - blkaddr + 1;
3321
3322                 /* update device state for fsync */
3323                 f2fs_set_dirty_device(sbi, ino, devidx, FLUSH_INO);
3324
3325                 /* update device state for checkpoint */
3326                 if (!f2fs_test_bit(devidx, (char *)&sbi->dirty_device)) {
3327                         spin_lock(&sbi->dev_lock);
3328                         f2fs_set_bit(devidx, (char *)&sbi->dirty_device);
3329                         spin_unlock(&sbi->dev_lock);
3330                 }
3331
3332                 if (blkcnt <= blks)
3333                         break;
3334                 blkcnt -= blks;
3335                 blkaddr += blks;
3336         }
3337 }
3338
3339 static void do_write_page(struct f2fs_summary *sum, struct f2fs_io_info *fio)
3340 {
3341         int type = __get_segment_type(fio);
3342         bool keep_order = (f2fs_lfs_mode(fio->sbi) && type == CURSEG_COLD_DATA);
3343
3344         if (keep_order)
3345                 f2fs_down_read(&fio->sbi->io_order_lock);
3346 reallocate:
3347         f2fs_allocate_data_block(fio->sbi, fio->page, fio->old_blkaddr,
3348                         &fio->new_blkaddr, sum, type, fio);
3349         if (GET_SEGNO(fio->sbi, fio->old_blkaddr) != NULL_SEGNO) {
3350                 invalidate_mapping_pages(META_MAPPING(fio->sbi),
3351                                         fio->old_blkaddr, fio->old_blkaddr);
3352                 f2fs_invalidate_compress_page(fio->sbi, fio->old_blkaddr);
3353         }
3354
3355         /* writeout dirty page into bdev */
3356         f2fs_submit_page_write(fio);
3357         if (fio->retry) {
3358                 fio->old_blkaddr = fio->new_blkaddr;
3359                 goto reallocate;
3360         }
3361
3362         f2fs_update_device_state(fio->sbi, fio->ino, fio->new_blkaddr, 1);
3363
3364         if (keep_order)
3365                 f2fs_up_read(&fio->sbi->io_order_lock);
3366 }
3367
3368 void f2fs_do_write_meta_page(struct f2fs_sb_info *sbi, struct page *page,
3369                                         enum iostat_type io_type)
3370 {
3371         struct f2fs_io_info fio = {
3372                 .sbi = sbi,
3373                 .type = META,
3374                 .temp = HOT,
3375                 .op = REQ_OP_WRITE,
3376                 .op_flags = REQ_SYNC | REQ_META | REQ_PRIO,
3377                 .old_blkaddr = page->index,
3378                 .new_blkaddr = page->index,
3379                 .page = page,
3380                 .encrypted_page = NULL,
3381                 .in_list = false,
3382         };
3383
3384         if (unlikely(page->index >= MAIN_BLKADDR(sbi)))
3385                 fio.op_flags &= ~REQ_META;
3386
3387         set_page_writeback(page);
3388         ClearPageError(page);
3389         f2fs_submit_page_write(&fio);
3390
3391         stat_inc_meta_count(sbi, page->index);
3392         f2fs_update_iostat(sbi, NULL, io_type, F2FS_BLKSIZE);
3393 }
3394
3395 void f2fs_do_write_node_page(unsigned int nid, struct f2fs_io_info *fio)
3396 {
3397         struct f2fs_summary sum;
3398
3399         set_summary(&sum, nid, 0, 0);
3400         do_write_page(&sum, fio);
3401
3402         f2fs_update_iostat(fio->sbi, NULL, fio->io_type, F2FS_BLKSIZE);
3403 }
3404
3405 void f2fs_outplace_write_data(struct dnode_of_data *dn,
3406                                         struct f2fs_io_info *fio)
3407 {
3408         struct f2fs_sb_info *sbi = fio->sbi;
3409         struct f2fs_summary sum;
3410
3411         f2fs_bug_on(sbi, dn->data_blkaddr == NULL_ADDR);
3412         set_summary(&sum, dn->nid, dn->ofs_in_node, fio->version);
3413         do_write_page(&sum, fio);
3414         f2fs_update_data_blkaddr(dn, fio->new_blkaddr);
3415
3416         f2fs_update_iostat(sbi, dn->inode, fio->io_type, F2FS_BLKSIZE);
3417 }
3418
3419 int f2fs_inplace_write_data(struct f2fs_io_info *fio)
3420 {
3421         int err;
3422         struct f2fs_sb_info *sbi = fio->sbi;
3423         unsigned int segno;
3424
3425         fio->new_blkaddr = fio->old_blkaddr;
3426         /* i/o temperature is needed for passing down write hints */
3427         __get_segment_type(fio);
3428
3429         segno = GET_SEGNO(sbi, fio->new_blkaddr);
3430
3431         if (!IS_DATASEG(get_seg_entry(sbi, segno)->type)) {
3432                 set_sbi_flag(sbi, SBI_NEED_FSCK);
3433                 f2fs_warn(sbi, "%s: incorrect segment(%u) type, run fsck to fix.",
3434                           __func__, segno);
3435                 err = -EFSCORRUPTED;
3436                 f2fs_handle_error(sbi, ERROR_INCONSISTENT_SUM_TYPE);
3437                 goto drop_bio;
3438         }
3439
3440         if (f2fs_cp_error(sbi)) {
3441                 err = -EIO;
3442                 goto drop_bio;
3443         }
3444
3445         if (fio->post_read)
3446                 invalidate_mapping_pages(META_MAPPING(sbi),
3447                                 fio->new_blkaddr, fio->new_blkaddr);
3448
3449         stat_inc_inplace_blocks(fio->sbi);
3450
3451         if (fio->bio && !(SM_I(sbi)->ipu_policy & (1 << F2FS_IPU_NOCACHE)))
3452                 err = f2fs_merge_page_bio(fio);
3453         else
3454                 err = f2fs_submit_page_bio(fio);
3455         if (!err) {
3456                 f2fs_update_device_state(fio->sbi, fio->ino,
3457                                                 fio->new_blkaddr, 1);
3458                 f2fs_update_iostat(fio->sbi, fio->page->mapping->host,
3459                                                 fio->io_type, F2FS_BLKSIZE);
3460         }
3461
3462         return err;
3463 drop_bio:
3464         if (fio->bio && *(fio->bio)) {
3465                 struct bio *bio = *(fio->bio);
3466
3467                 bio->bi_status = BLK_STS_IOERR;
3468                 bio_endio(bio);
3469                 *(fio->bio) = NULL;
3470         }
3471         return err;
3472 }
3473
3474 static inline int __f2fs_get_curseg(struct f2fs_sb_info *sbi,
3475                                                 unsigned int segno)
3476 {
3477         int i;
3478
3479         for (i = CURSEG_HOT_DATA; i < NO_CHECK_TYPE; i++) {
3480                 if (CURSEG_I(sbi, i)->segno == segno)
3481                         break;
3482         }
3483         return i;
3484 }
3485
3486 void f2fs_do_replace_block(struct f2fs_sb_info *sbi, struct f2fs_summary *sum,
3487                                 block_t old_blkaddr, block_t new_blkaddr,
3488                                 bool recover_curseg, bool recover_newaddr,
3489                                 bool from_gc)
3490 {
3491         struct sit_info *sit_i = SIT_I(sbi);
3492         struct curseg_info *curseg;
3493         unsigned int segno, old_cursegno;
3494         struct seg_entry *se;
3495         int type;
3496         unsigned short old_blkoff;
3497         unsigned char old_alloc_type;
3498
3499         segno = GET_SEGNO(sbi, new_blkaddr);
3500         se = get_seg_entry(sbi, segno);
3501         type = se->type;
3502
3503         f2fs_down_write(&SM_I(sbi)->curseg_lock);
3504
3505         if (!recover_curseg) {
3506                 /* for recovery flow */
3507                 if (se->valid_blocks == 0 && !IS_CURSEG(sbi, segno)) {
3508                         if (old_blkaddr == NULL_ADDR)
3509                                 type = CURSEG_COLD_DATA;
3510                         else
3511                                 type = CURSEG_WARM_DATA;
3512                 }
3513         } else {
3514                 if (IS_CURSEG(sbi, segno)) {
3515                         /* se->type is volatile as SSR allocation */
3516                         type = __f2fs_get_curseg(sbi, segno);
3517                         f2fs_bug_on(sbi, type == NO_CHECK_TYPE);
3518                 } else {
3519                         type = CURSEG_WARM_DATA;
3520                 }
3521         }
3522
3523         f2fs_bug_on(sbi, !IS_DATASEG(type));
3524         curseg = CURSEG_I(sbi, type);
3525
3526         mutex_lock(&curseg->curseg_mutex);
3527         down_write(&sit_i->sentry_lock);
3528
3529         old_cursegno = curseg->segno;
3530         old_blkoff = curseg->next_blkoff;
3531         old_alloc_type = curseg->alloc_type;
3532
3533         /* change the current segment */
3534         if (segno != curseg->segno) {
3535                 curseg->next_segno = segno;
3536                 change_curseg(sbi, type, true);
3537         }
3538
3539         curseg->next_blkoff = GET_BLKOFF_FROM_SEG0(sbi, new_blkaddr);
3540         __add_sum_entry(sbi, type, sum);
3541
3542         if (!recover_curseg || recover_newaddr) {
3543                 if (!from_gc)
3544                         update_segment_mtime(sbi, new_blkaddr, 0);
3545                 update_sit_entry(sbi, new_blkaddr, 1);
3546         }
3547         if (GET_SEGNO(sbi, old_blkaddr) != NULL_SEGNO) {
3548                 invalidate_mapping_pages(META_MAPPING(sbi),
3549                                         old_blkaddr, old_blkaddr);
3550                 f2fs_invalidate_compress_page(sbi, old_blkaddr);
3551                 if (!from_gc)
3552                         update_segment_mtime(sbi, old_blkaddr, 0);
3553                 update_sit_entry(sbi, old_blkaddr, -1);
3554         }
3555
3556         locate_dirty_segment(sbi, GET_SEGNO(sbi, old_blkaddr));
3557         locate_dirty_segment(sbi, GET_SEGNO(sbi, new_blkaddr));
3558
3559         locate_dirty_segment(sbi, old_cursegno);
3560
3561         if (recover_curseg) {
3562                 if (old_cursegno != curseg->segno) {
3563                         curseg->next_segno = old_cursegno;
3564                         change_curseg(sbi, type, true);
3565                 }
3566                 curseg->next_blkoff = old_blkoff;
3567                 curseg->alloc_type = old_alloc_type;
3568         }
3569
3570         up_write(&sit_i->sentry_lock);
3571         mutex_unlock(&curseg->curseg_mutex);
3572         f2fs_up_write(&SM_I(sbi)->curseg_lock);
3573 }
3574
3575 void f2fs_replace_block(struct f2fs_sb_info *sbi, struct dnode_of_data *dn,
3576                                 block_t old_addr, block_t new_addr,
3577                                 unsigned char version, bool recover_curseg,
3578                                 bool recover_newaddr)
3579 {
3580         struct f2fs_summary sum;
3581
3582         set_summary(&sum, dn->nid, dn->ofs_in_node, version);
3583
3584         f2fs_do_replace_block(sbi, &sum, old_addr, new_addr,
3585                                         recover_curseg, recover_newaddr, false);
3586
3587         f2fs_update_data_blkaddr(dn, new_addr);
3588 }
3589
3590 void f2fs_wait_on_page_writeback(struct page *page,
3591                                 enum page_type type, bool ordered, bool locked)
3592 {
3593         if (PageWriteback(page)) {
3594                 struct f2fs_sb_info *sbi = F2FS_P_SB(page);
3595
3596                 /* submit cached LFS IO */
3597                 f2fs_submit_merged_write_cond(sbi, NULL, page, 0, type);
3598                 /* sbumit cached IPU IO */
3599                 f2fs_submit_merged_ipu_write(sbi, NULL, page);
3600                 if (ordered) {
3601                         wait_on_page_writeback(page);
3602                         f2fs_bug_on(sbi, locked && PageWriteback(page));
3603                 } else {
3604                         wait_for_stable_page(page);
3605                 }
3606         }
3607 }
3608
3609 void f2fs_wait_on_block_writeback(struct inode *inode, block_t blkaddr)
3610 {
3611         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3612         struct page *cpage;
3613
3614         if (!f2fs_post_read_required(inode))
3615                 return;
3616
3617         if (!__is_valid_data_blkaddr(blkaddr))
3618                 return;
3619
3620         cpage = find_lock_page(META_MAPPING(sbi), blkaddr);
3621         if (cpage) {
3622                 f2fs_wait_on_page_writeback(cpage, DATA, true, true);
3623                 f2fs_put_page(cpage, 1);
3624         }
3625 }
3626
3627 void f2fs_wait_on_block_writeback_range(struct inode *inode, block_t blkaddr,
3628                                                                 block_t len)
3629 {
3630         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3631         block_t i;
3632
3633         if (!f2fs_post_read_required(inode))
3634                 return;
3635
3636         for (i = 0; i < len; i++)
3637                 f2fs_wait_on_block_writeback(inode, blkaddr + i);
3638
3639         invalidate_mapping_pages(META_MAPPING(sbi), blkaddr, blkaddr + len - 1);
3640 }
3641
3642 static int read_compacted_summaries(struct f2fs_sb_info *sbi)
3643 {
3644         struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
3645         struct curseg_info *seg_i;
3646         unsigned char *kaddr;
3647         struct page *page;
3648         block_t start;
3649         int i, j, offset;
3650
3651         start = start_sum_block(sbi);
3652
3653         page = f2fs_get_meta_page(sbi, start++);
3654         if (IS_ERR(page))
3655                 return PTR_ERR(page);
3656         kaddr = (unsigned char *)page_address(page);
3657
3658         /* Step 1: restore nat cache */
3659         seg_i = CURSEG_I(sbi, CURSEG_HOT_DATA);
3660         memcpy(seg_i->journal, kaddr, SUM_JOURNAL_SIZE);
3661
3662         /* Step 2: restore sit cache */
3663         seg_i = CURSEG_I(sbi, CURSEG_COLD_DATA);
3664         memcpy(seg_i->journal, kaddr + SUM_JOURNAL_SIZE, SUM_JOURNAL_SIZE);
3665         offset = 2 * SUM_JOURNAL_SIZE;
3666
3667         /* Step 3: restore summary entries */
3668         for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
3669                 unsigned short blk_off;
3670                 unsigned int segno;
3671
3672                 seg_i = CURSEG_I(sbi, i);
3673                 segno = le32_to_cpu(ckpt->cur_data_segno[i]);
3674                 blk_off = le16_to_cpu(ckpt->cur_data_blkoff[i]);
3675                 seg_i->next_segno = segno;
3676                 reset_curseg(sbi, i, 0);
3677                 seg_i->alloc_type = ckpt->alloc_type[i];
3678                 seg_i->next_blkoff = blk_off;
3679
3680                 if (seg_i->alloc_type == SSR)
3681                         blk_off = sbi->blocks_per_seg;
3682
3683                 for (j = 0; j < blk_off; j++) {
3684                         struct f2fs_summary *s;
3685
3686                         s = (struct f2fs_summary *)(kaddr + offset);
3687                         seg_i->sum_blk->entries[j] = *s;
3688                         offset += SUMMARY_SIZE;
3689                         if (offset + SUMMARY_SIZE <= PAGE_SIZE -
3690                                                 SUM_FOOTER_SIZE)
3691                                 continue;
3692
3693                         f2fs_put_page(page, 1);
3694                         page = NULL;
3695
3696                         page = f2fs_get_meta_page(sbi, start++);
3697                         if (IS_ERR(page))
3698                                 return PTR_ERR(page);
3699                         kaddr = (unsigned char *)page_address(page);
3700                         offset = 0;
3701                 }
3702         }
3703         f2fs_put_page(page, 1);
3704         return 0;
3705 }
3706
3707 static int read_normal_summaries(struct f2fs_sb_info *sbi, int type)
3708 {
3709         struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
3710         struct f2fs_summary_block *sum;
3711         struct curseg_info *curseg;
3712         struct page *new;
3713         unsigned short blk_off;
3714         unsigned int segno = 0;
3715         block_t blk_addr = 0;
3716         int err = 0;
3717
3718         /* get segment number and block addr */
3719         if (IS_DATASEG(type)) {
3720                 segno = le32_to_cpu(ckpt->cur_data_segno[type]);
3721                 blk_off = le16_to_cpu(ckpt->cur_data_blkoff[type -
3722                                                         CURSEG_HOT_DATA]);
3723                 if (__exist_node_summaries(sbi))
3724                         blk_addr = sum_blk_addr(sbi, NR_CURSEG_PERSIST_TYPE, type);
3725                 else
3726                         blk_addr = sum_blk_addr(sbi, NR_CURSEG_DATA_TYPE, type);
3727         } else {
3728                 segno = le32_to_cpu(ckpt->cur_node_segno[type -
3729                                                         CURSEG_HOT_NODE]);
3730                 blk_off = le16_to_cpu(ckpt->cur_node_blkoff[type -
3731                                                         CURSEG_HOT_NODE]);
3732                 if (__exist_node_summaries(sbi))
3733                         blk_addr = sum_blk_addr(sbi, NR_CURSEG_NODE_TYPE,
3734                                                         type - CURSEG_HOT_NODE);
3735                 else
3736                         blk_addr = GET_SUM_BLOCK(sbi, segno);
3737         }
3738
3739         new = f2fs_get_meta_page(sbi, blk_addr);
3740         if (IS_ERR(new))
3741                 return PTR_ERR(new);
3742         sum = (struct f2fs_summary_block *)page_address(new);
3743
3744         if (IS_NODESEG(type)) {
3745                 if (__exist_node_summaries(sbi)) {
3746                         struct f2fs_summary *ns = &sum->entries[0];
3747                         int i;
3748
3749                         for (i = 0; i < sbi->blocks_per_seg; i++, ns++) {
3750                                 ns->version = 0;
3751                                 ns->ofs_in_node = 0;
3752                         }
3753                 } else {
3754                         err = f2fs_restore_node_summary(sbi, segno, sum);
3755                         if (err)
3756                                 goto out;
3757                 }
3758         }
3759
3760         /* set uncompleted segment to curseg */
3761         curseg = CURSEG_I(sbi, type);
3762         mutex_lock(&curseg->curseg_mutex);
3763
3764         /* update journal info */
3765         down_write(&curseg->journal_rwsem);
3766         memcpy(curseg->journal, &sum->journal, SUM_JOURNAL_SIZE);
3767         up_write(&curseg->journal_rwsem);
3768
3769         memcpy(curseg->sum_blk->entries, sum->entries, SUM_ENTRY_SIZE);
3770         memcpy(&curseg->sum_blk->footer, &sum->footer, SUM_FOOTER_SIZE);
3771         curseg->next_segno = segno;
3772         reset_curseg(sbi, type, 0);
3773         curseg->alloc_type = ckpt->alloc_type[type];
3774         curseg->next_blkoff = blk_off;
3775         mutex_unlock(&curseg->curseg_mutex);
3776 out:
3777         f2fs_put_page(new, 1);
3778         return err;
3779 }
3780
3781 static int restore_curseg_summaries(struct f2fs_sb_info *sbi)
3782 {
3783         struct f2fs_journal *sit_j = CURSEG_I(sbi, CURSEG_COLD_DATA)->journal;
3784         struct f2fs_journal *nat_j = CURSEG_I(sbi, CURSEG_HOT_DATA)->journal;
3785         int type = CURSEG_HOT_DATA;
3786         int err;
3787
3788         if (is_set_ckpt_flags(sbi, CP_COMPACT_SUM_FLAG)) {
3789                 int npages = f2fs_npages_for_summary_flush(sbi, true);
3790
3791                 if (npages >= 2)
3792                         f2fs_ra_meta_pages(sbi, start_sum_block(sbi), npages,
3793                                                         META_CP, true);
3794
3795                 /* restore for compacted data summary */
3796                 err = read_compacted_summaries(sbi);
3797                 if (err)
3798                         return err;
3799                 type = CURSEG_HOT_NODE;
3800         }
3801
3802         if (__exist_node_summaries(sbi))
3803                 f2fs_ra_meta_pages(sbi,
3804                                 sum_blk_addr(sbi, NR_CURSEG_PERSIST_TYPE, type),
3805                                 NR_CURSEG_PERSIST_TYPE - type, META_CP, true);
3806
3807         for (; type <= CURSEG_COLD_NODE; type++) {
3808                 err = read_normal_summaries(sbi, type);
3809                 if (err)
3810                         return err;
3811         }
3812
3813         /* sanity check for summary blocks */
3814         if (nats_in_cursum(nat_j) > NAT_JOURNAL_ENTRIES ||
3815                         sits_in_cursum(sit_j) > SIT_JOURNAL_ENTRIES) {
3816                 f2fs_err(sbi, "invalid journal entries nats %u sits %u",
3817                          nats_in_cursum(nat_j), sits_in_cursum(sit_j));
3818                 return -EINVAL;
3819         }
3820
3821         return 0;
3822 }
3823
3824 static void write_compacted_summaries(struct f2fs_sb_info *sbi, block_t blkaddr)
3825 {
3826         struct page *page;
3827         unsigned char *kaddr;
3828         struct f2fs_summary *summary;
3829         struct curseg_info *seg_i;
3830         int written_size = 0;
3831         int i, j;
3832
3833         page = f2fs_grab_meta_page(sbi, blkaddr++);
3834         kaddr = (unsigned char *)page_address(page);
3835         memset(kaddr, 0, PAGE_SIZE);
3836
3837         /* Step 1: write nat cache */
3838         seg_i = CURSEG_I(sbi, CURSEG_HOT_DATA);
3839         memcpy(kaddr, seg_i->journal, SUM_JOURNAL_SIZE);
3840         written_size += SUM_JOURNAL_SIZE;
3841
3842         /* Step 2: write sit cache */
3843         seg_i = CURSEG_I(sbi, CURSEG_COLD_DATA);
3844         memcpy(kaddr + written_size, seg_i->journal, SUM_JOURNAL_SIZE);
3845         written_size += SUM_JOURNAL_SIZE;
3846
3847         /* Step 3: write summary entries */
3848         for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
3849                 unsigned short blkoff;
3850
3851                 seg_i = CURSEG_I(sbi, i);
3852                 if (sbi->ckpt->alloc_type[i] == SSR)
3853                         blkoff = sbi->blocks_per_seg;
3854                 else
3855                         blkoff = curseg_blkoff(sbi, i);
3856
3857                 for (j = 0; j < blkoff; j++) {
3858                         if (!page) {
3859                                 page = f2fs_grab_meta_page(sbi, blkaddr++);
3860                                 kaddr = (unsigned char *)page_address(page);
3861                                 memset(kaddr, 0, PAGE_SIZE);
3862                                 written_size = 0;
3863                         }
3864                         summary = (struct f2fs_summary *)(kaddr + written_size);
3865                         *summary = seg_i->sum_blk->entries[j];
3866                         written_size += SUMMARY_SIZE;
3867
3868                         if (written_size + SUMMARY_SIZE <= PAGE_SIZE -
3869                                                         SUM_FOOTER_SIZE)
3870                                 continue;
3871
3872                         set_page_dirty(page);
3873                         f2fs_put_page(page, 1);
3874                         page = NULL;
3875                 }
3876         }
3877         if (page) {
3878                 set_page_dirty(page);
3879                 f2fs_put_page(page, 1);
3880         }
3881 }
3882
3883 static void write_normal_summaries(struct f2fs_sb_info *sbi,
3884                                         block_t blkaddr, int type)
3885 {
3886         int i, end;
3887
3888         if (IS_DATASEG(type))
3889                 end = type + NR_CURSEG_DATA_TYPE;
3890         else
3891                 end = type + NR_CURSEG_NODE_TYPE;
3892
3893         for (i = type; i < end; i++)
3894                 write_current_sum_page(sbi, i, blkaddr + (i - type));
3895 }
3896
3897 void f2fs_write_data_summaries(struct f2fs_sb_info *sbi, block_t start_blk)
3898 {
3899         if (is_set_ckpt_flags(sbi, CP_COMPACT_SUM_FLAG))
3900                 write_compacted_summaries(sbi, start_blk);
3901         else
3902                 write_normal_summaries(sbi, start_blk, CURSEG_HOT_DATA);
3903 }
3904
3905 void f2fs_write_node_summaries(struct f2fs_sb_info *sbi, block_t start_blk)
3906 {
3907         write_normal_summaries(sbi, start_blk, CURSEG_HOT_NODE);
3908 }
3909
3910 int f2fs_lookup_journal_in_cursum(struct f2fs_journal *journal, int type,
3911                                         unsigned int val, int alloc)
3912 {
3913         int i;
3914
3915         if (type == NAT_JOURNAL) {
3916                 for (i = 0; i < nats_in_cursum(journal); i++) {
3917                         if (le32_to_cpu(nid_in_journal(journal, i)) == val)
3918                                 return i;
3919                 }
3920                 if (alloc && __has_cursum_space(journal, 1, NAT_JOURNAL))
3921                         return update_nats_in_cursum(journal, 1);
3922         } else if (type == SIT_JOURNAL) {
3923                 for (i = 0; i < sits_in_cursum(journal); i++)
3924                         if (le32_to_cpu(segno_in_journal(journal, i)) == val)
3925                                 return i;
3926                 if (alloc && __has_cursum_space(journal, 1, SIT_JOURNAL))
3927                         return update_sits_in_cursum(journal, 1);
3928         }
3929         return -1;
3930 }
3931
3932 static struct page *get_current_sit_page(struct f2fs_sb_info *sbi,
3933                                         unsigned int segno)
3934 {
3935         return f2fs_get_meta_page(sbi, current_sit_addr(sbi, segno));
3936 }
3937
3938 static struct page *get_next_sit_page(struct f2fs_sb_info *sbi,
3939                                         unsigned int start)
3940 {
3941         struct sit_info *sit_i = SIT_I(sbi);
3942         struct page *page;
3943         pgoff_t src_off, dst_off;
3944
3945         src_off = current_sit_addr(sbi, start);
3946         dst_off = next_sit_addr(sbi, src_off);
3947
3948         page = f2fs_grab_meta_page(sbi, dst_off);
3949         seg_info_to_sit_page(sbi, page, start);
3950
3951         set_page_dirty(page);
3952         set_to_next_sit(sit_i, start);
3953
3954         return page;
3955 }
3956
3957 static struct sit_entry_set *grab_sit_entry_set(void)
3958 {
3959         struct sit_entry_set *ses =
3960                         f2fs_kmem_cache_alloc(sit_entry_set_slab,
3961                                                 GFP_NOFS, true, NULL);
3962
3963         ses->entry_cnt = 0;
3964         INIT_LIST_HEAD(&ses->set_list);
3965         return ses;
3966 }
3967
3968 static void release_sit_entry_set(struct sit_entry_set *ses)
3969 {
3970         list_del(&ses->set_list);
3971         kmem_cache_free(sit_entry_set_slab, ses);
3972 }
3973
3974 static void adjust_sit_entry_set(struct sit_entry_set *ses,
3975                                                 struct list_head *head)
3976 {
3977         struct sit_entry_set *next = ses;
3978
3979         if (list_is_last(&ses->set_list, head))
3980                 return;
3981
3982         list_for_each_entry_continue(next, head, set_list)
3983                 if (ses->entry_cnt <= next->entry_cnt) {
3984                         list_move_tail(&ses->set_list, &next->set_list);
3985                         return;
3986                 }
3987
3988         list_move_tail(&ses->set_list, head);
3989 }
3990
3991 static void add_sit_entry(unsigned int segno, struct list_head *head)
3992 {
3993         struct sit_entry_set *ses;
3994         unsigned int start_segno = START_SEGNO(segno);
3995
3996         list_for_each_entry(ses, head, set_list) {
3997                 if (ses->start_segno == start_segno) {
3998                         ses->entry_cnt++;
3999                         adjust_sit_entry_set(ses, head);
4000                         return;
4001                 }
4002         }
4003
4004         ses = grab_sit_entry_set();
4005
4006         ses->start_segno = start_segno;
4007         ses->entry_cnt++;
4008         list_add(&ses->set_list, head);
4009 }
4010
4011 static void add_sits_in_set(struct f2fs_sb_info *sbi)
4012 {
4013         struct f2fs_sm_info *sm_info = SM_I(sbi);
4014         struct list_head *set_list = &sm_info->sit_entry_set;
4015         unsigned long *bitmap = SIT_I(sbi)->dirty_sentries_bitmap;
4016         unsigned int segno;
4017
4018         for_each_set_bit(segno, bitmap, MAIN_SEGS(sbi))
4019                 add_sit_entry(segno, set_list);
4020 }
4021
4022 static void remove_sits_in_journal(struct f2fs_sb_info *sbi)
4023 {
4024         struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
4025         struct f2fs_journal *journal = curseg->journal;
4026         int i;
4027
4028         down_write(&curseg->journal_rwsem);
4029         for (i = 0; i < sits_in_cursum(journal); i++) {
4030                 unsigned int segno;
4031                 bool dirtied;
4032
4033                 segno = le32_to_cpu(segno_in_journal(journal, i));
4034                 dirtied = __mark_sit_entry_dirty(sbi, segno);
4035
4036                 if (!dirtied)
4037                         add_sit_entry(segno, &SM_I(sbi)->sit_entry_set);
4038         }
4039         update_sits_in_cursum(journal, -i);
4040         up_write(&curseg->journal_rwsem);
4041 }
4042
4043 /*
4044  * CP calls this function, which flushes SIT entries including sit_journal,
4045  * and moves prefree segs to free segs.
4046  */
4047 void f2fs_flush_sit_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc)
4048 {
4049         struct sit_info *sit_i = SIT_I(sbi);
4050         unsigned long *bitmap = sit_i->dirty_sentries_bitmap;
4051         struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
4052         struct f2fs_journal *journal = curseg->journal;
4053         struct sit_entry_set *ses, *tmp;
4054         struct list_head *head = &SM_I(sbi)->sit_entry_set;
4055         bool to_journal = !is_sbi_flag_set(sbi, SBI_IS_RESIZEFS);
4056         struct seg_entry *se;
4057
4058         down_write(&sit_i->sentry_lock);
4059
4060         if (!sit_i->dirty_sentries)
4061                 goto out;
4062
4063         /*
4064          * add and account sit entries of dirty bitmap in sit entry
4065          * set temporarily
4066          */
4067         add_sits_in_set(sbi);
4068
4069         /*
4070          * if there are no enough space in journal to store dirty sit
4071          * entries, remove all entries from journal and add and account
4072          * them in sit entry set.
4073          */
4074         if (!__has_cursum_space(journal, sit_i->dirty_sentries, SIT_JOURNAL) ||
4075                                                                 !to_journal)
4076                 remove_sits_in_journal(sbi);
4077
4078         /*
4079          * there are two steps to flush sit entries:
4080          * #1, flush sit entries to journal in current cold data summary block.
4081          * #2, flush sit entries to sit page.
4082          */
4083         list_for_each_entry_safe(ses, tmp, head, set_list) {
4084                 struct page *page = NULL;
4085                 struct f2fs_sit_block *raw_sit = NULL;
4086                 unsigned int start_segno = ses->start_segno;
4087                 unsigned int end = min(start_segno + SIT_ENTRY_PER_BLOCK,
4088                                                 (unsigned long)MAIN_SEGS(sbi));
4089                 unsigned int segno = start_segno;
4090
4091                 if (to_journal &&
4092                         !__has_cursum_space(journal, ses->entry_cnt, SIT_JOURNAL))
4093                         to_journal = false;
4094
4095                 if (to_journal) {
4096                         down_write(&curseg->journal_rwsem);
4097                 } else {
4098                         page = get_next_sit_page(sbi, start_segno);
4099                         raw_sit = page_address(page);
4100                 }
4101
4102                 /* flush dirty sit entries in region of current sit set */
4103                 for_each_set_bit_from(segno, bitmap, end) {
4104                         int offset, sit_offset;
4105
4106                         se = get_seg_entry(sbi, segno);
4107 #ifdef CONFIG_F2FS_CHECK_FS
4108                         if (memcmp(se->cur_valid_map, se->cur_valid_map_mir,
4109                                                 SIT_VBLOCK_MAP_SIZE))
4110                                 f2fs_bug_on(sbi, 1);
4111 #endif
4112
4113                         /* add discard candidates */
4114                         if (!(cpc->reason & CP_DISCARD)) {
4115                                 cpc->trim_start = segno;
4116                                 add_discard_addrs(sbi, cpc, false);
4117                         }
4118
4119                         if (to_journal) {
4120                                 offset = f2fs_lookup_journal_in_cursum(journal,
4121                                                         SIT_JOURNAL, segno, 1);
4122                                 f2fs_bug_on(sbi, offset < 0);
4123                                 segno_in_journal(journal, offset) =
4124                                                         cpu_to_le32(segno);
4125                                 seg_info_to_raw_sit(se,
4126                                         &sit_in_journal(journal, offset));
4127                                 check_block_count(sbi, segno,
4128                                         &sit_in_journal(journal, offset));
4129                         } else {
4130                                 sit_offset = SIT_ENTRY_OFFSET(sit_i, segno);
4131                                 seg_info_to_raw_sit(se,
4132                                                 &raw_sit->entries[sit_offset]);
4133                                 check_block_count(sbi, segno,
4134                                                 &raw_sit->entries[sit_offset]);
4135                         }
4136
4137                         __clear_bit(segno, bitmap);
4138                         sit_i->dirty_sentries--;
4139                         ses->entry_cnt--;
4140                 }
4141
4142                 if (to_journal)
4143                         up_write(&curseg->journal_rwsem);
4144                 else
4145                         f2fs_put_page(page, 1);
4146
4147                 f2fs_bug_on(sbi, ses->entry_cnt);
4148                 release_sit_entry_set(ses);
4149         }
4150
4151         f2fs_bug_on(sbi, !list_empty(head));
4152         f2fs_bug_on(sbi, sit_i->dirty_sentries);
4153 out:
4154         if (cpc->reason & CP_DISCARD) {
4155                 __u64 trim_start = cpc->trim_start;
4156
4157                 for (; cpc->trim_start <= cpc->trim_end; cpc->trim_start++)
4158                         add_discard_addrs(sbi, cpc, false);
4159
4160                 cpc->trim_start = trim_start;
4161         }
4162         up_write(&sit_i->sentry_lock);
4163
4164         set_prefree_as_free_segments(sbi);
4165 }
4166
4167 static int build_sit_info(struct f2fs_sb_info *sbi)
4168 {
4169         struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
4170         struct sit_info *sit_i;
4171         unsigned int sit_segs, start;
4172         char *src_bitmap, *bitmap;
4173         unsigned int bitmap_size, main_bitmap_size, sit_bitmap_size;
4174         unsigned int discard_map = f2fs_block_unit_discard(sbi) ? 1 : 0;
4175
4176         /* allocate memory for SIT information */
4177         sit_i = f2fs_kzalloc(sbi, sizeof(struct sit_info), GFP_KERNEL);
4178         if (!sit_i)
4179                 return -ENOMEM;
4180
4181         SM_I(sbi)->sit_info = sit_i;
4182
4183         sit_i->sentries =
4184                 f2fs_kvzalloc(sbi, array_size(sizeof(struct seg_entry),
4185                                               MAIN_SEGS(sbi)),
4186                               GFP_KERNEL);
4187         if (!sit_i->sentries)
4188                 return -ENOMEM;
4189
4190         main_bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
4191         sit_i->dirty_sentries_bitmap = f2fs_kvzalloc(sbi, main_bitmap_size,
4192                                                                 GFP_KERNEL);
4193         if (!sit_i->dirty_sentries_bitmap)
4194                 return -ENOMEM;
4195
4196 #ifdef CONFIG_F2FS_CHECK_FS
4197         bitmap_size = MAIN_SEGS(sbi) * SIT_VBLOCK_MAP_SIZE * (3 + discard_map);
4198 #else
4199         bitmap_size = MAIN_SEGS(sbi) * SIT_VBLOCK_MAP_SIZE * (2 + discard_map);
4200 #endif
4201         sit_i->bitmap = f2fs_kvzalloc(sbi, bitmap_size, GFP_KERNEL);
4202         if (!sit_i->bitmap)
4203                 return -ENOMEM;
4204
4205         bitmap = sit_i->bitmap;
4206
4207         for (start = 0; start < MAIN_SEGS(sbi); start++) {
4208                 sit_i->sentries[start].cur_valid_map = bitmap;
4209                 bitmap += SIT_VBLOCK_MAP_SIZE;
4210
4211                 sit_i->sentries[start].ckpt_valid_map = bitmap;
4212                 bitmap += SIT_VBLOCK_MAP_SIZE;
4213
4214 #ifdef CONFIG_F2FS_CHECK_FS
4215                 sit_i->sentries[start].cur_valid_map_mir = bitmap;
4216                 bitmap += SIT_VBLOCK_MAP_SIZE;
4217 #endif
4218
4219                 if (discard_map) {
4220                         sit_i->sentries[start].discard_map = bitmap;
4221                         bitmap += SIT_VBLOCK_MAP_SIZE;
4222                 }
4223         }
4224
4225         sit_i->tmp_map = f2fs_kzalloc(sbi, SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
4226         if (!sit_i->tmp_map)
4227                 return -ENOMEM;
4228
4229         if (__is_large_section(sbi)) {
4230                 sit_i->sec_entries =
4231                         f2fs_kvzalloc(sbi, array_size(sizeof(struct sec_entry),
4232                                                       MAIN_SECS(sbi)),
4233                                       GFP_KERNEL);
4234                 if (!sit_i->sec_entries)
4235                         return -ENOMEM;
4236         }
4237
4238         /* get information related with SIT */
4239         sit_segs = le32_to_cpu(raw_super->segment_count_sit) >> 1;
4240
4241         /* setup SIT bitmap from ckeckpoint pack */
4242         sit_bitmap_size = __bitmap_size(sbi, SIT_BITMAP);
4243         src_bitmap = __bitmap_ptr(sbi, SIT_BITMAP);
4244
4245         sit_i->sit_bitmap = kmemdup(src_bitmap, sit_bitmap_size, GFP_KERNEL);
4246         if (!sit_i->sit_bitmap)
4247                 return -ENOMEM;
4248
4249 #ifdef CONFIG_F2FS_CHECK_FS
4250         sit_i->sit_bitmap_mir = kmemdup(src_bitmap,
4251                                         sit_bitmap_size, GFP_KERNEL);
4252         if (!sit_i->sit_bitmap_mir)
4253                 return -ENOMEM;
4254
4255         sit_i->invalid_segmap = f2fs_kvzalloc(sbi,
4256                                         main_bitmap_size, GFP_KERNEL);
4257         if (!sit_i->invalid_segmap)
4258                 return -ENOMEM;
4259 #endif
4260
4261         /* init SIT information */
4262         sit_i->s_ops = &default_salloc_ops;
4263
4264         sit_i->sit_base_addr = le32_to_cpu(raw_super->sit_blkaddr);
4265         sit_i->sit_blocks = sit_segs << sbi->log_blocks_per_seg;
4266         sit_i->written_valid_blocks = 0;
4267         sit_i->bitmap_size = sit_bitmap_size;
4268         sit_i->dirty_sentries = 0;
4269         sit_i->sents_per_block = SIT_ENTRY_PER_BLOCK;
4270         sit_i->elapsed_time = le64_to_cpu(sbi->ckpt->elapsed_time);
4271         sit_i->mounted_time = ktime_get_boottime_seconds();
4272         init_rwsem(&sit_i->sentry_lock);
4273         return 0;
4274 }
4275
4276 static int build_free_segmap(struct f2fs_sb_info *sbi)
4277 {
4278         struct free_segmap_info *free_i;
4279         unsigned int bitmap_size, sec_bitmap_size;
4280
4281         /* allocate memory for free segmap information */
4282         free_i = f2fs_kzalloc(sbi, sizeof(struct free_segmap_info), GFP_KERNEL);
4283         if (!free_i)
4284                 return -ENOMEM;
4285
4286         SM_I(sbi)->free_info = free_i;
4287
4288         bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
4289         free_i->free_segmap = f2fs_kvmalloc(sbi, bitmap_size, GFP_KERNEL);
4290         if (!free_i->free_segmap)
4291                 return -ENOMEM;
4292
4293         sec_bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
4294         free_i->free_secmap = f2fs_kvmalloc(sbi, sec_bitmap_size, GFP_KERNEL);
4295         if (!free_i->free_secmap)
4296                 return -ENOMEM;
4297
4298         /* set all segments as dirty temporarily */
4299         memset(free_i->free_segmap, 0xff, bitmap_size);
4300         memset(free_i->free_secmap, 0xff, sec_bitmap_size);
4301
4302         /* init free segmap information */
4303         free_i->start_segno = GET_SEGNO_FROM_SEG0(sbi, MAIN_BLKADDR(sbi));
4304         free_i->free_segments = 0;
4305         free_i->free_sections = 0;
4306         spin_lock_init(&free_i->segmap_lock);
4307         return 0;
4308 }
4309
4310 static int build_curseg(struct f2fs_sb_info *sbi)
4311 {
4312         struct curseg_info *array;
4313         int i;
4314
4315         array = f2fs_kzalloc(sbi, array_size(NR_CURSEG_TYPE,
4316                                         sizeof(*array)), GFP_KERNEL);
4317         if (!array)
4318                 return -ENOMEM;
4319
4320         SM_I(sbi)->curseg_array = array;
4321
4322         for (i = 0; i < NO_CHECK_TYPE; i++) {
4323                 mutex_init(&array[i].curseg_mutex);
4324                 array[i].sum_blk = f2fs_kzalloc(sbi, PAGE_SIZE, GFP_KERNEL);
4325                 if (!array[i].sum_blk)
4326                         return -ENOMEM;
4327                 init_rwsem(&array[i].journal_rwsem);
4328                 array[i].journal = f2fs_kzalloc(sbi,
4329                                 sizeof(struct f2fs_journal), GFP_KERNEL);
4330                 if (!array[i].journal)
4331                         return -ENOMEM;
4332                 if (i < NR_PERSISTENT_LOG)
4333                         array[i].seg_type = CURSEG_HOT_DATA + i;
4334                 else if (i == CURSEG_COLD_DATA_PINNED)
4335                         array[i].seg_type = CURSEG_COLD_DATA;
4336                 else if (i == CURSEG_ALL_DATA_ATGC)
4337                         array[i].seg_type = CURSEG_COLD_DATA;
4338                 array[i].segno = NULL_SEGNO;
4339                 array[i].next_blkoff = 0;
4340                 array[i].inited = false;
4341         }
4342         return restore_curseg_summaries(sbi);
4343 }
4344
4345 static int build_sit_entries(struct f2fs_sb_info *sbi)
4346 {
4347         struct sit_info *sit_i = SIT_I(sbi);
4348         struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
4349         struct f2fs_journal *journal = curseg->journal;
4350         struct seg_entry *se;
4351         struct f2fs_sit_entry sit;
4352         int sit_blk_cnt = SIT_BLK_CNT(sbi);
4353         unsigned int i, start, end;
4354         unsigned int readed, start_blk = 0;
4355         int err = 0;
4356         block_t sit_valid_blocks[2] = {0, 0};
4357
4358         do {
4359                 readed = f2fs_ra_meta_pages(sbi, start_blk, BIO_MAX_VECS,
4360                                                         META_SIT, true);
4361
4362                 start = start_blk * sit_i->sents_per_block;
4363                 end = (start_blk + readed) * sit_i->sents_per_block;
4364
4365                 for (; start < end && start < MAIN_SEGS(sbi); start++) {
4366                         struct f2fs_sit_block *sit_blk;
4367                         struct page *page;
4368
4369                         se = &sit_i->sentries[start];
4370                         page = get_current_sit_page(sbi, start);
4371                         if (IS_ERR(page))
4372                                 return PTR_ERR(page);
4373                         sit_blk = (struct f2fs_sit_block *)page_address(page);
4374                         sit = sit_blk->entries[SIT_ENTRY_OFFSET(sit_i, start)];
4375                         f2fs_put_page(page, 1);
4376
4377                         err = check_block_count(sbi, start, &sit);
4378                         if (err)
4379                                 return err;
4380                         seg_info_from_raw_sit(se, &sit);
4381
4382                         if (se->type >= NR_PERSISTENT_LOG) {
4383                                 f2fs_err(sbi, "Invalid segment type: %u, segno: %u",
4384                                                         se->type, start);
4385                                 f2fs_handle_error(sbi,
4386                                                 ERROR_INCONSISTENT_SUM_TYPE);
4387                                 return -EFSCORRUPTED;
4388                         }
4389
4390                         sit_valid_blocks[SE_PAGETYPE(se)] += se->valid_blocks;
4391
4392                         if (f2fs_block_unit_discard(sbi)) {
4393                                 /* build discard map only one time */
4394                                 if (is_set_ckpt_flags(sbi, CP_TRIMMED_FLAG)) {
4395                                         memset(se->discard_map, 0xff,
4396                                                 SIT_VBLOCK_MAP_SIZE);
4397                                 } else {
4398                                         memcpy(se->discard_map,
4399                                                 se->cur_valid_map,
4400                                                 SIT_VBLOCK_MAP_SIZE);
4401                                         sbi->discard_blks +=
4402                                                 sbi->blocks_per_seg -
4403                                                 se->valid_blocks;
4404                                 }
4405                         }
4406
4407                         if (__is_large_section(sbi))
4408                                 get_sec_entry(sbi, start)->valid_blocks +=
4409                                                         se->valid_blocks;
4410                 }
4411                 start_blk += readed;
4412         } while (start_blk < sit_blk_cnt);
4413
4414         down_read(&curseg->journal_rwsem);
4415         for (i = 0; i < sits_in_cursum(journal); i++) {
4416                 unsigned int old_valid_blocks;
4417
4418                 start = le32_to_cpu(segno_in_journal(journal, i));
4419                 if (start >= MAIN_SEGS(sbi)) {
4420                         f2fs_err(sbi, "Wrong journal entry on segno %u",
4421                                  start);
4422                         err = -EFSCORRUPTED;
4423                         f2fs_handle_error(sbi, ERROR_CORRUPTED_JOURNAL);
4424                         break;
4425                 }
4426
4427                 se = &sit_i->sentries[start];
4428                 sit = sit_in_journal(journal, i);
4429
4430                 old_valid_blocks = se->valid_blocks;
4431
4432                 sit_valid_blocks[SE_PAGETYPE(se)] -= old_valid_blocks;
4433
4434                 err = check_block_count(sbi, start, &sit);
4435                 if (err)
4436                         break;
4437                 seg_info_from_raw_sit(se, &sit);
4438
4439                 if (se->type >= NR_PERSISTENT_LOG) {
4440                         f2fs_err(sbi, "Invalid segment type: %u, segno: %u",
4441                                                         se->type, start);
4442                         err = -EFSCORRUPTED;
4443                         f2fs_handle_error(sbi, ERROR_INCONSISTENT_SUM_TYPE);
4444                         break;
4445                 }
4446
4447                 sit_valid_blocks[SE_PAGETYPE(se)] += se->valid_blocks;
4448
4449                 if (f2fs_block_unit_discard(sbi)) {
4450                         if (is_set_ckpt_flags(sbi, CP_TRIMMED_FLAG)) {
4451                                 memset(se->discard_map, 0xff, SIT_VBLOCK_MAP_SIZE);
4452                         } else {
4453                                 memcpy(se->discard_map, se->cur_valid_map,
4454                                                         SIT_VBLOCK_MAP_SIZE);
4455                                 sbi->discard_blks += old_valid_blocks;
4456                                 sbi->discard_blks -= se->valid_blocks;
4457                         }
4458                 }
4459
4460                 if (__is_large_section(sbi)) {
4461                         get_sec_entry(sbi, start)->valid_blocks +=
4462                                                         se->valid_blocks;
4463                         get_sec_entry(sbi, start)->valid_blocks -=
4464                                                         old_valid_blocks;
4465                 }
4466         }
4467         up_read(&curseg->journal_rwsem);
4468
4469         if (err)
4470                 return err;
4471
4472         if (sit_valid_blocks[NODE] != valid_node_count(sbi)) {
4473                 f2fs_err(sbi, "SIT is corrupted node# %u vs %u",
4474                          sit_valid_blocks[NODE], valid_node_count(sbi));
4475                 f2fs_handle_error(sbi, ERROR_INCONSISTENT_NODE_COUNT);
4476                 return -EFSCORRUPTED;
4477         }
4478
4479         if (sit_valid_blocks[DATA] + sit_valid_blocks[NODE] >
4480                                 valid_user_blocks(sbi)) {
4481                 f2fs_err(sbi, "SIT is corrupted data# %u %u vs %u",
4482                          sit_valid_blocks[DATA], sit_valid_blocks[NODE],
4483                          valid_user_blocks(sbi));
4484                 f2fs_handle_error(sbi, ERROR_INCONSISTENT_BLOCK_COUNT);
4485                 return -EFSCORRUPTED;
4486         }
4487
4488         return 0;
4489 }
4490
4491 static void init_free_segmap(struct f2fs_sb_info *sbi)
4492 {
4493         unsigned int start;
4494         int type;
4495         struct seg_entry *sentry;
4496
4497         for (start = 0; start < MAIN_SEGS(sbi); start++) {
4498                 if (f2fs_usable_blks_in_seg(sbi, start) == 0)
4499                         continue;
4500                 sentry = get_seg_entry(sbi, start);
4501                 if (!sentry->valid_blocks)
4502                         __set_free(sbi, start);
4503                 else
4504                         SIT_I(sbi)->written_valid_blocks +=
4505                                                 sentry->valid_blocks;
4506         }
4507
4508         /* set use the current segments */
4509         for (type = CURSEG_HOT_DATA; type <= CURSEG_COLD_NODE; type++) {
4510                 struct curseg_info *curseg_t = CURSEG_I(sbi, type);
4511
4512                 __set_test_and_inuse(sbi, curseg_t->segno);
4513         }
4514 }
4515
4516 static void init_dirty_segmap(struct f2fs_sb_info *sbi)
4517 {
4518         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
4519         struct free_segmap_info *free_i = FREE_I(sbi);
4520         unsigned int segno = 0, offset = 0, secno;
4521         block_t valid_blocks, usable_blks_in_seg;
4522
4523         while (1) {
4524                 /* find dirty segment based on free segmap */
4525                 segno = find_next_inuse(free_i, MAIN_SEGS(sbi), offset);
4526                 if (segno >= MAIN_SEGS(sbi))
4527                         break;
4528                 offset = segno + 1;
4529                 valid_blocks = get_valid_blocks(sbi, segno, false);
4530                 usable_blks_in_seg = f2fs_usable_blks_in_seg(sbi, segno);
4531                 if (valid_blocks == usable_blks_in_seg || !valid_blocks)
4532                         continue;
4533                 if (valid_blocks > usable_blks_in_seg) {
4534                         f2fs_bug_on(sbi, 1);
4535                         continue;
4536                 }
4537                 mutex_lock(&dirty_i->seglist_lock);
4538                 __locate_dirty_segment(sbi, segno, DIRTY);
4539                 mutex_unlock(&dirty_i->seglist_lock);
4540         }
4541
4542         if (!__is_large_section(sbi))
4543                 return;
4544
4545         mutex_lock(&dirty_i->seglist_lock);
4546         for (segno = 0; segno < MAIN_SEGS(sbi); segno += sbi->segs_per_sec) {
4547                 valid_blocks = get_valid_blocks(sbi, segno, true);
4548                 secno = GET_SEC_FROM_SEG(sbi, segno);
4549
4550                 if (!valid_blocks || valid_blocks == CAP_BLKS_PER_SEC(sbi))
4551                         continue;
4552                 if (IS_CURSEC(sbi, secno))
4553                         continue;
4554                 set_bit(secno, dirty_i->dirty_secmap);
4555         }
4556         mutex_unlock(&dirty_i->seglist_lock);
4557 }
4558
4559 static int init_victim_secmap(struct f2fs_sb_info *sbi)
4560 {
4561         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
4562         unsigned int bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
4563
4564         dirty_i->victim_secmap = f2fs_kvzalloc(sbi, bitmap_size, GFP_KERNEL);
4565         if (!dirty_i->victim_secmap)
4566                 return -ENOMEM;
4567
4568         dirty_i->pinned_secmap = f2fs_kvzalloc(sbi, bitmap_size, GFP_KERNEL);
4569         if (!dirty_i->pinned_secmap)
4570                 return -ENOMEM;
4571
4572         dirty_i->pinned_secmap_cnt = 0;
4573         dirty_i->enable_pin_section = true;
4574         return 0;
4575 }
4576
4577 static int build_dirty_segmap(struct f2fs_sb_info *sbi)
4578 {
4579         struct dirty_seglist_info *dirty_i;
4580         unsigned int bitmap_size, i;
4581
4582         /* allocate memory for dirty segments list information */
4583         dirty_i = f2fs_kzalloc(sbi, sizeof(struct dirty_seglist_info),
4584                                                                 GFP_KERNEL);
4585         if (!dirty_i)
4586                 return -ENOMEM;
4587
4588         SM_I(sbi)->dirty_info = dirty_i;
4589         mutex_init(&dirty_i->seglist_lock);
4590
4591         bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
4592
4593         for (i = 0; i < NR_DIRTY_TYPE; i++) {
4594                 dirty_i->dirty_segmap[i] = f2fs_kvzalloc(sbi, bitmap_size,
4595                                                                 GFP_KERNEL);
4596                 if (!dirty_i->dirty_segmap[i])
4597                         return -ENOMEM;
4598         }
4599
4600         if (__is_large_section(sbi)) {
4601                 bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
4602                 dirty_i->dirty_secmap = f2fs_kvzalloc(sbi,
4603                                                 bitmap_size, GFP_KERNEL);
4604                 if (!dirty_i->dirty_secmap)
4605                         return -ENOMEM;
4606         }
4607
4608         init_dirty_segmap(sbi);
4609         return init_victim_secmap(sbi);
4610 }
4611
4612 static int sanity_check_curseg(struct f2fs_sb_info *sbi)
4613 {
4614         int i;
4615
4616         /*
4617          * In LFS/SSR curseg, .next_blkoff should point to an unused blkaddr;
4618          * In LFS curseg, all blkaddr after .next_blkoff should be unused.
4619          */
4620         for (i = 0; i < NR_PERSISTENT_LOG; i++) {
4621                 struct curseg_info *curseg = CURSEG_I(sbi, i);
4622                 struct seg_entry *se = get_seg_entry(sbi, curseg->segno);
4623                 unsigned int blkofs = curseg->next_blkoff;
4624
4625                 if (f2fs_sb_has_readonly(sbi) &&
4626                         i != CURSEG_HOT_DATA && i != CURSEG_HOT_NODE)
4627                         continue;
4628
4629                 sanity_check_seg_type(sbi, curseg->seg_type);
4630
4631                 if (curseg->alloc_type != LFS && curseg->alloc_type != SSR) {
4632                         f2fs_err(sbi,
4633                                  "Current segment has invalid alloc_type:%d",
4634                                  curseg->alloc_type);
4635                         f2fs_handle_error(sbi, ERROR_INVALID_CURSEG);
4636                         return -EFSCORRUPTED;
4637                 }
4638
4639                 if (f2fs_test_bit(blkofs, se->cur_valid_map))
4640                         goto out;
4641
4642                 if (curseg->alloc_type == SSR)
4643                         continue;
4644
4645                 for (blkofs += 1; blkofs < sbi->blocks_per_seg; blkofs++) {
4646                         if (!f2fs_test_bit(blkofs, se->cur_valid_map))
4647                                 continue;
4648 out:
4649                         f2fs_err(sbi,
4650                                  "Current segment's next free block offset is inconsistent with bitmap, logtype:%u, segno:%u, type:%u, next_blkoff:%u, blkofs:%u",
4651                                  i, curseg->segno, curseg->alloc_type,
4652                                  curseg->next_blkoff, blkofs);
4653                         f2fs_handle_error(sbi, ERROR_INVALID_CURSEG);
4654                         return -EFSCORRUPTED;
4655                 }
4656         }
4657         return 0;
4658 }
4659
4660 #ifdef CONFIG_BLK_DEV_ZONED
4661
4662 static int check_zone_write_pointer(struct f2fs_sb_info *sbi,
4663                                     struct f2fs_dev_info *fdev,
4664                                     struct blk_zone *zone)
4665 {
4666         unsigned int wp_segno, wp_blkoff, zone_secno, zone_segno, segno;
4667         block_t zone_block, wp_block, last_valid_block;
4668         unsigned int log_sectors_per_block = sbi->log_blocksize - SECTOR_SHIFT;
4669         int i, s, b, ret;
4670         struct seg_entry *se;
4671
4672         if (zone->type != BLK_ZONE_TYPE_SEQWRITE_REQ)
4673                 return 0;
4674
4675         wp_block = fdev->start_blk + (zone->wp >> log_sectors_per_block);
4676         wp_segno = GET_SEGNO(sbi, wp_block);
4677         wp_blkoff = wp_block - START_BLOCK(sbi, wp_segno);
4678         zone_block = fdev->start_blk + (zone->start >> log_sectors_per_block);
4679         zone_segno = GET_SEGNO(sbi, zone_block);
4680         zone_secno = GET_SEC_FROM_SEG(sbi, zone_segno);
4681
4682         if (zone_segno >= MAIN_SEGS(sbi))
4683                 return 0;
4684
4685         /*
4686          * Skip check of zones cursegs point to, since
4687          * fix_curseg_write_pointer() checks them.
4688          */
4689         for (i = 0; i < NO_CHECK_TYPE; i++)
4690                 if (zone_secno == GET_SEC_FROM_SEG(sbi,
4691                                                    CURSEG_I(sbi, i)->segno))
4692                         return 0;
4693
4694         /*
4695          * Get last valid block of the zone.
4696          */
4697         last_valid_block = zone_block - 1;
4698         for (s = sbi->segs_per_sec - 1; s >= 0; s--) {
4699                 segno = zone_segno + s;
4700                 se = get_seg_entry(sbi, segno);
4701                 for (b = sbi->blocks_per_seg - 1; b >= 0; b--)
4702                         if (f2fs_test_bit(b, se->cur_valid_map)) {
4703                                 last_valid_block = START_BLOCK(sbi, segno) + b;
4704                                 break;
4705                         }
4706                 if (last_valid_block >= zone_block)
4707                         break;
4708         }
4709
4710         /*
4711          * If last valid block is beyond the write pointer, report the
4712          * inconsistency. This inconsistency does not cause write error
4713          * because the zone will not be selected for write operation until
4714          * it get discarded. Just report it.
4715          */
4716         if (last_valid_block >= wp_block) {
4717                 f2fs_notice(sbi, "Valid block beyond write pointer: "
4718                             "valid block[0x%x,0x%x] wp[0x%x,0x%x]",
4719                             GET_SEGNO(sbi, last_valid_block),
4720                             GET_BLKOFF_FROM_SEG0(sbi, last_valid_block),
4721                             wp_segno, wp_blkoff);
4722                 return 0;
4723         }
4724
4725         /*
4726          * If there is no valid block in the zone and if write pointer is
4727          * not at zone start, reset the write pointer.
4728          */
4729         if (last_valid_block + 1 == zone_block && zone->wp != zone->start) {
4730                 f2fs_notice(sbi,
4731                             "Zone without valid block has non-zero write "
4732                             "pointer. Reset the write pointer: wp[0x%x,0x%x]",
4733                             wp_segno, wp_blkoff);
4734                 ret = __f2fs_issue_discard_zone(sbi, fdev->bdev, zone_block,
4735                                         zone->len >> log_sectors_per_block);
4736                 if (ret) {
4737                         f2fs_err(sbi, "Discard zone failed: %s (errno=%d)",
4738                                  fdev->path, ret);
4739                         return ret;
4740                 }
4741         }
4742
4743         return 0;
4744 }
4745
4746 static struct f2fs_dev_info *get_target_zoned_dev(struct f2fs_sb_info *sbi,
4747                                                   block_t zone_blkaddr)
4748 {
4749         int i;
4750
4751         for (i = 0; i < sbi->s_ndevs; i++) {
4752                 if (!bdev_is_zoned(FDEV(i).bdev))
4753                         continue;
4754                 if (sbi->s_ndevs == 1 || (FDEV(i).start_blk <= zone_blkaddr &&
4755                                 zone_blkaddr <= FDEV(i).end_blk))
4756                         return &FDEV(i);
4757         }
4758
4759         return NULL;
4760 }
4761
4762 static int report_one_zone_cb(struct blk_zone *zone, unsigned int idx,
4763                               void *data)
4764 {
4765         memcpy(data, zone, sizeof(struct blk_zone));
4766         return 0;
4767 }
4768
4769 static int fix_curseg_write_pointer(struct f2fs_sb_info *sbi, int type)
4770 {
4771         struct curseg_info *cs = CURSEG_I(sbi, type);
4772         struct f2fs_dev_info *zbd;
4773         struct blk_zone zone;
4774         unsigned int cs_section, wp_segno, wp_blkoff, wp_sector_off;
4775         block_t cs_zone_block, wp_block;
4776         unsigned int log_sectors_per_block = sbi->log_blocksize - SECTOR_SHIFT;
4777         sector_t zone_sector;
4778         int err;
4779
4780         cs_section = GET_SEC_FROM_SEG(sbi, cs->segno);
4781         cs_zone_block = START_BLOCK(sbi, GET_SEG_FROM_SEC(sbi, cs_section));
4782
4783         zbd = get_target_zoned_dev(sbi, cs_zone_block);
4784         if (!zbd)
4785                 return 0;
4786
4787         /* report zone for the sector the curseg points to */
4788         zone_sector = (sector_t)(cs_zone_block - zbd->start_blk)
4789                 << log_sectors_per_block;
4790         err = blkdev_report_zones(zbd->bdev, zone_sector, 1,
4791                                   report_one_zone_cb, &zone);
4792         if (err != 1) {
4793                 f2fs_err(sbi, "Report zone failed: %s errno=(%d)",
4794                          zbd->path, err);
4795                 return err;
4796         }
4797
4798         if (zone.type != BLK_ZONE_TYPE_SEQWRITE_REQ)
4799                 return 0;
4800
4801         wp_block = zbd->start_blk + (zone.wp >> log_sectors_per_block);
4802         wp_segno = GET_SEGNO(sbi, wp_block);
4803         wp_blkoff = wp_block - START_BLOCK(sbi, wp_segno);
4804         wp_sector_off = zone.wp & GENMASK(log_sectors_per_block - 1, 0);
4805
4806         if (cs->segno == wp_segno && cs->next_blkoff == wp_blkoff &&
4807                 wp_sector_off == 0)
4808                 return 0;
4809
4810         f2fs_notice(sbi, "Unaligned curseg[%d] with write pointer: "
4811                     "curseg[0x%x,0x%x] wp[0x%x,0x%x]",
4812                     type, cs->segno, cs->next_blkoff, wp_segno, wp_blkoff);
4813
4814         f2fs_notice(sbi, "Assign new section to curseg[%d]: "
4815                     "curseg[0x%x,0x%x]", type, cs->segno, cs->next_blkoff);
4816
4817         f2fs_allocate_new_section(sbi, type, true);
4818
4819         /* check consistency of the zone curseg pointed to */
4820         if (check_zone_write_pointer(sbi, zbd, &zone))
4821                 return -EIO;
4822
4823         /* check newly assigned zone */
4824         cs_section = GET_SEC_FROM_SEG(sbi, cs->segno);
4825         cs_zone_block = START_BLOCK(sbi, GET_SEG_FROM_SEC(sbi, cs_section));
4826
4827         zbd = get_target_zoned_dev(sbi, cs_zone_block);
4828         if (!zbd)
4829                 return 0;
4830
4831         zone_sector = (sector_t)(cs_zone_block - zbd->start_blk)
4832                 << log_sectors_per_block;
4833         err = blkdev_report_zones(zbd->bdev, zone_sector, 1,
4834                                   report_one_zone_cb, &zone);
4835         if (err != 1) {
4836                 f2fs_err(sbi, "Report zone failed: %s errno=(%d)",
4837                          zbd->path, err);
4838                 return err;
4839         }
4840
4841         if (zone.type != BLK_ZONE_TYPE_SEQWRITE_REQ)
4842                 return 0;
4843
4844         if (zone.wp != zone.start) {
4845                 f2fs_notice(sbi,
4846                             "New zone for curseg[%d] is not yet discarded. "
4847                             "Reset the zone: curseg[0x%x,0x%x]",
4848                             type, cs->segno, cs->next_blkoff);
4849                 err = __f2fs_issue_discard_zone(sbi, zbd->bdev,
4850                                 zone_sector >> log_sectors_per_block,
4851                                 zone.len >> log_sectors_per_block);
4852                 if (err) {
4853                         f2fs_err(sbi, "Discard zone failed: %s (errno=%d)",
4854                                  zbd->path, err);
4855                         return err;
4856                 }
4857         }
4858
4859         return 0;
4860 }
4861
4862 int f2fs_fix_curseg_write_pointer(struct f2fs_sb_info *sbi)
4863 {
4864         int i, ret;
4865
4866         for (i = 0; i < NR_PERSISTENT_LOG; i++) {
4867                 ret = fix_curseg_write_pointer(sbi, i);
4868                 if (ret)
4869                         return ret;
4870         }
4871
4872         return 0;
4873 }
4874
4875 struct check_zone_write_pointer_args {
4876         struct f2fs_sb_info *sbi;
4877         struct f2fs_dev_info *fdev;
4878 };
4879
4880 static int check_zone_write_pointer_cb(struct blk_zone *zone, unsigned int idx,
4881                                       void *data)
4882 {
4883         struct check_zone_write_pointer_args *args;
4884
4885         args = (struct check_zone_write_pointer_args *)data;
4886
4887         return check_zone_write_pointer(args->sbi, args->fdev, zone);
4888 }
4889
4890 int f2fs_check_write_pointer(struct f2fs_sb_info *sbi)
4891 {
4892         int i, ret;
4893         struct check_zone_write_pointer_args args;
4894
4895         for (i = 0; i < sbi->s_ndevs; i++) {
4896                 if (!bdev_is_zoned(FDEV(i).bdev))
4897                         continue;
4898
4899                 args.sbi = sbi;
4900                 args.fdev = &FDEV(i);
4901                 ret = blkdev_report_zones(FDEV(i).bdev, 0, BLK_ALL_ZONES,
4902                                           check_zone_write_pointer_cb, &args);
4903                 if (ret < 0)
4904                         return ret;
4905         }
4906
4907         return 0;
4908 }
4909
4910 static bool is_conv_zone(struct f2fs_sb_info *sbi, unsigned int zone_idx,
4911                                                 unsigned int dev_idx)
4912 {
4913         if (!bdev_is_zoned(FDEV(dev_idx).bdev))
4914                 return true;
4915         return !test_bit(zone_idx, FDEV(dev_idx).blkz_seq);
4916 }
4917
4918 /* Return the zone index in the given device */
4919 static unsigned int get_zone_idx(struct f2fs_sb_info *sbi, unsigned int secno,
4920                                         int dev_idx)
4921 {
4922         block_t sec_start_blkaddr = START_BLOCK(sbi, GET_SEG_FROM_SEC(sbi, secno));
4923
4924         return (sec_start_blkaddr - FDEV(dev_idx).start_blk) >>
4925                                                 sbi->log_blocks_per_blkz;
4926 }
4927
4928 /*
4929  * Return the usable segments in a section based on the zone's
4930  * corresponding zone capacity. Zone is equal to a section.
4931  */
4932 static inline unsigned int f2fs_usable_zone_segs_in_sec(
4933                 struct f2fs_sb_info *sbi, unsigned int segno)
4934 {
4935         unsigned int dev_idx, zone_idx;
4936
4937         dev_idx = f2fs_target_device_index(sbi, START_BLOCK(sbi, segno));
4938         zone_idx = get_zone_idx(sbi, GET_SEC_FROM_SEG(sbi, segno), dev_idx);
4939
4940         /* Conventional zone's capacity is always equal to zone size */
4941         if (is_conv_zone(sbi, zone_idx, dev_idx))
4942                 return sbi->segs_per_sec;
4943
4944         if (!sbi->unusable_blocks_per_sec)
4945                 return sbi->segs_per_sec;
4946
4947         /* Get the segment count beyond zone capacity block */
4948         return sbi->segs_per_sec - (sbi->unusable_blocks_per_sec >>
4949                                                 sbi->log_blocks_per_seg);
4950 }
4951
4952 /*
4953  * Return the number of usable blocks in a segment. The number of blocks
4954  * returned is always equal to the number of blocks in a segment for
4955  * segments fully contained within a sequential zone capacity or a
4956  * conventional zone. For segments partially contained in a sequential
4957  * zone capacity, the number of usable blocks up to the zone capacity
4958  * is returned. 0 is returned in all other cases.
4959  */
4960 static inline unsigned int f2fs_usable_zone_blks_in_seg(
4961                         struct f2fs_sb_info *sbi, unsigned int segno)
4962 {
4963         block_t seg_start, sec_start_blkaddr, sec_cap_blkaddr;
4964         unsigned int zone_idx, dev_idx, secno;
4965
4966         secno = GET_SEC_FROM_SEG(sbi, segno);
4967         seg_start = START_BLOCK(sbi, segno);
4968         dev_idx = f2fs_target_device_index(sbi, seg_start);
4969         zone_idx = get_zone_idx(sbi, secno, dev_idx);
4970
4971         /*
4972          * Conventional zone's capacity is always equal to zone size,
4973          * so, blocks per segment is unchanged.
4974          */
4975         if (is_conv_zone(sbi, zone_idx, dev_idx))
4976                 return sbi->blocks_per_seg;
4977
4978         if (!sbi->unusable_blocks_per_sec)
4979                 return sbi->blocks_per_seg;
4980
4981         sec_start_blkaddr = START_BLOCK(sbi, GET_SEG_FROM_SEC(sbi, secno));
4982         sec_cap_blkaddr = sec_start_blkaddr + CAP_BLKS_PER_SEC(sbi);
4983
4984         /*
4985          * If segment starts before zone capacity and spans beyond
4986          * zone capacity, then usable blocks are from seg start to
4987          * zone capacity. If the segment starts after the zone capacity,
4988          * then there are no usable blocks.
4989          */
4990         if (seg_start >= sec_cap_blkaddr)
4991                 return 0;
4992         if (seg_start + sbi->blocks_per_seg > sec_cap_blkaddr)
4993                 return sec_cap_blkaddr - seg_start;
4994
4995         return sbi->blocks_per_seg;
4996 }
4997 #else
4998 int f2fs_fix_curseg_write_pointer(struct f2fs_sb_info *sbi)
4999 {
5000         return 0;
5001 }
5002
5003 int f2fs_check_write_pointer(struct f2fs_sb_info *sbi)
5004 {
5005         return 0;
5006 }
5007
5008 static inline unsigned int f2fs_usable_zone_blks_in_seg(struct f2fs_sb_info *sbi,
5009                                                         unsigned int segno)
5010 {
5011         return 0;
5012 }
5013
5014 static inline unsigned int f2fs_usable_zone_segs_in_sec(struct f2fs_sb_info *sbi,
5015                                                         unsigned int segno)
5016 {
5017         return 0;
5018 }
5019 #endif
5020 unsigned int f2fs_usable_blks_in_seg(struct f2fs_sb_info *sbi,
5021                                         unsigned int segno)
5022 {
5023         if (f2fs_sb_has_blkzoned(sbi))
5024                 return f2fs_usable_zone_blks_in_seg(sbi, segno);
5025
5026         return sbi->blocks_per_seg;
5027 }
5028
5029 unsigned int f2fs_usable_segs_in_sec(struct f2fs_sb_info *sbi,
5030                                         unsigned int segno)
5031 {
5032         if (f2fs_sb_has_blkzoned(sbi))
5033                 return f2fs_usable_zone_segs_in_sec(sbi, segno);
5034
5035         return sbi->segs_per_sec;
5036 }
5037
5038 /*
5039  * Update min, max modified time for cost-benefit GC algorithm
5040  */
5041 static void init_min_max_mtime(struct f2fs_sb_info *sbi)
5042 {
5043         struct sit_info *sit_i = SIT_I(sbi);
5044         unsigned int segno;
5045
5046         down_write(&sit_i->sentry_lock);
5047
5048         sit_i->min_mtime = ULLONG_MAX;
5049
5050         for (segno = 0; segno < MAIN_SEGS(sbi); segno += sbi->segs_per_sec) {
5051                 unsigned int i;
5052                 unsigned long long mtime = 0;
5053
5054                 for (i = 0; i < sbi->segs_per_sec; i++)
5055                         mtime += get_seg_entry(sbi, segno + i)->mtime;
5056
5057                 mtime = div_u64(mtime, sbi->segs_per_sec);
5058
5059                 if (sit_i->min_mtime > mtime)
5060                         sit_i->min_mtime = mtime;
5061         }
5062         sit_i->max_mtime = get_mtime(sbi, false);
5063         sit_i->dirty_max_mtime = 0;
5064         up_write(&sit_i->sentry_lock);
5065 }
5066
5067 int f2fs_build_segment_manager(struct f2fs_sb_info *sbi)
5068 {
5069         struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
5070         struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
5071         struct f2fs_sm_info *sm_info;
5072         int err;
5073
5074         sm_info = f2fs_kzalloc(sbi, sizeof(struct f2fs_sm_info), GFP_KERNEL);
5075         if (!sm_info)
5076                 return -ENOMEM;
5077
5078         /* init sm info */
5079         sbi->sm_info = sm_info;
5080         sm_info->seg0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr);
5081         sm_info->main_blkaddr = le32_to_cpu(raw_super->main_blkaddr);
5082         sm_info->segment_count = le32_to_cpu(raw_super->segment_count);
5083         sm_info->reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
5084         sm_info->ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
5085         sm_info->main_segments = le32_to_cpu(raw_super->segment_count_main);
5086         sm_info->ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr);
5087         sm_info->rec_prefree_segments = sm_info->main_segments *
5088                                         DEF_RECLAIM_PREFREE_SEGMENTS / 100;
5089         if (sm_info->rec_prefree_segments > DEF_MAX_RECLAIM_PREFREE_SEGMENTS)
5090                 sm_info->rec_prefree_segments = DEF_MAX_RECLAIM_PREFREE_SEGMENTS;
5091
5092         if (!f2fs_lfs_mode(sbi))
5093                 sm_info->ipu_policy = 1 << F2FS_IPU_FSYNC;
5094         sm_info->min_ipu_util = DEF_MIN_IPU_UTIL;
5095         sm_info->min_fsync_blocks = DEF_MIN_FSYNC_BLOCKS;
5096         sm_info->min_seq_blocks = sbi->blocks_per_seg;
5097         sm_info->min_hot_blocks = DEF_MIN_HOT_BLOCKS;
5098         sm_info->min_ssr_sections = reserved_sections(sbi);
5099
5100         INIT_LIST_HEAD(&sm_info->sit_entry_set);
5101
5102         init_f2fs_rwsem(&sm_info->curseg_lock);
5103
5104         if (!f2fs_readonly(sbi->sb)) {
5105                 err = f2fs_create_flush_cmd_control(sbi);
5106                 if (err)
5107                         return err;
5108         }
5109
5110         err = create_discard_cmd_control(sbi);
5111         if (err)
5112                 return err;
5113
5114         err = build_sit_info(sbi);
5115         if (err)
5116                 return err;
5117         err = build_free_segmap(sbi);
5118         if (err)
5119                 return err;
5120         err = build_curseg(sbi);
5121         if (err)
5122                 return err;
5123
5124         /* reinit free segmap based on SIT */
5125         err = build_sit_entries(sbi);
5126         if (err)
5127                 return err;
5128
5129         init_free_segmap(sbi);
5130         err = build_dirty_segmap(sbi);
5131         if (err)
5132                 return err;
5133
5134         err = sanity_check_curseg(sbi);
5135         if (err)
5136                 return err;
5137
5138         init_min_max_mtime(sbi);
5139         return 0;
5140 }
5141
5142 static void discard_dirty_segmap(struct f2fs_sb_info *sbi,
5143                 enum dirty_type dirty_type)
5144 {
5145         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
5146
5147         mutex_lock(&dirty_i->seglist_lock);
5148         kvfree(dirty_i->dirty_segmap[dirty_type]);
5149         dirty_i->nr_dirty[dirty_type] = 0;
5150         mutex_unlock(&dirty_i->seglist_lock);
5151 }
5152
5153 static void destroy_victim_secmap(struct f2fs_sb_info *sbi)
5154 {
5155         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
5156
5157         kvfree(dirty_i->pinned_secmap);
5158         kvfree(dirty_i->victim_secmap);
5159 }
5160
5161 static void destroy_dirty_segmap(struct f2fs_sb_info *sbi)
5162 {
5163         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
5164         int i;
5165
5166         if (!dirty_i)
5167                 return;
5168
5169         /* discard pre-free/dirty segments list */
5170         for (i = 0; i < NR_DIRTY_TYPE; i++)
5171                 discard_dirty_segmap(sbi, i);
5172
5173         if (__is_large_section(sbi)) {
5174                 mutex_lock(&dirty_i->seglist_lock);
5175                 kvfree(dirty_i->dirty_secmap);
5176                 mutex_unlock(&dirty_i->seglist_lock);
5177         }
5178
5179         destroy_victim_secmap(sbi);
5180         SM_I(sbi)->dirty_info = NULL;
5181         kfree(dirty_i);
5182 }
5183
5184 static void destroy_curseg(struct f2fs_sb_info *sbi)
5185 {
5186         struct curseg_info *array = SM_I(sbi)->curseg_array;
5187         int i;
5188
5189         if (!array)
5190                 return;
5191         SM_I(sbi)->curseg_array = NULL;
5192         for (i = 0; i < NR_CURSEG_TYPE; i++) {
5193                 kfree(array[i].sum_blk);
5194                 kfree(array[i].journal);
5195         }
5196         kfree(array);
5197 }
5198
5199 static void destroy_free_segmap(struct f2fs_sb_info *sbi)
5200 {
5201         struct free_segmap_info *free_i = SM_I(sbi)->free_info;
5202
5203         if (!free_i)
5204                 return;
5205         SM_I(sbi)->free_info = NULL;
5206         kvfree(free_i->free_segmap);
5207         kvfree(free_i->free_secmap);
5208         kfree(free_i);
5209 }
5210
5211 static void destroy_sit_info(struct f2fs_sb_info *sbi)
5212 {
5213         struct sit_info *sit_i = SIT_I(sbi);
5214
5215         if (!sit_i)
5216                 return;
5217
5218         if (sit_i->sentries)
5219                 kvfree(sit_i->bitmap);
5220         kfree(sit_i->tmp_map);
5221
5222         kvfree(sit_i->sentries);
5223         kvfree(sit_i->sec_entries);
5224         kvfree(sit_i->dirty_sentries_bitmap);
5225
5226         SM_I(sbi)->sit_info = NULL;
5227         kvfree(sit_i->sit_bitmap);
5228 #ifdef CONFIG_F2FS_CHECK_FS
5229         kvfree(sit_i->sit_bitmap_mir);
5230         kvfree(sit_i->invalid_segmap);
5231 #endif
5232         kfree(sit_i);
5233 }
5234
5235 void f2fs_destroy_segment_manager(struct f2fs_sb_info *sbi)
5236 {
5237         struct f2fs_sm_info *sm_info = SM_I(sbi);
5238
5239         if (!sm_info)
5240                 return;
5241         f2fs_destroy_flush_cmd_control(sbi, true);
5242         destroy_discard_cmd_control(sbi);
5243         destroy_dirty_segmap(sbi);
5244         destroy_curseg(sbi);
5245         destroy_free_segmap(sbi);
5246         destroy_sit_info(sbi);
5247         sbi->sm_info = NULL;
5248         kfree(sm_info);
5249 }
5250
5251 int __init f2fs_create_segment_manager_caches(void)
5252 {
5253         discard_entry_slab = f2fs_kmem_cache_create("f2fs_discard_entry",
5254                         sizeof(struct discard_entry));
5255         if (!discard_entry_slab)
5256                 goto fail;
5257
5258         discard_cmd_slab = f2fs_kmem_cache_create("f2fs_discard_cmd",
5259                         sizeof(struct discard_cmd));
5260         if (!discard_cmd_slab)
5261                 goto destroy_discard_entry;
5262
5263         sit_entry_set_slab = f2fs_kmem_cache_create("f2fs_sit_entry_set",
5264                         sizeof(struct sit_entry_set));
5265         if (!sit_entry_set_slab)
5266                 goto destroy_discard_cmd;
5267
5268         revoke_entry_slab = f2fs_kmem_cache_create("f2fs_revoke_entry",
5269                         sizeof(struct revoke_entry));
5270         if (!revoke_entry_slab)
5271                 goto destroy_sit_entry_set;
5272         return 0;
5273
5274 destroy_sit_entry_set:
5275         kmem_cache_destroy(sit_entry_set_slab);
5276 destroy_discard_cmd:
5277         kmem_cache_destroy(discard_cmd_slab);
5278 destroy_discard_entry:
5279         kmem_cache_destroy(discard_entry_slab);
5280 fail:
5281         return -ENOMEM;
5282 }
5283
5284 void f2fs_destroy_segment_manager_caches(void)
5285 {
5286         kmem_cache_destroy(sit_entry_set_slab);
5287         kmem_cache_destroy(discard_cmd_slab);
5288         kmem_cache_destroy(discard_entry_slab);
5289         kmem_cache_destroy(revoke_entry_slab);
5290 }