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