xref: /openbmc/linux/fs/f2fs/segment.c (revision 1f9f6a78)
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/vmalloc.h>
18 #include <linux/swap.h>
19 
20 #include "f2fs.h"
21 #include "segment.h"
22 #include "node.h"
23 #include <trace/events/f2fs.h>
24 
25 #define __reverse_ffz(x) __reverse_ffs(~(x))
26 
27 static struct kmem_cache *discard_entry_slab;
28 static struct kmem_cache *sit_entry_set_slab;
29 static struct kmem_cache *inmem_entry_slab;
30 
31 /*
32  * __reverse_ffs is copied from include/asm-generic/bitops/__ffs.h since
33  * MSB and LSB are reversed in a byte by f2fs_set_bit.
34  */
35 static inline unsigned long __reverse_ffs(unsigned long word)
36 {
37 	int num = 0;
38 
39 #if BITS_PER_LONG == 64
40 	if ((word & 0xffffffff) == 0) {
41 		num += 32;
42 		word >>= 32;
43 	}
44 #endif
45 	if ((word & 0xffff) == 0) {
46 		num += 16;
47 		word >>= 16;
48 	}
49 	if ((word & 0xff) == 0) {
50 		num += 8;
51 		word >>= 8;
52 	}
53 	if ((word & 0xf0) == 0)
54 		num += 4;
55 	else
56 		word >>= 4;
57 	if ((word & 0xc) == 0)
58 		num += 2;
59 	else
60 		word >>= 2;
61 	if ((word & 0x2) == 0)
62 		num += 1;
63 	return num;
64 }
65 
66 /*
67  * __find_rev_next(_zero)_bit is copied from lib/find_next_bit.c because
68  * f2fs_set_bit makes MSB and LSB reversed in a byte.
69  * Example:
70  *                             LSB <--> MSB
71  *   f2fs_set_bit(0, bitmap) => 0000 0001
72  *   f2fs_set_bit(7, bitmap) => 1000 0000
73  */
74 static unsigned long __find_rev_next_bit(const unsigned long *addr,
75 			unsigned long size, unsigned long offset)
76 {
77 	const unsigned long *p = addr + BIT_WORD(offset);
78 	unsigned long result = offset & ~(BITS_PER_LONG - 1);
79 	unsigned long tmp;
80 	unsigned long mask, submask;
81 	unsigned long quot, rest;
82 
83 	if (offset >= size)
84 		return size;
85 
86 	size -= result;
87 	offset %= BITS_PER_LONG;
88 	if (!offset)
89 		goto aligned;
90 
91 	tmp = *(p++);
92 	quot = (offset >> 3) << 3;
93 	rest = offset & 0x7;
94 	mask = ~0UL << quot;
95 	submask = (unsigned char)(0xff << rest) >> rest;
96 	submask <<= quot;
97 	mask &= submask;
98 	tmp &= mask;
99 	if (size < BITS_PER_LONG)
100 		goto found_first;
101 	if (tmp)
102 		goto found_middle;
103 
104 	size -= BITS_PER_LONG;
105 	result += BITS_PER_LONG;
106 aligned:
107 	while (size & ~(BITS_PER_LONG-1)) {
108 		tmp = *(p++);
109 		if (tmp)
110 			goto found_middle;
111 		result += BITS_PER_LONG;
112 		size -= BITS_PER_LONG;
113 	}
114 	if (!size)
115 		return result;
116 	tmp = *p;
117 found_first:
118 	tmp &= (~0UL >> (BITS_PER_LONG - size));
119 	if (tmp == 0UL)		/* Are any bits set? */
120 		return result + size;   /* Nope. */
121 found_middle:
122 	return result + __reverse_ffs(tmp);
123 }
124 
125 static unsigned long __find_rev_next_zero_bit(const unsigned long *addr,
126 			unsigned long size, unsigned long offset)
127 {
128 	const unsigned long *p = addr + BIT_WORD(offset);
129 	unsigned long result = offset & ~(BITS_PER_LONG - 1);
130 	unsigned long tmp;
131 	unsigned long mask, submask;
132 	unsigned long quot, rest;
133 
134 	if (offset >= size)
135 		return size;
136 
137 	size -= result;
138 	offset %= BITS_PER_LONG;
139 	if (!offset)
140 		goto aligned;
141 
142 	tmp = *(p++);
143 	quot = (offset >> 3) << 3;
144 	rest = offset & 0x7;
145 	mask = ~(~0UL << quot);
146 	submask = (unsigned char)~((unsigned char)(0xff << rest) >> rest);
147 	submask <<= quot;
148 	mask += submask;
149 	tmp |= mask;
150 	if (size < BITS_PER_LONG)
151 		goto found_first;
152 	if (~tmp)
153 		goto found_middle;
154 
155 	size -= BITS_PER_LONG;
156 	result += BITS_PER_LONG;
157 aligned:
158 	while (size & ~(BITS_PER_LONG - 1)) {
159 		tmp = *(p++);
160 		if (~tmp)
161 			goto found_middle;
162 		result += BITS_PER_LONG;
163 		size -= BITS_PER_LONG;
164 	}
165 	if (!size)
166 		return result;
167 	tmp = *p;
168 
169 found_first:
170 	tmp |= ~0UL << size;
171 	if (tmp == ~0UL)        /* Are any bits zero? */
172 		return result + size;   /* Nope. */
173 found_middle:
174 	return result + __reverse_ffz(tmp);
175 }
176 
177 void register_inmem_page(struct inode *inode, struct page *page)
178 {
179 	struct f2fs_inode_info *fi = F2FS_I(inode);
180 	struct inmem_pages *new;
181 	int err;
182 
183 	SetPagePrivate(page);
184 
185 	new = f2fs_kmem_cache_alloc(inmem_entry_slab, GFP_NOFS);
186 
187 	/* add atomic page indices to the list */
188 	new->page = page;
189 	INIT_LIST_HEAD(&new->list);
190 retry:
191 	/* increase reference count with clean state */
192 	mutex_lock(&fi->inmem_lock);
193 	err = radix_tree_insert(&fi->inmem_root, page->index, new);
194 	if (err == -EEXIST) {
195 		mutex_unlock(&fi->inmem_lock);
196 		kmem_cache_free(inmem_entry_slab, new);
197 		return;
198 	} else if (err) {
199 		mutex_unlock(&fi->inmem_lock);
200 		goto retry;
201 	}
202 	get_page(page);
203 	list_add_tail(&new->list, &fi->inmem_pages);
204 	inc_page_count(F2FS_I_SB(inode), F2FS_INMEM_PAGES);
205 	mutex_unlock(&fi->inmem_lock);
206 }
207 
208 void invalidate_inmem_page(struct inode *inode, struct page *page)
209 {
210 	struct f2fs_inode_info *fi = F2FS_I(inode);
211 	struct inmem_pages *cur;
212 
213 	mutex_lock(&fi->inmem_lock);
214 	cur = radix_tree_lookup(&fi->inmem_root, page->index);
215 	if (cur) {
216 		radix_tree_delete(&fi->inmem_root, cur->page->index);
217 		f2fs_put_page(cur->page, 0);
218 		list_del(&cur->list);
219 		kmem_cache_free(inmem_entry_slab, cur);
220 		dec_page_count(F2FS_I_SB(inode), F2FS_INMEM_PAGES);
221 	}
222 	mutex_unlock(&fi->inmem_lock);
223 }
224 
225 void commit_inmem_pages(struct inode *inode, bool abort)
226 {
227 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
228 	struct f2fs_inode_info *fi = F2FS_I(inode);
229 	struct inmem_pages *cur, *tmp;
230 	bool submit_bio = false;
231 	struct f2fs_io_info fio = {
232 		.type = DATA,
233 		.rw = WRITE_SYNC,
234 	};
235 
236 	/*
237 	 * The abort is true only when f2fs_evict_inode is called.
238 	 * Basically, the f2fs_evict_inode doesn't produce any data writes, so
239 	 * that we don't need to call f2fs_balance_fs.
240 	 * Otherwise, f2fs_gc in f2fs_balance_fs can wait forever until this
241 	 * inode becomes free by iget_locked in f2fs_iget.
242 	 */
243 	if (!abort)
244 		f2fs_balance_fs(sbi);
245 
246 	f2fs_lock_op(sbi);
247 
248 	mutex_lock(&fi->inmem_lock);
249 	list_for_each_entry_safe(cur, tmp, &fi->inmem_pages, list) {
250 		lock_page(cur->page);
251 		if (!abort && cur->page->mapping == inode->i_mapping) {
252 			f2fs_wait_on_page_writeback(cur->page, DATA);
253 			if (clear_page_dirty_for_io(cur->page))
254 				inode_dec_dirty_pages(inode);
255 			do_write_data_page(cur->page, &fio);
256 			submit_bio = true;
257 		}
258 		radix_tree_delete(&fi->inmem_root, cur->page->index);
259 		f2fs_put_page(cur->page, 1);
260 		list_del(&cur->list);
261 		kmem_cache_free(inmem_entry_slab, cur);
262 		dec_page_count(F2FS_I_SB(inode), F2FS_INMEM_PAGES);
263 	}
264 	if (submit_bio)
265 		f2fs_submit_merged_bio(sbi, DATA, WRITE);
266 	mutex_unlock(&fi->inmem_lock);
267 
268 	filemap_fdatawait_range(inode->i_mapping, 0, LLONG_MAX);
269 	f2fs_unlock_op(sbi);
270 }
271 
272 /*
273  * This function balances dirty node and dentry pages.
274  * In addition, it controls garbage collection.
275  */
276 void f2fs_balance_fs(struct f2fs_sb_info *sbi)
277 {
278 	/*
279 	 * We should do GC or end up with checkpoint, if there are so many dirty
280 	 * dir/node pages without enough free segments.
281 	 */
282 	if (has_not_enough_free_secs(sbi, 0)) {
283 		mutex_lock(&sbi->gc_mutex);
284 		f2fs_gc(sbi);
285 	}
286 }
287 
288 void f2fs_balance_fs_bg(struct f2fs_sb_info *sbi)
289 {
290 	/* check the # of cached NAT entries and prefree segments */
291 	if (try_to_free_nats(sbi, NAT_ENTRY_PER_BLOCK) ||
292 			excess_prefree_segs(sbi) ||
293 			available_free_memory(sbi, INO_ENTRIES))
294 		f2fs_sync_fs(sbi->sb, true);
295 }
296 
297 static int issue_flush_thread(void *data)
298 {
299 	struct f2fs_sb_info *sbi = data;
300 	struct flush_cmd_control *fcc = SM_I(sbi)->cmd_control_info;
301 	wait_queue_head_t *q = &fcc->flush_wait_queue;
302 repeat:
303 	if (kthread_should_stop())
304 		return 0;
305 
306 	if (!llist_empty(&fcc->issue_list)) {
307 		struct bio *bio = bio_alloc(GFP_NOIO, 0);
308 		struct flush_cmd *cmd, *next;
309 		int ret;
310 
311 		fcc->dispatch_list = llist_del_all(&fcc->issue_list);
312 		fcc->dispatch_list = llist_reverse_order(fcc->dispatch_list);
313 
314 		bio->bi_bdev = sbi->sb->s_bdev;
315 		ret = submit_bio_wait(WRITE_FLUSH, bio);
316 
317 		llist_for_each_entry_safe(cmd, next,
318 					  fcc->dispatch_list, llnode) {
319 			cmd->ret = ret;
320 			complete(&cmd->wait);
321 		}
322 		bio_put(bio);
323 		fcc->dispatch_list = NULL;
324 	}
325 
326 	wait_event_interruptible(*q,
327 		kthread_should_stop() || !llist_empty(&fcc->issue_list));
328 	goto repeat;
329 }
330 
331 int f2fs_issue_flush(struct f2fs_sb_info *sbi)
332 {
333 	struct flush_cmd_control *fcc = SM_I(sbi)->cmd_control_info;
334 	struct flush_cmd cmd;
335 
336 	trace_f2fs_issue_flush(sbi->sb, test_opt(sbi, NOBARRIER),
337 					test_opt(sbi, FLUSH_MERGE));
338 
339 	if (test_opt(sbi, NOBARRIER))
340 		return 0;
341 
342 	if (!test_opt(sbi, FLUSH_MERGE))
343 		return blkdev_issue_flush(sbi->sb->s_bdev, GFP_KERNEL, NULL);
344 
345 	init_completion(&cmd.wait);
346 
347 	llist_add(&cmd.llnode, &fcc->issue_list);
348 
349 	if (!fcc->dispatch_list)
350 		wake_up(&fcc->flush_wait_queue);
351 
352 	wait_for_completion(&cmd.wait);
353 
354 	return cmd.ret;
355 }
356 
357 int create_flush_cmd_control(struct f2fs_sb_info *sbi)
358 {
359 	dev_t dev = sbi->sb->s_bdev->bd_dev;
360 	struct flush_cmd_control *fcc;
361 	int err = 0;
362 
363 	fcc = kzalloc(sizeof(struct flush_cmd_control), GFP_KERNEL);
364 	if (!fcc)
365 		return -ENOMEM;
366 	init_waitqueue_head(&fcc->flush_wait_queue);
367 	init_llist_head(&fcc->issue_list);
368 	SM_I(sbi)->cmd_control_info = fcc;
369 	fcc->f2fs_issue_flush = kthread_run(issue_flush_thread, sbi,
370 				"f2fs_flush-%u:%u", MAJOR(dev), MINOR(dev));
371 	if (IS_ERR(fcc->f2fs_issue_flush)) {
372 		err = PTR_ERR(fcc->f2fs_issue_flush);
373 		kfree(fcc);
374 		SM_I(sbi)->cmd_control_info = NULL;
375 		return err;
376 	}
377 
378 	return err;
379 }
380 
381 void destroy_flush_cmd_control(struct f2fs_sb_info *sbi)
382 {
383 	struct flush_cmd_control *fcc = SM_I(sbi)->cmd_control_info;
384 
385 	if (fcc && fcc->f2fs_issue_flush)
386 		kthread_stop(fcc->f2fs_issue_flush);
387 	kfree(fcc);
388 	SM_I(sbi)->cmd_control_info = NULL;
389 }
390 
391 static void __locate_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno,
392 		enum dirty_type dirty_type)
393 {
394 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
395 
396 	/* need not be added */
397 	if (IS_CURSEG(sbi, segno))
398 		return;
399 
400 	if (!test_and_set_bit(segno, dirty_i->dirty_segmap[dirty_type]))
401 		dirty_i->nr_dirty[dirty_type]++;
402 
403 	if (dirty_type == DIRTY) {
404 		struct seg_entry *sentry = get_seg_entry(sbi, segno);
405 		enum dirty_type t = sentry->type;
406 
407 		if (unlikely(t >= DIRTY)) {
408 			f2fs_bug_on(sbi, 1);
409 			return;
410 		}
411 		if (!test_and_set_bit(segno, dirty_i->dirty_segmap[t]))
412 			dirty_i->nr_dirty[t]++;
413 	}
414 }
415 
416 static void __remove_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno,
417 		enum dirty_type dirty_type)
418 {
419 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
420 
421 	if (test_and_clear_bit(segno, dirty_i->dirty_segmap[dirty_type]))
422 		dirty_i->nr_dirty[dirty_type]--;
423 
424 	if (dirty_type == DIRTY) {
425 		struct seg_entry *sentry = get_seg_entry(sbi, segno);
426 		enum dirty_type t = sentry->type;
427 
428 		if (test_and_clear_bit(segno, dirty_i->dirty_segmap[t]))
429 			dirty_i->nr_dirty[t]--;
430 
431 		if (get_valid_blocks(sbi, segno, sbi->segs_per_sec) == 0)
432 			clear_bit(GET_SECNO(sbi, segno),
433 						dirty_i->victim_secmap);
434 	}
435 }
436 
437 /*
438  * Should not occur error such as -ENOMEM.
439  * Adding dirty entry into seglist is not critical operation.
440  * If a given segment is one of current working segments, it won't be added.
441  */
442 static void locate_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno)
443 {
444 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
445 	unsigned short valid_blocks;
446 
447 	if (segno == NULL_SEGNO || IS_CURSEG(sbi, segno))
448 		return;
449 
450 	mutex_lock(&dirty_i->seglist_lock);
451 
452 	valid_blocks = get_valid_blocks(sbi, segno, 0);
453 
454 	if (valid_blocks == 0) {
455 		__locate_dirty_segment(sbi, segno, PRE);
456 		__remove_dirty_segment(sbi, segno, DIRTY);
457 	} else if (valid_blocks < sbi->blocks_per_seg) {
458 		__locate_dirty_segment(sbi, segno, DIRTY);
459 	} else {
460 		/* Recovery routine with SSR needs this */
461 		__remove_dirty_segment(sbi, segno, DIRTY);
462 	}
463 
464 	mutex_unlock(&dirty_i->seglist_lock);
465 }
466 
467 static int f2fs_issue_discard(struct f2fs_sb_info *sbi,
468 				block_t blkstart, block_t blklen)
469 {
470 	sector_t start = SECTOR_FROM_BLOCK(blkstart);
471 	sector_t len = SECTOR_FROM_BLOCK(blklen);
472 	trace_f2fs_issue_discard(sbi->sb, blkstart, blklen);
473 	return blkdev_issue_discard(sbi->sb->s_bdev, start, len, GFP_NOFS, 0);
474 }
475 
476 void discard_next_dnode(struct f2fs_sb_info *sbi, block_t blkaddr)
477 {
478 	if (f2fs_issue_discard(sbi, blkaddr, 1)) {
479 		struct page *page = grab_meta_page(sbi, blkaddr);
480 		/* zero-filled page */
481 		set_page_dirty(page);
482 		f2fs_put_page(page, 1);
483 	}
484 }
485 
486 static void __add_discard_entry(struct f2fs_sb_info *sbi,
487 		struct cp_control *cpc, unsigned int start, unsigned int end)
488 {
489 	struct list_head *head = &SM_I(sbi)->discard_list;
490 	struct discard_entry *new, *last;
491 
492 	if (!list_empty(head)) {
493 		last = list_last_entry(head, struct discard_entry, list);
494 		if (START_BLOCK(sbi, cpc->trim_start) + start ==
495 						last->blkaddr + last->len) {
496 			last->len += end - start;
497 			goto done;
498 		}
499 	}
500 
501 	new = f2fs_kmem_cache_alloc(discard_entry_slab, GFP_NOFS);
502 	INIT_LIST_HEAD(&new->list);
503 	new->blkaddr = START_BLOCK(sbi, cpc->trim_start) + start;
504 	new->len = end - start;
505 	list_add_tail(&new->list, head);
506 done:
507 	SM_I(sbi)->nr_discards += end - start;
508 	cpc->trimmed += end - start;
509 }
510 
511 static void add_discard_addrs(struct f2fs_sb_info *sbi, struct cp_control *cpc)
512 {
513 	int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
514 	int max_blocks = sbi->blocks_per_seg;
515 	struct seg_entry *se = get_seg_entry(sbi, cpc->trim_start);
516 	unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
517 	unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
518 	unsigned long dmap[entries];
519 	unsigned int start = 0, end = -1;
520 	bool force = (cpc->reason == CP_DISCARD);
521 	int i;
522 
523 	if (!force && !test_opt(sbi, DISCARD))
524 		return;
525 
526 	if (force && !se->valid_blocks) {
527 		struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
528 		/*
529 		 * if this segment is registered in the prefree list, then
530 		 * we should skip adding a discard candidate, and let the
531 		 * checkpoint do that later.
532 		 */
533 		mutex_lock(&dirty_i->seglist_lock);
534 		if (test_bit(cpc->trim_start, dirty_i->dirty_segmap[PRE])) {
535 			mutex_unlock(&dirty_i->seglist_lock);
536 			cpc->trimmed += sbi->blocks_per_seg;
537 			return;
538 		}
539 		mutex_unlock(&dirty_i->seglist_lock);
540 
541 		__add_discard_entry(sbi, cpc, 0, sbi->blocks_per_seg);
542 		return;
543 	}
544 
545 	/* zero block will be discarded through the prefree list */
546 	if (!se->valid_blocks || se->valid_blocks == max_blocks)
547 		return;
548 
549 	/* SIT_VBLOCK_MAP_SIZE should be multiple of sizeof(unsigned long) */
550 	for (i = 0; i < entries; i++)
551 		dmap[i] = ~(cur_map[i] | ckpt_map[i]);
552 
553 	while (force || SM_I(sbi)->nr_discards <= SM_I(sbi)->max_discards) {
554 		start = __find_rev_next_bit(dmap, max_blocks, end + 1);
555 		if (start >= max_blocks)
556 			break;
557 
558 		end = __find_rev_next_zero_bit(dmap, max_blocks, start + 1);
559 
560 		if (end - start < cpc->trim_minlen)
561 			continue;
562 
563 		__add_discard_entry(sbi, cpc, start, end);
564 	}
565 }
566 
567 void release_discard_addrs(struct f2fs_sb_info *sbi)
568 {
569 	struct list_head *head = &(SM_I(sbi)->discard_list);
570 	struct discard_entry *entry, *this;
571 
572 	/* drop caches */
573 	list_for_each_entry_safe(entry, this, head, list) {
574 		list_del(&entry->list);
575 		kmem_cache_free(discard_entry_slab, entry);
576 	}
577 }
578 
579 /*
580  * Should call clear_prefree_segments after checkpoint is done.
581  */
582 static void set_prefree_as_free_segments(struct f2fs_sb_info *sbi)
583 {
584 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
585 	unsigned int segno;
586 
587 	mutex_lock(&dirty_i->seglist_lock);
588 	for_each_set_bit(segno, dirty_i->dirty_segmap[PRE], MAIN_SEGS(sbi))
589 		__set_test_and_free(sbi, segno);
590 	mutex_unlock(&dirty_i->seglist_lock);
591 }
592 
593 void clear_prefree_segments(struct f2fs_sb_info *sbi)
594 {
595 	struct list_head *head = &(SM_I(sbi)->discard_list);
596 	struct discard_entry *entry, *this;
597 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
598 	unsigned long *prefree_map = dirty_i->dirty_segmap[PRE];
599 	unsigned int start = 0, end = -1;
600 
601 	mutex_lock(&dirty_i->seglist_lock);
602 
603 	while (1) {
604 		int i;
605 		start = find_next_bit(prefree_map, MAIN_SEGS(sbi), end + 1);
606 		if (start >= MAIN_SEGS(sbi))
607 			break;
608 		end = find_next_zero_bit(prefree_map, MAIN_SEGS(sbi),
609 								start + 1);
610 
611 		for (i = start; i < end; i++)
612 			clear_bit(i, prefree_map);
613 
614 		dirty_i->nr_dirty[PRE] -= end - start;
615 
616 		if (!test_opt(sbi, DISCARD))
617 			continue;
618 
619 		f2fs_issue_discard(sbi, START_BLOCK(sbi, start),
620 				(end - start) << sbi->log_blocks_per_seg);
621 	}
622 	mutex_unlock(&dirty_i->seglist_lock);
623 
624 	/* send small discards */
625 	list_for_each_entry_safe(entry, this, head, list) {
626 		f2fs_issue_discard(sbi, entry->blkaddr, entry->len);
627 		list_del(&entry->list);
628 		SM_I(sbi)->nr_discards -= entry->len;
629 		kmem_cache_free(discard_entry_slab, entry);
630 	}
631 }
632 
633 static bool __mark_sit_entry_dirty(struct f2fs_sb_info *sbi, unsigned int segno)
634 {
635 	struct sit_info *sit_i = SIT_I(sbi);
636 
637 	if (!__test_and_set_bit(segno, sit_i->dirty_sentries_bitmap)) {
638 		sit_i->dirty_sentries++;
639 		return false;
640 	}
641 
642 	return true;
643 }
644 
645 static void __set_sit_entry_type(struct f2fs_sb_info *sbi, int type,
646 					unsigned int segno, int modified)
647 {
648 	struct seg_entry *se = get_seg_entry(sbi, segno);
649 	se->type = type;
650 	if (modified)
651 		__mark_sit_entry_dirty(sbi, segno);
652 }
653 
654 static void update_sit_entry(struct f2fs_sb_info *sbi, block_t blkaddr, int del)
655 {
656 	struct seg_entry *se;
657 	unsigned int segno, offset;
658 	long int new_vblocks;
659 
660 	segno = GET_SEGNO(sbi, blkaddr);
661 
662 	se = get_seg_entry(sbi, segno);
663 	new_vblocks = se->valid_blocks + del;
664 	offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
665 
666 	f2fs_bug_on(sbi, (new_vblocks >> (sizeof(unsigned short) << 3) ||
667 				(new_vblocks > sbi->blocks_per_seg)));
668 
669 	se->valid_blocks = new_vblocks;
670 	se->mtime = get_mtime(sbi);
671 	SIT_I(sbi)->max_mtime = se->mtime;
672 
673 	/* Update valid block bitmap */
674 	if (del > 0) {
675 		if (f2fs_test_and_set_bit(offset, se->cur_valid_map))
676 			f2fs_bug_on(sbi, 1);
677 	} else {
678 		if (!f2fs_test_and_clear_bit(offset, se->cur_valid_map))
679 			f2fs_bug_on(sbi, 1);
680 	}
681 	if (!f2fs_test_bit(offset, se->ckpt_valid_map))
682 		se->ckpt_valid_blocks += del;
683 
684 	__mark_sit_entry_dirty(sbi, segno);
685 
686 	/* update total number of valid blocks to be written in ckpt area */
687 	SIT_I(sbi)->written_valid_blocks += del;
688 
689 	if (sbi->segs_per_sec > 1)
690 		get_sec_entry(sbi, segno)->valid_blocks += del;
691 }
692 
693 void refresh_sit_entry(struct f2fs_sb_info *sbi, block_t old, block_t new)
694 {
695 	update_sit_entry(sbi, new, 1);
696 	if (GET_SEGNO(sbi, old) != NULL_SEGNO)
697 		update_sit_entry(sbi, old, -1);
698 
699 	locate_dirty_segment(sbi, GET_SEGNO(sbi, old));
700 	locate_dirty_segment(sbi, GET_SEGNO(sbi, new));
701 }
702 
703 void invalidate_blocks(struct f2fs_sb_info *sbi, block_t addr)
704 {
705 	unsigned int segno = GET_SEGNO(sbi, addr);
706 	struct sit_info *sit_i = SIT_I(sbi);
707 
708 	f2fs_bug_on(sbi, addr == NULL_ADDR);
709 	if (addr == NEW_ADDR)
710 		return;
711 
712 	/* add it into sit main buffer */
713 	mutex_lock(&sit_i->sentry_lock);
714 
715 	update_sit_entry(sbi, addr, -1);
716 
717 	/* add it into dirty seglist */
718 	locate_dirty_segment(sbi, segno);
719 
720 	mutex_unlock(&sit_i->sentry_lock);
721 }
722 
723 /*
724  * This function should be resided under the curseg_mutex lock
725  */
726 static void __add_sum_entry(struct f2fs_sb_info *sbi, int type,
727 					struct f2fs_summary *sum)
728 {
729 	struct curseg_info *curseg = CURSEG_I(sbi, type);
730 	void *addr = curseg->sum_blk;
731 	addr += curseg->next_blkoff * sizeof(struct f2fs_summary);
732 	memcpy(addr, sum, sizeof(struct f2fs_summary));
733 }
734 
735 /*
736  * Calculate the number of current summary pages for writing
737  */
738 int npages_for_summary_flush(struct f2fs_sb_info *sbi)
739 {
740 	int valid_sum_count = 0;
741 	int i, sum_in_page;
742 
743 	for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
744 		if (sbi->ckpt->alloc_type[i] == SSR)
745 			valid_sum_count += sbi->blocks_per_seg;
746 		else
747 			valid_sum_count += curseg_blkoff(sbi, i);
748 	}
749 
750 	sum_in_page = (PAGE_CACHE_SIZE - 2 * SUM_JOURNAL_SIZE -
751 			SUM_FOOTER_SIZE) / SUMMARY_SIZE;
752 	if (valid_sum_count <= sum_in_page)
753 		return 1;
754 	else if ((valid_sum_count - sum_in_page) <=
755 		(PAGE_CACHE_SIZE - SUM_FOOTER_SIZE) / SUMMARY_SIZE)
756 		return 2;
757 	return 3;
758 }
759 
760 /*
761  * Caller should put this summary page
762  */
763 struct page *get_sum_page(struct f2fs_sb_info *sbi, unsigned int segno)
764 {
765 	return get_meta_page(sbi, GET_SUM_BLOCK(sbi, segno));
766 }
767 
768 static void write_sum_page(struct f2fs_sb_info *sbi,
769 			struct f2fs_summary_block *sum_blk, block_t blk_addr)
770 {
771 	struct page *page = grab_meta_page(sbi, blk_addr);
772 	void *kaddr = page_address(page);
773 	memcpy(kaddr, sum_blk, PAGE_CACHE_SIZE);
774 	set_page_dirty(page);
775 	f2fs_put_page(page, 1);
776 }
777 
778 static int is_next_segment_free(struct f2fs_sb_info *sbi, int type)
779 {
780 	struct curseg_info *curseg = CURSEG_I(sbi, type);
781 	unsigned int segno = curseg->segno + 1;
782 	struct free_segmap_info *free_i = FREE_I(sbi);
783 
784 	if (segno < MAIN_SEGS(sbi) && segno % sbi->segs_per_sec)
785 		return !test_bit(segno, free_i->free_segmap);
786 	return 0;
787 }
788 
789 /*
790  * Find a new segment from the free segments bitmap to right order
791  * This function should be returned with success, otherwise BUG
792  */
793 static void get_new_segment(struct f2fs_sb_info *sbi,
794 			unsigned int *newseg, bool new_sec, int dir)
795 {
796 	struct free_segmap_info *free_i = FREE_I(sbi);
797 	unsigned int segno, secno, zoneno;
798 	unsigned int total_zones = MAIN_SECS(sbi) / sbi->secs_per_zone;
799 	unsigned int hint = *newseg / sbi->segs_per_sec;
800 	unsigned int old_zoneno = GET_ZONENO_FROM_SEGNO(sbi, *newseg);
801 	unsigned int left_start = hint;
802 	bool init = true;
803 	int go_left = 0;
804 	int i;
805 
806 	write_lock(&free_i->segmap_lock);
807 
808 	if (!new_sec && ((*newseg + 1) % sbi->segs_per_sec)) {
809 		segno = find_next_zero_bit(free_i->free_segmap,
810 					MAIN_SEGS(sbi), *newseg + 1);
811 		if (segno - *newseg < sbi->segs_per_sec -
812 					(*newseg % sbi->segs_per_sec))
813 			goto got_it;
814 	}
815 find_other_zone:
816 	secno = find_next_zero_bit(free_i->free_secmap, MAIN_SECS(sbi), hint);
817 	if (secno >= MAIN_SECS(sbi)) {
818 		if (dir == ALLOC_RIGHT) {
819 			secno = find_next_zero_bit(free_i->free_secmap,
820 							MAIN_SECS(sbi), 0);
821 			f2fs_bug_on(sbi, secno >= MAIN_SECS(sbi));
822 		} else {
823 			go_left = 1;
824 			left_start = hint - 1;
825 		}
826 	}
827 	if (go_left == 0)
828 		goto skip_left;
829 
830 	while (test_bit(left_start, free_i->free_secmap)) {
831 		if (left_start > 0) {
832 			left_start--;
833 			continue;
834 		}
835 		left_start = find_next_zero_bit(free_i->free_secmap,
836 							MAIN_SECS(sbi), 0);
837 		f2fs_bug_on(sbi, left_start >= MAIN_SECS(sbi));
838 		break;
839 	}
840 	secno = left_start;
841 skip_left:
842 	hint = secno;
843 	segno = secno * sbi->segs_per_sec;
844 	zoneno = secno / sbi->secs_per_zone;
845 
846 	/* give up on finding another zone */
847 	if (!init)
848 		goto got_it;
849 	if (sbi->secs_per_zone == 1)
850 		goto got_it;
851 	if (zoneno == old_zoneno)
852 		goto got_it;
853 	if (dir == ALLOC_LEFT) {
854 		if (!go_left && zoneno + 1 >= total_zones)
855 			goto got_it;
856 		if (go_left && zoneno == 0)
857 			goto got_it;
858 	}
859 	for (i = 0; i < NR_CURSEG_TYPE; i++)
860 		if (CURSEG_I(sbi, i)->zone == zoneno)
861 			break;
862 
863 	if (i < NR_CURSEG_TYPE) {
864 		/* zone is in user, try another */
865 		if (go_left)
866 			hint = zoneno * sbi->secs_per_zone - 1;
867 		else if (zoneno + 1 >= total_zones)
868 			hint = 0;
869 		else
870 			hint = (zoneno + 1) * sbi->secs_per_zone;
871 		init = false;
872 		goto find_other_zone;
873 	}
874 got_it:
875 	/* set it as dirty segment in free segmap */
876 	f2fs_bug_on(sbi, test_bit(segno, free_i->free_segmap));
877 	__set_inuse(sbi, segno);
878 	*newseg = segno;
879 	write_unlock(&free_i->segmap_lock);
880 }
881 
882 static void reset_curseg(struct f2fs_sb_info *sbi, int type, int modified)
883 {
884 	struct curseg_info *curseg = CURSEG_I(sbi, type);
885 	struct summary_footer *sum_footer;
886 
887 	curseg->segno = curseg->next_segno;
888 	curseg->zone = GET_ZONENO_FROM_SEGNO(sbi, curseg->segno);
889 	curseg->next_blkoff = 0;
890 	curseg->next_segno = NULL_SEGNO;
891 
892 	sum_footer = &(curseg->sum_blk->footer);
893 	memset(sum_footer, 0, sizeof(struct summary_footer));
894 	if (IS_DATASEG(type))
895 		SET_SUM_TYPE(sum_footer, SUM_TYPE_DATA);
896 	if (IS_NODESEG(type))
897 		SET_SUM_TYPE(sum_footer, SUM_TYPE_NODE);
898 	__set_sit_entry_type(sbi, type, curseg->segno, modified);
899 }
900 
901 /*
902  * Allocate a current working segment.
903  * This function always allocates a free segment in LFS manner.
904  */
905 static void new_curseg(struct f2fs_sb_info *sbi, int type, bool new_sec)
906 {
907 	struct curseg_info *curseg = CURSEG_I(sbi, type);
908 	unsigned int segno = curseg->segno;
909 	int dir = ALLOC_LEFT;
910 
911 	write_sum_page(sbi, curseg->sum_blk,
912 				GET_SUM_BLOCK(sbi, segno));
913 	if (type == CURSEG_WARM_DATA || type == CURSEG_COLD_DATA)
914 		dir = ALLOC_RIGHT;
915 
916 	if (test_opt(sbi, NOHEAP))
917 		dir = ALLOC_RIGHT;
918 
919 	get_new_segment(sbi, &segno, new_sec, dir);
920 	curseg->next_segno = segno;
921 	reset_curseg(sbi, type, 1);
922 	curseg->alloc_type = LFS;
923 }
924 
925 static void __next_free_blkoff(struct f2fs_sb_info *sbi,
926 			struct curseg_info *seg, block_t start)
927 {
928 	struct seg_entry *se = get_seg_entry(sbi, seg->segno);
929 	int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
930 	unsigned long target_map[entries];
931 	unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
932 	unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
933 	int i, pos;
934 
935 	for (i = 0; i < entries; i++)
936 		target_map[i] = ckpt_map[i] | cur_map[i];
937 
938 	pos = __find_rev_next_zero_bit(target_map, sbi->blocks_per_seg, start);
939 
940 	seg->next_blkoff = pos;
941 }
942 
943 /*
944  * If a segment is written by LFS manner, next block offset is just obtained
945  * by increasing the current block offset. However, if a segment is written by
946  * SSR manner, next block offset obtained by calling __next_free_blkoff
947  */
948 static void __refresh_next_blkoff(struct f2fs_sb_info *sbi,
949 				struct curseg_info *seg)
950 {
951 	if (seg->alloc_type == SSR)
952 		__next_free_blkoff(sbi, seg, seg->next_blkoff + 1);
953 	else
954 		seg->next_blkoff++;
955 }
956 
957 /*
958  * This function always allocates a used segment(from dirty seglist) by SSR
959  * manner, so it should recover the existing segment information of valid blocks
960  */
961 static void change_curseg(struct f2fs_sb_info *sbi, int type, bool reuse)
962 {
963 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
964 	struct curseg_info *curseg = CURSEG_I(sbi, type);
965 	unsigned int new_segno = curseg->next_segno;
966 	struct f2fs_summary_block *sum_node;
967 	struct page *sum_page;
968 
969 	write_sum_page(sbi, curseg->sum_blk,
970 				GET_SUM_BLOCK(sbi, curseg->segno));
971 	__set_test_and_inuse(sbi, new_segno);
972 
973 	mutex_lock(&dirty_i->seglist_lock);
974 	__remove_dirty_segment(sbi, new_segno, PRE);
975 	__remove_dirty_segment(sbi, new_segno, DIRTY);
976 	mutex_unlock(&dirty_i->seglist_lock);
977 
978 	reset_curseg(sbi, type, 1);
979 	curseg->alloc_type = SSR;
980 	__next_free_blkoff(sbi, curseg, 0);
981 
982 	if (reuse) {
983 		sum_page = get_sum_page(sbi, new_segno);
984 		sum_node = (struct f2fs_summary_block *)page_address(sum_page);
985 		memcpy(curseg->sum_blk, sum_node, SUM_ENTRY_SIZE);
986 		f2fs_put_page(sum_page, 1);
987 	}
988 }
989 
990 static int get_ssr_segment(struct f2fs_sb_info *sbi, int type)
991 {
992 	struct curseg_info *curseg = CURSEG_I(sbi, type);
993 	const struct victim_selection *v_ops = DIRTY_I(sbi)->v_ops;
994 
995 	if (IS_NODESEG(type) || !has_not_enough_free_secs(sbi, 0))
996 		return v_ops->get_victim(sbi,
997 				&(curseg)->next_segno, BG_GC, type, SSR);
998 
999 	/* For data segments, let's do SSR more intensively */
1000 	for (; type >= CURSEG_HOT_DATA; type--)
1001 		if (v_ops->get_victim(sbi, &(curseg)->next_segno,
1002 						BG_GC, type, SSR))
1003 			return 1;
1004 	return 0;
1005 }
1006 
1007 /*
1008  * flush out current segment and replace it with new segment
1009  * This function should be returned with success, otherwise BUG
1010  */
1011 static void allocate_segment_by_default(struct f2fs_sb_info *sbi,
1012 						int type, bool force)
1013 {
1014 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1015 
1016 	if (force)
1017 		new_curseg(sbi, type, true);
1018 	else if (type == CURSEG_WARM_NODE)
1019 		new_curseg(sbi, type, false);
1020 	else if (curseg->alloc_type == LFS && is_next_segment_free(sbi, type))
1021 		new_curseg(sbi, type, false);
1022 	else if (need_SSR(sbi) && get_ssr_segment(sbi, type))
1023 		change_curseg(sbi, type, true);
1024 	else
1025 		new_curseg(sbi, type, false);
1026 
1027 	stat_inc_seg_type(sbi, curseg);
1028 }
1029 
1030 void allocate_new_segments(struct f2fs_sb_info *sbi)
1031 {
1032 	struct curseg_info *curseg;
1033 	unsigned int old_curseg;
1034 	int i;
1035 
1036 	for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
1037 		curseg = CURSEG_I(sbi, i);
1038 		old_curseg = curseg->segno;
1039 		SIT_I(sbi)->s_ops->allocate_segment(sbi, i, true);
1040 		locate_dirty_segment(sbi, old_curseg);
1041 	}
1042 }
1043 
1044 static const struct segment_allocation default_salloc_ops = {
1045 	.allocate_segment = allocate_segment_by_default,
1046 };
1047 
1048 int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range)
1049 {
1050 	__u64 start = range->start >> sbi->log_blocksize;
1051 	__u64 end = start + (range->len >> sbi->log_blocksize) - 1;
1052 	unsigned int start_segno, end_segno;
1053 	struct cp_control cpc;
1054 
1055 	if (range->minlen > SEGMENT_SIZE(sbi) || start >= MAX_BLKADDR(sbi) ||
1056 						range->len < sbi->blocksize)
1057 		return -EINVAL;
1058 
1059 	cpc.trimmed = 0;
1060 	if (end <= MAIN_BLKADDR(sbi))
1061 		goto out;
1062 
1063 	/* start/end segment number in main_area */
1064 	start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start);
1065 	end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 :
1066 						GET_SEGNO(sbi, end);
1067 	cpc.reason = CP_DISCARD;
1068 	cpc.trim_start = start_segno;
1069 	cpc.trim_end = end_segno;
1070 	cpc.trim_minlen = range->minlen >> sbi->log_blocksize;
1071 
1072 	/* do checkpoint to issue discard commands safely */
1073 	mutex_lock(&sbi->gc_mutex);
1074 	write_checkpoint(sbi, &cpc);
1075 	mutex_unlock(&sbi->gc_mutex);
1076 out:
1077 	range->len = cpc.trimmed << sbi->log_blocksize;
1078 	return 0;
1079 }
1080 
1081 static bool __has_curseg_space(struct f2fs_sb_info *sbi, int type)
1082 {
1083 	struct curseg_info *curseg = CURSEG_I(sbi, type);
1084 	if (curseg->next_blkoff < sbi->blocks_per_seg)
1085 		return true;
1086 	return false;
1087 }
1088 
1089 static int __get_segment_type_2(struct page *page, enum page_type p_type)
1090 {
1091 	if (p_type == DATA)
1092 		return CURSEG_HOT_DATA;
1093 	else
1094 		return CURSEG_HOT_NODE;
1095 }
1096 
1097 static int __get_segment_type_4(struct page *page, enum page_type p_type)
1098 {
1099 	if (p_type == DATA) {
1100 		struct inode *inode = page->mapping->host;
1101 
1102 		if (S_ISDIR(inode->i_mode))
1103 			return CURSEG_HOT_DATA;
1104 		else
1105 			return CURSEG_COLD_DATA;
1106 	} else {
1107 		if (IS_DNODE(page) && is_cold_node(page))
1108 			return CURSEG_WARM_NODE;
1109 		else
1110 			return CURSEG_COLD_NODE;
1111 	}
1112 }
1113 
1114 static int __get_segment_type_6(struct page *page, enum page_type p_type)
1115 {
1116 	if (p_type == DATA) {
1117 		struct inode *inode = page->mapping->host;
1118 
1119 		if (S_ISDIR(inode->i_mode))
1120 			return CURSEG_HOT_DATA;
1121 		else if (is_cold_data(page) || file_is_cold(inode))
1122 			return CURSEG_COLD_DATA;
1123 		else
1124 			return CURSEG_WARM_DATA;
1125 	} else {
1126 		if (IS_DNODE(page))
1127 			return is_cold_node(page) ? CURSEG_WARM_NODE :
1128 						CURSEG_HOT_NODE;
1129 		else
1130 			return CURSEG_COLD_NODE;
1131 	}
1132 }
1133 
1134 static int __get_segment_type(struct page *page, enum page_type p_type)
1135 {
1136 	switch (F2FS_P_SB(page)->active_logs) {
1137 	case 2:
1138 		return __get_segment_type_2(page, p_type);
1139 	case 4:
1140 		return __get_segment_type_4(page, p_type);
1141 	}
1142 	/* NR_CURSEG_TYPE(6) logs by default */
1143 	f2fs_bug_on(F2FS_P_SB(page),
1144 		F2FS_P_SB(page)->active_logs != NR_CURSEG_TYPE);
1145 	return __get_segment_type_6(page, p_type);
1146 }
1147 
1148 void allocate_data_block(struct f2fs_sb_info *sbi, struct page *page,
1149 		block_t old_blkaddr, block_t *new_blkaddr,
1150 		struct f2fs_summary *sum, int type)
1151 {
1152 	struct sit_info *sit_i = SIT_I(sbi);
1153 	struct curseg_info *curseg;
1154 
1155 	curseg = CURSEG_I(sbi, type);
1156 
1157 	mutex_lock(&curseg->curseg_mutex);
1158 
1159 	*new_blkaddr = NEXT_FREE_BLKADDR(sbi, curseg);
1160 
1161 	/*
1162 	 * __add_sum_entry should be resided under the curseg_mutex
1163 	 * because, this function updates a summary entry in the
1164 	 * current summary block.
1165 	 */
1166 	__add_sum_entry(sbi, type, sum);
1167 
1168 	mutex_lock(&sit_i->sentry_lock);
1169 	__refresh_next_blkoff(sbi, curseg);
1170 
1171 	stat_inc_block_count(sbi, curseg);
1172 
1173 	if (!__has_curseg_space(sbi, type))
1174 		sit_i->s_ops->allocate_segment(sbi, type, false);
1175 	/*
1176 	 * SIT information should be updated before segment allocation,
1177 	 * since SSR needs latest valid block information.
1178 	 */
1179 	refresh_sit_entry(sbi, old_blkaddr, *new_blkaddr);
1180 
1181 	mutex_unlock(&sit_i->sentry_lock);
1182 
1183 	if (page && IS_NODESEG(type))
1184 		fill_node_footer_blkaddr(page, NEXT_FREE_BLKADDR(sbi, curseg));
1185 
1186 	mutex_unlock(&curseg->curseg_mutex);
1187 }
1188 
1189 static void do_write_page(struct f2fs_sb_info *sbi, struct page *page,
1190 			block_t old_blkaddr, block_t *new_blkaddr,
1191 			struct f2fs_summary *sum, struct f2fs_io_info *fio)
1192 {
1193 	int type = __get_segment_type(page, fio->type);
1194 
1195 	allocate_data_block(sbi, page, old_blkaddr, new_blkaddr, sum, type);
1196 
1197 	/* writeout dirty page into bdev */
1198 	f2fs_submit_page_mbio(sbi, page, *new_blkaddr, fio);
1199 }
1200 
1201 void write_meta_page(struct f2fs_sb_info *sbi, struct page *page)
1202 {
1203 	struct f2fs_io_info fio = {
1204 		.type = META,
1205 		.rw = WRITE_SYNC | REQ_META | REQ_PRIO
1206 	};
1207 
1208 	set_page_writeback(page);
1209 	f2fs_submit_page_mbio(sbi, page, page->index, &fio);
1210 }
1211 
1212 void write_node_page(struct f2fs_sb_info *sbi, struct page *page,
1213 		struct f2fs_io_info *fio,
1214 		unsigned int nid, block_t old_blkaddr, block_t *new_blkaddr)
1215 {
1216 	struct f2fs_summary sum;
1217 	set_summary(&sum, nid, 0, 0);
1218 	do_write_page(sbi, page, old_blkaddr, new_blkaddr, &sum, fio);
1219 }
1220 
1221 void write_data_page(struct page *page, struct dnode_of_data *dn,
1222 		block_t *new_blkaddr, struct f2fs_io_info *fio)
1223 {
1224 	struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
1225 	struct f2fs_summary sum;
1226 	struct node_info ni;
1227 
1228 	f2fs_bug_on(sbi, dn->data_blkaddr == NULL_ADDR);
1229 	get_node_info(sbi, dn->nid, &ni);
1230 	set_summary(&sum, dn->nid, dn->ofs_in_node, ni.version);
1231 
1232 	do_write_page(sbi, page, dn->data_blkaddr, new_blkaddr, &sum, fio);
1233 }
1234 
1235 void rewrite_data_page(struct page *page, block_t old_blkaddr,
1236 					struct f2fs_io_info *fio)
1237 {
1238 	f2fs_submit_page_mbio(F2FS_P_SB(page), page, old_blkaddr, fio);
1239 }
1240 
1241 void recover_data_page(struct f2fs_sb_info *sbi,
1242 			struct page *page, struct f2fs_summary *sum,
1243 			block_t old_blkaddr, block_t new_blkaddr)
1244 {
1245 	struct sit_info *sit_i = SIT_I(sbi);
1246 	struct curseg_info *curseg;
1247 	unsigned int segno, old_cursegno;
1248 	struct seg_entry *se;
1249 	int type;
1250 
1251 	segno = GET_SEGNO(sbi, new_blkaddr);
1252 	se = get_seg_entry(sbi, segno);
1253 	type = se->type;
1254 
1255 	if (se->valid_blocks == 0 && !IS_CURSEG(sbi, segno)) {
1256 		if (old_blkaddr == NULL_ADDR)
1257 			type = CURSEG_COLD_DATA;
1258 		else
1259 			type = CURSEG_WARM_DATA;
1260 	}
1261 	curseg = CURSEG_I(sbi, type);
1262 
1263 	mutex_lock(&curseg->curseg_mutex);
1264 	mutex_lock(&sit_i->sentry_lock);
1265 
1266 	old_cursegno = curseg->segno;
1267 
1268 	/* change the current segment */
1269 	if (segno != curseg->segno) {
1270 		curseg->next_segno = segno;
1271 		change_curseg(sbi, type, true);
1272 	}
1273 
1274 	curseg->next_blkoff = GET_BLKOFF_FROM_SEG0(sbi, new_blkaddr);
1275 	__add_sum_entry(sbi, type, sum);
1276 
1277 	refresh_sit_entry(sbi, old_blkaddr, new_blkaddr);
1278 	locate_dirty_segment(sbi, old_cursegno);
1279 
1280 	mutex_unlock(&sit_i->sentry_lock);
1281 	mutex_unlock(&curseg->curseg_mutex);
1282 }
1283 
1284 static inline bool is_merged_page(struct f2fs_sb_info *sbi,
1285 					struct page *page, enum page_type type)
1286 {
1287 	enum page_type btype = PAGE_TYPE_OF_BIO(type);
1288 	struct f2fs_bio_info *io = &sbi->write_io[btype];
1289 	struct bio_vec *bvec;
1290 	int i;
1291 
1292 	down_read(&io->io_rwsem);
1293 	if (!io->bio)
1294 		goto out;
1295 
1296 	bio_for_each_segment_all(bvec, io->bio, i) {
1297 		if (page == bvec->bv_page) {
1298 			up_read(&io->io_rwsem);
1299 			return true;
1300 		}
1301 	}
1302 
1303 out:
1304 	up_read(&io->io_rwsem);
1305 	return false;
1306 }
1307 
1308 void f2fs_wait_on_page_writeback(struct page *page,
1309 				enum page_type type)
1310 {
1311 	if (PageWriteback(page)) {
1312 		struct f2fs_sb_info *sbi = F2FS_P_SB(page);
1313 
1314 		if (is_merged_page(sbi, page, type))
1315 			f2fs_submit_merged_bio(sbi, type, WRITE);
1316 		wait_on_page_writeback(page);
1317 	}
1318 }
1319 
1320 static int read_compacted_summaries(struct f2fs_sb_info *sbi)
1321 {
1322 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
1323 	struct curseg_info *seg_i;
1324 	unsigned char *kaddr;
1325 	struct page *page;
1326 	block_t start;
1327 	int i, j, offset;
1328 
1329 	start = start_sum_block(sbi);
1330 
1331 	page = get_meta_page(sbi, start++);
1332 	kaddr = (unsigned char *)page_address(page);
1333 
1334 	/* Step 1: restore nat cache */
1335 	seg_i = CURSEG_I(sbi, CURSEG_HOT_DATA);
1336 	memcpy(&seg_i->sum_blk->n_nats, kaddr, SUM_JOURNAL_SIZE);
1337 
1338 	/* Step 2: restore sit cache */
1339 	seg_i = CURSEG_I(sbi, CURSEG_COLD_DATA);
1340 	memcpy(&seg_i->sum_blk->n_sits, kaddr + SUM_JOURNAL_SIZE,
1341 						SUM_JOURNAL_SIZE);
1342 	offset = 2 * SUM_JOURNAL_SIZE;
1343 
1344 	/* Step 3: restore summary entries */
1345 	for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
1346 		unsigned short blk_off;
1347 		unsigned int segno;
1348 
1349 		seg_i = CURSEG_I(sbi, i);
1350 		segno = le32_to_cpu(ckpt->cur_data_segno[i]);
1351 		blk_off = le16_to_cpu(ckpt->cur_data_blkoff[i]);
1352 		seg_i->next_segno = segno;
1353 		reset_curseg(sbi, i, 0);
1354 		seg_i->alloc_type = ckpt->alloc_type[i];
1355 		seg_i->next_blkoff = blk_off;
1356 
1357 		if (seg_i->alloc_type == SSR)
1358 			blk_off = sbi->blocks_per_seg;
1359 
1360 		for (j = 0; j < blk_off; j++) {
1361 			struct f2fs_summary *s;
1362 			s = (struct f2fs_summary *)(kaddr + offset);
1363 			seg_i->sum_blk->entries[j] = *s;
1364 			offset += SUMMARY_SIZE;
1365 			if (offset + SUMMARY_SIZE <= PAGE_CACHE_SIZE -
1366 						SUM_FOOTER_SIZE)
1367 				continue;
1368 
1369 			f2fs_put_page(page, 1);
1370 			page = NULL;
1371 
1372 			page = get_meta_page(sbi, start++);
1373 			kaddr = (unsigned char *)page_address(page);
1374 			offset = 0;
1375 		}
1376 	}
1377 	f2fs_put_page(page, 1);
1378 	return 0;
1379 }
1380 
1381 static int read_normal_summaries(struct f2fs_sb_info *sbi, int type)
1382 {
1383 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
1384 	struct f2fs_summary_block *sum;
1385 	struct curseg_info *curseg;
1386 	struct page *new;
1387 	unsigned short blk_off;
1388 	unsigned int segno = 0;
1389 	block_t blk_addr = 0;
1390 
1391 	/* get segment number and block addr */
1392 	if (IS_DATASEG(type)) {
1393 		segno = le32_to_cpu(ckpt->cur_data_segno[type]);
1394 		blk_off = le16_to_cpu(ckpt->cur_data_blkoff[type -
1395 							CURSEG_HOT_DATA]);
1396 		if (is_set_ckpt_flags(ckpt, CP_UMOUNT_FLAG))
1397 			blk_addr = sum_blk_addr(sbi, NR_CURSEG_TYPE, type);
1398 		else
1399 			blk_addr = sum_blk_addr(sbi, NR_CURSEG_DATA_TYPE, type);
1400 	} else {
1401 		segno = le32_to_cpu(ckpt->cur_node_segno[type -
1402 							CURSEG_HOT_NODE]);
1403 		blk_off = le16_to_cpu(ckpt->cur_node_blkoff[type -
1404 							CURSEG_HOT_NODE]);
1405 		if (is_set_ckpt_flags(ckpt, CP_UMOUNT_FLAG))
1406 			blk_addr = sum_blk_addr(sbi, NR_CURSEG_NODE_TYPE,
1407 							type - CURSEG_HOT_NODE);
1408 		else
1409 			blk_addr = GET_SUM_BLOCK(sbi, segno);
1410 	}
1411 
1412 	new = get_meta_page(sbi, blk_addr);
1413 	sum = (struct f2fs_summary_block *)page_address(new);
1414 
1415 	if (IS_NODESEG(type)) {
1416 		if (is_set_ckpt_flags(ckpt, CP_UMOUNT_FLAG)) {
1417 			struct f2fs_summary *ns = &sum->entries[0];
1418 			int i;
1419 			for (i = 0; i < sbi->blocks_per_seg; i++, ns++) {
1420 				ns->version = 0;
1421 				ns->ofs_in_node = 0;
1422 			}
1423 		} else {
1424 			int err;
1425 
1426 			err = restore_node_summary(sbi, segno, sum);
1427 			if (err) {
1428 				f2fs_put_page(new, 1);
1429 				return err;
1430 			}
1431 		}
1432 	}
1433 
1434 	/* set uncompleted segment to curseg */
1435 	curseg = CURSEG_I(sbi, type);
1436 	mutex_lock(&curseg->curseg_mutex);
1437 	memcpy(curseg->sum_blk, sum, PAGE_CACHE_SIZE);
1438 	curseg->next_segno = segno;
1439 	reset_curseg(sbi, type, 0);
1440 	curseg->alloc_type = ckpt->alloc_type[type];
1441 	curseg->next_blkoff = blk_off;
1442 	mutex_unlock(&curseg->curseg_mutex);
1443 	f2fs_put_page(new, 1);
1444 	return 0;
1445 }
1446 
1447 static int restore_curseg_summaries(struct f2fs_sb_info *sbi)
1448 {
1449 	int type = CURSEG_HOT_DATA;
1450 	int err;
1451 
1452 	if (is_set_ckpt_flags(F2FS_CKPT(sbi), CP_COMPACT_SUM_FLAG)) {
1453 		/* restore for compacted data summary */
1454 		if (read_compacted_summaries(sbi))
1455 			return -EINVAL;
1456 		type = CURSEG_HOT_NODE;
1457 	}
1458 
1459 	for (; type <= CURSEG_COLD_NODE; type++) {
1460 		err = read_normal_summaries(sbi, type);
1461 		if (err)
1462 			return err;
1463 	}
1464 
1465 	return 0;
1466 }
1467 
1468 static void write_compacted_summaries(struct f2fs_sb_info *sbi, block_t blkaddr)
1469 {
1470 	struct page *page;
1471 	unsigned char *kaddr;
1472 	struct f2fs_summary *summary;
1473 	struct curseg_info *seg_i;
1474 	int written_size = 0;
1475 	int i, j;
1476 
1477 	page = grab_meta_page(sbi, blkaddr++);
1478 	kaddr = (unsigned char *)page_address(page);
1479 
1480 	/* Step 1: write nat cache */
1481 	seg_i = CURSEG_I(sbi, CURSEG_HOT_DATA);
1482 	memcpy(kaddr, &seg_i->sum_blk->n_nats, SUM_JOURNAL_SIZE);
1483 	written_size += SUM_JOURNAL_SIZE;
1484 
1485 	/* Step 2: write sit cache */
1486 	seg_i = CURSEG_I(sbi, CURSEG_COLD_DATA);
1487 	memcpy(kaddr + written_size, &seg_i->sum_blk->n_sits,
1488 						SUM_JOURNAL_SIZE);
1489 	written_size += SUM_JOURNAL_SIZE;
1490 
1491 	/* Step 3: write summary entries */
1492 	for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
1493 		unsigned short blkoff;
1494 		seg_i = CURSEG_I(sbi, i);
1495 		if (sbi->ckpt->alloc_type[i] == SSR)
1496 			blkoff = sbi->blocks_per_seg;
1497 		else
1498 			blkoff = curseg_blkoff(sbi, i);
1499 
1500 		for (j = 0; j < blkoff; j++) {
1501 			if (!page) {
1502 				page = grab_meta_page(sbi, blkaddr++);
1503 				kaddr = (unsigned char *)page_address(page);
1504 				written_size = 0;
1505 			}
1506 			summary = (struct f2fs_summary *)(kaddr + written_size);
1507 			*summary = seg_i->sum_blk->entries[j];
1508 			written_size += SUMMARY_SIZE;
1509 
1510 			if (written_size + SUMMARY_SIZE <= PAGE_CACHE_SIZE -
1511 							SUM_FOOTER_SIZE)
1512 				continue;
1513 
1514 			set_page_dirty(page);
1515 			f2fs_put_page(page, 1);
1516 			page = NULL;
1517 		}
1518 	}
1519 	if (page) {
1520 		set_page_dirty(page);
1521 		f2fs_put_page(page, 1);
1522 	}
1523 }
1524 
1525 static void write_normal_summaries(struct f2fs_sb_info *sbi,
1526 					block_t blkaddr, int type)
1527 {
1528 	int i, end;
1529 	if (IS_DATASEG(type))
1530 		end = type + NR_CURSEG_DATA_TYPE;
1531 	else
1532 		end = type + NR_CURSEG_NODE_TYPE;
1533 
1534 	for (i = type; i < end; i++) {
1535 		struct curseg_info *sum = CURSEG_I(sbi, i);
1536 		mutex_lock(&sum->curseg_mutex);
1537 		write_sum_page(sbi, sum->sum_blk, blkaddr + (i - type));
1538 		mutex_unlock(&sum->curseg_mutex);
1539 	}
1540 }
1541 
1542 void write_data_summaries(struct f2fs_sb_info *sbi, block_t start_blk)
1543 {
1544 	if (is_set_ckpt_flags(F2FS_CKPT(sbi), CP_COMPACT_SUM_FLAG))
1545 		write_compacted_summaries(sbi, start_blk);
1546 	else
1547 		write_normal_summaries(sbi, start_blk, CURSEG_HOT_DATA);
1548 }
1549 
1550 void write_node_summaries(struct f2fs_sb_info *sbi, block_t start_blk)
1551 {
1552 	if (is_set_ckpt_flags(F2FS_CKPT(sbi), CP_UMOUNT_FLAG))
1553 		write_normal_summaries(sbi, start_blk, CURSEG_HOT_NODE);
1554 }
1555 
1556 int lookup_journal_in_cursum(struct f2fs_summary_block *sum, int type,
1557 					unsigned int val, int alloc)
1558 {
1559 	int i;
1560 
1561 	if (type == NAT_JOURNAL) {
1562 		for (i = 0; i < nats_in_cursum(sum); i++) {
1563 			if (le32_to_cpu(nid_in_journal(sum, i)) == val)
1564 				return i;
1565 		}
1566 		if (alloc && nats_in_cursum(sum) < NAT_JOURNAL_ENTRIES)
1567 			return update_nats_in_cursum(sum, 1);
1568 	} else if (type == SIT_JOURNAL) {
1569 		for (i = 0; i < sits_in_cursum(sum); i++)
1570 			if (le32_to_cpu(segno_in_journal(sum, i)) == val)
1571 				return i;
1572 		if (alloc && sits_in_cursum(sum) < SIT_JOURNAL_ENTRIES)
1573 			return update_sits_in_cursum(sum, 1);
1574 	}
1575 	return -1;
1576 }
1577 
1578 static struct page *get_current_sit_page(struct f2fs_sb_info *sbi,
1579 					unsigned int segno)
1580 {
1581 	return get_meta_page(sbi, current_sit_addr(sbi, segno));
1582 }
1583 
1584 static struct page *get_next_sit_page(struct f2fs_sb_info *sbi,
1585 					unsigned int start)
1586 {
1587 	struct sit_info *sit_i = SIT_I(sbi);
1588 	struct page *src_page, *dst_page;
1589 	pgoff_t src_off, dst_off;
1590 	void *src_addr, *dst_addr;
1591 
1592 	src_off = current_sit_addr(sbi, start);
1593 	dst_off = next_sit_addr(sbi, src_off);
1594 
1595 	/* get current sit block page without lock */
1596 	src_page = get_meta_page(sbi, src_off);
1597 	dst_page = grab_meta_page(sbi, dst_off);
1598 	f2fs_bug_on(sbi, PageDirty(src_page));
1599 
1600 	src_addr = page_address(src_page);
1601 	dst_addr = page_address(dst_page);
1602 	memcpy(dst_addr, src_addr, PAGE_CACHE_SIZE);
1603 
1604 	set_page_dirty(dst_page);
1605 	f2fs_put_page(src_page, 1);
1606 
1607 	set_to_next_sit(sit_i, start);
1608 
1609 	return dst_page;
1610 }
1611 
1612 static struct sit_entry_set *grab_sit_entry_set(void)
1613 {
1614 	struct sit_entry_set *ses =
1615 			f2fs_kmem_cache_alloc(sit_entry_set_slab, GFP_ATOMIC);
1616 
1617 	ses->entry_cnt = 0;
1618 	INIT_LIST_HEAD(&ses->set_list);
1619 	return ses;
1620 }
1621 
1622 static void release_sit_entry_set(struct sit_entry_set *ses)
1623 {
1624 	list_del(&ses->set_list);
1625 	kmem_cache_free(sit_entry_set_slab, ses);
1626 }
1627 
1628 static void adjust_sit_entry_set(struct sit_entry_set *ses,
1629 						struct list_head *head)
1630 {
1631 	struct sit_entry_set *next = ses;
1632 
1633 	if (list_is_last(&ses->set_list, head))
1634 		return;
1635 
1636 	list_for_each_entry_continue(next, head, set_list)
1637 		if (ses->entry_cnt <= next->entry_cnt)
1638 			break;
1639 
1640 	list_move_tail(&ses->set_list, &next->set_list);
1641 }
1642 
1643 static void add_sit_entry(unsigned int segno, struct list_head *head)
1644 {
1645 	struct sit_entry_set *ses;
1646 	unsigned int start_segno = START_SEGNO(segno);
1647 
1648 	list_for_each_entry(ses, head, set_list) {
1649 		if (ses->start_segno == start_segno) {
1650 			ses->entry_cnt++;
1651 			adjust_sit_entry_set(ses, head);
1652 			return;
1653 		}
1654 	}
1655 
1656 	ses = grab_sit_entry_set();
1657 
1658 	ses->start_segno = start_segno;
1659 	ses->entry_cnt++;
1660 	list_add(&ses->set_list, head);
1661 }
1662 
1663 static void add_sits_in_set(struct f2fs_sb_info *sbi)
1664 {
1665 	struct f2fs_sm_info *sm_info = SM_I(sbi);
1666 	struct list_head *set_list = &sm_info->sit_entry_set;
1667 	unsigned long *bitmap = SIT_I(sbi)->dirty_sentries_bitmap;
1668 	unsigned int segno;
1669 
1670 	for_each_set_bit(segno, bitmap, MAIN_SEGS(sbi))
1671 		add_sit_entry(segno, set_list);
1672 }
1673 
1674 static void remove_sits_in_journal(struct f2fs_sb_info *sbi)
1675 {
1676 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
1677 	struct f2fs_summary_block *sum = curseg->sum_blk;
1678 	int i;
1679 
1680 	for (i = sits_in_cursum(sum) - 1; i >= 0; i--) {
1681 		unsigned int segno;
1682 		bool dirtied;
1683 
1684 		segno = le32_to_cpu(segno_in_journal(sum, i));
1685 		dirtied = __mark_sit_entry_dirty(sbi, segno);
1686 
1687 		if (!dirtied)
1688 			add_sit_entry(segno, &SM_I(sbi)->sit_entry_set);
1689 	}
1690 	update_sits_in_cursum(sum, -sits_in_cursum(sum));
1691 }
1692 
1693 /*
1694  * CP calls this function, which flushes SIT entries including sit_journal,
1695  * and moves prefree segs to free segs.
1696  */
1697 void flush_sit_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc)
1698 {
1699 	struct sit_info *sit_i = SIT_I(sbi);
1700 	unsigned long *bitmap = sit_i->dirty_sentries_bitmap;
1701 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
1702 	struct f2fs_summary_block *sum = curseg->sum_blk;
1703 	struct sit_entry_set *ses, *tmp;
1704 	struct list_head *head = &SM_I(sbi)->sit_entry_set;
1705 	bool to_journal = true;
1706 	struct seg_entry *se;
1707 
1708 	mutex_lock(&curseg->curseg_mutex);
1709 	mutex_lock(&sit_i->sentry_lock);
1710 
1711 	/*
1712 	 * add and account sit entries of dirty bitmap in sit entry
1713 	 * set temporarily
1714 	 */
1715 	add_sits_in_set(sbi);
1716 
1717 	/*
1718 	 * if there are no enough space in journal to store dirty sit
1719 	 * entries, remove all entries from journal and add and account
1720 	 * them in sit entry set.
1721 	 */
1722 	if (!__has_cursum_space(sum, sit_i->dirty_sentries, SIT_JOURNAL))
1723 		remove_sits_in_journal(sbi);
1724 
1725 	if (!sit_i->dirty_sentries)
1726 		goto out;
1727 
1728 	/*
1729 	 * there are two steps to flush sit entries:
1730 	 * #1, flush sit entries to journal in current cold data summary block.
1731 	 * #2, flush sit entries to sit page.
1732 	 */
1733 	list_for_each_entry_safe(ses, tmp, head, set_list) {
1734 		struct page *page = NULL;
1735 		struct f2fs_sit_block *raw_sit = NULL;
1736 		unsigned int start_segno = ses->start_segno;
1737 		unsigned int end = min(start_segno + SIT_ENTRY_PER_BLOCK,
1738 						(unsigned long)MAIN_SEGS(sbi));
1739 		unsigned int segno = start_segno;
1740 
1741 		if (to_journal &&
1742 			!__has_cursum_space(sum, ses->entry_cnt, SIT_JOURNAL))
1743 			to_journal = false;
1744 
1745 		if (!to_journal) {
1746 			page = get_next_sit_page(sbi, start_segno);
1747 			raw_sit = page_address(page);
1748 		}
1749 
1750 		/* flush dirty sit entries in region of current sit set */
1751 		for_each_set_bit_from(segno, bitmap, end) {
1752 			int offset, sit_offset;
1753 
1754 			se = get_seg_entry(sbi, segno);
1755 
1756 			/* add discard candidates */
1757 			if (SM_I(sbi)->nr_discards < SM_I(sbi)->max_discards) {
1758 				cpc->trim_start = segno;
1759 				add_discard_addrs(sbi, cpc);
1760 			}
1761 
1762 			if (to_journal) {
1763 				offset = lookup_journal_in_cursum(sum,
1764 							SIT_JOURNAL, segno, 1);
1765 				f2fs_bug_on(sbi, offset < 0);
1766 				segno_in_journal(sum, offset) =
1767 							cpu_to_le32(segno);
1768 				seg_info_to_raw_sit(se,
1769 						&sit_in_journal(sum, offset));
1770 			} else {
1771 				sit_offset = SIT_ENTRY_OFFSET(sit_i, segno);
1772 				seg_info_to_raw_sit(se,
1773 						&raw_sit->entries[sit_offset]);
1774 			}
1775 
1776 			__clear_bit(segno, bitmap);
1777 			sit_i->dirty_sentries--;
1778 			ses->entry_cnt--;
1779 		}
1780 
1781 		if (!to_journal)
1782 			f2fs_put_page(page, 1);
1783 
1784 		f2fs_bug_on(sbi, ses->entry_cnt);
1785 		release_sit_entry_set(ses);
1786 	}
1787 
1788 	f2fs_bug_on(sbi, !list_empty(head));
1789 	f2fs_bug_on(sbi, sit_i->dirty_sentries);
1790 out:
1791 	if (cpc->reason == CP_DISCARD) {
1792 		for (; cpc->trim_start <= cpc->trim_end; cpc->trim_start++)
1793 			add_discard_addrs(sbi, cpc);
1794 	}
1795 	mutex_unlock(&sit_i->sentry_lock);
1796 	mutex_unlock(&curseg->curseg_mutex);
1797 
1798 	set_prefree_as_free_segments(sbi);
1799 }
1800 
1801 static int build_sit_info(struct f2fs_sb_info *sbi)
1802 {
1803 	struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
1804 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
1805 	struct sit_info *sit_i;
1806 	unsigned int sit_segs, start;
1807 	char *src_bitmap, *dst_bitmap;
1808 	unsigned int bitmap_size;
1809 
1810 	/* allocate memory for SIT information */
1811 	sit_i = kzalloc(sizeof(struct sit_info), GFP_KERNEL);
1812 	if (!sit_i)
1813 		return -ENOMEM;
1814 
1815 	SM_I(sbi)->sit_info = sit_i;
1816 
1817 	sit_i->sentries = vzalloc(MAIN_SEGS(sbi) * sizeof(struct seg_entry));
1818 	if (!sit_i->sentries)
1819 		return -ENOMEM;
1820 
1821 	bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
1822 	sit_i->dirty_sentries_bitmap = kzalloc(bitmap_size, GFP_KERNEL);
1823 	if (!sit_i->dirty_sentries_bitmap)
1824 		return -ENOMEM;
1825 
1826 	for (start = 0; start < MAIN_SEGS(sbi); start++) {
1827 		sit_i->sentries[start].cur_valid_map
1828 			= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
1829 		sit_i->sentries[start].ckpt_valid_map
1830 			= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
1831 		if (!sit_i->sentries[start].cur_valid_map
1832 				|| !sit_i->sentries[start].ckpt_valid_map)
1833 			return -ENOMEM;
1834 	}
1835 
1836 	if (sbi->segs_per_sec > 1) {
1837 		sit_i->sec_entries = vzalloc(MAIN_SECS(sbi) *
1838 					sizeof(struct sec_entry));
1839 		if (!sit_i->sec_entries)
1840 			return -ENOMEM;
1841 	}
1842 
1843 	/* get information related with SIT */
1844 	sit_segs = le32_to_cpu(raw_super->segment_count_sit) >> 1;
1845 
1846 	/* setup SIT bitmap from ckeckpoint pack */
1847 	bitmap_size = __bitmap_size(sbi, SIT_BITMAP);
1848 	src_bitmap = __bitmap_ptr(sbi, SIT_BITMAP);
1849 
1850 	dst_bitmap = kmemdup(src_bitmap, bitmap_size, GFP_KERNEL);
1851 	if (!dst_bitmap)
1852 		return -ENOMEM;
1853 
1854 	/* init SIT information */
1855 	sit_i->s_ops = &default_salloc_ops;
1856 
1857 	sit_i->sit_base_addr = le32_to_cpu(raw_super->sit_blkaddr);
1858 	sit_i->sit_blocks = sit_segs << sbi->log_blocks_per_seg;
1859 	sit_i->written_valid_blocks = le64_to_cpu(ckpt->valid_block_count);
1860 	sit_i->sit_bitmap = dst_bitmap;
1861 	sit_i->bitmap_size = bitmap_size;
1862 	sit_i->dirty_sentries = 0;
1863 	sit_i->sents_per_block = SIT_ENTRY_PER_BLOCK;
1864 	sit_i->elapsed_time = le64_to_cpu(sbi->ckpt->elapsed_time);
1865 	sit_i->mounted_time = CURRENT_TIME_SEC.tv_sec;
1866 	mutex_init(&sit_i->sentry_lock);
1867 	return 0;
1868 }
1869 
1870 static int build_free_segmap(struct f2fs_sb_info *sbi)
1871 {
1872 	struct free_segmap_info *free_i;
1873 	unsigned int bitmap_size, sec_bitmap_size;
1874 
1875 	/* allocate memory for free segmap information */
1876 	free_i = kzalloc(sizeof(struct free_segmap_info), GFP_KERNEL);
1877 	if (!free_i)
1878 		return -ENOMEM;
1879 
1880 	SM_I(sbi)->free_info = free_i;
1881 
1882 	bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
1883 	free_i->free_segmap = kmalloc(bitmap_size, GFP_KERNEL);
1884 	if (!free_i->free_segmap)
1885 		return -ENOMEM;
1886 
1887 	sec_bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
1888 	free_i->free_secmap = kmalloc(sec_bitmap_size, GFP_KERNEL);
1889 	if (!free_i->free_secmap)
1890 		return -ENOMEM;
1891 
1892 	/* set all segments as dirty temporarily */
1893 	memset(free_i->free_segmap, 0xff, bitmap_size);
1894 	memset(free_i->free_secmap, 0xff, sec_bitmap_size);
1895 
1896 	/* init free segmap information */
1897 	free_i->start_segno = GET_SEGNO_FROM_SEG0(sbi, MAIN_BLKADDR(sbi));
1898 	free_i->free_segments = 0;
1899 	free_i->free_sections = 0;
1900 	rwlock_init(&free_i->segmap_lock);
1901 	return 0;
1902 }
1903 
1904 static int build_curseg(struct f2fs_sb_info *sbi)
1905 {
1906 	struct curseg_info *array;
1907 	int i;
1908 
1909 	array = kcalloc(NR_CURSEG_TYPE, sizeof(*array), GFP_KERNEL);
1910 	if (!array)
1911 		return -ENOMEM;
1912 
1913 	SM_I(sbi)->curseg_array = array;
1914 
1915 	for (i = 0; i < NR_CURSEG_TYPE; i++) {
1916 		mutex_init(&array[i].curseg_mutex);
1917 		array[i].sum_blk = kzalloc(PAGE_CACHE_SIZE, GFP_KERNEL);
1918 		if (!array[i].sum_blk)
1919 			return -ENOMEM;
1920 		array[i].segno = NULL_SEGNO;
1921 		array[i].next_blkoff = 0;
1922 	}
1923 	return restore_curseg_summaries(sbi);
1924 }
1925 
1926 static void build_sit_entries(struct f2fs_sb_info *sbi)
1927 {
1928 	struct sit_info *sit_i = SIT_I(sbi);
1929 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
1930 	struct f2fs_summary_block *sum = curseg->sum_blk;
1931 	int sit_blk_cnt = SIT_BLK_CNT(sbi);
1932 	unsigned int i, start, end;
1933 	unsigned int readed, start_blk = 0;
1934 	int nrpages = MAX_BIO_BLOCKS(sbi);
1935 
1936 	do {
1937 		readed = ra_meta_pages(sbi, start_blk, nrpages, META_SIT);
1938 
1939 		start = start_blk * sit_i->sents_per_block;
1940 		end = (start_blk + readed) * sit_i->sents_per_block;
1941 
1942 		for (; start < end && start < MAIN_SEGS(sbi); start++) {
1943 			struct seg_entry *se = &sit_i->sentries[start];
1944 			struct f2fs_sit_block *sit_blk;
1945 			struct f2fs_sit_entry sit;
1946 			struct page *page;
1947 
1948 			mutex_lock(&curseg->curseg_mutex);
1949 			for (i = 0; i < sits_in_cursum(sum); i++) {
1950 				if (le32_to_cpu(segno_in_journal(sum, i))
1951 								== start) {
1952 					sit = sit_in_journal(sum, i);
1953 					mutex_unlock(&curseg->curseg_mutex);
1954 					goto got_it;
1955 				}
1956 			}
1957 			mutex_unlock(&curseg->curseg_mutex);
1958 
1959 			page = get_current_sit_page(sbi, start);
1960 			sit_blk = (struct f2fs_sit_block *)page_address(page);
1961 			sit = sit_blk->entries[SIT_ENTRY_OFFSET(sit_i, start)];
1962 			f2fs_put_page(page, 1);
1963 got_it:
1964 			check_block_count(sbi, start, &sit);
1965 			seg_info_from_raw_sit(se, &sit);
1966 			if (sbi->segs_per_sec > 1) {
1967 				struct sec_entry *e = get_sec_entry(sbi, start);
1968 				e->valid_blocks += se->valid_blocks;
1969 			}
1970 		}
1971 		start_blk += readed;
1972 	} while (start_blk < sit_blk_cnt);
1973 }
1974 
1975 static void init_free_segmap(struct f2fs_sb_info *sbi)
1976 {
1977 	unsigned int start;
1978 	int type;
1979 
1980 	for (start = 0; start < MAIN_SEGS(sbi); start++) {
1981 		struct seg_entry *sentry = get_seg_entry(sbi, start);
1982 		if (!sentry->valid_blocks)
1983 			__set_free(sbi, start);
1984 	}
1985 
1986 	/* set use the current segments */
1987 	for (type = CURSEG_HOT_DATA; type <= CURSEG_COLD_NODE; type++) {
1988 		struct curseg_info *curseg_t = CURSEG_I(sbi, type);
1989 		__set_test_and_inuse(sbi, curseg_t->segno);
1990 	}
1991 }
1992 
1993 static void init_dirty_segmap(struct f2fs_sb_info *sbi)
1994 {
1995 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
1996 	struct free_segmap_info *free_i = FREE_I(sbi);
1997 	unsigned int segno = 0, offset = 0;
1998 	unsigned short valid_blocks;
1999 
2000 	while (1) {
2001 		/* find dirty segment based on free segmap */
2002 		segno = find_next_inuse(free_i, MAIN_SEGS(sbi), offset);
2003 		if (segno >= MAIN_SEGS(sbi))
2004 			break;
2005 		offset = segno + 1;
2006 		valid_blocks = get_valid_blocks(sbi, segno, 0);
2007 		if (valid_blocks == sbi->blocks_per_seg || !valid_blocks)
2008 			continue;
2009 		if (valid_blocks > sbi->blocks_per_seg) {
2010 			f2fs_bug_on(sbi, 1);
2011 			continue;
2012 		}
2013 		mutex_lock(&dirty_i->seglist_lock);
2014 		__locate_dirty_segment(sbi, segno, DIRTY);
2015 		mutex_unlock(&dirty_i->seglist_lock);
2016 	}
2017 }
2018 
2019 static int init_victim_secmap(struct f2fs_sb_info *sbi)
2020 {
2021 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
2022 	unsigned int bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
2023 
2024 	dirty_i->victim_secmap = kzalloc(bitmap_size, GFP_KERNEL);
2025 	if (!dirty_i->victim_secmap)
2026 		return -ENOMEM;
2027 	return 0;
2028 }
2029 
2030 static int build_dirty_segmap(struct f2fs_sb_info *sbi)
2031 {
2032 	struct dirty_seglist_info *dirty_i;
2033 	unsigned int bitmap_size, i;
2034 
2035 	/* allocate memory for dirty segments list information */
2036 	dirty_i = kzalloc(sizeof(struct dirty_seglist_info), GFP_KERNEL);
2037 	if (!dirty_i)
2038 		return -ENOMEM;
2039 
2040 	SM_I(sbi)->dirty_info = dirty_i;
2041 	mutex_init(&dirty_i->seglist_lock);
2042 
2043 	bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
2044 
2045 	for (i = 0; i < NR_DIRTY_TYPE; i++) {
2046 		dirty_i->dirty_segmap[i] = kzalloc(bitmap_size, GFP_KERNEL);
2047 		if (!dirty_i->dirty_segmap[i])
2048 			return -ENOMEM;
2049 	}
2050 
2051 	init_dirty_segmap(sbi);
2052 	return init_victim_secmap(sbi);
2053 }
2054 
2055 /*
2056  * Update min, max modified time for cost-benefit GC algorithm
2057  */
2058 static void init_min_max_mtime(struct f2fs_sb_info *sbi)
2059 {
2060 	struct sit_info *sit_i = SIT_I(sbi);
2061 	unsigned int segno;
2062 
2063 	mutex_lock(&sit_i->sentry_lock);
2064 
2065 	sit_i->min_mtime = LLONG_MAX;
2066 
2067 	for (segno = 0; segno < MAIN_SEGS(sbi); segno += sbi->segs_per_sec) {
2068 		unsigned int i;
2069 		unsigned long long mtime = 0;
2070 
2071 		for (i = 0; i < sbi->segs_per_sec; i++)
2072 			mtime += get_seg_entry(sbi, segno + i)->mtime;
2073 
2074 		mtime = div_u64(mtime, sbi->segs_per_sec);
2075 
2076 		if (sit_i->min_mtime > mtime)
2077 			sit_i->min_mtime = mtime;
2078 	}
2079 	sit_i->max_mtime = get_mtime(sbi);
2080 	mutex_unlock(&sit_i->sentry_lock);
2081 }
2082 
2083 int build_segment_manager(struct f2fs_sb_info *sbi)
2084 {
2085 	struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
2086 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
2087 	struct f2fs_sm_info *sm_info;
2088 	int err;
2089 
2090 	sm_info = kzalloc(sizeof(struct f2fs_sm_info), GFP_KERNEL);
2091 	if (!sm_info)
2092 		return -ENOMEM;
2093 
2094 	/* init sm info */
2095 	sbi->sm_info = sm_info;
2096 	sm_info->seg0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr);
2097 	sm_info->main_blkaddr = le32_to_cpu(raw_super->main_blkaddr);
2098 	sm_info->segment_count = le32_to_cpu(raw_super->segment_count);
2099 	sm_info->reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
2100 	sm_info->ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
2101 	sm_info->main_segments = le32_to_cpu(raw_super->segment_count_main);
2102 	sm_info->ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr);
2103 	sm_info->rec_prefree_segments = sm_info->main_segments *
2104 					DEF_RECLAIM_PREFREE_SEGMENTS / 100;
2105 	sm_info->ipu_policy = 1 << F2FS_IPU_FSYNC;
2106 	sm_info->min_ipu_util = DEF_MIN_IPU_UTIL;
2107 	sm_info->min_fsync_blocks = DEF_MIN_FSYNC_BLOCKS;
2108 
2109 	INIT_LIST_HEAD(&sm_info->discard_list);
2110 	sm_info->nr_discards = 0;
2111 	sm_info->max_discards = 0;
2112 
2113 	INIT_LIST_HEAD(&sm_info->sit_entry_set);
2114 
2115 	if (test_opt(sbi, FLUSH_MERGE) && !f2fs_readonly(sbi->sb)) {
2116 		err = create_flush_cmd_control(sbi);
2117 		if (err)
2118 			return err;
2119 	}
2120 
2121 	err = build_sit_info(sbi);
2122 	if (err)
2123 		return err;
2124 	err = build_free_segmap(sbi);
2125 	if (err)
2126 		return err;
2127 	err = build_curseg(sbi);
2128 	if (err)
2129 		return err;
2130 
2131 	/* reinit free segmap based on SIT */
2132 	build_sit_entries(sbi);
2133 
2134 	init_free_segmap(sbi);
2135 	err = build_dirty_segmap(sbi);
2136 	if (err)
2137 		return err;
2138 
2139 	init_min_max_mtime(sbi);
2140 	return 0;
2141 }
2142 
2143 static void discard_dirty_segmap(struct f2fs_sb_info *sbi,
2144 		enum dirty_type dirty_type)
2145 {
2146 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
2147 
2148 	mutex_lock(&dirty_i->seglist_lock);
2149 	kfree(dirty_i->dirty_segmap[dirty_type]);
2150 	dirty_i->nr_dirty[dirty_type] = 0;
2151 	mutex_unlock(&dirty_i->seglist_lock);
2152 }
2153 
2154 static void destroy_victim_secmap(struct f2fs_sb_info *sbi)
2155 {
2156 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
2157 	kfree(dirty_i->victim_secmap);
2158 }
2159 
2160 static void destroy_dirty_segmap(struct f2fs_sb_info *sbi)
2161 {
2162 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
2163 	int i;
2164 
2165 	if (!dirty_i)
2166 		return;
2167 
2168 	/* discard pre-free/dirty segments list */
2169 	for (i = 0; i < NR_DIRTY_TYPE; i++)
2170 		discard_dirty_segmap(sbi, i);
2171 
2172 	destroy_victim_secmap(sbi);
2173 	SM_I(sbi)->dirty_info = NULL;
2174 	kfree(dirty_i);
2175 }
2176 
2177 static void destroy_curseg(struct f2fs_sb_info *sbi)
2178 {
2179 	struct curseg_info *array = SM_I(sbi)->curseg_array;
2180 	int i;
2181 
2182 	if (!array)
2183 		return;
2184 	SM_I(sbi)->curseg_array = NULL;
2185 	for (i = 0; i < NR_CURSEG_TYPE; i++)
2186 		kfree(array[i].sum_blk);
2187 	kfree(array);
2188 }
2189 
2190 static void destroy_free_segmap(struct f2fs_sb_info *sbi)
2191 {
2192 	struct free_segmap_info *free_i = SM_I(sbi)->free_info;
2193 	if (!free_i)
2194 		return;
2195 	SM_I(sbi)->free_info = NULL;
2196 	kfree(free_i->free_segmap);
2197 	kfree(free_i->free_secmap);
2198 	kfree(free_i);
2199 }
2200 
2201 static void destroy_sit_info(struct f2fs_sb_info *sbi)
2202 {
2203 	struct sit_info *sit_i = SIT_I(sbi);
2204 	unsigned int start;
2205 
2206 	if (!sit_i)
2207 		return;
2208 
2209 	if (sit_i->sentries) {
2210 		for (start = 0; start < MAIN_SEGS(sbi); start++) {
2211 			kfree(sit_i->sentries[start].cur_valid_map);
2212 			kfree(sit_i->sentries[start].ckpt_valid_map);
2213 		}
2214 	}
2215 	vfree(sit_i->sentries);
2216 	vfree(sit_i->sec_entries);
2217 	kfree(sit_i->dirty_sentries_bitmap);
2218 
2219 	SM_I(sbi)->sit_info = NULL;
2220 	kfree(sit_i->sit_bitmap);
2221 	kfree(sit_i);
2222 }
2223 
2224 void destroy_segment_manager(struct f2fs_sb_info *sbi)
2225 {
2226 	struct f2fs_sm_info *sm_info = SM_I(sbi);
2227 
2228 	if (!sm_info)
2229 		return;
2230 	destroy_flush_cmd_control(sbi);
2231 	destroy_dirty_segmap(sbi);
2232 	destroy_curseg(sbi);
2233 	destroy_free_segmap(sbi);
2234 	destroy_sit_info(sbi);
2235 	sbi->sm_info = NULL;
2236 	kfree(sm_info);
2237 }
2238 
2239 int __init create_segment_manager_caches(void)
2240 {
2241 	discard_entry_slab = f2fs_kmem_cache_create("discard_entry",
2242 			sizeof(struct discard_entry));
2243 	if (!discard_entry_slab)
2244 		goto fail;
2245 
2246 	sit_entry_set_slab = f2fs_kmem_cache_create("sit_entry_set",
2247 			sizeof(struct sit_entry_set));
2248 	if (!sit_entry_set_slab)
2249 		goto destory_discard_entry;
2250 
2251 	inmem_entry_slab = f2fs_kmem_cache_create("inmem_page_entry",
2252 			sizeof(struct inmem_pages));
2253 	if (!inmem_entry_slab)
2254 		goto destroy_sit_entry_set;
2255 	return 0;
2256 
2257 destroy_sit_entry_set:
2258 	kmem_cache_destroy(sit_entry_set_slab);
2259 destory_discard_entry:
2260 	kmem_cache_destroy(discard_entry_slab);
2261 fail:
2262 	return -ENOMEM;
2263 }
2264 
2265 void destroy_segment_manager_caches(void)
2266 {
2267 	kmem_cache_destroy(sit_entry_set_slab);
2268 	kmem_cache_destroy(discard_entry_slab);
2269 	kmem_cache_destroy(inmem_entry_slab);
2270 }
2271