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