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