OSDN Git Service

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