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