xref: /openbmc/linux/fs/f2fs/segment.c (revision 6b5fc336)
1 /*
2  * fs/f2fs/segment.c
3  *
4  * Copyright (c) 2012 Samsung Electronics Co., Ltd.
5  *             http://www.samsung.com/
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  */
11 #include <linux/fs.h>
12 #include <linux/f2fs_fs.h>
13 #include <linux/bio.h>
14 #include <linux/blkdev.h>
15 #include <linux/prefetch.h>
16 #include <linux/kthread.h>
17 #include <linux/swap.h>
18 #include <linux/timer.h>
19 #include <linux/freezer.h>
20 
21 #include "f2fs.h"
22 #include "segment.h"
23 #include "node.h"
24 #include "trace.h"
25 #include <trace/events/f2fs.h>
26 
27 #define __reverse_ffz(x) __reverse_ffs(~(x))
28 
29 static struct kmem_cache *discard_entry_slab;
30 static struct kmem_cache *discard_cmd_slab;
31 static struct kmem_cache *sit_entry_set_slab;
32 static struct kmem_cache *inmem_entry_slab;
33 
34 static unsigned long __reverse_ulong(unsigned char *str)
35 {
36 	unsigned long tmp = 0;
37 	int shift = 24, idx = 0;
38 
39 #if BITS_PER_LONG == 64
40 	shift = 56;
41 #endif
42 	while (shift >= 0) {
43 		tmp |= (unsigned long)str[idx++] << shift;
44 		shift -= BITS_PER_BYTE;
45 	}
46 	return tmp;
47 }
48 
49 /*
50  * __reverse_ffs is copied from include/asm-generic/bitops/__ffs.h since
51  * MSB and LSB are reversed in a byte by f2fs_set_bit.
52  */
53 static inline unsigned long __reverse_ffs(unsigned long word)
54 {
55 	int num = 0;
56 
57 #if BITS_PER_LONG == 64
58 	if ((word & 0xffffffff00000000UL) == 0)
59 		num += 32;
60 	else
61 		word >>= 32;
62 #endif
63 	if ((word & 0xffff0000) == 0)
64 		num += 16;
65 	else
66 		word >>= 16;
67 
68 	if ((word & 0xff00) == 0)
69 		num += 8;
70 	else
71 		word >>= 8;
72 
73 	if ((word & 0xf0) == 0)
74 		num += 4;
75 	else
76 		word >>= 4;
77 
78 	if ((word & 0xc) == 0)
79 		num += 2;
80 	else
81 		word >>= 2;
82 
83 	if ((word & 0x2) == 0)
84 		num += 1;
85 	return num;
86 }
87 
88 /*
89  * __find_rev_next(_zero)_bit is copied from lib/find_next_bit.c because
90  * f2fs_set_bit makes MSB and LSB reversed in a byte.
91  * @size must be integral times of unsigned long.
92  * Example:
93  *                             MSB <--> LSB
94  *   f2fs_set_bit(0, bitmap) => 1000 0000
95  *   f2fs_set_bit(7, bitmap) => 0000 0001
96  */
97 static unsigned long __find_rev_next_bit(const unsigned long *addr,
98 			unsigned long size, unsigned long offset)
99 {
100 	const unsigned long *p = addr + BIT_WORD(offset);
101 	unsigned long result = size;
102 	unsigned long tmp;
103 
104 	if (offset >= size)
105 		return size;
106 
107 	size -= (offset & ~(BITS_PER_LONG - 1));
108 	offset %= BITS_PER_LONG;
109 
110 	while (1) {
111 		if (*p == 0)
112 			goto pass;
113 
114 		tmp = __reverse_ulong((unsigned char *)p);
115 
116 		tmp &= ~0UL >> offset;
117 		if (size < BITS_PER_LONG)
118 			tmp &= (~0UL << (BITS_PER_LONG - size));
119 		if (tmp)
120 			goto found;
121 pass:
122 		if (size <= BITS_PER_LONG)
123 			break;
124 		size -= BITS_PER_LONG;
125 		offset = 0;
126 		p++;
127 	}
128 	return result;
129 found:
130 	return result - size + __reverse_ffs(tmp);
131 }
132 
133 static unsigned long __find_rev_next_zero_bit(const unsigned long *addr,
134 			unsigned long size, unsigned long offset)
135 {
136 	const unsigned long *p = addr + BIT_WORD(offset);
137 	unsigned long result = size;
138 	unsigned long tmp;
139 
140 	if (offset >= size)
141 		return size;
142 
143 	size -= (offset & ~(BITS_PER_LONG - 1));
144 	offset %= BITS_PER_LONG;
145 
146 	while (1) {
147 		if (*p == ~0UL)
148 			goto pass;
149 
150 		tmp = __reverse_ulong((unsigned char *)p);
151 
152 		if (offset)
153 			tmp |= ~0UL << (BITS_PER_LONG - offset);
154 		if (size < BITS_PER_LONG)
155 			tmp |= ~0UL >> size;
156 		if (tmp != ~0UL)
157 			goto found;
158 pass:
159 		if (size <= BITS_PER_LONG)
160 			break;
161 		size -= BITS_PER_LONG;
162 		offset = 0;
163 		p++;
164 	}
165 	return result;
166 found:
167 	return result - size + __reverse_ffz(tmp);
168 }
169 
170 void register_inmem_page(struct inode *inode, struct page *page)
171 {
172 	struct f2fs_inode_info *fi = F2FS_I(inode);
173 	struct inmem_pages *new;
174 
175 	f2fs_trace_pid(page);
176 
177 	set_page_private(page, (unsigned long)ATOMIC_WRITTEN_PAGE);
178 	SetPagePrivate(page);
179 
180 	new = f2fs_kmem_cache_alloc(inmem_entry_slab, GFP_NOFS);
181 
182 	/* add atomic page indices to the list */
183 	new->page = page;
184 	INIT_LIST_HEAD(&new->list);
185 
186 	/* increase reference count with clean state */
187 	mutex_lock(&fi->inmem_lock);
188 	get_page(page);
189 	list_add_tail(&new->list, &fi->inmem_pages);
190 	inc_page_count(F2FS_I_SB(inode), F2FS_INMEM_PAGES);
191 	mutex_unlock(&fi->inmem_lock);
192 
193 	trace_f2fs_register_inmem_page(page, INMEM);
194 }
195 
196 static int __revoke_inmem_pages(struct inode *inode,
197 				struct list_head *head, bool drop, bool recover)
198 {
199 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
200 	struct inmem_pages *cur, *tmp;
201 	int err = 0;
202 
203 	list_for_each_entry_safe(cur, tmp, head, list) {
204 		struct page *page = cur->page;
205 
206 		if (drop)
207 			trace_f2fs_commit_inmem_page(page, INMEM_DROP);
208 
209 		lock_page(page);
210 
211 		if (recover) {
212 			struct dnode_of_data dn;
213 			struct node_info ni;
214 
215 			trace_f2fs_commit_inmem_page(page, INMEM_REVOKE);
216 
217 			set_new_dnode(&dn, inode, NULL, NULL, 0);
218 			if (get_dnode_of_data(&dn, page->index, LOOKUP_NODE)) {
219 				err = -EAGAIN;
220 				goto next;
221 			}
222 			get_node_info(sbi, dn.nid, &ni);
223 			f2fs_replace_block(sbi, &dn, dn.data_blkaddr,
224 					cur->old_addr, ni.version, true, true);
225 			f2fs_put_dnode(&dn);
226 		}
227 next:
228 		/* we don't need to invalidate this in the sccessful status */
229 		if (drop || recover)
230 			ClearPageUptodate(page);
231 		set_page_private(page, 0);
232 		ClearPagePrivate(page);
233 		f2fs_put_page(page, 1);
234 
235 		list_del(&cur->list);
236 		kmem_cache_free(inmem_entry_slab, cur);
237 		dec_page_count(F2FS_I_SB(inode), F2FS_INMEM_PAGES);
238 	}
239 	return err;
240 }
241 
242 void drop_inmem_pages(struct inode *inode)
243 {
244 	struct f2fs_inode_info *fi = F2FS_I(inode);
245 
246 	mutex_lock(&fi->inmem_lock);
247 	__revoke_inmem_pages(inode, &fi->inmem_pages, true, false);
248 	mutex_unlock(&fi->inmem_lock);
249 
250 	clear_inode_flag(inode, FI_ATOMIC_FILE);
251 	stat_dec_atomic_write(inode);
252 }
253 
254 void drop_inmem_page(struct inode *inode, struct page *page)
255 {
256 	struct f2fs_inode_info *fi = F2FS_I(inode);
257 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
258 	struct list_head *head = &fi->inmem_pages;
259 	struct inmem_pages *cur = NULL;
260 
261 	f2fs_bug_on(sbi, !IS_ATOMIC_WRITTEN_PAGE(page));
262 
263 	mutex_lock(&fi->inmem_lock);
264 	list_for_each_entry(cur, head, list) {
265 		if (cur->page == page)
266 			break;
267 	}
268 
269 	f2fs_bug_on(sbi, !cur || cur->page != page);
270 	list_del(&cur->list);
271 	mutex_unlock(&fi->inmem_lock);
272 
273 	dec_page_count(sbi, F2FS_INMEM_PAGES);
274 	kmem_cache_free(inmem_entry_slab, cur);
275 
276 	ClearPageUptodate(page);
277 	set_page_private(page, 0);
278 	ClearPagePrivate(page);
279 	f2fs_put_page(page, 0);
280 
281 	trace_f2fs_commit_inmem_page(page, INMEM_INVALIDATE);
282 }
283 
284 static int __commit_inmem_pages(struct inode *inode,
285 					struct list_head *revoke_list)
286 {
287 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
288 	struct f2fs_inode_info *fi = F2FS_I(inode);
289 	struct inmem_pages *cur, *tmp;
290 	struct f2fs_io_info fio = {
291 		.sbi = sbi,
292 		.type = DATA,
293 		.op = REQ_OP_WRITE,
294 		.op_flags = REQ_SYNC | REQ_PRIO,
295 	};
296 	pgoff_t last_idx = ULONG_MAX;
297 	int err = 0;
298 
299 	list_for_each_entry_safe(cur, tmp, &fi->inmem_pages, list) {
300 		struct page *page = cur->page;
301 
302 		lock_page(page);
303 		if (page->mapping == inode->i_mapping) {
304 			trace_f2fs_commit_inmem_page(page, INMEM);
305 
306 			set_page_dirty(page);
307 			f2fs_wait_on_page_writeback(page, DATA, true);
308 			if (clear_page_dirty_for_io(page)) {
309 				inode_dec_dirty_pages(inode);
310 				remove_dirty_inode(inode);
311 			}
312 
313 			fio.page = page;
314 			fio.old_blkaddr = NULL_ADDR;
315 			fio.encrypted_page = NULL;
316 			fio.need_lock = LOCK_DONE;
317 			err = do_write_data_page(&fio);
318 			if (err) {
319 				unlock_page(page);
320 				break;
321 			}
322 
323 			/* record old blkaddr for revoking */
324 			cur->old_addr = fio.old_blkaddr;
325 			last_idx = page->index;
326 		}
327 		unlock_page(page);
328 		list_move_tail(&cur->list, revoke_list);
329 	}
330 
331 	if (last_idx != ULONG_MAX)
332 		f2fs_submit_merged_write_cond(sbi, inode, 0, last_idx, DATA);
333 
334 	if (!err)
335 		__revoke_inmem_pages(inode, revoke_list, false, false);
336 
337 	return err;
338 }
339 
340 int commit_inmem_pages(struct inode *inode)
341 {
342 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
343 	struct f2fs_inode_info *fi = F2FS_I(inode);
344 	struct list_head revoke_list;
345 	int err;
346 
347 	INIT_LIST_HEAD(&revoke_list);
348 	f2fs_balance_fs(sbi, true);
349 	f2fs_lock_op(sbi);
350 
351 	set_inode_flag(inode, FI_ATOMIC_COMMIT);
352 
353 	mutex_lock(&fi->inmem_lock);
354 	err = __commit_inmem_pages(inode, &revoke_list);
355 	if (err) {
356 		int ret;
357 		/*
358 		 * try to revoke all committed pages, but still we could fail
359 		 * due to no memory or other reason, if that happened, EAGAIN
360 		 * will be returned, which means in such case, transaction is
361 		 * already not integrity, caller should use journal to do the
362 		 * recovery or rewrite & commit last transaction. For other
363 		 * error number, revoking was done by filesystem itself.
364 		 */
365 		ret = __revoke_inmem_pages(inode, &revoke_list, false, true);
366 		if (ret)
367 			err = ret;
368 
369 		/* drop all uncommitted pages */
370 		__revoke_inmem_pages(inode, &fi->inmem_pages, true, false);
371 	}
372 	mutex_unlock(&fi->inmem_lock);
373 
374 	clear_inode_flag(inode, FI_ATOMIC_COMMIT);
375 
376 	f2fs_unlock_op(sbi);
377 	return err;
378 }
379 
380 /*
381  * This function balances dirty node and dentry pages.
382  * In addition, it controls garbage collection.
383  */
384 void f2fs_balance_fs(struct f2fs_sb_info *sbi, bool need)
385 {
386 #ifdef CONFIG_F2FS_FAULT_INJECTION
387 	if (time_to_inject(sbi, FAULT_CHECKPOINT)) {
388 		f2fs_show_injection_info(FAULT_CHECKPOINT);
389 		f2fs_stop_checkpoint(sbi, false);
390 	}
391 #endif
392 
393 	/* balance_fs_bg is able to be pending */
394 	if (need && excess_cached_nats(sbi))
395 		f2fs_balance_fs_bg(sbi);
396 
397 	/*
398 	 * We should do GC or end up with checkpoint, if there are so many dirty
399 	 * dir/node pages without enough free segments.
400 	 */
401 	if (has_not_enough_free_secs(sbi, 0, 0)) {
402 		mutex_lock(&sbi->gc_mutex);
403 		f2fs_gc(sbi, false, false, NULL_SEGNO);
404 	}
405 }
406 
407 void f2fs_balance_fs_bg(struct f2fs_sb_info *sbi)
408 {
409 	/* try to shrink extent cache when there is no enough memory */
410 	if (!available_free_memory(sbi, EXTENT_CACHE))
411 		f2fs_shrink_extent_tree(sbi, EXTENT_CACHE_SHRINK_NUMBER);
412 
413 	/* check the # of cached NAT entries */
414 	if (!available_free_memory(sbi, NAT_ENTRIES))
415 		try_to_free_nats(sbi, NAT_ENTRY_PER_BLOCK);
416 
417 	if (!available_free_memory(sbi, FREE_NIDS))
418 		try_to_free_nids(sbi, MAX_FREE_NIDS);
419 	else
420 		build_free_nids(sbi, false, false);
421 
422 	if (!is_idle(sbi) && !excess_dirty_nats(sbi))
423 		return;
424 
425 	/* checkpoint is the only way to shrink partial cached entries */
426 	if (!available_free_memory(sbi, NAT_ENTRIES) ||
427 			!available_free_memory(sbi, INO_ENTRIES) ||
428 			excess_prefree_segs(sbi) ||
429 			excess_dirty_nats(sbi) ||
430 			f2fs_time_over(sbi, CP_TIME)) {
431 		if (test_opt(sbi, DATA_FLUSH)) {
432 			struct blk_plug plug;
433 
434 			blk_start_plug(&plug);
435 			sync_dirty_inodes(sbi, FILE_INODE);
436 			blk_finish_plug(&plug);
437 		}
438 		f2fs_sync_fs(sbi->sb, true);
439 		stat_inc_bg_cp_count(sbi->stat_info);
440 	}
441 }
442 
443 static int __submit_flush_wait(struct f2fs_sb_info *sbi,
444 				struct block_device *bdev)
445 {
446 	struct bio *bio = f2fs_bio_alloc(0);
447 	int ret;
448 
449 	bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
450 	bio->bi_bdev = bdev;
451 	ret = submit_bio_wait(bio);
452 	bio_put(bio);
453 
454 	trace_f2fs_issue_flush(bdev, test_opt(sbi, NOBARRIER),
455 				test_opt(sbi, FLUSH_MERGE), ret);
456 	return ret;
457 }
458 
459 static int submit_flush_wait(struct f2fs_sb_info *sbi)
460 {
461 	int ret = __submit_flush_wait(sbi, sbi->sb->s_bdev);
462 	int i;
463 
464 	if (!sbi->s_ndevs || ret)
465 		return ret;
466 
467 	for (i = 1; i < sbi->s_ndevs; i++) {
468 		ret = __submit_flush_wait(sbi, FDEV(i).bdev);
469 		if (ret)
470 			break;
471 	}
472 	return ret;
473 }
474 
475 static int issue_flush_thread(void *data)
476 {
477 	struct f2fs_sb_info *sbi = data;
478 	struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
479 	wait_queue_head_t *q = &fcc->flush_wait_queue;
480 repeat:
481 	if (kthread_should_stop())
482 		return 0;
483 
484 	if (!llist_empty(&fcc->issue_list)) {
485 		struct flush_cmd *cmd, *next;
486 		int ret;
487 
488 		fcc->dispatch_list = llist_del_all(&fcc->issue_list);
489 		fcc->dispatch_list = llist_reverse_order(fcc->dispatch_list);
490 
491 		ret = submit_flush_wait(sbi);
492 		atomic_inc(&fcc->issued_flush);
493 
494 		llist_for_each_entry_safe(cmd, next,
495 					  fcc->dispatch_list, llnode) {
496 			cmd->ret = ret;
497 			complete(&cmd->wait);
498 		}
499 		fcc->dispatch_list = NULL;
500 	}
501 
502 	wait_event_interruptible(*q,
503 		kthread_should_stop() || !llist_empty(&fcc->issue_list));
504 	goto repeat;
505 }
506 
507 int f2fs_issue_flush(struct f2fs_sb_info *sbi)
508 {
509 	struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
510 	struct flush_cmd cmd;
511 	int ret;
512 
513 	if (test_opt(sbi, NOBARRIER))
514 		return 0;
515 
516 	if (!test_opt(sbi, FLUSH_MERGE)) {
517 		ret = submit_flush_wait(sbi);
518 		atomic_inc(&fcc->issued_flush);
519 		return ret;
520 	}
521 
522 	if (!atomic_read(&fcc->issing_flush)) {
523 		atomic_inc(&fcc->issing_flush);
524 		ret = submit_flush_wait(sbi);
525 		atomic_dec(&fcc->issing_flush);
526 
527 		atomic_inc(&fcc->issued_flush);
528 		return ret;
529 	}
530 
531 	init_completion(&cmd.wait);
532 
533 	atomic_inc(&fcc->issing_flush);
534 	llist_add(&cmd.llnode, &fcc->issue_list);
535 
536 	if (!fcc->dispatch_list)
537 		wake_up(&fcc->flush_wait_queue);
538 
539 	if (fcc->f2fs_issue_flush) {
540 		wait_for_completion(&cmd.wait);
541 		atomic_dec(&fcc->issing_flush);
542 	} else {
543 		llist_del_all(&fcc->issue_list);
544 		atomic_set(&fcc->issing_flush, 0);
545 	}
546 
547 	return cmd.ret;
548 }
549 
550 int create_flush_cmd_control(struct f2fs_sb_info *sbi)
551 {
552 	dev_t dev = sbi->sb->s_bdev->bd_dev;
553 	struct flush_cmd_control *fcc;
554 	int err = 0;
555 
556 	if (SM_I(sbi)->fcc_info) {
557 		fcc = SM_I(sbi)->fcc_info;
558 		if (fcc->f2fs_issue_flush)
559 			return err;
560 		goto init_thread;
561 	}
562 
563 	fcc = kzalloc(sizeof(struct flush_cmd_control), GFP_KERNEL);
564 	if (!fcc)
565 		return -ENOMEM;
566 	atomic_set(&fcc->issued_flush, 0);
567 	atomic_set(&fcc->issing_flush, 0);
568 	init_waitqueue_head(&fcc->flush_wait_queue);
569 	init_llist_head(&fcc->issue_list);
570 	SM_I(sbi)->fcc_info = fcc;
571 	if (!test_opt(sbi, FLUSH_MERGE))
572 		return err;
573 
574 init_thread:
575 	fcc->f2fs_issue_flush = kthread_run(issue_flush_thread, sbi,
576 				"f2fs_flush-%u:%u", MAJOR(dev), MINOR(dev));
577 	if (IS_ERR(fcc->f2fs_issue_flush)) {
578 		err = PTR_ERR(fcc->f2fs_issue_flush);
579 		kfree(fcc);
580 		SM_I(sbi)->fcc_info = NULL;
581 		return err;
582 	}
583 
584 	return err;
585 }
586 
587 void destroy_flush_cmd_control(struct f2fs_sb_info *sbi, bool free)
588 {
589 	struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
590 
591 	if (fcc && fcc->f2fs_issue_flush) {
592 		struct task_struct *flush_thread = fcc->f2fs_issue_flush;
593 
594 		fcc->f2fs_issue_flush = NULL;
595 		kthread_stop(flush_thread);
596 	}
597 	if (free) {
598 		kfree(fcc);
599 		SM_I(sbi)->fcc_info = NULL;
600 	}
601 }
602 
603 static void __locate_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno,
604 		enum dirty_type dirty_type)
605 {
606 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
607 
608 	/* need not be added */
609 	if (IS_CURSEG(sbi, segno))
610 		return;
611 
612 	if (!test_and_set_bit(segno, dirty_i->dirty_segmap[dirty_type]))
613 		dirty_i->nr_dirty[dirty_type]++;
614 
615 	if (dirty_type == DIRTY) {
616 		struct seg_entry *sentry = get_seg_entry(sbi, segno);
617 		enum dirty_type t = sentry->type;
618 
619 		if (unlikely(t >= DIRTY)) {
620 			f2fs_bug_on(sbi, 1);
621 			return;
622 		}
623 		if (!test_and_set_bit(segno, dirty_i->dirty_segmap[t]))
624 			dirty_i->nr_dirty[t]++;
625 	}
626 }
627 
628 static void __remove_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno,
629 		enum dirty_type dirty_type)
630 {
631 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
632 
633 	if (test_and_clear_bit(segno, dirty_i->dirty_segmap[dirty_type]))
634 		dirty_i->nr_dirty[dirty_type]--;
635 
636 	if (dirty_type == DIRTY) {
637 		struct seg_entry *sentry = get_seg_entry(sbi, segno);
638 		enum dirty_type t = sentry->type;
639 
640 		if (test_and_clear_bit(segno, dirty_i->dirty_segmap[t]))
641 			dirty_i->nr_dirty[t]--;
642 
643 		if (get_valid_blocks(sbi, segno, true) == 0)
644 			clear_bit(GET_SEC_FROM_SEG(sbi, segno),
645 						dirty_i->victim_secmap);
646 	}
647 }
648 
649 /*
650  * Should not occur error such as -ENOMEM.
651  * Adding dirty entry into seglist is not critical operation.
652  * If a given segment is one of current working segments, it won't be added.
653  */
654 static void locate_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno)
655 {
656 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
657 	unsigned short valid_blocks;
658 
659 	if (segno == NULL_SEGNO || IS_CURSEG(sbi, segno))
660 		return;
661 
662 	mutex_lock(&dirty_i->seglist_lock);
663 
664 	valid_blocks = get_valid_blocks(sbi, segno, false);
665 
666 	if (valid_blocks == 0) {
667 		__locate_dirty_segment(sbi, segno, PRE);
668 		__remove_dirty_segment(sbi, segno, DIRTY);
669 	} else if (valid_blocks < sbi->blocks_per_seg) {
670 		__locate_dirty_segment(sbi, segno, DIRTY);
671 	} else {
672 		/* Recovery routine with SSR needs this */
673 		__remove_dirty_segment(sbi, segno, DIRTY);
674 	}
675 
676 	mutex_unlock(&dirty_i->seglist_lock);
677 }
678 
679 static struct discard_cmd *__create_discard_cmd(struct f2fs_sb_info *sbi,
680 		struct block_device *bdev, block_t lstart,
681 		block_t start, block_t len)
682 {
683 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
684 	struct list_head *pend_list;
685 	struct discard_cmd *dc;
686 
687 	f2fs_bug_on(sbi, !len);
688 
689 	pend_list = &dcc->pend_list[plist_idx(len)];
690 
691 	dc = f2fs_kmem_cache_alloc(discard_cmd_slab, GFP_NOFS);
692 	INIT_LIST_HEAD(&dc->list);
693 	dc->bdev = bdev;
694 	dc->lstart = lstart;
695 	dc->start = start;
696 	dc->len = len;
697 	dc->ref = 0;
698 	dc->state = D_PREP;
699 	dc->error = 0;
700 	init_completion(&dc->wait);
701 	list_add_tail(&dc->list, pend_list);
702 	atomic_inc(&dcc->discard_cmd_cnt);
703 	dcc->undiscard_blks += len;
704 
705 	return dc;
706 }
707 
708 static struct discard_cmd *__attach_discard_cmd(struct f2fs_sb_info *sbi,
709 				struct block_device *bdev, block_t lstart,
710 				block_t start, block_t len,
711 				struct rb_node *parent, struct rb_node **p)
712 {
713 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
714 	struct discard_cmd *dc;
715 
716 	dc = __create_discard_cmd(sbi, bdev, lstart, start, len);
717 
718 	rb_link_node(&dc->rb_node, parent, p);
719 	rb_insert_color(&dc->rb_node, &dcc->root);
720 
721 	return dc;
722 }
723 
724 static void __detach_discard_cmd(struct discard_cmd_control *dcc,
725 							struct discard_cmd *dc)
726 {
727 	if (dc->state == D_DONE)
728 		atomic_dec(&dcc->issing_discard);
729 
730 	list_del(&dc->list);
731 	rb_erase(&dc->rb_node, &dcc->root);
732 	dcc->undiscard_blks -= dc->len;
733 
734 	kmem_cache_free(discard_cmd_slab, dc);
735 
736 	atomic_dec(&dcc->discard_cmd_cnt);
737 }
738 
739 static void __remove_discard_cmd(struct f2fs_sb_info *sbi,
740 							struct discard_cmd *dc)
741 {
742 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
743 
744 	f2fs_bug_on(sbi, dc->ref);
745 
746 	if (dc->error == -EOPNOTSUPP)
747 		dc->error = 0;
748 
749 	if (dc->error)
750 		f2fs_msg(sbi->sb, KERN_INFO,
751 			"Issue discard(%u, %u, %u) failed, ret: %d",
752 			dc->lstart, dc->start, dc->len, dc->error);
753 	__detach_discard_cmd(dcc, dc);
754 }
755 
756 static void f2fs_submit_discard_endio(struct bio *bio)
757 {
758 	struct discard_cmd *dc = (struct discard_cmd *)bio->bi_private;
759 
760 	dc->error = blk_status_to_errno(bio->bi_status);
761 	dc->state = D_DONE;
762 	complete_all(&dc->wait);
763 	bio_put(bio);
764 }
765 
766 void __check_sit_bitmap(struct f2fs_sb_info *sbi,
767 				block_t start, block_t end)
768 {
769 #ifdef CONFIG_F2FS_CHECK_FS
770 	struct seg_entry *sentry;
771 	unsigned int segno;
772 	block_t blk = start;
773 	unsigned long offset, size, max_blocks = sbi->blocks_per_seg;
774 	unsigned long *map;
775 
776 	while (blk < end) {
777 		segno = GET_SEGNO(sbi, blk);
778 		sentry = get_seg_entry(sbi, segno);
779 		offset = GET_BLKOFF_FROM_SEG0(sbi, blk);
780 
781 		size = min((unsigned long)(end - blk), max_blocks);
782 		map = (unsigned long *)(sentry->cur_valid_map);
783 		offset = __find_rev_next_bit(map, size, offset);
784 		f2fs_bug_on(sbi, offset != size);
785 		blk += size;
786 	}
787 #endif
788 }
789 
790 /* this function is copied from blkdev_issue_discard from block/blk-lib.c */
791 static void __submit_discard_cmd(struct f2fs_sb_info *sbi,
792 				struct discard_cmd *dc)
793 {
794 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
795 	struct bio *bio = NULL;
796 
797 	if (dc->state != D_PREP)
798 		return;
799 
800 	trace_f2fs_issue_discard(dc->bdev, dc->start, dc->len);
801 
802 	dc->error = __blkdev_issue_discard(dc->bdev,
803 				SECTOR_FROM_BLOCK(dc->start),
804 				SECTOR_FROM_BLOCK(dc->len),
805 				GFP_NOFS, 0, &bio);
806 	if (!dc->error) {
807 		/* should keep before submission to avoid D_DONE right away */
808 		dc->state = D_SUBMIT;
809 		atomic_inc(&dcc->issued_discard);
810 		atomic_inc(&dcc->issing_discard);
811 		if (bio) {
812 			bio->bi_private = dc;
813 			bio->bi_end_io = f2fs_submit_discard_endio;
814 			bio->bi_opf |= REQ_SYNC;
815 			submit_bio(bio);
816 			list_move_tail(&dc->list, &dcc->wait_list);
817 			__check_sit_bitmap(sbi, dc->start, dc->start + dc->len);
818 		}
819 	} else {
820 		__remove_discard_cmd(sbi, dc);
821 	}
822 }
823 
824 static struct discard_cmd *__insert_discard_tree(struct f2fs_sb_info *sbi,
825 				struct block_device *bdev, block_t lstart,
826 				block_t start, block_t len,
827 				struct rb_node **insert_p,
828 				struct rb_node *insert_parent)
829 {
830 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
831 	struct rb_node **p = &dcc->root.rb_node;
832 	struct rb_node *parent = NULL;
833 	struct discard_cmd *dc = NULL;
834 
835 	if (insert_p && insert_parent) {
836 		parent = insert_parent;
837 		p = insert_p;
838 		goto do_insert;
839 	}
840 
841 	p = __lookup_rb_tree_for_insert(sbi, &dcc->root, &parent, lstart);
842 do_insert:
843 	dc = __attach_discard_cmd(sbi, bdev, lstart, start, len, parent, p);
844 	if (!dc)
845 		return NULL;
846 
847 	return dc;
848 }
849 
850 static void __relocate_discard_cmd(struct discard_cmd_control *dcc,
851 						struct discard_cmd *dc)
852 {
853 	list_move_tail(&dc->list, &dcc->pend_list[plist_idx(dc->len)]);
854 }
855 
856 static void __punch_discard_cmd(struct f2fs_sb_info *sbi,
857 				struct discard_cmd *dc, block_t blkaddr)
858 {
859 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
860 	struct discard_info di = dc->di;
861 	bool modified = false;
862 
863 	if (dc->state == D_DONE || dc->len == 1) {
864 		__remove_discard_cmd(sbi, dc);
865 		return;
866 	}
867 
868 	dcc->undiscard_blks -= di.len;
869 
870 	if (blkaddr > di.lstart) {
871 		dc->len = blkaddr - dc->lstart;
872 		dcc->undiscard_blks += dc->len;
873 		__relocate_discard_cmd(dcc, dc);
874 		modified = true;
875 	}
876 
877 	if (blkaddr < di.lstart + di.len - 1) {
878 		if (modified) {
879 			__insert_discard_tree(sbi, dc->bdev, blkaddr + 1,
880 					di.start + blkaddr + 1 - di.lstart,
881 					di.lstart + di.len - 1 - blkaddr,
882 					NULL, NULL);
883 		} else {
884 			dc->lstart++;
885 			dc->len--;
886 			dc->start++;
887 			dcc->undiscard_blks += dc->len;
888 			__relocate_discard_cmd(dcc, dc);
889 		}
890 	}
891 }
892 
893 static void __update_discard_tree_range(struct f2fs_sb_info *sbi,
894 				struct block_device *bdev, block_t lstart,
895 				block_t start, block_t len)
896 {
897 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
898 	struct discard_cmd *prev_dc = NULL, *next_dc = NULL;
899 	struct discard_cmd *dc;
900 	struct discard_info di = {0};
901 	struct rb_node **insert_p = NULL, *insert_parent = NULL;
902 	block_t end = lstart + len;
903 
904 	mutex_lock(&dcc->cmd_lock);
905 
906 	dc = (struct discard_cmd *)__lookup_rb_tree_ret(&dcc->root,
907 					NULL, lstart,
908 					(struct rb_entry **)&prev_dc,
909 					(struct rb_entry **)&next_dc,
910 					&insert_p, &insert_parent, true);
911 	if (dc)
912 		prev_dc = dc;
913 
914 	if (!prev_dc) {
915 		di.lstart = lstart;
916 		di.len = next_dc ? next_dc->lstart - lstart : len;
917 		di.len = min(di.len, len);
918 		di.start = start;
919 	}
920 
921 	while (1) {
922 		struct rb_node *node;
923 		bool merged = false;
924 		struct discard_cmd *tdc = NULL;
925 
926 		if (prev_dc) {
927 			di.lstart = prev_dc->lstart + prev_dc->len;
928 			if (di.lstart < lstart)
929 				di.lstart = lstart;
930 			if (di.lstart >= end)
931 				break;
932 
933 			if (!next_dc || next_dc->lstart > end)
934 				di.len = end - di.lstart;
935 			else
936 				di.len = next_dc->lstart - di.lstart;
937 			di.start = start + di.lstart - lstart;
938 		}
939 
940 		if (!di.len)
941 			goto next;
942 
943 		if (prev_dc && prev_dc->state == D_PREP &&
944 			prev_dc->bdev == bdev &&
945 			__is_discard_back_mergeable(&di, &prev_dc->di)) {
946 			prev_dc->di.len += di.len;
947 			dcc->undiscard_blks += di.len;
948 			__relocate_discard_cmd(dcc, prev_dc);
949 			di = prev_dc->di;
950 			tdc = prev_dc;
951 			merged = true;
952 		}
953 
954 		if (next_dc && next_dc->state == D_PREP &&
955 			next_dc->bdev == bdev &&
956 			__is_discard_front_mergeable(&di, &next_dc->di)) {
957 			next_dc->di.lstart = di.lstart;
958 			next_dc->di.len += di.len;
959 			next_dc->di.start = di.start;
960 			dcc->undiscard_blks += di.len;
961 			__relocate_discard_cmd(dcc, next_dc);
962 			if (tdc)
963 				__remove_discard_cmd(sbi, tdc);
964 			merged = true;
965 		}
966 
967 		if (!merged) {
968 			__insert_discard_tree(sbi, bdev, di.lstart, di.start,
969 							di.len, NULL, NULL);
970 		}
971  next:
972 		prev_dc = next_dc;
973 		if (!prev_dc)
974 			break;
975 
976 		node = rb_next(&prev_dc->rb_node);
977 		next_dc = rb_entry_safe(node, struct discard_cmd, rb_node);
978 	}
979 
980 	mutex_unlock(&dcc->cmd_lock);
981 }
982 
983 static int __queue_discard_cmd(struct f2fs_sb_info *sbi,
984 		struct block_device *bdev, block_t blkstart, block_t blklen)
985 {
986 	block_t lblkstart = blkstart;
987 
988 	trace_f2fs_queue_discard(bdev, blkstart, blklen);
989 
990 	if (sbi->s_ndevs) {
991 		int devi = f2fs_target_device_index(sbi, blkstart);
992 
993 		blkstart -= FDEV(devi).start_blk;
994 	}
995 	__update_discard_tree_range(sbi, bdev, lblkstart, blkstart, blklen);
996 	return 0;
997 }
998 
999 static void __issue_discard_cmd(struct f2fs_sb_info *sbi, bool issue_cond)
1000 {
1001 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1002 	struct list_head *pend_list;
1003 	struct discard_cmd *dc, *tmp;
1004 	struct blk_plug plug;
1005 	int i, iter = 0;
1006 
1007 	mutex_lock(&dcc->cmd_lock);
1008 	f2fs_bug_on(sbi,
1009 		!__check_rb_tree_consistence(sbi, &dcc->root));
1010 	blk_start_plug(&plug);
1011 	for (i = MAX_PLIST_NUM - 1; i >= 0; i--) {
1012 		pend_list = &dcc->pend_list[i];
1013 		list_for_each_entry_safe(dc, tmp, pend_list, list) {
1014 			f2fs_bug_on(sbi, dc->state != D_PREP);
1015 
1016 			if (!issue_cond || is_idle(sbi))
1017 				__submit_discard_cmd(sbi, dc);
1018 			if (issue_cond && iter++ > DISCARD_ISSUE_RATE)
1019 				goto out;
1020 		}
1021 	}
1022 out:
1023 	blk_finish_plug(&plug);
1024 	mutex_unlock(&dcc->cmd_lock);
1025 }
1026 
1027 static void __wait_one_discard_bio(struct f2fs_sb_info *sbi,
1028 							struct discard_cmd *dc)
1029 {
1030 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1031 
1032 	wait_for_completion_io(&dc->wait);
1033 	mutex_lock(&dcc->cmd_lock);
1034 	f2fs_bug_on(sbi, dc->state != D_DONE);
1035 	dc->ref--;
1036 	if (!dc->ref)
1037 		__remove_discard_cmd(sbi, dc);
1038 	mutex_unlock(&dcc->cmd_lock);
1039 }
1040 
1041 static void __wait_discard_cmd(struct f2fs_sb_info *sbi, bool wait_cond)
1042 {
1043 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1044 	struct list_head *wait_list = &(dcc->wait_list);
1045 	struct discard_cmd *dc, *tmp;
1046 	bool need_wait;
1047 
1048 next:
1049 	need_wait = false;
1050 
1051 	mutex_lock(&dcc->cmd_lock);
1052 	list_for_each_entry_safe(dc, tmp, wait_list, list) {
1053 		if (!wait_cond || (dc->state == D_DONE && !dc->ref)) {
1054 			wait_for_completion_io(&dc->wait);
1055 			__remove_discard_cmd(sbi, dc);
1056 		} else {
1057 			dc->ref++;
1058 			need_wait = true;
1059 			break;
1060 		}
1061 	}
1062 	mutex_unlock(&dcc->cmd_lock);
1063 
1064 	if (need_wait) {
1065 		__wait_one_discard_bio(sbi, dc);
1066 		goto next;
1067 	}
1068 }
1069 
1070 /* This should be covered by global mutex, &sit_i->sentry_lock */
1071 void f2fs_wait_discard_bio(struct f2fs_sb_info *sbi, block_t blkaddr)
1072 {
1073 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1074 	struct discard_cmd *dc;
1075 	bool need_wait = false;
1076 
1077 	mutex_lock(&dcc->cmd_lock);
1078 	dc = (struct discard_cmd *)__lookup_rb_tree(&dcc->root, NULL, blkaddr);
1079 	if (dc) {
1080 		if (dc->state == D_PREP) {
1081 			__punch_discard_cmd(sbi, dc, blkaddr);
1082 		} else {
1083 			dc->ref++;
1084 			need_wait = true;
1085 		}
1086 	}
1087 	mutex_unlock(&dcc->cmd_lock);
1088 
1089 	if (need_wait)
1090 		__wait_one_discard_bio(sbi, dc);
1091 }
1092 
1093 void stop_discard_thread(struct f2fs_sb_info *sbi)
1094 {
1095 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1096 
1097 	if (dcc && dcc->f2fs_issue_discard) {
1098 		struct task_struct *discard_thread = dcc->f2fs_issue_discard;
1099 
1100 		dcc->f2fs_issue_discard = NULL;
1101 		kthread_stop(discard_thread);
1102 	}
1103 }
1104 
1105 /* This comes from f2fs_put_super */
1106 void f2fs_wait_discard_bios(struct f2fs_sb_info *sbi)
1107 {
1108 	__issue_discard_cmd(sbi, false);
1109 	__wait_discard_cmd(sbi, false);
1110 }
1111 
1112 static int issue_discard_thread(void *data)
1113 {
1114 	struct f2fs_sb_info *sbi = data;
1115 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1116 	wait_queue_head_t *q = &dcc->discard_wait_queue;
1117 
1118 	set_freezable();
1119 
1120 	do {
1121 		wait_event_interruptible(*q, kthread_should_stop() ||
1122 					freezing(current) ||
1123 					atomic_read(&dcc->discard_cmd_cnt));
1124 		if (try_to_freeze())
1125 			continue;
1126 		if (kthread_should_stop())
1127 			return 0;
1128 
1129 		__issue_discard_cmd(sbi, true);
1130 		__wait_discard_cmd(sbi, true);
1131 
1132 		congestion_wait(BLK_RW_SYNC, HZ/50);
1133 	} while (!kthread_should_stop());
1134 	return 0;
1135 }
1136 
1137 #ifdef CONFIG_BLK_DEV_ZONED
1138 static int __f2fs_issue_discard_zone(struct f2fs_sb_info *sbi,
1139 		struct block_device *bdev, block_t blkstart, block_t blklen)
1140 {
1141 	sector_t sector, nr_sects;
1142 	block_t lblkstart = blkstart;
1143 	int devi = 0;
1144 
1145 	if (sbi->s_ndevs) {
1146 		devi = f2fs_target_device_index(sbi, blkstart);
1147 		blkstart -= FDEV(devi).start_blk;
1148 	}
1149 
1150 	/*
1151 	 * We need to know the type of the zone: for conventional zones,
1152 	 * use regular discard if the drive supports it. For sequential
1153 	 * zones, reset the zone write pointer.
1154 	 */
1155 	switch (get_blkz_type(sbi, bdev, blkstart)) {
1156 
1157 	case BLK_ZONE_TYPE_CONVENTIONAL:
1158 		if (!blk_queue_discard(bdev_get_queue(bdev)))
1159 			return 0;
1160 		return __queue_discard_cmd(sbi, bdev, lblkstart, blklen);
1161 	case BLK_ZONE_TYPE_SEQWRITE_REQ:
1162 	case BLK_ZONE_TYPE_SEQWRITE_PREF:
1163 		sector = SECTOR_FROM_BLOCK(blkstart);
1164 		nr_sects = SECTOR_FROM_BLOCK(blklen);
1165 
1166 		if (sector & (bdev_zone_sectors(bdev) - 1) ||
1167 				nr_sects != bdev_zone_sectors(bdev)) {
1168 			f2fs_msg(sbi->sb, KERN_INFO,
1169 				"(%d) %s: Unaligned discard attempted (block %x + %x)",
1170 				devi, sbi->s_ndevs ? FDEV(devi).path: "",
1171 				blkstart, blklen);
1172 			return -EIO;
1173 		}
1174 		trace_f2fs_issue_reset_zone(bdev, blkstart);
1175 		return blkdev_reset_zones(bdev, sector,
1176 					  nr_sects, GFP_NOFS);
1177 	default:
1178 		/* Unknown zone type: broken device ? */
1179 		return -EIO;
1180 	}
1181 }
1182 #endif
1183 
1184 static int __issue_discard_async(struct f2fs_sb_info *sbi,
1185 		struct block_device *bdev, block_t blkstart, block_t blklen)
1186 {
1187 #ifdef CONFIG_BLK_DEV_ZONED
1188 	if (f2fs_sb_mounted_blkzoned(sbi->sb) &&
1189 				bdev_zoned_model(bdev) != BLK_ZONED_NONE)
1190 		return __f2fs_issue_discard_zone(sbi, bdev, blkstart, blklen);
1191 #endif
1192 	return __queue_discard_cmd(sbi, bdev, blkstart, blklen);
1193 }
1194 
1195 static int f2fs_issue_discard(struct f2fs_sb_info *sbi,
1196 				block_t blkstart, block_t blklen)
1197 {
1198 	sector_t start = blkstart, len = 0;
1199 	struct block_device *bdev;
1200 	struct seg_entry *se;
1201 	unsigned int offset;
1202 	block_t i;
1203 	int err = 0;
1204 
1205 	bdev = f2fs_target_device(sbi, blkstart, NULL);
1206 
1207 	for (i = blkstart; i < blkstart + blklen; i++, len++) {
1208 		if (i != start) {
1209 			struct block_device *bdev2 =
1210 				f2fs_target_device(sbi, i, NULL);
1211 
1212 			if (bdev2 != bdev) {
1213 				err = __issue_discard_async(sbi, bdev,
1214 						start, len);
1215 				if (err)
1216 					return err;
1217 				bdev = bdev2;
1218 				start = i;
1219 				len = 0;
1220 			}
1221 		}
1222 
1223 		se = get_seg_entry(sbi, GET_SEGNO(sbi, i));
1224 		offset = GET_BLKOFF_FROM_SEG0(sbi, i);
1225 
1226 		if (!f2fs_test_and_set_bit(offset, se->discard_map))
1227 			sbi->discard_blks--;
1228 	}
1229 
1230 	if (len)
1231 		err = __issue_discard_async(sbi, bdev, start, len);
1232 	return err;
1233 }
1234 
1235 static bool add_discard_addrs(struct f2fs_sb_info *sbi, struct cp_control *cpc,
1236 							bool check_only)
1237 {
1238 	int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
1239 	int max_blocks = sbi->blocks_per_seg;
1240 	struct seg_entry *se = get_seg_entry(sbi, cpc->trim_start);
1241 	unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
1242 	unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
1243 	unsigned long *discard_map = (unsigned long *)se->discard_map;
1244 	unsigned long *dmap = SIT_I(sbi)->tmp_map;
1245 	unsigned int start = 0, end = -1;
1246 	bool force = (cpc->reason & CP_DISCARD);
1247 	struct discard_entry *de = NULL;
1248 	struct list_head *head = &SM_I(sbi)->dcc_info->entry_list;
1249 	int i;
1250 
1251 	if (se->valid_blocks == max_blocks || !f2fs_discard_en(sbi))
1252 		return false;
1253 
1254 	if (!force) {
1255 		if (!test_opt(sbi, DISCARD) || !se->valid_blocks ||
1256 			SM_I(sbi)->dcc_info->nr_discards >=
1257 				SM_I(sbi)->dcc_info->max_discards)
1258 			return false;
1259 	}
1260 
1261 	/* SIT_VBLOCK_MAP_SIZE should be multiple of sizeof(unsigned long) */
1262 	for (i = 0; i < entries; i++)
1263 		dmap[i] = force ? ~ckpt_map[i] & ~discard_map[i] :
1264 				(cur_map[i] ^ ckpt_map[i]) & ckpt_map[i];
1265 
1266 	while (force || SM_I(sbi)->dcc_info->nr_discards <=
1267 				SM_I(sbi)->dcc_info->max_discards) {
1268 		start = __find_rev_next_bit(dmap, max_blocks, end + 1);
1269 		if (start >= max_blocks)
1270 			break;
1271 
1272 		end = __find_rev_next_zero_bit(dmap, max_blocks, start + 1);
1273 		if (force && start && end != max_blocks
1274 					&& (end - start) < cpc->trim_minlen)
1275 			continue;
1276 
1277 		if (check_only)
1278 			return true;
1279 
1280 		if (!de) {
1281 			de = f2fs_kmem_cache_alloc(discard_entry_slab,
1282 								GFP_F2FS_ZERO);
1283 			de->start_blkaddr = START_BLOCK(sbi, cpc->trim_start);
1284 			list_add_tail(&de->list, head);
1285 		}
1286 
1287 		for (i = start; i < end; i++)
1288 			__set_bit_le(i, (void *)de->discard_map);
1289 
1290 		SM_I(sbi)->dcc_info->nr_discards += end - start;
1291 	}
1292 	return false;
1293 }
1294 
1295 void release_discard_addrs(struct f2fs_sb_info *sbi)
1296 {
1297 	struct list_head *head = &(SM_I(sbi)->dcc_info->entry_list);
1298 	struct discard_entry *entry, *this;
1299 
1300 	/* drop caches */
1301 	list_for_each_entry_safe(entry, this, head, list) {
1302 		list_del(&entry->list);
1303 		kmem_cache_free(discard_entry_slab, entry);
1304 	}
1305 }
1306 
1307 /*
1308  * Should call clear_prefree_segments after checkpoint is done.
1309  */
1310 static void set_prefree_as_free_segments(struct f2fs_sb_info *sbi)
1311 {
1312 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
1313 	unsigned int segno;
1314 
1315 	mutex_lock(&dirty_i->seglist_lock);
1316 	for_each_set_bit(segno, dirty_i->dirty_segmap[PRE], MAIN_SEGS(sbi))
1317 		__set_test_and_free(sbi, segno);
1318 	mutex_unlock(&dirty_i->seglist_lock);
1319 }
1320 
1321 void clear_prefree_segments(struct f2fs_sb_info *sbi, struct cp_control *cpc)
1322 {
1323 	struct list_head *head = &(SM_I(sbi)->dcc_info->entry_list);
1324 	struct discard_entry *entry, *this;
1325 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
1326 	unsigned long *prefree_map = dirty_i->dirty_segmap[PRE];
1327 	unsigned int start = 0, end = -1;
1328 	unsigned int secno, start_segno;
1329 	bool force = (cpc->reason & CP_DISCARD);
1330 
1331 	mutex_lock(&dirty_i->seglist_lock);
1332 
1333 	while (1) {
1334 		int i;
1335 		start = find_next_bit(prefree_map, MAIN_SEGS(sbi), end + 1);
1336 		if (start >= MAIN_SEGS(sbi))
1337 			break;
1338 		end = find_next_zero_bit(prefree_map, MAIN_SEGS(sbi),
1339 								start + 1);
1340 
1341 		for (i = start; i < end; i++)
1342 			clear_bit(i, prefree_map);
1343 
1344 		dirty_i->nr_dirty[PRE] -= end - start;
1345 
1346 		if (!test_opt(sbi, DISCARD))
1347 			continue;
1348 
1349 		if (force && start >= cpc->trim_start &&
1350 					(end - 1) <= cpc->trim_end)
1351 				continue;
1352 
1353 		if (!test_opt(sbi, LFS) || sbi->segs_per_sec == 1) {
1354 			f2fs_issue_discard(sbi, START_BLOCK(sbi, start),
1355 				(end - start) << sbi->log_blocks_per_seg);
1356 			continue;
1357 		}
1358 next:
1359 		secno = GET_SEC_FROM_SEG(sbi, start);
1360 		start_segno = GET_SEG_FROM_SEC(sbi, secno);
1361 		if (!IS_CURSEC(sbi, secno) &&
1362 			!get_valid_blocks(sbi, start, true))
1363 			f2fs_issue_discard(sbi, START_BLOCK(sbi, start_segno),
1364 				sbi->segs_per_sec << sbi->log_blocks_per_seg);
1365 
1366 		start = start_segno + sbi->segs_per_sec;
1367 		if (start < end)
1368 			goto next;
1369 		else
1370 			end = start - 1;
1371 	}
1372 	mutex_unlock(&dirty_i->seglist_lock);
1373 
1374 	/* send small discards */
1375 	list_for_each_entry_safe(entry, this, head, list) {
1376 		unsigned int cur_pos = 0, next_pos, len, total_len = 0;
1377 		bool is_valid = test_bit_le(0, entry->discard_map);
1378 
1379 find_next:
1380 		if (is_valid) {
1381 			next_pos = find_next_zero_bit_le(entry->discard_map,
1382 					sbi->blocks_per_seg, cur_pos);
1383 			len = next_pos - cur_pos;
1384 
1385 			if (f2fs_sb_mounted_blkzoned(sbi->sb) ||
1386 			    (force && len < cpc->trim_minlen))
1387 				goto skip;
1388 
1389 			f2fs_issue_discard(sbi, entry->start_blkaddr + cur_pos,
1390 									len);
1391 			cpc->trimmed += len;
1392 			total_len += len;
1393 		} else {
1394 			next_pos = find_next_bit_le(entry->discard_map,
1395 					sbi->blocks_per_seg, cur_pos);
1396 		}
1397 skip:
1398 		cur_pos = next_pos;
1399 		is_valid = !is_valid;
1400 
1401 		if (cur_pos < sbi->blocks_per_seg)
1402 			goto find_next;
1403 
1404 		list_del(&entry->list);
1405 		SM_I(sbi)->dcc_info->nr_discards -= total_len;
1406 		kmem_cache_free(discard_entry_slab, entry);
1407 	}
1408 
1409 	wake_up(&SM_I(sbi)->dcc_info->discard_wait_queue);
1410 }
1411 
1412 static int create_discard_cmd_control(struct f2fs_sb_info *sbi)
1413 {
1414 	dev_t dev = sbi->sb->s_bdev->bd_dev;
1415 	struct discard_cmd_control *dcc;
1416 	int err = 0, i;
1417 
1418 	if (SM_I(sbi)->dcc_info) {
1419 		dcc = SM_I(sbi)->dcc_info;
1420 		goto init_thread;
1421 	}
1422 
1423 	dcc = kzalloc(sizeof(struct discard_cmd_control), GFP_KERNEL);
1424 	if (!dcc)
1425 		return -ENOMEM;
1426 
1427 	INIT_LIST_HEAD(&dcc->entry_list);
1428 	for (i = 0; i < MAX_PLIST_NUM; i++)
1429 		INIT_LIST_HEAD(&dcc->pend_list[i]);
1430 	INIT_LIST_HEAD(&dcc->wait_list);
1431 	mutex_init(&dcc->cmd_lock);
1432 	atomic_set(&dcc->issued_discard, 0);
1433 	atomic_set(&dcc->issing_discard, 0);
1434 	atomic_set(&dcc->discard_cmd_cnt, 0);
1435 	dcc->nr_discards = 0;
1436 	dcc->max_discards = MAIN_SEGS(sbi) << sbi->log_blocks_per_seg;
1437 	dcc->undiscard_blks = 0;
1438 	dcc->root = RB_ROOT;
1439 
1440 	init_waitqueue_head(&dcc->discard_wait_queue);
1441 	SM_I(sbi)->dcc_info = dcc;
1442 init_thread:
1443 	dcc->f2fs_issue_discard = kthread_run(issue_discard_thread, sbi,
1444 				"f2fs_discard-%u:%u", MAJOR(dev), MINOR(dev));
1445 	if (IS_ERR(dcc->f2fs_issue_discard)) {
1446 		err = PTR_ERR(dcc->f2fs_issue_discard);
1447 		kfree(dcc);
1448 		SM_I(sbi)->dcc_info = NULL;
1449 		return err;
1450 	}
1451 
1452 	return err;
1453 }
1454 
1455 static void destroy_discard_cmd_control(struct f2fs_sb_info *sbi)
1456 {
1457 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1458 
1459 	if (!dcc)
1460 		return;
1461 
1462 	stop_discard_thread(sbi);
1463 
1464 	kfree(dcc);
1465 	SM_I(sbi)->dcc_info = NULL;
1466 }
1467 
1468 static bool __mark_sit_entry_dirty(struct f2fs_sb_info *sbi, unsigned int segno)
1469 {
1470 	struct sit_info *sit_i = SIT_I(sbi);
1471 
1472 	if (!__test_and_set_bit(segno, sit_i->dirty_sentries_bitmap)) {
1473 		sit_i->dirty_sentries++;
1474 		return false;
1475 	}
1476 
1477 	return true;
1478 }
1479 
1480 static void __set_sit_entry_type(struct f2fs_sb_info *sbi, int type,
1481 					unsigned int segno, int modified)
1482 {
1483 	struct seg_entry *se = get_seg_entry(sbi, segno);
1484 	se->type = type;
1485 	if (modified)
1486 		__mark_sit_entry_dirty(sbi, segno);
1487 }
1488 
1489 static void update_sit_entry(struct f2fs_sb_info *sbi, block_t blkaddr, int del)
1490 {
1491 	struct seg_entry *se;
1492 	unsigned int segno, offset;
1493 	long int new_vblocks;
1494 
1495 	segno = GET_SEGNO(sbi, blkaddr);
1496 
1497 	se = get_seg_entry(sbi, segno);
1498 	new_vblocks = se->valid_blocks + del;
1499 	offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
1500 
1501 	f2fs_bug_on(sbi, (new_vblocks >> (sizeof(unsigned short) << 3) ||
1502 				(new_vblocks > sbi->blocks_per_seg)));
1503 
1504 	se->valid_blocks = new_vblocks;
1505 	se->mtime = get_mtime(sbi);
1506 	SIT_I(sbi)->max_mtime = se->mtime;
1507 
1508 	/* Update valid block bitmap */
1509 	if (del > 0) {
1510 		if (f2fs_test_and_set_bit(offset, se->cur_valid_map)) {
1511 #ifdef CONFIG_F2FS_CHECK_FS
1512 			if (f2fs_test_and_set_bit(offset,
1513 						se->cur_valid_map_mir))
1514 				f2fs_bug_on(sbi, 1);
1515 			else
1516 				WARN_ON(1);
1517 #else
1518 			f2fs_bug_on(sbi, 1);
1519 #endif
1520 		}
1521 		if (f2fs_discard_en(sbi) &&
1522 			!f2fs_test_and_set_bit(offset, se->discard_map))
1523 			sbi->discard_blks--;
1524 
1525 		/* don't overwrite by SSR to keep node chain */
1526 		if (se->type == CURSEG_WARM_NODE) {
1527 			if (!f2fs_test_and_set_bit(offset, se->ckpt_valid_map))
1528 				se->ckpt_valid_blocks++;
1529 		}
1530 	} else {
1531 		if (!f2fs_test_and_clear_bit(offset, se->cur_valid_map)) {
1532 #ifdef CONFIG_F2FS_CHECK_FS
1533 			if (!f2fs_test_and_clear_bit(offset,
1534 						se->cur_valid_map_mir))
1535 				f2fs_bug_on(sbi, 1);
1536 			else
1537 				WARN_ON(1);
1538 #else
1539 			f2fs_bug_on(sbi, 1);
1540 #endif
1541 		}
1542 		if (f2fs_discard_en(sbi) &&
1543 			f2fs_test_and_clear_bit(offset, se->discard_map))
1544 			sbi->discard_blks++;
1545 	}
1546 	if (!f2fs_test_bit(offset, se->ckpt_valid_map))
1547 		se->ckpt_valid_blocks += del;
1548 
1549 	__mark_sit_entry_dirty(sbi, segno);
1550 
1551 	/* update total number of valid blocks to be written in ckpt area */
1552 	SIT_I(sbi)->written_valid_blocks += del;
1553 
1554 	if (sbi->segs_per_sec > 1)
1555 		get_sec_entry(sbi, segno)->valid_blocks += del;
1556 }
1557 
1558 void refresh_sit_entry(struct f2fs_sb_info *sbi, block_t old, block_t new)
1559 {
1560 	update_sit_entry(sbi, new, 1);
1561 	if (GET_SEGNO(sbi, old) != NULL_SEGNO)
1562 		update_sit_entry(sbi, old, -1);
1563 
1564 	locate_dirty_segment(sbi, GET_SEGNO(sbi, old));
1565 	locate_dirty_segment(sbi, GET_SEGNO(sbi, new));
1566 }
1567 
1568 void invalidate_blocks(struct f2fs_sb_info *sbi, block_t addr)
1569 {
1570 	unsigned int segno = GET_SEGNO(sbi, addr);
1571 	struct sit_info *sit_i = SIT_I(sbi);
1572 
1573 	f2fs_bug_on(sbi, addr == NULL_ADDR);
1574 	if (addr == NEW_ADDR)
1575 		return;
1576 
1577 	/* add it into sit main buffer */
1578 	mutex_lock(&sit_i->sentry_lock);
1579 
1580 	update_sit_entry(sbi, addr, -1);
1581 
1582 	/* add it into dirty seglist */
1583 	locate_dirty_segment(sbi, segno);
1584 
1585 	mutex_unlock(&sit_i->sentry_lock);
1586 }
1587 
1588 bool is_checkpointed_data(struct f2fs_sb_info *sbi, block_t blkaddr)
1589 {
1590 	struct sit_info *sit_i = SIT_I(sbi);
1591 	unsigned int segno, offset;
1592 	struct seg_entry *se;
1593 	bool is_cp = false;
1594 
1595 	if (blkaddr == NEW_ADDR || blkaddr == NULL_ADDR)
1596 		return true;
1597 
1598 	mutex_lock(&sit_i->sentry_lock);
1599 
1600 	segno = GET_SEGNO(sbi, blkaddr);
1601 	se = get_seg_entry(sbi, segno);
1602 	offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
1603 
1604 	if (f2fs_test_bit(offset, se->ckpt_valid_map))
1605 		is_cp = true;
1606 
1607 	mutex_unlock(&sit_i->sentry_lock);
1608 
1609 	return is_cp;
1610 }
1611 
1612 /*
1613  * This function should be resided under the curseg_mutex lock
1614  */
1615 static void __add_sum_entry(struct f2fs_sb_info *sbi, int type,
1616 					struct f2fs_summary *sum)
1617 {
1618 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1619 	void *addr = curseg->sum_blk;
1620 	addr += curseg->next_blkoff * sizeof(struct f2fs_summary);
1621 	memcpy(addr, sum, sizeof(struct f2fs_summary));
1622 }
1623 
1624 /*
1625  * Calculate the number of current summary pages for writing
1626  */
1627 int npages_for_summary_flush(struct f2fs_sb_info *sbi, bool for_ra)
1628 {
1629 	int valid_sum_count = 0;
1630 	int i, sum_in_page;
1631 
1632 	for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
1633 		if (sbi->ckpt->alloc_type[i] == SSR)
1634 			valid_sum_count += sbi->blocks_per_seg;
1635 		else {
1636 			if (for_ra)
1637 				valid_sum_count += le16_to_cpu(
1638 					F2FS_CKPT(sbi)->cur_data_blkoff[i]);
1639 			else
1640 				valid_sum_count += curseg_blkoff(sbi, i);
1641 		}
1642 	}
1643 
1644 	sum_in_page = (PAGE_SIZE - 2 * SUM_JOURNAL_SIZE -
1645 			SUM_FOOTER_SIZE) / SUMMARY_SIZE;
1646 	if (valid_sum_count <= sum_in_page)
1647 		return 1;
1648 	else if ((valid_sum_count - sum_in_page) <=
1649 		(PAGE_SIZE - SUM_FOOTER_SIZE) / SUMMARY_SIZE)
1650 		return 2;
1651 	return 3;
1652 }
1653 
1654 /*
1655  * Caller should put this summary page
1656  */
1657 struct page *get_sum_page(struct f2fs_sb_info *sbi, unsigned int segno)
1658 {
1659 	return get_meta_page(sbi, GET_SUM_BLOCK(sbi, segno));
1660 }
1661 
1662 void update_meta_page(struct f2fs_sb_info *sbi, void *src, block_t blk_addr)
1663 {
1664 	struct page *page = grab_meta_page(sbi, blk_addr);
1665 	void *dst = page_address(page);
1666 
1667 	if (src)
1668 		memcpy(dst, src, PAGE_SIZE);
1669 	else
1670 		memset(dst, 0, PAGE_SIZE);
1671 	set_page_dirty(page);
1672 	f2fs_put_page(page, 1);
1673 }
1674 
1675 static void write_sum_page(struct f2fs_sb_info *sbi,
1676 			struct f2fs_summary_block *sum_blk, block_t blk_addr)
1677 {
1678 	update_meta_page(sbi, (void *)sum_blk, blk_addr);
1679 }
1680 
1681 static void write_current_sum_page(struct f2fs_sb_info *sbi,
1682 						int type, block_t blk_addr)
1683 {
1684 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1685 	struct page *page = grab_meta_page(sbi, blk_addr);
1686 	struct f2fs_summary_block *src = curseg->sum_blk;
1687 	struct f2fs_summary_block *dst;
1688 
1689 	dst = (struct f2fs_summary_block *)page_address(page);
1690 
1691 	mutex_lock(&curseg->curseg_mutex);
1692 
1693 	down_read(&curseg->journal_rwsem);
1694 	memcpy(&dst->journal, curseg->journal, SUM_JOURNAL_SIZE);
1695 	up_read(&curseg->journal_rwsem);
1696 
1697 	memcpy(dst->entries, src->entries, SUM_ENTRY_SIZE);
1698 	memcpy(&dst->footer, &src->footer, SUM_FOOTER_SIZE);
1699 
1700 	mutex_unlock(&curseg->curseg_mutex);
1701 
1702 	set_page_dirty(page);
1703 	f2fs_put_page(page, 1);
1704 }
1705 
1706 static int is_next_segment_free(struct f2fs_sb_info *sbi, int type)
1707 {
1708 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1709 	unsigned int segno = curseg->segno + 1;
1710 	struct free_segmap_info *free_i = FREE_I(sbi);
1711 
1712 	if (segno < MAIN_SEGS(sbi) && segno % sbi->segs_per_sec)
1713 		return !test_bit(segno, free_i->free_segmap);
1714 	return 0;
1715 }
1716 
1717 /*
1718  * Find a new segment from the free segments bitmap to right order
1719  * This function should be returned with success, otherwise BUG
1720  */
1721 static void get_new_segment(struct f2fs_sb_info *sbi,
1722 			unsigned int *newseg, bool new_sec, int dir)
1723 {
1724 	struct free_segmap_info *free_i = FREE_I(sbi);
1725 	unsigned int segno, secno, zoneno;
1726 	unsigned int total_zones = MAIN_SECS(sbi) / sbi->secs_per_zone;
1727 	unsigned int hint = GET_SEC_FROM_SEG(sbi, *newseg);
1728 	unsigned int old_zoneno = GET_ZONE_FROM_SEG(sbi, *newseg);
1729 	unsigned int left_start = hint;
1730 	bool init = true;
1731 	int go_left = 0;
1732 	int i;
1733 
1734 	spin_lock(&free_i->segmap_lock);
1735 
1736 	if (!new_sec && ((*newseg + 1) % sbi->segs_per_sec)) {
1737 		segno = find_next_zero_bit(free_i->free_segmap,
1738 			GET_SEG_FROM_SEC(sbi, hint + 1), *newseg + 1);
1739 		if (segno < GET_SEG_FROM_SEC(sbi, hint + 1))
1740 			goto got_it;
1741 	}
1742 find_other_zone:
1743 	secno = find_next_zero_bit(free_i->free_secmap, MAIN_SECS(sbi), hint);
1744 	if (secno >= MAIN_SECS(sbi)) {
1745 		if (dir == ALLOC_RIGHT) {
1746 			secno = find_next_zero_bit(free_i->free_secmap,
1747 							MAIN_SECS(sbi), 0);
1748 			f2fs_bug_on(sbi, secno >= MAIN_SECS(sbi));
1749 		} else {
1750 			go_left = 1;
1751 			left_start = hint - 1;
1752 		}
1753 	}
1754 	if (go_left == 0)
1755 		goto skip_left;
1756 
1757 	while (test_bit(left_start, free_i->free_secmap)) {
1758 		if (left_start > 0) {
1759 			left_start--;
1760 			continue;
1761 		}
1762 		left_start = find_next_zero_bit(free_i->free_secmap,
1763 							MAIN_SECS(sbi), 0);
1764 		f2fs_bug_on(sbi, left_start >= MAIN_SECS(sbi));
1765 		break;
1766 	}
1767 	secno = left_start;
1768 skip_left:
1769 	hint = secno;
1770 	segno = GET_SEG_FROM_SEC(sbi, secno);
1771 	zoneno = GET_ZONE_FROM_SEC(sbi, secno);
1772 
1773 	/* give up on finding another zone */
1774 	if (!init)
1775 		goto got_it;
1776 	if (sbi->secs_per_zone == 1)
1777 		goto got_it;
1778 	if (zoneno == old_zoneno)
1779 		goto got_it;
1780 	if (dir == ALLOC_LEFT) {
1781 		if (!go_left && zoneno + 1 >= total_zones)
1782 			goto got_it;
1783 		if (go_left && zoneno == 0)
1784 			goto got_it;
1785 	}
1786 	for (i = 0; i < NR_CURSEG_TYPE; i++)
1787 		if (CURSEG_I(sbi, i)->zone == zoneno)
1788 			break;
1789 
1790 	if (i < NR_CURSEG_TYPE) {
1791 		/* zone is in user, try another */
1792 		if (go_left)
1793 			hint = zoneno * sbi->secs_per_zone - 1;
1794 		else if (zoneno + 1 >= total_zones)
1795 			hint = 0;
1796 		else
1797 			hint = (zoneno + 1) * sbi->secs_per_zone;
1798 		init = false;
1799 		goto find_other_zone;
1800 	}
1801 got_it:
1802 	/* set it as dirty segment in free segmap */
1803 	f2fs_bug_on(sbi, test_bit(segno, free_i->free_segmap));
1804 	__set_inuse(sbi, segno);
1805 	*newseg = segno;
1806 	spin_unlock(&free_i->segmap_lock);
1807 }
1808 
1809 static void reset_curseg(struct f2fs_sb_info *sbi, int type, int modified)
1810 {
1811 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1812 	struct summary_footer *sum_footer;
1813 
1814 	curseg->segno = curseg->next_segno;
1815 	curseg->zone = GET_ZONE_FROM_SEG(sbi, curseg->segno);
1816 	curseg->next_blkoff = 0;
1817 	curseg->next_segno = NULL_SEGNO;
1818 
1819 	sum_footer = &(curseg->sum_blk->footer);
1820 	memset(sum_footer, 0, sizeof(struct summary_footer));
1821 	if (IS_DATASEG(type))
1822 		SET_SUM_TYPE(sum_footer, SUM_TYPE_DATA);
1823 	if (IS_NODESEG(type))
1824 		SET_SUM_TYPE(sum_footer, SUM_TYPE_NODE);
1825 	__set_sit_entry_type(sbi, type, curseg->segno, modified);
1826 }
1827 
1828 static unsigned int __get_next_segno(struct f2fs_sb_info *sbi, int type)
1829 {
1830 	/* if segs_per_sec is large than 1, we need to keep original policy. */
1831 	if (sbi->segs_per_sec != 1)
1832 		return CURSEG_I(sbi, type)->segno;
1833 
1834 	if (type == CURSEG_HOT_DATA || IS_NODESEG(type))
1835 		return 0;
1836 
1837 	if (SIT_I(sbi)->last_victim[ALLOC_NEXT])
1838 		return SIT_I(sbi)->last_victim[ALLOC_NEXT];
1839 	return CURSEG_I(sbi, type)->segno;
1840 }
1841 
1842 /*
1843  * Allocate a current working segment.
1844  * This function always allocates a free segment in LFS manner.
1845  */
1846 static void new_curseg(struct f2fs_sb_info *sbi, int type, bool new_sec)
1847 {
1848 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1849 	unsigned int segno = curseg->segno;
1850 	int dir = ALLOC_LEFT;
1851 
1852 	write_sum_page(sbi, curseg->sum_blk,
1853 				GET_SUM_BLOCK(sbi, segno));
1854 	if (type == CURSEG_WARM_DATA || type == CURSEG_COLD_DATA)
1855 		dir = ALLOC_RIGHT;
1856 
1857 	if (test_opt(sbi, NOHEAP))
1858 		dir = ALLOC_RIGHT;
1859 
1860 	segno = __get_next_segno(sbi, type);
1861 	get_new_segment(sbi, &segno, new_sec, dir);
1862 	curseg->next_segno = segno;
1863 	reset_curseg(sbi, type, 1);
1864 	curseg->alloc_type = LFS;
1865 }
1866 
1867 static void __next_free_blkoff(struct f2fs_sb_info *sbi,
1868 			struct curseg_info *seg, block_t start)
1869 {
1870 	struct seg_entry *se = get_seg_entry(sbi, seg->segno);
1871 	int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
1872 	unsigned long *target_map = SIT_I(sbi)->tmp_map;
1873 	unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
1874 	unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
1875 	int i, pos;
1876 
1877 	for (i = 0; i < entries; i++)
1878 		target_map[i] = ckpt_map[i] | cur_map[i];
1879 
1880 	pos = __find_rev_next_zero_bit(target_map, sbi->blocks_per_seg, start);
1881 
1882 	seg->next_blkoff = pos;
1883 }
1884 
1885 /*
1886  * If a segment is written by LFS manner, next block offset is just obtained
1887  * by increasing the current block offset. However, if a segment is written by
1888  * SSR manner, next block offset obtained by calling __next_free_blkoff
1889  */
1890 static void __refresh_next_blkoff(struct f2fs_sb_info *sbi,
1891 				struct curseg_info *seg)
1892 {
1893 	if (seg->alloc_type == SSR)
1894 		__next_free_blkoff(sbi, seg, seg->next_blkoff + 1);
1895 	else
1896 		seg->next_blkoff++;
1897 }
1898 
1899 /*
1900  * This function always allocates a used segment(from dirty seglist) by SSR
1901  * manner, so it should recover the existing segment information of valid blocks
1902  */
1903 static void change_curseg(struct f2fs_sb_info *sbi, int type, bool reuse)
1904 {
1905 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
1906 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1907 	unsigned int new_segno = curseg->next_segno;
1908 	struct f2fs_summary_block *sum_node;
1909 	struct page *sum_page;
1910 
1911 	write_sum_page(sbi, curseg->sum_blk,
1912 				GET_SUM_BLOCK(sbi, curseg->segno));
1913 	__set_test_and_inuse(sbi, new_segno);
1914 
1915 	mutex_lock(&dirty_i->seglist_lock);
1916 	__remove_dirty_segment(sbi, new_segno, PRE);
1917 	__remove_dirty_segment(sbi, new_segno, DIRTY);
1918 	mutex_unlock(&dirty_i->seglist_lock);
1919 
1920 	reset_curseg(sbi, type, 1);
1921 	curseg->alloc_type = SSR;
1922 	__next_free_blkoff(sbi, curseg, 0);
1923 
1924 	if (reuse) {
1925 		sum_page = get_sum_page(sbi, new_segno);
1926 		sum_node = (struct f2fs_summary_block *)page_address(sum_page);
1927 		memcpy(curseg->sum_blk, sum_node, SUM_ENTRY_SIZE);
1928 		f2fs_put_page(sum_page, 1);
1929 	}
1930 }
1931 
1932 static int get_ssr_segment(struct f2fs_sb_info *sbi, int type)
1933 {
1934 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1935 	const struct victim_selection *v_ops = DIRTY_I(sbi)->v_ops;
1936 	unsigned segno = NULL_SEGNO;
1937 	int i, cnt;
1938 	bool reversed = false;
1939 
1940 	/* need_SSR() already forces to do this */
1941 	if (v_ops->get_victim(sbi, &segno, BG_GC, type, SSR)) {
1942 		curseg->next_segno = segno;
1943 		return 1;
1944 	}
1945 
1946 	/* For node segments, let's do SSR more intensively */
1947 	if (IS_NODESEG(type)) {
1948 		if (type >= CURSEG_WARM_NODE) {
1949 			reversed = true;
1950 			i = CURSEG_COLD_NODE;
1951 		} else {
1952 			i = CURSEG_HOT_NODE;
1953 		}
1954 		cnt = NR_CURSEG_NODE_TYPE;
1955 	} else {
1956 		if (type >= CURSEG_WARM_DATA) {
1957 			reversed = true;
1958 			i = CURSEG_COLD_DATA;
1959 		} else {
1960 			i = CURSEG_HOT_DATA;
1961 		}
1962 		cnt = NR_CURSEG_DATA_TYPE;
1963 	}
1964 
1965 	for (; cnt-- > 0; reversed ? i-- : i++) {
1966 		if (i == type)
1967 			continue;
1968 		if (v_ops->get_victim(sbi, &segno, BG_GC, i, SSR)) {
1969 			curseg->next_segno = segno;
1970 			return 1;
1971 		}
1972 	}
1973 	return 0;
1974 }
1975 
1976 /*
1977  * flush out current segment and replace it with new segment
1978  * This function should be returned with success, otherwise BUG
1979  */
1980 static void allocate_segment_by_default(struct f2fs_sb_info *sbi,
1981 						int type, bool force)
1982 {
1983 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1984 
1985 	if (force)
1986 		new_curseg(sbi, type, true);
1987 	else if (!is_set_ckpt_flags(sbi, CP_CRC_RECOVERY_FLAG) &&
1988 					type == CURSEG_WARM_NODE)
1989 		new_curseg(sbi, type, false);
1990 	else if (curseg->alloc_type == LFS && is_next_segment_free(sbi, type))
1991 		new_curseg(sbi, type, false);
1992 	else if (need_SSR(sbi) && get_ssr_segment(sbi, type))
1993 		change_curseg(sbi, type, true);
1994 	else
1995 		new_curseg(sbi, type, false);
1996 
1997 	stat_inc_seg_type(sbi, curseg);
1998 }
1999 
2000 void allocate_new_segments(struct f2fs_sb_info *sbi)
2001 {
2002 	struct curseg_info *curseg;
2003 	unsigned int old_segno;
2004 	int i;
2005 
2006 	for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
2007 		curseg = CURSEG_I(sbi, i);
2008 		old_segno = curseg->segno;
2009 		SIT_I(sbi)->s_ops->allocate_segment(sbi, i, true);
2010 		locate_dirty_segment(sbi, old_segno);
2011 	}
2012 }
2013 
2014 static const struct segment_allocation default_salloc_ops = {
2015 	.allocate_segment = allocate_segment_by_default,
2016 };
2017 
2018 bool exist_trim_candidates(struct f2fs_sb_info *sbi, struct cp_control *cpc)
2019 {
2020 	__u64 trim_start = cpc->trim_start;
2021 	bool has_candidate = false;
2022 
2023 	mutex_lock(&SIT_I(sbi)->sentry_lock);
2024 	for (; cpc->trim_start <= cpc->trim_end; cpc->trim_start++) {
2025 		if (add_discard_addrs(sbi, cpc, true)) {
2026 			has_candidate = true;
2027 			break;
2028 		}
2029 	}
2030 	mutex_unlock(&SIT_I(sbi)->sentry_lock);
2031 
2032 	cpc->trim_start = trim_start;
2033 	return has_candidate;
2034 }
2035 
2036 int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range)
2037 {
2038 	__u64 start = F2FS_BYTES_TO_BLK(range->start);
2039 	__u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1;
2040 	unsigned int start_segno, end_segno;
2041 	struct cp_control cpc;
2042 	int err = 0;
2043 
2044 	if (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize)
2045 		return -EINVAL;
2046 
2047 	cpc.trimmed = 0;
2048 	if (end <= MAIN_BLKADDR(sbi))
2049 		goto out;
2050 
2051 	if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) {
2052 		f2fs_msg(sbi->sb, KERN_WARNING,
2053 			"Found FS corruption, run fsck to fix.");
2054 		goto out;
2055 	}
2056 
2057 	/* start/end segment number in main_area */
2058 	start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start);
2059 	end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 :
2060 						GET_SEGNO(sbi, end);
2061 	cpc.reason = CP_DISCARD;
2062 	cpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen));
2063 
2064 	/* do checkpoint to issue discard commands safely */
2065 	for (; start_segno <= end_segno; start_segno = cpc.trim_end + 1) {
2066 		cpc.trim_start = start_segno;
2067 
2068 		if (sbi->discard_blks == 0)
2069 			break;
2070 		else if (sbi->discard_blks < BATCHED_TRIM_BLOCKS(sbi))
2071 			cpc.trim_end = end_segno;
2072 		else
2073 			cpc.trim_end = min_t(unsigned int,
2074 				rounddown(start_segno +
2075 				BATCHED_TRIM_SEGMENTS(sbi),
2076 				sbi->segs_per_sec) - 1, end_segno);
2077 
2078 		mutex_lock(&sbi->gc_mutex);
2079 		err = write_checkpoint(sbi, &cpc);
2080 		mutex_unlock(&sbi->gc_mutex);
2081 		if (err)
2082 			break;
2083 
2084 		schedule();
2085 	}
2086 out:
2087 	range->len = F2FS_BLK_TO_BYTES(cpc.trimmed);
2088 	return err;
2089 }
2090 
2091 static bool __has_curseg_space(struct f2fs_sb_info *sbi, int type)
2092 {
2093 	struct curseg_info *curseg = CURSEG_I(sbi, type);
2094 	if (curseg->next_blkoff < sbi->blocks_per_seg)
2095 		return true;
2096 	return false;
2097 }
2098 
2099 static int __get_segment_type_2(struct f2fs_io_info *fio)
2100 {
2101 	if (fio->type == DATA)
2102 		return CURSEG_HOT_DATA;
2103 	else
2104 		return CURSEG_HOT_NODE;
2105 }
2106 
2107 static int __get_segment_type_4(struct f2fs_io_info *fio)
2108 {
2109 	if (fio->type == DATA) {
2110 		struct inode *inode = fio->page->mapping->host;
2111 
2112 		if (S_ISDIR(inode->i_mode))
2113 			return CURSEG_HOT_DATA;
2114 		else
2115 			return CURSEG_COLD_DATA;
2116 	} else {
2117 		if (IS_DNODE(fio->page) && is_cold_node(fio->page))
2118 			return CURSEG_WARM_NODE;
2119 		else
2120 			return CURSEG_COLD_NODE;
2121 	}
2122 }
2123 
2124 static int __get_segment_type_6(struct f2fs_io_info *fio)
2125 {
2126 	if (fio->type == DATA) {
2127 		struct inode *inode = fio->page->mapping->host;
2128 
2129 		if (is_cold_data(fio->page) || file_is_cold(inode))
2130 			return CURSEG_COLD_DATA;
2131 		if (is_inode_flag_set(inode, FI_HOT_DATA))
2132 			return CURSEG_HOT_DATA;
2133 		return CURSEG_WARM_DATA;
2134 	} else {
2135 		if (IS_DNODE(fio->page))
2136 			return is_cold_node(fio->page) ? CURSEG_WARM_NODE :
2137 						CURSEG_HOT_NODE;
2138 		return CURSEG_COLD_NODE;
2139 	}
2140 }
2141 
2142 static int __get_segment_type(struct f2fs_io_info *fio)
2143 {
2144 	int type = 0;
2145 
2146 	switch (fio->sbi->active_logs) {
2147 	case 2:
2148 		type = __get_segment_type_2(fio);
2149 		break;
2150 	case 4:
2151 		type = __get_segment_type_4(fio);
2152 		break;
2153 	case 6:
2154 		type = __get_segment_type_6(fio);
2155 		break;
2156 	default:
2157 		f2fs_bug_on(fio->sbi, true);
2158 	}
2159 
2160 	if (IS_HOT(type))
2161 		fio->temp = HOT;
2162 	else if (IS_WARM(type))
2163 		fio->temp = WARM;
2164 	else
2165 		fio->temp = COLD;
2166 	return type;
2167 }
2168 
2169 void allocate_data_block(struct f2fs_sb_info *sbi, struct page *page,
2170 		block_t old_blkaddr, block_t *new_blkaddr,
2171 		struct f2fs_summary *sum, int type,
2172 		struct f2fs_io_info *fio, bool add_list)
2173 {
2174 	struct sit_info *sit_i = SIT_I(sbi);
2175 	struct curseg_info *curseg = CURSEG_I(sbi, type);
2176 
2177 	mutex_lock(&curseg->curseg_mutex);
2178 	mutex_lock(&sit_i->sentry_lock);
2179 
2180 	*new_blkaddr = NEXT_FREE_BLKADDR(sbi, curseg);
2181 
2182 	f2fs_wait_discard_bio(sbi, *new_blkaddr);
2183 
2184 	/*
2185 	 * __add_sum_entry should be resided under the curseg_mutex
2186 	 * because, this function updates a summary entry in the
2187 	 * current summary block.
2188 	 */
2189 	__add_sum_entry(sbi, type, sum);
2190 
2191 	__refresh_next_blkoff(sbi, curseg);
2192 
2193 	stat_inc_block_count(sbi, curseg);
2194 
2195 	if (!__has_curseg_space(sbi, type))
2196 		sit_i->s_ops->allocate_segment(sbi, type, false);
2197 	/*
2198 	 * SIT information should be updated after segment allocation,
2199 	 * since we need to keep dirty segments precisely under SSR.
2200 	 */
2201 	refresh_sit_entry(sbi, old_blkaddr, *new_blkaddr);
2202 
2203 	mutex_unlock(&sit_i->sentry_lock);
2204 
2205 	if (page && IS_NODESEG(type))
2206 		fill_node_footer_blkaddr(page, NEXT_FREE_BLKADDR(sbi, curseg));
2207 
2208 	if (add_list) {
2209 		struct f2fs_bio_info *io;
2210 
2211 		INIT_LIST_HEAD(&fio->list);
2212 		fio->in_list = true;
2213 		io = sbi->write_io[fio->type] + fio->temp;
2214 		spin_lock(&io->io_lock);
2215 		list_add_tail(&fio->list, &io->io_list);
2216 		spin_unlock(&io->io_lock);
2217 	}
2218 
2219 	mutex_unlock(&curseg->curseg_mutex);
2220 }
2221 
2222 static void do_write_page(struct f2fs_summary *sum, struct f2fs_io_info *fio)
2223 {
2224 	int type = __get_segment_type(fio);
2225 	int err;
2226 
2227 reallocate:
2228 	allocate_data_block(fio->sbi, fio->page, fio->old_blkaddr,
2229 			&fio->new_blkaddr, sum, type, fio, true);
2230 
2231 	/* writeout dirty page into bdev */
2232 	err = f2fs_submit_page_write(fio);
2233 	if (err == -EAGAIN) {
2234 		fio->old_blkaddr = fio->new_blkaddr;
2235 		goto reallocate;
2236 	}
2237 }
2238 
2239 void write_meta_page(struct f2fs_sb_info *sbi, struct page *page)
2240 {
2241 	struct f2fs_io_info fio = {
2242 		.sbi = sbi,
2243 		.type = META,
2244 		.op = REQ_OP_WRITE,
2245 		.op_flags = REQ_SYNC | REQ_META | REQ_PRIO,
2246 		.old_blkaddr = page->index,
2247 		.new_blkaddr = page->index,
2248 		.page = page,
2249 		.encrypted_page = NULL,
2250 		.in_list = false,
2251 	};
2252 
2253 	if (unlikely(page->index >= MAIN_BLKADDR(sbi)))
2254 		fio.op_flags &= ~REQ_META;
2255 
2256 	set_page_writeback(page);
2257 	f2fs_submit_page_write(&fio);
2258 }
2259 
2260 void write_node_page(unsigned int nid, struct f2fs_io_info *fio)
2261 {
2262 	struct f2fs_summary sum;
2263 
2264 	set_summary(&sum, nid, 0, 0);
2265 	do_write_page(&sum, fio);
2266 }
2267 
2268 void write_data_page(struct dnode_of_data *dn, struct f2fs_io_info *fio)
2269 {
2270 	struct f2fs_sb_info *sbi = fio->sbi;
2271 	struct f2fs_summary sum;
2272 	struct node_info ni;
2273 
2274 	f2fs_bug_on(sbi, dn->data_blkaddr == NULL_ADDR);
2275 	get_node_info(sbi, dn->nid, &ni);
2276 	set_summary(&sum, dn->nid, dn->ofs_in_node, ni.version);
2277 	do_write_page(&sum, fio);
2278 	f2fs_update_data_blkaddr(dn, fio->new_blkaddr);
2279 }
2280 
2281 int rewrite_data_page(struct f2fs_io_info *fio)
2282 {
2283 	fio->new_blkaddr = fio->old_blkaddr;
2284 	stat_inc_inplace_blocks(fio->sbi);
2285 	return f2fs_submit_page_bio(fio);
2286 }
2287 
2288 void __f2fs_replace_block(struct f2fs_sb_info *sbi, struct f2fs_summary *sum,
2289 				block_t old_blkaddr, block_t new_blkaddr,
2290 				bool recover_curseg, bool recover_newaddr)
2291 {
2292 	struct sit_info *sit_i = SIT_I(sbi);
2293 	struct curseg_info *curseg;
2294 	unsigned int segno, old_cursegno;
2295 	struct seg_entry *se;
2296 	int type;
2297 	unsigned short old_blkoff;
2298 
2299 	segno = GET_SEGNO(sbi, new_blkaddr);
2300 	se = get_seg_entry(sbi, segno);
2301 	type = se->type;
2302 
2303 	if (!recover_curseg) {
2304 		/* for recovery flow */
2305 		if (se->valid_blocks == 0 && !IS_CURSEG(sbi, segno)) {
2306 			if (old_blkaddr == NULL_ADDR)
2307 				type = CURSEG_COLD_DATA;
2308 			else
2309 				type = CURSEG_WARM_DATA;
2310 		}
2311 	} else {
2312 		if (!IS_CURSEG(sbi, segno))
2313 			type = CURSEG_WARM_DATA;
2314 	}
2315 
2316 	curseg = CURSEG_I(sbi, type);
2317 
2318 	mutex_lock(&curseg->curseg_mutex);
2319 	mutex_lock(&sit_i->sentry_lock);
2320 
2321 	old_cursegno = curseg->segno;
2322 	old_blkoff = curseg->next_blkoff;
2323 
2324 	/* change the current segment */
2325 	if (segno != curseg->segno) {
2326 		curseg->next_segno = segno;
2327 		change_curseg(sbi, type, true);
2328 	}
2329 
2330 	curseg->next_blkoff = GET_BLKOFF_FROM_SEG0(sbi, new_blkaddr);
2331 	__add_sum_entry(sbi, type, sum);
2332 
2333 	if (!recover_curseg || recover_newaddr)
2334 		update_sit_entry(sbi, new_blkaddr, 1);
2335 	if (GET_SEGNO(sbi, old_blkaddr) != NULL_SEGNO)
2336 		update_sit_entry(sbi, old_blkaddr, -1);
2337 
2338 	locate_dirty_segment(sbi, GET_SEGNO(sbi, old_blkaddr));
2339 	locate_dirty_segment(sbi, GET_SEGNO(sbi, new_blkaddr));
2340 
2341 	locate_dirty_segment(sbi, old_cursegno);
2342 
2343 	if (recover_curseg) {
2344 		if (old_cursegno != curseg->segno) {
2345 			curseg->next_segno = old_cursegno;
2346 			change_curseg(sbi, type, true);
2347 		}
2348 		curseg->next_blkoff = old_blkoff;
2349 	}
2350 
2351 	mutex_unlock(&sit_i->sentry_lock);
2352 	mutex_unlock(&curseg->curseg_mutex);
2353 }
2354 
2355 void f2fs_replace_block(struct f2fs_sb_info *sbi, struct dnode_of_data *dn,
2356 				block_t old_addr, block_t new_addr,
2357 				unsigned char version, bool recover_curseg,
2358 				bool recover_newaddr)
2359 {
2360 	struct f2fs_summary sum;
2361 
2362 	set_summary(&sum, dn->nid, dn->ofs_in_node, version);
2363 
2364 	__f2fs_replace_block(sbi, &sum, old_addr, new_addr,
2365 					recover_curseg, recover_newaddr);
2366 
2367 	f2fs_update_data_blkaddr(dn, new_addr);
2368 }
2369 
2370 void f2fs_wait_on_page_writeback(struct page *page,
2371 				enum page_type type, bool ordered)
2372 {
2373 	if (PageWriteback(page)) {
2374 		struct f2fs_sb_info *sbi = F2FS_P_SB(page);
2375 
2376 		f2fs_submit_merged_write_cond(sbi, page->mapping->host,
2377 						0, page->index, type);
2378 		if (ordered)
2379 			wait_on_page_writeback(page);
2380 		else
2381 			wait_for_stable_page(page);
2382 	}
2383 }
2384 
2385 void f2fs_wait_on_encrypted_page_writeback(struct f2fs_sb_info *sbi,
2386 							block_t blkaddr)
2387 {
2388 	struct page *cpage;
2389 
2390 	if (blkaddr == NEW_ADDR || blkaddr == NULL_ADDR)
2391 		return;
2392 
2393 	cpage = find_lock_page(META_MAPPING(sbi), blkaddr);
2394 	if (cpage) {
2395 		f2fs_wait_on_page_writeback(cpage, DATA, true);
2396 		f2fs_put_page(cpage, 1);
2397 	}
2398 }
2399 
2400 static int read_compacted_summaries(struct f2fs_sb_info *sbi)
2401 {
2402 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
2403 	struct curseg_info *seg_i;
2404 	unsigned char *kaddr;
2405 	struct page *page;
2406 	block_t start;
2407 	int i, j, offset;
2408 
2409 	start = start_sum_block(sbi);
2410 
2411 	page = get_meta_page(sbi, start++);
2412 	kaddr = (unsigned char *)page_address(page);
2413 
2414 	/* Step 1: restore nat cache */
2415 	seg_i = CURSEG_I(sbi, CURSEG_HOT_DATA);
2416 	memcpy(seg_i->journal, kaddr, SUM_JOURNAL_SIZE);
2417 
2418 	/* Step 2: restore sit cache */
2419 	seg_i = CURSEG_I(sbi, CURSEG_COLD_DATA);
2420 	memcpy(seg_i->journal, kaddr + SUM_JOURNAL_SIZE, SUM_JOURNAL_SIZE);
2421 	offset = 2 * SUM_JOURNAL_SIZE;
2422 
2423 	/* Step 3: restore summary entries */
2424 	for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
2425 		unsigned short blk_off;
2426 		unsigned int segno;
2427 
2428 		seg_i = CURSEG_I(sbi, i);
2429 		segno = le32_to_cpu(ckpt->cur_data_segno[i]);
2430 		blk_off = le16_to_cpu(ckpt->cur_data_blkoff[i]);
2431 		seg_i->next_segno = segno;
2432 		reset_curseg(sbi, i, 0);
2433 		seg_i->alloc_type = ckpt->alloc_type[i];
2434 		seg_i->next_blkoff = blk_off;
2435 
2436 		if (seg_i->alloc_type == SSR)
2437 			blk_off = sbi->blocks_per_seg;
2438 
2439 		for (j = 0; j < blk_off; j++) {
2440 			struct f2fs_summary *s;
2441 			s = (struct f2fs_summary *)(kaddr + offset);
2442 			seg_i->sum_blk->entries[j] = *s;
2443 			offset += SUMMARY_SIZE;
2444 			if (offset + SUMMARY_SIZE <= PAGE_SIZE -
2445 						SUM_FOOTER_SIZE)
2446 				continue;
2447 
2448 			f2fs_put_page(page, 1);
2449 			page = NULL;
2450 
2451 			page = get_meta_page(sbi, start++);
2452 			kaddr = (unsigned char *)page_address(page);
2453 			offset = 0;
2454 		}
2455 	}
2456 	f2fs_put_page(page, 1);
2457 	return 0;
2458 }
2459 
2460 static int read_normal_summaries(struct f2fs_sb_info *sbi, int type)
2461 {
2462 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
2463 	struct f2fs_summary_block *sum;
2464 	struct curseg_info *curseg;
2465 	struct page *new;
2466 	unsigned short blk_off;
2467 	unsigned int segno = 0;
2468 	block_t blk_addr = 0;
2469 
2470 	/* get segment number and block addr */
2471 	if (IS_DATASEG(type)) {
2472 		segno = le32_to_cpu(ckpt->cur_data_segno[type]);
2473 		blk_off = le16_to_cpu(ckpt->cur_data_blkoff[type -
2474 							CURSEG_HOT_DATA]);
2475 		if (__exist_node_summaries(sbi))
2476 			blk_addr = sum_blk_addr(sbi, NR_CURSEG_TYPE, type);
2477 		else
2478 			blk_addr = sum_blk_addr(sbi, NR_CURSEG_DATA_TYPE, type);
2479 	} else {
2480 		segno = le32_to_cpu(ckpt->cur_node_segno[type -
2481 							CURSEG_HOT_NODE]);
2482 		blk_off = le16_to_cpu(ckpt->cur_node_blkoff[type -
2483 							CURSEG_HOT_NODE]);
2484 		if (__exist_node_summaries(sbi))
2485 			blk_addr = sum_blk_addr(sbi, NR_CURSEG_NODE_TYPE,
2486 							type - CURSEG_HOT_NODE);
2487 		else
2488 			blk_addr = GET_SUM_BLOCK(sbi, segno);
2489 	}
2490 
2491 	new = get_meta_page(sbi, blk_addr);
2492 	sum = (struct f2fs_summary_block *)page_address(new);
2493 
2494 	if (IS_NODESEG(type)) {
2495 		if (__exist_node_summaries(sbi)) {
2496 			struct f2fs_summary *ns = &sum->entries[0];
2497 			int i;
2498 			for (i = 0; i < sbi->blocks_per_seg; i++, ns++) {
2499 				ns->version = 0;
2500 				ns->ofs_in_node = 0;
2501 			}
2502 		} else {
2503 			int err;
2504 
2505 			err = restore_node_summary(sbi, segno, sum);
2506 			if (err) {
2507 				f2fs_put_page(new, 1);
2508 				return err;
2509 			}
2510 		}
2511 	}
2512 
2513 	/* set uncompleted segment to curseg */
2514 	curseg = CURSEG_I(sbi, type);
2515 	mutex_lock(&curseg->curseg_mutex);
2516 
2517 	/* update journal info */
2518 	down_write(&curseg->journal_rwsem);
2519 	memcpy(curseg->journal, &sum->journal, SUM_JOURNAL_SIZE);
2520 	up_write(&curseg->journal_rwsem);
2521 
2522 	memcpy(curseg->sum_blk->entries, sum->entries, SUM_ENTRY_SIZE);
2523 	memcpy(&curseg->sum_blk->footer, &sum->footer, SUM_FOOTER_SIZE);
2524 	curseg->next_segno = segno;
2525 	reset_curseg(sbi, type, 0);
2526 	curseg->alloc_type = ckpt->alloc_type[type];
2527 	curseg->next_blkoff = blk_off;
2528 	mutex_unlock(&curseg->curseg_mutex);
2529 	f2fs_put_page(new, 1);
2530 	return 0;
2531 }
2532 
2533 static int restore_curseg_summaries(struct f2fs_sb_info *sbi)
2534 {
2535 	struct f2fs_journal *sit_j = CURSEG_I(sbi, CURSEG_COLD_DATA)->journal;
2536 	struct f2fs_journal *nat_j = CURSEG_I(sbi, CURSEG_HOT_DATA)->journal;
2537 	int type = CURSEG_HOT_DATA;
2538 	int err;
2539 
2540 	if (is_set_ckpt_flags(sbi, CP_COMPACT_SUM_FLAG)) {
2541 		int npages = npages_for_summary_flush(sbi, true);
2542 
2543 		if (npages >= 2)
2544 			ra_meta_pages(sbi, start_sum_block(sbi), npages,
2545 							META_CP, true);
2546 
2547 		/* restore for compacted data summary */
2548 		if (read_compacted_summaries(sbi))
2549 			return -EINVAL;
2550 		type = CURSEG_HOT_NODE;
2551 	}
2552 
2553 	if (__exist_node_summaries(sbi))
2554 		ra_meta_pages(sbi, sum_blk_addr(sbi, NR_CURSEG_TYPE, type),
2555 					NR_CURSEG_TYPE - type, META_CP, true);
2556 
2557 	for (; type <= CURSEG_COLD_NODE; type++) {
2558 		err = read_normal_summaries(sbi, type);
2559 		if (err)
2560 			return err;
2561 	}
2562 
2563 	/* sanity check for summary blocks */
2564 	if (nats_in_cursum(nat_j) > NAT_JOURNAL_ENTRIES ||
2565 			sits_in_cursum(sit_j) > SIT_JOURNAL_ENTRIES)
2566 		return -EINVAL;
2567 
2568 	return 0;
2569 }
2570 
2571 static void write_compacted_summaries(struct f2fs_sb_info *sbi, block_t blkaddr)
2572 {
2573 	struct page *page;
2574 	unsigned char *kaddr;
2575 	struct f2fs_summary *summary;
2576 	struct curseg_info *seg_i;
2577 	int written_size = 0;
2578 	int i, j;
2579 
2580 	page = grab_meta_page(sbi, blkaddr++);
2581 	kaddr = (unsigned char *)page_address(page);
2582 
2583 	/* Step 1: write nat cache */
2584 	seg_i = CURSEG_I(sbi, CURSEG_HOT_DATA);
2585 	memcpy(kaddr, seg_i->journal, SUM_JOURNAL_SIZE);
2586 	written_size += SUM_JOURNAL_SIZE;
2587 
2588 	/* Step 2: write sit cache */
2589 	seg_i = CURSEG_I(sbi, CURSEG_COLD_DATA);
2590 	memcpy(kaddr + written_size, seg_i->journal, SUM_JOURNAL_SIZE);
2591 	written_size += SUM_JOURNAL_SIZE;
2592 
2593 	/* Step 3: write summary entries */
2594 	for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
2595 		unsigned short blkoff;
2596 		seg_i = CURSEG_I(sbi, i);
2597 		if (sbi->ckpt->alloc_type[i] == SSR)
2598 			blkoff = sbi->blocks_per_seg;
2599 		else
2600 			blkoff = curseg_blkoff(sbi, i);
2601 
2602 		for (j = 0; j < blkoff; j++) {
2603 			if (!page) {
2604 				page = grab_meta_page(sbi, blkaddr++);
2605 				kaddr = (unsigned char *)page_address(page);
2606 				written_size = 0;
2607 			}
2608 			summary = (struct f2fs_summary *)(kaddr + written_size);
2609 			*summary = seg_i->sum_blk->entries[j];
2610 			written_size += SUMMARY_SIZE;
2611 
2612 			if (written_size + SUMMARY_SIZE <= PAGE_SIZE -
2613 							SUM_FOOTER_SIZE)
2614 				continue;
2615 
2616 			set_page_dirty(page);
2617 			f2fs_put_page(page, 1);
2618 			page = NULL;
2619 		}
2620 	}
2621 	if (page) {
2622 		set_page_dirty(page);
2623 		f2fs_put_page(page, 1);
2624 	}
2625 }
2626 
2627 static void write_normal_summaries(struct f2fs_sb_info *sbi,
2628 					block_t blkaddr, int type)
2629 {
2630 	int i, end;
2631 	if (IS_DATASEG(type))
2632 		end = type + NR_CURSEG_DATA_TYPE;
2633 	else
2634 		end = type + NR_CURSEG_NODE_TYPE;
2635 
2636 	for (i = type; i < end; i++)
2637 		write_current_sum_page(sbi, i, blkaddr + (i - type));
2638 }
2639 
2640 void write_data_summaries(struct f2fs_sb_info *sbi, block_t start_blk)
2641 {
2642 	if (is_set_ckpt_flags(sbi, CP_COMPACT_SUM_FLAG))
2643 		write_compacted_summaries(sbi, start_blk);
2644 	else
2645 		write_normal_summaries(sbi, start_blk, CURSEG_HOT_DATA);
2646 }
2647 
2648 void write_node_summaries(struct f2fs_sb_info *sbi, block_t start_blk)
2649 {
2650 	write_normal_summaries(sbi, start_blk, CURSEG_HOT_NODE);
2651 }
2652 
2653 int lookup_journal_in_cursum(struct f2fs_journal *journal, int type,
2654 					unsigned int val, int alloc)
2655 {
2656 	int i;
2657 
2658 	if (type == NAT_JOURNAL) {
2659 		for (i = 0; i < nats_in_cursum(journal); i++) {
2660 			if (le32_to_cpu(nid_in_journal(journal, i)) == val)
2661 				return i;
2662 		}
2663 		if (alloc && __has_cursum_space(journal, 1, NAT_JOURNAL))
2664 			return update_nats_in_cursum(journal, 1);
2665 	} else if (type == SIT_JOURNAL) {
2666 		for (i = 0; i < sits_in_cursum(journal); i++)
2667 			if (le32_to_cpu(segno_in_journal(journal, i)) == val)
2668 				return i;
2669 		if (alloc && __has_cursum_space(journal, 1, SIT_JOURNAL))
2670 			return update_sits_in_cursum(journal, 1);
2671 	}
2672 	return -1;
2673 }
2674 
2675 static struct page *get_current_sit_page(struct f2fs_sb_info *sbi,
2676 					unsigned int segno)
2677 {
2678 	return get_meta_page(sbi, current_sit_addr(sbi, segno));
2679 }
2680 
2681 static struct page *get_next_sit_page(struct f2fs_sb_info *sbi,
2682 					unsigned int start)
2683 {
2684 	struct sit_info *sit_i = SIT_I(sbi);
2685 	struct page *src_page, *dst_page;
2686 	pgoff_t src_off, dst_off;
2687 	void *src_addr, *dst_addr;
2688 
2689 	src_off = current_sit_addr(sbi, start);
2690 	dst_off = next_sit_addr(sbi, src_off);
2691 
2692 	/* get current sit block page without lock */
2693 	src_page = get_meta_page(sbi, src_off);
2694 	dst_page = grab_meta_page(sbi, dst_off);
2695 	f2fs_bug_on(sbi, PageDirty(src_page));
2696 
2697 	src_addr = page_address(src_page);
2698 	dst_addr = page_address(dst_page);
2699 	memcpy(dst_addr, src_addr, PAGE_SIZE);
2700 
2701 	set_page_dirty(dst_page);
2702 	f2fs_put_page(src_page, 1);
2703 
2704 	set_to_next_sit(sit_i, start);
2705 
2706 	return dst_page;
2707 }
2708 
2709 static struct sit_entry_set *grab_sit_entry_set(void)
2710 {
2711 	struct sit_entry_set *ses =
2712 			f2fs_kmem_cache_alloc(sit_entry_set_slab, GFP_NOFS);
2713 
2714 	ses->entry_cnt = 0;
2715 	INIT_LIST_HEAD(&ses->set_list);
2716 	return ses;
2717 }
2718 
2719 static void release_sit_entry_set(struct sit_entry_set *ses)
2720 {
2721 	list_del(&ses->set_list);
2722 	kmem_cache_free(sit_entry_set_slab, ses);
2723 }
2724 
2725 static void adjust_sit_entry_set(struct sit_entry_set *ses,
2726 						struct list_head *head)
2727 {
2728 	struct sit_entry_set *next = ses;
2729 
2730 	if (list_is_last(&ses->set_list, head))
2731 		return;
2732 
2733 	list_for_each_entry_continue(next, head, set_list)
2734 		if (ses->entry_cnt <= next->entry_cnt)
2735 			break;
2736 
2737 	list_move_tail(&ses->set_list, &next->set_list);
2738 }
2739 
2740 static void add_sit_entry(unsigned int segno, struct list_head *head)
2741 {
2742 	struct sit_entry_set *ses;
2743 	unsigned int start_segno = START_SEGNO(segno);
2744 
2745 	list_for_each_entry(ses, head, set_list) {
2746 		if (ses->start_segno == start_segno) {
2747 			ses->entry_cnt++;
2748 			adjust_sit_entry_set(ses, head);
2749 			return;
2750 		}
2751 	}
2752 
2753 	ses = grab_sit_entry_set();
2754 
2755 	ses->start_segno = start_segno;
2756 	ses->entry_cnt++;
2757 	list_add(&ses->set_list, head);
2758 }
2759 
2760 static void add_sits_in_set(struct f2fs_sb_info *sbi)
2761 {
2762 	struct f2fs_sm_info *sm_info = SM_I(sbi);
2763 	struct list_head *set_list = &sm_info->sit_entry_set;
2764 	unsigned long *bitmap = SIT_I(sbi)->dirty_sentries_bitmap;
2765 	unsigned int segno;
2766 
2767 	for_each_set_bit(segno, bitmap, MAIN_SEGS(sbi))
2768 		add_sit_entry(segno, set_list);
2769 }
2770 
2771 static void remove_sits_in_journal(struct f2fs_sb_info *sbi)
2772 {
2773 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
2774 	struct f2fs_journal *journal = curseg->journal;
2775 	int i;
2776 
2777 	down_write(&curseg->journal_rwsem);
2778 	for (i = 0; i < sits_in_cursum(journal); i++) {
2779 		unsigned int segno;
2780 		bool dirtied;
2781 
2782 		segno = le32_to_cpu(segno_in_journal(journal, i));
2783 		dirtied = __mark_sit_entry_dirty(sbi, segno);
2784 
2785 		if (!dirtied)
2786 			add_sit_entry(segno, &SM_I(sbi)->sit_entry_set);
2787 	}
2788 	update_sits_in_cursum(journal, -i);
2789 	up_write(&curseg->journal_rwsem);
2790 }
2791 
2792 /*
2793  * CP calls this function, which flushes SIT entries including sit_journal,
2794  * and moves prefree segs to free segs.
2795  */
2796 void flush_sit_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc)
2797 {
2798 	struct sit_info *sit_i = SIT_I(sbi);
2799 	unsigned long *bitmap = sit_i->dirty_sentries_bitmap;
2800 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
2801 	struct f2fs_journal *journal = curseg->journal;
2802 	struct sit_entry_set *ses, *tmp;
2803 	struct list_head *head = &SM_I(sbi)->sit_entry_set;
2804 	bool to_journal = true;
2805 	struct seg_entry *se;
2806 
2807 	mutex_lock(&sit_i->sentry_lock);
2808 
2809 	if (!sit_i->dirty_sentries)
2810 		goto out;
2811 
2812 	/*
2813 	 * add and account sit entries of dirty bitmap in sit entry
2814 	 * set temporarily
2815 	 */
2816 	add_sits_in_set(sbi);
2817 
2818 	/*
2819 	 * if there are no enough space in journal to store dirty sit
2820 	 * entries, remove all entries from journal and add and account
2821 	 * them in sit entry set.
2822 	 */
2823 	if (!__has_cursum_space(journal, sit_i->dirty_sentries, SIT_JOURNAL))
2824 		remove_sits_in_journal(sbi);
2825 
2826 	/*
2827 	 * there are two steps to flush sit entries:
2828 	 * #1, flush sit entries to journal in current cold data summary block.
2829 	 * #2, flush sit entries to sit page.
2830 	 */
2831 	list_for_each_entry_safe(ses, tmp, head, set_list) {
2832 		struct page *page = NULL;
2833 		struct f2fs_sit_block *raw_sit = NULL;
2834 		unsigned int start_segno = ses->start_segno;
2835 		unsigned int end = min(start_segno + SIT_ENTRY_PER_BLOCK,
2836 						(unsigned long)MAIN_SEGS(sbi));
2837 		unsigned int segno = start_segno;
2838 
2839 		if (to_journal &&
2840 			!__has_cursum_space(journal, ses->entry_cnt, SIT_JOURNAL))
2841 			to_journal = false;
2842 
2843 		if (to_journal) {
2844 			down_write(&curseg->journal_rwsem);
2845 		} else {
2846 			page = get_next_sit_page(sbi, start_segno);
2847 			raw_sit = page_address(page);
2848 		}
2849 
2850 		/* flush dirty sit entries in region of current sit set */
2851 		for_each_set_bit_from(segno, bitmap, end) {
2852 			int offset, sit_offset;
2853 
2854 			se = get_seg_entry(sbi, segno);
2855 
2856 			/* add discard candidates */
2857 			if (!(cpc->reason & CP_DISCARD)) {
2858 				cpc->trim_start = segno;
2859 				add_discard_addrs(sbi, cpc, false);
2860 			}
2861 
2862 			if (to_journal) {
2863 				offset = lookup_journal_in_cursum(journal,
2864 							SIT_JOURNAL, segno, 1);
2865 				f2fs_bug_on(sbi, offset < 0);
2866 				segno_in_journal(journal, offset) =
2867 							cpu_to_le32(segno);
2868 				seg_info_to_raw_sit(se,
2869 					&sit_in_journal(journal, offset));
2870 			} else {
2871 				sit_offset = SIT_ENTRY_OFFSET(sit_i, segno);
2872 				seg_info_to_raw_sit(se,
2873 						&raw_sit->entries[sit_offset]);
2874 			}
2875 
2876 			__clear_bit(segno, bitmap);
2877 			sit_i->dirty_sentries--;
2878 			ses->entry_cnt--;
2879 		}
2880 
2881 		if (to_journal)
2882 			up_write(&curseg->journal_rwsem);
2883 		else
2884 			f2fs_put_page(page, 1);
2885 
2886 		f2fs_bug_on(sbi, ses->entry_cnt);
2887 		release_sit_entry_set(ses);
2888 	}
2889 
2890 	f2fs_bug_on(sbi, !list_empty(head));
2891 	f2fs_bug_on(sbi, sit_i->dirty_sentries);
2892 out:
2893 	if (cpc->reason & CP_DISCARD) {
2894 		__u64 trim_start = cpc->trim_start;
2895 
2896 		for (; cpc->trim_start <= cpc->trim_end; cpc->trim_start++)
2897 			add_discard_addrs(sbi, cpc, false);
2898 
2899 		cpc->trim_start = trim_start;
2900 	}
2901 	mutex_unlock(&sit_i->sentry_lock);
2902 
2903 	set_prefree_as_free_segments(sbi);
2904 }
2905 
2906 static int build_sit_info(struct f2fs_sb_info *sbi)
2907 {
2908 	struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
2909 	struct sit_info *sit_i;
2910 	unsigned int sit_segs, start;
2911 	char *src_bitmap;
2912 	unsigned int bitmap_size;
2913 
2914 	/* allocate memory for SIT information */
2915 	sit_i = kzalloc(sizeof(struct sit_info), GFP_KERNEL);
2916 	if (!sit_i)
2917 		return -ENOMEM;
2918 
2919 	SM_I(sbi)->sit_info = sit_i;
2920 
2921 	sit_i->sentries = kvzalloc(MAIN_SEGS(sbi) *
2922 					sizeof(struct seg_entry), GFP_KERNEL);
2923 	if (!sit_i->sentries)
2924 		return -ENOMEM;
2925 
2926 	bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
2927 	sit_i->dirty_sentries_bitmap = kvzalloc(bitmap_size, GFP_KERNEL);
2928 	if (!sit_i->dirty_sentries_bitmap)
2929 		return -ENOMEM;
2930 
2931 	for (start = 0; start < MAIN_SEGS(sbi); start++) {
2932 		sit_i->sentries[start].cur_valid_map
2933 			= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
2934 		sit_i->sentries[start].ckpt_valid_map
2935 			= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
2936 		if (!sit_i->sentries[start].cur_valid_map ||
2937 				!sit_i->sentries[start].ckpt_valid_map)
2938 			return -ENOMEM;
2939 
2940 #ifdef CONFIG_F2FS_CHECK_FS
2941 		sit_i->sentries[start].cur_valid_map_mir
2942 			= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
2943 		if (!sit_i->sentries[start].cur_valid_map_mir)
2944 			return -ENOMEM;
2945 #endif
2946 
2947 		if (f2fs_discard_en(sbi)) {
2948 			sit_i->sentries[start].discard_map
2949 				= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
2950 			if (!sit_i->sentries[start].discard_map)
2951 				return -ENOMEM;
2952 		}
2953 	}
2954 
2955 	sit_i->tmp_map = kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
2956 	if (!sit_i->tmp_map)
2957 		return -ENOMEM;
2958 
2959 	if (sbi->segs_per_sec > 1) {
2960 		sit_i->sec_entries = kvzalloc(MAIN_SECS(sbi) *
2961 					sizeof(struct sec_entry), GFP_KERNEL);
2962 		if (!sit_i->sec_entries)
2963 			return -ENOMEM;
2964 	}
2965 
2966 	/* get information related with SIT */
2967 	sit_segs = le32_to_cpu(raw_super->segment_count_sit) >> 1;
2968 
2969 	/* setup SIT bitmap from ckeckpoint pack */
2970 	bitmap_size = __bitmap_size(sbi, SIT_BITMAP);
2971 	src_bitmap = __bitmap_ptr(sbi, SIT_BITMAP);
2972 
2973 	sit_i->sit_bitmap = kmemdup(src_bitmap, bitmap_size, GFP_KERNEL);
2974 	if (!sit_i->sit_bitmap)
2975 		return -ENOMEM;
2976 
2977 #ifdef CONFIG_F2FS_CHECK_FS
2978 	sit_i->sit_bitmap_mir = kmemdup(src_bitmap, bitmap_size, GFP_KERNEL);
2979 	if (!sit_i->sit_bitmap_mir)
2980 		return -ENOMEM;
2981 #endif
2982 
2983 	/* init SIT information */
2984 	sit_i->s_ops = &default_salloc_ops;
2985 
2986 	sit_i->sit_base_addr = le32_to_cpu(raw_super->sit_blkaddr);
2987 	sit_i->sit_blocks = sit_segs << sbi->log_blocks_per_seg;
2988 	sit_i->written_valid_blocks = 0;
2989 	sit_i->bitmap_size = bitmap_size;
2990 	sit_i->dirty_sentries = 0;
2991 	sit_i->sents_per_block = SIT_ENTRY_PER_BLOCK;
2992 	sit_i->elapsed_time = le64_to_cpu(sbi->ckpt->elapsed_time);
2993 	sit_i->mounted_time = ktime_get_real_seconds();
2994 	mutex_init(&sit_i->sentry_lock);
2995 	return 0;
2996 }
2997 
2998 static int build_free_segmap(struct f2fs_sb_info *sbi)
2999 {
3000 	struct free_segmap_info *free_i;
3001 	unsigned int bitmap_size, sec_bitmap_size;
3002 
3003 	/* allocate memory for free segmap information */
3004 	free_i = kzalloc(sizeof(struct free_segmap_info), GFP_KERNEL);
3005 	if (!free_i)
3006 		return -ENOMEM;
3007 
3008 	SM_I(sbi)->free_info = free_i;
3009 
3010 	bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
3011 	free_i->free_segmap = kvmalloc(bitmap_size, GFP_KERNEL);
3012 	if (!free_i->free_segmap)
3013 		return -ENOMEM;
3014 
3015 	sec_bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
3016 	free_i->free_secmap = kvmalloc(sec_bitmap_size, GFP_KERNEL);
3017 	if (!free_i->free_secmap)
3018 		return -ENOMEM;
3019 
3020 	/* set all segments as dirty temporarily */
3021 	memset(free_i->free_segmap, 0xff, bitmap_size);
3022 	memset(free_i->free_secmap, 0xff, sec_bitmap_size);
3023 
3024 	/* init free segmap information */
3025 	free_i->start_segno = GET_SEGNO_FROM_SEG0(sbi, MAIN_BLKADDR(sbi));
3026 	free_i->free_segments = 0;
3027 	free_i->free_sections = 0;
3028 	spin_lock_init(&free_i->segmap_lock);
3029 	return 0;
3030 }
3031 
3032 static int build_curseg(struct f2fs_sb_info *sbi)
3033 {
3034 	struct curseg_info *array;
3035 	int i;
3036 
3037 	array = kcalloc(NR_CURSEG_TYPE, sizeof(*array), GFP_KERNEL);
3038 	if (!array)
3039 		return -ENOMEM;
3040 
3041 	SM_I(sbi)->curseg_array = array;
3042 
3043 	for (i = 0; i < NR_CURSEG_TYPE; i++) {
3044 		mutex_init(&array[i].curseg_mutex);
3045 		array[i].sum_blk = kzalloc(PAGE_SIZE, GFP_KERNEL);
3046 		if (!array[i].sum_blk)
3047 			return -ENOMEM;
3048 		init_rwsem(&array[i].journal_rwsem);
3049 		array[i].journal = kzalloc(sizeof(struct f2fs_journal),
3050 							GFP_KERNEL);
3051 		if (!array[i].journal)
3052 			return -ENOMEM;
3053 		array[i].segno = NULL_SEGNO;
3054 		array[i].next_blkoff = 0;
3055 	}
3056 	return restore_curseg_summaries(sbi);
3057 }
3058 
3059 static void build_sit_entries(struct f2fs_sb_info *sbi)
3060 {
3061 	struct sit_info *sit_i = SIT_I(sbi);
3062 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
3063 	struct f2fs_journal *journal = curseg->journal;
3064 	struct seg_entry *se;
3065 	struct f2fs_sit_entry sit;
3066 	int sit_blk_cnt = SIT_BLK_CNT(sbi);
3067 	unsigned int i, start, end;
3068 	unsigned int readed, start_blk = 0;
3069 
3070 	do {
3071 		readed = ra_meta_pages(sbi, start_blk, BIO_MAX_PAGES,
3072 							META_SIT, true);
3073 
3074 		start = start_blk * sit_i->sents_per_block;
3075 		end = (start_blk + readed) * sit_i->sents_per_block;
3076 
3077 		for (; start < end && start < MAIN_SEGS(sbi); start++) {
3078 			struct f2fs_sit_block *sit_blk;
3079 			struct page *page;
3080 
3081 			se = &sit_i->sentries[start];
3082 			page = get_current_sit_page(sbi, start);
3083 			sit_blk = (struct f2fs_sit_block *)page_address(page);
3084 			sit = sit_blk->entries[SIT_ENTRY_OFFSET(sit_i, start)];
3085 			f2fs_put_page(page, 1);
3086 
3087 			check_block_count(sbi, start, &sit);
3088 			seg_info_from_raw_sit(se, &sit);
3089 
3090 			/* build discard map only one time */
3091 			if (f2fs_discard_en(sbi)) {
3092 				if (is_set_ckpt_flags(sbi, CP_TRIMMED_FLAG)) {
3093 					memset(se->discard_map, 0xff,
3094 						SIT_VBLOCK_MAP_SIZE);
3095 				} else {
3096 					memcpy(se->discard_map,
3097 						se->cur_valid_map,
3098 						SIT_VBLOCK_MAP_SIZE);
3099 					sbi->discard_blks +=
3100 						sbi->blocks_per_seg -
3101 						se->valid_blocks;
3102 				}
3103 			}
3104 
3105 			if (sbi->segs_per_sec > 1)
3106 				get_sec_entry(sbi, start)->valid_blocks +=
3107 							se->valid_blocks;
3108 		}
3109 		start_blk += readed;
3110 	} while (start_blk < sit_blk_cnt);
3111 
3112 	down_read(&curseg->journal_rwsem);
3113 	for (i = 0; i < sits_in_cursum(journal); i++) {
3114 		unsigned int old_valid_blocks;
3115 
3116 		start = le32_to_cpu(segno_in_journal(journal, i));
3117 		se = &sit_i->sentries[start];
3118 		sit = sit_in_journal(journal, i);
3119 
3120 		old_valid_blocks = se->valid_blocks;
3121 
3122 		check_block_count(sbi, start, &sit);
3123 		seg_info_from_raw_sit(se, &sit);
3124 
3125 		if (f2fs_discard_en(sbi)) {
3126 			if (is_set_ckpt_flags(sbi, CP_TRIMMED_FLAG)) {
3127 				memset(se->discard_map, 0xff,
3128 							SIT_VBLOCK_MAP_SIZE);
3129 			} else {
3130 				memcpy(se->discard_map, se->cur_valid_map,
3131 							SIT_VBLOCK_MAP_SIZE);
3132 				sbi->discard_blks += old_valid_blocks -
3133 							se->valid_blocks;
3134 			}
3135 		}
3136 
3137 		if (sbi->segs_per_sec > 1)
3138 			get_sec_entry(sbi, start)->valid_blocks +=
3139 				se->valid_blocks - old_valid_blocks;
3140 	}
3141 	up_read(&curseg->journal_rwsem);
3142 }
3143 
3144 static void init_free_segmap(struct f2fs_sb_info *sbi)
3145 {
3146 	unsigned int start;
3147 	int type;
3148 
3149 	for (start = 0; start < MAIN_SEGS(sbi); start++) {
3150 		struct seg_entry *sentry = get_seg_entry(sbi, start);
3151 		if (!sentry->valid_blocks)
3152 			__set_free(sbi, start);
3153 		else
3154 			SIT_I(sbi)->written_valid_blocks +=
3155 						sentry->valid_blocks;
3156 	}
3157 
3158 	/* set use the current segments */
3159 	for (type = CURSEG_HOT_DATA; type <= CURSEG_COLD_NODE; type++) {
3160 		struct curseg_info *curseg_t = CURSEG_I(sbi, type);
3161 		__set_test_and_inuse(sbi, curseg_t->segno);
3162 	}
3163 }
3164 
3165 static void init_dirty_segmap(struct f2fs_sb_info *sbi)
3166 {
3167 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
3168 	struct free_segmap_info *free_i = FREE_I(sbi);
3169 	unsigned int segno = 0, offset = 0;
3170 	unsigned short valid_blocks;
3171 
3172 	while (1) {
3173 		/* find dirty segment based on free segmap */
3174 		segno = find_next_inuse(free_i, MAIN_SEGS(sbi), offset);
3175 		if (segno >= MAIN_SEGS(sbi))
3176 			break;
3177 		offset = segno + 1;
3178 		valid_blocks = get_valid_blocks(sbi, segno, false);
3179 		if (valid_blocks == sbi->blocks_per_seg || !valid_blocks)
3180 			continue;
3181 		if (valid_blocks > sbi->blocks_per_seg) {
3182 			f2fs_bug_on(sbi, 1);
3183 			continue;
3184 		}
3185 		mutex_lock(&dirty_i->seglist_lock);
3186 		__locate_dirty_segment(sbi, segno, DIRTY);
3187 		mutex_unlock(&dirty_i->seglist_lock);
3188 	}
3189 }
3190 
3191 static int init_victim_secmap(struct f2fs_sb_info *sbi)
3192 {
3193 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
3194 	unsigned int bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
3195 
3196 	dirty_i->victim_secmap = kvzalloc(bitmap_size, GFP_KERNEL);
3197 	if (!dirty_i->victim_secmap)
3198 		return -ENOMEM;
3199 	return 0;
3200 }
3201 
3202 static int build_dirty_segmap(struct f2fs_sb_info *sbi)
3203 {
3204 	struct dirty_seglist_info *dirty_i;
3205 	unsigned int bitmap_size, i;
3206 
3207 	/* allocate memory for dirty segments list information */
3208 	dirty_i = kzalloc(sizeof(struct dirty_seglist_info), GFP_KERNEL);
3209 	if (!dirty_i)
3210 		return -ENOMEM;
3211 
3212 	SM_I(sbi)->dirty_info = dirty_i;
3213 	mutex_init(&dirty_i->seglist_lock);
3214 
3215 	bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
3216 
3217 	for (i = 0; i < NR_DIRTY_TYPE; i++) {
3218 		dirty_i->dirty_segmap[i] = kvzalloc(bitmap_size, GFP_KERNEL);
3219 		if (!dirty_i->dirty_segmap[i])
3220 			return -ENOMEM;
3221 	}
3222 
3223 	init_dirty_segmap(sbi);
3224 	return init_victim_secmap(sbi);
3225 }
3226 
3227 /*
3228  * Update min, max modified time for cost-benefit GC algorithm
3229  */
3230 static void init_min_max_mtime(struct f2fs_sb_info *sbi)
3231 {
3232 	struct sit_info *sit_i = SIT_I(sbi);
3233 	unsigned int segno;
3234 
3235 	mutex_lock(&sit_i->sentry_lock);
3236 
3237 	sit_i->min_mtime = LLONG_MAX;
3238 
3239 	for (segno = 0; segno < MAIN_SEGS(sbi); segno += sbi->segs_per_sec) {
3240 		unsigned int i;
3241 		unsigned long long mtime = 0;
3242 
3243 		for (i = 0; i < sbi->segs_per_sec; i++)
3244 			mtime += get_seg_entry(sbi, segno + i)->mtime;
3245 
3246 		mtime = div_u64(mtime, sbi->segs_per_sec);
3247 
3248 		if (sit_i->min_mtime > mtime)
3249 			sit_i->min_mtime = mtime;
3250 	}
3251 	sit_i->max_mtime = get_mtime(sbi);
3252 	mutex_unlock(&sit_i->sentry_lock);
3253 }
3254 
3255 int build_segment_manager(struct f2fs_sb_info *sbi)
3256 {
3257 	struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
3258 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
3259 	struct f2fs_sm_info *sm_info;
3260 	int err;
3261 
3262 	sm_info = kzalloc(sizeof(struct f2fs_sm_info), GFP_KERNEL);
3263 	if (!sm_info)
3264 		return -ENOMEM;
3265 
3266 	/* init sm info */
3267 	sbi->sm_info = sm_info;
3268 	sm_info->seg0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr);
3269 	sm_info->main_blkaddr = le32_to_cpu(raw_super->main_blkaddr);
3270 	sm_info->segment_count = le32_to_cpu(raw_super->segment_count);
3271 	sm_info->reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
3272 	sm_info->ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
3273 	sm_info->main_segments = le32_to_cpu(raw_super->segment_count_main);
3274 	sm_info->ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr);
3275 	sm_info->rec_prefree_segments = sm_info->main_segments *
3276 					DEF_RECLAIM_PREFREE_SEGMENTS / 100;
3277 	if (sm_info->rec_prefree_segments > DEF_MAX_RECLAIM_PREFREE_SEGMENTS)
3278 		sm_info->rec_prefree_segments = DEF_MAX_RECLAIM_PREFREE_SEGMENTS;
3279 
3280 	if (!test_opt(sbi, LFS))
3281 		sm_info->ipu_policy = 1 << F2FS_IPU_FSYNC;
3282 	sm_info->min_ipu_util = DEF_MIN_IPU_UTIL;
3283 	sm_info->min_fsync_blocks = DEF_MIN_FSYNC_BLOCKS;
3284 	sm_info->min_hot_blocks = DEF_MIN_HOT_BLOCKS;
3285 
3286 	sm_info->trim_sections = DEF_BATCHED_TRIM_SECTIONS;
3287 
3288 	INIT_LIST_HEAD(&sm_info->sit_entry_set);
3289 
3290 	if (!f2fs_readonly(sbi->sb)) {
3291 		err = create_flush_cmd_control(sbi);
3292 		if (err)
3293 			return err;
3294 	}
3295 
3296 	err = create_discard_cmd_control(sbi);
3297 	if (err)
3298 		return err;
3299 
3300 	err = build_sit_info(sbi);
3301 	if (err)
3302 		return err;
3303 	err = build_free_segmap(sbi);
3304 	if (err)
3305 		return err;
3306 	err = build_curseg(sbi);
3307 	if (err)
3308 		return err;
3309 
3310 	/* reinit free segmap based on SIT */
3311 	build_sit_entries(sbi);
3312 
3313 	init_free_segmap(sbi);
3314 	err = build_dirty_segmap(sbi);
3315 	if (err)
3316 		return err;
3317 
3318 	init_min_max_mtime(sbi);
3319 	return 0;
3320 }
3321 
3322 static void discard_dirty_segmap(struct f2fs_sb_info *sbi,
3323 		enum dirty_type dirty_type)
3324 {
3325 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
3326 
3327 	mutex_lock(&dirty_i->seglist_lock);
3328 	kvfree(dirty_i->dirty_segmap[dirty_type]);
3329 	dirty_i->nr_dirty[dirty_type] = 0;
3330 	mutex_unlock(&dirty_i->seglist_lock);
3331 }
3332 
3333 static void destroy_victim_secmap(struct f2fs_sb_info *sbi)
3334 {
3335 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
3336 	kvfree(dirty_i->victim_secmap);
3337 }
3338 
3339 static void destroy_dirty_segmap(struct f2fs_sb_info *sbi)
3340 {
3341 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
3342 	int i;
3343 
3344 	if (!dirty_i)
3345 		return;
3346 
3347 	/* discard pre-free/dirty segments list */
3348 	for (i = 0; i < NR_DIRTY_TYPE; i++)
3349 		discard_dirty_segmap(sbi, i);
3350 
3351 	destroy_victim_secmap(sbi);
3352 	SM_I(sbi)->dirty_info = NULL;
3353 	kfree(dirty_i);
3354 }
3355 
3356 static void destroy_curseg(struct f2fs_sb_info *sbi)
3357 {
3358 	struct curseg_info *array = SM_I(sbi)->curseg_array;
3359 	int i;
3360 
3361 	if (!array)
3362 		return;
3363 	SM_I(sbi)->curseg_array = NULL;
3364 	for (i = 0; i < NR_CURSEG_TYPE; i++) {
3365 		kfree(array[i].sum_blk);
3366 		kfree(array[i].journal);
3367 	}
3368 	kfree(array);
3369 }
3370 
3371 static void destroy_free_segmap(struct f2fs_sb_info *sbi)
3372 {
3373 	struct free_segmap_info *free_i = SM_I(sbi)->free_info;
3374 	if (!free_i)
3375 		return;
3376 	SM_I(sbi)->free_info = NULL;
3377 	kvfree(free_i->free_segmap);
3378 	kvfree(free_i->free_secmap);
3379 	kfree(free_i);
3380 }
3381 
3382 static void destroy_sit_info(struct f2fs_sb_info *sbi)
3383 {
3384 	struct sit_info *sit_i = SIT_I(sbi);
3385 	unsigned int start;
3386 
3387 	if (!sit_i)
3388 		return;
3389 
3390 	if (sit_i->sentries) {
3391 		for (start = 0; start < MAIN_SEGS(sbi); start++) {
3392 			kfree(sit_i->sentries[start].cur_valid_map);
3393 #ifdef CONFIG_F2FS_CHECK_FS
3394 			kfree(sit_i->sentries[start].cur_valid_map_mir);
3395 #endif
3396 			kfree(sit_i->sentries[start].ckpt_valid_map);
3397 			kfree(sit_i->sentries[start].discard_map);
3398 		}
3399 	}
3400 	kfree(sit_i->tmp_map);
3401 
3402 	kvfree(sit_i->sentries);
3403 	kvfree(sit_i->sec_entries);
3404 	kvfree(sit_i->dirty_sentries_bitmap);
3405 
3406 	SM_I(sbi)->sit_info = NULL;
3407 	kfree(sit_i->sit_bitmap);
3408 #ifdef CONFIG_F2FS_CHECK_FS
3409 	kfree(sit_i->sit_bitmap_mir);
3410 #endif
3411 	kfree(sit_i);
3412 }
3413 
3414 void destroy_segment_manager(struct f2fs_sb_info *sbi)
3415 {
3416 	struct f2fs_sm_info *sm_info = SM_I(sbi);
3417 
3418 	if (!sm_info)
3419 		return;
3420 	destroy_flush_cmd_control(sbi, true);
3421 	destroy_discard_cmd_control(sbi);
3422 	destroy_dirty_segmap(sbi);
3423 	destroy_curseg(sbi);
3424 	destroy_free_segmap(sbi);
3425 	destroy_sit_info(sbi);
3426 	sbi->sm_info = NULL;
3427 	kfree(sm_info);
3428 }
3429 
3430 int __init create_segment_manager_caches(void)
3431 {
3432 	discard_entry_slab = f2fs_kmem_cache_create("discard_entry",
3433 			sizeof(struct discard_entry));
3434 	if (!discard_entry_slab)
3435 		goto fail;
3436 
3437 	discard_cmd_slab = f2fs_kmem_cache_create("discard_cmd",
3438 			sizeof(struct discard_cmd));
3439 	if (!discard_cmd_slab)
3440 		goto destroy_discard_entry;
3441 
3442 	sit_entry_set_slab = f2fs_kmem_cache_create("sit_entry_set",
3443 			sizeof(struct sit_entry_set));
3444 	if (!sit_entry_set_slab)
3445 		goto destroy_discard_cmd;
3446 
3447 	inmem_entry_slab = f2fs_kmem_cache_create("inmem_page_entry",
3448 			sizeof(struct inmem_pages));
3449 	if (!inmem_entry_slab)
3450 		goto destroy_sit_entry_set;
3451 	return 0;
3452 
3453 destroy_sit_entry_set:
3454 	kmem_cache_destroy(sit_entry_set_slab);
3455 destroy_discard_cmd:
3456 	kmem_cache_destroy(discard_cmd_slab);
3457 destroy_discard_entry:
3458 	kmem_cache_destroy(discard_entry_slab);
3459 fail:
3460 	return -ENOMEM;
3461 }
3462 
3463 void destroy_segment_manager_caches(void)
3464 {
3465 	kmem_cache_destroy(sit_entry_set_slab);
3466 	kmem_cache_destroy(discard_cmd_slab);
3467 	kmem_cache_destroy(discard_entry_slab);
3468 	kmem_cache_destroy(inmem_entry_slab);
3469 }
3470