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