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