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