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