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