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