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