xref: /openbmc/linux/fs/f2fs/segment.c (revision 6ae1be13e85f4c42c8ca371fda50ae39eebbfd96)
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/timer.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 *bio_entry_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 	clear_inode_flag(inode, FI_ATOMIC_FILE);
247 
248 	mutex_lock(&fi->inmem_lock);
249 	__revoke_inmem_pages(inode, &fi->inmem_pages, true, false);
250 	mutex_unlock(&fi->inmem_lock);
251 }
252 
253 static int __commit_inmem_pages(struct inode *inode,
254 					struct list_head *revoke_list)
255 {
256 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
257 	struct f2fs_inode_info *fi = F2FS_I(inode);
258 	struct inmem_pages *cur, *tmp;
259 	struct f2fs_io_info fio = {
260 		.sbi = sbi,
261 		.type = DATA,
262 		.op = REQ_OP_WRITE,
263 		.op_flags = WRITE_SYNC | REQ_PRIO,
264 		.encrypted_page = NULL,
265 	};
266 	bool submit_bio = false;
267 	int err = 0;
268 
269 	list_for_each_entry_safe(cur, tmp, &fi->inmem_pages, list) {
270 		struct page *page = cur->page;
271 
272 		lock_page(page);
273 		if (page->mapping == inode->i_mapping) {
274 			trace_f2fs_commit_inmem_page(page, INMEM);
275 
276 			set_page_dirty(page);
277 			f2fs_wait_on_page_writeback(page, DATA, true);
278 			if (clear_page_dirty_for_io(page)) {
279 				inode_dec_dirty_pages(inode);
280 				remove_dirty_inode(inode);
281 			}
282 
283 			fio.page = page;
284 			err = do_write_data_page(&fio);
285 			if (err) {
286 				unlock_page(page);
287 				break;
288 			}
289 
290 			/* record old blkaddr for revoking */
291 			cur->old_addr = fio.old_blkaddr;
292 
293 			clear_cold_data(page);
294 			submit_bio = true;
295 		}
296 		unlock_page(page);
297 		list_move_tail(&cur->list, revoke_list);
298 	}
299 
300 	if (submit_bio)
301 		f2fs_submit_merged_bio_cond(sbi, inode, NULL, 0, DATA, WRITE);
302 
303 	if (!err)
304 		__revoke_inmem_pages(inode, revoke_list, false, false);
305 
306 	return err;
307 }
308 
309 int commit_inmem_pages(struct inode *inode)
310 {
311 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
312 	struct f2fs_inode_info *fi = F2FS_I(inode);
313 	struct list_head revoke_list;
314 	int err;
315 
316 	INIT_LIST_HEAD(&revoke_list);
317 	f2fs_balance_fs(sbi, true);
318 	f2fs_lock_op(sbi);
319 
320 	mutex_lock(&fi->inmem_lock);
321 	err = __commit_inmem_pages(inode, &revoke_list);
322 	if (err) {
323 		int ret;
324 		/*
325 		 * try to revoke all committed pages, but still we could fail
326 		 * due to no memory or other reason, if that happened, EAGAIN
327 		 * will be returned, which means in such case, transaction is
328 		 * already not integrity, caller should use journal to do the
329 		 * recovery or rewrite & commit last transaction. For other
330 		 * error number, revoking was done by filesystem itself.
331 		 */
332 		ret = __revoke_inmem_pages(inode, &revoke_list, false, true);
333 		if (ret)
334 			err = ret;
335 
336 		/* drop all uncommitted pages */
337 		__revoke_inmem_pages(inode, &fi->inmem_pages, true, false);
338 	}
339 	mutex_unlock(&fi->inmem_lock);
340 
341 	f2fs_unlock_op(sbi);
342 	return err;
343 }
344 
345 /*
346  * This function balances dirty node and dentry pages.
347  * In addition, it controls garbage collection.
348  */
349 void f2fs_balance_fs(struct f2fs_sb_info *sbi, bool need)
350 {
351 #ifdef CONFIG_F2FS_FAULT_INJECTION
352 	if (time_to_inject(sbi, FAULT_CHECKPOINT))
353 		f2fs_stop_checkpoint(sbi, false);
354 #endif
355 
356 	if (!need)
357 		return;
358 
359 	/* balance_fs_bg is able to be pending */
360 	if (excess_cached_nats(sbi))
361 		f2fs_balance_fs_bg(sbi);
362 
363 	/*
364 	 * We should do GC or end up with checkpoint, if there are so many dirty
365 	 * dir/node pages without enough free segments.
366 	 */
367 	if (has_not_enough_free_secs(sbi, 0, 0)) {
368 		mutex_lock(&sbi->gc_mutex);
369 		f2fs_gc(sbi, false);
370 	}
371 }
372 
373 void f2fs_balance_fs_bg(struct f2fs_sb_info *sbi)
374 {
375 	/* try to shrink extent cache when there is no enough memory */
376 	if (!available_free_memory(sbi, EXTENT_CACHE))
377 		f2fs_shrink_extent_tree(sbi, EXTENT_CACHE_SHRINK_NUMBER);
378 
379 	/* check the # of cached NAT entries */
380 	if (!available_free_memory(sbi, NAT_ENTRIES))
381 		try_to_free_nats(sbi, NAT_ENTRY_PER_BLOCK);
382 
383 	if (!available_free_memory(sbi, FREE_NIDS))
384 		try_to_free_nids(sbi, MAX_FREE_NIDS);
385 	else
386 		build_free_nids(sbi, false);
387 
388 	/* checkpoint is the only way to shrink partial cached entries */
389 	if (!available_free_memory(sbi, NAT_ENTRIES) ||
390 			!available_free_memory(sbi, INO_ENTRIES) ||
391 			excess_prefree_segs(sbi) ||
392 			excess_dirty_nats(sbi) ||
393 			(is_idle(sbi) && f2fs_time_over(sbi, CP_TIME))) {
394 		if (test_opt(sbi, DATA_FLUSH)) {
395 			struct blk_plug plug;
396 
397 			blk_start_plug(&plug);
398 			sync_dirty_inodes(sbi, FILE_INODE);
399 			blk_finish_plug(&plug);
400 		}
401 		f2fs_sync_fs(sbi->sb, true);
402 		stat_inc_bg_cp_count(sbi->stat_info);
403 	}
404 }
405 
406 static int issue_flush_thread(void *data)
407 {
408 	struct f2fs_sb_info *sbi = data;
409 	struct flush_cmd_control *fcc = SM_I(sbi)->cmd_control_info;
410 	wait_queue_head_t *q = &fcc->flush_wait_queue;
411 repeat:
412 	if (kthread_should_stop())
413 		return 0;
414 
415 	if (!llist_empty(&fcc->issue_list)) {
416 		struct bio *bio;
417 		struct flush_cmd *cmd, *next;
418 		int ret;
419 
420 		bio = f2fs_bio_alloc(0);
421 
422 		fcc->dispatch_list = llist_del_all(&fcc->issue_list);
423 		fcc->dispatch_list = llist_reverse_order(fcc->dispatch_list);
424 
425 		bio->bi_bdev = sbi->sb->s_bdev;
426 		bio_set_op_attrs(bio, REQ_OP_WRITE, WRITE_FLUSH);
427 		ret = submit_bio_wait(bio);
428 
429 		llist_for_each_entry_safe(cmd, next,
430 					  fcc->dispatch_list, llnode) {
431 			cmd->ret = ret;
432 			complete(&cmd->wait);
433 		}
434 		bio_put(bio);
435 		fcc->dispatch_list = NULL;
436 	}
437 
438 	wait_event_interruptible(*q,
439 		kthread_should_stop() || !llist_empty(&fcc->issue_list));
440 	goto repeat;
441 }
442 
443 int f2fs_issue_flush(struct f2fs_sb_info *sbi)
444 {
445 	struct flush_cmd_control *fcc = SM_I(sbi)->cmd_control_info;
446 	struct flush_cmd cmd;
447 
448 	trace_f2fs_issue_flush(sbi->sb, test_opt(sbi, NOBARRIER),
449 					test_opt(sbi, FLUSH_MERGE));
450 
451 	if (test_opt(sbi, NOBARRIER))
452 		return 0;
453 
454 	if (!test_opt(sbi, FLUSH_MERGE) || !atomic_read(&fcc->submit_flush)) {
455 		struct bio *bio = f2fs_bio_alloc(0);
456 		int ret;
457 
458 		atomic_inc(&fcc->submit_flush);
459 		bio->bi_bdev = sbi->sb->s_bdev;
460 		bio_set_op_attrs(bio, REQ_OP_WRITE, WRITE_FLUSH);
461 		ret = submit_bio_wait(bio);
462 		atomic_dec(&fcc->submit_flush);
463 		bio_put(bio);
464 		return ret;
465 	}
466 
467 	init_completion(&cmd.wait);
468 
469 	atomic_inc(&fcc->submit_flush);
470 	llist_add(&cmd.llnode, &fcc->issue_list);
471 
472 	if (!fcc->dispatch_list)
473 		wake_up(&fcc->flush_wait_queue);
474 
475 	wait_for_completion(&cmd.wait);
476 	atomic_dec(&fcc->submit_flush);
477 
478 	return cmd.ret;
479 }
480 
481 int create_flush_cmd_control(struct f2fs_sb_info *sbi)
482 {
483 	dev_t dev = sbi->sb->s_bdev->bd_dev;
484 	struct flush_cmd_control *fcc;
485 	int err = 0;
486 
487 	fcc = kzalloc(sizeof(struct flush_cmd_control), GFP_KERNEL);
488 	if (!fcc)
489 		return -ENOMEM;
490 	atomic_set(&fcc->submit_flush, 0);
491 	init_waitqueue_head(&fcc->flush_wait_queue);
492 	init_llist_head(&fcc->issue_list);
493 	SM_I(sbi)->cmd_control_info = fcc;
494 	fcc->f2fs_issue_flush = kthread_run(issue_flush_thread, sbi,
495 				"f2fs_flush-%u:%u", MAJOR(dev), MINOR(dev));
496 	if (IS_ERR(fcc->f2fs_issue_flush)) {
497 		err = PTR_ERR(fcc->f2fs_issue_flush);
498 		kfree(fcc);
499 		SM_I(sbi)->cmd_control_info = NULL;
500 		return err;
501 	}
502 
503 	return err;
504 }
505 
506 void destroy_flush_cmd_control(struct f2fs_sb_info *sbi)
507 {
508 	struct flush_cmd_control *fcc = SM_I(sbi)->cmd_control_info;
509 
510 	if (fcc && fcc->f2fs_issue_flush)
511 		kthread_stop(fcc->f2fs_issue_flush);
512 	kfree(fcc);
513 	SM_I(sbi)->cmd_control_info = NULL;
514 }
515 
516 static void __locate_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno,
517 		enum dirty_type dirty_type)
518 {
519 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
520 
521 	/* need not be added */
522 	if (IS_CURSEG(sbi, segno))
523 		return;
524 
525 	if (!test_and_set_bit(segno, dirty_i->dirty_segmap[dirty_type]))
526 		dirty_i->nr_dirty[dirty_type]++;
527 
528 	if (dirty_type == DIRTY) {
529 		struct seg_entry *sentry = get_seg_entry(sbi, segno);
530 		enum dirty_type t = sentry->type;
531 
532 		if (unlikely(t >= DIRTY)) {
533 			f2fs_bug_on(sbi, 1);
534 			return;
535 		}
536 		if (!test_and_set_bit(segno, dirty_i->dirty_segmap[t]))
537 			dirty_i->nr_dirty[t]++;
538 	}
539 }
540 
541 static void __remove_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno,
542 		enum dirty_type dirty_type)
543 {
544 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
545 
546 	if (test_and_clear_bit(segno, dirty_i->dirty_segmap[dirty_type]))
547 		dirty_i->nr_dirty[dirty_type]--;
548 
549 	if (dirty_type == DIRTY) {
550 		struct seg_entry *sentry = get_seg_entry(sbi, segno);
551 		enum dirty_type t = sentry->type;
552 
553 		if (test_and_clear_bit(segno, dirty_i->dirty_segmap[t]))
554 			dirty_i->nr_dirty[t]--;
555 
556 		if (get_valid_blocks(sbi, segno, sbi->segs_per_sec) == 0)
557 			clear_bit(GET_SECNO(sbi, segno),
558 						dirty_i->victim_secmap);
559 	}
560 }
561 
562 /*
563  * Should not occur error such as -ENOMEM.
564  * Adding dirty entry into seglist is not critical operation.
565  * If a given segment is one of current working segments, it won't be added.
566  */
567 static void locate_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno)
568 {
569 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
570 	unsigned short valid_blocks;
571 
572 	if (segno == NULL_SEGNO || IS_CURSEG(sbi, segno))
573 		return;
574 
575 	mutex_lock(&dirty_i->seglist_lock);
576 
577 	valid_blocks = get_valid_blocks(sbi, segno, 0);
578 
579 	if (valid_blocks == 0) {
580 		__locate_dirty_segment(sbi, segno, PRE);
581 		__remove_dirty_segment(sbi, segno, DIRTY);
582 	} else if (valid_blocks < sbi->blocks_per_seg) {
583 		__locate_dirty_segment(sbi, segno, DIRTY);
584 	} else {
585 		/* Recovery routine with SSR needs this */
586 		__remove_dirty_segment(sbi, segno, DIRTY);
587 	}
588 
589 	mutex_unlock(&dirty_i->seglist_lock);
590 }
591 
592 static struct bio_entry *__add_bio_entry(struct f2fs_sb_info *sbi,
593 							struct bio *bio)
594 {
595 	struct list_head *wait_list = &(SM_I(sbi)->wait_list);
596 	struct bio_entry *be = f2fs_kmem_cache_alloc(bio_entry_slab, GFP_NOFS);
597 
598 	INIT_LIST_HEAD(&be->list);
599 	be->bio = bio;
600 	init_completion(&be->event);
601 	list_add_tail(&be->list, wait_list);
602 
603 	return be;
604 }
605 
606 void f2fs_wait_all_discard_bio(struct f2fs_sb_info *sbi)
607 {
608 	struct list_head *wait_list = &(SM_I(sbi)->wait_list);
609 	struct bio_entry *be, *tmp;
610 
611 	list_for_each_entry_safe(be, tmp, wait_list, list) {
612 		struct bio *bio = be->bio;
613 		int err;
614 
615 		wait_for_completion_io(&be->event);
616 		err = be->error;
617 		if (err == -EOPNOTSUPP)
618 			err = 0;
619 
620 		if (err)
621 			f2fs_msg(sbi->sb, KERN_INFO,
622 				"Issue discard failed, ret: %d", err);
623 
624 		bio_put(bio);
625 		list_del(&be->list);
626 		kmem_cache_free(bio_entry_slab, be);
627 	}
628 }
629 
630 static void f2fs_submit_bio_wait_endio(struct bio *bio)
631 {
632 	struct bio_entry *be = (struct bio_entry *)bio->bi_private;
633 
634 	be->error = bio->bi_error;
635 	complete(&be->event);
636 }
637 
638 /* this function is copied from blkdev_issue_discard from block/blk-lib.c */
639 static int __f2fs_issue_discard_async(struct f2fs_sb_info *sbi,
640 				block_t blkstart, block_t blklen)
641 {
642 	struct block_device *bdev = sbi->sb->s_bdev;
643 	struct bio *bio = NULL;
644 	int err;
645 
646 	trace_f2fs_issue_discard(sbi->sb, blkstart, blklen);
647 
648 	err = __blkdev_issue_discard(bdev,
649 				SECTOR_FROM_BLOCK(blkstart),
650 				SECTOR_FROM_BLOCK(blklen),
651 				GFP_NOFS, 0, &bio);
652 	if (!err && bio) {
653 		struct bio_entry *be = __add_bio_entry(sbi, bio);
654 
655 		bio->bi_private = be;
656 		bio->bi_end_io = f2fs_submit_bio_wait_endio;
657 		bio->bi_opf |= REQ_SYNC;
658 		submit_bio(bio);
659 	}
660 
661 	return err;
662 }
663 
664 #ifdef CONFIG_BLK_DEV_ZONED
665 static int f2fs_issue_discard_zone(struct f2fs_sb_info *sbi,
666 					block_t blkstart, block_t blklen)
667 {
668 	sector_t sector = SECTOR_FROM_BLOCK(blkstart);
669 	sector_t nr_sects = SECTOR_FROM_BLOCK(blklen);
670 	struct block_device *bdev = sbi->sb->s_bdev;
671 
672 	if (nr_sects != bdev_zone_size(bdev)) {
673 		f2fs_msg(sbi->sb, KERN_INFO,
674 			 "Unaligned discard attempted (sector %llu + %llu)",
675 			 (unsigned long long)sector,
676 			 (unsigned long long)nr_sects);
677 		return -EIO;
678 	}
679 
680 	/*
681 	 * We need to know the type of the zone: for conventional zones,
682 	 * use regular discard if the drive supports it. For sequential
683 	 * zones, reset the zone write pointer.
684 	 */
685 	switch (get_blkz_type(sbi, blkstart)) {
686 
687 	case BLK_ZONE_TYPE_CONVENTIONAL:
688 		if (!blk_queue_discard(bdev_get_queue(bdev)))
689 			return 0;
690 		return __f2fs_issue_discard_async(sbi, blkstart,
691 						  blklen);
692 
693 	case BLK_ZONE_TYPE_SEQWRITE_REQ:
694 	case BLK_ZONE_TYPE_SEQWRITE_PREF:
695 		trace_f2fs_issue_reset_zone(sbi->sb, blkstart);
696 		return blkdev_reset_zones(bdev, sector,
697 					  nr_sects, GFP_NOFS);
698 	default:
699 		/* Unknown zone type: broken device ? */
700 		return -EIO;
701 	}
702 }
703 #endif
704 
705 static int f2fs_issue_discard(struct f2fs_sb_info *sbi,
706 				block_t blkstart, block_t blklen)
707 {
708 	struct seg_entry *se;
709 	unsigned int offset;
710 	block_t i;
711 
712 	for (i = blkstart; i < blkstart + blklen; i++) {
713 		se = get_seg_entry(sbi, GET_SEGNO(sbi, i));
714 		offset = GET_BLKOFF_FROM_SEG0(sbi, i);
715 
716 		if (!f2fs_test_and_set_bit(offset, se->discard_map))
717 			sbi->discard_blks--;
718 	}
719 
720 #ifdef CONFIG_BLK_DEV_ZONED
721 	if (f2fs_sb_mounted_blkzoned(sbi->sb))
722 		return f2fs_issue_discard_zone(sbi, blkstart, blklen);
723 #endif
724 	return __f2fs_issue_discard_async(sbi, blkstart, blklen);
725 }
726 
727 static void __add_discard_entry(struct f2fs_sb_info *sbi,
728 		struct cp_control *cpc, struct seg_entry *se,
729 		unsigned int start, unsigned int end)
730 {
731 	struct list_head *head = &SM_I(sbi)->discard_list;
732 	struct discard_entry *new, *last;
733 
734 	if (!list_empty(head)) {
735 		last = list_last_entry(head, struct discard_entry, list);
736 		if (START_BLOCK(sbi, cpc->trim_start) + start ==
737 						last->blkaddr + last->len) {
738 			last->len += end - start;
739 			goto done;
740 		}
741 	}
742 
743 	new = f2fs_kmem_cache_alloc(discard_entry_slab, GFP_NOFS);
744 	INIT_LIST_HEAD(&new->list);
745 	new->blkaddr = START_BLOCK(sbi, cpc->trim_start) + start;
746 	new->len = end - start;
747 	list_add_tail(&new->list, head);
748 done:
749 	SM_I(sbi)->nr_discards += end - start;
750 }
751 
752 static void add_discard_addrs(struct f2fs_sb_info *sbi, struct cp_control *cpc)
753 {
754 	int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
755 	int max_blocks = sbi->blocks_per_seg;
756 	struct seg_entry *se = get_seg_entry(sbi, cpc->trim_start);
757 	unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
758 	unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
759 	unsigned long *discard_map = (unsigned long *)se->discard_map;
760 	unsigned long *dmap = SIT_I(sbi)->tmp_map;
761 	unsigned int start = 0, end = -1;
762 	bool force = (cpc->reason == CP_DISCARD);
763 	int i;
764 
765 	if (se->valid_blocks == max_blocks || !f2fs_discard_en(sbi))
766 		return;
767 
768 	if (!force) {
769 		if (!test_opt(sbi, DISCARD) || !se->valid_blocks ||
770 		    SM_I(sbi)->nr_discards >= SM_I(sbi)->max_discards)
771 			return;
772 	}
773 
774 	/* SIT_VBLOCK_MAP_SIZE should be multiple of sizeof(unsigned long) */
775 	for (i = 0; i < entries; i++)
776 		dmap[i] = force ? ~ckpt_map[i] & ~discard_map[i] :
777 				(cur_map[i] ^ ckpt_map[i]) & ckpt_map[i];
778 
779 	while (force || SM_I(sbi)->nr_discards <= SM_I(sbi)->max_discards) {
780 		start = __find_rev_next_bit(dmap, max_blocks, end + 1);
781 		if (start >= max_blocks)
782 			break;
783 
784 		end = __find_rev_next_zero_bit(dmap, max_blocks, start + 1);
785 		if (force && start && end != max_blocks
786 					&& (end - start) < cpc->trim_minlen)
787 			continue;
788 
789 		__add_discard_entry(sbi, cpc, se, start, end);
790 	}
791 }
792 
793 void release_discard_addrs(struct f2fs_sb_info *sbi)
794 {
795 	struct list_head *head = &(SM_I(sbi)->discard_list);
796 	struct discard_entry *entry, *this;
797 
798 	/* drop caches */
799 	list_for_each_entry_safe(entry, this, head, list) {
800 		list_del(&entry->list);
801 		kmem_cache_free(discard_entry_slab, entry);
802 	}
803 }
804 
805 /*
806  * Should call clear_prefree_segments after checkpoint is done.
807  */
808 static void set_prefree_as_free_segments(struct f2fs_sb_info *sbi)
809 {
810 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
811 	unsigned int segno;
812 
813 	mutex_lock(&dirty_i->seglist_lock);
814 	for_each_set_bit(segno, dirty_i->dirty_segmap[PRE], MAIN_SEGS(sbi))
815 		__set_test_and_free(sbi, segno);
816 	mutex_unlock(&dirty_i->seglist_lock);
817 }
818 
819 void clear_prefree_segments(struct f2fs_sb_info *sbi, struct cp_control *cpc)
820 {
821 	struct list_head *head = &(SM_I(sbi)->discard_list);
822 	struct discard_entry *entry, *this;
823 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
824 	struct blk_plug plug;
825 	unsigned long *prefree_map = dirty_i->dirty_segmap[PRE];
826 	unsigned int start = 0, end = -1;
827 	unsigned int secno, start_segno;
828 	bool force = (cpc->reason == CP_DISCARD);
829 
830 	blk_start_plug(&plug);
831 
832 	mutex_lock(&dirty_i->seglist_lock);
833 
834 	while (1) {
835 		int i;
836 		start = find_next_bit(prefree_map, MAIN_SEGS(sbi), end + 1);
837 		if (start >= MAIN_SEGS(sbi))
838 			break;
839 		end = find_next_zero_bit(prefree_map, MAIN_SEGS(sbi),
840 								start + 1);
841 
842 		for (i = start; i < end; i++)
843 			clear_bit(i, prefree_map);
844 
845 		dirty_i->nr_dirty[PRE] -= end - start;
846 
847 		if (force || !test_opt(sbi, DISCARD))
848 			continue;
849 
850 		if (!test_opt(sbi, LFS) || sbi->segs_per_sec == 1) {
851 			f2fs_issue_discard(sbi, START_BLOCK(sbi, start),
852 				(end - start) << sbi->log_blocks_per_seg);
853 			continue;
854 		}
855 next:
856 		secno = GET_SECNO(sbi, start);
857 		start_segno = secno * sbi->segs_per_sec;
858 		if (!IS_CURSEC(sbi, secno) &&
859 			!get_valid_blocks(sbi, start, sbi->segs_per_sec))
860 			f2fs_issue_discard(sbi, START_BLOCK(sbi, start_segno),
861 				sbi->segs_per_sec << sbi->log_blocks_per_seg);
862 
863 		start = start_segno + sbi->segs_per_sec;
864 		if (start < end)
865 			goto next;
866 	}
867 	mutex_unlock(&dirty_i->seglist_lock);
868 
869 	/* send small discards */
870 	list_for_each_entry_safe(entry, this, head, list) {
871 		if (force && entry->len < cpc->trim_minlen)
872 			goto skip;
873 		f2fs_issue_discard(sbi, entry->blkaddr, entry->len);
874 		cpc->trimmed += entry->len;
875 skip:
876 		list_del(&entry->list);
877 		SM_I(sbi)->nr_discards -= entry->len;
878 		kmem_cache_free(discard_entry_slab, entry);
879 	}
880 
881 	blk_finish_plug(&plug);
882 }
883 
884 static bool __mark_sit_entry_dirty(struct f2fs_sb_info *sbi, unsigned int segno)
885 {
886 	struct sit_info *sit_i = SIT_I(sbi);
887 
888 	if (!__test_and_set_bit(segno, sit_i->dirty_sentries_bitmap)) {
889 		sit_i->dirty_sentries++;
890 		return false;
891 	}
892 
893 	return true;
894 }
895 
896 static void __set_sit_entry_type(struct f2fs_sb_info *sbi, int type,
897 					unsigned int segno, int modified)
898 {
899 	struct seg_entry *se = get_seg_entry(sbi, segno);
900 	se->type = type;
901 	if (modified)
902 		__mark_sit_entry_dirty(sbi, segno);
903 }
904 
905 static void update_sit_entry(struct f2fs_sb_info *sbi, block_t blkaddr, int del)
906 {
907 	struct seg_entry *se;
908 	unsigned int segno, offset;
909 	long int new_vblocks;
910 
911 	segno = GET_SEGNO(sbi, blkaddr);
912 
913 	se = get_seg_entry(sbi, segno);
914 	new_vblocks = se->valid_blocks + del;
915 	offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
916 
917 	f2fs_bug_on(sbi, (new_vblocks >> (sizeof(unsigned short) << 3) ||
918 				(new_vblocks > sbi->blocks_per_seg)));
919 
920 	se->valid_blocks = new_vblocks;
921 	se->mtime = get_mtime(sbi);
922 	SIT_I(sbi)->max_mtime = se->mtime;
923 
924 	/* Update valid block bitmap */
925 	if (del > 0) {
926 		if (f2fs_test_and_set_bit(offset, se->cur_valid_map))
927 			f2fs_bug_on(sbi, 1);
928 		if (f2fs_discard_en(sbi) &&
929 			!f2fs_test_and_set_bit(offset, se->discard_map))
930 			sbi->discard_blks--;
931 	} else {
932 		if (!f2fs_test_and_clear_bit(offset, se->cur_valid_map))
933 			f2fs_bug_on(sbi, 1);
934 		if (f2fs_discard_en(sbi) &&
935 			f2fs_test_and_clear_bit(offset, se->discard_map))
936 			sbi->discard_blks++;
937 	}
938 	if (!f2fs_test_bit(offset, se->ckpt_valid_map))
939 		se->ckpt_valid_blocks += del;
940 
941 	__mark_sit_entry_dirty(sbi, segno);
942 
943 	/* update total number of valid blocks to be written in ckpt area */
944 	SIT_I(sbi)->written_valid_blocks += del;
945 
946 	if (sbi->segs_per_sec > 1)
947 		get_sec_entry(sbi, segno)->valid_blocks += del;
948 }
949 
950 void refresh_sit_entry(struct f2fs_sb_info *sbi, block_t old, block_t new)
951 {
952 	update_sit_entry(sbi, new, 1);
953 	if (GET_SEGNO(sbi, old) != NULL_SEGNO)
954 		update_sit_entry(sbi, old, -1);
955 
956 	locate_dirty_segment(sbi, GET_SEGNO(sbi, old));
957 	locate_dirty_segment(sbi, GET_SEGNO(sbi, new));
958 }
959 
960 void invalidate_blocks(struct f2fs_sb_info *sbi, block_t addr)
961 {
962 	unsigned int segno = GET_SEGNO(sbi, addr);
963 	struct sit_info *sit_i = SIT_I(sbi);
964 
965 	f2fs_bug_on(sbi, addr == NULL_ADDR);
966 	if (addr == NEW_ADDR)
967 		return;
968 
969 	/* add it into sit main buffer */
970 	mutex_lock(&sit_i->sentry_lock);
971 
972 	update_sit_entry(sbi, addr, -1);
973 
974 	/* add it into dirty seglist */
975 	locate_dirty_segment(sbi, segno);
976 
977 	mutex_unlock(&sit_i->sentry_lock);
978 }
979 
980 bool is_checkpointed_data(struct f2fs_sb_info *sbi, block_t blkaddr)
981 {
982 	struct sit_info *sit_i = SIT_I(sbi);
983 	unsigned int segno, offset;
984 	struct seg_entry *se;
985 	bool is_cp = false;
986 
987 	if (blkaddr == NEW_ADDR || blkaddr == NULL_ADDR)
988 		return true;
989 
990 	mutex_lock(&sit_i->sentry_lock);
991 
992 	segno = GET_SEGNO(sbi, blkaddr);
993 	se = get_seg_entry(sbi, segno);
994 	offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
995 
996 	if (f2fs_test_bit(offset, se->ckpt_valid_map))
997 		is_cp = true;
998 
999 	mutex_unlock(&sit_i->sentry_lock);
1000 
1001 	return is_cp;
1002 }
1003 
1004 /*
1005  * This function should be resided under the curseg_mutex lock
1006  */
1007 static void __add_sum_entry(struct f2fs_sb_info *sbi, int type,
1008 					struct f2fs_summary *sum)
1009 {
1010 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1011 	void *addr = curseg->sum_blk;
1012 	addr += curseg->next_blkoff * sizeof(struct f2fs_summary);
1013 	memcpy(addr, sum, sizeof(struct f2fs_summary));
1014 }
1015 
1016 /*
1017  * Calculate the number of current summary pages for writing
1018  */
1019 int npages_for_summary_flush(struct f2fs_sb_info *sbi, bool for_ra)
1020 {
1021 	int valid_sum_count = 0;
1022 	int i, sum_in_page;
1023 
1024 	for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
1025 		if (sbi->ckpt->alloc_type[i] == SSR)
1026 			valid_sum_count += sbi->blocks_per_seg;
1027 		else {
1028 			if (for_ra)
1029 				valid_sum_count += le16_to_cpu(
1030 					F2FS_CKPT(sbi)->cur_data_blkoff[i]);
1031 			else
1032 				valid_sum_count += curseg_blkoff(sbi, i);
1033 		}
1034 	}
1035 
1036 	sum_in_page = (PAGE_SIZE - 2 * SUM_JOURNAL_SIZE -
1037 			SUM_FOOTER_SIZE) / SUMMARY_SIZE;
1038 	if (valid_sum_count <= sum_in_page)
1039 		return 1;
1040 	else if ((valid_sum_count - sum_in_page) <=
1041 		(PAGE_SIZE - SUM_FOOTER_SIZE) / SUMMARY_SIZE)
1042 		return 2;
1043 	return 3;
1044 }
1045 
1046 /*
1047  * Caller should put this summary page
1048  */
1049 struct page *get_sum_page(struct f2fs_sb_info *sbi, unsigned int segno)
1050 {
1051 	return get_meta_page(sbi, GET_SUM_BLOCK(sbi, segno));
1052 }
1053 
1054 void update_meta_page(struct f2fs_sb_info *sbi, void *src, block_t blk_addr)
1055 {
1056 	struct page *page = grab_meta_page(sbi, blk_addr);
1057 	void *dst = page_address(page);
1058 
1059 	if (src)
1060 		memcpy(dst, src, PAGE_SIZE);
1061 	else
1062 		memset(dst, 0, PAGE_SIZE);
1063 	set_page_dirty(page);
1064 	f2fs_put_page(page, 1);
1065 }
1066 
1067 static void write_sum_page(struct f2fs_sb_info *sbi,
1068 			struct f2fs_summary_block *sum_blk, block_t blk_addr)
1069 {
1070 	update_meta_page(sbi, (void *)sum_blk, blk_addr);
1071 }
1072 
1073 static void write_current_sum_page(struct f2fs_sb_info *sbi,
1074 						int type, block_t blk_addr)
1075 {
1076 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1077 	struct page *page = grab_meta_page(sbi, blk_addr);
1078 	struct f2fs_summary_block *src = curseg->sum_blk;
1079 	struct f2fs_summary_block *dst;
1080 
1081 	dst = (struct f2fs_summary_block *)page_address(page);
1082 
1083 	mutex_lock(&curseg->curseg_mutex);
1084 
1085 	down_read(&curseg->journal_rwsem);
1086 	memcpy(&dst->journal, curseg->journal, SUM_JOURNAL_SIZE);
1087 	up_read(&curseg->journal_rwsem);
1088 
1089 	memcpy(dst->entries, src->entries, SUM_ENTRY_SIZE);
1090 	memcpy(&dst->footer, &src->footer, SUM_FOOTER_SIZE);
1091 
1092 	mutex_unlock(&curseg->curseg_mutex);
1093 
1094 	set_page_dirty(page);
1095 	f2fs_put_page(page, 1);
1096 }
1097 
1098 static int is_next_segment_free(struct f2fs_sb_info *sbi, int type)
1099 {
1100 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1101 	unsigned int segno = curseg->segno + 1;
1102 	struct free_segmap_info *free_i = FREE_I(sbi);
1103 
1104 	if (segno < MAIN_SEGS(sbi) && segno % sbi->segs_per_sec)
1105 		return !test_bit(segno, free_i->free_segmap);
1106 	return 0;
1107 }
1108 
1109 /*
1110  * Find a new segment from the free segments bitmap to right order
1111  * This function should be returned with success, otherwise BUG
1112  */
1113 static void get_new_segment(struct f2fs_sb_info *sbi,
1114 			unsigned int *newseg, bool new_sec, int dir)
1115 {
1116 	struct free_segmap_info *free_i = FREE_I(sbi);
1117 	unsigned int segno, secno, zoneno;
1118 	unsigned int total_zones = MAIN_SECS(sbi) / sbi->secs_per_zone;
1119 	unsigned int hint = *newseg / sbi->segs_per_sec;
1120 	unsigned int old_zoneno = GET_ZONENO_FROM_SEGNO(sbi, *newseg);
1121 	unsigned int left_start = hint;
1122 	bool init = true;
1123 	int go_left = 0;
1124 	int i;
1125 
1126 	spin_lock(&free_i->segmap_lock);
1127 
1128 	if (!new_sec && ((*newseg + 1) % sbi->segs_per_sec)) {
1129 		segno = find_next_zero_bit(free_i->free_segmap,
1130 				(hint + 1) * sbi->segs_per_sec, *newseg + 1);
1131 		if (segno < (hint + 1) * sbi->segs_per_sec)
1132 			goto got_it;
1133 	}
1134 find_other_zone:
1135 	secno = find_next_zero_bit(free_i->free_secmap, MAIN_SECS(sbi), hint);
1136 	if (secno >= MAIN_SECS(sbi)) {
1137 		if (dir == ALLOC_RIGHT) {
1138 			secno = find_next_zero_bit(free_i->free_secmap,
1139 							MAIN_SECS(sbi), 0);
1140 			f2fs_bug_on(sbi, secno >= MAIN_SECS(sbi));
1141 		} else {
1142 			go_left = 1;
1143 			left_start = hint - 1;
1144 		}
1145 	}
1146 	if (go_left == 0)
1147 		goto skip_left;
1148 
1149 	while (test_bit(left_start, free_i->free_secmap)) {
1150 		if (left_start > 0) {
1151 			left_start--;
1152 			continue;
1153 		}
1154 		left_start = find_next_zero_bit(free_i->free_secmap,
1155 							MAIN_SECS(sbi), 0);
1156 		f2fs_bug_on(sbi, left_start >= MAIN_SECS(sbi));
1157 		break;
1158 	}
1159 	secno = left_start;
1160 skip_left:
1161 	hint = secno;
1162 	segno = secno * sbi->segs_per_sec;
1163 	zoneno = secno / sbi->secs_per_zone;
1164 
1165 	/* give up on finding another zone */
1166 	if (!init)
1167 		goto got_it;
1168 	if (sbi->secs_per_zone == 1)
1169 		goto got_it;
1170 	if (zoneno == old_zoneno)
1171 		goto got_it;
1172 	if (dir == ALLOC_LEFT) {
1173 		if (!go_left && zoneno + 1 >= total_zones)
1174 			goto got_it;
1175 		if (go_left && zoneno == 0)
1176 			goto got_it;
1177 	}
1178 	for (i = 0; i < NR_CURSEG_TYPE; i++)
1179 		if (CURSEG_I(sbi, i)->zone == zoneno)
1180 			break;
1181 
1182 	if (i < NR_CURSEG_TYPE) {
1183 		/* zone is in user, try another */
1184 		if (go_left)
1185 			hint = zoneno * sbi->secs_per_zone - 1;
1186 		else if (zoneno + 1 >= total_zones)
1187 			hint = 0;
1188 		else
1189 			hint = (zoneno + 1) * sbi->secs_per_zone;
1190 		init = false;
1191 		goto find_other_zone;
1192 	}
1193 got_it:
1194 	/* set it as dirty segment in free segmap */
1195 	f2fs_bug_on(sbi, test_bit(segno, free_i->free_segmap));
1196 	__set_inuse(sbi, segno);
1197 	*newseg = segno;
1198 	spin_unlock(&free_i->segmap_lock);
1199 }
1200 
1201 static void reset_curseg(struct f2fs_sb_info *sbi, int type, int modified)
1202 {
1203 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1204 	struct summary_footer *sum_footer;
1205 
1206 	curseg->segno = curseg->next_segno;
1207 	curseg->zone = GET_ZONENO_FROM_SEGNO(sbi, curseg->segno);
1208 	curseg->next_blkoff = 0;
1209 	curseg->next_segno = NULL_SEGNO;
1210 
1211 	sum_footer = &(curseg->sum_blk->footer);
1212 	memset(sum_footer, 0, sizeof(struct summary_footer));
1213 	if (IS_DATASEG(type))
1214 		SET_SUM_TYPE(sum_footer, SUM_TYPE_DATA);
1215 	if (IS_NODESEG(type))
1216 		SET_SUM_TYPE(sum_footer, SUM_TYPE_NODE);
1217 	__set_sit_entry_type(sbi, type, curseg->segno, modified);
1218 }
1219 
1220 /*
1221  * Allocate a current working segment.
1222  * This function always allocates a free segment in LFS manner.
1223  */
1224 static void new_curseg(struct f2fs_sb_info *sbi, int type, bool new_sec)
1225 {
1226 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1227 	unsigned int segno = curseg->segno;
1228 	int dir = ALLOC_LEFT;
1229 
1230 	write_sum_page(sbi, curseg->sum_blk,
1231 				GET_SUM_BLOCK(sbi, segno));
1232 	if (type == CURSEG_WARM_DATA || type == CURSEG_COLD_DATA)
1233 		dir = ALLOC_RIGHT;
1234 
1235 	if (test_opt(sbi, NOHEAP))
1236 		dir = ALLOC_RIGHT;
1237 
1238 	get_new_segment(sbi, &segno, new_sec, dir);
1239 	curseg->next_segno = segno;
1240 	reset_curseg(sbi, type, 1);
1241 	curseg->alloc_type = LFS;
1242 }
1243 
1244 static void __next_free_blkoff(struct f2fs_sb_info *sbi,
1245 			struct curseg_info *seg, block_t start)
1246 {
1247 	struct seg_entry *se = get_seg_entry(sbi, seg->segno);
1248 	int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
1249 	unsigned long *target_map = SIT_I(sbi)->tmp_map;
1250 	unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
1251 	unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
1252 	int i, pos;
1253 
1254 	for (i = 0; i < entries; i++)
1255 		target_map[i] = ckpt_map[i] | cur_map[i];
1256 
1257 	pos = __find_rev_next_zero_bit(target_map, sbi->blocks_per_seg, start);
1258 
1259 	seg->next_blkoff = pos;
1260 }
1261 
1262 /*
1263  * If a segment is written by LFS manner, next block offset is just obtained
1264  * by increasing the current block offset. However, if a segment is written by
1265  * SSR manner, next block offset obtained by calling __next_free_blkoff
1266  */
1267 static void __refresh_next_blkoff(struct f2fs_sb_info *sbi,
1268 				struct curseg_info *seg)
1269 {
1270 	if (seg->alloc_type == SSR)
1271 		__next_free_blkoff(sbi, seg, seg->next_blkoff + 1);
1272 	else
1273 		seg->next_blkoff++;
1274 }
1275 
1276 /*
1277  * This function always allocates a used segment(from dirty seglist) by SSR
1278  * manner, so it should recover the existing segment information of valid blocks
1279  */
1280 static void change_curseg(struct f2fs_sb_info *sbi, int type, bool reuse)
1281 {
1282 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
1283 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1284 	unsigned int new_segno = curseg->next_segno;
1285 	struct f2fs_summary_block *sum_node;
1286 	struct page *sum_page;
1287 
1288 	write_sum_page(sbi, curseg->sum_blk,
1289 				GET_SUM_BLOCK(sbi, curseg->segno));
1290 	__set_test_and_inuse(sbi, new_segno);
1291 
1292 	mutex_lock(&dirty_i->seglist_lock);
1293 	__remove_dirty_segment(sbi, new_segno, PRE);
1294 	__remove_dirty_segment(sbi, new_segno, DIRTY);
1295 	mutex_unlock(&dirty_i->seglist_lock);
1296 
1297 	reset_curseg(sbi, type, 1);
1298 	curseg->alloc_type = SSR;
1299 	__next_free_blkoff(sbi, curseg, 0);
1300 
1301 	if (reuse) {
1302 		sum_page = get_sum_page(sbi, new_segno);
1303 		sum_node = (struct f2fs_summary_block *)page_address(sum_page);
1304 		memcpy(curseg->sum_blk, sum_node, SUM_ENTRY_SIZE);
1305 		f2fs_put_page(sum_page, 1);
1306 	}
1307 }
1308 
1309 static int get_ssr_segment(struct f2fs_sb_info *sbi, int type)
1310 {
1311 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1312 	const struct victim_selection *v_ops = DIRTY_I(sbi)->v_ops;
1313 
1314 	if (IS_NODESEG(type) || !has_not_enough_free_secs(sbi, 0, 0))
1315 		return v_ops->get_victim(sbi,
1316 				&(curseg)->next_segno, BG_GC, type, SSR);
1317 
1318 	/* For data segments, let's do SSR more intensively */
1319 	for (; type >= CURSEG_HOT_DATA; type--)
1320 		if (v_ops->get_victim(sbi, &(curseg)->next_segno,
1321 						BG_GC, type, SSR))
1322 			return 1;
1323 	return 0;
1324 }
1325 
1326 /*
1327  * flush out current segment and replace it with new segment
1328  * This function should be returned with success, otherwise BUG
1329  */
1330 static void allocate_segment_by_default(struct f2fs_sb_info *sbi,
1331 						int type, bool force)
1332 {
1333 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1334 
1335 	if (force)
1336 		new_curseg(sbi, type, true);
1337 	else if (type == CURSEG_WARM_NODE)
1338 		new_curseg(sbi, type, false);
1339 	else if (curseg->alloc_type == LFS && is_next_segment_free(sbi, type))
1340 		new_curseg(sbi, type, false);
1341 	else if (need_SSR(sbi) && get_ssr_segment(sbi, type))
1342 		change_curseg(sbi, type, true);
1343 	else
1344 		new_curseg(sbi, type, false);
1345 
1346 	stat_inc_seg_type(sbi, curseg);
1347 }
1348 
1349 void allocate_new_segments(struct f2fs_sb_info *sbi)
1350 {
1351 	struct curseg_info *curseg;
1352 	unsigned int old_segno;
1353 	int i;
1354 
1355 	if (test_opt(sbi, LFS))
1356 		return;
1357 
1358 	for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
1359 		curseg = CURSEG_I(sbi, i);
1360 		old_segno = curseg->segno;
1361 		SIT_I(sbi)->s_ops->allocate_segment(sbi, i, true);
1362 		locate_dirty_segment(sbi, old_segno);
1363 	}
1364 }
1365 
1366 static const struct segment_allocation default_salloc_ops = {
1367 	.allocate_segment = allocate_segment_by_default,
1368 };
1369 
1370 int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range)
1371 {
1372 	__u64 start = F2FS_BYTES_TO_BLK(range->start);
1373 	__u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1;
1374 	unsigned int start_segno, end_segno;
1375 	struct cp_control cpc;
1376 	int err = 0;
1377 
1378 	if (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize)
1379 		return -EINVAL;
1380 
1381 	cpc.trimmed = 0;
1382 	if (end <= MAIN_BLKADDR(sbi))
1383 		goto out;
1384 
1385 	if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) {
1386 		f2fs_msg(sbi->sb, KERN_WARNING,
1387 			"Found FS corruption, run fsck to fix.");
1388 		goto out;
1389 	}
1390 
1391 	/* start/end segment number in main_area */
1392 	start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start);
1393 	end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 :
1394 						GET_SEGNO(sbi, end);
1395 	cpc.reason = CP_DISCARD;
1396 	cpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen));
1397 
1398 	/* do checkpoint to issue discard commands safely */
1399 	for (; start_segno <= end_segno; start_segno = cpc.trim_end + 1) {
1400 		cpc.trim_start = start_segno;
1401 
1402 		if (sbi->discard_blks == 0)
1403 			break;
1404 		else if (sbi->discard_blks < BATCHED_TRIM_BLOCKS(sbi))
1405 			cpc.trim_end = end_segno;
1406 		else
1407 			cpc.trim_end = min_t(unsigned int,
1408 				rounddown(start_segno +
1409 				BATCHED_TRIM_SEGMENTS(sbi),
1410 				sbi->segs_per_sec) - 1, end_segno);
1411 
1412 		mutex_lock(&sbi->gc_mutex);
1413 		err = write_checkpoint(sbi, &cpc);
1414 		mutex_unlock(&sbi->gc_mutex);
1415 		if (err)
1416 			break;
1417 
1418 		schedule();
1419 	}
1420 out:
1421 	range->len = F2FS_BLK_TO_BYTES(cpc.trimmed);
1422 	return err;
1423 }
1424 
1425 static bool __has_curseg_space(struct f2fs_sb_info *sbi, int type)
1426 {
1427 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1428 	if (curseg->next_blkoff < sbi->blocks_per_seg)
1429 		return true;
1430 	return false;
1431 }
1432 
1433 static int __get_segment_type_2(struct page *page, enum page_type p_type)
1434 {
1435 	if (p_type == DATA)
1436 		return CURSEG_HOT_DATA;
1437 	else
1438 		return CURSEG_HOT_NODE;
1439 }
1440 
1441 static int __get_segment_type_4(struct page *page, enum page_type p_type)
1442 {
1443 	if (p_type == DATA) {
1444 		struct inode *inode = page->mapping->host;
1445 
1446 		if (S_ISDIR(inode->i_mode))
1447 			return CURSEG_HOT_DATA;
1448 		else
1449 			return CURSEG_COLD_DATA;
1450 	} else {
1451 		if (IS_DNODE(page) && is_cold_node(page))
1452 			return CURSEG_WARM_NODE;
1453 		else
1454 			return CURSEG_COLD_NODE;
1455 	}
1456 }
1457 
1458 static int __get_segment_type_6(struct page *page, enum page_type p_type)
1459 {
1460 	if (p_type == DATA) {
1461 		struct inode *inode = page->mapping->host;
1462 
1463 		if (S_ISDIR(inode->i_mode))
1464 			return CURSEG_HOT_DATA;
1465 		else if (is_cold_data(page) || file_is_cold(inode))
1466 			return CURSEG_COLD_DATA;
1467 		else
1468 			return CURSEG_WARM_DATA;
1469 	} else {
1470 		if (IS_DNODE(page))
1471 			return is_cold_node(page) ? CURSEG_WARM_NODE :
1472 						CURSEG_HOT_NODE;
1473 		else
1474 			return CURSEG_COLD_NODE;
1475 	}
1476 }
1477 
1478 static int __get_segment_type(struct page *page, enum page_type p_type)
1479 {
1480 	switch (F2FS_P_SB(page)->active_logs) {
1481 	case 2:
1482 		return __get_segment_type_2(page, p_type);
1483 	case 4:
1484 		return __get_segment_type_4(page, p_type);
1485 	}
1486 	/* NR_CURSEG_TYPE(6) logs by default */
1487 	f2fs_bug_on(F2FS_P_SB(page),
1488 		F2FS_P_SB(page)->active_logs != NR_CURSEG_TYPE);
1489 	return __get_segment_type_6(page, p_type);
1490 }
1491 
1492 void allocate_data_block(struct f2fs_sb_info *sbi, struct page *page,
1493 		block_t old_blkaddr, block_t *new_blkaddr,
1494 		struct f2fs_summary *sum, int type)
1495 {
1496 	struct sit_info *sit_i = SIT_I(sbi);
1497 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1498 
1499 	mutex_lock(&curseg->curseg_mutex);
1500 	mutex_lock(&sit_i->sentry_lock);
1501 
1502 	*new_blkaddr = NEXT_FREE_BLKADDR(sbi, curseg);
1503 
1504 	/*
1505 	 * __add_sum_entry should be resided under the curseg_mutex
1506 	 * because, this function updates a summary entry in the
1507 	 * current summary block.
1508 	 */
1509 	__add_sum_entry(sbi, type, sum);
1510 
1511 	__refresh_next_blkoff(sbi, curseg);
1512 
1513 	stat_inc_block_count(sbi, curseg);
1514 
1515 	if (!__has_curseg_space(sbi, type))
1516 		sit_i->s_ops->allocate_segment(sbi, type, false);
1517 	/*
1518 	 * SIT information should be updated before segment allocation,
1519 	 * since SSR needs latest valid block information.
1520 	 */
1521 	refresh_sit_entry(sbi, old_blkaddr, *new_blkaddr);
1522 
1523 	mutex_unlock(&sit_i->sentry_lock);
1524 
1525 	if (page && IS_NODESEG(type))
1526 		fill_node_footer_blkaddr(page, NEXT_FREE_BLKADDR(sbi, curseg));
1527 
1528 	mutex_unlock(&curseg->curseg_mutex);
1529 }
1530 
1531 static void do_write_page(struct f2fs_summary *sum, struct f2fs_io_info *fio)
1532 {
1533 	int type = __get_segment_type(fio->page, fio->type);
1534 
1535 	if (fio->type == NODE || fio->type == DATA)
1536 		mutex_lock(&fio->sbi->wio_mutex[fio->type]);
1537 
1538 	allocate_data_block(fio->sbi, fio->page, fio->old_blkaddr,
1539 					&fio->new_blkaddr, sum, type);
1540 
1541 	/* writeout dirty page into bdev */
1542 	f2fs_submit_page_mbio(fio);
1543 
1544 	if (fio->type == NODE || fio->type == DATA)
1545 		mutex_unlock(&fio->sbi->wio_mutex[fio->type]);
1546 }
1547 
1548 void write_meta_page(struct f2fs_sb_info *sbi, struct page *page)
1549 {
1550 	struct f2fs_io_info fio = {
1551 		.sbi = sbi,
1552 		.type = META,
1553 		.op = REQ_OP_WRITE,
1554 		.op_flags = WRITE_SYNC | REQ_META | REQ_PRIO,
1555 		.old_blkaddr = page->index,
1556 		.new_blkaddr = page->index,
1557 		.page = page,
1558 		.encrypted_page = NULL,
1559 	};
1560 
1561 	if (unlikely(page->index >= MAIN_BLKADDR(sbi)))
1562 		fio.op_flags &= ~REQ_META;
1563 
1564 	set_page_writeback(page);
1565 	f2fs_submit_page_mbio(&fio);
1566 }
1567 
1568 void write_node_page(unsigned int nid, struct f2fs_io_info *fio)
1569 {
1570 	struct f2fs_summary sum;
1571 
1572 	set_summary(&sum, nid, 0, 0);
1573 	do_write_page(&sum, fio);
1574 }
1575 
1576 void write_data_page(struct dnode_of_data *dn, struct f2fs_io_info *fio)
1577 {
1578 	struct f2fs_sb_info *sbi = fio->sbi;
1579 	struct f2fs_summary sum;
1580 	struct node_info ni;
1581 
1582 	f2fs_bug_on(sbi, dn->data_blkaddr == NULL_ADDR);
1583 	get_node_info(sbi, dn->nid, &ni);
1584 	set_summary(&sum, dn->nid, dn->ofs_in_node, ni.version);
1585 	do_write_page(&sum, fio);
1586 	f2fs_update_data_blkaddr(dn, fio->new_blkaddr);
1587 }
1588 
1589 void rewrite_data_page(struct f2fs_io_info *fio)
1590 {
1591 	fio->new_blkaddr = fio->old_blkaddr;
1592 	stat_inc_inplace_blocks(fio->sbi);
1593 	f2fs_submit_page_mbio(fio);
1594 }
1595 
1596 void __f2fs_replace_block(struct f2fs_sb_info *sbi, struct f2fs_summary *sum,
1597 				block_t old_blkaddr, block_t new_blkaddr,
1598 				bool recover_curseg, bool recover_newaddr)
1599 {
1600 	struct sit_info *sit_i = SIT_I(sbi);
1601 	struct curseg_info *curseg;
1602 	unsigned int segno, old_cursegno;
1603 	struct seg_entry *se;
1604 	int type;
1605 	unsigned short old_blkoff;
1606 
1607 	segno = GET_SEGNO(sbi, new_blkaddr);
1608 	se = get_seg_entry(sbi, segno);
1609 	type = se->type;
1610 
1611 	if (!recover_curseg) {
1612 		/* for recovery flow */
1613 		if (se->valid_blocks == 0 && !IS_CURSEG(sbi, segno)) {
1614 			if (old_blkaddr == NULL_ADDR)
1615 				type = CURSEG_COLD_DATA;
1616 			else
1617 				type = CURSEG_WARM_DATA;
1618 		}
1619 	} else {
1620 		if (!IS_CURSEG(sbi, segno))
1621 			type = CURSEG_WARM_DATA;
1622 	}
1623 
1624 	curseg = CURSEG_I(sbi, type);
1625 
1626 	mutex_lock(&curseg->curseg_mutex);
1627 	mutex_lock(&sit_i->sentry_lock);
1628 
1629 	old_cursegno = curseg->segno;
1630 	old_blkoff = curseg->next_blkoff;
1631 
1632 	/* change the current segment */
1633 	if (segno != curseg->segno) {
1634 		curseg->next_segno = segno;
1635 		change_curseg(sbi, type, true);
1636 	}
1637 
1638 	curseg->next_blkoff = GET_BLKOFF_FROM_SEG0(sbi, new_blkaddr);
1639 	__add_sum_entry(sbi, type, sum);
1640 
1641 	if (!recover_curseg || recover_newaddr)
1642 		update_sit_entry(sbi, new_blkaddr, 1);
1643 	if (GET_SEGNO(sbi, old_blkaddr) != NULL_SEGNO)
1644 		update_sit_entry(sbi, old_blkaddr, -1);
1645 
1646 	locate_dirty_segment(sbi, GET_SEGNO(sbi, old_blkaddr));
1647 	locate_dirty_segment(sbi, GET_SEGNO(sbi, new_blkaddr));
1648 
1649 	locate_dirty_segment(sbi, old_cursegno);
1650 
1651 	if (recover_curseg) {
1652 		if (old_cursegno != curseg->segno) {
1653 			curseg->next_segno = old_cursegno;
1654 			change_curseg(sbi, type, true);
1655 		}
1656 		curseg->next_blkoff = old_blkoff;
1657 	}
1658 
1659 	mutex_unlock(&sit_i->sentry_lock);
1660 	mutex_unlock(&curseg->curseg_mutex);
1661 }
1662 
1663 void f2fs_replace_block(struct f2fs_sb_info *sbi, struct dnode_of_data *dn,
1664 				block_t old_addr, block_t new_addr,
1665 				unsigned char version, bool recover_curseg,
1666 				bool recover_newaddr)
1667 {
1668 	struct f2fs_summary sum;
1669 
1670 	set_summary(&sum, dn->nid, dn->ofs_in_node, version);
1671 
1672 	__f2fs_replace_block(sbi, &sum, old_addr, new_addr,
1673 					recover_curseg, recover_newaddr);
1674 
1675 	f2fs_update_data_blkaddr(dn, new_addr);
1676 }
1677 
1678 void f2fs_wait_on_page_writeback(struct page *page,
1679 				enum page_type type, bool ordered)
1680 {
1681 	if (PageWriteback(page)) {
1682 		struct f2fs_sb_info *sbi = F2FS_P_SB(page);
1683 
1684 		f2fs_submit_merged_bio_cond(sbi, NULL, page, 0, type, WRITE);
1685 		if (ordered)
1686 			wait_on_page_writeback(page);
1687 		else
1688 			wait_for_stable_page(page);
1689 	}
1690 }
1691 
1692 void f2fs_wait_on_encrypted_page_writeback(struct f2fs_sb_info *sbi,
1693 							block_t blkaddr)
1694 {
1695 	struct page *cpage;
1696 
1697 	if (blkaddr == NEW_ADDR || blkaddr == NULL_ADDR)
1698 		return;
1699 
1700 	cpage = find_lock_page(META_MAPPING(sbi), blkaddr);
1701 	if (cpage) {
1702 		f2fs_wait_on_page_writeback(cpage, DATA, true);
1703 		f2fs_put_page(cpage, 1);
1704 	}
1705 }
1706 
1707 static int read_compacted_summaries(struct f2fs_sb_info *sbi)
1708 {
1709 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
1710 	struct curseg_info *seg_i;
1711 	unsigned char *kaddr;
1712 	struct page *page;
1713 	block_t start;
1714 	int i, j, offset;
1715 
1716 	start = start_sum_block(sbi);
1717 
1718 	page = get_meta_page(sbi, start++);
1719 	kaddr = (unsigned char *)page_address(page);
1720 
1721 	/* Step 1: restore nat cache */
1722 	seg_i = CURSEG_I(sbi, CURSEG_HOT_DATA);
1723 	memcpy(seg_i->journal, kaddr, SUM_JOURNAL_SIZE);
1724 
1725 	/* Step 2: restore sit cache */
1726 	seg_i = CURSEG_I(sbi, CURSEG_COLD_DATA);
1727 	memcpy(seg_i->journal, kaddr + SUM_JOURNAL_SIZE, SUM_JOURNAL_SIZE);
1728 	offset = 2 * SUM_JOURNAL_SIZE;
1729 
1730 	/* Step 3: restore summary entries */
1731 	for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
1732 		unsigned short blk_off;
1733 		unsigned int segno;
1734 
1735 		seg_i = CURSEG_I(sbi, i);
1736 		segno = le32_to_cpu(ckpt->cur_data_segno[i]);
1737 		blk_off = le16_to_cpu(ckpt->cur_data_blkoff[i]);
1738 		seg_i->next_segno = segno;
1739 		reset_curseg(sbi, i, 0);
1740 		seg_i->alloc_type = ckpt->alloc_type[i];
1741 		seg_i->next_blkoff = blk_off;
1742 
1743 		if (seg_i->alloc_type == SSR)
1744 			blk_off = sbi->blocks_per_seg;
1745 
1746 		for (j = 0; j < blk_off; j++) {
1747 			struct f2fs_summary *s;
1748 			s = (struct f2fs_summary *)(kaddr + offset);
1749 			seg_i->sum_blk->entries[j] = *s;
1750 			offset += SUMMARY_SIZE;
1751 			if (offset + SUMMARY_SIZE <= PAGE_SIZE -
1752 						SUM_FOOTER_SIZE)
1753 				continue;
1754 
1755 			f2fs_put_page(page, 1);
1756 			page = NULL;
1757 
1758 			page = get_meta_page(sbi, start++);
1759 			kaddr = (unsigned char *)page_address(page);
1760 			offset = 0;
1761 		}
1762 	}
1763 	f2fs_put_page(page, 1);
1764 	return 0;
1765 }
1766 
1767 static int read_normal_summaries(struct f2fs_sb_info *sbi, int type)
1768 {
1769 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
1770 	struct f2fs_summary_block *sum;
1771 	struct curseg_info *curseg;
1772 	struct page *new;
1773 	unsigned short blk_off;
1774 	unsigned int segno = 0;
1775 	block_t blk_addr = 0;
1776 
1777 	/* get segment number and block addr */
1778 	if (IS_DATASEG(type)) {
1779 		segno = le32_to_cpu(ckpt->cur_data_segno[type]);
1780 		blk_off = le16_to_cpu(ckpt->cur_data_blkoff[type -
1781 							CURSEG_HOT_DATA]);
1782 		if (__exist_node_summaries(sbi))
1783 			blk_addr = sum_blk_addr(sbi, NR_CURSEG_TYPE, type);
1784 		else
1785 			blk_addr = sum_blk_addr(sbi, NR_CURSEG_DATA_TYPE, type);
1786 	} else {
1787 		segno = le32_to_cpu(ckpt->cur_node_segno[type -
1788 							CURSEG_HOT_NODE]);
1789 		blk_off = le16_to_cpu(ckpt->cur_node_blkoff[type -
1790 							CURSEG_HOT_NODE]);
1791 		if (__exist_node_summaries(sbi))
1792 			blk_addr = sum_blk_addr(sbi, NR_CURSEG_NODE_TYPE,
1793 							type - CURSEG_HOT_NODE);
1794 		else
1795 			blk_addr = GET_SUM_BLOCK(sbi, segno);
1796 	}
1797 
1798 	new = get_meta_page(sbi, blk_addr);
1799 	sum = (struct f2fs_summary_block *)page_address(new);
1800 
1801 	if (IS_NODESEG(type)) {
1802 		if (__exist_node_summaries(sbi)) {
1803 			struct f2fs_summary *ns = &sum->entries[0];
1804 			int i;
1805 			for (i = 0; i < sbi->blocks_per_seg; i++, ns++) {
1806 				ns->version = 0;
1807 				ns->ofs_in_node = 0;
1808 			}
1809 		} else {
1810 			int err;
1811 
1812 			err = restore_node_summary(sbi, segno, sum);
1813 			if (err) {
1814 				f2fs_put_page(new, 1);
1815 				return err;
1816 			}
1817 		}
1818 	}
1819 
1820 	/* set uncompleted segment to curseg */
1821 	curseg = CURSEG_I(sbi, type);
1822 	mutex_lock(&curseg->curseg_mutex);
1823 
1824 	/* update journal info */
1825 	down_write(&curseg->journal_rwsem);
1826 	memcpy(curseg->journal, &sum->journal, SUM_JOURNAL_SIZE);
1827 	up_write(&curseg->journal_rwsem);
1828 
1829 	memcpy(curseg->sum_blk->entries, sum->entries, SUM_ENTRY_SIZE);
1830 	memcpy(&curseg->sum_blk->footer, &sum->footer, SUM_FOOTER_SIZE);
1831 	curseg->next_segno = segno;
1832 	reset_curseg(sbi, type, 0);
1833 	curseg->alloc_type = ckpt->alloc_type[type];
1834 	curseg->next_blkoff = blk_off;
1835 	mutex_unlock(&curseg->curseg_mutex);
1836 	f2fs_put_page(new, 1);
1837 	return 0;
1838 }
1839 
1840 static int restore_curseg_summaries(struct f2fs_sb_info *sbi)
1841 {
1842 	int type = CURSEG_HOT_DATA;
1843 	int err;
1844 
1845 	if (is_set_ckpt_flags(sbi, CP_COMPACT_SUM_FLAG)) {
1846 		int npages = npages_for_summary_flush(sbi, true);
1847 
1848 		if (npages >= 2)
1849 			ra_meta_pages(sbi, start_sum_block(sbi), npages,
1850 							META_CP, true);
1851 
1852 		/* restore for compacted data summary */
1853 		if (read_compacted_summaries(sbi))
1854 			return -EINVAL;
1855 		type = CURSEG_HOT_NODE;
1856 	}
1857 
1858 	if (__exist_node_summaries(sbi))
1859 		ra_meta_pages(sbi, sum_blk_addr(sbi, NR_CURSEG_TYPE, type),
1860 					NR_CURSEG_TYPE - type, META_CP, true);
1861 
1862 	for (; type <= CURSEG_COLD_NODE; type++) {
1863 		err = read_normal_summaries(sbi, type);
1864 		if (err)
1865 			return err;
1866 	}
1867 
1868 	return 0;
1869 }
1870 
1871 static void write_compacted_summaries(struct f2fs_sb_info *sbi, block_t blkaddr)
1872 {
1873 	struct page *page;
1874 	unsigned char *kaddr;
1875 	struct f2fs_summary *summary;
1876 	struct curseg_info *seg_i;
1877 	int written_size = 0;
1878 	int i, j;
1879 
1880 	page = grab_meta_page(sbi, blkaddr++);
1881 	kaddr = (unsigned char *)page_address(page);
1882 
1883 	/* Step 1: write nat cache */
1884 	seg_i = CURSEG_I(sbi, CURSEG_HOT_DATA);
1885 	memcpy(kaddr, seg_i->journal, SUM_JOURNAL_SIZE);
1886 	written_size += SUM_JOURNAL_SIZE;
1887 
1888 	/* Step 2: write sit cache */
1889 	seg_i = CURSEG_I(sbi, CURSEG_COLD_DATA);
1890 	memcpy(kaddr + written_size, seg_i->journal, SUM_JOURNAL_SIZE);
1891 	written_size += SUM_JOURNAL_SIZE;
1892 
1893 	/* Step 3: write summary entries */
1894 	for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
1895 		unsigned short blkoff;
1896 		seg_i = CURSEG_I(sbi, i);
1897 		if (sbi->ckpt->alloc_type[i] == SSR)
1898 			blkoff = sbi->blocks_per_seg;
1899 		else
1900 			blkoff = curseg_blkoff(sbi, i);
1901 
1902 		for (j = 0; j < blkoff; j++) {
1903 			if (!page) {
1904 				page = grab_meta_page(sbi, blkaddr++);
1905 				kaddr = (unsigned char *)page_address(page);
1906 				written_size = 0;
1907 			}
1908 			summary = (struct f2fs_summary *)(kaddr + written_size);
1909 			*summary = seg_i->sum_blk->entries[j];
1910 			written_size += SUMMARY_SIZE;
1911 
1912 			if (written_size + SUMMARY_SIZE <= PAGE_SIZE -
1913 							SUM_FOOTER_SIZE)
1914 				continue;
1915 
1916 			set_page_dirty(page);
1917 			f2fs_put_page(page, 1);
1918 			page = NULL;
1919 		}
1920 	}
1921 	if (page) {
1922 		set_page_dirty(page);
1923 		f2fs_put_page(page, 1);
1924 	}
1925 }
1926 
1927 static void write_normal_summaries(struct f2fs_sb_info *sbi,
1928 					block_t blkaddr, int type)
1929 {
1930 	int i, end;
1931 	if (IS_DATASEG(type))
1932 		end = type + NR_CURSEG_DATA_TYPE;
1933 	else
1934 		end = type + NR_CURSEG_NODE_TYPE;
1935 
1936 	for (i = type; i < end; i++)
1937 		write_current_sum_page(sbi, i, blkaddr + (i - type));
1938 }
1939 
1940 void write_data_summaries(struct f2fs_sb_info *sbi, block_t start_blk)
1941 {
1942 	if (is_set_ckpt_flags(sbi, CP_COMPACT_SUM_FLAG))
1943 		write_compacted_summaries(sbi, start_blk);
1944 	else
1945 		write_normal_summaries(sbi, start_blk, CURSEG_HOT_DATA);
1946 }
1947 
1948 void write_node_summaries(struct f2fs_sb_info *sbi, block_t start_blk)
1949 {
1950 	write_normal_summaries(sbi, start_blk, CURSEG_HOT_NODE);
1951 }
1952 
1953 int lookup_journal_in_cursum(struct f2fs_journal *journal, int type,
1954 					unsigned int val, int alloc)
1955 {
1956 	int i;
1957 
1958 	if (type == NAT_JOURNAL) {
1959 		for (i = 0; i < nats_in_cursum(journal); i++) {
1960 			if (le32_to_cpu(nid_in_journal(journal, i)) == val)
1961 				return i;
1962 		}
1963 		if (alloc && __has_cursum_space(journal, 1, NAT_JOURNAL))
1964 			return update_nats_in_cursum(journal, 1);
1965 	} else if (type == SIT_JOURNAL) {
1966 		for (i = 0; i < sits_in_cursum(journal); i++)
1967 			if (le32_to_cpu(segno_in_journal(journal, i)) == val)
1968 				return i;
1969 		if (alloc && __has_cursum_space(journal, 1, SIT_JOURNAL))
1970 			return update_sits_in_cursum(journal, 1);
1971 	}
1972 	return -1;
1973 }
1974 
1975 static struct page *get_current_sit_page(struct f2fs_sb_info *sbi,
1976 					unsigned int segno)
1977 {
1978 	return get_meta_page(sbi, current_sit_addr(sbi, segno));
1979 }
1980 
1981 static struct page *get_next_sit_page(struct f2fs_sb_info *sbi,
1982 					unsigned int start)
1983 {
1984 	struct sit_info *sit_i = SIT_I(sbi);
1985 	struct page *src_page, *dst_page;
1986 	pgoff_t src_off, dst_off;
1987 	void *src_addr, *dst_addr;
1988 
1989 	src_off = current_sit_addr(sbi, start);
1990 	dst_off = next_sit_addr(sbi, src_off);
1991 
1992 	/* get current sit block page without lock */
1993 	src_page = get_meta_page(sbi, src_off);
1994 	dst_page = grab_meta_page(sbi, dst_off);
1995 	f2fs_bug_on(sbi, PageDirty(src_page));
1996 
1997 	src_addr = page_address(src_page);
1998 	dst_addr = page_address(dst_page);
1999 	memcpy(dst_addr, src_addr, PAGE_SIZE);
2000 
2001 	set_page_dirty(dst_page);
2002 	f2fs_put_page(src_page, 1);
2003 
2004 	set_to_next_sit(sit_i, start);
2005 
2006 	return dst_page;
2007 }
2008 
2009 static struct sit_entry_set *grab_sit_entry_set(void)
2010 {
2011 	struct sit_entry_set *ses =
2012 			f2fs_kmem_cache_alloc(sit_entry_set_slab, GFP_NOFS);
2013 
2014 	ses->entry_cnt = 0;
2015 	INIT_LIST_HEAD(&ses->set_list);
2016 	return ses;
2017 }
2018 
2019 static void release_sit_entry_set(struct sit_entry_set *ses)
2020 {
2021 	list_del(&ses->set_list);
2022 	kmem_cache_free(sit_entry_set_slab, ses);
2023 }
2024 
2025 static void adjust_sit_entry_set(struct sit_entry_set *ses,
2026 						struct list_head *head)
2027 {
2028 	struct sit_entry_set *next = ses;
2029 
2030 	if (list_is_last(&ses->set_list, head))
2031 		return;
2032 
2033 	list_for_each_entry_continue(next, head, set_list)
2034 		if (ses->entry_cnt <= next->entry_cnt)
2035 			break;
2036 
2037 	list_move_tail(&ses->set_list, &next->set_list);
2038 }
2039 
2040 static void add_sit_entry(unsigned int segno, struct list_head *head)
2041 {
2042 	struct sit_entry_set *ses;
2043 	unsigned int start_segno = START_SEGNO(segno);
2044 
2045 	list_for_each_entry(ses, head, set_list) {
2046 		if (ses->start_segno == start_segno) {
2047 			ses->entry_cnt++;
2048 			adjust_sit_entry_set(ses, head);
2049 			return;
2050 		}
2051 	}
2052 
2053 	ses = grab_sit_entry_set();
2054 
2055 	ses->start_segno = start_segno;
2056 	ses->entry_cnt++;
2057 	list_add(&ses->set_list, head);
2058 }
2059 
2060 static void add_sits_in_set(struct f2fs_sb_info *sbi)
2061 {
2062 	struct f2fs_sm_info *sm_info = SM_I(sbi);
2063 	struct list_head *set_list = &sm_info->sit_entry_set;
2064 	unsigned long *bitmap = SIT_I(sbi)->dirty_sentries_bitmap;
2065 	unsigned int segno;
2066 
2067 	for_each_set_bit(segno, bitmap, MAIN_SEGS(sbi))
2068 		add_sit_entry(segno, set_list);
2069 }
2070 
2071 static void remove_sits_in_journal(struct f2fs_sb_info *sbi)
2072 {
2073 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
2074 	struct f2fs_journal *journal = curseg->journal;
2075 	int i;
2076 
2077 	down_write(&curseg->journal_rwsem);
2078 	for (i = 0; i < sits_in_cursum(journal); i++) {
2079 		unsigned int segno;
2080 		bool dirtied;
2081 
2082 		segno = le32_to_cpu(segno_in_journal(journal, i));
2083 		dirtied = __mark_sit_entry_dirty(sbi, segno);
2084 
2085 		if (!dirtied)
2086 			add_sit_entry(segno, &SM_I(sbi)->sit_entry_set);
2087 	}
2088 	update_sits_in_cursum(journal, -i);
2089 	up_write(&curseg->journal_rwsem);
2090 }
2091 
2092 /*
2093  * CP calls this function, which flushes SIT entries including sit_journal,
2094  * and moves prefree segs to free segs.
2095  */
2096 void flush_sit_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc)
2097 {
2098 	struct sit_info *sit_i = SIT_I(sbi);
2099 	unsigned long *bitmap = sit_i->dirty_sentries_bitmap;
2100 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
2101 	struct f2fs_journal *journal = curseg->journal;
2102 	struct sit_entry_set *ses, *tmp;
2103 	struct list_head *head = &SM_I(sbi)->sit_entry_set;
2104 	bool to_journal = true;
2105 	struct seg_entry *se;
2106 
2107 	mutex_lock(&sit_i->sentry_lock);
2108 
2109 	if (!sit_i->dirty_sentries)
2110 		goto out;
2111 
2112 	/*
2113 	 * add and account sit entries of dirty bitmap in sit entry
2114 	 * set temporarily
2115 	 */
2116 	add_sits_in_set(sbi);
2117 
2118 	/*
2119 	 * if there are no enough space in journal to store dirty sit
2120 	 * entries, remove all entries from journal and add and account
2121 	 * them in sit entry set.
2122 	 */
2123 	if (!__has_cursum_space(journal, sit_i->dirty_sentries, SIT_JOURNAL))
2124 		remove_sits_in_journal(sbi);
2125 
2126 	/*
2127 	 * there are two steps to flush sit entries:
2128 	 * #1, flush sit entries to journal in current cold data summary block.
2129 	 * #2, flush sit entries to sit page.
2130 	 */
2131 	list_for_each_entry_safe(ses, tmp, head, set_list) {
2132 		struct page *page = NULL;
2133 		struct f2fs_sit_block *raw_sit = NULL;
2134 		unsigned int start_segno = ses->start_segno;
2135 		unsigned int end = min(start_segno + SIT_ENTRY_PER_BLOCK,
2136 						(unsigned long)MAIN_SEGS(sbi));
2137 		unsigned int segno = start_segno;
2138 
2139 		if (to_journal &&
2140 			!__has_cursum_space(journal, ses->entry_cnt, SIT_JOURNAL))
2141 			to_journal = false;
2142 
2143 		if (to_journal) {
2144 			down_write(&curseg->journal_rwsem);
2145 		} else {
2146 			page = get_next_sit_page(sbi, start_segno);
2147 			raw_sit = page_address(page);
2148 		}
2149 
2150 		/* flush dirty sit entries in region of current sit set */
2151 		for_each_set_bit_from(segno, bitmap, end) {
2152 			int offset, sit_offset;
2153 
2154 			se = get_seg_entry(sbi, segno);
2155 
2156 			/* add discard candidates */
2157 			if (cpc->reason != CP_DISCARD) {
2158 				cpc->trim_start = segno;
2159 				add_discard_addrs(sbi, cpc);
2160 			}
2161 
2162 			if (to_journal) {
2163 				offset = lookup_journal_in_cursum(journal,
2164 							SIT_JOURNAL, segno, 1);
2165 				f2fs_bug_on(sbi, offset < 0);
2166 				segno_in_journal(journal, offset) =
2167 							cpu_to_le32(segno);
2168 				seg_info_to_raw_sit(se,
2169 					&sit_in_journal(journal, offset));
2170 			} else {
2171 				sit_offset = SIT_ENTRY_OFFSET(sit_i, segno);
2172 				seg_info_to_raw_sit(se,
2173 						&raw_sit->entries[sit_offset]);
2174 			}
2175 
2176 			__clear_bit(segno, bitmap);
2177 			sit_i->dirty_sentries--;
2178 			ses->entry_cnt--;
2179 		}
2180 
2181 		if (to_journal)
2182 			up_write(&curseg->journal_rwsem);
2183 		else
2184 			f2fs_put_page(page, 1);
2185 
2186 		f2fs_bug_on(sbi, ses->entry_cnt);
2187 		release_sit_entry_set(ses);
2188 	}
2189 
2190 	f2fs_bug_on(sbi, !list_empty(head));
2191 	f2fs_bug_on(sbi, sit_i->dirty_sentries);
2192 out:
2193 	if (cpc->reason == CP_DISCARD) {
2194 		for (; cpc->trim_start <= cpc->trim_end; cpc->trim_start++)
2195 			add_discard_addrs(sbi, cpc);
2196 	}
2197 	mutex_unlock(&sit_i->sentry_lock);
2198 
2199 	set_prefree_as_free_segments(sbi);
2200 }
2201 
2202 static int build_sit_info(struct f2fs_sb_info *sbi)
2203 {
2204 	struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
2205 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
2206 	struct sit_info *sit_i;
2207 	unsigned int sit_segs, start;
2208 	char *src_bitmap, *dst_bitmap;
2209 	unsigned int bitmap_size;
2210 
2211 	/* allocate memory for SIT information */
2212 	sit_i = kzalloc(sizeof(struct sit_info), GFP_KERNEL);
2213 	if (!sit_i)
2214 		return -ENOMEM;
2215 
2216 	SM_I(sbi)->sit_info = sit_i;
2217 
2218 	sit_i->sentries = f2fs_kvzalloc(MAIN_SEGS(sbi) *
2219 					sizeof(struct seg_entry), GFP_KERNEL);
2220 	if (!sit_i->sentries)
2221 		return -ENOMEM;
2222 
2223 	bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
2224 	sit_i->dirty_sentries_bitmap = f2fs_kvzalloc(bitmap_size, GFP_KERNEL);
2225 	if (!sit_i->dirty_sentries_bitmap)
2226 		return -ENOMEM;
2227 
2228 	for (start = 0; start < MAIN_SEGS(sbi); start++) {
2229 		sit_i->sentries[start].cur_valid_map
2230 			= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
2231 		sit_i->sentries[start].ckpt_valid_map
2232 			= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
2233 		if (!sit_i->sentries[start].cur_valid_map ||
2234 				!sit_i->sentries[start].ckpt_valid_map)
2235 			return -ENOMEM;
2236 
2237 		if (f2fs_discard_en(sbi)) {
2238 			sit_i->sentries[start].discard_map
2239 				= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
2240 			if (!sit_i->sentries[start].discard_map)
2241 				return -ENOMEM;
2242 		}
2243 	}
2244 
2245 	sit_i->tmp_map = kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
2246 	if (!sit_i->tmp_map)
2247 		return -ENOMEM;
2248 
2249 	if (sbi->segs_per_sec > 1) {
2250 		sit_i->sec_entries = f2fs_kvzalloc(MAIN_SECS(sbi) *
2251 					sizeof(struct sec_entry), GFP_KERNEL);
2252 		if (!sit_i->sec_entries)
2253 			return -ENOMEM;
2254 	}
2255 
2256 	/* get information related with SIT */
2257 	sit_segs = le32_to_cpu(raw_super->segment_count_sit) >> 1;
2258 
2259 	/* setup SIT bitmap from ckeckpoint pack */
2260 	bitmap_size = __bitmap_size(sbi, SIT_BITMAP);
2261 	src_bitmap = __bitmap_ptr(sbi, SIT_BITMAP);
2262 
2263 	dst_bitmap = kmemdup(src_bitmap, bitmap_size, GFP_KERNEL);
2264 	if (!dst_bitmap)
2265 		return -ENOMEM;
2266 
2267 	/* init SIT information */
2268 	sit_i->s_ops = &default_salloc_ops;
2269 
2270 	sit_i->sit_base_addr = le32_to_cpu(raw_super->sit_blkaddr);
2271 	sit_i->sit_blocks = sit_segs << sbi->log_blocks_per_seg;
2272 	sit_i->written_valid_blocks = le64_to_cpu(ckpt->valid_block_count);
2273 	sit_i->sit_bitmap = dst_bitmap;
2274 	sit_i->bitmap_size = bitmap_size;
2275 	sit_i->dirty_sentries = 0;
2276 	sit_i->sents_per_block = SIT_ENTRY_PER_BLOCK;
2277 	sit_i->elapsed_time = le64_to_cpu(sbi->ckpt->elapsed_time);
2278 	sit_i->mounted_time = CURRENT_TIME_SEC.tv_sec;
2279 	mutex_init(&sit_i->sentry_lock);
2280 	return 0;
2281 }
2282 
2283 static int build_free_segmap(struct f2fs_sb_info *sbi)
2284 {
2285 	struct free_segmap_info *free_i;
2286 	unsigned int bitmap_size, sec_bitmap_size;
2287 
2288 	/* allocate memory for free segmap information */
2289 	free_i = kzalloc(sizeof(struct free_segmap_info), GFP_KERNEL);
2290 	if (!free_i)
2291 		return -ENOMEM;
2292 
2293 	SM_I(sbi)->free_info = free_i;
2294 
2295 	bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
2296 	free_i->free_segmap = f2fs_kvmalloc(bitmap_size, GFP_KERNEL);
2297 	if (!free_i->free_segmap)
2298 		return -ENOMEM;
2299 
2300 	sec_bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
2301 	free_i->free_secmap = f2fs_kvmalloc(sec_bitmap_size, GFP_KERNEL);
2302 	if (!free_i->free_secmap)
2303 		return -ENOMEM;
2304 
2305 	/* set all segments as dirty temporarily */
2306 	memset(free_i->free_segmap, 0xff, bitmap_size);
2307 	memset(free_i->free_secmap, 0xff, sec_bitmap_size);
2308 
2309 	/* init free segmap information */
2310 	free_i->start_segno = GET_SEGNO_FROM_SEG0(sbi, MAIN_BLKADDR(sbi));
2311 	free_i->free_segments = 0;
2312 	free_i->free_sections = 0;
2313 	spin_lock_init(&free_i->segmap_lock);
2314 	return 0;
2315 }
2316 
2317 static int build_curseg(struct f2fs_sb_info *sbi)
2318 {
2319 	struct curseg_info *array;
2320 	int i;
2321 
2322 	array = kcalloc(NR_CURSEG_TYPE, sizeof(*array), GFP_KERNEL);
2323 	if (!array)
2324 		return -ENOMEM;
2325 
2326 	SM_I(sbi)->curseg_array = array;
2327 
2328 	for (i = 0; i < NR_CURSEG_TYPE; i++) {
2329 		mutex_init(&array[i].curseg_mutex);
2330 		array[i].sum_blk = kzalloc(PAGE_SIZE, GFP_KERNEL);
2331 		if (!array[i].sum_blk)
2332 			return -ENOMEM;
2333 		init_rwsem(&array[i].journal_rwsem);
2334 		array[i].journal = kzalloc(sizeof(struct f2fs_journal),
2335 							GFP_KERNEL);
2336 		if (!array[i].journal)
2337 			return -ENOMEM;
2338 		array[i].segno = NULL_SEGNO;
2339 		array[i].next_blkoff = 0;
2340 	}
2341 	return restore_curseg_summaries(sbi);
2342 }
2343 
2344 static void build_sit_entries(struct f2fs_sb_info *sbi)
2345 {
2346 	struct sit_info *sit_i = SIT_I(sbi);
2347 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
2348 	struct f2fs_journal *journal = curseg->journal;
2349 	struct seg_entry *se;
2350 	struct f2fs_sit_entry sit;
2351 	int sit_blk_cnt = SIT_BLK_CNT(sbi);
2352 	unsigned int i, start, end;
2353 	unsigned int readed, start_blk = 0;
2354 
2355 	do {
2356 		readed = ra_meta_pages(sbi, start_blk, BIO_MAX_PAGES,
2357 							META_SIT, true);
2358 
2359 		start = start_blk * sit_i->sents_per_block;
2360 		end = (start_blk + readed) * sit_i->sents_per_block;
2361 
2362 		for (; start < end && start < MAIN_SEGS(sbi); start++) {
2363 			struct f2fs_sit_block *sit_blk;
2364 			struct page *page;
2365 
2366 			se = &sit_i->sentries[start];
2367 			page = get_current_sit_page(sbi, start);
2368 			sit_blk = (struct f2fs_sit_block *)page_address(page);
2369 			sit = sit_blk->entries[SIT_ENTRY_OFFSET(sit_i, start)];
2370 			f2fs_put_page(page, 1);
2371 
2372 			check_block_count(sbi, start, &sit);
2373 			seg_info_from_raw_sit(se, &sit);
2374 
2375 			/* build discard map only one time */
2376 			if (f2fs_discard_en(sbi)) {
2377 				memcpy(se->discard_map, se->cur_valid_map,
2378 							SIT_VBLOCK_MAP_SIZE);
2379 				sbi->discard_blks += sbi->blocks_per_seg -
2380 							se->valid_blocks;
2381 			}
2382 
2383 			if (sbi->segs_per_sec > 1)
2384 				get_sec_entry(sbi, start)->valid_blocks +=
2385 							se->valid_blocks;
2386 		}
2387 		start_blk += readed;
2388 	} while (start_blk < sit_blk_cnt);
2389 
2390 	down_read(&curseg->journal_rwsem);
2391 	for (i = 0; i < sits_in_cursum(journal); i++) {
2392 		unsigned int old_valid_blocks;
2393 
2394 		start = le32_to_cpu(segno_in_journal(journal, i));
2395 		se = &sit_i->sentries[start];
2396 		sit = sit_in_journal(journal, i);
2397 
2398 		old_valid_blocks = se->valid_blocks;
2399 
2400 		check_block_count(sbi, start, &sit);
2401 		seg_info_from_raw_sit(se, &sit);
2402 
2403 		if (f2fs_discard_en(sbi)) {
2404 			memcpy(se->discard_map, se->cur_valid_map,
2405 						SIT_VBLOCK_MAP_SIZE);
2406 			sbi->discard_blks += old_valid_blocks -
2407 						se->valid_blocks;
2408 		}
2409 
2410 		if (sbi->segs_per_sec > 1)
2411 			get_sec_entry(sbi, start)->valid_blocks +=
2412 				se->valid_blocks - old_valid_blocks;
2413 	}
2414 	up_read(&curseg->journal_rwsem);
2415 }
2416 
2417 static void init_free_segmap(struct f2fs_sb_info *sbi)
2418 {
2419 	unsigned int start;
2420 	int type;
2421 
2422 	for (start = 0; start < MAIN_SEGS(sbi); start++) {
2423 		struct seg_entry *sentry = get_seg_entry(sbi, start);
2424 		if (!sentry->valid_blocks)
2425 			__set_free(sbi, start);
2426 	}
2427 
2428 	/* set use the current segments */
2429 	for (type = CURSEG_HOT_DATA; type <= CURSEG_COLD_NODE; type++) {
2430 		struct curseg_info *curseg_t = CURSEG_I(sbi, type);
2431 		__set_test_and_inuse(sbi, curseg_t->segno);
2432 	}
2433 }
2434 
2435 static void init_dirty_segmap(struct f2fs_sb_info *sbi)
2436 {
2437 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
2438 	struct free_segmap_info *free_i = FREE_I(sbi);
2439 	unsigned int segno = 0, offset = 0;
2440 	unsigned short valid_blocks;
2441 
2442 	while (1) {
2443 		/* find dirty segment based on free segmap */
2444 		segno = find_next_inuse(free_i, MAIN_SEGS(sbi), offset);
2445 		if (segno >= MAIN_SEGS(sbi))
2446 			break;
2447 		offset = segno + 1;
2448 		valid_blocks = get_valid_blocks(sbi, segno, 0);
2449 		if (valid_blocks == sbi->blocks_per_seg || !valid_blocks)
2450 			continue;
2451 		if (valid_blocks > sbi->blocks_per_seg) {
2452 			f2fs_bug_on(sbi, 1);
2453 			continue;
2454 		}
2455 		mutex_lock(&dirty_i->seglist_lock);
2456 		__locate_dirty_segment(sbi, segno, DIRTY);
2457 		mutex_unlock(&dirty_i->seglist_lock);
2458 	}
2459 }
2460 
2461 static int init_victim_secmap(struct f2fs_sb_info *sbi)
2462 {
2463 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
2464 	unsigned int bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
2465 
2466 	dirty_i->victim_secmap = f2fs_kvzalloc(bitmap_size, GFP_KERNEL);
2467 	if (!dirty_i->victim_secmap)
2468 		return -ENOMEM;
2469 	return 0;
2470 }
2471 
2472 static int build_dirty_segmap(struct f2fs_sb_info *sbi)
2473 {
2474 	struct dirty_seglist_info *dirty_i;
2475 	unsigned int bitmap_size, i;
2476 
2477 	/* allocate memory for dirty segments list information */
2478 	dirty_i = kzalloc(sizeof(struct dirty_seglist_info), GFP_KERNEL);
2479 	if (!dirty_i)
2480 		return -ENOMEM;
2481 
2482 	SM_I(sbi)->dirty_info = dirty_i;
2483 	mutex_init(&dirty_i->seglist_lock);
2484 
2485 	bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
2486 
2487 	for (i = 0; i < NR_DIRTY_TYPE; i++) {
2488 		dirty_i->dirty_segmap[i] = f2fs_kvzalloc(bitmap_size, GFP_KERNEL);
2489 		if (!dirty_i->dirty_segmap[i])
2490 			return -ENOMEM;
2491 	}
2492 
2493 	init_dirty_segmap(sbi);
2494 	return init_victim_secmap(sbi);
2495 }
2496 
2497 /*
2498  * Update min, max modified time for cost-benefit GC algorithm
2499  */
2500 static void init_min_max_mtime(struct f2fs_sb_info *sbi)
2501 {
2502 	struct sit_info *sit_i = SIT_I(sbi);
2503 	unsigned int segno;
2504 
2505 	mutex_lock(&sit_i->sentry_lock);
2506 
2507 	sit_i->min_mtime = LLONG_MAX;
2508 
2509 	for (segno = 0; segno < MAIN_SEGS(sbi); segno += sbi->segs_per_sec) {
2510 		unsigned int i;
2511 		unsigned long long mtime = 0;
2512 
2513 		for (i = 0; i < sbi->segs_per_sec; i++)
2514 			mtime += get_seg_entry(sbi, segno + i)->mtime;
2515 
2516 		mtime = div_u64(mtime, sbi->segs_per_sec);
2517 
2518 		if (sit_i->min_mtime > mtime)
2519 			sit_i->min_mtime = mtime;
2520 	}
2521 	sit_i->max_mtime = get_mtime(sbi);
2522 	mutex_unlock(&sit_i->sentry_lock);
2523 }
2524 
2525 int build_segment_manager(struct f2fs_sb_info *sbi)
2526 {
2527 	struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
2528 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
2529 	struct f2fs_sm_info *sm_info;
2530 	int err;
2531 
2532 	sm_info = kzalloc(sizeof(struct f2fs_sm_info), GFP_KERNEL);
2533 	if (!sm_info)
2534 		return -ENOMEM;
2535 
2536 	/* init sm info */
2537 	sbi->sm_info = sm_info;
2538 	sm_info->seg0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr);
2539 	sm_info->main_blkaddr = le32_to_cpu(raw_super->main_blkaddr);
2540 	sm_info->segment_count = le32_to_cpu(raw_super->segment_count);
2541 	sm_info->reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
2542 	sm_info->ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
2543 	sm_info->main_segments = le32_to_cpu(raw_super->segment_count_main);
2544 	sm_info->ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr);
2545 	sm_info->rec_prefree_segments = sm_info->main_segments *
2546 					DEF_RECLAIM_PREFREE_SEGMENTS / 100;
2547 	if (sm_info->rec_prefree_segments > DEF_MAX_RECLAIM_PREFREE_SEGMENTS)
2548 		sm_info->rec_prefree_segments = DEF_MAX_RECLAIM_PREFREE_SEGMENTS;
2549 
2550 	if (!test_opt(sbi, LFS))
2551 		sm_info->ipu_policy = 1 << F2FS_IPU_FSYNC;
2552 	sm_info->min_ipu_util = DEF_MIN_IPU_UTIL;
2553 	sm_info->min_fsync_blocks = DEF_MIN_FSYNC_BLOCKS;
2554 
2555 	INIT_LIST_HEAD(&sm_info->discard_list);
2556 	INIT_LIST_HEAD(&sm_info->wait_list);
2557 	sm_info->nr_discards = 0;
2558 	sm_info->max_discards = 0;
2559 
2560 	sm_info->trim_sections = DEF_BATCHED_TRIM_SECTIONS;
2561 
2562 	INIT_LIST_HEAD(&sm_info->sit_entry_set);
2563 
2564 	if (test_opt(sbi, FLUSH_MERGE) && !f2fs_readonly(sbi->sb)) {
2565 		err = create_flush_cmd_control(sbi);
2566 		if (err)
2567 			return err;
2568 	}
2569 
2570 	err = build_sit_info(sbi);
2571 	if (err)
2572 		return err;
2573 	err = build_free_segmap(sbi);
2574 	if (err)
2575 		return err;
2576 	err = build_curseg(sbi);
2577 	if (err)
2578 		return err;
2579 
2580 	/* reinit free segmap based on SIT */
2581 	build_sit_entries(sbi);
2582 
2583 	init_free_segmap(sbi);
2584 	err = build_dirty_segmap(sbi);
2585 	if (err)
2586 		return err;
2587 
2588 	init_min_max_mtime(sbi);
2589 	return 0;
2590 }
2591 
2592 static void discard_dirty_segmap(struct f2fs_sb_info *sbi,
2593 		enum dirty_type dirty_type)
2594 {
2595 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
2596 
2597 	mutex_lock(&dirty_i->seglist_lock);
2598 	kvfree(dirty_i->dirty_segmap[dirty_type]);
2599 	dirty_i->nr_dirty[dirty_type] = 0;
2600 	mutex_unlock(&dirty_i->seglist_lock);
2601 }
2602 
2603 static void destroy_victim_secmap(struct f2fs_sb_info *sbi)
2604 {
2605 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
2606 	kvfree(dirty_i->victim_secmap);
2607 }
2608 
2609 static void destroy_dirty_segmap(struct f2fs_sb_info *sbi)
2610 {
2611 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
2612 	int i;
2613 
2614 	if (!dirty_i)
2615 		return;
2616 
2617 	/* discard pre-free/dirty segments list */
2618 	for (i = 0; i < NR_DIRTY_TYPE; i++)
2619 		discard_dirty_segmap(sbi, i);
2620 
2621 	destroy_victim_secmap(sbi);
2622 	SM_I(sbi)->dirty_info = NULL;
2623 	kfree(dirty_i);
2624 }
2625 
2626 static void destroy_curseg(struct f2fs_sb_info *sbi)
2627 {
2628 	struct curseg_info *array = SM_I(sbi)->curseg_array;
2629 	int i;
2630 
2631 	if (!array)
2632 		return;
2633 	SM_I(sbi)->curseg_array = NULL;
2634 	for (i = 0; i < NR_CURSEG_TYPE; i++) {
2635 		kfree(array[i].sum_blk);
2636 		kfree(array[i].journal);
2637 	}
2638 	kfree(array);
2639 }
2640 
2641 static void destroy_free_segmap(struct f2fs_sb_info *sbi)
2642 {
2643 	struct free_segmap_info *free_i = SM_I(sbi)->free_info;
2644 	if (!free_i)
2645 		return;
2646 	SM_I(sbi)->free_info = NULL;
2647 	kvfree(free_i->free_segmap);
2648 	kvfree(free_i->free_secmap);
2649 	kfree(free_i);
2650 }
2651 
2652 static void destroy_sit_info(struct f2fs_sb_info *sbi)
2653 {
2654 	struct sit_info *sit_i = SIT_I(sbi);
2655 	unsigned int start;
2656 
2657 	if (!sit_i)
2658 		return;
2659 
2660 	if (sit_i->sentries) {
2661 		for (start = 0; start < MAIN_SEGS(sbi); start++) {
2662 			kfree(sit_i->sentries[start].cur_valid_map);
2663 			kfree(sit_i->sentries[start].ckpt_valid_map);
2664 			kfree(sit_i->sentries[start].discard_map);
2665 		}
2666 	}
2667 	kfree(sit_i->tmp_map);
2668 
2669 	kvfree(sit_i->sentries);
2670 	kvfree(sit_i->sec_entries);
2671 	kvfree(sit_i->dirty_sentries_bitmap);
2672 
2673 	SM_I(sbi)->sit_info = NULL;
2674 	kfree(sit_i->sit_bitmap);
2675 	kfree(sit_i);
2676 }
2677 
2678 void destroy_segment_manager(struct f2fs_sb_info *sbi)
2679 {
2680 	struct f2fs_sm_info *sm_info = SM_I(sbi);
2681 
2682 	if (!sm_info)
2683 		return;
2684 	destroy_flush_cmd_control(sbi);
2685 	destroy_dirty_segmap(sbi);
2686 	destroy_curseg(sbi);
2687 	destroy_free_segmap(sbi);
2688 	destroy_sit_info(sbi);
2689 	sbi->sm_info = NULL;
2690 	kfree(sm_info);
2691 }
2692 
2693 int __init create_segment_manager_caches(void)
2694 {
2695 	discard_entry_slab = f2fs_kmem_cache_create("discard_entry",
2696 			sizeof(struct discard_entry));
2697 	if (!discard_entry_slab)
2698 		goto fail;
2699 
2700 	bio_entry_slab = f2fs_kmem_cache_create("bio_entry",
2701 			sizeof(struct bio_entry));
2702 	if (!bio_entry_slab)
2703 		goto destroy_discard_entry;
2704 
2705 	sit_entry_set_slab = f2fs_kmem_cache_create("sit_entry_set",
2706 			sizeof(struct sit_entry_set));
2707 	if (!sit_entry_set_slab)
2708 		goto destroy_bio_entry;
2709 
2710 	inmem_entry_slab = f2fs_kmem_cache_create("inmem_page_entry",
2711 			sizeof(struct inmem_pages));
2712 	if (!inmem_entry_slab)
2713 		goto destroy_sit_entry_set;
2714 	return 0;
2715 
2716 destroy_sit_entry_set:
2717 	kmem_cache_destroy(sit_entry_set_slab);
2718 destroy_bio_entry:
2719 	kmem_cache_destroy(bio_entry_slab);
2720 destroy_discard_entry:
2721 	kmem_cache_destroy(discard_entry_slab);
2722 fail:
2723 	return -ENOMEM;
2724 }
2725 
2726 void destroy_segment_manager_caches(void)
2727 {
2728 	kmem_cache_destroy(sit_entry_set_slab);
2729 	kmem_cache_destroy(bio_entry_slab);
2730 	kmem_cache_destroy(discard_entry_slab);
2731 	kmem_cache_destroy(inmem_entry_slab);
2732 }
2733