OSDN Git Service

Merge 4.4.195 into android-4.4-p
[sagit-ice-cold/kernel_xiaomi_msm8998.git] / fs / f2fs / segment.c
1 /*
2  * fs/f2fs/segment.c
3  *
4  * Copyright (c) 2012 Samsung Electronics Co., Ltd.
5  *             http://www.samsung.com/
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  */
11 #include <linux/fs.h>
12 #include <linux/f2fs_fs.h>
13 #include <linux/bio.h>
14 #include <linux/blkdev.h>
15 #include <linux/prefetch.h>
16 #include <linux/kthread.h>
17 #include <linux/swap.h>
18 #include <linux/timer.h>
19 #include <linux/freezer.h>
20 #include <linux/sched.h>
21
22 #include "f2fs.h"
23 #include "segment.h"
24 #include "node.h"
25 #include "gc.h"
26 #include "trace.h"
27 #include <trace/events/f2fs.h>
28
29 #define __reverse_ffz(x) __reverse_ffs(~(x))
30
31 static struct kmem_cache *discard_entry_slab;
32 static struct kmem_cache *discard_cmd_slab;
33 static struct kmem_cache *sit_entry_set_slab;
34 static struct kmem_cache *inmem_entry_slab;
35
36 static unsigned long __reverse_ulong(unsigned char *str)
37 {
38         unsigned long tmp = 0;
39         int shift = 24, idx = 0;
40
41 #if BITS_PER_LONG == 64
42         shift = 56;
43 #endif
44         while (shift >= 0) {
45                 tmp |= (unsigned long)str[idx++] << shift;
46                 shift -= BITS_PER_BYTE;
47         }
48         return tmp;
49 }
50
51 /*
52  * __reverse_ffs is copied from include/asm-generic/bitops/__ffs.h since
53  * MSB and LSB are reversed in a byte by f2fs_set_bit.
54  */
55 static inline unsigned long __reverse_ffs(unsigned long word)
56 {
57         int num = 0;
58
59 #if BITS_PER_LONG == 64
60         if ((word & 0xffffffff00000000UL) == 0)
61                 num += 32;
62         else
63                 word >>= 32;
64 #endif
65         if ((word & 0xffff0000) == 0)
66                 num += 16;
67         else
68                 word >>= 16;
69
70         if ((word & 0xff00) == 0)
71                 num += 8;
72         else
73                 word >>= 8;
74
75         if ((word & 0xf0) == 0)
76                 num += 4;
77         else
78                 word >>= 4;
79
80         if ((word & 0xc) == 0)
81                 num += 2;
82         else
83                 word >>= 2;
84
85         if ((word & 0x2) == 0)
86                 num += 1;
87         return num;
88 }
89
90 /*
91  * __find_rev_next(_zero)_bit is copied from lib/find_next_bit.c because
92  * f2fs_set_bit makes MSB and LSB reversed in a byte.
93  * @size must be integral times of unsigned long.
94  * Example:
95  *                             MSB <--> LSB
96  *   f2fs_set_bit(0, bitmap) => 1000 0000
97  *   f2fs_set_bit(7, bitmap) => 0000 0001
98  */
99 static unsigned long __find_rev_next_bit(const unsigned long *addr,
100                         unsigned long size, unsigned long offset)
101 {
102         const unsigned long *p = addr + BIT_WORD(offset);
103         unsigned long result = size;
104         unsigned long tmp;
105
106         if (offset >= size)
107                 return size;
108
109         size -= (offset & ~(BITS_PER_LONG - 1));
110         offset %= BITS_PER_LONG;
111
112         while (1) {
113                 if (*p == 0)
114                         goto pass;
115
116                 tmp = __reverse_ulong((unsigned char *)p);
117
118                 tmp &= ~0UL >> offset;
119                 if (size < BITS_PER_LONG)
120                         tmp &= (~0UL << (BITS_PER_LONG - size));
121                 if (tmp)
122                         goto found;
123 pass:
124                 if (size <= BITS_PER_LONG)
125                         break;
126                 size -= BITS_PER_LONG;
127                 offset = 0;
128                 p++;
129         }
130         return result;
131 found:
132         return result - size + __reverse_ffs(tmp);
133 }
134
135 static unsigned long __find_rev_next_zero_bit(const unsigned long *addr,
136                         unsigned long size, unsigned long offset)
137 {
138         const unsigned long *p = addr + BIT_WORD(offset);
139         unsigned long result = size;
140         unsigned long tmp;
141
142         if (offset >= size)
143                 return size;
144
145         size -= (offset & ~(BITS_PER_LONG - 1));
146         offset %= BITS_PER_LONG;
147
148         while (1) {
149                 if (*p == ~0UL)
150                         goto pass;
151
152                 tmp = __reverse_ulong((unsigned char *)p);
153
154                 if (offset)
155                         tmp |= ~0UL << (BITS_PER_LONG - offset);
156                 if (size < BITS_PER_LONG)
157                         tmp |= ~0UL >> size;
158                 if (tmp != ~0UL)
159                         goto found;
160 pass:
161                 if (size <= BITS_PER_LONG)
162                         break;
163                 size -= BITS_PER_LONG;
164                 offset = 0;
165                 p++;
166         }
167         return result;
168 found:
169         return result - size + __reverse_ffz(tmp);
170 }
171
172 bool need_SSR(struct f2fs_sb_info *sbi)
173 {
174         int node_secs = get_blocktype_secs(sbi, F2FS_DIRTY_NODES);
175         int dent_secs = get_blocktype_secs(sbi, F2FS_DIRTY_DENTS);
176         int imeta_secs = get_blocktype_secs(sbi, F2FS_DIRTY_IMETA);
177
178         if (test_opt(sbi, LFS))
179                 return false;
180         if (sbi->gc_thread && sbi->gc_thread->gc_urgent)
181                 return true;
182
183         return free_sections(sbi) <= (node_secs + 2 * dent_secs + imeta_secs +
184                         SM_I(sbi)->min_ssr_sections + reserved_sections(sbi));
185 }
186
187 void register_inmem_page(struct inode *inode, struct page *page)
188 {
189         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
190         struct f2fs_inode_info *fi = F2FS_I(inode);
191         struct inmem_pages *new;
192
193         f2fs_trace_pid(page);
194
195         set_page_private(page, (unsigned long)ATOMIC_WRITTEN_PAGE);
196         SetPagePrivate(page);
197
198         new = f2fs_kmem_cache_alloc(inmem_entry_slab, GFP_NOFS);
199
200         /* add atomic page indices to the list */
201         new->page = page;
202         INIT_LIST_HEAD(&new->list);
203
204         /* increase reference count with clean state */
205         mutex_lock(&fi->inmem_lock);
206         get_page(page);
207         list_add_tail(&new->list, &fi->inmem_pages);
208         spin_lock(&sbi->inode_lock[ATOMIC_FILE]);
209         if (list_empty(&fi->inmem_ilist))
210                 list_add_tail(&fi->inmem_ilist, &sbi->inode_list[ATOMIC_FILE]);
211         spin_unlock(&sbi->inode_lock[ATOMIC_FILE]);
212         inc_page_count(F2FS_I_SB(inode), F2FS_INMEM_PAGES);
213         mutex_unlock(&fi->inmem_lock);
214
215         trace_f2fs_register_inmem_page(page, INMEM);
216 }
217
218 static int __revoke_inmem_pages(struct inode *inode,
219                                 struct list_head *head, bool drop, bool recover)
220 {
221         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
222         struct inmem_pages *cur, *tmp;
223         int err = 0;
224
225         list_for_each_entry_safe(cur, tmp, head, list) {
226                 struct page *page = cur->page;
227
228                 if (drop)
229                         trace_f2fs_commit_inmem_page(page, INMEM_DROP);
230
231                 lock_page(page);
232
233                 if (recover) {
234                         struct dnode_of_data dn;
235                         struct node_info ni;
236
237                         trace_f2fs_commit_inmem_page(page, INMEM_REVOKE);
238 retry:
239                         set_new_dnode(&dn, inode, NULL, NULL, 0);
240                         err = get_dnode_of_data(&dn, page->index, LOOKUP_NODE);
241                         if (err) {
242                                 if (err == -ENOMEM) {
243                                         congestion_wait(BLK_RW_ASYNC, HZ/50);
244                                         cond_resched();
245                                         goto retry;
246                                 }
247                                 err = -EAGAIN;
248                                 goto next;
249                         }
250                         get_node_info(sbi, dn.nid, &ni);
251                         if (cur->old_addr == NEW_ADDR) {
252                                 invalidate_blocks(sbi, dn.data_blkaddr);
253                                 f2fs_update_data_blkaddr(&dn, NEW_ADDR);
254                         } else
255                                 f2fs_replace_block(sbi, &dn, dn.data_blkaddr,
256                                         cur->old_addr, ni.version, true, true);
257                         f2fs_put_dnode(&dn);
258                 }
259 next:
260                 /* we don't need to invalidate this in the sccessful status */
261                 if (drop || recover)
262                         ClearPageUptodate(page);
263                 set_page_private(page, 0);
264                 ClearPagePrivate(page);
265                 f2fs_put_page(page, 1);
266
267                 list_del(&cur->list);
268                 kmem_cache_free(inmem_entry_slab, cur);
269                 dec_page_count(F2FS_I_SB(inode), F2FS_INMEM_PAGES);
270         }
271         return err;
272 }
273
274 void drop_inmem_pages_all(struct f2fs_sb_info *sbi)
275 {
276         struct list_head *head = &sbi->inode_list[ATOMIC_FILE];
277         struct inode *inode;
278         struct f2fs_inode_info *fi;
279 next:
280         spin_lock(&sbi->inode_lock[ATOMIC_FILE]);
281         if (list_empty(head)) {
282                 spin_unlock(&sbi->inode_lock[ATOMIC_FILE]);
283                 return;
284         }
285         fi = list_first_entry(head, struct f2fs_inode_info, inmem_ilist);
286         inode = igrab(&fi->vfs_inode);
287         spin_unlock(&sbi->inode_lock[ATOMIC_FILE]);
288
289         if (inode) {
290                 drop_inmem_pages(inode);
291                 iput(inode);
292         }
293         congestion_wait(BLK_RW_ASYNC, HZ/50);
294         cond_resched();
295         goto next;
296 }
297
298 void drop_inmem_pages(struct inode *inode)
299 {
300         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
301         struct f2fs_inode_info *fi = F2FS_I(inode);
302
303         mutex_lock(&fi->inmem_lock);
304         __revoke_inmem_pages(inode, &fi->inmem_pages, true, false);
305         spin_lock(&sbi->inode_lock[ATOMIC_FILE]);
306         if (!list_empty(&fi->inmem_ilist))
307                 list_del_init(&fi->inmem_ilist);
308         spin_unlock(&sbi->inode_lock[ATOMIC_FILE]);
309         mutex_unlock(&fi->inmem_lock);
310
311         clear_inode_flag(inode, FI_ATOMIC_FILE);
312         clear_inode_flag(inode, FI_HOT_DATA);
313         stat_dec_atomic_write(inode);
314 }
315
316 void drop_inmem_page(struct inode *inode, struct page *page)
317 {
318         struct f2fs_inode_info *fi = F2FS_I(inode);
319         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
320         struct list_head *head = &fi->inmem_pages;
321         struct inmem_pages *cur = NULL;
322
323         f2fs_bug_on(sbi, !IS_ATOMIC_WRITTEN_PAGE(page));
324
325         mutex_lock(&fi->inmem_lock);
326         list_for_each_entry(cur, head, list) {
327                 if (cur->page == page)
328                         break;
329         }
330
331         f2fs_bug_on(sbi, !cur || cur->page != page);
332         list_del(&cur->list);
333         mutex_unlock(&fi->inmem_lock);
334
335         dec_page_count(sbi, F2FS_INMEM_PAGES);
336         kmem_cache_free(inmem_entry_slab, cur);
337
338         ClearPageUptodate(page);
339         set_page_private(page, 0);
340         ClearPagePrivate(page);
341         f2fs_put_page(page, 0);
342
343         trace_f2fs_commit_inmem_page(page, INMEM_INVALIDATE);
344 }
345
346 static int __commit_inmem_pages(struct inode *inode,
347                                         struct list_head *revoke_list)
348 {
349         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
350         struct f2fs_inode_info *fi = F2FS_I(inode);
351         struct inmem_pages *cur, *tmp;
352         struct f2fs_io_info fio = {
353                 .sbi = sbi,
354                 .ino = inode->i_ino,
355                 .type = DATA,
356                 .op = REQ_OP_WRITE,
357                 .op_flags = REQ_SYNC | REQ_PRIO,
358                 .io_type = FS_DATA_IO,
359         };
360         pgoff_t last_idx = ULONG_MAX;
361         int err = 0;
362
363         list_for_each_entry_safe(cur, tmp, &fi->inmem_pages, list) {
364                 struct page *page = cur->page;
365
366                 lock_page(page);
367                 if (page->mapping == inode->i_mapping) {
368                         trace_f2fs_commit_inmem_page(page, INMEM);
369
370                         set_page_dirty(page);
371                         f2fs_wait_on_page_writeback(page, DATA, true);
372                         if (clear_page_dirty_for_io(page)) {
373                                 inode_dec_dirty_pages(inode);
374                                 remove_dirty_inode(inode);
375                         }
376 retry:
377                         fio.page = page;
378                         fio.old_blkaddr = NULL_ADDR;
379                         fio.encrypted_page = NULL;
380                         fio.need_lock = LOCK_DONE;
381                         err = do_write_data_page(&fio);
382                         if (err) {
383                                 if (err == -ENOMEM) {
384                                         congestion_wait(BLK_RW_ASYNC, HZ/50);
385                                         cond_resched();
386                                         goto retry;
387                                 }
388                                 unlock_page(page);
389                                 break;
390                         }
391                         /* record old blkaddr for revoking */
392                         cur->old_addr = fio.old_blkaddr;
393                         last_idx = page->index;
394                 }
395                 unlock_page(page);
396                 list_move_tail(&cur->list, revoke_list);
397         }
398
399         if (last_idx != ULONG_MAX)
400                 f2fs_submit_merged_write_cond(sbi, inode, 0, last_idx, DATA);
401
402         if (!err)
403                 __revoke_inmem_pages(inode, revoke_list, false, false);
404
405         return err;
406 }
407
408 int commit_inmem_pages(struct inode *inode)
409 {
410         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
411         struct f2fs_inode_info *fi = F2FS_I(inode);
412         struct list_head revoke_list;
413         int err;
414
415         INIT_LIST_HEAD(&revoke_list);
416         f2fs_balance_fs(sbi, true);
417         f2fs_lock_op(sbi);
418
419         set_inode_flag(inode, FI_ATOMIC_COMMIT);
420
421         mutex_lock(&fi->inmem_lock);
422         err = __commit_inmem_pages(inode, &revoke_list);
423         if (err) {
424                 int ret;
425                 /*
426                  * try to revoke all committed pages, but still we could fail
427                  * due to no memory or other reason, if that happened, EAGAIN
428                  * will be returned, which means in such case, transaction is
429                  * already not integrity, caller should use journal to do the
430                  * recovery or rewrite & commit last transaction. For other
431                  * error number, revoking was done by filesystem itself.
432                  */
433                 ret = __revoke_inmem_pages(inode, &revoke_list, false, true);
434                 if (ret)
435                         err = ret;
436
437                 /* drop all uncommitted pages */
438                 __revoke_inmem_pages(inode, &fi->inmem_pages, true, false);
439         }
440         spin_lock(&sbi->inode_lock[ATOMIC_FILE]);
441         if (!list_empty(&fi->inmem_ilist))
442                 list_del_init(&fi->inmem_ilist);
443         spin_unlock(&sbi->inode_lock[ATOMIC_FILE]);
444         mutex_unlock(&fi->inmem_lock);
445
446         clear_inode_flag(inode, FI_ATOMIC_COMMIT);
447
448         f2fs_unlock_op(sbi);
449         return err;
450 }
451
452 /*
453  * This function balances dirty node and dentry pages.
454  * In addition, it controls garbage collection.
455  */
456 void f2fs_balance_fs(struct f2fs_sb_info *sbi, bool need)
457 {
458 #ifdef CONFIG_F2FS_FAULT_INJECTION
459         if (time_to_inject(sbi, FAULT_CHECKPOINT)) {
460                 f2fs_show_injection_info(FAULT_CHECKPOINT);
461                 f2fs_stop_checkpoint(sbi, false);
462         }
463 #endif
464
465         /* balance_fs_bg is able to be pending */
466         if (need && excess_cached_nats(sbi))
467                 f2fs_balance_fs_bg(sbi);
468
469         /*
470          * We should do GC or end up with checkpoint, if there are so many dirty
471          * dir/node pages without enough free segments.
472          */
473         if (has_not_enough_free_secs(sbi, 0, 0)) {
474                 mutex_lock(&sbi->gc_mutex);
475                 f2fs_gc(sbi, false, false, NULL_SEGNO);
476         }
477 }
478
479 void f2fs_balance_fs_bg(struct f2fs_sb_info *sbi)
480 {
481         if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
482                 return;
483
484         /* try to shrink extent cache when there is no enough memory */
485         if (!available_free_memory(sbi, EXTENT_CACHE))
486                 f2fs_shrink_extent_tree(sbi, EXTENT_CACHE_SHRINK_NUMBER);
487
488         /* check the # of cached NAT entries */
489         if (!available_free_memory(sbi, NAT_ENTRIES))
490                 try_to_free_nats(sbi, NAT_ENTRY_PER_BLOCK);
491
492         if (!available_free_memory(sbi, FREE_NIDS))
493                 try_to_free_nids(sbi, MAX_FREE_NIDS);
494         else
495                 build_free_nids(sbi, false, false);
496
497         if (!is_idle(sbi) && !excess_dirty_nats(sbi))
498                 return;
499
500         /* checkpoint is the only way to shrink partial cached entries */
501         if (!available_free_memory(sbi, NAT_ENTRIES) ||
502                         !available_free_memory(sbi, INO_ENTRIES) ||
503                         excess_prefree_segs(sbi) ||
504                         excess_dirty_nats(sbi) ||
505                         f2fs_time_over(sbi, CP_TIME)) {
506                 if (test_opt(sbi, DATA_FLUSH)) {
507                         struct blk_plug plug;
508
509                         blk_start_plug(&plug);
510                         sync_dirty_inodes(sbi, FILE_INODE);
511                         blk_finish_plug(&plug);
512                 }
513                 f2fs_sync_fs(sbi->sb, true);
514                 stat_inc_bg_cp_count(sbi->stat_info);
515         }
516 }
517
518 static int __submit_flush_wait(struct f2fs_sb_info *sbi,
519                                 struct block_device *bdev)
520 {
521         struct bio *bio = f2fs_bio_alloc(sbi, 0, true);
522         int ret;
523
524         bio->bi_rw = REQ_OP_WRITE;
525         bio->bi_bdev = bdev;
526         ret = submit_bio_wait(WRITE_FLUSH, bio);
527         bio_put(bio);
528
529         trace_f2fs_issue_flush(bdev, test_opt(sbi, NOBARRIER),
530                                 test_opt(sbi, FLUSH_MERGE), ret);
531         return ret;
532 }
533
534 static int submit_flush_wait(struct f2fs_sb_info *sbi, nid_t ino)
535 {
536         int ret = 0;
537         int i;
538
539         if (!sbi->s_ndevs)
540                 return __submit_flush_wait(sbi, sbi->sb->s_bdev);
541
542         for (i = 0; i < sbi->s_ndevs; i++) {
543                 if (!is_dirty_device(sbi, ino, i, FLUSH_INO))
544                         continue;
545                 ret = __submit_flush_wait(sbi, FDEV(i).bdev);
546                 if (ret)
547                         break;
548         }
549         return ret;
550 }
551
552 static int issue_flush_thread(void *data)
553 {
554         struct f2fs_sb_info *sbi = data;
555         struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
556         wait_queue_head_t *q = &fcc->flush_wait_queue;
557 repeat:
558         if (kthread_should_stop())
559                 return 0;
560
561         sb_start_intwrite(sbi->sb);
562
563         if (!llist_empty(&fcc->issue_list)) {
564                 struct flush_cmd *cmd, *next;
565                 int ret;
566
567                 fcc->dispatch_list = llist_del_all(&fcc->issue_list);
568                 fcc->dispatch_list = llist_reverse_order(fcc->dispatch_list);
569
570                 cmd = llist_entry(fcc->dispatch_list, struct flush_cmd, llnode);
571
572                 ret = submit_flush_wait(sbi, cmd->ino);
573                 atomic_inc(&fcc->issued_flush);
574
575                 llist_for_each_entry_safe(cmd, next,
576                                           fcc->dispatch_list, llnode) {
577                         cmd->ret = ret;
578                         complete(&cmd->wait);
579                 }
580                 fcc->dispatch_list = NULL;
581         }
582
583         sb_end_intwrite(sbi->sb);
584
585         wait_event_interruptible(*q,
586                 kthread_should_stop() || !llist_empty(&fcc->issue_list));
587         goto repeat;
588 }
589
590 int f2fs_issue_flush(struct f2fs_sb_info *sbi, nid_t ino)
591 {
592         struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
593         struct flush_cmd cmd;
594         int ret;
595
596         if (test_opt(sbi, NOBARRIER))
597                 return 0;
598
599         if (!test_opt(sbi, FLUSH_MERGE)) {
600                 ret = submit_flush_wait(sbi, ino);
601                 atomic_inc(&fcc->issued_flush);
602                 return ret;
603         }
604
605         if (atomic_inc_return(&fcc->issing_flush) == 1 || sbi->s_ndevs > 1) {
606                 ret = submit_flush_wait(sbi, ino);
607                 atomic_dec(&fcc->issing_flush);
608
609                 atomic_inc(&fcc->issued_flush);
610                 return ret;
611         }
612
613         cmd.ino = ino;
614         init_completion(&cmd.wait);
615
616         llist_add(&cmd.llnode, &fcc->issue_list);
617
618         /* update issue_list before we wake up issue_flush thread */
619         smp_mb();
620
621         if (waitqueue_active(&fcc->flush_wait_queue))
622                 wake_up(&fcc->flush_wait_queue);
623
624         if (fcc->f2fs_issue_flush) {
625                 wait_for_completion(&cmd.wait);
626                 atomic_dec(&fcc->issing_flush);
627         } else {
628                 struct llist_node *list;
629
630                 list = llist_del_all(&fcc->issue_list);
631                 if (!list) {
632                         wait_for_completion(&cmd.wait);
633                         atomic_dec(&fcc->issing_flush);
634                 } else {
635                         struct flush_cmd *tmp, *next;
636
637                         ret = submit_flush_wait(sbi, ino);
638
639                         llist_for_each_entry_safe(tmp, next, list, llnode) {
640                                 if (tmp == &cmd) {
641                                         cmd.ret = ret;
642                                         atomic_dec(&fcc->issing_flush);
643                                         continue;
644                                 }
645                                 tmp->ret = ret;
646                                 complete(&tmp->wait);
647                         }
648                 }
649         }
650
651         return cmd.ret;
652 }
653
654 int create_flush_cmd_control(struct f2fs_sb_info *sbi)
655 {
656         dev_t dev = sbi->sb->s_bdev->bd_dev;
657         struct flush_cmd_control *fcc;
658         int err = 0;
659
660         if (SM_I(sbi)->fcc_info) {
661                 fcc = SM_I(sbi)->fcc_info;
662                 if (fcc->f2fs_issue_flush)
663                         return err;
664                 goto init_thread;
665         }
666
667         fcc = f2fs_kzalloc(sbi, sizeof(struct flush_cmd_control), GFP_KERNEL);
668         if (!fcc)
669                 return -ENOMEM;
670         atomic_set(&fcc->issued_flush, 0);
671         atomic_set(&fcc->issing_flush, 0);
672         init_waitqueue_head(&fcc->flush_wait_queue);
673         init_llist_head(&fcc->issue_list);
674         SM_I(sbi)->fcc_info = fcc;
675         if (!test_opt(sbi, FLUSH_MERGE))
676                 return err;
677
678 init_thread:
679         fcc->f2fs_issue_flush = kthread_run(issue_flush_thread, sbi,
680                                 "f2fs_flush-%u:%u", MAJOR(dev), MINOR(dev));
681         if (IS_ERR(fcc->f2fs_issue_flush)) {
682                 err = PTR_ERR(fcc->f2fs_issue_flush);
683                 kfree(fcc);
684                 SM_I(sbi)->fcc_info = NULL;
685                 return err;
686         }
687
688         return err;
689 }
690
691 void destroy_flush_cmd_control(struct f2fs_sb_info *sbi, bool free)
692 {
693         struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
694
695         if (fcc && fcc->f2fs_issue_flush) {
696                 struct task_struct *flush_thread = fcc->f2fs_issue_flush;
697
698                 fcc->f2fs_issue_flush = NULL;
699                 kthread_stop(flush_thread);
700         }
701         if (free) {
702                 kfree(fcc);
703                 SM_I(sbi)->fcc_info = NULL;
704         }
705 }
706
707 int f2fs_flush_device_cache(struct f2fs_sb_info *sbi)
708 {
709         int ret = 0, i;
710
711         if (!sbi->s_ndevs)
712                 return 0;
713
714         for (i = 1; i < sbi->s_ndevs; i++) {
715                 if (!f2fs_test_bit(i, (char *)&sbi->dirty_device))
716                         continue;
717                 ret = __submit_flush_wait(sbi, FDEV(i).bdev);
718                 if (ret)
719                         break;
720
721                 spin_lock(&sbi->dev_lock);
722                 f2fs_clear_bit(i, (char *)&sbi->dirty_device);
723                 spin_unlock(&sbi->dev_lock);
724         }
725
726         return ret;
727 }
728
729 static void __locate_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno,
730                 enum dirty_type dirty_type)
731 {
732         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
733
734         /* need not be added */
735         if (IS_CURSEG(sbi, segno))
736                 return;
737
738         if (!test_and_set_bit(segno, dirty_i->dirty_segmap[dirty_type]))
739                 dirty_i->nr_dirty[dirty_type]++;
740
741         if (dirty_type == DIRTY) {
742                 struct seg_entry *sentry = get_seg_entry(sbi, segno);
743                 enum dirty_type t = sentry->type;
744
745                 if (unlikely(t >= DIRTY)) {
746                         f2fs_bug_on(sbi, 1);
747                         return;
748                 }
749                 if (!test_and_set_bit(segno, dirty_i->dirty_segmap[t]))
750                         dirty_i->nr_dirty[t]++;
751         }
752 }
753
754 static void __remove_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno,
755                 enum dirty_type dirty_type)
756 {
757         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
758
759         if (test_and_clear_bit(segno, dirty_i->dirty_segmap[dirty_type]))
760                 dirty_i->nr_dirty[dirty_type]--;
761
762         if (dirty_type == DIRTY) {
763                 struct seg_entry *sentry = get_seg_entry(sbi, segno);
764                 enum dirty_type t = sentry->type;
765
766                 if (test_and_clear_bit(segno, dirty_i->dirty_segmap[t]))
767                         dirty_i->nr_dirty[t]--;
768
769                 if (get_valid_blocks(sbi, segno, true) == 0)
770                         clear_bit(GET_SEC_FROM_SEG(sbi, segno),
771                                                 dirty_i->victim_secmap);
772         }
773 }
774
775 /*
776  * Should not occur error such as -ENOMEM.
777  * Adding dirty entry into seglist is not critical operation.
778  * If a given segment is one of current working segments, it won't be added.
779  */
780 static void locate_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno)
781 {
782         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
783         unsigned short valid_blocks;
784
785         if (segno == NULL_SEGNO || IS_CURSEG(sbi, segno))
786                 return;
787
788         mutex_lock(&dirty_i->seglist_lock);
789
790         valid_blocks = get_valid_blocks(sbi, segno, false);
791
792         if (valid_blocks == 0) {
793                 __locate_dirty_segment(sbi, segno, PRE);
794                 __remove_dirty_segment(sbi, segno, DIRTY);
795         } else if (valid_blocks < sbi->blocks_per_seg) {
796                 __locate_dirty_segment(sbi, segno, DIRTY);
797         } else {
798                 /* Recovery routine with SSR needs this */
799                 __remove_dirty_segment(sbi, segno, DIRTY);
800         }
801
802         mutex_unlock(&dirty_i->seglist_lock);
803 }
804
805 static struct discard_cmd *__create_discard_cmd(struct f2fs_sb_info *sbi,
806                 struct block_device *bdev, block_t lstart,
807                 block_t start, block_t len)
808 {
809         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
810         struct list_head *pend_list;
811         struct discard_cmd *dc;
812
813         f2fs_bug_on(sbi, !len);
814
815         pend_list = &dcc->pend_list[plist_idx(len)];
816
817         dc = f2fs_kmem_cache_alloc(discard_cmd_slab, GFP_NOFS);
818         INIT_LIST_HEAD(&dc->list);
819         dc->bdev = bdev;
820         dc->lstart = lstart;
821         dc->start = start;
822         dc->len = len;
823         dc->ref = 0;
824         dc->state = D_PREP;
825         dc->error = 0;
826         init_completion(&dc->wait);
827         list_add_tail(&dc->list, pend_list);
828         atomic_inc(&dcc->discard_cmd_cnt);
829         dcc->undiscard_blks += len;
830
831         return dc;
832 }
833
834 static struct discard_cmd *__attach_discard_cmd(struct f2fs_sb_info *sbi,
835                                 struct block_device *bdev, block_t lstart,
836                                 block_t start, block_t len,
837                                 struct rb_node *parent, struct rb_node **p)
838 {
839         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
840         struct discard_cmd *dc;
841
842         dc = __create_discard_cmd(sbi, bdev, lstart, start, len);
843
844         rb_link_node(&dc->rb_node, parent, p);
845         rb_insert_color(&dc->rb_node, &dcc->root);
846
847         return dc;
848 }
849
850 static void __detach_discard_cmd(struct discard_cmd_control *dcc,
851                                                         struct discard_cmd *dc)
852 {
853         if (dc->state == D_DONE)
854                 atomic_dec(&dcc->issing_discard);
855
856         list_del(&dc->list);
857         rb_erase(&dc->rb_node, &dcc->root);
858         dcc->undiscard_blks -= dc->len;
859
860         kmem_cache_free(discard_cmd_slab, dc);
861
862         atomic_dec(&dcc->discard_cmd_cnt);
863 }
864
865 static void __remove_discard_cmd(struct f2fs_sb_info *sbi,
866                                                         struct discard_cmd *dc)
867 {
868         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
869
870         trace_f2fs_remove_discard(dc->bdev, dc->start, dc->len);
871
872         f2fs_bug_on(sbi, dc->ref);
873
874         if (dc->error == -EOPNOTSUPP)
875                 dc->error = 0;
876
877         if (dc->error)
878                 f2fs_msg(sbi->sb, KERN_INFO,
879                         "Issue discard(%u, %u, %u) failed, ret: %d",
880                         dc->lstart, dc->start, dc->len, dc->error);
881         __detach_discard_cmd(dcc, dc);
882 }
883
884 static void f2fs_submit_discard_endio(struct bio *bio)
885 {
886         struct discard_cmd *dc = (struct discard_cmd *)bio->bi_private;
887
888         dc->error = bio->bi_error;
889         dc->state = D_DONE;
890         complete_all(&dc->wait);
891         bio_put(bio);
892 }
893
894 /* copied from block/blk-lib.c in 4.10-rc1 */
895 static int __blkdev_issue_discard(struct block_device *bdev, sector_t sector,
896                 sector_t nr_sects, gfp_t gfp_mask, int flags,
897                 struct bio **biop)
898 {
899         struct request_queue *q = bdev_get_queue(bdev);
900         struct bio *bio = *biop;
901         unsigned int granularity;
902         int op = REQ_WRITE | REQ_DISCARD;
903         int alignment;
904         sector_t bs_mask;
905
906         if (!q)
907                 return -ENXIO;
908
909         if (!blk_queue_discard(q))
910                 return -EOPNOTSUPP;
911
912         if (flags & BLKDEV_DISCARD_SECURE) {
913                 if (!blk_queue_secdiscard(q))
914                         return -EOPNOTSUPP;
915                 op |= REQ_SECURE;
916         }
917
918         bs_mask = (bdev_logical_block_size(bdev) >> 9) - 1;
919         if ((sector | nr_sects) & bs_mask)
920                 return -EINVAL;
921
922         /* Zero-sector (unknown) and one-sector granularities are the same.  */
923         granularity = max(q->limits.discard_granularity >> 9, 1U);
924         alignment = (bdev_discard_alignment(bdev) >> 9) % granularity;
925
926         while (nr_sects) {
927                 unsigned int req_sects;
928                 sector_t end_sect, tmp;
929
930                 /* Make sure bi_size doesn't overflow */
931                 req_sects = min_t(sector_t, nr_sects, UINT_MAX >> 9);
932
933                 /**
934                  * If splitting a request, and the next starting sector would be
935                  * misaligned, stop the discard at the previous aligned sector.
936                  */
937                 end_sect = sector + req_sects;
938                 tmp = end_sect;
939                 if (req_sects < nr_sects &&
940                     sector_div(tmp, granularity) != alignment) {
941                         end_sect = end_sect - alignment;
942                         sector_div(end_sect, granularity);
943                         end_sect = end_sect * granularity + alignment;
944                         req_sects = end_sect - sector;
945                 }
946
947                 if (bio) {
948                         int ret = submit_bio_wait(op, bio);
949                         bio_put(bio);
950                         if (ret)
951                                 return ret;
952                 }
953                 bio = bio_alloc(GFP_NOIO | __GFP_NOFAIL, 1);
954                 bio->bi_iter.bi_sector = sector;
955                 bio->bi_bdev = bdev;
956                 bio_set_op_attrs(bio, op, 0);
957
958                 bio->bi_iter.bi_size = req_sects << 9;
959                 nr_sects -= req_sects;
960                 sector = end_sect;
961
962                 /*
963                  * We can loop for a long time in here, if someone does
964                  * full device discards (like mkfs). Be nice and allow
965                  * us to schedule out to avoid softlocking if preempt
966                  * is disabled.
967                  */
968                 cond_resched();
969         }
970
971         *biop = bio;
972         return 0;
973 }
974
975 static void __check_sit_bitmap(struct f2fs_sb_info *sbi,
976                                 block_t start, block_t end)
977 {
978 #ifdef CONFIG_F2FS_CHECK_FS
979         struct seg_entry *sentry;
980         unsigned int segno;
981         block_t blk = start;
982         unsigned long offset, size, max_blocks = sbi->blocks_per_seg;
983         unsigned long *map;
984
985         while (blk < end) {
986                 segno = GET_SEGNO(sbi, blk);
987                 sentry = get_seg_entry(sbi, segno);
988                 offset = GET_BLKOFF_FROM_SEG0(sbi, blk);
989
990                 if (end < START_BLOCK(sbi, segno + 1))
991                         size = GET_BLKOFF_FROM_SEG0(sbi, end);
992                 else
993                         size = max_blocks;
994                 map = (unsigned long *)(sentry->cur_valid_map);
995                 offset = __find_rev_next_bit(map, size, offset);
996                 f2fs_bug_on(sbi, offset != size);
997                 blk = START_BLOCK(sbi, segno + 1);
998         }
999 #endif
1000 }
1001
1002 static void __init_discard_policy(struct f2fs_sb_info *sbi,
1003                                 struct discard_policy *dpolicy,
1004                                 int discard_type, unsigned int granularity)
1005 {
1006         /* common policy */
1007         dpolicy->type = discard_type;
1008         dpolicy->sync = true;
1009         dpolicy->granularity = granularity;
1010
1011         dpolicy->max_requests = DEF_MAX_DISCARD_REQUEST;
1012         dpolicy->io_aware_gran = MAX_PLIST_NUM;
1013
1014         if (discard_type == DPOLICY_BG) {
1015                 dpolicy->min_interval = DEF_MIN_DISCARD_ISSUE_TIME;
1016                 dpolicy->max_interval = DEF_MAX_DISCARD_ISSUE_TIME;
1017                 dpolicy->io_aware = true;
1018                 dpolicy->sync = false;
1019                 if (utilization(sbi) > DEF_DISCARD_URGENT_UTIL) {
1020                         dpolicy->granularity = 1;
1021                         dpolicy->max_interval = DEF_MIN_DISCARD_ISSUE_TIME;
1022                 }
1023         } else if (discard_type == DPOLICY_FORCE) {
1024                 dpolicy->min_interval = DEF_MIN_DISCARD_ISSUE_TIME;
1025                 dpolicy->max_interval = DEF_MAX_DISCARD_ISSUE_TIME;
1026                 dpolicy->io_aware = false;
1027         } else if (discard_type == DPOLICY_FSTRIM) {
1028                 dpolicy->io_aware = false;
1029         } else if (discard_type == DPOLICY_UMOUNT) {
1030                 dpolicy->io_aware = false;
1031         }
1032 }
1033
1034
1035 /* this function is copied from blkdev_issue_discard from block/blk-lib.c */
1036 static void __submit_discard_cmd(struct f2fs_sb_info *sbi,
1037                                                 struct discard_policy *dpolicy,
1038                                                 struct discard_cmd *dc)
1039 {
1040         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1041         struct list_head *wait_list = (dpolicy->type == DPOLICY_FSTRIM) ?
1042                                         &(dcc->fstrim_list) : &(dcc->wait_list);
1043         struct bio *bio = NULL;
1044         int flag = dpolicy->sync ? REQ_SYNC : 0;
1045
1046         if (dc->state != D_PREP)
1047                 return;
1048
1049         trace_f2fs_issue_discard(dc->bdev, dc->start, dc->len);
1050
1051         dc->error = __blkdev_issue_discard(dc->bdev,
1052                                 SECTOR_FROM_BLOCK(dc->start),
1053                                 SECTOR_FROM_BLOCK(dc->len),
1054                                 GFP_NOFS, 0, &bio);
1055         if (!dc->error) {
1056                 /* should keep before submission to avoid D_DONE right away */
1057                 dc->state = D_SUBMIT;
1058                 atomic_inc(&dcc->issued_discard);
1059                 atomic_inc(&dcc->issing_discard);
1060                 if (bio) {
1061                         bio->bi_private = dc;
1062                         bio->bi_end_io = f2fs_submit_discard_endio;
1063                         submit_bio(flag, bio);
1064                         list_move_tail(&dc->list, wait_list);
1065                         __check_sit_bitmap(sbi, dc->start, dc->start + dc->len);
1066
1067                         f2fs_update_iostat(sbi, FS_DISCARD, 1);
1068                 }
1069         } else {
1070                 __remove_discard_cmd(sbi, dc);
1071         }
1072 }
1073
1074 static struct discard_cmd *__insert_discard_tree(struct f2fs_sb_info *sbi,
1075                                 struct block_device *bdev, block_t lstart,
1076                                 block_t start, block_t len,
1077                                 struct rb_node **insert_p,
1078                                 struct rb_node *insert_parent)
1079 {
1080         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1081         struct rb_node **p;
1082         struct rb_node *parent = NULL;
1083         struct discard_cmd *dc = NULL;
1084
1085         if (insert_p && insert_parent) {
1086                 parent = insert_parent;
1087                 p = insert_p;
1088                 goto do_insert;
1089         }
1090
1091         p = __lookup_rb_tree_for_insert(sbi, &dcc->root, &parent, lstart);
1092 do_insert:
1093         dc = __attach_discard_cmd(sbi, bdev, lstart, start, len, parent, p);
1094         if (!dc)
1095                 return NULL;
1096
1097         return dc;
1098 }
1099
1100 static void __relocate_discard_cmd(struct discard_cmd_control *dcc,
1101                                                 struct discard_cmd *dc)
1102 {
1103         list_move_tail(&dc->list, &dcc->pend_list[plist_idx(dc->len)]);
1104 }
1105
1106 static void __punch_discard_cmd(struct f2fs_sb_info *sbi,
1107                                 struct discard_cmd *dc, block_t blkaddr)
1108 {
1109         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1110         struct discard_info di = dc->di;
1111         bool modified = false;
1112
1113         if (dc->state == D_DONE || dc->len == 1) {
1114                 __remove_discard_cmd(sbi, dc);
1115                 return;
1116         }
1117
1118         dcc->undiscard_blks -= di.len;
1119
1120         if (blkaddr > di.lstart) {
1121                 dc->len = blkaddr - dc->lstart;
1122                 dcc->undiscard_blks += dc->len;
1123                 __relocate_discard_cmd(dcc, dc);
1124                 modified = true;
1125         }
1126
1127         if (blkaddr < di.lstart + di.len - 1) {
1128                 if (modified) {
1129                         __insert_discard_tree(sbi, dc->bdev, blkaddr + 1,
1130                                         di.start + blkaddr + 1 - di.lstart,
1131                                         di.lstart + di.len - 1 - blkaddr,
1132                                         NULL, NULL);
1133                 } else {
1134                         dc->lstart++;
1135                         dc->len--;
1136                         dc->start++;
1137                         dcc->undiscard_blks += dc->len;
1138                         __relocate_discard_cmd(dcc, dc);
1139                 }
1140         }
1141 }
1142
1143 static void __update_discard_tree_range(struct f2fs_sb_info *sbi,
1144                                 struct block_device *bdev, block_t lstart,
1145                                 block_t start, block_t len)
1146 {
1147         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1148         struct discard_cmd *prev_dc = NULL, *next_dc = NULL;
1149         struct discard_cmd *dc;
1150         struct discard_info di = {0};
1151         struct rb_node **insert_p = NULL, *insert_parent = NULL;
1152         block_t end = lstart + len;
1153
1154         mutex_lock(&dcc->cmd_lock);
1155
1156         dc = (struct discard_cmd *)__lookup_rb_tree_ret(&dcc->root,
1157                                         NULL, lstart,
1158                                         (struct rb_entry **)&prev_dc,
1159                                         (struct rb_entry **)&next_dc,
1160                                         &insert_p, &insert_parent, true);
1161         if (dc)
1162                 prev_dc = dc;
1163
1164         if (!prev_dc) {
1165                 di.lstart = lstart;
1166                 di.len = next_dc ? next_dc->lstart - lstart : len;
1167                 di.len = min(di.len, len);
1168                 di.start = start;
1169         }
1170
1171         while (1) {
1172                 struct rb_node *node;
1173                 bool merged = false;
1174                 struct discard_cmd *tdc = NULL;
1175
1176                 if (prev_dc) {
1177                         di.lstart = prev_dc->lstart + prev_dc->len;
1178                         if (di.lstart < lstart)
1179                                 di.lstart = lstart;
1180                         if (di.lstart >= end)
1181                                 break;
1182
1183                         if (!next_dc || next_dc->lstart > end)
1184                                 di.len = end - di.lstart;
1185                         else
1186                                 di.len = next_dc->lstart - di.lstart;
1187                         di.start = start + di.lstart - lstart;
1188                 }
1189
1190                 if (!di.len)
1191                         goto next;
1192
1193                 if (prev_dc && prev_dc->state == D_PREP &&
1194                         prev_dc->bdev == bdev &&
1195                         __is_discard_back_mergeable(&di, &prev_dc->di)) {
1196                         prev_dc->di.len += di.len;
1197                         dcc->undiscard_blks += di.len;
1198                         __relocate_discard_cmd(dcc, prev_dc);
1199                         di = prev_dc->di;
1200                         tdc = prev_dc;
1201                         merged = true;
1202                 }
1203
1204                 if (next_dc && next_dc->state == D_PREP &&
1205                         next_dc->bdev == bdev &&
1206                         __is_discard_front_mergeable(&di, &next_dc->di)) {
1207                         next_dc->di.lstart = di.lstart;
1208                         next_dc->di.len += di.len;
1209                         next_dc->di.start = di.start;
1210                         dcc->undiscard_blks += di.len;
1211                         __relocate_discard_cmd(dcc, next_dc);
1212                         if (tdc)
1213                                 __remove_discard_cmd(sbi, tdc);
1214                         merged = true;
1215                 }
1216
1217                 if (!merged) {
1218                         __insert_discard_tree(sbi, bdev, di.lstart, di.start,
1219                                                         di.len, NULL, NULL);
1220                 }
1221  next:
1222                 prev_dc = next_dc;
1223                 if (!prev_dc)
1224                         break;
1225
1226                 node = rb_next(&prev_dc->rb_node);
1227                 next_dc = rb_entry_safe(node, struct discard_cmd, rb_node);
1228         }
1229
1230         mutex_unlock(&dcc->cmd_lock);
1231 }
1232
1233 static int __queue_discard_cmd(struct f2fs_sb_info *sbi,
1234                 struct block_device *bdev, block_t blkstart, block_t blklen)
1235 {
1236         block_t lblkstart = blkstart;
1237
1238         trace_f2fs_queue_discard(bdev, blkstart, blklen);
1239
1240         if (sbi->s_ndevs) {
1241                 int devi = f2fs_target_device_index(sbi, blkstart);
1242
1243                 blkstart -= FDEV(devi).start_blk;
1244         }
1245         __update_discard_tree_range(sbi, bdev, lblkstart, blkstart, blklen);
1246         return 0;
1247 }
1248
1249 static int __issue_discard_cmd(struct f2fs_sb_info *sbi,
1250                                         struct discard_policy *dpolicy)
1251 {
1252         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1253         struct list_head *pend_list;
1254         struct discard_cmd *dc, *tmp;
1255         struct blk_plug plug;
1256         int i, iter = 0, issued = 0;
1257         bool io_interrupted = false;
1258
1259         for (i = MAX_PLIST_NUM - 1; i >= 0; i--) {
1260                 if (i + 1 < dpolicy->granularity)
1261                         break;
1262                 pend_list = &dcc->pend_list[i];
1263
1264                 mutex_lock(&dcc->cmd_lock);
1265                 if (list_empty(pend_list))
1266                         goto next;
1267                 f2fs_bug_on(sbi, !__check_rb_tree_consistence(sbi, &dcc->root));
1268                 blk_start_plug(&plug);
1269                 list_for_each_entry_safe(dc, tmp, pend_list, list) {
1270                         f2fs_bug_on(sbi, dc->state != D_PREP);
1271
1272                         if (dpolicy->io_aware && i < dpolicy->io_aware_gran &&
1273                                                                 !is_idle(sbi)) {
1274                                 io_interrupted = true;
1275                                 goto skip;
1276                         }
1277
1278                         __submit_discard_cmd(sbi, dpolicy, dc);
1279                         issued++;
1280 skip:
1281                         if (++iter >= dpolicy->max_requests)
1282                                 break;
1283                 }
1284                 blk_finish_plug(&plug);
1285 next:
1286                 mutex_unlock(&dcc->cmd_lock);
1287
1288                 if (iter >= dpolicy->max_requests)
1289                         break;
1290         }
1291
1292         if (!issued && io_interrupted)
1293                 issued = -1;
1294
1295         return issued;
1296 }
1297
1298 static bool __drop_discard_cmd(struct f2fs_sb_info *sbi)
1299 {
1300         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1301         struct list_head *pend_list;
1302         struct discard_cmd *dc, *tmp;
1303         int i;
1304         bool dropped = false;
1305
1306         mutex_lock(&dcc->cmd_lock);
1307         for (i = MAX_PLIST_NUM - 1; i >= 0; i--) {
1308                 pend_list = &dcc->pend_list[i];
1309                 list_for_each_entry_safe(dc, tmp, pend_list, list) {
1310                         f2fs_bug_on(sbi, dc->state != D_PREP);
1311                         __remove_discard_cmd(sbi, dc);
1312                         dropped = true;
1313                 }
1314         }
1315         mutex_unlock(&dcc->cmd_lock);
1316
1317         return dropped;
1318 }
1319
1320 void drop_discard_cmd(struct f2fs_sb_info *sbi)
1321 {
1322         __drop_discard_cmd(sbi);
1323 }
1324
1325 static unsigned int __wait_one_discard_bio(struct f2fs_sb_info *sbi,
1326                                                         struct discard_cmd *dc)
1327 {
1328         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1329         unsigned int len = 0;
1330
1331         wait_for_completion_io(&dc->wait);
1332         mutex_lock(&dcc->cmd_lock);
1333         f2fs_bug_on(sbi, dc->state != D_DONE);
1334         dc->ref--;
1335         if (!dc->ref) {
1336                 if (!dc->error)
1337                         len = dc->len;
1338                 __remove_discard_cmd(sbi, dc);
1339         }
1340         mutex_unlock(&dcc->cmd_lock);
1341
1342         return len;
1343 }
1344
1345 static unsigned int __wait_discard_cmd_range(struct f2fs_sb_info *sbi,
1346                                                 struct discard_policy *dpolicy,
1347                                                 block_t start, block_t end)
1348 {
1349         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1350         struct list_head *wait_list = (dpolicy->type == DPOLICY_FSTRIM) ?
1351                                         &(dcc->fstrim_list) : &(dcc->wait_list);
1352         struct discard_cmd *dc, *tmp;
1353         bool need_wait;
1354         unsigned int trimmed = 0;
1355
1356 next:
1357         need_wait = false;
1358
1359         mutex_lock(&dcc->cmd_lock);
1360         list_for_each_entry_safe(dc, tmp, wait_list, list) {
1361                 if (dc->lstart + dc->len <= start || end <= dc->lstart)
1362                         continue;
1363                 if (dc->len < dpolicy->granularity)
1364                         continue;
1365                 if (dc->state == D_DONE && !dc->ref) {
1366                         wait_for_completion_io(&dc->wait);
1367                         if (!dc->error)
1368                                 trimmed += dc->len;
1369                         __remove_discard_cmd(sbi, dc);
1370                 } else {
1371                         dc->ref++;
1372                         need_wait = true;
1373                         break;
1374                 }
1375         }
1376         mutex_unlock(&dcc->cmd_lock);
1377
1378         if (need_wait) {
1379                 trimmed += __wait_one_discard_bio(sbi, dc);
1380                 goto next;
1381         }
1382
1383         return trimmed;
1384 }
1385
1386 static void __wait_all_discard_cmd(struct f2fs_sb_info *sbi,
1387                                                 struct discard_policy *dpolicy)
1388 {
1389         struct discard_policy dp;
1390
1391         if (dpolicy) {
1392                 __wait_discard_cmd_range(sbi, dpolicy, 0, UINT_MAX);
1393                 return;
1394         }
1395
1396         /* wait all */
1397         __init_discard_policy(sbi, &dp, DPOLICY_FSTRIM, 1);
1398         __wait_discard_cmd_range(sbi, &dp, 0, UINT_MAX);
1399         __init_discard_policy(sbi, &dp, DPOLICY_UMOUNT, 1);
1400         __wait_discard_cmd_range(sbi, &dp, 0, UINT_MAX);
1401 }
1402
1403 /* This should be covered by global mutex, &sit_i->sentry_lock */
1404 static void f2fs_wait_discard_bio(struct f2fs_sb_info *sbi, block_t blkaddr)
1405 {
1406         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1407         struct discard_cmd *dc;
1408         bool need_wait = false;
1409
1410         mutex_lock(&dcc->cmd_lock);
1411         dc = (struct discard_cmd *)__lookup_rb_tree(&dcc->root, NULL, blkaddr);
1412         if (dc) {
1413                 if (dc->state == D_PREP) {
1414                         __punch_discard_cmd(sbi, dc, blkaddr);
1415                 } else {
1416                         dc->ref++;
1417                         need_wait = true;
1418                 }
1419         }
1420         mutex_unlock(&dcc->cmd_lock);
1421
1422         if (need_wait)
1423                 __wait_one_discard_bio(sbi, dc);
1424 }
1425
1426 void stop_discard_thread(struct f2fs_sb_info *sbi)
1427 {
1428         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1429
1430         if (dcc && dcc->f2fs_issue_discard) {
1431                 struct task_struct *discard_thread = dcc->f2fs_issue_discard;
1432
1433                 dcc->f2fs_issue_discard = NULL;
1434                 kthread_stop(discard_thread);
1435         }
1436 }
1437
1438 /* This comes from f2fs_put_super */
1439 bool f2fs_wait_discard_bios(struct f2fs_sb_info *sbi)
1440 {
1441         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1442         struct discard_policy dpolicy;
1443         bool dropped;
1444
1445         __init_discard_policy(sbi, &dpolicy, DPOLICY_UMOUNT,
1446                                         dcc->discard_granularity);
1447         __issue_discard_cmd(sbi, &dpolicy);
1448         dropped = __drop_discard_cmd(sbi);
1449
1450         /* just to make sure there is no pending discard commands */
1451         __wait_all_discard_cmd(sbi, NULL);
1452         return dropped;
1453 }
1454
1455 static int issue_discard_thread(void *data)
1456 {
1457         struct f2fs_sb_info *sbi = data;
1458         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1459         wait_queue_head_t *q = &dcc->discard_wait_queue;
1460         struct discard_policy dpolicy;
1461         unsigned int wait_ms = DEF_MIN_DISCARD_ISSUE_TIME;
1462         int issued;
1463
1464         set_freezable();
1465
1466         do {
1467                 __init_discard_policy(sbi, &dpolicy, DPOLICY_BG,
1468                                         dcc->discard_granularity);
1469
1470                 wait_event_interruptible_timeout(*q,
1471                                 kthread_should_stop() || freezing(current) ||
1472                                 dcc->discard_wake,
1473                                 msecs_to_jiffies(wait_ms));
1474                 if (try_to_freeze())
1475                         continue;
1476                 if (f2fs_readonly(sbi->sb))
1477                         continue;
1478                 if (kthread_should_stop())
1479                         return 0;
1480
1481                 if (dcc->discard_wake)
1482                         dcc->discard_wake = 0;
1483
1484                 if (sbi->gc_thread && sbi->gc_thread->gc_urgent)
1485                         __init_discard_policy(sbi, &dpolicy, DPOLICY_FORCE, 1);
1486
1487                 sb_start_intwrite(sbi->sb);
1488
1489                 issued = __issue_discard_cmd(sbi, &dpolicy);
1490                 if (issued) {
1491                         __wait_all_discard_cmd(sbi, &dpolicy);
1492                         wait_ms = dpolicy.min_interval;
1493                 } else {
1494                         wait_ms = dpolicy.max_interval;
1495                 }
1496
1497                 sb_end_intwrite(sbi->sb);
1498
1499         } while (!kthread_should_stop());
1500         return 0;
1501 }
1502
1503 #ifdef CONFIG_BLK_DEV_ZONED
1504 static int __f2fs_issue_discard_zone(struct f2fs_sb_info *sbi,
1505                 struct block_device *bdev, block_t blkstart, block_t blklen)
1506 {
1507         sector_t sector, nr_sects;
1508         block_t lblkstart = blkstart;
1509         int devi = 0;
1510
1511         if (sbi->s_ndevs) {
1512                 devi = f2fs_target_device_index(sbi, blkstart);
1513                 blkstart -= FDEV(devi).start_blk;
1514         }
1515
1516         /*
1517          * We need to know the type of the zone: for conventional zones,
1518          * use regular discard if the drive supports it. For sequential
1519          * zones, reset the zone write pointer.
1520          */
1521         switch (get_blkz_type(sbi, bdev, blkstart)) {
1522
1523         case BLK_ZONE_TYPE_CONVENTIONAL:
1524                 if (!blk_queue_discard(bdev_get_queue(bdev)))
1525                         return 0;
1526                 return __queue_discard_cmd(sbi, bdev, lblkstart, blklen);
1527         case BLK_ZONE_TYPE_SEQWRITE_REQ:
1528         case BLK_ZONE_TYPE_SEQWRITE_PREF:
1529                 sector = SECTOR_FROM_BLOCK(blkstart);
1530                 nr_sects = SECTOR_FROM_BLOCK(blklen);
1531
1532                 if (sector & (bdev_zone_sectors(bdev) - 1) ||
1533                                 nr_sects != bdev_zone_sectors(bdev)) {
1534                         f2fs_msg(sbi->sb, KERN_INFO,
1535                                 "(%d) %s: Unaligned discard attempted (block %x + %x)",
1536                                 devi, sbi->s_ndevs ? FDEV(devi).path: "",
1537                                 blkstart, blklen);
1538                         return -EIO;
1539                 }
1540                 trace_f2fs_issue_reset_zone(bdev, blkstart);
1541                 return blkdev_reset_zones(bdev, sector,
1542                                           nr_sects, GFP_NOFS);
1543         default:
1544                 /* Unknown zone type: broken device ? */
1545                 return -EIO;
1546         }
1547 }
1548 #endif
1549
1550 static int __issue_discard_async(struct f2fs_sb_info *sbi,
1551                 struct block_device *bdev, block_t blkstart, block_t blklen)
1552 {
1553 #ifdef CONFIG_BLK_DEV_ZONED
1554         if (f2fs_sb_has_blkzoned(sbi->sb) &&
1555                                 bdev_zoned_model(bdev) != BLK_ZONED_NONE)
1556                 return __f2fs_issue_discard_zone(sbi, bdev, blkstart, blklen);
1557 #endif
1558         return __queue_discard_cmd(sbi, bdev, blkstart, blklen);
1559 }
1560
1561 static int f2fs_issue_discard(struct f2fs_sb_info *sbi,
1562                                 block_t blkstart, block_t blklen)
1563 {
1564         sector_t start = blkstart, len = 0;
1565         struct block_device *bdev;
1566         struct seg_entry *se;
1567         unsigned int offset;
1568         block_t i;
1569         int err = 0;
1570
1571         bdev = f2fs_target_device(sbi, blkstart, NULL);
1572
1573         for (i = blkstart; i < blkstart + blklen; i++, len++) {
1574                 if (i != start) {
1575                         struct block_device *bdev2 =
1576                                 f2fs_target_device(sbi, i, NULL);
1577
1578                         if (bdev2 != bdev) {
1579                                 err = __issue_discard_async(sbi, bdev,
1580                                                 start, len);
1581                                 if (err)
1582                                         return err;
1583                                 bdev = bdev2;
1584                                 start = i;
1585                                 len = 0;
1586                         }
1587                 }
1588
1589                 se = get_seg_entry(sbi, GET_SEGNO(sbi, i));
1590                 offset = GET_BLKOFF_FROM_SEG0(sbi, i);
1591
1592                 if (!f2fs_test_and_set_bit(offset, se->discard_map))
1593                         sbi->discard_blks--;
1594         }
1595
1596         if (len)
1597                 err = __issue_discard_async(sbi, bdev, start, len);
1598         return err;
1599 }
1600
1601 static bool add_discard_addrs(struct f2fs_sb_info *sbi, struct cp_control *cpc,
1602                                                         bool check_only)
1603 {
1604         int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
1605         int max_blocks = sbi->blocks_per_seg;
1606         struct seg_entry *se = get_seg_entry(sbi, cpc->trim_start);
1607         unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
1608         unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
1609         unsigned long *discard_map = (unsigned long *)se->discard_map;
1610         unsigned long *dmap = SIT_I(sbi)->tmp_map;
1611         unsigned int start = 0, end = -1;
1612         bool force = (cpc->reason & CP_DISCARD);
1613         struct discard_entry *de = NULL;
1614         struct list_head *head = &SM_I(sbi)->dcc_info->entry_list;
1615         int i;
1616
1617         if (se->valid_blocks == max_blocks || !f2fs_discard_en(sbi))
1618                 return false;
1619
1620         if (!force) {
1621                 if (!test_opt(sbi, DISCARD) || !se->valid_blocks ||
1622                         SM_I(sbi)->dcc_info->nr_discards >=
1623                                 SM_I(sbi)->dcc_info->max_discards)
1624                         return false;
1625         }
1626
1627         /* SIT_VBLOCK_MAP_SIZE should be multiple of sizeof(unsigned long) */
1628         for (i = 0; i < entries; i++)
1629                 dmap[i] = force ? ~ckpt_map[i] & ~discard_map[i] :
1630                                 (cur_map[i] ^ ckpt_map[i]) & ckpt_map[i];
1631
1632         while (force || SM_I(sbi)->dcc_info->nr_discards <=
1633                                 SM_I(sbi)->dcc_info->max_discards) {
1634                 start = __find_rev_next_bit(dmap, max_blocks, end + 1);
1635                 if (start >= max_blocks)
1636                         break;
1637
1638                 end = __find_rev_next_zero_bit(dmap, max_blocks, start + 1);
1639                 if (force && start && end != max_blocks
1640                                         && (end - start) < cpc->trim_minlen)
1641                         continue;
1642
1643                 if (check_only)
1644                         return true;
1645
1646                 if (!de) {
1647                         de = f2fs_kmem_cache_alloc(discard_entry_slab,
1648                                                                 GFP_F2FS_ZERO);
1649                         de->start_blkaddr = START_BLOCK(sbi, cpc->trim_start);
1650                         list_add_tail(&de->list, head);
1651                 }
1652
1653                 for (i = start; i < end; i++)
1654                         __set_bit_le(i, (void *)de->discard_map);
1655
1656                 SM_I(sbi)->dcc_info->nr_discards += end - start;
1657         }
1658         return false;
1659 }
1660
1661 void release_discard_addrs(struct f2fs_sb_info *sbi)
1662 {
1663         struct list_head *head = &(SM_I(sbi)->dcc_info->entry_list);
1664         struct discard_entry *entry, *this;
1665
1666         /* drop caches */
1667         list_for_each_entry_safe(entry, this, head, list) {
1668                 list_del(&entry->list);
1669                 kmem_cache_free(discard_entry_slab, entry);
1670         }
1671 }
1672
1673 /*
1674  * Should call clear_prefree_segments after checkpoint is done.
1675  */
1676 static void set_prefree_as_free_segments(struct f2fs_sb_info *sbi)
1677 {
1678         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
1679         unsigned int segno;
1680
1681         mutex_lock(&dirty_i->seglist_lock);
1682         for_each_set_bit(segno, dirty_i->dirty_segmap[PRE], MAIN_SEGS(sbi))
1683                 __set_test_and_free(sbi, segno);
1684         mutex_unlock(&dirty_i->seglist_lock);
1685 }
1686
1687 void clear_prefree_segments(struct f2fs_sb_info *sbi, struct cp_control *cpc)
1688 {
1689         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1690         struct list_head *head = &dcc->entry_list;
1691         struct discard_entry *entry, *this;
1692         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
1693         unsigned long *prefree_map = dirty_i->dirty_segmap[PRE];
1694         unsigned int start = 0, end = -1;
1695         unsigned int secno, start_segno;
1696         bool force = (cpc->reason & CP_DISCARD);
1697
1698         mutex_lock(&dirty_i->seglist_lock);
1699
1700         while (1) {
1701                 int i;
1702                 start = find_next_bit(prefree_map, MAIN_SEGS(sbi), end + 1);
1703                 if (start >= MAIN_SEGS(sbi))
1704                         break;
1705                 end = find_next_zero_bit(prefree_map, MAIN_SEGS(sbi),
1706                                                                 start + 1);
1707
1708                 for (i = start; i < end; i++)
1709                         clear_bit(i, prefree_map);
1710
1711                 dirty_i->nr_dirty[PRE] -= end - start;
1712
1713                 if (!test_opt(sbi, DISCARD))
1714                         continue;
1715
1716                 if (force && start >= cpc->trim_start &&
1717                                         (end - 1) <= cpc->trim_end)
1718                                 continue;
1719
1720                 if (!test_opt(sbi, LFS) || sbi->segs_per_sec == 1) {
1721                         f2fs_issue_discard(sbi, START_BLOCK(sbi, start),
1722                                 (end - start) << sbi->log_blocks_per_seg);
1723                         continue;
1724                 }
1725 next:
1726                 secno = GET_SEC_FROM_SEG(sbi, start);
1727                 start_segno = GET_SEG_FROM_SEC(sbi, secno);
1728                 if (!IS_CURSEC(sbi, secno) &&
1729                         !get_valid_blocks(sbi, start, true))
1730                         f2fs_issue_discard(sbi, START_BLOCK(sbi, start_segno),
1731                                 sbi->segs_per_sec << sbi->log_blocks_per_seg);
1732
1733                 start = start_segno + sbi->segs_per_sec;
1734                 if (start < end)
1735                         goto next;
1736                 else
1737                         end = start - 1;
1738         }
1739         mutex_unlock(&dirty_i->seglist_lock);
1740
1741         /* send small discards */
1742         list_for_each_entry_safe(entry, this, head, list) {
1743                 unsigned int cur_pos = 0, next_pos, len, total_len = 0;
1744                 bool is_valid = test_bit_le(0, entry->discard_map);
1745
1746 find_next:
1747                 if (is_valid) {
1748                         next_pos = find_next_zero_bit_le(entry->discard_map,
1749                                         sbi->blocks_per_seg, cur_pos);
1750                         len = next_pos - cur_pos;
1751
1752                         if (f2fs_sb_has_blkzoned(sbi->sb) ||
1753                             (force && len < cpc->trim_minlen))
1754                                 goto skip;
1755
1756                         f2fs_issue_discard(sbi, entry->start_blkaddr + cur_pos,
1757                                                                         len);
1758                         total_len += len;
1759                 } else {
1760                         next_pos = find_next_bit_le(entry->discard_map,
1761                                         sbi->blocks_per_seg, cur_pos);
1762                 }
1763 skip:
1764                 cur_pos = next_pos;
1765                 is_valid = !is_valid;
1766
1767                 if (cur_pos < sbi->blocks_per_seg)
1768                         goto find_next;
1769
1770                 list_del(&entry->list);
1771                 dcc->nr_discards -= total_len;
1772                 kmem_cache_free(discard_entry_slab, entry);
1773         }
1774
1775         wake_up_discard_thread(sbi, false);
1776 }
1777
1778 static int create_discard_cmd_control(struct f2fs_sb_info *sbi)
1779 {
1780         dev_t dev = sbi->sb->s_bdev->bd_dev;
1781         struct discard_cmd_control *dcc;
1782         int err = 0, i;
1783
1784         if (SM_I(sbi)->dcc_info) {
1785                 dcc = SM_I(sbi)->dcc_info;
1786                 goto init_thread;
1787         }
1788
1789         dcc = f2fs_kzalloc(sbi, sizeof(struct discard_cmd_control), GFP_KERNEL);
1790         if (!dcc)
1791                 return -ENOMEM;
1792
1793         dcc->discard_granularity = DEFAULT_DISCARD_GRANULARITY;
1794         INIT_LIST_HEAD(&dcc->entry_list);
1795         for (i = 0; i < MAX_PLIST_NUM; i++)
1796                 INIT_LIST_HEAD(&dcc->pend_list[i]);
1797         INIT_LIST_HEAD(&dcc->wait_list);
1798         INIT_LIST_HEAD(&dcc->fstrim_list);
1799         mutex_init(&dcc->cmd_lock);
1800         atomic_set(&dcc->issued_discard, 0);
1801         atomic_set(&dcc->issing_discard, 0);
1802         atomic_set(&dcc->discard_cmd_cnt, 0);
1803         dcc->nr_discards = 0;
1804         dcc->max_discards = MAIN_SEGS(sbi) << sbi->log_blocks_per_seg;
1805         dcc->undiscard_blks = 0;
1806         dcc->root = RB_ROOT;
1807
1808         init_waitqueue_head(&dcc->discard_wait_queue);
1809         SM_I(sbi)->dcc_info = dcc;
1810 init_thread:
1811         dcc->f2fs_issue_discard = kthread_run(issue_discard_thread, sbi,
1812                                 "f2fs_discard-%u:%u", MAJOR(dev), MINOR(dev));
1813         if (IS_ERR(dcc->f2fs_issue_discard)) {
1814                 err = PTR_ERR(dcc->f2fs_issue_discard);
1815                 kfree(dcc);
1816                 SM_I(sbi)->dcc_info = NULL;
1817                 return err;
1818         }
1819
1820         return err;
1821 }
1822
1823 static void destroy_discard_cmd_control(struct f2fs_sb_info *sbi)
1824 {
1825         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1826
1827         if (!dcc)
1828                 return;
1829
1830         stop_discard_thread(sbi);
1831
1832         kfree(dcc);
1833         SM_I(sbi)->dcc_info = NULL;
1834 }
1835
1836 static bool __mark_sit_entry_dirty(struct f2fs_sb_info *sbi, unsigned int segno)
1837 {
1838         struct sit_info *sit_i = SIT_I(sbi);
1839
1840         if (!__test_and_set_bit(segno, sit_i->dirty_sentries_bitmap)) {
1841                 sit_i->dirty_sentries++;
1842                 return false;
1843         }
1844
1845         return true;
1846 }
1847
1848 static void __set_sit_entry_type(struct f2fs_sb_info *sbi, int type,
1849                                         unsigned int segno, int modified)
1850 {
1851         struct seg_entry *se = get_seg_entry(sbi, segno);
1852         se->type = type;
1853         if (modified)
1854                 __mark_sit_entry_dirty(sbi, segno);
1855 }
1856
1857 static void update_sit_entry(struct f2fs_sb_info *sbi, block_t blkaddr, int del)
1858 {
1859         struct seg_entry *se;
1860         unsigned int segno, offset;
1861         long int new_vblocks;
1862         bool exist;
1863 #ifdef CONFIG_F2FS_CHECK_FS
1864         bool mir_exist;
1865 #endif
1866
1867         segno = GET_SEGNO(sbi, blkaddr);
1868
1869         se = get_seg_entry(sbi, segno);
1870         new_vblocks = se->valid_blocks + del;
1871         offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
1872
1873         f2fs_bug_on(sbi, (new_vblocks >> (sizeof(unsigned short) << 3) ||
1874                                 (new_vblocks > sbi->blocks_per_seg)));
1875
1876         se->valid_blocks = new_vblocks;
1877         se->mtime = get_mtime(sbi);
1878         SIT_I(sbi)->max_mtime = se->mtime;
1879
1880         /* Update valid block bitmap */
1881         if (del > 0) {
1882                 exist = f2fs_test_and_set_bit(offset, se->cur_valid_map);
1883 #ifdef CONFIG_F2FS_CHECK_FS
1884                 mir_exist = f2fs_test_and_set_bit(offset,
1885                                                 se->cur_valid_map_mir);
1886                 if (unlikely(exist != mir_exist)) {
1887                         f2fs_msg(sbi->sb, KERN_ERR, "Inconsistent error "
1888                                 "when setting bitmap, blk:%u, old bit:%d",
1889                                 blkaddr, exist);
1890                         f2fs_bug_on(sbi, 1);
1891                 }
1892 #endif
1893                 if (unlikely(exist)) {
1894                         f2fs_msg(sbi->sb, KERN_ERR,
1895                                 "Bitmap was wrongly set, blk:%u", blkaddr);
1896                         f2fs_bug_on(sbi, 1);
1897                         se->valid_blocks--;
1898                         del = 0;
1899                 }
1900
1901                 if (f2fs_discard_en(sbi) &&
1902                         !f2fs_test_and_set_bit(offset, se->discard_map))
1903                         sbi->discard_blks--;
1904
1905                 /* don't overwrite by SSR to keep node chain */
1906                 if (IS_NODESEG(se->type)) {
1907                         if (!f2fs_test_and_set_bit(offset, se->ckpt_valid_map))
1908                                 se->ckpt_valid_blocks++;
1909                 }
1910         } else {
1911                 exist = f2fs_test_and_clear_bit(offset, se->cur_valid_map);
1912 #ifdef CONFIG_F2FS_CHECK_FS
1913                 mir_exist = f2fs_test_and_clear_bit(offset,
1914                                                 se->cur_valid_map_mir);
1915                 if (unlikely(exist != mir_exist)) {
1916                         f2fs_msg(sbi->sb, KERN_ERR, "Inconsistent error "
1917                                 "when clearing bitmap, blk:%u, old bit:%d",
1918                                 blkaddr, exist);
1919                         f2fs_bug_on(sbi, 1);
1920                 }
1921 #endif
1922                 if (unlikely(!exist)) {
1923                         f2fs_msg(sbi->sb, KERN_ERR,
1924                                 "Bitmap was wrongly cleared, blk:%u", blkaddr);
1925                         f2fs_bug_on(sbi, 1);
1926                         se->valid_blocks++;
1927                         del = 0;
1928                 }
1929
1930                 if (f2fs_discard_en(sbi) &&
1931                         f2fs_test_and_clear_bit(offset, se->discard_map))
1932                         sbi->discard_blks++;
1933         }
1934         if (!f2fs_test_bit(offset, se->ckpt_valid_map))
1935                 se->ckpt_valid_blocks += del;
1936
1937         __mark_sit_entry_dirty(sbi, segno);
1938
1939         /* update total number of valid blocks to be written in ckpt area */
1940         SIT_I(sbi)->written_valid_blocks += del;
1941
1942         if (sbi->segs_per_sec > 1)
1943                 get_sec_entry(sbi, segno)->valid_blocks += del;
1944 }
1945
1946 void invalidate_blocks(struct f2fs_sb_info *sbi, block_t addr)
1947 {
1948         unsigned int segno = GET_SEGNO(sbi, addr);
1949         struct sit_info *sit_i = SIT_I(sbi);
1950
1951         f2fs_bug_on(sbi, addr == NULL_ADDR);
1952         if (addr == NEW_ADDR)
1953                 return;
1954
1955         /* add it into sit main buffer */
1956         down_write(&sit_i->sentry_lock);
1957
1958         update_sit_entry(sbi, addr, -1);
1959
1960         /* add it into dirty seglist */
1961         locate_dirty_segment(sbi, segno);
1962
1963         up_write(&sit_i->sentry_lock);
1964 }
1965
1966 bool is_checkpointed_data(struct f2fs_sb_info *sbi, block_t blkaddr)
1967 {
1968         struct sit_info *sit_i = SIT_I(sbi);
1969         unsigned int segno, offset;
1970         struct seg_entry *se;
1971         bool is_cp = false;
1972
1973         if (blkaddr == NEW_ADDR || blkaddr == NULL_ADDR)
1974                 return true;
1975
1976         down_read(&sit_i->sentry_lock);
1977
1978         segno = GET_SEGNO(sbi, blkaddr);
1979         se = get_seg_entry(sbi, segno);
1980         offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
1981
1982         if (f2fs_test_bit(offset, se->ckpt_valid_map))
1983                 is_cp = true;
1984
1985         up_read(&sit_i->sentry_lock);
1986
1987         return is_cp;
1988 }
1989
1990 /*
1991  * This function should be resided under the curseg_mutex lock
1992  */
1993 static void __add_sum_entry(struct f2fs_sb_info *sbi, int type,
1994                                         struct f2fs_summary *sum)
1995 {
1996         struct curseg_info *curseg = CURSEG_I(sbi, type);
1997         void *addr = curseg->sum_blk;
1998         addr += curseg->next_blkoff * sizeof(struct f2fs_summary);
1999         memcpy(addr, sum, sizeof(struct f2fs_summary));
2000 }
2001
2002 /*
2003  * Calculate the number of current summary pages for writing
2004  */
2005 int npages_for_summary_flush(struct f2fs_sb_info *sbi, bool for_ra)
2006 {
2007         int valid_sum_count = 0;
2008         int i, sum_in_page;
2009
2010         for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
2011                 if (sbi->ckpt->alloc_type[i] == SSR)
2012                         valid_sum_count += sbi->blocks_per_seg;
2013                 else {
2014                         if (for_ra)
2015                                 valid_sum_count += le16_to_cpu(
2016                                         F2FS_CKPT(sbi)->cur_data_blkoff[i]);
2017                         else
2018                                 valid_sum_count += curseg_blkoff(sbi, i);
2019                 }
2020         }
2021
2022         sum_in_page = (PAGE_SIZE - 2 * SUM_JOURNAL_SIZE -
2023                         SUM_FOOTER_SIZE) / SUMMARY_SIZE;
2024         if (valid_sum_count <= sum_in_page)
2025                 return 1;
2026         else if ((valid_sum_count - sum_in_page) <=
2027                 (PAGE_SIZE - SUM_FOOTER_SIZE) / SUMMARY_SIZE)
2028                 return 2;
2029         return 3;
2030 }
2031
2032 /*
2033  * Caller should put this summary page
2034  */
2035 struct page *get_sum_page(struct f2fs_sb_info *sbi, unsigned int segno)
2036 {
2037         return get_meta_page(sbi, GET_SUM_BLOCK(sbi, segno));
2038 }
2039
2040 void update_meta_page(struct f2fs_sb_info *sbi, void *src, block_t blk_addr)
2041 {
2042         struct page *page = grab_meta_page(sbi, blk_addr);
2043
2044         memcpy(page_address(page), src, PAGE_SIZE);
2045         set_page_dirty(page);
2046         f2fs_put_page(page, 1);
2047 }
2048
2049 static void write_sum_page(struct f2fs_sb_info *sbi,
2050                         struct f2fs_summary_block *sum_blk, block_t blk_addr)
2051 {
2052         update_meta_page(sbi, (void *)sum_blk, blk_addr);
2053 }
2054
2055 static void write_current_sum_page(struct f2fs_sb_info *sbi,
2056                                                 int type, block_t blk_addr)
2057 {
2058         struct curseg_info *curseg = CURSEG_I(sbi, type);
2059         struct page *page = grab_meta_page(sbi, blk_addr);
2060         struct f2fs_summary_block *src = curseg->sum_blk;
2061         struct f2fs_summary_block *dst;
2062
2063         dst = (struct f2fs_summary_block *)page_address(page);
2064
2065         mutex_lock(&curseg->curseg_mutex);
2066
2067         down_read(&curseg->journal_rwsem);
2068         memcpy(&dst->journal, curseg->journal, SUM_JOURNAL_SIZE);
2069         up_read(&curseg->journal_rwsem);
2070
2071         memcpy(dst->entries, src->entries, SUM_ENTRY_SIZE);
2072         memcpy(&dst->footer, &src->footer, SUM_FOOTER_SIZE);
2073
2074         mutex_unlock(&curseg->curseg_mutex);
2075
2076         set_page_dirty(page);
2077         f2fs_put_page(page, 1);
2078 }
2079
2080 static int is_next_segment_free(struct f2fs_sb_info *sbi, int type)
2081 {
2082         struct curseg_info *curseg = CURSEG_I(sbi, type);
2083         unsigned int segno = curseg->segno + 1;
2084         struct free_segmap_info *free_i = FREE_I(sbi);
2085
2086         if (segno < MAIN_SEGS(sbi) && segno % sbi->segs_per_sec)
2087                 return !test_bit(segno, free_i->free_segmap);
2088         return 0;
2089 }
2090
2091 /*
2092  * Find a new segment from the free segments bitmap to right order
2093  * This function should be returned with success, otherwise BUG
2094  */
2095 static void get_new_segment(struct f2fs_sb_info *sbi,
2096                         unsigned int *newseg, bool new_sec, int dir)
2097 {
2098         struct free_segmap_info *free_i = FREE_I(sbi);
2099         unsigned int segno, secno, zoneno;
2100         unsigned int total_zones = MAIN_SECS(sbi) / sbi->secs_per_zone;
2101         unsigned int hint = GET_SEC_FROM_SEG(sbi, *newseg);
2102         unsigned int old_zoneno = GET_ZONE_FROM_SEG(sbi, *newseg);
2103         unsigned int left_start = hint;
2104         bool init = true;
2105         int go_left = 0;
2106         int i;
2107
2108         spin_lock(&free_i->segmap_lock);
2109
2110         if (!new_sec && ((*newseg + 1) % sbi->segs_per_sec)) {
2111                 segno = find_next_zero_bit(free_i->free_segmap,
2112                         GET_SEG_FROM_SEC(sbi, hint + 1), *newseg + 1);
2113                 if (segno < GET_SEG_FROM_SEC(sbi, hint + 1))
2114                         goto got_it;
2115         }
2116 find_other_zone:
2117         secno = find_next_zero_bit(free_i->free_secmap, MAIN_SECS(sbi), hint);
2118         if (secno >= MAIN_SECS(sbi)) {
2119                 if (dir == ALLOC_RIGHT) {
2120                         secno = find_next_zero_bit(free_i->free_secmap,
2121                                                         MAIN_SECS(sbi), 0);
2122                         f2fs_bug_on(sbi, secno >= MAIN_SECS(sbi));
2123                 } else {
2124                         go_left = 1;
2125                         left_start = hint - 1;
2126                 }
2127         }
2128         if (go_left == 0)
2129                 goto skip_left;
2130
2131         while (test_bit(left_start, free_i->free_secmap)) {
2132                 if (left_start > 0) {
2133                         left_start--;
2134                         continue;
2135                 }
2136                 left_start = find_next_zero_bit(free_i->free_secmap,
2137                                                         MAIN_SECS(sbi), 0);
2138                 f2fs_bug_on(sbi, left_start >= MAIN_SECS(sbi));
2139                 break;
2140         }
2141         secno = left_start;
2142 skip_left:
2143         segno = GET_SEG_FROM_SEC(sbi, secno);
2144         zoneno = GET_ZONE_FROM_SEC(sbi, secno);
2145
2146         /* give up on finding another zone */
2147         if (!init)
2148                 goto got_it;
2149         if (sbi->secs_per_zone == 1)
2150                 goto got_it;
2151         if (zoneno == old_zoneno)
2152                 goto got_it;
2153         if (dir == ALLOC_LEFT) {
2154                 if (!go_left && zoneno + 1 >= total_zones)
2155                         goto got_it;
2156                 if (go_left && zoneno == 0)
2157                         goto got_it;
2158         }
2159         for (i = 0; i < NR_CURSEG_TYPE; i++)
2160                 if (CURSEG_I(sbi, i)->zone == zoneno)
2161                         break;
2162
2163         if (i < NR_CURSEG_TYPE) {
2164                 /* zone is in user, try another */
2165                 if (go_left)
2166                         hint = zoneno * sbi->secs_per_zone - 1;
2167                 else if (zoneno + 1 >= total_zones)
2168                         hint = 0;
2169                 else
2170                         hint = (zoneno + 1) * sbi->secs_per_zone;
2171                 init = false;
2172                 goto find_other_zone;
2173         }
2174 got_it:
2175         /* set it as dirty segment in free segmap */
2176         f2fs_bug_on(sbi, test_bit(segno, free_i->free_segmap));
2177         __set_inuse(sbi, segno);
2178         *newseg = segno;
2179         spin_unlock(&free_i->segmap_lock);
2180 }
2181
2182 static void reset_curseg(struct f2fs_sb_info *sbi, int type, int modified)
2183 {
2184         struct curseg_info *curseg = CURSEG_I(sbi, type);
2185         struct summary_footer *sum_footer;
2186
2187         curseg->segno = curseg->next_segno;
2188         curseg->zone = GET_ZONE_FROM_SEG(sbi, curseg->segno);
2189         curseg->next_blkoff = 0;
2190         curseg->next_segno = NULL_SEGNO;
2191
2192         sum_footer = &(curseg->sum_blk->footer);
2193         memset(sum_footer, 0, sizeof(struct summary_footer));
2194         if (IS_DATASEG(type))
2195                 SET_SUM_TYPE(sum_footer, SUM_TYPE_DATA);
2196         if (IS_NODESEG(type))
2197                 SET_SUM_TYPE(sum_footer, SUM_TYPE_NODE);
2198         __set_sit_entry_type(sbi, type, curseg->segno, modified);
2199 }
2200
2201 static unsigned int __get_next_segno(struct f2fs_sb_info *sbi, int type)
2202 {
2203         /* if segs_per_sec is large than 1, we need to keep original policy. */
2204         if (sbi->segs_per_sec != 1)
2205                 return CURSEG_I(sbi, type)->segno;
2206
2207         if (test_opt(sbi, NOHEAP) &&
2208                 (type == CURSEG_HOT_DATA || IS_NODESEG(type)))
2209                 return 0;
2210
2211         if (SIT_I(sbi)->last_victim[ALLOC_NEXT])
2212                 return SIT_I(sbi)->last_victim[ALLOC_NEXT];
2213
2214         /* find segments from 0 to reuse freed segments */
2215         if (F2FS_OPTION(sbi).alloc_mode == ALLOC_MODE_REUSE)
2216                 return 0;
2217
2218         return CURSEG_I(sbi, type)->segno;
2219 }
2220
2221 /*
2222  * Allocate a current working segment.
2223  * This function always allocates a free segment in LFS manner.
2224  */
2225 static void new_curseg(struct f2fs_sb_info *sbi, int type, bool new_sec)
2226 {
2227         struct curseg_info *curseg = CURSEG_I(sbi, type);
2228         unsigned int segno = curseg->segno;
2229         int dir = ALLOC_LEFT;
2230
2231         write_sum_page(sbi, curseg->sum_blk,
2232                                 GET_SUM_BLOCK(sbi, segno));
2233         if (type == CURSEG_WARM_DATA || type == CURSEG_COLD_DATA)
2234                 dir = ALLOC_RIGHT;
2235
2236         if (test_opt(sbi, NOHEAP))
2237                 dir = ALLOC_RIGHT;
2238
2239         segno = __get_next_segno(sbi, type);
2240         get_new_segment(sbi, &segno, new_sec, dir);
2241         curseg->next_segno = segno;
2242         reset_curseg(sbi, type, 1);
2243         curseg->alloc_type = LFS;
2244 }
2245
2246 static void __next_free_blkoff(struct f2fs_sb_info *sbi,
2247                         struct curseg_info *seg, block_t start)
2248 {
2249         struct seg_entry *se = get_seg_entry(sbi, seg->segno);
2250         int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
2251         unsigned long *target_map = SIT_I(sbi)->tmp_map;
2252         unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
2253         unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
2254         int i, pos;
2255
2256         for (i = 0; i < entries; i++)
2257                 target_map[i] = ckpt_map[i] | cur_map[i];
2258
2259         pos = __find_rev_next_zero_bit(target_map, sbi->blocks_per_seg, start);
2260
2261         seg->next_blkoff = pos;
2262 }
2263
2264 /*
2265  * If a segment is written by LFS manner, next block offset is just obtained
2266  * by increasing the current block offset. However, if a segment is written by
2267  * SSR manner, next block offset obtained by calling __next_free_blkoff
2268  */
2269 static void __refresh_next_blkoff(struct f2fs_sb_info *sbi,
2270                                 struct curseg_info *seg)
2271 {
2272         if (seg->alloc_type == SSR)
2273                 __next_free_blkoff(sbi, seg, seg->next_blkoff + 1);
2274         else
2275                 seg->next_blkoff++;
2276 }
2277
2278 /*
2279  * This function always allocates a used segment(from dirty seglist) by SSR
2280  * manner, so it should recover the existing segment information of valid blocks
2281  */
2282 static void change_curseg(struct f2fs_sb_info *sbi, int type)
2283 {
2284         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
2285         struct curseg_info *curseg = CURSEG_I(sbi, type);
2286         unsigned int new_segno = curseg->next_segno;
2287         struct f2fs_summary_block *sum_node;
2288         struct page *sum_page;
2289
2290         write_sum_page(sbi, curseg->sum_blk,
2291                                 GET_SUM_BLOCK(sbi, curseg->segno));
2292         __set_test_and_inuse(sbi, new_segno);
2293
2294         mutex_lock(&dirty_i->seglist_lock);
2295         __remove_dirty_segment(sbi, new_segno, PRE);
2296         __remove_dirty_segment(sbi, new_segno, DIRTY);
2297         mutex_unlock(&dirty_i->seglist_lock);
2298
2299         reset_curseg(sbi, type, 1);
2300         curseg->alloc_type = SSR;
2301         __next_free_blkoff(sbi, curseg, 0);
2302
2303         sum_page = get_sum_page(sbi, new_segno);
2304         sum_node = (struct f2fs_summary_block *)page_address(sum_page);
2305         memcpy(curseg->sum_blk, sum_node, SUM_ENTRY_SIZE);
2306         f2fs_put_page(sum_page, 1);
2307 }
2308
2309 static int get_ssr_segment(struct f2fs_sb_info *sbi, int type)
2310 {
2311         struct curseg_info *curseg = CURSEG_I(sbi, type);
2312         const struct victim_selection *v_ops = DIRTY_I(sbi)->v_ops;
2313         unsigned segno = NULL_SEGNO;
2314         int i, cnt;
2315         bool reversed = false;
2316
2317         /* need_SSR() already forces to do this */
2318         if (v_ops->get_victim(sbi, &segno, BG_GC, type, SSR)) {
2319                 curseg->next_segno = segno;
2320                 return 1;
2321         }
2322
2323         /* For node segments, let's do SSR more intensively */
2324         if (IS_NODESEG(type)) {
2325                 if (type >= CURSEG_WARM_NODE) {
2326                         reversed = true;
2327                         i = CURSEG_COLD_NODE;
2328                 } else {
2329                         i = CURSEG_HOT_NODE;
2330                 }
2331                 cnt = NR_CURSEG_NODE_TYPE;
2332         } else {
2333                 if (type >= CURSEG_WARM_DATA) {
2334                         reversed = true;
2335                         i = CURSEG_COLD_DATA;
2336                 } else {
2337                         i = CURSEG_HOT_DATA;
2338                 }
2339                 cnt = NR_CURSEG_DATA_TYPE;
2340         }
2341
2342         for (; cnt-- > 0; reversed ? i-- : i++) {
2343                 if (i == type)
2344                         continue;
2345                 if (v_ops->get_victim(sbi, &segno, BG_GC, i, SSR)) {
2346                         curseg->next_segno = segno;
2347                         return 1;
2348                 }
2349         }
2350         return 0;
2351 }
2352
2353 /*
2354  * flush out current segment and replace it with new segment
2355  * This function should be returned with success, otherwise BUG
2356  */
2357 static void allocate_segment_by_default(struct f2fs_sb_info *sbi,
2358                                                 int type, bool force)
2359 {
2360         struct curseg_info *curseg = CURSEG_I(sbi, type);
2361
2362         if (force)
2363                 new_curseg(sbi, type, true);
2364         else if (!is_set_ckpt_flags(sbi, CP_CRC_RECOVERY_FLAG) &&
2365                                         type == CURSEG_WARM_NODE)
2366                 new_curseg(sbi, type, false);
2367         else if (curseg->alloc_type == LFS && is_next_segment_free(sbi, type))
2368                 new_curseg(sbi, type, false);
2369         else if (need_SSR(sbi) && get_ssr_segment(sbi, type))
2370                 change_curseg(sbi, type);
2371         else
2372                 new_curseg(sbi, type, false);
2373
2374         stat_inc_seg_type(sbi, curseg);
2375 }
2376
2377 void allocate_new_segments(struct f2fs_sb_info *sbi)
2378 {
2379         struct curseg_info *curseg;
2380         unsigned int old_segno;
2381         int i;
2382
2383         down_write(&SIT_I(sbi)->sentry_lock);
2384
2385         for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
2386                 curseg = CURSEG_I(sbi, i);
2387                 old_segno = curseg->segno;
2388                 SIT_I(sbi)->s_ops->allocate_segment(sbi, i, true);
2389                 locate_dirty_segment(sbi, old_segno);
2390         }
2391
2392         up_write(&SIT_I(sbi)->sentry_lock);
2393 }
2394
2395 static const struct segment_allocation default_salloc_ops = {
2396         .allocate_segment = allocate_segment_by_default,
2397 };
2398
2399 bool exist_trim_candidates(struct f2fs_sb_info *sbi, struct cp_control *cpc)
2400 {
2401         __u64 trim_start = cpc->trim_start;
2402         bool has_candidate = false;
2403
2404         down_write(&SIT_I(sbi)->sentry_lock);
2405         for (; cpc->trim_start <= cpc->trim_end; cpc->trim_start++) {
2406                 if (add_discard_addrs(sbi, cpc, true)) {
2407                         has_candidate = true;
2408                         break;
2409                 }
2410         }
2411         up_write(&SIT_I(sbi)->sentry_lock);
2412
2413         cpc->trim_start = trim_start;
2414         return has_candidate;
2415 }
2416
2417 static void __issue_discard_cmd_range(struct f2fs_sb_info *sbi,
2418                                         struct discard_policy *dpolicy,
2419                                         unsigned int start, unsigned int end)
2420 {
2421         struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
2422         struct discard_cmd *prev_dc = NULL, *next_dc = NULL;
2423         struct rb_node **insert_p = NULL, *insert_parent = NULL;
2424         struct discard_cmd *dc;
2425         struct blk_plug plug;
2426         int issued;
2427
2428 next:
2429         issued = 0;
2430
2431         mutex_lock(&dcc->cmd_lock);
2432         f2fs_bug_on(sbi, !__check_rb_tree_consistence(sbi, &dcc->root));
2433
2434         dc = (struct discard_cmd *)__lookup_rb_tree_ret(&dcc->root,
2435                                         NULL, start,
2436                                         (struct rb_entry **)&prev_dc,
2437                                         (struct rb_entry **)&next_dc,
2438                                         &insert_p, &insert_parent, true);
2439         if (!dc)
2440                 dc = next_dc;
2441
2442         blk_start_plug(&plug);
2443
2444         while (dc && dc->lstart <= end) {
2445                 struct rb_node *node;
2446
2447                 if (dc->len < dpolicy->granularity)
2448                         goto skip;
2449
2450                 if (dc->state != D_PREP) {
2451                         list_move_tail(&dc->list, &dcc->fstrim_list);
2452                         goto skip;
2453                 }
2454
2455                 __submit_discard_cmd(sbi, dpolicy, dc);
2456
2457                 if (++issued >= dpolicy->max_requests) {
2458                         start = dc->lstart + dc->len;
2459
2460                         blk_finish_plug(&plug);
2461                         mutex_unlock(&dcc->cmd_lock);
2462                         __wait_all_discard_cmd(sbi, NULL);
2463                         congestion_wait(BLK_RW_ASYNC, HZ/50);
2464                         goto next;
2465                 }
2466 skip:
2467                 node = rb_next(&dc->rb_node);
2468                 dc = rb_entry_safe(node, struct discard_cmd, rb_node);
2469
2470                 if (fatal_signal_pending(current))
2471                         break;
2472         }
2473
2474         blk_finish_plug(&plug);
2475         mutex_unlock(&dcc->cmd_lock);
2476 }
2477
2478 int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range)
2479 {
2480         __u64 start = F2FS_BYTES_TO_BLK(range->start);
2481         __u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1;
2482         unsigned int start_segno, end_segno;
2483         block_t start_block, end_block;
2484         struct cp_control cpc;
2485         struct discard_policy dpolicy;
2486         unsigned long long trimmed = 0;
2487         int err = 0;
2488
2489         if (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize)
2490                 return -EINVAL;
2491
2492         if (end <= MAIN_BLKADDR(sbi))
2493                 goto out;
2494
2495         if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) {
2496                 f2fs_msg(sbi->sb, KERN_WARNING,
2497                         "Found FS corruption, run fsck to fix.");
2498                 goto out;
2499         }
2500
2501         /* start/end segment number in main_area */
2502         start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start);
2503         end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 :
2504                                                 GET_SEGNO(sbi, end);
2505
2506         cpc.reason = CP_DISCARD;
2507         cpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen));
2508         cpc.trim_start = start_segno;
2509         cpc.trim_end = end_segno;
2510
2511         if (sbi->discard_blks == 0)
2512                 goto out;
2513
2514         mutex_lock(&sbi->gc_mutex);
2515         err = write_checkpoint(sbi, &cpc);
2516         mutex_unlock(&sbi->gc_mutex);
2517         if (err)
2518                 goto out;
2519
2520         start_block = START_BLOCK(sbi, start_segno);
2521         end_block = START_BLOCK(sbi, end_segno + 1);
2522
2523         __init_discard_policy(sbi, &dpolicy, DPOLICY_FSTRIM, cpc.trim_minlen);
2524         __issue_discard_cmd_range(sbi, &dpolicy, start_block, end_block);
2525
2526         /*
2527          * We filed discard candidates, but actually we don't need to wait for
2528          * all of them, since they'll be issued in idle time along with runtime
2529          * discard option. User configuration looks like using runtime discard
2530          * or periodic fstrim instead of it.
2531          */
2532         if (!test_opt(sbi, DISCARD)) {
2533                 trimmed = __wait_discard_cmd_range(sbi, &dpolicy,
2534                                         start_block, end_block);
2535                 range->len = F2FS_BLK_TO_BYTES(trimmed);
2536         }
2537 out:
2538         return err;
2539 }
2540
2541 static bool __has_curseg_space(struct f2fs_sb_info *sbi, int type)
2542 {
2543         struct curseg_info *curseg = CURSEG_I(sbi, type);
2544         if (curseg->next_blkoff < sbi->blocks_per_seg)
2545                 return true;
2546         return false;
2547 }
2548
2549 int rw_hint_to_seg_type(enum rw_hint hint)
2550 {
2551         switch (hint) {
2552         case WRITE_LIFE_SHORT:
2553                 return CURSEG_HOT_DATA;
2554         case WRITE_LIFE_EXTREME:
2555                 return CURSEG_COLD_DATA;
2556         default:
2557                 return CURSEG_WARM_DATA;
2558         }
2559 }
2560
2561 /* This returns write hints for each segment type. This hints will be
2562  * passed down to block layer. There are mapping tables which depend on
2563  * the mount option 'whint_mode'.
2564  *
2565  * 1) whint_mode=off. F2FS only passes down WRITE_LIFE_NOT_SET.
2566  *
2567  * 2) whint_mode=user-based. F2FS tries to pass down hints given by users.
2568  *
2569  * User                  F2FS                     Block
2570  * ----                  ----                     -----
2571  *                       META                     WRITE_LIFE_NOT_SET
2572  *                       HOT_NODE                 "
2573  *                       WARM_NODE                "
2574  *                       COLD_NODE                "
2575  * ioctl(COLD)           COLD_DATA                WRITE_LIFE_EXTREME
2576  * extension list        "                        "
2577  *
2578  * -- buffered io
2579  * WRITE_LIFE_EXTREME    COLD_DATA                WRITE_LIFE_EXTREME
2580  * WRITE_LIFE_SHORT      HOT_DATA                 WRITE_LIFE_SHORT
2581  * WRITE_LIFE_NOT_SET    WARM_DATA                WRITE_LIFE_NOT_SET
2582  * WRITE_LIFE_NONE       "                        "
2583  * WRITE_LIFE_MEDIUM     "                        "
2584  * WRITE_LIFE_LONG       "                        "
2585  *
2586  * -- direct io
2587  * WRITE_LIFE_EXTREME    COLD_DATA                WRITE_LIFE_EXTREME
2588  * WRITE_LIFE_SHORT      HOT_DATA                 WRITE_LIFE_SHORT
2589  * WRITE_LIFE_NOT_SET    WARM_DATA                WRITE_LIFE_NOT_SET
2590  * WRITE_LIFE_NONE       "                        WRITE_LIFE_NONE
2591  * WRITE_LIFE_MEDIUM     "                        WRITE_LIFE_MEDIUM
2592  * WRITE_LIFE_LONG       "                        WRITE_LIFE_LONG
2593  *
2594  * 3) whint_mode=fs-based. F2FS passes down hints with its policy.
2595  *
2596  * User                  F2FS                     Block
2597  * ----                  ----                     -----
2598  *                       META                     WRITE_LIFE_MEDIUM;
2599  *                       HOT_NODE                 WRITE_LIFE_NOT_SET
2600  *                       WARM_NODE                "
2601  *                       COLD_NODE                WRITE_LIFE_NONE
2602  * ioctl(COLD)           COLD_DATA                WRITE_LIFE_EXTREME
2603  * extension list        "                        "
2604  *
2605  * -- buffered io
2606  * WRITE_LIFE_EXTREME    COLD_DATA                WRITE_LIFE_EXTREME
2607  * WRITE_LIFE_SHORT      HOT_DATA                 WRITE_LIFE_SHORT
2608  * WRITE_LIFE_NOT_SET    WARM_DATA                WRITE_LIFE_LONG
2609  * WRITE_LIFE_NONE       "                        "
2610  * WRITE_LIFE_MEDIUM     "                        "
2611  * WRITE_LIFE_LONG       "                        "
2612  *
2613  * -- direct io
2614  * WRITE_LIFE_EXTREME    COLD_DATA                WRITE_LIFE_EXTREME
2615  * WRITE_LIFE_SHORT      HOT_DATA                 WRITE_LIFE_SHORT
2616  * WRITE_LIFE_NOT_SET    WARM_DATA                WRITE_LIFE_NOT_SET
2617  * WRITE_LIFE_NONE       "                        WRITE_LIFE_NONE
2618  * WRITE_LIFE_MEDIUM     "                        WRITE_LIFE_MEDIUM
2619  * WRITE_LIFE_LONG       "                        WRITE_LIFE_LONG
2620  */
2621
2622 enum rw_hint io_type_to_rw_hint(struct f2fs_sb_info *sbi,
2623                                 enum page_type type, enum temp_type temp)
2624 {
2625         if (F2FS_OPTION(sbi).whint_mode == WHINT_MODE_USER) {
2626                 if (type == DATA) {
2627                         if (temp == WARM)
2628                                 return WRITE_LIFE_NOT_SET;
2629                         else if (temp == HOT)
2630                                 return WRITE_LIFE_SHORT;
2631                         else if (temp == COLD)
2632                                 return WRITE_LIFE_EXTREME;
2633                 } else {
2634                         return WRITE_LIFE_NOT_SET;
2635                 }
2636         } else if (F2FS_OPTION(sbi).whint_mode == WHINT_MODE_FS) {
2637                 if (type == DATA) {
2638                         if (temp == WARM)
2639                                 return WRITE_LIFE_LONG;
2640                         else if (temp == HOT)
2641                                 return WRITE_LIFE_SHORT;
2642                         else if (temp == COLD)
2643                                 return WRITE_LIFE_EXTREME;
2644                 } else if (type == NODE) {
2645                         if (temp == WARM || temp == HOT)
2646                                 return WRITE_LIFE_NOT_SET;
2647                         else if (temp == COLD)
2648                                 return WRITE_LIFE_NONE;
2649                 } else if (type == META) {
2650                         return WRITE_LIFE_MEDIUM;
2651                 }
2652         }
2653         return WRITE_LIFE_NOT_SET;
2654 }
2655
2656 static int __get_segment_type_2(struct f2fs_io_info *fio)
2657 {
2658         if (fio->type == DATA)
2659                 return CURSEG_HOT_DATA;
2660         else
2661                 return CURSEG_HOT_NODE;
2662 }
2663
2664 static int __get_segment_type_4(struct f2fs_io_info *fio)
2665 {
2666         if (fio->type == DATA) {
2667                 struct inode *inode = fio->page->mapping->host;
2668
2669                 if (S_ISDIR(inode->i_mode))
2670                         return CURSEG_HOT_DATA;
2671                 else
2672                         return CURSEG_COLD_DATA;
2673         } else {
2674                 if (IS_DNODE(fio->page) && is_cold_node(fio->page))
2675                         return CURSEG_WARM_NODE;
2676                 else
2677                         return CURSEG_COLD_NODE;
2678         }
2679 }
2680
2681 static int __get_segment_type_6(struct f2fs_io_info *fio)
2682 {
2683         if (fio->type == DATA) {
2684                 struct inode *inode = fio->page->mapping->host;
2685
2686                 if (is_cold_data(fio->page) || file_is_cold(inode))
2687                         return CURSEG_COLD_DATA;
2688                 if (file_is_hot(inode) ||
2689                                 is_inode_flag_set(inode, FI_HOT_DATA))
2690                         return CURSEG_HOT_DATA;
2691                 /* rw_hint_to_seg_type(inode->i_write_hint); */
2692                 return CURSEG_WARM_DATA;
2693         } else {
2694                 if (IS_DNODE(fio->page))
2695                         return is_cold_node(fio->page) ? CURSEG_WARM_NODE :
2696                                                 CURSEG_HOT_NODE;
2697                 return CURSEG_COLD_NODE;
2698         }
2699 }
2700
2701 static int __get_segment_type(struct f2fs_io_info *fio)
2702 {
2703         int type = 0;
2704
2705         switch (F2FS_OPTION(fio->sbi).active_logs) {
2706         case 2:
2707                 type = __get_segment_type_2(fio);
2708                 break;
2709         case 4:
2710                 type = __get_segment_type_4(fio);
2711                 break;
2712         case 6:
2713                 type = __get_segment_type_6(fio);
2714                 break;
2715         default:
2716                 f2fs_bug_on(fio->sbi, true);
2717         }
2718
2719         if (IS_HOT(type))
2720                 fio->temp = HOT;
2721         else if (IS_WARM(type))
2722                 fio->temp = WARM;
2723         else
2724                 fio->temp = COLD;
2725         return type;
2726 }
2727
2728 void allocate_data_block(struct f2fs_sb_info *sbi, struct page *page,
2729                 block_t old_blkaddr, block_t *new_blkaddr,
2730                 struct f2fs_summary *sum, int type,
2731                 struct f2fs_io_info *fio, bool add_list)
2732 {
2733         struct sit_info *sit_i = SIT_I(sbi);
2734         struct curseg_info *curseg = CURSEG_I(sbi, type);
2735
2736         down_read(&SM_I(sbi)->curseg_lock);
2737
2738         mutex_lock(&curseg->curseg_mutex);
2739         down_write(&sit_i->sentry_lock);
2740
2741         *new_blkaddr = NEXT_FREE_BLKADDR(sbi, curseg);
2742
2743         f2fs_wait_discard_bio(sbi, *new_blkaddr);
2744
2745         /*
2746          * __add_sum_entry should be resided under the curseg_mutex
2747          * because, this function updates a summary entry in the
2748          * current summary block.
2749          */
2750         __add_sum_entry(sbi, type, sum);
2751
2752         __refresh_next_blkoff(sbi, curseg);
2753
2754         stat_inc_block_count(sbi, curseg);
2755
2756         /*
2757          * SIT information should be updated before segment allocation,
2758          * since SSR needs latest valid block information.
2759          */
2760         update_sit_entry(sbi, *new_blkaddr, 1);
2761         if (GET_SEGNO(sbi, old_blkaddr) != NULL_SEGNO)
2762                 update_sit_entry(sbi, old_blkaddr, -1);
2763
2764         if (!__has_curseg_space(sbi, type))
2765                 sit_i->s_ops->allocate_segment(sbi, type, false);
2766
2767         /*
2768          * segment dirty status should be updated after segment allocation,
2769          * so we just need to update status only one time after previous
2770          * segment being closed.
2771          */
2772         locate_dirty_segment(sbi, GET_SEGNO(sbi, old_blkaddr));
2773         locate_dirty_segment(sbi, GET_SEGNO(sbi, *new_blkaddr));
2774
2775         up_write(&sit_i->sentry_lock);
2776
2777         if (page && IS_NODESEG(type)) {
2778                 fill_node_footer_blkaddr(page, NEXT_FREE_BLKADDR(sbi, curseg));
2779
2780                 f2fs_inode_chksum_set(sbi, page);
2781         }
2782
2783         if (add_list) {
2784                 struct f2fs_bio_info *io;
2785
2786                 INIT_LIST_HEAD(&fio->list);
2787                 fio->in_list = true;
2788                 io = sbi->write_io[fio->type] + fio->temp;
2789                 spin_lock(&io->io_lock);
2790                 list_add_tail(&fio->list, &io->io_list);
2791                 spin_unlock(&io->io_lock);
2792         }
2793
2794         mutex_unlock(&curseg->curseg_mutex);
2795
2796         up_read(&SM_I(sbi)->curseg_lock);
2797 }
2798
2799 static void update_device_state(struct f2fs_io_info *fio)
2800 {
2801         struct f2fs_sb_info *sbi = fio->sbi;
2802         unsigned int devidx;
2803
2804         if (!sbi->s_ndevs)
2805                 return;
2806
2807         devidx = f2fs_target_device_index(sbi, fio->new_blkaddr);
2808
2809         /* update device state for fsync */
2810         set_dirty_device(sbi, fio->ino, devidx, FLUSH_INO);
2811
2812         /* update device state for checkpoint */
2813         if (!f2fs_test_bit(devidx, (char *)&sbi->dirty_device)) {
2814                 spin_lock(&sbi->dev_lock);
2815                 f2fs_set_bit(devidx, (char *)&sbi->dirty_device);
2816                 spin_unlock(&sbi->dev_lock);
2817         }
2818 }
2819
2820 static void do_write_page(struct f2fs_summary *sum, struct f2fs_io_info *fio)
2821 {
2822         int type = __get_segment_type(fio);
2823         int err;
2824
2825 reallocate:
2826         allocate_data_block(fio->sbi, fio->page, fio->old_blkaddr,
2827                         &fio->new_blkaddr, sum, type, fio, true);
2828
2829         /* writeout dirty page into bdev */
2830         err = f2fs_submit_page_write(fio);
2831         if (err == -EAGAIN) {
2832                 fio->old_blkaddr = fio->new_blkaddr;
2833                 goto reallocate;
2834         } else if (!err) {
2835                 update_device_state(fio);
2836         }
2837 }
2838
2839 void write_meta_page(struct f2fs_sb_info *sbi, struct page *page,
2840                                         enum iostat_type io_type)
2841 {
2842         struct f2fs_io_info fio = {
2843                 .sbi = sbi,
2844                 .type = META,
2845                 .temp = HOT,
2846                 .op = REQ_OP_WRITE,
2847                 .op_flags = REQ_SYNC | REQ_NOIDLE | REQ_META | REQ_PRIO,
2848                 .old_blkaddr = page->index,
2849                 .new_blkaddr = page->index,
2850                 .page = page,
2851                 .encrypted_page = NULL,
2852                 .in_list = false,
2853         };
2854
2855         if (unlikely(page->index >= MAIN_BLKADDR(sbi)))
2856                 fio.op_flags &= ~REQ_META;
2857
2858         set_page_writeback(page);
2859         ClearPageError(page);
2860         f2fs_submit_page_write(&fio);
2861
2862         f2fs_update_iostat(sbi, io_type, F2FS_BLKSIZE);
2863 }
2864
2865 void write_node_page(unsigned int nid, struct f2fs_io_info *fio)
2866 {
2867         struct f2fs_summary sum;
2868
2869         set_summary(&sum, nid, 0, 0);
2870         do_write_page(&sum, fio);
2871
2872         f2fs_update_iostat(fio->sbi, fio->io_type, F2FS_BLKSIZE);
2873 }
2874
2875 void write_data_page(struct dnode_of_data *dn, struct f2fs_io_info *fio)
2876 {
2877         struct f2fs_sb_info *sbi = fio->sbi;
2878         struct f2fs_summary sum;
2879         struct node_info ni;
2880
2881         f2fs_bug_on(sbi, dn->data_blkaddr == NULL_ADDR);
2882         get_node_info(sbi, dn->nid, &ni);
2883         set_summary(&sum, dn->nid, dn->ofs_in_node, ni.version);
2884         do_write_page(&sum, fio);
2885         f2fs_update_data_blkaddr(dn, fio->new_blkaddr);
2886
2887         f2fs_update_iostat(sbi, fio->io_type, F2FS_BLKSIZE);
2888 }
2889
2890 int rewrite_data_page(struct f2fs_io_info *fio)
2891 {
2892         int err;
2893         struct f2fs_sb_info *sbi = fio->sbi;
2894
2895         fio->new_blkaddr = fio->old_blkaddr;
2896         /* i/o temperature is needed for passing down write hints */
2897         __get_segment_type(fio);
2898
2899         f2fs_bug_on(sbi, !IS_DATASEG(get_seg_entry(sbi,
2900                         GET_SEGNO(sbi, fio->new_blkaddr))->type));
2901
2902         stat_inc_inplace_blocks(fio->sbi);
2903
2904         err = f2fs_submit_page_bio(fio);
2905         if (!err)
2906                 update_device_state(fio);
2907
2908         f2fs_update_iostat(fio->sbi, fio->io_type, F2FS_BLKSIZE);
2909
2910         return err;
2911 }
2912
2913 static inline int __f2fs_get_curseg(struct f2fs_sb_info *sbi,
2914                                                 unsigned int segno)
2915 {
2916         int i;
2917
2918         for (i = CURSEG_HOT_DATA; i < NO_CHECK_TYPE; i++) {
2919                 if (CURSEG_I(sbi, i)->segno == segno)
2920                         break;
2921         }
2922         return i;
2923 }
2924
2925 void __f2fs_replace_block(struct f2fs_sb_info *sbi, struct f2fs_summary *sum,
2926                                 block_t old_blkaddr, block_t new_blkaddr,
2927                                 bool recover_curseg, bool recover_newaddr)
2928 {
2929         struct sit_info *sit_i = SIT_I(sbi);
2930         struct curseg_info *curseg;
2931         unsigned int segno, old_cursegno;
2932         struct seg_entry *se;
2933         int type;
2934         unsigned short old_blkoff;
2935
2936         segno = GET_SEGNO(sbi, new_blkaddr);
2937         se = get_seg_entry(sbi, segno);
2938         type = se->type;
2939
2940         down_write(&SM_I(sbi)->curseg_lock);
2941
2942         if (!recover_curseg) {
2943                 /* for recovery flow */
2944                 if (se->valid_blocks == 0 && !IS_CURSEG(sbi, segno)) {
2945                         if (old_blkaddr == NULL_ADDR)
2946                                 type = CURSEG_COLD_DATA;
2947                         else
2948                                 type = CURSEG_WARM_DATA;
2949                 }
2950         } else {
2951                 if (IS_CURSEG(sbi, segno)) {
2952                         /* se->type is volatile as SSR allocation */
2953                         type = __f2fs_get_curseg(sbi, segno);
2954                         f2fs_bug_on(sbi, type == NO_CHECK_TYPE);
2955                 } else {
2956                         type = CURSEG_WARM_DATA;
2957                 }
2958         }
2959
2960         f2fs_bug_on(sbi, !IS_DATASEG(type));
2961         curseg = CURSEG_I(sbi, type);
2962
2963         mutex_lock(&curseg->curseg_mutex);
2964         down_write(&sit_i->sentry_lock);
2965
2966         old_cursegno = curseg->segno;
2967         old_blkoff = curseg->next_blkoff;
2968
2969         /* change the current segment */
2970         if (segno != curseg->segno) {
2971                 curseg->next_segno = segno;
2972                 change_curseg(sbi, type);
2973         }
2974
2975         curseg->next_blkoff = GET_BLKOFF_FROM_SEG0(sbi, new_blkaddr);
2976         __add_sum_entry(sbi, type, sum);
2977
2978         if (!recover_curseg || recover_newaddr)
2979                 update_sit_entry(sbi, new_blkaddr, 1);
2980         if (GET_SEGNO(sbi, old_blkaddr) != NULL_SEGNO)
2981                 update_sit_entry(sbi, old_blkaddr, -1);
2982
2983         locate_dirty_segment(sbi, GET_SEGNO(sbi, old_blkaddr));
2984         locate_dirty_segment(sbi, GET_SEGNO(sbi, new_blkaddr));
2985
2986         locate_dirty_segment(sbi, old_cursegno);
2987
2988         if (recover_curseg) {
2989                 if (old_cursegno != curseg->segno) {
2990                         curseg->next_segno = old_cursegno;
2991                         change_curseg(sbi, type);
2992                 }
2993                 curseg->next_blkoff = old_blkoff;
2994         }
2995
2996         up_write(&sit_i->sentry_lock);
2997         mutex_unlock(&curseg->curseg_mutex);
2998         up_write(&SM_I(sbi)->curseg_lock);
2999 }
3000
3001 void f2fs_replace_block(struct f2fs_sb_info *sbi, struct dnode_of_data *dn,
3002                                 block_t old_addr, block_t new_addr,
3003                                 unsigned char version, bool recover_curseg,
3004                                 bool recover_newaddr)
3005 {
3006         struct f2fs_summary sum;
3007
3008         set_summary(&sum, dn->nid, dn->ofs_in_node, version);
3009
3010         __f2fs_replace_block(sbi, &sum, old_addr, new_addr,
3011                                         recover_curseg, recover_newaddr);
3012
3013         f2fs_update_data_blkaddr(dn, new_addr);
3014 }
3015
3016 void f2fs_wait_on_page_writeback(struct page *page,
3017                                 enum page_type type, bool ordered)
3018 {
3019         if (PageWriteback(page)) {
3020                 struct f2fs_sb_info *sbi = F2FS_P_SB(page);
3021
3022                 f2fs_submit_merged_write_cond(sbi, page->mapping->host,
3023                                                 0, page->index, type);
3024                 if (ordered)
3025                         wait_on_page_writeback(page);
3026                 else
3027                         wait_for_stable_page(page);
3028         }
3029 }
3030
3031 void f2fs_wait_on_block_writeback(struct f2fs_sb_info *sbi, block_t blkaddr)
3032 {
3033         struct page *cpage;
3034
3035         if (blkaddr == NEW_ADDR || blkaddr == NULL_ADDR)
3036                 return;
3037
3038         cpage = find_lock_page(META_MAPPING(sbi), blkaddr);
3039         if (cpage) {
3040                 f2fs_wait_on_page_writeback(cpage, DATA, true);
3041                 f2fs_put_page(cpage, 1);
3042         }
3043 }
3044
3045 static void read_compacted_summaries(struct f2fs_sb_info *sbi)
3046 {
3047         struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
3048         struct curseg_info *seg_i;
3049         unsigned char *kaddr;
3050         struct page *page;
3051         block_t start;
3052         int i, j, offset;
3053
3054         start = start_sum_block(sbi);
3055
3056         page = get_meta_page(sbi, start++);
3057         kaddr = (unsigned char *)page_address(page);
3058
3059         /* Step 1: restore nat cache */
3060         seg_i = CURSEG_I(sbi, CURSEG_HOT_DATA);
3061         memcpy(seg_i->journal, kaddr, SUM_JOURNAL_SIZE);
3062
3063         /* Step 2: restore sit cache */
3064         seg_i = CURSEG_I(sbi, CURSEG_COLD_DATA);
3065         memcpy(seg_i->journal, kaddr + SUM_JOURNAL_SIZE, SUM_JOURNAL_SIZE);
3066         offset = 2 * SUM_JOURNAL_SIZE;
3067
3068         /* Step 3: restore summary entries */
3069         for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
3070                 unsigned short blk_off;
3071                 unsigned int segno;
3072
3073                 seg_i = CURSEG_I(sbi, i);
3074                 segno = le32_to_cpu(ckpt->cur_data_segno[i]);
3075                 blk_off = le16_to_cpu(ckpt->cur_data_blkoff[i]);
3076                 seg_i->next_segno = segno;
3077                 reset_curseg(sbi, i, 0);
3078                 seg_i->alloc_type = ckpt->alloc_type[i];
3079                 seg_i->next_blkoff = blk_off;
3080
3081                 if (seg_i->alloc_type == SSR)
3082                         blk_off = sbi->blocks_per_seg;
3083
3084                 for (j = 0; j < blk_off; j++) {
3085                         struct f2fs_summary *s;
3086                         s = (struct f2fs_summary *)(kaddr + offset);
3087                         seg_i->sum_blk->entries[j] = *s;
3088                         offset += SUMMARY_SIZE;
3089                         if (offset + SUMMARY_SIZE <= PAGE_SIZE -
3090                                                 SUM_FOOTER_SIZE)
3091                                 continue;
3092
3093                         f2fs_put_page(page, 1);
3094                         page = NULL;
3095
3096                         page = get_meta_page(sbi, start++);
3097                         kaddr = (unsigned char *)page_address(page);
3098                         offset = 0;
3099                 }
3100         }
3101         f2fs_put_page(page, 1);
3102 }
3103
3104 static int read_normal_summaries(struct f2fs_sb_info *sbi, int type)
3105 {
3106         struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
3107         struct f2fs_summary_block *sum;
3108         struct curseg_info *curseg;
3109         struct page *new;
3110         unsigned short blk_off;
3111         unsigned int segno = 0;
3112         block_t blk_addr = 0;
3113
3114         /* get segment number and block addr */
3115         if (IS_DATASEG(type)) {
3116                 segno = le32_to_cpu(ckpt->cur_data_segno[type]);
3117                 blk_off = le16_to_cpu(ckpt->cur_data_blkoff[type -
3118                                                         CURSEG_HOT_DATA]);
3119                 if (__exist_node_summaries(sbi))
3120                         blk_addr = sum_blk_addr(sbi, NR_CURSEG_TYPE, type);
3121                 else
3122                         blk_addr = sum_blk_addr(sbi, NR_CURSEG_DATA_TYPE, type);
3123         } else {
3124                 segno = le32_to_cpu(ckpt->cur_node_segno[type -
3125                                                         CURSEG_HOT_NODE]);
3126                 blk_off = le16_to_cpu(ckpt->cur_node_blkoff[type -
3127                                                         CURSEG_HOT_NODE]);
3128                 if (__exist_node_summaries(sbi))
3129                         blk_addr = sum_blk_addr(sbi, NR_CURSEG_NODE_TYPE,
3130                                                         type - CURSEG_HOT_NODE);
3131                 else
3132                         blk_addr = GET_SUM_BLOCK(sbi, segno);
3133         }
3134
3135         new = get_meta_page(sbi, blk_addr);
3136         sum = (struct f2fs_summary_block *)page_address(new);
3137
3138         if (IS_NODESEG(type)) {
3139                 if (__exist_node_summaries(sbi)) {
3140                         struct f2fs_summary *ns = &sum->entries[0];
3141                         int i;
3142                         for (i = 0; i < sbi->blocks_per_seg; i++, ns++) {
3143                                 ns->version = 0;
3144                                 ns->ofs_in_node = 0;
3145                         }
3146                 } else {
3147                         restore_node_summary(sbi, segno, sum);
3148                 }
3149         }
3150
3151         /* set uncompleted segment to curseg */
3152         curseg = CURSEG_I(sbi, type);
3153         mutex_lock(&curseg->curseg_mutex);
3154
3155         /* update journal info */
3156         down_write(&curseg->journal_rwsem);
3157         memcpy(curseg->journal, &sum->journal, SUM_JOURNAL_SIZE);
3158         up_write(&curseg->journal_rwsem);
3159
3160         memcpy(curseg->sum_blk->entries, sum->entries, SUM_ENTRY_SIZE);
3161         memcpy(&curseg->sum_blk->footer, &sum->footer, SUM_FOOTER_SIZE);
3162         curseg->next_segno = segno;
3163         reset_curseg(sbi, type, 0);
3164         curseg->alloc_type = ckpt->alloc_type[type];
3165         curseg->next_blkoff = blk_off;
3166         mutex_unlock(&curseg->curseg_mutex);
3167         f2fs_put_page(new, 1);
3168         return 0;
3169 }
3170
3171 static int restore_curseg_summaries(struct f2fs_sb_info *sbi)
3172 {
3173         struct f2fs_journal *sit_j = CURSEG_I(sbi, CURSEG_COLD_DATA)->journal;
3174         struct f2fs_journal *nat_j = CURSEG_I(sbi, CURSEG_HOT_DATA)->journal;
3175         int type = CURSEG_HOT_DATA;
3176         int err;
3177
3178         if (is_set_ckpt_flags(sbi, CP_COMPACT_SUM_FLAG)) {
3179                 int npages = npages_for_summary_flush(sbi, true);
3180
3181                 if (npages >= 2)
3182                         ra_meta_pages(sbi, start_sum_block(sbi), npages,
3183                                                         META_CP, true);
3184
3185                 /* restore for compacted data summary */
3186                 read_compacted_summaries(sbi);
3187                 type = CURSEG_HOT_NODE;
3188         }
3189
3190         if (__exist_node_summaries(sbi))
3191                 ra_meta_pages(sbi, sum_blk_addr(sbi, NR_CURSEG_TYPE, type),
3192                                         NR_CURSEG_TYPE - type, META_CP, true);
3193
3194         for (; type <= CURSEG_COLD_NODE; type++) {
3195                 err = read_normal_summaries(sbi, type);
3196                 if (err)
3197                         return err;
3198         }
3199
3200         /* sanity check for summary blocks */
3201         if (nats_in_cursum(nat_j) > NAT_JOURNAL_ENTRIES ||
3202                         sits_in_cursum(sit_j) > SIT_JOURNAL_ENTRIES)
3203                 return -EINVAL;
3204
3205         return 0;
3206 }
3207
3208 static void write_compacted_summaries(struct f2fs_sb_info *sbi, block_t blkaddr)
3209 {
3210         struct page *page;
3211         unsigned char *kaddr;
3212         struct f2fs_summary *summary;
3213         struct curseg_info *seg_i;
3214         int written_size = 0;
3215         int i, j;
3216
3217         page = grab_meta_page(sbi, blkaddr++);
3218         kaddr = (unsigned char *)page_address(page);
3219
3220         /* Step 1: write nat cache */
3221         seg_i = CURSEG_I(sbi, CURSEG_HOT_DATA);
3222         memcpy(kaddr, seg_i->journal, SUM_JOURNAL_SIZE);
3223         written_size += SUM_JOURNAL_SIZE;
3224
3225         /* Step 2: write sit cache */
3226         seg_i = CURSEG_I(sbi, CURSEG_COLD_DATA);
3227         memcpy(kaddr + written_size, seg_i->journal, SUM_JOURNAL_SIZE);
3228         written_size += SUM_JOURNAL_SIZE;
3229
3230         /* Step 3: write summary entries */
3231         for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
3232                 unsigned short blkoff;
3233                 seg_i = CURSEG_I(sbi, i);
3234                 if (sbi->ckpt->alloc_type[i] == SSR)
3235                         blkoff = sbi->blocks_per_seg;
3236                 else
3237                         blkoff = curseg_blkoff(sbi, i);
3238
3239                 for (j = 0; j < blkoff; j++) {
3240                         if (!page) {
3241                                 page = grab_meta_page(sbi, blkaddr++);
3242                                 kaddr = (unsigned char *)page_address(page);
3243                                 written_size = 0;
3244                         }
3245                         summary = (struct f2fs_summary *)(kaddr + written_size);
3246                         *summary = seg_i->sum_blk->entries[j];
3247                         written_size += SUMMARY_SIZE;
3248
3249                         if (written_size + SUMMARY_SIZE <= PAGE_SIZE -
3250                                                         SUM_FOOTER_SIZE)
3251                                 continue;
3252
3253                         set_page_dirty(page);
3254                         f2fs_put_page(page, 1);
3255                         page = NULL;
3256                 }
3257         }
3258         if (page) {
3259                 set_page_dirty(page);
3260                 f2fs_put_page(page, 1);
3261         }
3262 }
3263
3264 static void write_normal_summaries(struct f2fs_sb_info *sbi,
3265                                         block_t blkaddr, int type)
3266 {
3267         int i, end;
3268         if (IS_DATASEG(type))
3269                 end = type + NR_CURSEG_DATA_TYPE;
3270         else
3271                 end = type + NR_CURSEG_NODE_TYPE;
3272
3273         for (i = type; i < end; i++)
3274                 write_current_sum_page(sbi, i, blkaddr + (i - type));
3275 }
3276
3277 void write_data_summaries(struct f2fs_sb_info *sbi, block_t start_blk)
3278 {
3279         if (is_set_ckpt_flags(sbi, CP_COMPACT_SUM_FLAG))
3280                 write_compacted_summaries(sbi, start_blk);
3281         else
3282                 write_normal_summaries(sbi, start_blk, CURSEG_HOT_DATA);
3283 }
3284
3285 void write_node_summaries(struct f2fs_sb_info *sbi, block_t start_blk)
3286 {
3287         write_normal_summaries(sbi, start_blk, CURSEG_HOT_NODE);
3288 }
3289
3290 int lookup_journal_in_cursum(struct f2fs_journal *journal, int type,
3291                                         unsigned int val, int alloc)
3292 {
3293         int i;
3294
3295         if (type == NAT_JOURNAL) {
3296                 for (i = 0; i < nats_in_cursum(journal); i++) {
3297                         if (le32_to_cpu(nid_in_journal(journal, i)) == val)
3298                                 return i;
3299                 }
3300                 if (alloc && __has_cursum_space(journal, 1, NAT_JOURNAL))
3301                         return update_nats_in_cursum(journal, 1);
3302         } else if (type == SIT_JOURNAL) {
3303                 for (i = 0; i < sits_in_cursum(journal); i++)
3304                         if (le32_to_cpu(segno_in_journal(journal, i)) == val)
3305                                 return i;
3306                 if (alloc && __has_cursum_space(journal, 1, SIT_JOURNAL))
3307                         return update_sits_in_cursum(journal, 1);
3308         }
3309         return -1;
3310 }
3311
3312 static struct page *get_current_sit_page(struct f2fs_sb_info *sbi,
3313                                         unsigned int segno)
3314 {
3315         return get_meta_page(sbi, current_sit_addr(sbi, segno));
3316 }
3317
3318 static struct page *get_next_sit_page(struct f2fs_sb_info *sbi,
3319                                         unsigned int start)
3320 {
3321         struct sit_info *sit_i = SIT_I(sbi);
3322         struct page *page;
3323         pgoff_t src_off, dst_off;
3324
3325         src_off = current_sit_addr(sbi, start);
3326         dst_off = next_sit_addr(sbi, src_off);
3327
3328         page = grab_meta_page(sbi, dst_off);
3329         seg_info_to_sit_page(sbi, page, start);
3330
3331         set_page_dirty(page);
3332         set_to_next_sit(sit_i, start);
3333
3334         return page;
3335 }
3336
3337 static struct sit_entry_set *grab_sit_entry_set(void)
3338 {
3339         struct sit_entry_set *ses =
3340                         f2fs_kmem_cache_alloc(sit_entry_set_slab, GFP_NOFS);
3341
3342         ses->entry_cnt = 0;
3343         INIT_LIST_HEAD(&ses->set_list);
3344         return ses;
3345 }
3346
3347 static void release_sit_entry_set(struct sit_entry_set *ses)
3348 {
3349         list_del(&ses->set_list);
3350         kmem_cache_free(sit_entry_set_slab, ses);
3351 }
3352
3353 static void adjust_sit_entry_set(struct sit_entry_set *ses,
3354                                                 struct list_head *head)
3355 {
3356         struct sit_entry_set *next = ses;
3357
3358         if (list_is_last(&ses->set_list, head))
3359                 return;
3360
3361         list_for_each_entry_continue(next, head, set_list)
3362                 if (ses->entry_cnt <= next->entry_cnt)
3363                         break;
3364
3365         list_move_tail(&ses->set_list, &next->set_list);
3366 }
3367
3368 static void add_sit_entry(unsigned int segno, struct list_head *head)
3369 {
3370         struct sit_entry_set *ses;
3371         unsigned int start_segno = START_SEGNO(segno);
3372
3373         list_for_each_entry(ses, head, set_list) {
3374                 if (ses->start_segno == start_segno) {
3375                         ses->entry_cnt++;
3376                         adjust_sit_entry_set(ses, head);
3377                         return;
3378                 }
3379         }
3380
3381         ses = grab_sit_entry_set();
3382
3383         ses->start_segno = start_segno;
3384         ses->entry_cnt++;
3385         list_add(&ses->set_list, head);
3386 }
3387
3388 static void add_sits_in_set(struct f2fs_sb_info *sbi)
3389 {
3390         struct f2fs_sm_info *sm_info = SM_I(sbi);
3391         struct list_head *set_list = &sm_info->sit_entry_set;
3392         unsigned long *bitmap = SIT_I(sbi)->dirty_sentries_bitmap;
3393         unsigned int segno;
3394
3395         for_each_set_bit(segno, bitmap, MAIN_SEGS(sbi))
3396                 add_sit_entry(segno, set_list);
3397 }
3398
3399 static void remove_sits_in_journal(struct f2fs_sb_info *sbi)
3400 {
3401         struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
3402         struct f2fs_journal *journal = curseg->journal;
3403         int i;
3404
3405         down_write(&curseg->journal_rwsem);
3406         for (i = 0; i < sits_in_cursum(journal); i++) {
3407                 unsigned int segno;
3408                 bool dirtied;
3409
3410                 segno = le32_to_cpu(segno_in_journal(journal, i));
3411                 dirtied = __mark_sit_entry_dirty(sbi, segno);
3412
3413                 if (!dirtied)
3414                         add_sit_entry(segno, &SM_I(sbi)->sit_entry_set);
3415         }
3416         update_sits_in_cursum(journal, -i);
3417         up_write(&curseg->journal_rwsem);
3418 }
3419
3420 /*
3421  * CP calls this function, which flushes SIT entries including sit_journal,
3422  * and moves prefree segs to free segs.
3423  */
3424 void flush_sit_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc)
3425 {
3426         struct sit_info *sit_i = SIT_I(sbi);
3427         unsigned long *bitmap = sit_i->dirty_sentries_bitmap;
3428         struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
3429         struct f2fs_journal *journal = curseg->journal;
3430         struct sit_entry_set *ses, *tmp;
3431         struct list_head *head = &SM_I(sbi)->sit_entry_set;
3432         bool to_journal = true;
3433         struct seg_entry *se;
3434
3435         down_write(&sit_i->sentry_lock);
3436
3437         if (!sit_i->dirty_sentries)
3438                 goto out;
3439
3440         /*
3441          * add and account sit entries of dirty bitmap in sit entry
3442          * set temporarily
3443          */
3444         add_sits_in_set(sbi);
3445
3446         /*
3447          * if there are no enough space in journal to store dirty sit
3448          * entries, remove all entries from journal and add and account
3449          * them in sit entry set.
3450          */
3451         if (!__has_cursum_space(journal, sit_i->dirty_sentries, SIT_JOURNAL))
3452                 remove_sits_in_journal(sbi);
3453
3454         /*
3455          * there are two steps to flush sit entries:
3456          * #1, flush sit entries to journal in current cold data summary block.
3457          * #2, flush sit entries to sit page.
3458          */
3459         list_for_each_entry_safe(ses, tmp, head, set_list) {
3460                 struct page *page = NULL;
3461                 struct f2fs_sit_block *raw_sit = NULL;
3462                 unsigned int start_segno = ses->start_segno;
3463                 unsigned int end = min(start_segno + SIT_ENTRY_PER_BLOCK,
3464                                                 (unsigned long)MAIN_SEGS(sbi));
3465                 unsigned int segno = start_segno;
3466
3467                 if (to_journal &&
3468                         !__has_cursum_space(journal, ses->entry_cnt, SIT_JOURNAL))
3469                         to_journal = false;
3470
3471                 if (to_journal) {
3472                         down_write(&curseg->journal_rwsem);
3473                 } else {
3474                         page = get_next_sit_page(sbi, start_segno);
3475                         raw_sit = page_address(page);
3476                 }
3477
3478                 /* flush dirty sit entries in region of current sit set */
3479                 for_each_set_bit_from(segno, bitmap, end) {
3480                         int offset, sit_offset;
3481
3482                         se = get_seg_entry(sbi, segno);
3483
3484                         /* add discard candidates */
3485                         if (!(cpc->reason & CP_DISCARD)) {
3486                                 cpc->trim_start = segno;
3487                                 add_discard_addrs(sbi, cpc, false);
3488                         }
3489
3490                         if (to_journal) {
3491                                 offset = lookup_journal_in_cursum(journal,
3492                                                         SIT_JOURNAL, segno, 1);
3493                                 f2fs_bug_on(sbi, offset < 0);
3494                                 segno_in_journal(journal, offset) =
3495                                                         cpu_to_le32(segno);
3496                                 seg_info_to_raw_sit(se,
3497                                         &sit_in_journal(journal, offset));
3498                         } else {
3499                                 sit_offset = SIT_ENTRY_OFFSET(sit_i, segno);
3500                                 seg_info_to_raw_sit(se,
3501                                                 &raw_sit->entries[sit_offset]);
3502                         }
3503
3504                         __clear_bit(segno, bitmap);
3505                         sit_i->dirty_sentries--;
3506                         ses->entry_cnt--;
3507                 }
3508
3509                 if (to_journal)
3510                         up_write(&curseg->journal_rwsem);
3511                 else
3512                         f2fs_put_page(page, 1);
3513
3514                 f2fs_bug_on(sbi, ses->entry_cnt);
3515                 release_sit_entry_set(ses);
3516         }
3517
3518         f2fs_bug_on(sbi, !list_empty(head));
3519         f2fs_bug_on(sbi, sit_i->dirty_sentries);
3520 out:
3521         if (cpc->reason & CP_DISCARD) {
3522                 __u64 trim_start = cpc->trim_start;
3523
3524                 for (; cpc->trim_start <= cpc->trim_end; cpc->trim_start++)
3525                         add_discard_addrs(sbi, cpc, false);
3526
3527                 cpc->trim_start = trim_start;
3528         }
3529         up_write(&sit_i->sentry_lock);
3530
3531         set_prefree_as_free_segments(sbi);
3532 }
3533
3534 static int build_sit_info(struct f2fs_sb_info *sbi)
3535 {
3536         struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
3537         struct sit_info *sit_i;
3538         unsigned int sit_segs, start;
3539         char *src_bitmap;
3540         unsigned int bitmap_size;
3541
3542         /* allocate memory for SIT information */
3543         sit_i = f2fs_kzalloc(sbi, sizeof(struct sit_info), GFP_KERNEL);
3544         if (!sit_i)
3545                 return -ENOMEM;
3546
3547         SM_I(sbi)->sit_info = sit_i;
3548
3549         sit_i->sentries = f2fs_kvzalloc(sbi, MAIN_SEGS(sbi) *
3550                                         sizeof(struct seg_entry), GFP_KERNEL);
3551         if (!sit_i->sentries)
3552                 return -ENOMEM;
3553
3554         bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
3555         sit_i->dirty_sentries_bitmap = f2fs_kvzalloc(sbi, bitmap_size,
3556                                                                 GFP_KERNEL);
3557         if (!sit_i->dirty_sentries_bitmap)
3558                 return -ENOMEM;
3559
3560         for (start = 0; start < MAIN_SEGS(sbi); start++) {
3561                 sit_i->sentries[start].cur_valid_map
3562                         = f2fs_kzalloc(sbi, SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
3563                 sit_i->sentries[start].ckpt_valid_map
3564                         = f2fs_kzalloc(sbi, SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
3565                 if (!sit_i->sentries[start].cur_valid_map ||
3566                                 !sit_i->sentries[start].ckpt_valid_map)
3567                         return -ENOMEM;
3568
3569 #ifdef CONFIG_F2FS_CHECK_FS
3570                 sit_i->sentries[start].cur_valid_map_mir
3571                         = f2fs_kzalloc(sbi, SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
3572                 if (!sit_i->sentries[start].cur_valid_map_mir)
3573                         return -ENOMEM;
3574 #endif
3575
3576                 if (f2fs_discard_en(sbi)) {
3577                         sit_i->sentries[start].discard_map
3578                                 = f2fs_kzalloc(sbi, SIT_VBLOCK_MAP_SIZE,
3579                                                                 GFP_KERNEL);
3580                         if (!sit_i->sentries[start].discard_map)
3581                                 return -ENOMEM;
3582                 }
3583         }
3584
3585         sit_i->tmp_map = f2fs_kzalloc(sbi, SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
3586         if (!sit_i->tmp_map)
3587                 return -ENOMEM;
3588
3589         if (sbi->segs_per_sec > 1) {
3590                 sit_i->sec_entries = f2fs_kvzalloc(sbi, MAIN_SECS(sbi) *
3591                                         sizeof(struct sec_entry), GFP_KERNEL);
3592                 if (!sit_i->sec_entries)
3593                         return -ENOMEM;
3594         }
3595
3596         /* get information related with SIT */
3597         sit_segs = le32_to_cpu(raw_super->segment_count_sit) >> 1;
3598
3599         /* setup SIT bitmap from ckeckpoint pack */
3600         bitmap_size = __bitmap_size(sbi, SIT_BITMAP);
3601         src_bitmap = __bitmap_ptr(sbi, SIT_BITMAP);
3602
3603         sit_i->sit_bitmap = kmemdup(src_bitmap, bitmap_size, GFP_KERNEL);
3604         if (!sit_i->sit_bitmap)
3605                 return -ENOMEM;
3606
3607 #ifdef CONFIG_F2FS_CHECK_FS
3608         sit_i->sit_bitmap_mir = kmemdup(src_bitmap, bitmap_size, GFP_KERNEL);
3609         if (!sit_i->sit_bitmap_mir)
3610                 return -ENOMEM;
3611 #endif
3612
3613         /* init SIT information */
3614         sit_i->s_ops = &default_salloc_ops;
3615
3616         sit_i->sit_base_addr = le32_to_cpu(raw_super->sit_blkaddr);
3617         sit_i->sit_blocks = sit_segs << sbi->log_blocks_per_seg;
3618         sit_i->written_valid_blocks = 0;
3619         sit_i->bitmap_size = bitmap_size;
3620         sit_i->dirty_sentries = 0;
3621         sit_i->sents_per_block = SIT_ENTRY_PER_BLOCK;
3622         sit_i->elapsed_time = le64_to_cpu(sbi->ckpt->elapsed_time);
3623         sit_i->mounted_time = CURRENT_TIME_SEC.tv_sec;
3624         init_rwsem(&sit_i->sentry_lock);
3625         return 0;
3626 }
3627
3628 static int build_free_segmap(struct f2fs_sb_info *sbi)
3629 {
3630         struct free_segmap_info *free_i;
3631         unsigned int bitmap_size, sec_bitmap_size;
3632
3633         /* allocate memory for free segmap information */
3634         free_i = f2fs_kzalloc(sbi, sizeof(struct free_segmap_info), GFP_KERNEL);
3635         if (!free_i)
3636                 return -ENOMEM;
3637
3638         SM_I(sbi)->free_info = free_i;
3639
3640         bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
3641         free_i->free_segmap = f2fs_kvmalloc(sbi, bitmap_size, GFP_KERNEL);
3642         if (!free_i->free_segmap)
3643                 return -ENOMEM;
3644
3645         sec_bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
3646         free_i->free_secmap = f2fs_kvmalloc(sbi, sec_bitmap_size, GFP_KERNEL);
3647         if (!free_i->free_secmap)
3648                 return -ENOMEM;
3649
3650         /* set all segments as dirty temporarily */
3651         memset(free_i->free_segmap, 0xff, bitmap_size);
3652         memset(free_i->free_secmap, 0xff, sec_bitmap_size);
3653
3654         /* init free segmap information */
3655         free_i->start_segno = GET_SEGNO_FROM_SEG0(sbi, MAIN_BLKADDR(sbi));
3656         free_i->free_segments = 0;
3657         free_i->free_sections = 0;
3658         spin_lock_init(&free_i->segmap_lock);
3659         return 0;
3660 }
3661
3662 static int build_curseg(struct f2fs_sb_info *sbi)
3663 {
3664         struct curseg_info *array;
3665         int i;
3666
3667         array = f2fs_kzalloc(sbi, sizeof(*array) * NR_CURSEG_TYPE, GFP_KERNEL);
3668         if (!array)
3669                 return -ENOMEM;
3670
3671         SM_I(sbi)->curseg_array = array;
3672
3673         for (i = 0; i < NR_CURSEG_TYPE; i++) {
3674                 mutex_init(&array[i].curseg_mutex);
3675                 array[i].sum_blk = f2fs_kzalloc(sbi, PAGE_SIZE, GFP_KERNEL);
3676                 if (!array[i].sum_blk)
3677                         return -ENOMEM;
3678                 init_rwsem(&array[i].journal_rwsem);
3679                 array[i].journal = f2fs_kzalloc(sbi,
3680                                 sizeof(struct f2fs_journal), GFP_KERNEL);
3681                 if (!array[i].journal)
3682                         return -ENOMEM;
3683                 array[i].segno = NULL_SEGNO;
3684                 array[i].next_blkoff = 0;
3685         }
3686         return restore_curseg_summaries(sbi);
3687 }
3688
3689 static int build_sit_entries(struct f2fs_sb_info *sbi)
3690 {
3691         struct sit_info *sit_i = SIT_I(sbi);
3692         struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
3693         struct f2fs_journal *journal = curseg->journal;
3694         struct seg_entry *se;
3695         struct f2fs_sit_entry sit;
3696         int sit_blk_cnt = SIT_BLK_CNT(sbi);
3697         unsigned int i, start, end;
3698         unsigned int readed, start_blk = 0;
3699         int err = 0;
3700
3701         do {
3702                 readed = ra_meta_pages(sbi, start_blk, BIO_MAX_PAGES,
3703                                                         META_SIT, true);
3704
3705                 start = start_blk * sit_i->sents_per_block;
3706                 end = (start_blk + readed) * sit_i->sents_per_block;
3707
3708                 for (; start < end && start < MAIN_SEGS(sbi); start++) {
3709                         struct f2fs_sit_block *sit_blk;
3710                         struct page *page;
3711
3712                         se = &sit_i->sentries[start];
3713                         page = get_current_sit_page(sbi, start);
3714                         sit_blk = (struct f2fs_sit_block *)page_address(page);
3715                         sit = sit_blk->entries[SIT_ENTRY_OFFSET(sit_i, start)];
3716                         f2fs_put_page(page, 1);
3717
3718                         err = check_block_count(sbi, start, &sit);
3719                         if (err)
3720                                 return err;
3721                         seg_info_from_raw_sit(se, &sit);
3722
3723                         /* build discard map only one time */
3724                         if (f2fs_discard_en(sbi)) {
3725                                 if (is_set_ckpt_flags(sbi, CP_TRIMMED_FLAG)) {
3726                                         memset(se->discard_map, 0xff,
3727                                                 SIT_VBLOCK_MAP_SIZE);
3728                                 } else {
3729                                         memcpy(se->discard_map,
3730                                                 se->cur_valid_map,
3731                                                 SIT_VBLOCK_MAP_SIZE);
3732                                         sbi->discard_blks +=
3733                                                 sbi->blocks_per_seg -
3734                                                 se->valid_blocks;
3735                                 }
3736                         }
3737
3738                         if (sbi->segs_per_sec > 1)
3739                                 get_sec_entry(sbi, start)->valid_blocks +=
3740                                                         se->valid_blocks;
3741                 }
3742                 start_blk += readed;
3743         } while (start_blk < sit_blk_cnt);
3744
3745         down_read(&curseg->journal_rwsem);
3746         for (i = 0; i < sits_in_cursum(journal); i++) {
3747                 unsigned int old_valid_blocks;
3748
3749                 start = le32_to_cpu(segno_in_journal(journal, i));
3750                 se = &sit_i->sentries[start];
3751                 sit = sit_in_journal(journal, i);
3752
3753                 old_valid_blocks = se->valid_blocks;
3754
3755                 err = check_block_count(sbi, start, &sit);
3756                 if (err)
3757                         break;
3758                 seg_info_from_raw_sit(se, &sit);
3759
3760                 if (f2fs_discard_en(sbi)) {
3761                         if (is_set_ckpt_flags(sbi, CP_TRIMMED_FLAG)) {
3762                                 memset(se->discard_map, 0xff,
3763                                                         SIT_VBLOCK_MAP_SIZE);
3764                         } else {
3765                                 memcpy(se->discard_map, se->cur_valid_map,
3766                                                         SIT_VBLOCK_MAP_SIZE);
3767                                 sbi->discard_blks += old_valid_blocks -
3768                                                         se->valid_blocks;
3769                         }
3770                 }
3771
3772                 if (sbi->segs_per_sec > 1)
3773                         get_sec_entry(sbi, start)->valid_blocks +=
3774                                 se->valid_blocks - old_valid_blocks;
3775         }
3776         up_read(&curseg->journal_rwsem);
3777         return err;
3778 }
3779
3780 static void init_free_segmap(struct f2fs_sb_info *sbi)
3781 {
3782         unsigned int start;
3783         int type;
3784
3785         for (start = 0; start < MAIN_SEGS(sbi); start++) {
3786                 struct seg_entry *sentry = get_seg_entry(sbi, start);
3787                 if (!sentry->valid_blocks)
3788                         __set_free(sbi, start);
3789                 else
3790                         SIT_I(sbi)->written_valid_blocks +=
3791                                                 sentry->valid_blocks;
3792         }
3793
3794         /* set use the current segments */
3795         for (type = CURSEG_HOT_DATA; type <= CURSEG_COLD_NODE; type++) {
3796                 struct curseg_info *curseg_t = CURSEG_I(sbi, type);
3797                 __set_test_and_inuse(sbi, curseg_t->segno);
3798         }
3799 }
3800
3801 static void init_dirty_segmap(struct f2fs_sb_info *sbi)
3802 {
3803         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
3804         struct free_segmap_info *free_i = FREE_I(sbi);
3805         unsigned int segno = 0, offset = 0;
3806         unsigned short valid_blocks;
3807
3808         while (1) {
3809                 /* find dirty segment based on free segmap */
3810                 segno = find_next_inuse(free_i, MAIN_SEGS(sbi), offset);
3811                 if (segno >= MAIN_SEGS(sbi))
3812                         break;
3813                 offset = segno + 1;
3814                 valid_blocks = get_valid_blocks(sbi, segno, false);
3815                 if (valid_blocks == sbi->blocks_per_seg || !valid_blocks)
3816                         continue;
3817                 if (valid_blocks > sbi->blocks_per_seg) {
3818                         f2fs_bug_on(sbi, 1);
3819                         continue;
3820                 }
3821                 mutex_lock(&dirty_i->seglist_lock);
3822                 __locate_dirty_segment(sbi, segno, DIRTY);
3823                 mutex_unlock(&dirty_i->seglist_lock);
3824         }
3825 }
3826
3827 static int init_victim_secmap(struct f2fs_sb_info *sbi)
3828 {
3829         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
3830         unsigned int bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
3831
3832         dirty_i->victim_secmap = f2fs_kvzalloc(sbi, bitmap_size, GFP_KERNEL);
3833         if (!dirty_i->victim_secmap)
3834                 return -ENOMEM;
3835         return 0;
3836 }
3837
3838 static int build_dirty_segmap(struct f2fs_sb_info *sbi)
3839 {
3840         struct dirty_seglist_info *dirty_i;
3841         unsigned int bitmap_size, i;
3842
3843         /* allocate memory for dirty segments list information */
3844         dirty_i = f2fs_kzalloc(sbi, sizeof(struct dirty_seglist_info),
3845                                                                 GFP_KERNEL);
3846         if (!dirty_i)
3847                 return -ENOMEM;
3848
3849         SM_I(sbi)->dirty_info = dirty_i;
3850         mutex_init(&dirty_i->seglist_lock);
3851
3852         bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
3853
3854         for (i = 0; i < NR_DIRTY_TYPE; i++) {
3855                 dirty_i->dirty_segmap[i] = f2fs_kvzalloc(sbi, bitmap_size,
3856                                                                 GFP_KERNEL);
3857                 if (!dirty_i->dirty_segmap[i])
3858                         return -ENOMEM;
3859         }
3860
3861         init_dirty_segmap(sbi);
3862         return init_victim_secmap(sbi);
3863 }
3864
3865 static int sanity_check_curseg(struct f2fs_sb_info *sbi)
3866 {
3867         int i;
3868
3869         /*
3870          * In LFS/SSR curseg, .next_blkoff should point to an unused blkaddr;
3871          * In LFS curseg, all blkaddr after .next_blkoff should be unused.
3872          */
3873         for (i = 0; i < NO_CHECK_TYPE; i++) {
3874                 struct curseg_info *curseg = CURSEG_I(sbi, i);
3875                 struct seg_entry *se = get_seg_entry(sbi, curseg->segno);
3876                 unsigned int blkofs = curseg->next_blkoff;
3877
3878                 if (f2fs_test_bit(blkofs, se->cur_valid_map))
3879                         goto out;
3880
3881                 if (curseg->alloc_type == SSR)
3882                         continue;
3883
3884                 for (blkofs += 1; blkofs < sbi->blocks_per_seg; blkofs++) {
3885                         if (!f2fs_test_bit(blkofs, se->cur_valid_map))
3886                                 continue;
3887 out:
3888                         f2fs_msg(sbi->sb, KERN_ERR,
3889                                 "Current segment's next free block offset is "
3890                                 "inconsistent with bitmap, logtype:%u, "
3891                                 "segno:%u, type:%u, next_blkoff:%u, blkofs:%u",
3892                                 i, curseg->segno, curseg->alloc_type,
3893                                 curseg->next_blkoff, blkofs);
3894                         return -EINVAL;
3895                 }
3896         }
3897         return 0;
3898 }
3899
3900 /*
3901  * Update min, max modified time for cost-benefit GC algorithm
3902  */
3903 static void init_min_max_mtime(struct f2fs_sb_info *sbi)
3904 {
3905         struct sit_info *sit_i = SIT_I(sbi);
3906         unsigned int segno;
3907
3908         down_write(&sit_i->sentry_lock);
3909
3910         sit_i->min_mtime = LLONG_MAX;
3911
3912         for (segno = 0; segno < MAIN_SEGS(sbi); segno += sbi->segs_per_sec) {
3913                 unsigned int i;
3914                 unsigned long long mtime = 0;
3915
3916                 for (i = 0; i < sbi->segs_per_sec; i++)
3917                         mtime += get_seg_entry(sbi, segno + i)->mtime;
3918
3919                 mtime = div_u64(mtime, sbi->segs_per_sec);
3920
3921                 if (sit_i->min_mtime > mtime)
3922                         sit_i->min_mtime = mtime;
3923         }
3924         sit_i->max_mtime = get_mtime(sbi);
3925         up_write(&sit_i->sentry_lock);
3926 }
3927
3928 int build_segment_manager(struct f2fs_sb_info *sbi)
3929 {
3930         struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
3931         struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
3932         struct f2fs_sm_info *sm_info;
3933         int err;
3934
3935         sm_info = f2fs_kzalloc(sbi, sizeof(struct f2fs_sm_info), GFP_KERNEL);
3936         if (!sm_info)
3937                 return -ENOMEM;
3938
3939         /* init sm info */
3940         sbi->sm_info = sm_info;
3941         sm_info->seg0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr);
3942         sm_info->main_blkaddr = le32_to_cpu(raw_super->main_blkaddr);
3943         sm_info->segment_count = le32_to_cpu(raw_super->segment_count);
3944         sm_info->reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
3945         sm_info->ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
3946         sm_info->main_segments = le32_to_cpu(raw_super->segment_count_main);
3947         sm_info->ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr);
3948         sm_info->rec_prefree_segments = sm_info->main_segments *
3949                                         DEF_RECLAIM_PREFREE_SEGMENTS / 100;
3950         if (sm_info->rec_prefree_segments > DEF_MAX_RECLAIM_PREFREE_SEGMENTS)
3951                 sm_info->rec_prefree_segments = DEF_MAX_RECLAIM_PREFREE_SEGMENTS;
3952
3953         if (!test_opt(sbi, LFS))
3954                 sm_info->ipu_policy = 1 << F2FS_IPU_FSYNC;
3955         sm_info->min_ipu_util = DEF_MIN_IPU_UTIL;
3956         sm_info->min_fsync_blocks = DEF_MIN_FSYNC_BLOCKS;
3957         sm_info->min_hot_blocks = DEF_MIN_HOT_BLOCKS;
3958         sm_info->min_ssr_sections = reserved_sections(sbi);
3959
3960         INIT_LIST_HEAD(&sm_info->sit_entry_set);
3961
3962         init_rwsem(&sm_info->curseg_lock);
3963
3964         if (!f2fs_readonly(sbi->sb)) {
3965                 err = create_flush_cmd_control(sbi);
3966                 if (err)
3967                         return err;
3968         }
3969
3970         err = create_discard_cmd_control(sbi);
3971         if (err)
3972                 return err;
3973
3974         err = build_sit_info(sbi);
3975         if (err)
3976                 return err;
3977         err = build_free_segmap(sbi);
3978         if (err)
3979                 return err;
3980         err = build_curseg(sbi);
3981         if (err)
3982                 return err;
3983
3984         /* reinit free segmap based on SIT */
3985         err = build_sit_entries(sbi);
3986         if (err)
3987                 return err;
3988
3989         init_free_segmap(sbi);
3990         err = build_dirty_segmap(sbi);
3991         if (err)
3992                 return err;
3993
3994         err = sanity_check_curseg(sbi);
3995         if (err)
3996                 return err;
3997
3998         init_min_max_mtime(sbi);
3999         return 0;
4000 }
4001
4002 static void discard_dirty_segmap(struct f2fs_sb_info *sbi,
4003                 enum dirty_type dirty_type)
4004 {
4005         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
4006
4007         mutex_lock(&dirty_i->seglist_lock);
4008         kvfree(dirty_i->dirty_segmap[dirty_type]);
4009         dirty_i->nr_dirty[dirty_type] = 0;
4010         mutex_unlock(&dirty_i->seglist_lock);
4011 }
4012
4013 static void destroy_victim_secmap(struct f2fs_sb_info *sbi)
4014 {
4015         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
4016         kvfree(dirty_i->victim_secmap);
4017 }
4018
4019 static void destroy_dirty_segmap(struct f2fs_sb_info *sbi)
4020 {
4021         struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
4022         int i;
4023
4024         if (!dirty_i)
4025                 return;
4026
4027         /* discard pre-free/dirty segments list */
4028         for (i = 0; i < NR_DIRTY_TYPE; i++)
4029                 discard_dirty_segmap(sbi, i);
4030
4031         destroy_victim_secmap(sbi);
4032         SM_I(sbi)->dirty_info = NULL;
4033         kfree(dirty_i);
4034 }
4035
4036 static void destroy_curseg(struct f2fs_sb_info *sbi)
4037 {
4038         struct curseg_info *array = SM_I(sbi)->curseg_array;
4039         int i;
4040
4041         if (!array)
4042                 return;
4043         SM_I(sbi)->curseg_array = NULL;
4044         for (i = 0; i < NR_CURSEG_TYPE; i++) {
4045                 kfree(array[i].sum_blk);
4046                 kfree(array[i].journal);
4047         }
4048         kfree(array);
4049 }
4050
4051 static void destroy_free_segmap(struct f2fs_sb_info *sbi)
4052 {
4053         struct free_segmap_info *free_i = SM_I(sbi)->free_info;
4054         if (!free_i)
4055                 return;
4056         SM_I(sbi)->free_info = NULL;
4057         kvfree(free_i->free_segmap);
4058         kvfree(free_i->free_secmap);
4059         kfree(free_i);
4060 }
4061
4062 static void destroy_sit_info(struct f2fs_sb_info *sbi)
4063 {
4064         struct sit_info *sit_i = SIT_I(sbi);
4065         unsigned int start;
4066
4067         if (!sit_i)
4068                 return;
4069
4070         if (sit_i->sentries) {
4071                 for (start = 0; start < MAIN_SEGS(sbi); start++) {
4072                         kfree(sit_i->sentries[start].cur_valid_map);
4073 #ifdef CONFIG_F2FS_CHECK_FS
4074                         kfree(sit_i->sentries[start].cur_valid_map_mir);
4075 #endif
4076                         kfree(sit_i->sentries[start].ckpt_valid_map);
4077                         kfree(sit_i->sentries[start].discard_map);
4078                 }
4079         }
4080         kfree(sit_i->tmp_map);
4081
4082         kvfree(sit_i->sentries);
4083         kvfree(sit_i->sec_entries);
4084         kvfree(sit_i->dirty_sentries_bitmap);
4085
4086         SM_I(sbi)->sit_info = NULL;
4087         kfree(sit_i->sit_bitmap);
4088 #ifdef CONFIG_F2FS_CHECK_FS
4089         kfree(sit_i->sit_bitmap_mir);
4090 #endif
4091         kfree(sit_i);
4092 }
4093
4094 void destroy_segment_manager(struct f2fs_sb_info *sbi)
4095 {
4096         struct f2fs_sm_info *sm_info = SM_I(sbi);
4097
4098         if (!sm_info)
4099                 return;
4100         destroy_flush_cmd_control(sbi, true);
4101         destroy_discard_cmd_control(sbi);
4102         destroy_dirty_segmap(sbi);
4103         destroy_curseg(sbi);
4104         destroy_free_segmap(sbi);
4105         destroy_sit_info(sbi);
4106         sbi->sm_info = NULL;
4107         kfree(sm_info);
4108 }
4109
4110 int __init create_segment_manager_caches(void)
4111 {
4112         discard_entry_slab = f2fs_kmem_cache_create("discard_entry",
4113                         sizeof(struct discard_entry));
4114         if (!discard_entry_slab)
4115                 goto fail;
4116
4117         discard_cmd_slab = f2fs_kmem_cache_create("discard_cmd",
4118                         sizeof(struct discard_cmd));
4119         if (!discard_cmd_slab)
4120                 goto destroy_discard_entry;
4121
4122         sit_entry_set_slab = f2fs_kmem_cache_create("sit_entry_set",
4123                         sizeof(struct sit_entry_set));
4124         if (!sit_entry_set_slab)
4125                 goto destroy_discard_cmd;
4126
4127         inmem_entry_slab = f2fs_kmem_cache_create("inmem_page_entry",
4128                         sizeof(struct inmem_pages));
4129         if (!inmem_entry_slab)
4130                 goto destroy_sit_entry_set;
4131         return 0;
4132
4133 destroy_sit_entry_set:
4134         kmem_cache_destroy(sit_entry_set_slab);
4135 destroy_discard_cmd:
4136         kmem_cache_destroy(discard_cmd_slab);
4137 destroy_discard_entry:
4138         kmem_cache_destroy(discard_entry_slab);
4139 fail:
4140         return -ENOMEM;
4141 }
4142
4143 void destroy_segment_manager_caches(void)
4144 {
4145         kmem_cache_destroy(sit_entry_set_slab);
4146         kmem_cache_destroy(discard_cmd_slab);
4147         kmem_cache_destroy(discard_entry_slab);
4148         kmem_cache_destroy(inmem_entry_slab);
4149 }