xref: /openbmc/linux/fs/f2fs/segment.c (revision 58f9d806)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * fs/f2fs/segment.c
4  *
5  * Copyright (c) 2012 Samsung Electronics Co., Ltd.
6  *             http://www.samsung.com/
7  */
8 #include <linux/fs.h>
9 #include <linux/f2fs_fs.h>
10 #include <linux/bio.h>
11 #include <linux/blkdev.h>
12 #include <linux/prefetch.h>
13 #include <linux/kthread.h>
14 #include <linux/swap.h>
15 #include <linux/timer.h>
16 #include <linux/freezer.h>
17 #include <linux/sched/signal.h>
18 
19 #include "f2fs.h"
20 #include "segment.h"
21 #include "node.h"
22 #include "gc.h"
23 #include "trace.h"
24 #include <trace/events/f2fs.h>
25 
26 #define __reverse_ffz(x) __reverse_ffs(~(x))
27 
28 static struct kmem_cache *discard_entry_slab;
29 static struct kmem_cache *discard_cmd_slab;
30 static struct kmem_cache *sit_entry_set_slab;
31 static struct kmem_cache *inmem_entry_slab;
32 
33 static unsigned long __reverse_ulong(unsigned char *str)
34 {
35 	unsigned long tmp = 0;
36 	int shift = 24, idx = 0;
37 
38 #if BITS_PER_LONG == 64
39 	shift = 56;
40 #endif
41 	while (shift >= 0) {
42 		tmp |= (unsigned long)str[idx++] << shift;
43 		shift -= BITS_PER_BYTE;
44 	}
45 	return tmp;
46 }
47 
48 /*
49  * __reverse_ffs is copied from include/asm-generic/bitops/__ffs.h since
50  * MSB and LSB are reversed in a byte by f2fs_set_bit.
51  */
52 static inline unsigned long __reverse_ffs(unsigned long word)
53 {
54 	int num = 0;
55 
56 #if BITS_PER_LONG == 64
57 	if ((word & 0xffffffff00000000UL) == 0)
58 		num += 32;
59 	else
60 		word >>= 32;
61 #endif
62 	if ((word & 0xffff0000) == 0)
63 		num += 16;
64 	else
65 		word >>= 16;
66 
67 	if ((word & 0xff00) == 0)
68 		num += 8;
69 	else
70 		word >>= 8;
71 
72 	if ((word & 0xf0) == 0)
73 		num += 4;
74 	else
75 		word >>= 4;
76 
77 	if ((word & 0xc) == 0)
78 		num += 2;
79 	else
80 		word >>= 2;
81 
82 	if ((word & 0x2) == 0)
83 		num += 1;
84 	return num;
85 }
86 
87 /*
88  * __find_rev_next(_zero)_bit is copied from lib/find_next_bit.c because
89  * f2fs_set_bit makes MSB and LSB reversed in a byte.
90  * @size must be integral times of unsigned long.
91  * Example:
92  *                             MSB <--> LSB
93  *   f2fs_set_bit(0, bitmap) => 1000 0000
94  *   f2fs_set_bit(7, bitmap) => 0000 0001
95  */
96 static unsigned long __find_rev_next_bit(const unsigned long *addr,
97 			unsigned long size, unsigned long offset)
98 {
99 	const unsigned long *p = addr + BIT_WORD(offset);
100 	unsigned long result = size;
101 	unsigned long tmp;
102 
103 	if (offset >= size)
104 		return size;
105 
106 	size -= (offset & ~(BITS_PER_LONG - 1));
107 	offset %= BITS_PER_LONG;
108 
109 	while (1) {
110 		if (*p == 0)
111 			goto pass;
112 
113 		tmp = __reverse_ulong((unsigned char *)p);
114 
115 		tmp &= ~0UL >> offset;
116 		if (size < BITS_PER_LONG)
117 			tmp &= (~0UL << (BITS_PER_LONG - size));
118 		if (tmp)
119 			goto found;
120 pass:
121 		if (size <= BITS_PER_LONG)
122 			break;
123 		size -= BITS_PER_LONG;
124 		offset = 0;
125 		p++;
126 	}
127 	return result;
128 found:
129 	return result - size + __reverse_ffs(tmp);
130 }
131 
132 static unsigned long __find_rev_next_zero_bit(const unsigned long *addr,
133 			unsigned long size, unsigned long offset)
134 {
135 	const unsigned long *p = addr + BIT_WORD(offset);
136 	unsigned long result = size;
137 	unsigned long tmp;
138 
139 	if (offset >= size)
140 		return size;
141 
142 	size -= (offset & ~(BITS_PER_LONG - 1));
143 	offset %= BITS_PER_LONG;
144 
145 	while (1) {
146 		if (*p == ~0UL)
147 			goto pass;
148 
149 		tmp = __reverse_ulong((unsigned char *)p);
150 
151 		if (offset)
152 			tmp |= ~0UL << (BITS_PER_LONG - offset);
153 		if (size < BITS_PER_LONG)
154 			tmp |= ~0UL >> size;
155 		if (tmp != ~0UL)
156 			goto found;
157 pass:
158 		if (size <= BITS_PER_LONG)
159 			break;
160 		size -= BITS_PER_LONG;
161 		offset = 0;
162 		p++;
163 	}
164 	return result;
165 found:
166 	return result - size + __reverse_ffz(tmp);
167 }
168 
169 bool f2fs_need_SSR(struct f2fs_sb_info *sbi)
170 {
171 	int node_secs = get_blocktype_secs(sbi, F2FS_DIRTY_NODES);
172 	int dent_secs = get_blocktype_secs(sbi, F2FS_DIRTY_DENTS);
173 	int imeta_secs = get_blocktype_secs(sbi, F2FS_DIRTY_IMETA);
174 
175 	if (test_opt(sbi, LFS))
176 		return false;
177 	if (sbi->gc_mode == GC_URGENT)
178 		return true;
179 	if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED)))
180 		return true;
181 
182 	return free_sections(sbi) <= (node_secs + 2 * dent_secs + imeta_secs +
183 			SM_I(sbi)->min_ssr_sections + reserved_sections(sbi));
184 }
185 
186 void f2fs_register_inmem_page(struct inode *inode, struct page *page)
187 {
188 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
189 	struct f2fs_inode_info *fi = F2FS_I(inode);
190 	struct inmem_pages *new;
191 
192 	f2fs_trace_pid(page);
193 
194 	set_page_private(page, (unsigned long)ATOMIC_WRITTEN_PAGE);
195 	SetPagePrivate(page);
196 
197 	new = f2fs_kmem_cache_alloc(inmem_entry_slab, GFP_NOFS);
198 
199 	/* add atomic page indices to the list */
200 	new->page = page;
201 	INIT_LIST_HEAD(&new->list);
202 
203 	/* increase reference count with clean state */
204 	mutex_lock(&fi->inmem_lock);
205 	get_page(page);
206 	list_add_tail(&new->list, &fi->inmem_pages);
207 	spin_lock(&sbi->inode_lock[ATOMIC_FILE]);
208 	if (list_empty(&fi->inmem_ilist))
209 		list_add_tail(&fi->inmem_ilist, &sbi->inode_list[ATOMIC_FILE]);
210 	spin_unlock(&sbi->inode_lock[ATOMIC_FILE]);
211 	inc_page_count(F2FS_I_SB(inode), F2FS_INMEM_PAGES);
212 	mutex_unlock(&fi->inmem_lock);
213 
214 	trace_f2fs_register_inmem_page(page, INMEM);
215 }
216 
217 static int __revoke_inmem_pages(struct inode *inode,
218 				struct list_head *head, bool drop, bool recover)
219 {
220 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
221 	struct inmem_pages *cur, *tmp;
222 	int err = 0;
223 
224 	list_for_each_entry_safe(cur, tmp, head, list) {
225 		struct page *page = cur->page;
226 
227 		if (drop)
228 			trace_f2fs_commit_inmem_page(page, INMEM_DROP);
229 
230 		lock_page(page);
231 
232 		f2fs_wait_on_page_writeback(page, DATA, true);
233 
234 		if (recover) {
235 			struct dnode_of_data dn;
236 			struct node_info ni;
237 
238 			trace_f2fs_commit_inmem_page(page, INMEM_REVOKE);
239 retry:
240 			set_new_dnode(&dn, inode, NULL, NULL, 0);
241 			err = f2fs_get_dnode_of_data(&dn, page->index,
242 								LOOKUP_NODE);
243 			if (err) {
244 				if (err == -ENOMEM) {
245 					congestion_wait(BLK_RW_ASYNC, HZ/50);
246 					cond_resched();
247 					goto retry;
248 				}
249 				err = -EAGAIN;
250 				goto next;
251 			}
252 
253 			err = f2fs_get_node_info(sbi, dn.nid, &ni);
254 			if (err) {
255 				f2fs_put_dnode(&dn);
256 				return err;
257 			}
258 
259 			if (cur->old_addr == NEW_ADDR) {
260 				f2fs_invalidate_blocks(sbi, dn.data_blkaddr);
261 				f2fs_update_data_blkaddr(&dn, NEW_ADDR);
262 			} else
263 				f2fs_replace_block(sbi, &dn, dn.data_blkaddr,
264 					cur->old_addr, ni.version, true, true);
265 			f2fs_put_dnode(&dn);
266 		}
267 next:
268 		/* we don't need to invalidate this in the sccessful status */
269 		if (drop || recover) {
270 			ClearPageUptodate(page);
271 			clear_cold_data(page);
272 		}
273 		set_page_private(page, 0);
274 		ClearPagePrivate(page);
275 		f2fs_put_page(page, 1);
276 
277 		list_del(&cur->list);
278 		kmem_cache_free(inmem_entry_slab, cur);
279 		dec_page_count(F2FS_I_SB(inode), F2FS_INMEM_PAGES);
280 	}
281 	return err;
282 }
283 
284 void f2fs_drop_inmem_pages_all(struct f2fs_sb_info *sbi, bool gc_failure)
285 {
286 	struct list_head *head = &sbi->inode_list[ATOMIC_FILE];
287 	struct inode *inode;
288 	struct f2fs_inode_info *fi;
289 next:
290 	spin_lock(&sbi->inode_lock[ATOMIC_FILE]);
291 	if (list_empty(head)) {
292 		spin_unlock(&sbi->inode_lock[ATOMIC_FILE]);
293 		return;
294 	}
295 	fi = list_first_entry(head, struct f2fs_inode_info, inmem_ilist);
296 	inode = igrab(&fi->vfs_inode);
297 	spin_unlock(&sbi->inode_lock[ATOMIC_FILE]);
298 
299 	if (inode) {
300 		if (gc_failure) {
301 			if (fi->i_gc_failures[GC_FAILURE_ATOMIC])
302 				goto drop;
303 			goto skip;
304 		}
305 drop:
306 		set_inode_flag(inode, FI_ATOMIC_REVOKE_REQUEST);
307 		f2fs_drop_inmem_pages(inode);
308 		iput(inode);
309 	}
310 skip:
311 	congestion_wait(BLK_RW_ASYNC, HZ/50);
312 	cond_resched();
313 	goto next;
314 }
315 
316 void f2fs_drop_inmem_pages(struct inode *inode)
317 {
318 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
319 	struct f2fs_inode_info *fi = F2FS_I(inode);
320 
321 	mutex_lock(&fi->inmem_lock);
322 	__revoke_inmem_pages(inode, &fi->inmem_pages, true, false);
323 	spin_lock(&sbi->inode_lock[ATOMIC_FILE]);
324 	if (!list_empty(&fi->inmem_ilist))
325 		list_del_init(&fi->inmem_ilist);
326 	spin_unlock(&sbi->inode_lock[ATOMIC_FILE]);
327 	mutex_unlock(&fi->inmem_lock);
328 
329 	clear_inode_flag(inode, FI_ATOMIC_FILE);
330 	fi->i_gc_failures[GC_FAILURE_ATOMIC] = 0;
331 	stat_dec_atomic_write(inode);
332 }
333 
334 void f2fs_drop_inmem_page(struct inode *inode, struct page *page)
335 {
336 	struct f2fs_inode_info *fi = F2FS_I(inode);
337 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
338 	struct list_head *head = &fi->inmem_pages;
339 	struct inmem_pages *cur = NULL;
340 
341 	f2fs_bug_on(sbi, !IS_ATOMIC_WRITTEN_PAGE(page));
342 
343 	mutex_lock(&fi->inmem_lock);
344 	list_for_each_entry(cur, head, list) {
345 		if (cur->page == page)
346 			break;
347 	}
348 
349 	f2fs_bug_on(sbi, list_empty(head) || cur->page != page);
350 	list_del(&cur->list);
351 	mutex_unlock(&fi->inmem_lock);
352 
353 	dec_page_count(sbi, F2FS_INMEM_PAGES);
354 	kmem_cache_free(inmem_entry_slab, cur);
355 
356 	ClearPageUptodate(page);
357 	set_page_private(page, 0);
358 	ClearPagePrivate(page);
359 	f2fs_put_page(page, 0);
360 
361 	trace_f2fs_commit_inmem_page(page, INMEM_INVALIDATE);
362 }
363 
364 static int __f2fs_commit_inmem_pages(struct inode *inode)
365 {
366 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
367 	struct f2fs_inode_info *fi = F2FS_I(inode);
368 	struct inmem_pages *cur, *tmp;
369 	struct f2fs_io_info fio = {
370 		.sbi = sbi,
371 		.ino = inode->i_ino,
372 		.type = DATA,
373 		.op = REQ_OP_WRITE,
374 		.op_flags = REQ_SYNC | REQ_PRIO,
375 		.io_type = FS_DATA_IO,
376 	};
377 	struct list_head revoke_list;
378 	bool submit_bio = false;
379 	int err = 0;
380 
381 	INIT_LIST_HEAD(&revoke_list);
382 
383 	list_for_each_entry_safe(cur, tmp, &fi->inmem_pages, list) {
384 		struct page *page = cur->page;
385 
386 		lock_page(page);
387 		if (page->mapping == inode->i_mapping) {
388 			trace_f2fs_commit_inmem_page(page, INMEM);
389 
390 			set_page_dirty(page);
391 			f2fs_wait_on_page_writeback(page, DATA, true);
392 			if (clear_page_dirty_for_io(page)) {
393 				inode_dec_dirty_pages(inode);
394 				f2fs_remove_dirty_inode(inode);
395 			}
396 retry:
397 			fio.page = page;
398 			fio.old_blkaddr = NULL_ADDR;
399 			fio.encrypted_page = NULL;
400 			fio.need_lock = LOCK_DONE;
401 			err = f2fs_do_write_data_page(&fio);
402 			if (err) {
403 				if (err == -ENOMEM) {
404 					congestion_wait(BLK_RW_ASYNC, HZ/50);
405 					cond_resched();
406 					goto retry;
407 				}
408 				unlock_page(page);
409 				break;
410 			}
411 			/* record old blkaddr for revoking */
412 			cur->old_addr = fio.old_blkaddr;
413 			submit_bio = true;
414 		}
415 		unlock_page(page);
416 		list_move_tail(&cur->list, &revoke_list);
417 	}
418 
419 	if (submit_bio)
420 		f2fs_submit_merged_write_cond(sbi, inode, NULL, 0, DATA);
421 
422 	if (err) {
423 		/*
424 		 * try to revoke all committed pages, but still we could fail
425 		 * due to no memory or other reason, if that happened, EAGAIN
426 		 * will be returned, which means in such case, transaction is
427 		 * already not integrity, caller should use journal to do the
428 		 * recovery or rewrite & commit last transaction. For other
429 		 * error number, revoking was done by filesystem itself.
430 		 */
431 		err = __revoke_inmem_pages(inode, &revoke_list, false, true);
432 
433 		/* drop all uncommitted pages */
434 		__revoke_inmem_pages(inode, &fi->inmem_pages, true, false);
435 	} else {
436 		__revoke_inmem_pages(inode, &revoke_list, false, false);
437 	}
438 
439 	return err;
440 }
441 
442 int f2fs_commit_inmem_pages(struct inode *inode)
443 {
444 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
445 	struct f2fs_inode_info *fi = F2FS_I(inode);
446 	int err;
447 
448 	f2fs_balance_fs(sbi, true);
449 
450 	down_write(&fi->i_gc_rwsem[WRITE]);
451 
452 	f2fs_lock_op(sbi);
453 	set_inode_flag(inode, FI_ATOMIC_COMMIT);
454 
455 	mutex_lock(&fi->inmem_lock);
456 	err = __f2fs_commit_inmem_pages(inode);
457 
458 	spin_lock(&sbi->inode_lock[ATOMIC_FILE]);
459 	if (!list_empty(&fi->inmem_ilist))
460 		list_del_init(&fi->inmem_ilist);
461 	spin_unlock(&sbi->inode_lock[ATOMIC_FILE]);
462 	mutex_unlock(&fi->inmem_lock);
463 
464 	clear_inode_flag(inode, FI_ATOMIC_COMMIT);
465 
466 	f2fs_unlock_op(sbi);
467 	up_write(&fi->i_gc_rwsem[WRITE]);
468 
469 	return err;
470 }
471 
472 /*
473  * This function balances dirty node and dentry pages.
474  * In addition, it controls garbage collection.
475  */
476 void f2fs_balance_fs(struct f2fs_sb_info *sbi, bool need)
477 {
478 	if (time_to_inject(sbi, FAULT_CHECKPOINT)) {
479 		f2fs_show_injection_info(FAULT_CHECKPOINT);
480 		f2fs_stop_checkpoint(sbi, false);
481 	}
482 
483 	/* balance_fs_bg is able to be pending */
484 	if (need && excess_cached_nats(sbi))
485 		f2fs_balance_fs_bg(sbi);
486 
487 	if (f2fs_is_checkpoint_ready(sbi))
488 		return;
489 
490 	/*
491 	 * We should do GC or end up with checkpoint, if there are so many dirty
492 	 * dir/node pages without enough free segments.
493 	 */
494 	if (has_not_enough_free_secs(sbi, 0, 0)) {
495 		mutex_lock(&sbi->gc_mutex);
496 		f2fs_gc(sbi, false, false, NULL_SEGNO);
497 	}
498 }
499 
500 void f2fs_balance_fs_bg(struct f2fs_sb_info *sbi)
501 {
502 	if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
503 		return;
504 
505 	/* try to shrink extent cache when there is no enough memory */
506 	if (!f2fs_available_free_memory(sbi, EXTENT_CACHE))
507 		f2fs_shrink_extent_tree(sbi, EXTENT_CACHE_SHRINK_NUMBER);
508 
509 	/* check the # of cached NAT entries */
510 	if (!f2fs_available_free_memory(sbi, NAT_ENTRIES))
511 		f2fs_try_to_free_nats(sbi, NAT_ENTRY_PER_BLOCK);
512 
513 	if (!f2fs_available_free_memory(sbi, FREE_NIDS))
514 		f2fs_try_to_free_nids(sbi, MAX_FREE_NIDS);
515 	else
516 		f2fs_build_free_nids(sbi, false, false);
517 
518 	if (!is_idle(sbi, REQ_TIME) &&
519 		(!excess_dirty_nats(sbi) && !excess_dirty_nodes(sbi)))
520 		return;
521 
522 	/* checkpoint is the only way to shrink partial cached entries */
523 	if (!f2fs_available_free_memory(sbi, NAT_ENTRIES) ||
524 			!f2fs_available_free_memory(sbi, INO_ENTRIES) ||
525 			excess_prefree_segs(sbi) ||
526 			excess_dirty_nats(sbi) ||
527 			excess_dirty_nodes(sbi) ||
528 			f2fs_time_over(sbi, CP_TIME)) {
529 		if (test_opt(sbi, DATA_FLUSH)) {
530 			struct blk_plug plug;
531 
532 			blk_start_plug(&plug);
533 			f2fs_sync_dirty_inodes(sbi, FILE_INODE);
534 			blk_finish_plug(&plug);
535 		}
536 		f2fs_sync_fs(sbi->sb, true);
537 		stat_inc_bg_cp_count(sbi->stat_info);
538 	}
539 }
540 
541 static int __submit_flush_wait(struct f2fs_sb_info *sbi,
542 				struct block_device *bdev)
543 {
544 	struct bio *bio = f2fs_bio_alloc(sbi, 0, true);
545 	int ret;
546 
547 	bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
548 	bio_set_dev(bio, bdev);
549 	ret = submit_bio_wait(bio);
550 	bio_put(bio);
551 
552 	trace_f2fs_issue_flush(bdev, test_opt(sbi, NOBARRIER),
553 				test_opt(sbi, FLUSH_MERGE), ret);
554 	return ret;
555 }
556 
557 static int submit_flush_wait(struct f2fs_sb_info *sbi, nid_t ino)
558 {
559 	int ret = 0;
560 	int i;
561 
562 	if (!sbi->s_ndevs)
563 		return __submit_flush_wait(sbi, sbi->sb->s_bdev);
564 
565 	for (i = 0; i < sbi->s_ndevs; i++) {
566 		if (!f2fs_is_dirty_device(sbi, ino, i, FLUSH_INO))
567 			continue;
568 		ret = __submit_flush_wait(sbi, FDEV(i).bdev);
569 		if (ret)
570 			break;
571 	}
572 	return ret;
573 }
574 
575 static int issue_flush_thread(void *data)
576 {
577 	struct f2fs_sb_info *sbi = data;
578 	struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
579 	wait_queue_head_t *q = &fcc->flush_wait_queue;
580 repeat:
581 	if (kthread_should_stop())
582 		return 0;
583 
584 	sb_start_intwrite(sbi->sb);
585 
586 	if (!llist_empty(&fcc->issue_list)) {
587 		struct flush_cmd *cmd, *next;
588 		int ret;
589 
590 		fcc->dispatch_list = llist_del_all(&fcc->issue_list);
591 		fcc->dispatch_list = llist_reverse_order(fcc->dispatch_list);
592 
593 		cmd = llist_entry(fcc->dispatch_list, struct flush_cmd, llnode);
594 
595 		ret = submit_flush_wait(sbi, cmd->ino);
596 		atomic_inc(&fcc->issued_flush);
597 
598 		llist_for_each_entry_safe(cmd, next,
599 					  fcc->dispatch_list, llnode) {
600 			cmd->ret = ret;
601 			complete(&cmd->wait);
602 		}
603 		fcc->dispatch_list = NULL;
604 	}
605 
606 	sb_end_intwrite(sbi->sb);
607 
608 	wait_event_interruptible(*q,
609 		kthread_should_stop() || !llist_empty(&fcc->issue_list));
610 	goto repeat;
611 }
612 
613 int f2fs_issue_flush(struct f2fs_sb_info *sbi, nid_t ino)
614 {
615 	struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
616 	struct flush_cmd cmd;
617 	int ret;
618 
619 	if (test_opt(sbi, NOBARRIER))
620 		return 0;
621 
622 	if (!test_opt(sbi, FLUSH_MERGE)) {
623 		ret = submit_flush_wait(sbi, ino);
624 		atomic_inc(&fcc->issued_flush);
625 		return ret;
626 	}
627 
628 	if (atomic_inc_return(&fcc->issing_flush) == 1 || sbi->s_ndevs > 1) {
629 		ret = submit_flush_wait(sbi, ino);
630 		atomic_dec(&fcc->issing_flush);
631 
632 		atomic_inc(&fcc->issued_flush);
633 		return ret;
634 	}
635 
636 	cmd.ino = ino;
637 	init_completion(&cmd.wait);
638 
639 	llist_add(&cmd.llnode, &fcc->issue_list);
640 
641 	/* update issue_list before we wake up issue_flush thread */
642 	smp_mb();
643 
644 	if (waitqueue_active(&fcc->flush_wait_queue))
645 		wake_up(&fcc->flush_wait_queue);
646 
647 	if (fcc->f2fs_issue_flush) {
648 		wait_for_completion(&cmd.wait);
649 		atomic_dec(&fcc->issing_flush);
650 	} else {
651 		struct llist_node *list;
652 
653 		list = llist_del_all(&fcc->issue_list);
654 		if (!list) {
655 			wait_for_completion(&cmd.wait);
656 			atomic_dec(&fcc->issing_flush);
657 		} else {
658 			struct flush_cmd *tmp, *next;
659 
660 			ret = submit_flush_wait(sbi, ino);
661 
662 			llist_for_each_entry_safe(tmp, next, list, llnode) {
663 				if (tmp == &cmd) {
664 					cmd.ret = ret;
665 					atomic_dec(&fcc->issing_flush);
666 					continue;
667 				}
668 				tmp->ret = ret;
669 				complete(&tmp->wait);
670 			}
671 		}
672 	}
673 
674 	return cmd.ret;
675 }
676 
677 int f2fs_create_flush_cmd_control(struct f2fs_sb_info *sbi)
678 {
679 	dev_t dev = sbi->sb->s_bdev->bd_dev;
680 	struct flush_cmd_control *fcc;
681 	int err = 0;
682 
683 	if (SM_I(sbi)->fcc_info) {
684 		fcc = SM_I(sbi)->fcc_info;
685 		if (fcc->f2fs_issue_flush)
686 			return err;
687 		goto init_thread;
688 	}
689 
690 	fcc = f2fs_kzalloc(sbi, sizeof(struct flush_cmd_control), GFP_KERNEL);
691 	if (!fcc)
692 		return -ENOMEM;
693 	atomic_set(&fcc->issued_flush, 0);
694 	atomic_set(&fcc->issing_flush, 0);
695 	init_waitqueue_head(&fcc->flush_wait_queue);
696 	init_llist_head(&fcc->issue_list);
697 	SM_I(sbi)->fcc_info = fcc;
698 	if (!test_opt(sbi, FLUSH_MERGE))
699 		return err;
700 
701 init_thread:
702 	fcc->f2fs_issue_flush = kthread_run(issue_flush_thread, sbi,
703 				"f2fs_flush-%u:%u", MAJOR(dev), MINOR(dev));
704 	if (IS_ERR(fcc->f2fs_issue_flush)) {
705 		err = PTR_ERR(fcc->f2fs_issue_flush);
706 		kfree(fcc);
707 		SM_I(sbi)->fcc_info = NULL;
708 		return err;
709 	}
710 
711 	return err;
712 }
713 
714 void f2fs_destroy_flush_cmd_control(struct f2fs_sb_info *sbi, bool free)
715 {
716 	struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
717 
718 	if (fcc && fcc->f2fs_issue_flush) {
719 		struct task_struct *flush_thread = fcc->f2fs_issue_flush;
720 
721 		fcc->f2fs_issue_flush = NULL;
722 		kthread_stop(flush_thread);
723 	}
724 	if (free) {
725 		kfree(fcc);
726 		SM_I(sbi)->fcc_info = NULL;
727 	}
728 }
729 
730 int f2fs_flush_device_cache(struct f2fs_sb_info *sbi)
731 {
732 	int ret = 0, i;
733 
734 	if (!sbi->s_ndevs)
735 		return 0;
736 
737 	for (i = 1; i < sbi->s_ndevs; i++) {
738 		if (!f2fs_test_bit(i, (char *)&sbi->dirty_device))
739 			continue;
740 		ret = __submit_flush_wait(sbi, FDEV(i).bdev);
741 		if (ret)
742 			break;
743 
744 		spin_lock(&sbi->dev_lock);
745 		f2fs_clear_bit(i, (char *)&sbi->dirty_device);
746 		spin_unlock(&sbi->dev_lock);
747 	}
748 
749 	return ret;
750 }
751 
752 static void __locate_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno,
753 		enum dirty_type dirty_type)
754 {
755 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
756 
757 	/* need not be added */
758 	if (IS_CURSEG(sbi, segno))
759 		return;
760 
761 	if (!test_and_set_bit(segno, dirty_i->dirty_segmap[dirty_type]))
762 		dirty_i->nr_dirty[dirty_type]++;
763 
764 	if (dirty_type == DIRTY) {
765 		struct seg_entry *sentry = get_seg_entry(sbi, segno);
766 		enum dirty_type t = sentry->type;
767 
768 		if (unlikely(t >= DIRTY)) {
769 			f2fs_bug_on(sbi, 1);
770 			return;
771 		}
772 		if (!test_and_set_bit(segno, dirty_i->dirty_segmap[t]))
773 			dirty_i->nr_dirty[t]++;
774 	}
775 }
776 
777 static void __remove_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno,
778 		enum dirty_type dirty_type)
779 {
780 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
781 
782 	if (test_and_clear_bit(segno, dirty_i->dirty_segmap[dirty_type]))
783 		dirty_i->nr_dirty[dirty_type]--;
784 
785 	if (dirty_type == DIRTY) {
786 		struct seg_entry *sentry = get_seg_entry(sbi, segno);
787 		enum dirty_type t = sentry->type;
788 
789 		if (test_and_clear_bit(segno, dirty_i->dirty_segmap[t]))
790 			dirty_i->nr_dirty[t]--;
791 
792 		if (get_valid_blocks(sbi, segno, true) == 0)
793 			clear_bit(GET_SEC_FROM_SEG(sbi, segno),
794 						dirty_i->victim_secmap);
795 	}
796 }
797 
798 /*
799  * Should not occur error such as -ENOMEM.
800  * Adding dirty entry into seglist is not critical operation.
801  * If a given segment is one of current working segments, it won't be added.
802  */
803 static void locate_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno)
804 {
805 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
806 	unsigned short valid_blocks, ckpt_valid_blocks;
807 
808 	if (segno == NULL_SEGNO || IS_CURSEG(sbi, segno))
809 		return;
810 
811 	mutex_lock(&dirty_i->seglist_lock);
812 
813 	valid_blocks = get_valid_blocks(sbi, segno, false);
814 	ckpt_valid_blocks = get_ckpt_valid_blocks(sbi, segno);
815 
816 	if (valid_blocks == 0 && (!is_sbi_flag_set(sbi, SBI_CP_DISABLED) ||
817 				ckpt_valid_blocks == sbi->blocks_per_seg)) {
818 		__locate_dirty_segment(sbi, segno, PRE);
819 		__remove_dirty_segment(sbi, segno, DIRTY);
820 	} else if (valid_blocks < sbi->blocks_per_seg) {
821 		__locate_dirty_segment(sbi, segno, DIRTY);
822 	} else {
823 		/* Recovery routine with SSR needs this */
824 		__remove_dirty_segment(sbi, segno, DIRTY);
825 	}
826 
827 	mutex_unlock(&dirty_i->seglist_lock);
828 }
829 
830 /* This moves currently empty dirty blocks to prefree. Must hold seglist_lock */
831 void f2fs_dirty_to_prefree(struct f2fs_sb_info *sbi)
832 {
833 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
834 	unsigned int segno;
835 
836 	mutex_lock(&dirty_i->seglist_lock);
837 	for_each_set_bit(segno, dirty_i->dirty_segmap[DIRTY], MAIN_SEGS(sbi)) {
838 		if (get_valid_blocks(sbi, segno, false))
839 			continue;
840 		if (IS_CURSEG(sbi, segno))
841 			continue;
842 		__locate_dirty_segment(sbi, segno, PRE);
843 		__remove_dirty_segment(sbi, segno, DIRTY);
844 	}
845 	mutex_unlock(&dirty_i->seglist_lock);
846 }
847 
848 int f2fs_disable_cp_again(struct f2fs_sb_info *sbi)
849 {
850 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
851 	block_t ovp = overprovision_segments(sbi) << sbi->log_blocks_per_seg;
852 	block_t holes[2] = {0, 0};	/* DATA and NODE */
853 	struct seg_entry *se;
854 	unsigned int segno;
855 
856 	mutex_lock(&dirty_i->seglist_lock);
857 	for_each_set_bit(segno, dirty_i->dirty_segmap[DIRTY], MAIN_SEGS(sbi)) {
858 		se = get_seg_entry(sbi, segno);
859 		if (IS_NODESEG(se->type))
860 			holes[NODE] += sbi->blocks_per_seg - se->valid_blocks;
861 		else
862 			holes[DATA] += sbi->blocks_per_seg - se->valid_blocks;
863 	}
864 	mutex_unlock(&dirty_i->seglist_lock);
865 
866 	if (holes[DATA] > ovp || holes[NODE] > ovp)
867 		return -EAGAIN;
868 	return 0;
869 }
870 
871 /* This is only used by SBI_CP_DISABLED */
872 static unsigned int get_free_segment(struct f2fs_sb_info *sbi)
873 {
874 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
875 	unsigned int segno = 0;
876 
877 	mutex_lock(&dirty_i->seglist_lock);
878 	for_each_set_bit(segno, dirty_i->dirty_segmap[DIRTY], MAIN_SEGS(sbi)) {
879 		if (get_valid_blocks(sbi, segno, false))
880 			continue;
881 		if (get_ckpt_valid_blocks(sbi, segno))
882 			continue;
883 		mutex_unlock(&dirty_i->seglist_lock);
884 		return segno;
885 	}
886 	mutex_unlock(&dirty_i->seglist_lock);
887 	return NULL_SEGNO;
888 }
889 
890 static struct discard_cmd *__create_discard_cmd(struct f2fs_sb_info *sbi,
891 		struct block_device *bdev, block_t lstart,
892 		block_t start, block_t len)
893 {
894 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
895 	struct list_head *pend_list;
896 	struct discard_cmd *dc;
897 
898 	f2fs_bug_on(sbi, !len);
899 
900 	pend_list = &dcc->pend_list[plist_idx(len)];
901 
902 	dc = f2fs_kmem_cache_alloc(discard_cmd_slab, GFP_NOFS);
903 	INIT_LIST_HEAD(&dc->list);
904 	dc->bdev = bdev;
905 	dc->lstart = lstart;
906 	dc->start = start;
907 	dc->len = len;
908 	dc->ref = 0;
909 	dc->state = D_PREP;
910 	dc->issuing = 0;
911 	dc->error = 0;
912 	init_completion(&dc->wait);
913 	list_add_tail(&dc->list, pend_list);
914 	spin_lock_init(&dc->lock);
915 	dc->bio_ref = 0;
916 	atomic_inc(&dcc->discard_cmd_cnt);
917 	dcc->undiscard_blks += len;
918 
919 	return dc;
920 }
921 
922 static struct discard_cmd *__attach_discard_cmd(struct f2fs_sb_info *sbi,
923 				struct block_device *bdev, block_t lstart,
924 				block_t start, block_t len,
925 				struct rb_node *parent, struct rb_node **p,
926 				bool leftmost)
927 {
928 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
929 	struct discard_cmd *dc;
930 
931 	dc = __create_discard_cmd(sbi, bdev, lstart, start, len);
932 
933 	rb_link_node(&dc->rb_node, parent, p);
934 	rb_insert_color_cached(&dc->rb_node, &dcc->root, leftmost);
935 
936 	return dc;
937 }
938 
939 static void __detach_discard_cmd(struct discard_cmd_control *dcc,
940 							struct discard_cmd *dc)
941 {
942 	if (dc->state == D_DONE)
943 		atomic_sub(dc->issuing, &dcc->issing_discard);
944 
945 	list_del(&dc->list);
946 	rb_erase_cached(&dc->rb_node, &dcc->root);
947 	dcc->undiscard_blks -= dc->len;
948 
949 	kmem_cache_free(discard_cmd_slab, dc);
950 
951 	atomic_dec(&dcc->discard_cmd_cnt);
952 }
953 
954 static void __remove_discard_cmd(struct f2fs_sb_info *sbi,
955 							struct discard_cmd *dc)
956 {
957 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
958 	unsigned long flags;
959 
960 	trace_f2fs_remove_discard(dc->bdev, dc->start, dc->len);
961 
962 	spin_lock_irqsave(&dc->lock, flags);
963 	if (dc->bio_ref) {
964 		spin_unlock_irqrestore(&dc->lock, flags);
965 		return;
966 	}
967 	spin_unlock_irqrestore(&dc->lock, flags);
968 
969 	f2fs_bug_on(sbi, dc->ref);
970 
971 	if (dc->error == -EOPNOTSUPP)
972 		dc->error = 0;
973 
974 	if (dc->error)
975 		printk_ratelimited(
976 			"%sF2FS-fs: Issue discard(%u, %u, %u) failed, ret: %d",
977 			KERN_INFO, dc->lstart, dc->start, dc->len, dc->error);
978 	__detach_discard_cmd(dcc, dc);
979 }
980 
981 static void f2fs_submit_discard_endio(struct bio *bio)
982 {
983 	struct discard_cmd *dc = (struct discard_cmd *)bio->bi_private;
984 	unsigned long flags;
985 
986 	dc->error = blk_status_to_errno(bio->bi_status);
987 
988 	spin_lock_irqsave(&dc->lock, flags);
989 	dc->bio_ref--;
990 	if (!dc->bio_ref && dc->state == D_SUBMIT) {
991 		dc->state = D_DONE;
992 		complete_all(&dc->wait);
993 	}
994 	spin_unlock_irqrestore(&dc->lock, flags);
995 	bio_put(bio);
996 }
997 
998 static void __check_sit_bitmap(struct f2fs_sb_info *sbi,
999 				block_t start, block_t end)
1000 {
1001 #ifdef CONFIG_F2FS_CHECK_FS
1002 	struct seg_entry *sentry;
1003 	unsigned int segno;
1004 	block_t blk = start;
1005 	unsigned long offset, size, max_blocks = sbi->blocks_per_seg;
1006 	unsigned long *map;
1007 
1008 	while (blk < end) {
1009 		segno = GET_SEGNO(sbi, blk);
1010 		sentry = get_seg_entry(sbi, segno);
1011 		offset = GET_BLKOFF_FROM_SEG0(sbi, blk);
1012 
1013 		if (end < START_BLOCK(sbi, segno + 1))
1014 			size = GET_BLKOFF_FROM_SEG0(sbi, end);
1015 		else
1016 			size = max_blocks;
1017 		map = (unsigned long *)(sentry->cur_valid_map);
1018 		offset = __find_rev_next_bit(map, size, offset);
1019 		f2fs_bug_on(sbi, offset != size);
1020 		blk = START_BLOCK(sbi, segno + 1);
1021 	}
1022 #endif
1023 }
1024 
1025 static void __init_discard_policy(struct f2fs_sb_info *sbi,
1026 				struct discard_policy *dpolicy,
1027 				int discard_type, unsigned int granularity)
1028 {
1029 	/* common policy */
1030 	dpolicy->type = discard_type;
1031 	dpolicy->sync = true;
1032 	dpolicy->ordered = false;
1033 	dpolicy->granularity = granularity;
1034 
1035 	dpolicy->max_requests = DEF_MAX_DISCARD_REQUEST;
1036 	dpolicy->io_aware_gran = MAX_PLIST_NUM;
1037 
1038 	if (discard_type == DPOLICY_BG) {
1039 		dpolicy->min_interval = DEF_MIN_DISCARD_ISSUE_TIME;
1040 		dpolicy->mid_interval = DEF_MID_DISCARD_ISSUE_TIME;
1041 		dpolicy->max_interval = DEF_MAX_DISCARD_ISSUE_TIME;
1042 		dpolicy->io_aware = true;
1043 		dpolicy->sync = false;
1044 		dpolicy->ordered = true;
1045 		if (utilization(sbi) > DEF_DISCARD_URGENT_UTIL) {
1046 			dpolicy->granularity = 1;
1047 			dpolicy->max_interval = DEF_MIN_DISCARD_ISSUE_TIME;
1048 		}
1049 	} else if (discard_type == DPOLICY_FORCE) {
1050 		dpolicy->min_interval = DEF_MIN_DISCARD_ISSUE_TIME;
1051 		dpolicy->mid_interval = DEF_MID_DISCARD_ISSUE_TIME;
1052 		dpolicy->max_interval = DEF_MAX_DISCARD_ISSUE_TIME;
1053 		dpolicy->io_aware = false;
1054 	} else if (discard_type == DPOLICY_FSTRIM) {
1055 		dpolicy->io_aware = false;
1056 	} else if (discard_type == DPOLICY_UMOUNT) {
1057 		dpolicy->max_requests = UINT_MAX;
1058 		dpolicy->io_aware = false;
1059 	}
1060 }
1061 
1062 static void __update_discard_tree_range(struct f2fs_sb_info *sbi,
1063 				struct block_device *bdev, block_t lstart,
1064 				block_t start, block_t len);
1065 /* this function is copied from blkdev_issue_discard from block/blk-lib.c */
1066 static int __submit_discard_cmd(struct f2fs_sb_info *sbi,
1067 						struct discard_policy *dpolicy,
1068 						struct discard_cmd *dc,
1069 						unsigned int *issued)
1070 {
1071 	struct block_device *bdev = dc->bdev;
1072 	struct request_queue *q = bdev_get_queue(bdev);
1073 	unsigned int max_discard_blocks =
1074 			SECTOR_TO_BLOCK(q->limits.max_discard_sectors);
1075 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1076 	struct list_head *wait_list = (dpolicy->type == DPOLICY_FSTRIM) ?
1077 					&(dcc->fstrim_list) : &(dcc->wait_list);
1078 	int flag = dpolicy->sync ? REQ_SYNC : 0;
1079 	block_t lstart, start, len, total_len;
1080 	int err = 0;
1081 
1082 	if (dc->state != D_PREP)
1083 		return 0;
1084 
1085 	if (is_sbi_flag_set(sbi, SBI_NEED_FSCK))
1086 		return 0;
1087 
1088 	trace_f2fs_issue_discard(bdev, dc->start, dc->len);
1089 
1090 	lstart = dc->lstart;
1091 	start = dc->start;
1092 	len = dc->len;
1093 	total_len = len;
1094 
1095 	dc->len = 0;
1096 
1097 	while (total_len && *issued < dpolicy->max_requests && !err) {
1098 		struct bio *bio = NULL;
1099 		unsigned long flags;
1100 		bool last = true;
1101 
1102 		if (len > max_discard_blocks) {
1103 			len = max_discard_blocks;
1104 			last = false;
1105 		}
1106 
1107 		(*issued)++;
1108 		if (*issued == dpolicy->max_requests)
1109 			last = true;
1110 
1111 		dc->len += len;
1112 
1113 		if (time_to_inject(sbi, FAULT_DISCARD)) {
1114 			f2fs_show_injection_info(FAULT_DISCARD);
1115 			err = -EIO;
1116 			goto submit;
1117 		}
1118 		err = __blkdev_issue_discard(bdev,
1119 					SECTOR_FROM_BLOCK(start),
1120 					SECTOR_FROM_BLOCK(len),
1121 					GFP_NOFS, 0, &bio);
1122 submit:
1123 		if (err) {
1124 			spin_lock_irqsave(&dc->lock, flags);
1125 			if (dc->state == D_PARTIAL)
1126 				dc->state = D_SUBMIT;
1127 			spin_unlock_irqrestore(&dc->lock, flags);
1128 
1129 			break;
1130 		}
1131 
1132 		f2fs_bug_on(sbi, !bio);
1133 
1134 		/*
1135 		 * should keep before submission to avoid D_DONE
1136 		 * right away
1137 		 */
1138 		spin_lock_irqsave(&dc->lock, flags);
1139 		if (last)
1140 			dc->state = D_SUBMIT;
1141 		else
1142 			dc->state = D_PARTIAL;
1143 		dc->bio_ref++;
1144 		spin_unlock_irqrestore(&dc->lock, flags);
1145 
1146 		atomic_inc(&dcc->issing_discard);
1147 		dc->issuing++;
1148 		list_move_tail(&dc->list, wait_list);
1149 
1150 		/* sanity check on discard range */
1151 		__check_sit_bitmap(sbi, start, start + len);
1152 
1153 		bio->bi_private = dc;
1154 		bio->bi_end_io = f2fs_submit_discard_endio;
1155 		bio->bi_opf |= flag;
1156 		submit_bio(bio);
1157 
1158 		atomic_inc(&dcc->issued_discard);
1159 
1160 		f2fs_update_iostat(sbi, FS_DISCARD, 1);
1161 
1162 		lstart += len;
1163 		start += len;
1164 		total_len -= len;
1165 		len = total_len;
1166 	}
1167 
1168 	if (!err && len)
1169 		__update_discard_tree_range(sbi, bdev, lstart, start, len);
1170 	return err;
1171 }
1172 
1173 static struct discard_cmd *__insert_discard_tree(struct f2fs_sb_info *sbi,
1174 				struct block_device *bdev, block_t lstart,
1175 				block_t start, block_t len,
1176 				struct rb_node **insert_p,
1177 				struct rb_node *insert_parent)
1178 {
1179 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1180 	struct rb_node **p;
1181 	struct rb_node *parent = NULL;
1182 	struct discard_cmd *dc = NULL;
1183 	bool leftmost = true;
1184 
1185 	if (insert_p && insert_parent) {
1186 		parent = insert_parent;
1187 		p = insert_p;
1188 		goto do_insert;
1189 	}
1190 
1191 	p = f2fs_lookup_rb_tree_for_insert(sbi, &dcc->root, &parent,
1192 							lstart, &leftmost);
1193 do_insert:
1194 	dc = __attach_discard_cmd(sbi, bdev, lstart, start, len, parent,
1195 								p, leftmost);
1196 	if (!dc)
1197 		return NULL;
1198 
1199 	return dc;
1200 }
1201 
1202 static void __relocate_discard_cmd(struct discard_cmd_control *dcc,
1203 						struct discard_cmd *dc)
1204 {
1205 	list_move_tail(&dc->list, &dcc->pend_list[plist_idx(dc->len)]);
1206 }
1207 
1208 static void __punch_discard_cmd(struct f2fs_sb_info *sbi,
1209 				struct discard_cmd *dc, block_t blkaddr)
1210 {
1211 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1212 	struct discard_info di = dc->di;
1213 	bool modified = false;
1214 
1215 	if (dc->state == D_DONE || dc->len == 1) {
1216 		__remove_discard_cmd(sbi, dc);
1217 		return;
1218 	}
1219 
1220 	dcc->undiscard_blks -= di.len;
1221 
1222 	if (blkaddr > di.lstart) {
1223 		dc->len = blkaddr - dc->lstart;
1224 		dcc->undiscard_blks += dc->len;
1225 		__relocate_discard_cmd(dcc, dc);
1226 		modified = true;
1227 	}
1228 
1229 	if (blkaddr < di.lstart + di.len - 1) {
1230 		if (modified) {
1231 			__insert_discard_tree(sbi, dc->bdev, blkaddr + 1,
1232 					di.start + blkaddr + 1 - di.lstart,
1233 					di.lstart + di.len - 1 - blkaddr,
1234 					NULL, NULL);
1235 		} else {
1236 			dc->lstart++;
1237 			dc->len--;
1238 			dc->start++;
1239 			dcc->undiscard_blks += dc->len;
1240 			__relocate_discard_cmd(dcc, dc);
1241 		}
1242 	}
1243 }
1244 
1245 static void __update_discard_tree_range(struct f2fs_sb_info *sbi,
1246 				struct block_device *bdev, block_t lstart,
1247 				block_t start, block_t len)
1248 {
1249 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1250 	struct discard_cmd *prev_dc = NULL, *next_dc = NULL;
1251 	struct discard_cmd *dc;
1252 	struct discard_info di = {0};
1253 	struct rb_node **insert_p = NULL, *insert_parent = NULL;
1254 	struct request_queue *q = bdev_get_queue(bdev);
1255 	unsigned int max_discard_blocks =
1256 			SECTOR_TO_BLOCK(q->limits.max_discard_sectors);
1257 	block_t end = lstart + len;
1258 
1259 	dc = (struct discard_cmd *)f2fs_lookup_rb_tree_ret(&dcc->root,
1260 					NULL, lstart,
1261 					(struct rb_entry **)&prev_dc,
1262 					(struct rb_entry **)&next_dc,
1263 					&insert_p, &insert_parent, true, NULL);
1264 	if (dc)
1265 		prev_dc = dc;
1266 
1267 	if (!prev_dc) {
1268 		di.lstart = lstart;
1269 		di.len = next_dc ? next_dc->lstart - lstart : len;
1270 		di.len = min(di.len, len);
1271 		di.start = start;
1272 	}
1273 
1274 	while (1) {
1275 		struct rb_node *node;
1276 		bool merged = false;
1277 		struct discard_cmd *tdc = NULL;
1278 
1279 		if (prev_dc) {
1280 			di.lstart = prev_dc->lstart + prev_dc->len;
1281 			if (di.lstart < lstart)
1282 				di.lstart = lstart;
1283 			if (di.lstart >= end)
1284 				break;
1285 
1286 			if (!next_dc || next_dc->lstart > end)
1287 				di.len = end - di.lstart;
1288 			else
1289 				di.len = next_dc->lstart - di.lstart;
1290 			di.start = start + di.lstart - lstart;
1291 		}
1292 
1293 		if (!di.len)
1294 			goto next;
1295 
1296 		if (prev_dc && prev_dc->state == D_PREP &&
1297 			prev_dc->bdev == bdev &&
1298 			__is_discard_back_mergeable(&di, &prev_dc->di,
1299 							max_discard_blocks)) {
1300 			prev_dc->di.len += di.len;
1301 			dcc->undiscard_blks += di.len;
1302 			__relocate_discard_cmd(dcc, prev_dc);
1303 			di = prev_dc->di;
1304 			tdc = prev_dc;
1305 			merged = true;
1306 		}
1307 
1308 		if (next_dc && next_dc->state == D_PREP &&
1309 			next_dc->bdev == bdev &&
1310 			__is_discard_front_mergeable(&di, &next_dc->di,
1311 							max_discard_blocks)) {
1312 			next_dc->di.lstart = di.lstart;
1313 			next_dc->di.len += di.len;
1314 			next_dc->di.start = di.start;
1315 			dcc->undiscard_blks += di.len;
1316 			__relocate_discard_cmd(dcc, next_dc);
1317 			if (tdc)
1318 				__remove_discard_cmd(sbi, tdc);
1319 			merged = true;
1320 		}
1321 
1322 		if (!merged) {
1323 			__insert_discard_tree(sbi, bdev, di.lstart, di.start,
1324 							di.len, NULL, NULL);
1325 		}
1326  next:
1327 		prev_dc = next_dc;
1328 		if (!prev_dc)
1329 			break;
1330 
1331 		node = rb_next(&prev_dc->rb_node);
1332 		next_dc = rb_entry_safe(node, struct discard_cmd, rb_node);
1333 	}
1334 }
1335 
1336 static int __queue_discard_cmd(struct f2fs_sb_info *sbi,
1337 		struct block_device *bdev, block_t blkstart, block_t blklen)
1338 {
1339 	block_t lblkstart = blkstart;
1340 
1341 	trace_f2fs_queue_discard(bdev, blkstart, blklen);
1342 
1343 	if (sbi->s_ndevs) {
1344 		int devi = f2fs_target_device_index(sbi, blkstart);
1345 
1346 		blkstart -= FDEV(devi).start_blk;
1347 	}
1348 	mutex_lock(&SM_I(sbi)->dcc_info->cmd_lock);
1349 	__update_discard_tree_range(sbi, bdev, lblkstart, blkstart, blklen);
1350 	mutex_unlock(&SM_I(sbi)->dcc_info->cmd_lock);
1351 	return 0;
1352 }
1353 
1354 static unsigned int __issue_discard_cmd_orderly(struct f2fs_sb_info *sbi,
1355 					struct discard_policy *dpolicy)
1356 {
1357 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1358 	struct discard_cmd *prev_dc = NULL, *next_dc = NULL;
1359 	struct rb_node **insert_p = NULL, *insert_parent = NULL;
1360 	struct discard_cmd *dc;
1361 	struct blk_plug plug;
1362 	unsigned int pos = dcc->next_pos;
1363 	unsigned int issued = 0;
1364 	bool io_interrupted = false;
1365 
1366 	mutex_lock(&dcc->cmd_lock);
1367 	dc = (struct discard_cmd *)f2fs_lookup_rb_tree_ret(&dcc->root,
1368 					NULL, pos,
1369 					(struct rb_entry **)&prev_dc,
1370 					(struct rb_entry **)&next_dc,
1371 					&insert_p, &insert_parent, true, NULL);
1372 	if (!dc)
1373 		dc = next_dc;
1374 
1375 	blk_start_plug(&plug);
1376 
1377 	while (dc) {
1378 		struct rb_node *node;
1379 		int err = 0;
1380 
1381 		if (dc->state != D_PREP)
1382 			goto next;
1383 
1384 		if (dpolicy->io_aware && !is_idle(sbi, DISCARD_TIME)) {
1385 			io_interrupted = true;
1386 			break;
1387 		}
1388 
1389 		dcc->next_pos = dc->lstart + dc->len;
1390 		err = __submit_discard_cmd(sbi, dpolicy, dc, &issued);
1391 
1392 		if (issued >= dpolicy->max_requests)
1393 			break;
1394 next:
1395 		node = rb_next(&dc->rb_node);
1396 		if (err)
1397 			__remove_discard_cmd(sbi, dc);
1398 		dc = rb_entry_safe(node, struct discard_cmd, rb_node);
1399 	}
1400 
1401 	blk_finish_plug(&plug);
1402 
1403 	if (!dc)
1404 		dcc->next_pos = 0;
1405 
1406 	mutex_unlock(&dcc->cmd_lock);
1407 
1408 	if (!issued && io_interrupted)
1409 		issued = -1;
1410 
1411 	return issued;
1412 }
1413 
1414 static int __issue_discard_cmd(struct f2fs_sb_info *sbi,
1415 					struct discard_policy *dpolicy)
1416 {
1417 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1418 	struct list_head *pend_list;
1419 	struct discard_cmd *dc, *tmp;
1420 	struct blk_plug plug;
1421 	int i, issued = 0;
1422 	bool io_interrupted = false;
1423 
1424 	for (i = MAX_PLIST_NUM - 1; i >= 0; i--) {
1425 		if (i + 1 < dpolicy->granularity)
1426 			break;
1427 
1428 		if (i < DEFAULT_DISCARD_GRANULARITY && dpolicy->ordered)
1429 			return __issue_discard_cmd_orderly(sbi, dpolicy);
1430 
1431 		pend_list = &dcc->pend_list[i];
1432 
1433 		mutex_lock(&dcc->cmd_lock);
1434 		if (list_empty(pend_list))
1435 			goto next;
1436 		if (unlikely(dcc->rbtree_check))
1437 			f2fs_bug_on(sbi, !f2fs_check_rb_tree_consistence(sbi,
1438 								&dcc->root));
1439 		blk_start_plug(&plug);
1440 		list_for_each_entry_safe(dc, tmp, pend_list, list) {
1441 			f2fs_bug_on(sbi, dc->state != D_PREP);
1442 
1443 			if (dpolicy->io_aware && i < dpolicy->io_aware_gran &&
1444 						!is_idle(sbi, DISCARD_TIME)) {
1445 				io_interrupted = true;
1446 				break;
1447 			}
1448 
1449 			__submit_discard_cmd(sbi, dpolicy, dc, &issued);
1450 
1451 			if (issued >= dpolicy->max_requests)
1452 				break;
1453 		}
1454 		blk_finish_plug(&plug);
1455 next:
1456 		mutex_unlock(&dcc->cmd_lock);
1457 
1458 		if (issued >= dpolicy->max_requests || io_interrupted)
1459 			break;
1460 	}
1461 
1462 	if (!issued && io_interrupted)
1463 		issued = -1;
1464 
1465 	return issued;
1466 }
1467 
1468 static bool __drop_discard_cmd(struct f2fs_sb_info *sbi)
1469 {
1470 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1471 	struct list_head *pend_list;
1472 	struct discard_cmd *dc, *tmp;
1473 	int i;
1474 	bool dropped = false;
1475 
1476 	mutex_lock(&dcc->cmd_lock);
1477 	for (i = MAX_PLIST_NUM - 1; i >= 0; i--) {
1478 		pend_list = &dcc->pend_list[i];
1479 		list_for_each_entry_safe(dc, tmp, pend_list, list) {
1480 			f2fs_bug_on(sbi, dc->state != D_PREP);
1481 			__remove_discard_cmd(sbi, dc);
1482 			dropped = true;
1483 		}
1484 	}
1485 	mutex_unlock(&dcc->cmd_lock);
1486 
1487 	return dropped;
1488 }
1489 
1490 void f2fs_drop_discard_cmd(struct f2fs_sb_info *sbi)
1491 {
1492 	__drop_discard_cmd(sbi);
1493 }
1494 
1495 static unsigned int __wait_one_discard_bio(struct f2fs_sb_info *sbi,
1496 							struct discard_cmd *dc)
1497 {
1498 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1499 	unsigned int len = 0;
1500 
1501 	wait_for_completion_io(&dc->wait);
1502 	mutex_lock(&dcc->cmd_lock);
1503 	f2fs_bug_on(sbi, dc->state != D_DONE);
1504 	dc->ref--;
1505 	if (!dc->ref) {
1506 		if (!dc->error)
1507 			len = dc->len;
1508 		__remove_discard_cmd(sbi, dc);
1509 	}
1510 	mutex_unlock(&dcc->cmd_lock);
1511 
1512 	return len;
1513 }
1514 
1515 static unsigned int __wait_discard_cmd_range(struct f2fs_sb_info *sbi,
1516 						struct discard_policy *dpolicy,
1517 						block_t start, block_t end)
1518 {
1519 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1520 	struct list_head *wait_list = (dpolicy->type == DPOLICY_FSTRIM) ?
1521 					&(dcc->fstrim_list) : &(dcc->wait_list);
1522 	struct discard_cmd *dc, *tmp;
1523 	bool need_wait;
1524 	unsigned int trimmed = 0;
1525 
1526 next:
1527 	need_wait = false;
1528 
1529 	mutex_lock(&dcc->cmd_lock);
1530 	list_for_each_entry_safe(dc, tmp, wait_list, list) {
1531 		if (dc->lstart + dc->len <= start || end <= dc->lstart)
1532 			continue;
1533 		if (dc->len < dpolicy->granularity)
1534 			continue;
1535 		if (dc->state == D_DONE && !dc->ref) {
1536 			wait_for_completion_io(&dc->wait);
1537 			if (!dc->error)
1538 				trimmed += dc->len;
1539 			__remove_discard_cmd(sbi, dc);
1540 		} else {
1541 			dc->ref++;
1542 			need_wait = true;
1543 			break;
1544 		}
1545 	}
1546 	mutex_unlock(&dcc->cmd_lock);
1547 
1548 	if (need_wait) {
1549 		trimmed += __wait_one_discard_bio(sbi, dc);
1550 		goto next;
1551 	}
1552 
1553 	return trimmed;
1554 }
1555 
1556 static unsigned int __wait_all_discard_cmd(struct f2fs_sb_info *sbi,
1557 						struct discard_policy *dpolicy)
1558 {
1559 	struct discard_policy dp;
1560 	unsigned int discard_blks;
1561 
1562 	if (dpolicy)
1563 		return __wait_discard_cmd_range(sbi, dpolicy, 0, UINT_MAX);
1564 
1565 	/* wait all */
1566 	__init_discard_policy(sbi, &dp, DPOLICY_FSTRIM, 1);
1567 	discard_blks = __wait_discard_cmd_range(sbi, &dp, 0, UINT_MAX);
1568 	__init_discard_policy(sbi, &dp, DPOLICY_UMOUNT, 1);
1569 	discard_blks += __wait_discard_cmd_range(sbi, &dp, 0, UINT_MAX);
1570 
1571 	return discard_blks;
1572 }
1573 
1574 /* This should be covered by global mutex, &sit_i->sentry_lock */
1575 static void f2fs_wait_discard_bio(struct f2fs_sb_info *sbi, block_t blkaddr)
1576 {
1577 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1578 	struct discard_cmd *dc;
1579 	bool need_wait = false;
1580 
1581 	mutex_lock(&dcc->cmd_lock);
1582 	dc = (struct discard_cmd *)f2fs_lookup_rb_tree(&dcc->root,
1583 							NULL, blkaddr);
1584 	if (dc) {
1585 		if (dc->state == D_PREP) {
1586 			__punch_discard_cmd(sbi, dc, blkaddr);
1587 		} else {
1588 			dc->ref++;
1589 			need_wait = true;
1590 		}
1591 	}
1592 	mutex_unlock(&dcc->cmd_lock);
1593 
1594 	if (need_wait)
1595 		__wait_one_discard_bio(sbi, dc);
1596 }
1597 
1598 void f2fs_stop_discard_thread(struct f2fs_sb_info *sbi)
1599 {
1600 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1601 
1602 	if (dcc && dcc->f2fs_issue_discard) {
1603 		struct task_struct *discard_thread = dcc->f2fs_issue_discard;
1604 
1605 		dcc->f2fs_issue_discard = NULL;
1606 		kthread_stop(discard_thread);
1607 	}
1608 }
1609 
1610 /* This comes from f2fs_put_super */
1611 bool f2fs_wait_discard_bios(struct f2fs_sb_info *sbi)
1612 {
1613 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1614 	struct discard_policy dpolicy;
1615 	bool dropped;
1616 
1617 	__init_discard_policy(sbi, &dpolicy, DPOLICY_UMOUNT,
1618 					dcc->discard_granularity);
1619 	__issue_discard_cmd(sbi, &dpolicy);
1620 	dropped = __drop_discard_cmd(sbi);
1621 
1622 	/* just to make sure there is no pending discard commands */
1623 	__wait_all_discard_cmd(sbi, NULL);
1624 
1625 	f2fs_bug_on(sbi, atomic_read(&dcc->discard_cmd_cnt));
1626 	return dropped;
1627 }
1628 
1629 static int issue_discard_thread(void *data)
1630 {
1631 	struct f2fs_sb_info *sbi = data;
1632 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1633 	wait_queue_head_t *q = &dcc->discard_wait_queue;
1634 	struct discard_policy dpolicy;
1635 	unsigned int wait_ms = DEF_MIN_DISCARD_ISSUE_TIME;
1636 	int issued;
1637 
1638 	set_freezable();
1639 
1640 	do {
1641 		__init_discard_policy(sbi, &dpolicy, DPOLICY_BG,
1642 					dcc->discard_granularity);
1643 
1644 		wait_event_interruptible_timeout(*q,
1645 				kthread_should_stop() || freezing(current) ||
1646 				dcc->discard_wake,
1647 				msecs_to_jiffies(wait_ms));
1648 
1649 		if (dcc->discard_wake)
1650 			dcc->discard_wake = 0;
1651 
1652 		if (try_to_freeze())
1653 			continue;
1654 		if (f2fs_readonly(sbi->sb))
1655 			continue;
1656 		if (kthread_should_stop())
1657 			return 0;
1658 		if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) {
1659 			wait_ms = dpolicy.max_interval;
1660 			continue;
1661 		}
1662 
1663 		if (sbi->gc_mode == GC_URGENT)
1664 			__init_discard_policy(sbi, &dpolicy, DPOLICY_FORCE, 1);
1665 
1666 		sb_start_intwrite(sbi->sb);
1667 
1668 		issued = __issue_discard_cmd(sbi, &dpolicy);
1669 		if (issued > 0) {
1670 			__wait_all_discard_cmd(sbi, &dpolicy);
1671 			wait_ms = dpolicy.min_interval;
1672 		} else if (issued == -1){
1673 			wait_ms = f2fs_time_to_wait(sbi, DISCARD_TIME);
1674 			if (!wait_ms)
1675 				wait_ms = dpolicy.mid_interval;
1676 		} else {
1677 			wait_ms = dpolicy.max_interval;
1678 		}
1679 
1680 		sb_end_intwrite(sbi->sb);
1681 
1682 	} while (!kthread_should_stop());
1683 	return 0;
1684 }
1685 
1686 #ifdef CONFIG_BLK_DEV_ZONED
1687 static int __f2fs_issue_discard_zone(struct f2fs_sb_info *sbi,
1688 		struct block_device *bdev, block_t blkstart, block_t blklen)
1689 {
1690 	sector_t sector, nr_sects;
1691 	block_t lblkstart = blkstart;
1692 	int devi = 0;
1693 
1694 	if (sbi->s_ndevs) {
1695 		devi = f2fs_target_device_index(sbi, blkstart);
1696 		blkstart -= FDEV(devi).start_blk;
1697 	}
1698 
1699 	/*
1700 	 * We need to know the type of the zone: for conventional zones,
1701 	 * use regular discard if the drive supports it. For sequential
1702 	 * zones, reset the zone write pointer.
1703 	 */
1704 	switch (get_blkz_type(sbi, bdev, blkstart)) {
1705 
1706 	case BLK_ZONE_TYPE_CONVENTIONAL:
1707 		if (!blk_queue_discard(bdev_get_queue(bdev)))
1708 			return 0;
1709 		return __queue_discard_cmd(sbi, bdev, lblkstart, blklen);
1710 	case BLK_ZONE_TYPE_SEQWRITE_REQ:
1711 	case BLK_ZONE_TYPE_SEQWRITE_PREF:
1712 		sector = SECTOR_FROM_BLOCK(blkstart);
1713 		nr_sects = SECTOR_FROM_BLOCK(blklen);
1714 
1715 		if (sector & (bdev_zone_sectors(bdev) - 1) ||
1716 				nr_sects != bdev_zone_sectors(bdev)) {
1717 			f2fs_msg(sbi->sb, KERN_INFO,
1718 				"(%d) %s: Unaligned discard attempted (block %x + %x)",
1719 				devi, sbi->s_ndevs ? FDEV(devi).path: "",
1720 				blkstart, blklen);
1721 			return -EIO;
1722 		}
1723 		trace_f2fs_issue_reset_zone(bdev, blkstart);
1724 		return blkdev_reset_zones(bdev, sector,
1725 					  nr_sects, GFP_NOFS);
1726 	default:
1727 		/* Unknown zone type: broken device ? */
1728 		return -EIO;
1729 	}
1730 }
1731 #endif
1732 
1733 static int __issue_discard_async(struct f2fs_sb_info *sbi,
1734 		struct block_device *bdev, block_t blkstart, block_t blklen)
1735 {
1736 #ifdef CONFIG_BLK_DEV_ZONED
1737 	if (f2fs_sb_has_blkzoned(sbi->sb) &&
1738 				bdev_zoned_model(bdev) != BLK_ZONED_NONE)
1739 		return __f2fs_issue_discard_zone(sbi, bdev, blkstart, blklen);
1740 #endif
1741 	return __queue_discard_cmd(sbi, bdev, blkstart, blklen);
1742 }
1743 
1744 static int f2fs_issue_discard(struct f2fs_sb_info *sbi,
1745 				block_t blkstart, block_t blklen)
1746 {
1747 	sector_t start = blkstart, len = 0;
1748 	struct block_device *bdev;
1749 	struct seg_entry *se;
1750 	unsigned int offset;
1751 	block_t i;
1752 	int err = 0;
1753 
1754 	bdev = f2fs_target_device(sbi, blkstart, NULL);
1755 
1756 	for (i = blkstart; i < blkstart + blklen; i++, len++) {
1757 		if (i != start) {
1758 			struct block_device *bdev2 =
1759 				f2fs_target_device(sbi, i, NULL);
1760 
1761 			if (bdev2 != bdev) {
1762 				err = __issue_discard_async(sbi, bdev,
1763 						start, len);
1764 				if (err)
1765 					return err;
1766 				bdev = bdev2;
1767 				start = i;
1768 				len = 0;
1769 			}
1770 		}
1771 
1772 		se = get_seg_entry(sbi, GET_SEGNO(sbi, i));
1773 		offset = GET_BLKOFF_FROM_SEG0(sbi, i);
1774 
1775 		if (!f2fs_test_and_set_bit(offset, se->discard_map))
1776 			sbi->discard_blks--;
1777 	}
1778 
1779 	if (len)
1780 		err = __issue_discard_async(sbi, bdev, start, len);
1781 	return err;
1782 }
1783 
1784 static bool add_discard_addrs(struct f2fs_sb_info *sbi, struct cp_control *cpc,
1785 							bool check_only)
1786 {
1787 	int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
1788 	int max_blocks = sbi->blocks_per_seg;
1789 	struct seg_entry *se = get_seg_entry(sbi, cpc->trim_start);
1790 	unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
1791 	unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
1792 	unsigned long *discard_map = (unsigned long *)se->discard_map;
1793 	unsigned long *dmap = SIT_I(sbi)->tmp_map;
1794 	unsigned int start = 0, end = -1;
1795 	bool force = (cpc->reason & CP_DISCARD);
1796 	struct discard_entry *de = NULL;
1797 	struct list_head *head = &SM_I(sbi)->dcc_info->entry_list;
1798 	int i;
1799 
1800 	if (se->valid_blocks == max_blocks || !f2fs_hw_support_discard(sbi))
1801 		return false;
1802 
1803 	if (!force) {
1804 		if (!f2fs_realtime_discard_enable(sbi) || !se->valid_blocks ||
1805 			SM_I(sbi)->dcc_info->nr_discards >=
1806 				SM_I(sbi)->dcc_info->max_discards)
1807 			return false;
1808 	}
1809 
1810 	/* SIT_VBLOCK_MAP_SIZE should be multiple of sizeof(unsigned long) */
1811 	for (i = 0; i < entries; i++)
1812 		dmap[i] = force ? ~ckpt_map[i] & ~discard_map[i] :
1813 				(cur_map[i] ^ ckpt_map[i]) & ckpt_map[i];
1814 
1815 	while (force || SM_I(sbi)->dcc_info->nr_discards <=
1816 				SM_I(sbi)->dcc_info->max_discards) {
1817 		start = __find_rev_next_bit(dmap, max_blocks, end + 1);
1818 		if (start >= max_blocks)
1819 			break;
1820 
1821 		end = __find_rev_next_zero_bit(dmap, max_blocks, start + 1);
1822 		if (force && start && end != max_blocks
1823 					&& (end - start) < cpc->trim_minlen)
1824 			continue;
1825 
1826 		if (check_only)
1827 			return true;
1828 
1829 		if (!de) {
1830 			de = f2fs_kmem_cache_alloc(discard_entry_slab,
1831 								GFP_F2FS_ZERO);
1832 			de->start_blkaddr = START_BLOCK(sbi, cpc->trim_start);
1833 			list_add_tail(&de->list, head);
1834 		}
1835 
1836 		for (i = start; i < end; i++)
1837 			__set_bit_le(i, (void *)de->discard_map);
1838 
1839 		SM_I(sbi)->dcc_info->nr_discards += end - start;
1840 	}
1841 	return false;
1842 }
1843 
1844 static void release_discard_addr(struct discard_entry *entry)
1845 {
1846 	list_del(&entry->list);
1847 	kmem_cache_free(discard_entry_slab, entry);
1848 }
1849 
1850 void f2fs_release_discard_addrs(struct f2fs_sb_info *sbi)
1851 {
1852 	struct list_head *head = &(SM_I(sbi)->dcc_info->entry_list);
1853 	struct discard_entry *entry, *this;
1854 
1855 	/* drop caches */
1856 	list_for_each_entry_safe(entry, this, head, list)
1857 		release_discard_addr(entry);
1858 }
1859 
1860 /*
1861  * Should call f2fs_clear_prefree_segments after checkpoint is done.
1862  */
1863 static void set_prefree_as_free_segments(struct f2fs_sb_info *sbi)
1864 {
1865 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
1866 	unsigned int segno;
1867 
1868 	mutex_lock(&dirty_i->seglist_lock);
1869 	for_each_set_bit(segno, dirty_i->dirty_segmap[PRE], MAIN_SEGS(sbi))
1870 		__set_test_and_free(sbi, segno);
1871 	mutex_unlock(&dirty_i->seglist_lock);
1872 }
1873 
1874 void f2fs_clear_prefree_segments(struct f2fs_sb_info *sbi,
1875 						struct cp_control *cpc)
1876 {
1877 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
1878 	struct list_head *head = &dcc->entry_list;
1879 	struct discard_entry *entry, *this;
1880 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
1881 	unsigned long *prefree_map = dirty_i->dirty_segmap[PRE];
1882 	unsigned int start = 0, end = -1;
1883 	unsigned int secno, start_segno;
1884 	bool force = (cpc->reason & CP_DISCARD);
1885 	bool need_align = test_opt(sbi, LFS) && sbi->segs_per_sec > 1;
1886 
1887 	mutex_lock(&dirty_i->seglist_lock);
1888 
1889 	while (1) {
1890 		int i;
1891 
1892 		if (need_align && end != -1)
1893 			end--;
1894 		start = find_next_bit(prefree_map, MAIN_SEGS(sbi), end + 1);
1895 		if (start >= MAIN_SEGS(sbi))
1896 			break;
1897 		end = find_next_zero_bit(prefree_map, MAIN_SEGS(sbi),
1898 								start + 1);
1899 
1900 		if (need_align) {
1901 			start = rounddown(start, sbi->segs_per_sec);
1902 			end = roundup(end, sbi->segs_per_sec);
1903 		}
1904 
1905 		for (i = start; i < end; i++) {
1906 			if (test_and_clear_bit(i, prefree_map))
1907 				dirty_i->nr_dirty[PRE]--;
1908 		}
1909 
1910 		if (!f2fs_realtime_discard_enable(sbi))
1911 			continue;
1912 
1913 		if (force && start >= cpc->trim_start &&
1914 					(end - 1) <= cpc->trim_end)
1915 				continue;
1916 
1917 		if (!test_opt(sbi, LFS) || sbi->segs_per_sec == 1) {
1918 			f2fs_issue_discard(sbi, START_BLOCK(sbi, start),
1919 				(end - start) << sbi->log_blocks_per_seg);
1920 			continue;
1921 		}
1922 next:
1923 		secno = GET_SEC_FROM_SEG(sbi, start);
1924 		start_segno = GET_SEG_FROM_SEC(sbi, secno);
1925 		if (!IS_CURSEC(sbi, secno) &&
1926 			!get_valid_blocks(sbi, start, true))
1927 			f2fs_issue_discard(sbi, START_BLOCK(sbi, start_segno),
1928 				sbi->segs_per_sec << sbi->log_blocks_per_seg);
1929 
1930 		start = start_segno + sbi->segs_per_sec;
1931 		if (start < end)
1932 			goto next;
1933 		else
1934 			end = start - 1;
1935 	}
1936 	mutex_unlock(&dirty_i->seglist_lock);
1937 
1938 	/* send small discards */
1939 	list_for_each_entry_safe(entry, this, head, list) {
1940 		unsigned int cur_pos = 0, next_pos, len, total_len = 0;
1941 		bool is_valid = test_bit_le(0, entry->discard_map);
1942 
1943 find_next:
1944 		if (is_valid) {
1945 			next_pos = find_next_zero_bit_le(entry->discard_map,
1946 					sbi->blocks_per_seg, cur_pos);
1947 			len = next_pos - cur_pos;
1948 
1949 			if (f2fs_sb_has_blkzoned(sbi->sb) ||
1950 			    (force && len < cpc->trim_minlen))
1951 				goto skip;
1952 
1953 			f2fs_issue_discard(sbi, entry->start_blkaddr + cur_pos,
1954 									len);
1955 			total_len += len;
1956 		} else {
1957 			next_pos = find_next_bit_le(entry->discard_map,
1958 					sbi->blocks_per_seg, cur_pos);
1959 		}
1960 skip:
1961 		cur_pos = next_pos;
1962 		is_valid = !is_valid;
1963 
1964 		if (cur_pos < sbi->blocks_per_seg)
1965 			goto find_next;
1966 
1967 		release_discard_addr(entry);
1968 		dcc->nr_discards -= total_len;
1969 	}
1970 
1971 	wake_up_discard_thread(sbi, false);
1972 }
1973 
1974 static int create_discard_cmd_control(struct f2fs_sb_info *sbi)
1975 {
1976 	dev_t dev = sbi->sb->s_bdev->bd_dev;
1977 	struct discard_cmd_control *dcc;
1978 	int err = 0, i;
1979 
1980 	if (SM_I(sbi)->dcc_info) {
1981 		dcc = SM_I(sbi)->dcc_info;
1982 		goto init_thread;
1983 	}
1984 
1985 	dcc = f2fs_kzalloc(sbi, sizeof(struct discard_cmd_control), GFP_KERNEL);
1986 	if (!dcc)
1987 		return -ENOMEM;
1988 
1989 	dcc->discard_granularity = DEFAULT_DISCARD_GRANULARITY;
1990 	INIT_LIST_HEAD(&dcc->entry_list);
1991 	for (i = 0; i < MAX_PLIST_NUM; i++)
1992 		INIT_LIST_HEAD(&dcc->pend_list[i]);
1993 	INIT_LIST_HEAD(&dcc->wait_list);
1994 	INIT_LIST_HEAD(&dcc->fstrim_list);
1995 	mutex_init(&dcc->cmd_lock);
1996 	atomic_set(&dcc->issued_discard, 0);
1997 	atomic_set(&dcc->issing_discard, 0);
1998 	atomic_set(&dcc->discard_cmd_cnt, 0);
1999 	dcc->nr_discards = 0;
2000 	dcc->max_discards = MAIN_SEGS(sbi) << sbi->log_blocks_per_seg;
2001 	dcc->undiscard_blks = 0;
2002 	dcc->next_pos = 0;
2003 	dcc->root = RB_ROOT_CACHED;
2004 	dcc->rbtree_check = false;
2005 
2006 	init_waitqueue_head(&dcc->discard_wait_queue);
2007 	SM_I(sbi)->dcc_info = dcc;
2008 init_thread:
2009 	dcc->f2fs_issue_discard = kthread_run(issue_discard_thread, sbi,
2010 				"f2fs_discard-%u:%u", MAJOR(dev), MINOR(dev));
2011 	if (IS_ERR(dcc->f2fs_issue_discard)) {
2012 		err = PTR_ERR(dcc->f2fs_issue_discard);
2013 		kfree(dcc);
2014 		SM_I(sbi)->dcc_info = NULL;
2015 		return err;
2016 	}
2017 
2018 	return err;
2019 }
2020 
2021 static void destroy_discard_cmd_control(struct f2fs_sb_info *sbi)
2022 {
2023 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
2024 
2025 	if (!dcc)
2026 		return;
2027 
2028 	f2fs_stop_discard_thread(sbi);
2029 
2030 	kfree(dcc);
2031 	SM_I(sbi)->dcc_info = NULL;
2032 }
2033 
2034 static bool __mark_sit_entry_dirty(struct f2fs_sb_info *sbi, unsigned int segno)
2035 {
2036 	struct sit_info *sit_i = SIT_I(sbi);
2037 
2038 	if (!__test_and_set_bit(segno, sit_i->dirty_sentries_bitmap)) {
2039 		sit_i->dirty_sentries++;
2040 		return false;
2041 	}
2042 
2043 	return true;
2044 }
2045 
2046 static void __set_sit_entry_type(struct f2fs_sb_info *sbi, int type,
2047 					unsigned int segno, int modified)
2048 {
2049 	struct seg_entry *se = get_seg_entry(sbi, segno);
2050 	se->type = type;
2051 	if (modified)
2052 		__mark_sit_entry_dirty(sbi, segno);
2053 }
2054 
2055 static void update_sit_entry(struct f2fs_sb_info *sbi, block_t blkaddr, int del)
2056 {
2057 	struct seg_entry *se;
2058 	unsigned int segno, offset;
2059 	long int new_vblocks;
2060 	bool exist;
2061 #ifdef CONFIG_F2FS_CHECK_FS
2062 	bool mir_exist;
2063 #endif
2064 
2065 	segno = GET_SEGNO(sbi, blkaddr);
2066 
2067 	se = get_seg_entry(sbi, segno);
2068 	new_vblocks = se->valid_blocks + del;
2069 	offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
2070 
2071 	f2fs_bug_on(sbi, (new_vblocks >> (sizeof(unsigned short) << 3) ||
2072 				(new_vblocks > sbi->blocks_per_seg)));
2073 
2074 	se->valid_blocks = new_vblocks;
2075 	se->mtime = get_mtime(sbi, false);
2076 	if (se->mtime > SIT_I(sbi)->max_mtime)
2077 		SIT_I(sbi)->max_mtime = se->mtime;
2078 
2079 	/* Update valid block bitmap */
2080 	if (del > 0) {
2081 		exist = f2fs_test_and_set_bit(offset, se->cur_valid_map);
2082 #ifdef CONFIG_F2FS_CHECK_FS
2083 		mir_exist = f2fs_test_and_set_bit(offset,
2084 						se->cur_valid_map_mir);
2085 		if (unlikely(exist != mir_exist)) {
2086 			f2fs_msg(sbi->sb, KERN_ERR, "Inconsistent error "
2087 				"when setting bitmap, blk:%u, old bit:%d",
2088 				blkaddr, exist);
2089 			f2fs_bug_on(sbi, 1);
2090 		}
2091 #endif
2092 		if (unlikely(exist)) {
2093 			f2fs_msg(sbi->sb, KERN_ERR,
2094 				"Bitmap was wrongly set, blk:%u", blkaddr);
2095 			f2fs_bug_on(sbi, 1);
2096 			se->valid_blocks--;
2097 			del = 0;
2098 		}
2099 
2100 		if (!f2fs_test_and_set_bit(offset, se->discard_map))
2101 			sbi->discard_blks--;
2102 
2103 		/* don't overwrite by SSR to keep node chain */
2104 		if (IS_NODESEG(se->type) &&
2105 				!is_sbi_flag_set(sbi, SBI_CP_DISABLED)) {
2106 			if (!f2fs_test_and_set_bit(offset, se->ckpt_valid_map))
2107 				se->ckpt_valid_blocks++;
2108 		}
2109 	} else {
2110 		exist = f2fs_test_and_clear_bit(offset, se->cur_valid_map);
2111 #ifdef CONFIG_F2FS_CHECK_FS
2112 		mir_exist = f2fs_test_and_clear_bit(offset,
2113 						se->cur_valid_map_mir);
2114 		if (unlikely(exist != mir_exist)) {
2115 			f2fs_msg(sbi->sb, KERN_ERR, "Inconsistent error "
2116 				"when clearing bitmap, blk:%u, old bit:%d",
2117 				blkaddr, exist);
2118 			f2fs_bug_on(sbi, 1);
2119 		}
2120 #endif
2121 		if (unlikely(!exist)) {
2122 			f2fs_msg(sbi->sb, KERN_ERR,
2123 				"Bitmap was wrongly cleared, blk:%u", blkaddr);
2124 			f2fs_bug_on(sbi, 1);
2125 			se->valid_blocks++;
2126 			del = 0;
2127 		} else if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) {
2128 			/*
2129 			 * If checkpoints are off, we must not reuse data that
2130 			 * was used in the previous checkpoint. If it was used
2131 			 * before, we must track that to know how much space we
2132 			 * really have.
2133 			 */
2134 			if (f2fs_test_bit(offset, se->ckpt_valid_map))
2135 				sbi->unusable_block_count++;
2136 		}
2137 
2138 		if (f2fs_test_and_clear_bit(offset, se->discard_map))
2139 			sbi->discard_blks++;
2140 	}
2141 	if (!f2fs_test_bit(offset, se->ckpt_valid_map))
2142 		se->ckpt_valid_blocks += del;
2143 
2144 	__mark_sit_entry_dirty(sbi, segno);
2145 
2146 	/* update total number of valid blocks to be written in ckpt area */
2147 	SIT_I(sbi)->written_valid_blocks += del;
2148 
2149 	if (sbi->segs_per_sec > 1)
2150 		get_sec_entry(sbi, segno)->valid_blocks += del;
2151 }
2152 
2153 void f2fs_invalidate_blocks(struct f2fs_sb_info *sbi, block_t addr)
2154 {
2155 	unsigned int segno = GET_SEGNO(sbi, addr);
2156 	struct sit_info *sit_i = SIT_I(sbi);
2157 
2158 	f2fs_bug_on(sbi, addr == NULL_ADDR);
2159 	if (addr == NEW_ADDR)
2160 		return;
2161 
2162 	invalidate_mapping_pages(META_MAPPING(sbi), addr, addr);
2163 
2164 	/* add it into sit main buffer */
2165 	down_write(&sit_i->sentry_lock);
2166 
2167 	update_sit_entry(sbi, addr, -1);
2168 
2169 	/* add it into dirty seglist */
2170 	locate_dirty_segment(sbi, segno);
2171 
2172 	up_write(&sit_i->sentry_lock);
2173 }
2174 
2175 bool f2fs_is_checkpointed_data(struct f2fs_sb_info *sbi, block_t blkaddr)
2176 {
2177 	struct sit_info *sit_i = SIT_I(sbi);
2178 	unsigned int segno, offset;
2179 	struct seg_entry *se;
2180 	bool is_cp = false;
2181 
2182 	if (!is_valid_data_blkaddr(sbi, blkaddr))
2183 		return true;
2184 
2185 	down_read(&sit_i->sentry_lock);
2186 
2187 	segno = GET_SEGNO(sbi, blkaddr);
2188 	se = get_seg_entry(sbi, segno);
2189 	offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
2190 
2191 	if (f2fs_test_bit(offset, se->ckpt_valid_map))
2192 		is_cp = true;
2193 
2194 	up_read(&sit_i->sentry_lock);
2195 
2196 	return is_cp;
2197 }
2198 
2199 /*
2200  * This function should be resided under the curseg_mutex lock
2201  */
2202 static void __add_sum_entry(struct f2fs_sb_info *sbi, int type,
2203 					struct f2fs_summary *sum)
2204 {
2205 	struct curseg_info *curseg = CURSEG_I(sbi, type);
2206 	void *addr = curseg->sum_blk;
2207 	addr += curseg->next_blkoff * sizeof(struct f2fs_summary);
2208 	memcpy(addr, sum, sizeof(struct f2fs_summary));
2209 }
2210 
2211 /*
2212  * Calculate the number of current summary pages for writing
2213  */
2214 int f2fs_npages_for_summary_flush(struct f2fs_sb_info *sbi, bool for_ra)
2215 {
2216 	int valid_sum_count = 0;
2217 	int i, sum_in_page;
2218 
2219 	for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
2220 		if (sbi->ckpt->alloc_type[i] == SSR)
2221 			valid_sum_count += sbi->blocks_per_seg;
2222 		else {
2223 			if (for_ra)
2224 				valid_sum_count += le16_to_cpu(
2225 					F2FS_CKPT(sbi)->cur_data_blkoff[i]);
2226 			else
2227 				valid_sum_count += curseg_blkoff(sbi, i);
2228 		}
2229 	}
2230 
2231 	sum_in_page = (PAGE_SIZE - 2 * SUM_JOURNAL_SIZE -
2232 			SUM_FOOTER_SIZE) / SUMMARY_SIZE;
2233 	if (valid_sum_count <= sum_in_page)
2234 		return 1;
2235 	else if ((valid_sum_count - sum_in_page) <=
2236 		(PAGE_SIZE - SUM_FOOTER_SIZE) / SUMMARY_SIZE)
2237 		return 2;
2238 	return 3;
2239 }
2240 
2241 /*
2242  * Caller should put this summary page
2243  */
2244 struct page *f2fs_get_sum_page(struct f2fs_sb_info *sbi, unsigned int segno)
2245 {
2246 	return f2fs_get_meta_page_nofail(sbi, GET_SUM_BLOCK(sbi, segno));
2247 }
2248 
2249 void f2fs_update_meta_page(struct f2fs_sb_info *sbi,
2250 					void *src, block_t blk_addr)
2251 {
2252 	struct page *page = f2fs_grab_meta_page(sbi, blk_addr);
2253 
2254 	memcpy(page_address(page), src, PAGE_SIZE);
2255 	set_page_dirty(page);
2256 	f2fs_put_page(page, 1);
2257 }
2258 
2259 static void write_sum_page(struct f2fs_sb_info *sbi,
2260 			struct f2fs_summary_block *sum_blk, block_t blk_addr)
2261 {
2262 	f2fs_update_meta_page(sbi, (void *)sum_blk, blk_addr);
2263 }
2264 
2265 static void write_current_sum_page(struct f2fs_sb_info *sbi,
2266 						int type, block_t blk_addr)
2267 {
2268 	struct curseg_info *curseg = CURSEG_I(sbi, type);
2269 	struct page *page = f2fs_grab_meta_page(sbi, blk_addr);
2270 	struct f2fs_summary_block *src = curseg->sum_blk;
2271 	struct f2fs_summary_block *dst;
2272 
2273 	dst = (struct f2fs_summary_block *)page_address(page);
2274 	memset(dst, 0, PAGE_SIZE);
2275 
2276 	mutex_lock(&curseg->curseg_mutex);
2277 
2278 	down_read(&curseg->journal_rwsem);
2279 	memcpy(&dst->journal, curseg->journal, SUM_JOURNAL_SIZE);
2280 	up_read(&curseg->journal_rwsem);
2281 
2282 	memcpy(dst->entries, src->entries, SUM_ENTRY_SIZE);
2283 	memcpy(&dst->footer, &src->footer, SUM_FOOTER_SIZE);
2284 
2285 	mutex_unlock(&curseg->curseg_mutex);
2286 
2287 	set_page_dirty(page);
2288 	f2fs_put_page(page, 1);
2289 }
2290 
2291 static int is_next_segment_free(struct f2fs_sb_info *sbi, int type)
2292 {
2293 	struct curseg_info *curseg = CURSEG_I(sbi, type);
2294 	unsigned int segno = curseg->segno + 1;
2295 	struct free_segmap_info *free_i = FREE_I(sbi);
2296 
2297 	if (segno < MAIN_SEGS(sbi) && segno % sbi->segs_per_sec)
2298 		return !test_bit(segno, free_i->free_segmap);
2299 	return 0;
2300 }
2301 
2302 /*
2303  * Find a new segment from the free segments bitmap to right order
2304  * This function should be returned with success, otherwise BUG
2305  */
2306 static void get_new_segment(struct f2fs_sb_info *sbi,
2307 			unsigned int *newseg, bool new_sec, int dir)
2308 {
2309 	struct free_segmap_info *free_i = FREE_I(sbi);
2310 	unsigned int segno, secno, zoneno;
2311 	unsigned int total_zones = MAIN_SECS(sbi) / sbi->secs_per_zone;
2312 	unsigned int hint = GET_SEC_FROM_SEG(sbi, *newseg);
2313 	unsigned int old_zoneno = GET_ZONE_FROM_SEG(sbi, *newseg);
2314 	unsigned int left_start = hint;
2315 	bool init = true;
2316 	int go_left = 0;
2317 	int i;
2318 
2319 	spin_lock(&free_i->segmap_lock);
2320 
2321 	if (!new_sec && ((*newseg + 1) % sbi->segs_per_sec)) {
2322 		segno = find_next_zero_bit(free_i->free_segmap,
2323 			GET_SEG_FROM_SEC(sbi, hint + 1), *newseg + 1);
2324 		if (segno < GET_SEG_FROM_SEC(sbi, hint + 1))
2325 			goto got_it;
2326 	}
2327 find_other_zone:
2328 	secno = find_next_zero_bit(free_i->free_secmap, MAIN_SECS(sbi), hint);
2329 	if (secno >= MAIN_SECS(sbi)) {
2330 		if (dir == ALLOC_RIGHT) {
2331 			secno = find_next_zero_bit(free_i->free_secmap,
2332 							MAIN_SECS(sbi), 0);
2333 			f2fs_bug_on(sbi, secno >= MAIN_SECS(sbi));
2334 		} else {
2335 			go_left = 1;
2336 			left_start = hint - 1;
2337 		}
2338 	}
2339 	if (go_left == 0)
2340 		goto skip_left;
2341 
2342 	while (test_bit(left_start, free_i->free_secmap)) {
2343 		if (left_start > 0) {
2344 			left_start--;
2345 			continue;
2346 		}
2347 		left_start = find_next_zero_bit(free_i->free_secmap,
2348 							MAIN_SECS(sbi), 0);
2349 		f2fs_bug_on(sbi, left_start >= MAIN_SECS(sbi));
2350 		break;
2351 	}
2352 	secno = left_start;
2353 skip_left:
2354 	segno = GET_SEG_FROM_SEC(sbi, secno);
2355 	zoneno = GET_ZONE_FROM_SEC(sbi, secno);
2356 
2357 	/* give up on finding another zone */
2358 	if (!init)
2359 		goto got_it;
2360 	if (sbi->secs_per_zone == 1)
2361 		goto got_it;
2362 	if (zoneno == old_zoneno)
2363 		goto got_it;
2364 	if (dir == ALLOC_LEFT) {
2365 		if (!go_left && zoneno + 1 >= total_zones)
2366 			goto got_it;
2367 		if (go_left && zoneno == 0)
2368 			goto got_it;
2369 	}
2370 	for (i = 0; i < NR_CURSEG_TYPE; i++)
2371 		if (CURSEG_I(sbi, i)->zone == zoneno)
2372 			break;
2373 
2374 	if (i < NR_CURSEG_TYPE) {
2375 		/* zone is in user, try another */
2376 		if (go_left)
2377 			hint = zoneno * sbi->secs_per_zone - 1;
2378 		else if (zoneno + 1 >= total_zones)
2379 			hint = 0;
2380 		else
2381 			hint = (zoneno + 1) * sbi->secs_per_zone;
2382 		init = false;
2383 		goto find_other_zone;
2384 	}
2385 got_it:
2386 	/* set it as dirty segment in free segmap */
2387 	f2fs_bug_on(sbi, test_bit(segno, free_i->free_segmap));
2388 	__set_inuse(sbi, segno);
2389 	*newseg = segno;
2390 	spin_unlock(&free_i->segmap_lock);
2391 }
2392 
2393 static void reset_curseg(struct f2fs_sb_info *sbi, int type, int modified)
2394 {
2395 	struct curseg_info *curseg = CURSEG_I(sbi, type);
2396 	struct summary_footer *sum_footer;
2397 
2398 	curseg->segno = curseg->next_segno;
2399 	curseg->zone = GET_ZONE_FROM_SEG(sbi, curseg->segno);
2400 	curseg->next_blkoff = 0;
2401 	curseg->next_segno = NULL_SEGNO;
2402 
2403 	sum_footer = &(curseg->sum_blk->footer);
2404 	memset(sum_footer, 0, sizeof(struct summary_footer));
2405 	if (IS_DATASEG(type))
2406 		SET_SUM_TYPE(sum_footer, SUM_TYPE_DATA);
2407 	if (IS_NODESEG(type))
2408 		SET_SUM_TYPE(sum_footer, SUM_TYPE_NODE);
2409 	__set_sit_entry_type(sbi, type, curseg->segno, modified);
2410 }
2411 
2412 static unsigned int __get_next_segno(struct f2fs_sb_info *sbi, int type)
2413 {
2414 	/* if segs_per_sec is large than 1, we need to keep original policy. */
2415 	if (sbi->segs_per_sec != 1)
2416 		return CURSEG_I(sbi, type)->segno;
2417 
2418 	if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED)))
2419 		return 0;
2420 
2421 	if (test_opt(sbi, NOHEAP) &&
2422 		(type == CURSEG_HOT_DATA || IS_NODESEG(type)))
2423 		return 0;
2424 
2425 	if (SIT_I(sbi)->last_victim[ALLOC_NEXT])
2426 		return SIT_I(sbi)->last_victim[ALLOC_NEXT];
2427 
2428 	/* find segments from 0 to reuse freed segments */
2429 	if (F2FS_OPTION(sbi).alloc_mode == ALLOC_MODE_REUSE)
2430 		return 0;
2431 
2432 	return CURSEG_I(sbi, type)->segno;
2433 }
2434 
2435 /*
2436  * Allocate a current working segment.
2437  * This function always allocates a free segment in LFS manner.
2438  */
2439 static void new_curseg(struct f2fs_sb_info *sbi, int type, bool new_sec)
2440 {
2441 	struct curseg_info *curseg = CURSEG_I(sbi, type);
2442 	unsigned int segno = curseg->segno;
2443 	int dir = ALLOC_LEFT;
2444 
2445 	write_sum_page(sbi, curseg->sum_blk,
2446 				GET_SUM_BLOCK(sbi, segno));
2447 	if (type == CURSEG_WARM_DATA || type == CURSEG_COLD_DATA)
2448 		dir = ALLOC_RIGHT;
2449 
2450 	if (test_opt(sbi, NOHEAP))
2451 		dir = ALLOC_RIGHT;
2452 
2453 	segno = __get_next_segno(sbi, type);
2454 	get_new_segment(sbi, &segno, new_sec, dir);
2455 	curseg->next_segno = segno;
2456 	reset_curseg(sbi, type, 1);
2457 	curseg->alloc_type = LFS;
2458 }
2459 
2460 static void __next_free_blkoff(struct f2fs_sb_info *sbi,
2461 			struct curseg_info *seg, block_t start)
2462 {
2463 	struct seg_entry *se = get_seg_entry(sbi, seg->segno);
2464 	int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
2465 	unsigned long *target_map = SIT_I(sbi)->tmp_map;
2466 	unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
2467 	unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
2468 	int i, pos;
2469 
2470 	for (i = 0; i < entries; i++)
2471 		target_map[i] = ckpt_map[i] | cur_map[i];
2472 
2473 	pos = __find_rev_next_zero_bit(target_map, sbi->blocks_per_seg, start);
2474 
2475 	seg->next_blkoff = pos;
2476 }
2477 
2478 /*
2479  * If a segment is written by LFS manner, next block offset is just obtained
2480  * by increasing the current block offset. However, if a segment is written by
2481  * SSR manner, next block offset obtained by calling __next_free_blkoff
2482  */
2483 static void __refresh_next_blkoff(struct f2fs_sb_info *sbi,
2484 				struct curseg_info *seg)
2485 {
2486 	if (seg->alloc_type == SSR)
2487 		__next_free_blkoff(sbi, seg, seg->next_blkoff + 1);
2488 	else
2489 		seg->next_blkoff++;
2490 }
2491 
2492 /*
2493  * This function always allocates a used segment(from dirty seglist) by SSR
2494  * manner, so it should recover the existing segment information of valid blocks
2495  */
2496 static void change_curseg(struct f2fs_sb_info *sbi, int type)
2497 {
2498 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
2499 	struct curseg_info *curseg = CURSEG_I(sbi, type);
2500 	unsigned int new_segno = curseg->next_segno;
2501 	struct f2fs_summary_block *sum_node;
2502 	struct page *sum_page;
2503 
2504 	write_sum_page(sbi, curseg->sum_blk,
2505 				GET_SUM_BLOCK(sbi, curseg->segno));
2506 	__set_test_and_inuse(sbi, new_segno);
2507 
2508 	mutex_lock(&dirty_i->seglist_lock);
2509 	__remove_dirty_segment(sbi, new_segno, PRE);
2510 	__remove_dirty_segment(sbi, new_segno, DIRTY);
2511 	mutex_unlock(&dirty_i->seglist_lock);
2512 
2513 	reset_curseg(sbi, type, 1);
2514 	curseg->alloc_type = SSR;
2515 	__next_free_blkoff(sbi, curseg, 0);
2516 
2517 	sum_page = f2fs_get_sum_page(sbi, new_segno);
2518 	f2fs_bug_on(sbi, IS_ERR(sum_page));
2519 	sum_node = (struct f2fs_summary_block *)page_address(sum_page);
2520 	memcpy(curseg->sum_blk, sum_node, SUM_ENTRY_SIZE);
2521 	f2fs_put_page(sum_page, 1);
2522 }
2523 
2524 static int get_ssr_segment(struct f2fs_sb_info *sbi, int type)
2525 {
2526 	struct curseg_info *curseg = CURSEG_I(sbi, type);
2527 	const struct victim_selection *v_ops = DIRTY_I(sbi)->v_ops;
2528 	unsigned segno = NULL_SEGNO;
2529 	int i, cnt;
2530 	bool reversed = false;
2531 
2532 	/* f2fs_need_SSR() already forces to do this */
2533 	if (v_ops->get_victim(sbi, &segno, BG_GC, type, SSR)) {
2534 		curseg->next_segno = segno;
2535 		return 1;
2536 	}
2537 
2538 	/* For node segments, let's do SSR more intensively */
2539 	if (IS_NODESEG(type)) {
2540 		if (type >= CURSEG_WARM_NODE) {
2541 			reversed = true;
2542 			i = CURSEG_COLD_NODE;
2543 		} else {
2544 			i = CURSEG_HOT_NODE;
2545 		}
2546 		cnt = NR_CURSEG_NODE_TYPE;
2547 	} else {
2548 		if (type >= CURSEG_WARM_DATA) {
2549 			reversed = true;
2550 			i = CURSEG_COLD_DATA;
2551 		} else {
2552 			i = CURSEG_HOT_DATA;
2553 		}
2554 		cnt = NR_CURSEG_DATA_TYPE;
2555 	}
2556 
2557 	for (; cnt-- > 0; reversed ? i-- : i++) {
2558 		if (i == type)
2559 			continue;
2560 		if (v_ops->get_victim(sbi, &segno, BG_GC, i, SSR)) {
2561 			curseg->next_segno = segno;
2562 			return 1;
2563 		}
2564 	}
2565 
2566 	/* find valid_blocks=0 in dirty list */
2567 	if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) {
2568 		segno = get_free_segment(sbi);
2569 		if (segno != NULL_SEGNO) {
2570 			curseg->next_segno = segno;
2571 			return 1;
2572 		}
2573 	}
2574 	return 0;
2575 }
2576 
2577 /*
2578  * flush out current segment and replace it with new segment
2579  * This function should be returned with success, otherwise BUG
2580  */
2581 static void allocate_segment_by_default(struct f2fs_sb_info *sbi,
2582 						int type, bool force)
2583 {
2584 	struct curseg_info *curseg = CURSEG_I(sbi, type);
2585 
2586 	if (force)
2587 		new_curseg(sbi, type, true);
2588 	else if (!is_set_ckpt_flags(sbi, CP_CRC_RECOVERY_FLAG) &&
2589 					type == CURSEG_WARM_NODE)
2590 		new_curseg(sbi, type, false);
2591 	else if (curseg->alloc_type == LFS && is_next_segment_free(sbi, type) &&
2592 			likely(!is_sbi_flag_set(sbi, SBI_CP_DISABLED)))
2593 		new_curseg(sbi, type, false);
2594 	else if (f2fs_need_SSR(sbi) && get_ssr_segment(sbi, type))
2595 		change_curseg(sbi, type);
2596 	else
2597 		new_curseg(sbi, type, false);
2598 
2599 	stat_inc_seg_type(sbi, curseg);
2600 }
2601 
2602 void f2fs_allocate_new_segments(struct f2fs_sb_info *sbi)
2603 {
2604 	struct curseg_info *curseg;
2605 	unsigned int old_segno;
2606 	int i;
2607 
2608 	down_write(&SIT_I(sbi)->sentry_lock);
2609 
2610 	for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
2611 		curseg = CURSEG_I(sbi, i);
2612 		old_segno = curseg->segno;
2613 		SIT_I(sbi)->s_ops->allocate_segment(sbi, i, true);
2614 		locate_dirty_segment(sbi, old_segno);
2615 	}
2616 
2617 	up_write(&SIT_I(sbi)->sentry_lock);
2618 }
2619 
2620 static const struct segment_allocation default_salloc_ops = {
2621 	.allocate_segment = allocate_segment_by_default,
2622 };
2623 
2624 bool f2fs_exist_trim_candidates(struct f2fs_sb_info *sbi,
2625 						struct cp_control *cpc)
2626 {
2627 	__u64 trim_start = cpc->trim_start;
2628 	bool has_candidate = false;
2629 
2630 	down_write(&SIT_I(sbi)->sentry_lock);
2631 	for (; cpc->trim_start <= cpc->trim_end; cpc->trim_start++) {
2632 		if (add_discard_addrs(sbi, cpc, true)) {
2633 			has_candidate = true;
2634 			break;
2635 		}
2636 	}
2637 	up_write(&SIT_I(sbi)->sentry_lock);
2638 
2639 	cpc->trim_start = trim_start;
2640 	return has_candidate;
2641 }
2642 
2643 static unsigned int __issue_discard_cmd_range(struct f2fs_sb_info *sbi,
2644 					struct discard_policy *dpolicy,
2645 					unsigned int start, unsigned int end)
2646 {
2647 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
2648 	struct discard_cmd *prev_dc = NULL, *next_dc = NULL;
2649 	struct rb_node **insert_p = NULL, *insert_parent = NULL;
2650 	struct discard_cmd *dc;
2651 	struct blk_plug plug;
2652 	int issued;
2653 	unsigned int trimmed = 0;
2654 
2655 next:
2656 	issued = 0;
2657 
2658 	mutex_lock(&dcc->cmd_lock);
2659 	if (unlikely(dcc->rbtree_check))
2660 		f2fs_bug_on(sbi, !f2fs_check_rb_tree_consistence(sbi,
2661 								&dcc->root));
2662 
2663 	dc = (struct discard_cmd *)f2fs_lookup_rb_tree_ret(&dcc->root,
2664 					NULL, start,
2665 					(struct rb_entry **)&prev_dc,
2666 					(struct rb_entry **)&next_dc,
2667 					&insert_p, &insert_parent, true, NULL);
2668 	if (!dc)
2669 		dc = next_dc;
2670 
2671 	blk_start_plug(&plug);
2672 
2673 	while (dc && dc->lstart <= end) {
2674 		struct rb_node *node;
2675 		int err = 0;
2676 
2677 		if (dc->len < dpolicy->granularity)
2678 			goto skip;
2679 
2680 		if (dc->state != D_PREP) {
2681 			list_move_tail(&dc->list, &dcc->fstrim_list);
2682 			goto skip;
2683 		}
2684 
2685 		err = __submit_discard_cmd(sbi, dpolicy, dc, &issued);
2686 
2687 		if (issued >= dpolicy->max_requests) {
2688 			start = dc->lstart + dc->len;
2689 
2690 			if (err)
2691 				__remove_discard_cmd(sbi, dc);
2692 
2693 			blk_finish_plug(&plug);
2694 			mutex_unlock(&dcc->cmd_lock);
2695 			trimmed += __wait_all_discard_cmd(sbi, NULL);
2696 			congestion_wait(BLK_RW_ASYNC, HZ/50);
2697 			goto next;
2698 		}
2699 skip:
2700 		node = rb_next(&dc->rb_node);
2701 		if (err)
2702 			__remove_discard_cmd(sbi, dc);
2703 		dc = rb_entry_safe(node, struct discard_cmd, rb_node);
2704 
2705 		if (fatal_signal_pending(current))
2706 			break;
2707 	}
2708 
2709 	blk_finish_plug(&plug);
2710 	mutex_unlock(&dcc->cmd_lock);
2711 
2712 	return trimmed;
2713 }
2714 
2715 int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range)
2716 {
2717 	__u64 start = F2FS_BYTES_TO_BLK(range->start);
2718 	__u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1;
2719 	unsigned int start_segno, end_segno;
2720 	block_t start_block, end_block;
2721 	struct cp_control cpc;
2722 	struct discard_policy dpolicy;
2723 	unsigned long long trimmed = 0;
2724 	int err = 0;
2725 	bool need_align = test_opt(sbi, LFS) && sbi->segs_per_sec > 1;
2726 
2727 	if (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize)
2728 		return -EINVAL;
2729 
2730 	if (end < MAIN_BLKADDR(sbi))
2731 		goto out;
2732 
2733 	if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) {
2734 		f2fs_msg(sbi->sb, KERN_WARNING,
2735 			"Found FS corruption, run fsck to fix.");
2736 		return -EIO;
2737 	}
2738 
2739 	/* start/end segment number in main_area */
2740 	start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start);
2741 	end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 :
2742 						GET_SEGNO(sbi, end);
2743 	if (need_align) {
2744 		start_segno = rounddown(start_segno, sbi->segs_per_sec);
2745 		end_segno = roundup(end_segno + 1, sbi->segs_per_sec) - 1;
2746 	}
2747 
2748 	cpc.reason = CP_DISCARD;
2749 	cpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen));
2750 	cpc.trim_start = start_segno;
2751 	cpc.trim_end = end_segno;
2752 
2753 	if (sbi->discard_blks == 0)
2754 		goto out;
2755 
2756 	mutex_lock(&sbi->gc_mutex);
2757 	err = f2fs_write_checkpoint(sbi, &cpc);
2758 	mutex_unlock(&sbi->gc_mutex);
2759 	if (err)
2760 		goto out;
2761 
2762 	/*
2763 	 * We filed discard candidates, but actually we don't need to wait for
2764 	 * all of them, since they'll be issued in idle time along with runtime
2765 	 * discard option. User configuration looks like using runtime discard
2766 	 * or periodic fstrim instead of it.
2767 	 */
2768 	if (f2fs_realtime_discard_enable(sbi))
2769 		goto out;
2770 
2771 	start_block = START_BLOCK(sbi, start_segno);
2772 	end_block = START_BLOCK(sbi, end_segno + 1);
2773 
2774 	__init_discard_policy(sbi, &dpolicy, DPOLICY_FSTRIM, cpc.trim_minlen);
2775 	trimmed = __issue_discard_cmd_range(sbi, &dpolicy,
2776 					start_block, end_block);
2777 
2778 	trimmed += __wait_discard_cmd_range(sbi, &dpolicy,
2779 					start_block, end_block);
2780 out:
2781 	if (!err)
2782 		range->len = F2FS_BLK_TO_BYTES(trimmed);
2783 	return err;
2784 }
2785 
2786 static bool __has_curseg_space(struct f2fs_sb_info *sbi, int type)
2787 {
2788 	struct curseg_info *curseg = CURSEG_I(sbi, type);
2789 	if (curseg->next_blkoff < sbi->blocks_per_seg)
2790 		return true;
2791 	return false;
2792 }
2793 
2794 int f2fs_rw_hint_to_seg_type(enum rw_hint hint)
2795 {
2796 	switch (hint) {
2797 	case WRITE_LIFE_SHORT:
2798 		return CURSEG_HOT_DATA;
2799 	case WRITE_LIFE_EXTREME:
2800 		return CURSEG_COLD_DATA;
2801 	default:
2802 		return CURSEG_WARM_DATA;
2803 	}
2804 }
2805 
2806 /* This returns write hints for each segment type. This hints will be
2807  * passed down to block layer. There are mapping tables which depend on
2808  * the mount option 'whint_mode'.
2809  *
2810  * 1) whint_mode=off. F2FS only passes down WRITE_LIFE_NOT_SET.
2811  *
2812  * 2) whint_mode=user-based. F2FS tries to pass down hints given by users.
2813  *
2814  * User                  F2FS                     Block
2815  * ----                  ----                     -----
2816  *                       META                     WRITE_LIFE_NOT_SET
2817  *                       HOT_NODE                 "
2818  *                       WARM_NODE                "
2819  *                       COLD_NODE                "
2820  * ioctl(COLD)           COLD_DATA                WRITE_LIFE_EXTREME
2821  * extension list        "                        "
2822  *
2823  * -- buffered io
2824  * WRITE_LIFE_EXTREME    COLD_DATA                WRITE_LIFE_EXTREME
2825  * WRITE_LIFE_SHORT      HOT_DATA                 WRITE_LIFE_SHORT
2826  * WRITE_LIFE_NOT_SET    WARM_DATA                WRITE_LIFE_NOT_SET
2827  * WRITE_LIFE_NONE       "                        "
2828  * WRITE_LIFE_MEDIUM     "                        "
2829  * WRITE_LIFE_LONG       "                        "
2830  *
2831  * -- direct io
2832  * WRITE_LIFE_EXTREME    COLD_DATA                WRITE_LIFE_EXTREME
2833  * WRITE_LIFE_SHORT      HOT_DATA                 WRITE_LIFE_SHORT
2834  * WRITE_LIFE_NOT_SET    WARM_DATA                WRITE_LIFE_NOT_SET
2835  * WRITE_LIFE_NONE       "                        WRITE_LIFE_NONE
2836  * WRITE_LIFE_MEDIUM     "                        WRITE_LIFE_MEDIUM
2837  * WRITE_LIFE_LONG       "                        WRITE_LIFE_LONG
2838  *
2839  * 3) whint_mode=fs-based. F2FS passes down hints with its policy.
2840  *
2841  * User                  F2FS                     Block
2842  * ----                  ----                     -----
2843  *                       META                     WRITE_LIFE_MEDIUM;
2844  *                       HOT_NODE                 WRITE_LIFE_NOT_SET
2845  *                       WARM_NODE                "
2846  *                       COLD_NODE                WRITE_LIFE_NONE
2847  * ioctl(COLD)           COLD_DATA                WRITE_LIFE_EXTREME
2848  * extension list        "                        "
2849  *
2850  * -- buffered io
2851  * WRITE_LIFE_EXTREME    COLD_DATA                WRITE_LIFE_EXTREME
2852  * WRITE_LIFE_SHORT      HOT_DATA                 WRITE_LIFE_SHORT
2853  * WRITE_LIFE_NOT_SET    WARM_DATA                WRITE_LIFE_LONG
2854  * WRITE_LIFE_NONE       "                        "
2855  * WRITE_LIFE_MEDIUM     "                        "
2856  * WRITE_LIFE_LONG       "                        "
2857  *
2858  * -- direct io
2859  * WRITE_LIFE_EXTREME    COLD_DATA                WRITE_LIFE_EXTREME
2860  * WRITE_LIFE_SHORT      HOT_DATA                 WRITE_LIFE_SHORT
2861  * WRITE_LIFE_NOT_SET    WARM_DATA                WRITE_LIFE_NOT_SET
2862  * WRITE_LIFE_NONE       "                        WRITE_LIFE_NONE
2863  * WRITE_LIFE_MEDIUM     "                        WRITE_LIFE_MEDIUM
2864  * WRITE_LIFE_LONG       "                        WRITE_LIFE_LONG
2865  */
2866 
2867 enum rw_hint f2fs_io_type_to_rw_hint(struct f2fs_sb_info *sbi,
2868 				enum page_type type, enum temp_type temp)
2869 {
2870 	if (F2FS_OPTION(sbi).whint_mode == WHINT_MODE_USER) {
2871 		if (type == DATA) {
2872 			if (temp == WARM)
2873 				return WRITE_LIFE_NOT_SET;
2874 			else if (temp == HOT)
2875 				return WRITE_LIFE_SHORT;
2876 			else if (temp == COLD)
2877 				return WRITE_LIFE_EXTREME;
2878 		} else {
2879 			return WRITE_LIFE_NOT_SET;
2880 		}
2881 	} else if (F2FS_OPTION(sbi).whint_mode == WHINT_MODE_FS) {
2882 		if (type == DATA) {
2883 			if (temp == WARM)
2884 				return WRITE_LIFE_LONG;
2885 			else if (temp == HOT)
2886 				return WRITE_LIFE_SHORT;
2887 			else if (temp == COLD)
2888 				return WRITE_LIFE_EXTREME;
2889 		} else if (type == NODE) {
2890 			if (temp == WARM || temp == HOT)
2891 				return WRITE_LIFE_NOT_SET;
2892 			else if (temp == COLD)
2893 				return WRITE_LIFE_NONE;
2894 		} else if (type == META) {
2895 			return WRITE_LIFE_MEDIUM;
2896 		}
2897 	}
2898 	return WRITE_LIFE_NOT_SET;
2899 }
2900 
2901 static int __get_segment_type_2(struct f2fs_io_info *fio)
2902 {
2903 	if (fio->type == DATA)
2904 		return CURSEG_HOT_DATA;
2905 	else
2906 		return CURSEG_HOT_NODE;
2907 }
2908 
2909 static int __get_segment_type_4(struct f2fs_io_info *fio)
2910 {
2911 	if (fio->type == DATA) {
2912 		struct inode *inode = fio->page->mapping->host;
2913 
2914 		if (S_ISDIR(inode->i_mode))
2915 			return CURSEG_HOT_DATA;
2916 		else
2917 			return CURSEG_COLD_DATA;
2918 	} else {
2919 		if (IS_DNODE(fio->page) && is_cold_node(fio->page))
2920 			return CURSEG_WARM_NODE;
2921 		else
2922 			return CURSEG_COLD_NODE;
2923 	}
2924 }
2925 
2926 static int __get_segment_type_6(struct f2fs_io_info *fio)
2927 {
2928 	if (fio->type == DATA) {
2929 		struct inode *inode = fio->page->mapping->host;
2930 
2931 		if (is_cold_data(fio->page) || file_is_cold(inode))
2932 			return CURSEG_COLD_DATA;
2933 		if (file_is_hot(inode) ||
2934 				is_inode_flag_set(inode, FI_HOT_DATA) ||
2935 				f2fs_is_atomic_file(inode) ||
2936 				f2fs_is_volatile_file(inode))
2937 			return CURSEG_HOT_DATA;
2938 		return f2fs_rw_hint_to_seg_type(inode->i_write_hint);
2939 	} else {
2940 		if (IS_DNODE(fio->page))
2941 			return is_cold_node(fio->page) ? CURSEG_WARM_NODE :
2942 						CURSEG_HOT_NODE;
2943 		return CURSEG_COLD_NODE;
2944 	}
2945 }
2946 
2947 static int __get_segment_type(struct f2fs_io_info *fio)
2948 {
2949 	int type = 0;
2950 
2951 	switch (F2FS_OPTION(fio->sbi).active_logs) {
2952 	case 2:
2953 		type = __get_segment_type_2(fio);
2954 		break;
2955 	case 4:
2956 		type = __get_segment_type_4(fio);
2957 		break;
2958 	case 6:
2959 		type = __get_segment_type_6(fio);
2960 		break;
2961 	default:
2962 		f2fs_bug_on(fio->sbi, true);
2963 	}
2964 
2965 	if (IS_HOT(type))
2966 		fio->temp = HOT;
2967 	else if (IS_WARM(type))
2968 		fio->temp = WARM;
2969 	else
2970 		fio->temp = COLD;
2971 	return type;
2972 }
2973 
2974 void f2fs_allocate_data_block(struct f2fs_sb_info *sbi, struct page *page,
2975 		block_t old_blkaddr, block_t *new_blkaddr,
2976 		struct f2fs_summary *sum, int type,
2977 		struct f2fs_io_info *fio, bool add_list)
2978 {
2979 	struct sit_info *sit_i = SIT_I(sbi);
2980 	struct curseg_info *curseg = CURSEG_I(sbi, type);
2981 
2982 	down_read(&SM_I(sbi)->curseg_lock);
2983 
2984 	mutex_lock(&curseg->curseg_mutex);
2985 	down_write(&sit_i->sentry_lock);
2986 
2987 	*new_blkaddr = NEXT_FREE_BLKADDR(sbi, curseg);
2988 
2989 	f2fs_wait_discard_bio(sbi, *new_blkaddr);
2990 
2991 	/*
2992 	 * __add_sum_entry should be resided under the curseg_mutex
2993 	 * because, this function updates a summary entry in the
2994 	 * current summary block.
2995 	 */
2996 	__add_sum_entry(sbi, type, sum);
2997 
2998 	__refresh_next_blkoff(sbi, curseg);
2999 
3000 	stat_inc_block_count(sbi, curseg);
3001 
3002 	/*
3003 	 * SIT information should be updated before segment allocation,
3004 	 * since SSR needs latest valid block information.
3005 	 */
3006 	update_sit_entry(sbi, *new_blkaddr, 1);
3007 	if (GET_SEGNO(sbi, old_blkaddr) != NULL_SEGNO)
3008 		update_sit_entry(sbi, old_blkaddr, -1);
3009 
3010 	if (!__has_curseg_space(sbi, type))
3011 		sit_i->s_ops->allocate_segment(sbi, type, false);
3012 
3013 	/*
3014 	 * segment dirty status should be updated after segment allocation,
3015 	 * so we just need to update status only one time after previous
3016 	 * segment being closed.
3017 	 */
3018 	locate_dirty_segment(sbi, GET_SEGNO(sbi, old_blkaddr));
3019 	locate_dirty_segment(sbi, GET_SEGNO(sbi, *new_blkaddr));
3020 
3021 	up_write(&sit_i->sentry_lock);
3022 
3023 	if (page && IS_NODESEG(type)) {
3024 		fill_node_footer_blkaddr(page, NEXT_FREE_BLKADDR(sbi, curseg));
3025 
3026 		f2fs_inode_chksum_set(sbi, page);
3027 	}
3028 
3029 	if (add_list) {
3030 		struct f2fs_bio_info *io;
3031 
3032 		INIT_LIST_HEAD(&fio->list);
3033 		fio->in_list = true;
3034 		fio->retry = false;
3035 		io = sbi->write_io[fio->type] + fio->temp;
3036 		spin_lock(&io->io_lock);
3037 		list_add_tail(&fio->list, &io->io_list);
3038 		spin_unlock(&io->io_lock);
3039 	}
3040 
3041 	mutex_unlock(&curseg->curseg_mutex);
3042 
3043 	up_read(&SM_I(sbi)->curseg_lock);
3044 }
3045 
3046 static void update_device_state(struct f2fs_io_info *fio)
3047 {
3048 	struct f2fs_sb_info *sbi = fio->sbi;
3049 	unsigned int devidx;
3050 
3051 	if (!sbi->s_ndevs)
3052 		return;
3053 
3054 	devidx = f2fs_target_device_index(sbi, fio->new_blkaddr);
3055 
3056 	/* update device state for fsync */
3057 	f2fs_set_dirty_device(sbi, fio->ino, devidx, FLUSH_INO);
3058 
3059 	/* update device state for checkpoint */
3060 	if (!f2fs_test_bit(devidx, (char *)&sbi->dirty_device)) {
3061 		spin_lock(&sbi->dev_lock);
3062 		f2fs_set_bit(devidx, (char *)&sbi->dirty_device);
3063 		spin_unlock(&sbi->dev_lock);
3064 	}
3065 }
3066 
3067 static void do_write_page(struct f2fs_summary *sum, struct f2fs_io_info *fio)
3068 {
3069 	int type = __get_segment_type(fio);
3070 	bool keep_order = (test_opt(fio->sbi, LFS) && type == CURSEG_COLD_DATA);
3071 
3072 	if (keep_order)
3073 		down_read(&fio->sbi->io_order_lock);
3074 reallocate:
3075 	f2fs_allocate_data_block(fio->sbi, fio->page, fio->old_blkaddr,
3076 			&fio->new_blkaddr, sum, type, fio, true);
3077 	if (GET_SEGNO(fio->sbi, fio->old_blkaddr) != NULL_SEGNO)
3078 		invalidate_mapping_pages(META_MAPPING(fio->sbi),
3079 					fio->old_blkaddr, fio->old_blkaddr);
3080 
3081 	/* writeout dirty page into bdev */
3082 	f2fs_submit_page_write(fio);
3083 	if (fio->retry) {
3084 		fio->old_blkaddr = fio->new_blkaddr;
3085 		goto reallocate;
3086 	}
3087 
3088 	update_device_state(fio);
3089 
3090 	if (keep_order)
3091 		up_read(&fio->sbi->io_order_lock);
3092 }
3093 
3094 void f2fs_do_write_meta_page(struct f2fs_sb_info *sbi, struct page *page,
3095 					enum iostat_type io_type)
3096 {
3097 	struct f2fs_io_info fio = {
3098 		.sbi = sbi,
3099 		.type = META,
3100 		.temp = HOT,
3101 		.op = REQ_OP_WRITE,
3102 		.op_flags = REQ_SYNC | REQ_META | REQ_PRIO,
3103 		.old_blkaddr = page->index,
3104 		.new_blkaddr = page->index,
3105 		.page = page,
3106 		.encrypted_page = NULL,
3107 		.in_list = false,
3108 	};
3109 
3110 	if (unlikely(page->index >= MAIN_BLKADDR(sbi)))
3111 		fio.op_flags &= ~REQ_META;
3112 
3113 	set_page_writeback(page);
3114 	ClearPageError(page);
3115 	f2fs_submit_page_write(&fio);
3116 
3117 	stat_inc_meta_count(sbi, page->index);
3118 	f2fs_update_iostat(sbi, io_type, F2FS_BLKSIZE);
3119 }
3120 
3121 void f2fs_do_write_node_page(unsigned int nid, struct f2fs_io_info *fio)
3122 {
3123 	struct f2fs_summary sum;
3124 
3125 	set_summary(&sum, nid, 0, 0);
3126 	do_write_page(&sum, fio);
3127 
3128 	f2fs_update_iostat(fio->sbi, fio->io_type, F2FS_BLKSIZE);
3129 }
3130 
3131 void f2fs_outplace_write_data(struct dnode_of_data *dn,
3132 					struct f2fs_io_info *fio)
3133 {
3134 	struct f2fs_sb_info *sbi = fio->sbi;
3135 	struct f2fs_summary sum;
3136 
3137 	f2fs_bug_on(sbi, dn->data_blkaddr == NULL_ADDR);
3138 	set_summary(&sum, dn->nid, dn->ofs_in_node, fio->version);
3139 	do_write_page(&sum, fio);
3140 	f2fs_update_data_blkaddr(dn, fio->new_blkaddr);
3141 
3142 	f2fs_update_iostat(sbi, fio->io_type, F2FS_BLKSIZE);
3143 }
3144 
3145 int f2fs_inplace_write_data(struct f2fs_io_info *fio)
3146 {
3147 	int err;
3148 	struct f2fs_sb_info *sbi = fio->sbi;
3149 
3150 	fio->new_blkaddr = fio->old_blkaddr;
3151 	/* i/o temperature is needed for passing down write hints */
3152 	__get_segment_type(fio);
3153 
3154 	f2fs_bug_on(sbi, !IS_DATASEG(get_seg_entry(sbi,
3155 			GET_SEGNO(sbi, fio->new_blkaddr))->type));
3156 
3157 	stat_inc_inplace_blocks(fio->sbi);
3158 
3159 	err = f2fs_submit_page_bio(fio);
3160 	if (!err)
3161 		update_device_state(fio);
3162 
3163 	f2fs_update_iostat(fio->sbi, fio->io_type, F2FS_BLKSIZE);
3164 
3165 	return err;
3166 }
3167 
3168 static inline int __f2fs_get_curseg(struct f2fs_sb_info *sbi,
3169 						unsigned int segno)
3170 {
3171 	int i;
3172 
3173 	for (i = CURSEG_HOT_DATA; i < NO_CHECK_TYPE; i++) {
3174 		if (CURSEG_I(sbi, i)->segno == segno)
3175 			break;
3176 	}
3177 	return i;
3178 }
3179 
3180 void f2fs_do_replace_block(struct f2fs_sb_info *sbi, struct f2fs_summary *sum,
3181 				block_t old_blkaddr, block_t new_blkaddr,
3182 				bool recover_curseg, bool recover_newaddr)
3183 {
3184 	struct sit_info *sit_i = SIT_I(sbi);
3185 	struct curseg_info *curseg;
3186 	unsigned int segno, old_cursegno;
3187 	struct seg_entry *se;
3188 	int type;
3189 	unsigned short old_blkoff;
3190 
3191 	segno = GET_SEGNO(sbi, new_blkaddr);
3192 	se = get_seg_entry(sbi, segno);
3193 	type = se->type;
3194 
3195 	down_write(&SM_I(sbi)->curseg_lock);
3196 
3197 	if (!recover_curseg) {
3198 		/* for recovery flow */
3199 		if (se->valid_blocks == 0 && !IS_CURSEG(sbi, segno)) {
3200 			if (old_blkaddr == NULL_ADDR)
3201 				type = CURSEG_COLD_DATA;
3202 			else
3203 				type = CURSEG_WARM_DATA;
3204 		}
3205 	} else {
3206 		if (IS_CURSEG(sbi, segno)) {
3207 			/* se->type is volatile as SSR allocation */
3208 			type = __f2fs_get_curseg(sbi, segno);
3209 			f2fs_bug_on(sbi, type == NO_CHECK_TYPE);
3210 		} else {
3211 			type = CURSEG_WARM_DATA;
3212 		}
3213 	}
3214 
3215 	f2fs_bug_on(sbi, !IS_DATASEG(type));
3216 	curseg = CURSEG_I(sbi, type);
3217 
3218 	mutex_lock(&curseg->curseg_mutex);
3219 	down_write(&sit_i->sentry_lock);
3220 
3221 	old_cursegno = curseg->segno;
3222 	old_blkoff = curseg->next_blkoff;
3223 
3224 	/* change the current segment */
3225 	if (segno != curseg->segno) {
3226 		curseg->next_segno = segno;
3227 		change_curseg(sbi, type);
3228 	}
3229 
3230 	curseg->next_blkoff = GET_BLKOFF_FROM_SEG0(sbi, new_blkaddr);
3231 	__add_sum_entry(sbi, type, sum);
3232 
3233 	if (!recover_curseg || recover_newaddr)
3234 		update_sit_entry(sbi, new_blkaddr, 1);
3235 	if (GET_SEGNO(sbi, old_blkaddr) != NULL_SEGNO) {
3236 		invalidate_mapping_pages(META_MAPPING(sbi),
3237 					old_blkaddr, old_blkaddr);
3238 		update_sit_entry(sbi, old_blkaddr, -1);
3239 	}
3240 
3241 	locate_dirty_segment(sbi, GET_SEGNO(sbi, old_blkaddr));
3242 	locate_dirty_segment(sbi, GET_SEGNO(sbi, new_blkaddr));
3243 
3244 	locate_dirty_segment(sbi, old_cursegno);
3245 
3246 	if (recover_curseg) {
3247 		if (old_cursegno != curseg->segno) {
3248 			curseg->next_segno = old_cursegno;
3249 			change_curseg(sbi, type);
3250 		}
3251 		curseg->next_blkoff = old_blkoff;
3252 	}
3253 
3254 	up_write(&sit_i->sentry_lock);
3255 	mutex_unlock(&curseg->curseg_mutex);
3256 	up_write(&SM_I(sbi)->curseg_lock);
3257 }
3258 
3259 void f2fs_replace_block(struct f2fs_sb_info *sbi, struct dnode_of_data *dn,
3260 				block_t old_addr, block_t new_addr,
3261 				unsigned char version, bool recover_curseg,
3262 				bool recover_newaddr)
3263 {
3264 	struct f2fs_summary sum;
3265 
3266 	set_summary(&sum, dn->nid, dn->ofs_in_node, version);
3267 
3268 	f2fs_do_replace_block(sbi, &sum, old_addr, new_addr,
3269 					recover_curseg, recover_newaddr);
3270 
3271 	f2fs_update_data_blkaddr(dn, new_addr);
3272 }
3273 
3274 void f2fs_wait_on_page_writeback(struct page *page,
3275 				enum page_type type, bool ordered)
3276 {
3277 	if (PageWriteback(page)) {
3278 		struct f2fs_sb_info *sbi = F2FS_P_SB(page);
3279 
3280 		f2fs_submit_merged_write_cond(sbi, NULL, page, 0, type);
3281 		if (ordered)
3282 			wait_on_page_writeback(page);
3283 		else
3284 			wait_for_stable_page(page);
3285 	}
3286 }
3287 
3288 void f2fs_wait_on_block_writeback(struct inode *inode, block_t blkaddr)
3289 {
3290 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3291 	struct page *cpage;
3292 
3293 	if (!f2fs_post_read_required(inode))
3294 		return;
3295 
3296 	if (!is_valid_data_blkaddr(sbi, blkaddr))
3297 		return;
3298 
3299 	cpage = find_lock_page(META_MAPPING(sbi), blkaddr);
3300 	if (cpage) {
3301 		f2fs_wait_on_page_writeback(cpage, DATA, true);
3302 		f2fs_put_page(cpage, 1);
3303 	}
3304 }
3305 
3306 void f2fs_wait_on_block_writeback_range(struct inode *inode, block_t blkaddr,
3307 								block_t len)
3308 {
3309 	block_t i;
3310 
3311 	for (i = 0; i < len; i++)
3312 		f2fs_wait_on_block_writeback(inode, blkaddr + i);
3313 }
3314 
3315 static int read_compacted_summaries(struct f2fs_sb_info *sbi)
3316 {
3317 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
3318 	struct curseg_info *seg_i;
3319 	unsigned char *kaddr;
3320 	struct page *page;
3321 	block_t start;
3322 	int i, j, offset;
3323 
3324 	start = start_sum_block(sbi);
3325 
3326 	page = f2fs_get_meta_page(sbi, start++);
3327 	if (IS_ERR(page))
3328 		return PTR_ERR(page);
3329 	kaddr = (unsigned char *)page_address(page);
3330 
3331 	/* Step 1: restore nat cache */
3332 	seg_i = CURSEG_I(sbi, CURSEG_HOT_DATA);
3333 	memcpy(seg_i->journal, kaddr, SUM_JOURNAL_SIZE);
3334 
3335 	/* Step 2: restore sit cache */
3336 	seg_i = CURSEG_I(sbi, CURSEG_COLD_DATA);
3337 	memcpy(seg_i->journal, kaddr + SUM_JOURNAL_SIZE, SUM_JOURNAL_SIZE);
3338 	offset = 2 * SUM_JOURNAL_SIZE;
3339 
3340 	/* Step 3: restore summary entries */
3341 	for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
3342 		unsigned short blk_off;
3343 		unsigned int segno;
3344 
3345 		seg_i = CURSEG_I(sbi, i);
3346 		segno = le32_to_cpu(ckpt->cur_data_segno[i]);
3347 		blk_off = le16_to_cpu(ckpt->cur_data_blkoff[i]);
3348 		seg_i->next_segno = segno;
3349 		reset_curseg(sbi, i, 0);
3350 		seg_i->alloc_type = ckpt->alloc_type[i];
3351 		seg_i->next_blkoff = blk_off;
3352 
3353 		if (seg_i->alloc_type == SSR)
3354 			blk_off = sbi->blocks_per_seg;
3355 
3356 		for (j = 0; j < blk_off; j++) {
3357 			struct f2fs_summary *s;
3358 			s = (struct f2fs_summary *)(kaddr + offset);
3359 			seg_i->sum_blk->entries[j] = *s;
3360 			offset += SUMMARY_SIZE;
3361 			if (offset + SUMMARY_SIZE <= PAGE_SIZE -
3362 						SUM_FOOTER_SIZE)
3363 				continue;
3364 
3365 			f2fs_put_page(page, 1);
3366 			page = NULL;
3367 
3368 			page = f2fs_get_meta_page(sbi, start++);
3369 			if (IS_ERR(page))
3370 				return PTR_ERR(page);
3371 			kaddr = (unsigned char *)page_address(page);
3372 			offset = 0;
3373 		}
3374 	}
3375 	f2fs_put_page(page, 1);
3376 	return 0;
3377 }
3378 
3379 static int read_normal_summaries(struct f2fs_sb_info *sbi, int type)
3380 {
3381 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
3382 	struct f2fs_summary_block *sum;
3383 	struct curseg_info *curseg;
3384 	struct page *new;
3385 	unsigned short blk_off;
3386 	unsigned int segno = 0;
3387 	block_t blk_addr = 0;
3388 	int err = 0;
3389 
3390 	/* get segment number and block addr */
3391 	if (IS_DATASEG(type)) {
3392 		segno = le32_to_cpu(ckpt->cur_data_segno[type]);
3393 		blk_off = le16_to_cpu(ckpt->cur_data_blkoff[type -
3394 							CURSEG_HOT_DATA]);
3395 		if (__exist_node_summaries(sbi))
3396 			blk_addr = sum_blk_addr(sbi, NR_CURSEG_TYPE, type);
3397 		else
3398 			blk_addr = sum_blk_addr(sbi, NR_CURSEG_DATA_TYPE, type);
3399 	} else {
3400 		segno = le32_to_cpu(ckpt->cur_node_segno[type -
3401 							CURSEG_HOT_NODE]);
3402 		blk_off = le16_to_cpu(ckpt->cur_node_blkoff[type -
3403 							CURSEG_HOT_NODE]);
3404 		if (__exist_node_summaries(sbi))
3405 			blk_addr = sum_blk_addr(sbi, NR_CURSEG_NODE_TYPE,
3406 							type - CURSEG_HOT_NODE);
3407 		else
3408 			blk_addr = GET_SUM_BLOCK(sbi, segno);
3409 	}
3410 
3411 	new = f2fs_get_meta_page(sbi, blk_addr);
3412 	if (IS_ERR(new))
3413 		return PTR_ERR(new);
3414 	sum = (struct f2fs_summary_block *)page_address(new);
3415 
3416 	if (IS_NODESEG(type)) {
3417 		if (__exist_node_summaries(sbi)) {
3418 			struct f2fs_summary *ns = &sum->entries[0];
3419 			int i;
3420 			for (i = 0; i < sbi->blocks_per_seg; i++, ns++) {
3421 				ns->version = 0;
3422 				ns->ofs_in_node = 0;
3423 			}
3424 		} else {
3425 			err = f2fs_restore_node_summary(sbi, segno, sum);
3426 			if (err)
3427 				goto out;
3428 		}
3429 	}
3430 
3431 	/* set uncompleted segment to curseg */
3432 	curseg = CURSEG_I(sbi, type);
3433 	mutex_lock(&curseg->curseg_mutex);
3434 
3435 	/* update journal info */
3436 	down_write(&curseg->journal_rwsem);
3437 	memcpy(curseg->journal, &sum->journal, SUM_JOURNAL_SIZE);
3438 	up_write(&curseg->journal_rwsem);
3439 
3440 	memcpy(curseg->sum_blk->entries, sum->entries, SUM_ENTRY_SIZE);
3441 	memcpy(&curseg->sum_blk->footer, &sum->footer, SUM_FOOTER_SIZE);
3442 	curseg->next_segno = segno;
3443 	reset_curseg(sbi, type, 0);
3444 	curseg->alloc_type = ckpt->alloc_type[type];
3445 	curseg->next_blkoff = blk_off;
3446 	mutex_unlock(&curseg->curseg_mutex);
3447 out:
3448 	f2fs_put_page(new, 1);
3449 	return err;
3450 }
3451 
3452 static int restore_curseg_summaries(struct f2fs_sb_info *sbi)
3453 {
3454 	struct f2fs_journal *sit_j = CURSEG_I(sbi, CURSEG_COLD_DATA)->journal;
3455 	struct f2fs_journal *nat_j = CURSEG_I(sbi, CURSEG_HOT_DATA)->journal;
3456 	int type = CURSEG_HOT_DATA;
3457 	int err;
3458 
3459 	if (is_set_ckpt_flags(sbi, CP_COMPACT_SUM_FLAG)) {
3460 		int npages = f2fs_npages_for_summary_flush(sbi, true);
3461 
3462 		if (npages >= 2)
3463 			f2fs_ra_meta_pages(sbi, start_sum_block(sbi), npages,
3464 							META_CP, true);
3465 
3466 		/* restore for compacted data summary */
3467 		err = read_compacted_summaries(sbi);
3468 		if (err)
3469 			return err;
3470 		type = CURSEG_HOT_NODE;
3471 	}
3472 
3473 	if (__exist_node_summaries(sbi))
3474 		f2fs_ra_meta_pages(sbi, sum_blk_addr(sbi, NR_CURSEG_TYPE, type),
3475 					NR_CURSEG_TYPE - type, META_CP, true);
3476 
3477 	for (; type <= CURSEG_COLD_NODE; type++) {
3478 		err = read_normal_summaries(sbi, type);
3479 		if (err)
3480 			return err;
3481 	}
3482 
3483 	/* sanity check for summary blocks */
3484 	if (nats_in_cursum(nat_j) > NAT_JOURNAL_ENTRIES ||
3485 			sits_in_cursum(sit_j) > SIT_JOURNAL_ENTRIES)
3486 		return -EINVAL;
3487 
3488 	return 0;
3489 }
3490 
3491 static void write_compacted_summaries(struct f2fs_sb_info *sbi, block_t blkaddr)
3492 {
3493 	struct page *page;
3494 	unsigned char *kaddr;
3495 	struct f2fs_summary *summary;
3496 	struct curseg_info *seg_i;
3497 	int written_size = 0;
3498 	int i, j;
3499 
3500 	page = f2fs_grab_meta_page(sbi, blkaddr++);
3501 	kaddr = (unsigned char *)page_address(page);
3502 	memset(kaddr, 0, PAGE_SIZE);
3503 
3504 	/* Step 1: write nat cache */
3505 	seg_i = CURSEG_I(sbi, CURSEG_HOT_DATA);
3506 	memcpy(kaddr, seg_i->journal, SUM_JOURNAL_SIZE);
3507 	written_size += SUM_JOURNAL_SIZE;
3508 
3509 	/* Step 2: write sit cache */
3510 	seg_i = CURSEG_I(sbi, CURSEG_COLD_DATA);
3511 	memcpy(kaddr + written_size, seg_i->journal, SUM_JOURNAL_SIZE);
3512 	written_size += SUM_JOURNAL_SIZE;
3513 
3514 	/* Step 3: write summary entries */
3515 	for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
3516 		unsigned short blkoff;
3517 		seg_i = CURSEG_I(sbi, i);
3518 		if (sbi->ckpt->alloc_type[i] == SSR)
3519 			blkoff = sbi->blocks_per_seg;
3520 		else
3521 			blkoff = curseg_blkoff(sbi, i);
3522 
3523 		for (j = 0; j < blkoff; j++) {
3524 			if (!page) {
3525 				page = f2fs_grab_meta_page(sbi, blkaddr++);
3526 				kaddr = (unsigned char *)page_address(page);
3527 				memset(kaddr, 0, PAGE_SIZE);
3528 				written_size = 0;
3529 			}
3530 			summary = (struct f2fs_summary *)(kaddr + written_size);
3531 			*summary = seg_i->sum_blk->entries[j];
3532 			written_size += SUMMARY_SIZE;
3533 
3534 			if (written_size + SUMMARY_SIZE <= PAGE_SIZE -
3535 							SUM_FOOTER_SIZE)
3536 				continue;
3537 
3538 			set_page_dirty(page);
3539 			f2fs_put_page(page, 1);
3540 			page = NULL;
3541 		}
3542 	}
3543 	if (page) {
3544 		set_page_dirty(page);
3545 		f2fs_put_page(page, 1);
3546 	}
3547 }
3548 
3549 static void write_normal_summaries(struct f2fs_sb_info *sbi,
3550 					block_t blkaddr, int type)
3551 {
3552 	int i, end;
3553 	if (IS_DATASEG(type))
3554 		end = type + NR_CURSEG_DATA_TYPE;
3555 	else
3556 		end = type + NR_CURSEG_NODE_TYPE;
3557 
3558 	for (i = type; i < end; i++)
3559 		write_current_sum_page(sbi, i, blkaddr + (i - type));
3560 }
3561 
3562 void f2fs_write_data_summaries(struct f2fs_sb_info *sbi, block_t start_blk)
3563 {
3564 	if (is_set_ckpt_flags(sbi, CP_COMPACT_SUM_FLAG))
3565 		write_compacted_summaries(sbi, start_blk);
3566 	else
3567 		write_normal_summaries(sbi, start_blk, CURSEG_HOT_DATA);
3568 }
3569 
3570 void f2fs_write_node_summaries(struct f2fs_sb_info *sbi, block_t start_blk)
3571 {
3572 	write_normal_summaries(sbi, start_blk, CURSEG_HOT_NODE);
3573 }
3574 
3575 int f2fs_lookup_journal_in_cursum(struct f2fs_journal *journal, int type,
3576 					unsigned int val, int alloc)
3577 {
3578 	int i;
3579 
3580 	if (type == NAT_JOURNAL) {
3581 		for (i = 0; i < nats_in_cursum(journal); i++) {
3582 			if (le32_to_cpu(nid_in_journal(journal, i)) == val)
3583 				return i;
3584 		}
3585 		if (alloc && __has_cursum_space(journal, 1, NAT_JOURNAL))
3586 			return update_nats_in_cursum(journal, 1);
3587 	} else if (type == SIT_JOURNAL) {
3588 		for (i = 0; i < sits_in_cursum(journal); i++)
3589 			if (le32_to_cpu(segno_in_journal(journal, i)) == val)
3590 				return i;
3591 		if (alloc && __has_cursum_space(journal, 1, SIT_JOURNAL))
3592 			return update_sits_in_cursum(journal, 1);
3593 	}
3594 	return -1;
3595 }
3596 
3597 static struct page *get_current_sit_page(struct f2fs_sb_info *sbi,
3598 					unsigned int segno)
3599 {
3600 	return f2fs_get_meta_page_nofail(sbi, current_sit_addr(sbi, segno));
3601 }
3602 
3603 static struct page *get_next_sit_page(struct f2fs_sb_info *sbi,
3604 					unsigned int start)
3605 {
3606 	struct sit_info *sit_i = SIT_I(sbi);
3607 	struct page *page;
3608 	pgoff_t src_off, dst_off;
3609 
3610 	src_off = current_sit_addr(sbi, start);
3611 	dst_off = next_sit_addr(sbi, src_off);
3612 
3613 	page = f2fs_grab_meta_page(sbi, dst_off);
3614 	seg_info_to_sit_page(sbi, page, start);
3615 
3616 	set_page_dirty(page);
3617 	set_to_next_sit(sit_i, start);
3618 
3619 	return page;
3620 }
3621 
3622 static struct sit_entry_set *grab_sit_entry_set(void)
3623 {
3624 	struct sit_entry_set *ses =
3625 			f2fs_kmem_cache_alloc(sit_entry_set_slab, GFP_NOFS);
3626 
3627 	ses->entry_cnt = 0;
3628 	INIT_LIST_HEAD(&ses->set_list);
3629 	return ses;
3630 }
3631 
3632 static void release_sit_entry_set(struct sit_entry_set *ses)
3633 {
3634 	list_del(&ses->set_list);
3635 	kmem_cache_free(sit_entry_set_slab, ses);
3636 }
3637 
3638 static void adjust_sit_entry_set(struct sit_entry_set *ses,
3639 						struct list_head *head)
3640 {
3641 	struct sit_entry_set *next = ses;
3642 
3643 	if (list_is_last(&ses->set_list, head))
3644 		return;
3645 
3646 	list_for_each_entry_continue(next, head, set_list)
3647 		if (ses->entry_cnt <= next->entry_cnt)
3648 			break;
3649 
3650 	list_move_tail(&ses->set_list, &next->set_list);
3651 }
3652 
3653 static void add_sit_entry(unsigned int segno, struct list_head *head)
3654 {
3655 	struct sit_entry_set *ses;
3656 	unsigned int start_segno = START_SEGNO(segno);
3657 
3658 	list_for_each_entry(ses, head, set_list) {
3659 		if (ses->start_segno == start_segno) {
3660 			ses->entry_cnt++;
3661 			adjust_sit_entry_set(ses, head);
3662 			return;
3663 		}
3664 	}
3665 
3666 	ses = grab_sit_entry_set();
3667 
3668 	ses->start_segno = start_segno;
3669 	ses->entry_cnt++;
3670 	list_add(&ses->set_list, head);
3671 }
3672 
3673 static void add_sits_in_set(struct f2fs_sb_info *sbi)
3674 {
3675 	struct f2fs_sm_info *sm_info = SM_I(sbi);
3676 	struct list_head *set_list = &sm_info->sit_entry_set;
3677 	unsigned long *bitmap = SIT_I(sbi)->dirty_sentries_bitmap;
3678 	unsigned int segno;
3679 
3680 	for_each_set_bit(segno, bitmap, MAIN_SEGS(sbi))
3681 		add_sit_entry(segno, set_list);
3682 }
3683 
3684 static void remove_sits_in_journal(struct f2fs_sb_info *sbi)
3685 {
3686 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
3687 	struct f2fs_journal *journal = curseg->journal;
3688 	int i;
3689 
3690 	down_write(&curseg->journal_rwsem);
3691 	for (i = 0; i < sits_in_cursum(journal); i++) {
3692 		unsigned int segno;
3693 		bool dirtied;
3694 
3695 		segno = le32_to_cpu(segno_in_journal(journal, i));
3696 		dirtied = __mark_sit_entry_dirty(sbi, segno);
3697 
3698 		if (!dirtied)
3699 			add_sit_entry(segno, &SM_I(sbi)->sit_entry_set);
3700 	}
3701 	update_sits_in_cursum(journal, -i);
3702 	up_write(&curseg->journal_rwsem);
3703 }
3704 
3705 /*
3706  * CP calls this function, which flushes SIT entries including sit_journal,
3707  * and moves prefree segs to free segs.
3708  */
3709 void f2fs_flush_sit_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc)
3710 {
3711 	struct sit_info *sit_i = SIT_I(sbi);
3712 	unsigned long *bitmap = sit_i->dirty_sentries_bitmap;
3713 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
3714 	struct f2fs_journal *journal = curseg->journal;
3715 	struct sit_entry_set *ses, *tmp;
3716 	struct list_head *head = &SM_I(sbi)->sit_entry_set;
3717 	bool to_journal = true;
3718 	struct seg_entry *se;
3719 
3720 	down_write(&sit_i->sentry_lock);
3721 
3722 	if (!sit_i->dirty_sentries)
3723 		goto out;
3724 
3725 	/*
3726 	 * add and account sit entries of dirty bitmap in sit entry
3727 	 * set temporarily
3728 	 */
3729 	add_sits_in_set(sbi);
3730 
3731 	/*
3732 	 * if there are no enough space in journal to store dirty sit
3733 	 * entries, remove all entries from journal and add and account
3734 	 * them in sit entry set.
3735 	 */
3736 	if (!__has_cursum_space(journal, sit_i->dirty_sentries, SIT_JOURNAL))
3737 		remove_sits_in_journal(sbi);
3738 
3739 	/*
3740 	 * there are two steps to flush sit entries:
3741 	 * #1, flush sit entries to journal in current cold data summary block.
3742 	 * #2, flush sit entries to sit page.
3743 	 */
3744 	list_for_each_entry_safe(ses, tmp, head, set_list) {
3745 		struct page *page = NULL;
3746 		struct f2fs_sit_block *raw_sit = NULL;
3747 		unsigned int start_segno = ses->start_segno;
3748 		unsigned int end = min(start_segno + SIT_ENTRY_PER_BLOCK,
3749 						(unsigned long)MAIN_SEGS(sbi));
3750 		unsigned int segno = start_segno;
3751 
3752 		if (to_journal &&
3753 			!__has_cursum_space(journal, ses->entry_cnt, SIT_JOURNAL))
3754 			to_journal = false;
3755 
3756 		if (to_journal) {
3757 			down_write(&curseg->journal_rwsem);
3758 		} else {
3759 			page = get_next_sit_page(sbi, start_segno);
3760 			raw_sit = page_address(page);
3761 		}
3762 
3763 		/* flush dirty sit entries in region of current sit set */
3764 		for_each_set_bit_from(segno, bitmap, end) {
3765 			int offset, sit_offset;
3766 
3767 			se = get_seg_entry(sbi, segno);
3768 #ifdef CONFIG_F2FS_CHECK_FS
3769 			if (memcmp(se->cur_valid_map, se->cur_valid_map_mir,
3770 						SIT_VBLOCK_MAP_SIZE))
3771 				f2fs_bug_on(sbi, 1);
3772 #endif
3773 
3774 			/* add discard candidates */
3775 			if (!(cpc->reason & CP_DISCARD)) {
3776 				cpc->trim_start = segno;
3777 				add_discard_addrs(sbi, cpc, false);
3778 			}
3779 
3780 			if (to_journal) {
3781 				offset = f2fs_lookup_journal_in_cursum(journal,
3782 							SIT_JOURNAL, segno, 1);
3783 				f2fs_bug_on(sbi, offset < 0);
3784 				segno_in_journal(journal, offset) =
3785 							cpu_to_le32(segno);
3786 				seg_info_to_raw_sit(se,
3787 					&sit_in_journal(journal, offset));
3788 				check_block_count(sbi, segno,
3789 					&sit_in_journal(journal, offset));
3790 			} else {
3791 				sit_offset = SIT_ENTRY_OFFSET(sit_i, segno);
3792 				seg_info_to_raw_sit(se,
3793 						&raw_sit->entries[sit_offset]);
3794 				check_block_count(sbi, segno,
3795 						&raw_sit->entries[sit_offset]);
3796 			}
3797 
3798 			__clear_bit(segno, bitmap);
3799 			sit_i->dirty_sentries--;
3800 			ses->entry_cnt--;
3801 		}
3802 
3803 		if (to_journal)
3804 			up_write(&curseg->journal_rwsem);
3805 		else
3806 			f2fs_put_page(page, 1);
3807 
3808 		f2fs_bug_on(sbi, ses->entry_cnt);
3809 		release_sit_entry_set(ses);
3810 	}
3811 
3812 	f2fs_bug_on(sbi, !list_empty(head));
3813 	f2fs_bug_on(sbi, sit_i->dirty_sentries);
3814 out:
3815 	if (cpc->reason & CP_DISCARD) {
3816 		__u64 trim_start = cpc->trim_start;
3817 
3818 		for (; cpc->trim_start <= cpc->trim_end; cpc->trim_start++)
3819 			add_discard_addrs(sbi, cpc, false);
3820 
3821 		cpc->trim_start = trim_start;
3822 	}
3823 	up_write(&sit_i->sentry_lock);
3824 
3825 	set_prefree_as_free_segments(sbi);
3826 }
3827 
3828 static int build_sit_info(struct f2fs_sb_info *sbi)
3829 {
3830 	struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
3831 	struct sit_info *sit_i;
3832 	unsigned int sit_segs, start;
3833 	char *src_bitmap;
3834 	unsigned int bitmap_size;
3835 
3836 	/* allocate memory for SIT information */
3837 	sit_i = f2fs_kzalloc(sbi, sizeof(struct sit_info), GFP_KERNEL);
3838 	if (!sit_i)
3839 		return -ENOMEM;
3840 
3841 	SM_I(sbi)->sit_info = sit_i;
3842 
3843 	sit_i->sentries =
3844 		f2fs_kvzalloc(sbi, array_size(sizeof(struct seg_entry),
3845 					      MAIN_SEGS(sbi)),
3846 			      GFP_KERNEL);
3847 	if (!sit_i->sentries)
3848 		return -ENOMEM;
3849 
3850 	bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
3851 	sit_i->dirty_sentries_bitmap = f2fs_kvzalloc(sbi, bitmap_size,
3852 								GFP_KERNEL);
3853 	if (!sit_i->dirty_sentries_bitmap)
3854 		return -ENOMEM;
3855 
3856 	for (start = 0; start < MAIN_SEGS(sbi); start++) {
3857 		sit_i->sentries[start].cur_valid_map
3858 			= f2fs_kzalloc(sbi, SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
3859 		sit_i->sentries[start].ckpt_valid_map
3860 			= f2fs_kzalloc(sbi, SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
3861 		if (!sit_i->sentries[start].cur_valid_map ||
3862 				!sit_i->sentries[start].ckpt_valid_map)
3863 			return -ENOMEM;
3864 
3865 #ifdef CONFIG_F2FS_CHECK_FS
3866 		sit_i->sentries[start].cur_valid_map_mir
3867 			= f2fs_kzalloc(sbi, SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
3868 		if (!sit_i->sentries[start].cur_valid_map_mir)
3869 			return -ENOMEM;
3870 #endif
3871 
3872 		sit_i->sentries[start].discard_map
3873 			= f2fs_kzalloc(sbi, SIT_VBLOCK_MAP_SIZE,
3874 							GFP_KERNEL);
3875 		if (!sit_i->sentries[start].discard_map)
3876 			return -ENOMEM;
3877 	}
3878 
3879 	sit_i->tmp_map = f2fs_kzalloc(sbi, SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
3880 	if (!sit_i->tmp_map)
3881 		return -ENOMEM;
3882 
3883 	if (sbi->segs_per_sec > 1) {
3884 		sit_i->sec_entries =
3885 			f2fs_kvzalloc(sbi, array_size(sizeof(struct sec_entry),
3886 						      MAIN_SECS(sbi)),
3887 				      GFP_KERNEL);
3888 		if (!sit_i->sec_entries)
3889 			return -ENOMEM;
3890 	}
3891 
3892 	/* get information related with SIT */
3893 	sit_segs = le32_to_cpu(raw_super->segment_count_sit) >> 1;
3894 
3895 	/* setup SIT bitmap from ckeckpoint pack */
3896 	bitmap_size = __bitmap_size(sbi, SIT_BITMAP);
3897 	src_bitmap = __bitmap_ptr(sbi, SIT_BITMAP);
3898 
3899 	sit_i->sit_bitmap = kmemdup(src_bitmap, bitmap_size, GFP_KERNEL);
3900 	if (!sit_i->sit_bitmap)
3901 		return -ENOMEM;
3902 
3903 #ifdef CONFIG_F2FS_CHECK_FS
3904 	sit_i->sit_bitmap_mir = kmemdup(src_bitmap, bitmap_size, GFP_KERNEL);
3905 	if (!sit_i->sit_bitmap_mir)
3906 		return -ENOMEM;
3907 #endif
3908 
3909 	/* init SIT information */
3910 	sit_i->s_ops = &default_salloc_ops;
3911 
3912 	sit_i->sit_base_addr = le32_to_cpu(raw_super->sit_blkaddr);
3913 	sit_i->sit_blocks = sit_segs << sbi->log_blocks_per_seg;
3914 	sit_i->written_valid_blocks = 0;
3915 	sit_i->bitmap_size = bitmap_size;
3916 	sit_i->dirty_sentries = 0;
3917 	sit_i->sents_per_block = SIT_ENTRY_PER_BLOCK;
3918 	sit_i->elapsed_time = le64_to_cpu(sbi->ckpt->elapsed_time);
3919 	sit_i->mounted_time = ktime_get_real_seconds();
3920 	init_rwsem(&sit_i->sentry_lock);
3921 	return 0;
3922 }
3923 
3924 static int build_free_segmap(struct f2fs_sb_info *sbi)
3925 {
3926 	struct free_segmap_info *free_i;
3927 	unsigned int bitmap_size, sec_bitmap_size;
3928 
3929 	/* allocate memory for free segmap information */
3930 	free_i = f2fs_kzalloc(sbi, sizeof(struct free_segmap_info), GFP_KERNEL);
3931 	if (!free_i)
3932 		return -ENOMEM;
3933 
3934 	SM_I(sbi)->free_info = free_i;
3935 
3936 	bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
3937 	free_i->free_segmap = f2fs_kvmalloc(sbi, bitmap_size, GFP_KERNEL);
3938 	if (!free_i->free_segmap)
3939 		return -ENOMEM;
3940 
3941 	sec_bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
3942 	free_i->free_secmap = f2fs_kvmalloc(sbi, sec_bitmap_size, GFP_KERNEL);
3943 	if (!free_i->free_secmap)
3944 		return -ENOMEM;
3945 
3946 	/* set all segments as dirty temporarily */
3947 	memset(free_i->free_segmap, 0xff, bitmap_size);
3948 	memset(free_i->free_secmap, 0xff, sec_bitmap_size);
3949 
3950 	/* init free segmap information */
3951 	free_i->start_segno = GET_SEGNO_FROM_SEG0(sbi, MAIN_BLKADDR(sbi));
3952 	free_i->free_segments = 0;
3953 	free_i->free_sections = 0;
3954 	spin_lock_init(&free_i->segmap_lock);
3955 	return 0;
3956 }
3957 
3958 static int build_curseg(struct f2fs_sb_info *sbi)
3959 {
3960 	struct curseg_info *array;
3961 	int i;
3962 
3963 	array = f2fs_kzalloc(sbi, array_size(NR_CURSEG_TYPE, sizeof(*array)),
3964 			     GFP_KERNEL);
3965 	if (!array)
3966 		return -ENOMEM;
3967 
3968 	SM_I(sbi)->curseg_array = array;
3969 
3970 	for (i = 0; i < NR_CURSEG_TYPE; i++) {
3971 		mutex_init(&array[i].curseg_mutex);
3972 		array[i].sum_blk = f2fs_kzalloc(sbi, PAGE_SIZE, GFP_KERNEL);
3973 		if (!array[i].sum_blk)
3974 			return -ENOMEM;
3975 		init_rwsem(&array[i].journal_rwsem);
3976 		array[i].journal = f2fs_kzalloc(sbi,
3977 				sizeof(struct f2fs_journal), GFP_KERNEL);
3978 		if (!array[i].journal)
3979 			return -ENOMEM;
3980 		array[i].segno = NULL_SEGNO;
3981 		array[i].next_blkoff = 0;
3982 	}
3983 	return restore_curseg_summaries(sbi);
3984 }
3985 
3986 static int build_sit_entries(struct f2fs_sb_info *sbi)
3987 {
3988 	struct sit_info *sit_i = SIT_I(sbi);
3989 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
3990 	struct f2fs_journal *journal = curseg->journal;
3991 	struct seg_entry *se;
3992 	struct f2fs_sit_entry sit;
3993 	int sit_blk_cnt = SIT_BLK_CNT(sbi);
3994 	unsigned int i, start, end;
3995 	unsigned int readed, start_blk = 0;
3996 	int err = 0;
3997 	block_t total_node_blocks = 0;
3998 
3999 	do {
4000 		readed = f2fs_ra_meta_pages(sbi, start_blk, BIO_MAX_PAGES,
4001 							META_SIT, true);
4002 
4003 		start = start_blk * sit_i->sents_per_block;
4004 		end = (start_blk + readed) * sit_i->sents_per_block;
4005 
4006 		for (; start < end && start < MAIN_SEGS(sbi); start++) {
4007 			struct f2fs_sit_block *sit_blk;
4008 			struct page *page;
4009 
4010 			se = &sit_i->sentries[start];
4011 			page = get_current_sit_page(sbi, start);
4012 			if (IS_ERR(page))
4013 				return PTR_ERR(page);
4014 			sit_blk = (struct f2fs_sit_block *)page_address(page);
4015 			sit = sit_blk->entries[SIT_ENTRY_OFFSET(sit_i, start)];
4016 			f2fs_put_page(page, 1);
4017 
4018 			err = check_block_count(sbi, start, &sit);
4019 			if (err)
4020 				return err;
4021 			seg_info_from_raw_sit(se, &sit);
4022 			if (IS_NODESEG(se->type))
4023 				total_node_blocks += se->valid_blocks;
4024 
4025 			/* build discard map only one time */
4026 			if (is_set_ckpt_flags(sbi, CP_TRIMMED_FLAG)) {
4027 				memset(se->discard_map, 0xff,
4028 					SIT_VBLOCK_MAP_SIZE);
4029 			} else {
4030 				memcpy(se->discard_map,
4031 					se->cur_valid_map,
4032 					SIT_VBLOCK_MAP_SIZE);
4033 				sbi->discard_blks +=
4034 					sbi->blocks_per_seg -
4035 					se->valid_blocks;
4036 			}
4037 
4038 			if (sbi->segs_per_sec > 1)
4039 				get_sec_entry(sbi, start)->valid_blocks +=
4040 							se->valid_blocks;
4041 		}
4042 		start_blk += readed;
4043 	} while (start_blk < sit_blk_cnt);
4044 
4045 	down_read(&curseg->journal_rwsem);
4046 	for (i = 0; i < sits_in_cursum(journal); i++) {
4047 		unsigned int old_valid_blocks;
4048 
4049 		start = le32_to_cpu(segno_in_journal(journal, i));
4050 		if (start >= MAIN_SEGS(sbi)) {
4051 			f2fs_msg(sbi->sb, KERN_ERR,
4052 					"Wrong journal entry on segno %u",
4053 					start);
4054 			set_sbi_flag(sbi, SBI_NEED_FSCK);
4055 			err = -EINVAL;
4056 			break;
4057 		}
4058 
4059 		se = &sit_i->sentries[start];
4060 		sit = sit_in_journal(journal, i);
4061 
4062 		old_valid_blocks = se->valid_blocks;
4063 		if (IS_NODESEG(se->type))
4064 			total_node_blocks -= old_valid_blocks;
4065 
4066 		err = check_block_count(sbi, start, &sit);
4067 		if (err)
4068 			break;
4069 		seg_info_from_raw_sit(se, &sit);
4070 		if (IS_NODESEG(se->type))
4071 			total_node_blocks += se->valid_blocks;
4072 
4073 		if (is_set_ckpt_flags(sbi, CP_TRIMMED_FLAG)) {
4074 			memset(se->discard_map, 0xff, SIT_VBLOCK_MAP_SIZE);
4075 		} else {
4076 			memcpy(se->discard_map, se->cur_valid_map,
4077 						SIT_VBLOCK_MAP_SIZE);
4078 			sbi->discard_blks += old_valid_blocks;
4079 			sbi->discard_blks -= se->valid_blocks;
4080 		}
4081 
4082 		if (sbi->segs_per_sec > 1) {
4083 			get_sec_entry(sbi, start)->valid_blocks +=
4084 							se->valid_blocks;
4085 			get_sec_entry(sbi, start)->valid_blocks -=
4086 							old_valid_blocks;
4087 		}
4088 	}
4089 	up_read(&curseg->journal_rwsem);
4090 
4091 	if (!err && total_node_blocks != valid_node_count(sbi)) {
4092 		f2fs_msg(sbi->sb, KERN_ERR,
4093 			"SIT is corrupted node# %u vs %u",
4094 			total_node_blocks, valid_node_count(sbi));
4095 		set_sbi_flag(sbi, SBI_NEED_FSCK);
4096 		err = -EINVAL;
4097 	}
4098 
4099 	return err;
4100 }
4101 
4102 static void init_free_segmap(struct f2fs_sb_info *sbi)
4103 {
4104 	unsigned int start;
4105 	int type;
4106 
4107 	for (start = 0; start < MAIN_SEGS(sbi); start++) {
4108 		struct seg_entry *sentry = get_seg_entry(sbi, start);
4109 		if (!sentry->valid_blocks)
4110 			__set_free(sbi, start);
4111 		else
4112 			SIT_I(sbi)->written_valid_blocks +=
4113 						sentry->valid_blocks;
4114 	}
4115 
4116 	/* set use the current segments */
4117 	for (type = CURSEG_HOT_DATA; type <= CURSEG_COLD_NODE; type++) {
4118 		struct curseg_info *curseg_t = CURSEG_I(sbi, type);
4119 		__set_test_and_inuse(sbi, curseg_t->segno);
4120 	}
4121 }
4122 
4123 static void init_dirty_segmap(struct f2fs_sb_info *sbi)
4124 {
4125 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
4126 	struct free_segmap_info *free_i = FREE_I(sbi);
4127 	unsigned int segno = 0, offset = 0;
4128 	unsigned short valid_blocks;
4129 
4130 	while (1) {
4131 		/* find dirty segment based on free segmap */
4132 		segno = find_next_inuse(free_i, MAIN_SEGS(sbi), offset);
4133 		if (segno >= MAIN_SEGS(sbi))
4134 			break;
4135 		offset = segno + 1;
4136 		valid_blocks = get_valid_blocks(sbi, segno, false);
4137 		if (valid_blocks == sbi->blocks_per_seg || !valid_blocks)
4138 			continue;
4139 		if (valid_blocks > sbi->blocks_per_seg) {
4140 			f2fs_bug_on(sbi, 1);
4141 			continue;
4142 		}
4143 		mutex_lock(&dirty_i->seglist_lock);
4144 		__locate_dirty_segment(sbi, segno, DIRTY);
4145 		mutex_unlock(&dirty_i->seglist_lock);
4146 	}
4147 }
4148 
4149 static int init_victim_secmap(struct f2fs_sb_info *sbi)
4150 {
4151 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
4152 	unsigned int bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
4153 
4154 	dirty_i->victim_secmap = f2fs_kvzalloc(sbi, bitmap_size, GFP_KERNEL);
4155 	if (!dirty_i->victim_secmap)
4156 		return -ENOMEM;
4157 	return 0;
4158 }
4159 
4160 static int build_dirty_segmap(struct f2fs_sb_info *sbi)
4161 {
4162 	struct dirty_seglist_info *dirty_i;
4163 	unsigned int bitmap_size, i;
4164 
4165 	/* allocate memory for dirty segments list information */
4166 	dirty_i = f2fs_kzalloc(sbi, sizeof(struct dirty_seglist_info),
4167 								GFP_KERNEL);
4168 	if (!dirty_i)
4169 		return -ENOMEM;
4170 
4171 	SM_I(sbi)->dirty_info = dirty_i;
4172 	mutex_init(&dirty_i->seglist_lock);
4173 
4174 	bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
4175 
4176 	for (i = 0; i < NR_DIRTY_TYPE; i++) {
4177 		dirty_i->dirty_segmap[i] = f2fs_kvzalloc(sbi, bitmap_size,
4178 								GFP_KERNEL);
4179 		if (!dirty_i->dirty_segmap[i])
4180 			return -ENOMEM;
4181 	}
4182 
4183 	init_dirty_segmap(sbi);
4184 	return init_victim_secmap(sbi);
4185 }
4186 
4187 /*
4188  * Update min, max modified time for cost-benefit GC algorithm
4189  */
4190 static void init_min_max_mtime(struct f2fs_sb_info *sbi)
4191 {
4192 	struct sit_info *sit_i = SIT_I(sbi);
4193 	unsigned int segno;
4194 
4195 	down_write(&sit_i->sentry_lock);
4196 
4197 	sit_i->min_mtime = ULLONG_MAX;
4198 
4199 	for (segno = 0; segno < MAIN_SEGS(sbi); segno += sbi->segs_per_sec) {
4200 		unsigned int i;
4201 		unsigned long long mtime = 0;
4202 
4203 		for (i = 0; i < sbi->segs_per_sec; i++)
4204 			mtime += get_seg_entry(sbi, segno + i)->mtime;
4205 
4206 		mtime = div_u64(mtime, sbi->segs_per_sec);
4207 
4208 		if (sit_i->min_mtime > mtime)
4209 			sit_i->min_mtime = mtime;
4210 	}
4211 	sit_i->max_mtime = get_mtime(sbi, false);
4212 	up_write(&sit_i->sentry_lock);
4213 }
4214 
4215 int f2fs_build_segment_manager(struct f2fs_sb_info *sbi)
4216 {
4217 	struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
4218 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
4219 	struct f2fs_sm_info *sm_info;
4220 	int err;
4221 
4222 	sm_info = f2fs_kzalloc(sbi, sizeof(struct f2fs_sm_info), GFP_KERNEL);
4223 	if (!sm_info)
4224 		return -ENOMEM;
4225 
4226 	/* init sm info */
4227 	sbi->sm_info = sm_info;
4228 	sm_info->seg0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr);
4229 	sm_info->main_blkaddr = le32_to_cpu(raw_super->main_blkaddr);
4230 	sm_info->segment_count = le32_to_cpu(raw_super->segment_count);
4231 	sm_info->reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
4232 	sm_info->ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
4233 	sm_info->main_segments = le32_to_cpu(raw_super->segment_count_main);
4234 	sm_info->ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr);
4235 	sm_info->rec_prefree_segments = sm_info->main_segments *
4236 					DEF_RECLAIM_PREFREE_SEGMENTS / 100;
4237 	if (sm_info->rec_prefree_segments > DEF_MAX_RECLAIM_PREFREE_SEGMENTS)
4238 		sm_info->rec_prefree_segments = DEF_MAX_RECLAIM_PREFREE_SEGMENTS;
4239 
4240 	if (!test_opt(sbi, LFS))
4241 		sm_info->ipu_policy = 1 << F2FS_IPU_FSYNC;
4242 	sm_info->min_ipu_util = DEF_MIN_IPU_UTIL;
4243 	sm_info->min_fsync_blocks = DEF_MIN_FSYNC_BLOCKS;
4244 	sm_info->min_seq_blocks = sbi->blocks_per_seg * sbi->segs_per_sec;
4245 	sm_info->min_hot_blocks = DEF_MIN_HOT_BLOCKS;
4246 	sm_info->min_ssr_sections = reserved_sections(sbi);
4247 
4248 	INIT_LIST_HEAD(&sm_info->sit_entry_set);
4249 
4250 	init_rwsem(&sm_info->curseg_lock);
4251 
4252 	if (!f2fs_readonly(sbi->sb)) {
4253 		err = f2fs_create_flush_cmd_control(sbi);
4254 		if (err)
4255 			return err;
4256 	}
4257 
4258 	err = create_discard_cmd_control(sbi);
4259 	if (err)
4260 		return err;
4261 
4262 	err = build_sit_info(sbi);
4263 	if (err)
4264 		return err;
4265 	err = build_free_segmap(sbi);
4266 	if (err)
4267 		return err;
4268 	err = build_curseg(sbi);
4269 	if (err)
4270 		return err;
4271 
4272 	/* reinit free segmap based on SIT */
4273 	err = build_sit_entries(sbi);
4274 	if (err)
4275 		return err;
4276 
4277 	init_free_segmap(sbi);
4278 	err = build_dirty_segmap(sbi);
4279 	if (err)
4280 		return err;
4281 
4282 	init_min_max_mtime(sbi);
4283 	return 0;
4284 }
4285 
4286 static void discard_dirty_segmap(struct f2fs_sb_info *sbi,
4287 		enum dirty_type dirty_type)
4288 {
4289 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
4290 
4291 	mutex_lock(&dirty_i->seglist_lock);
4292 	kvfree(dirty_i->dirty_segmap[dirty_type]);
4293 	dirty_i->nr_dirty[dirty_type] = 0;
4294 	mutex_unlock(&dirty_i->seglist_lock);
4295 }
4296 
4297 static void destroy_victim_secmap(struct f2fs_sb_info *sbi)
4298 {
4299 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
4300 	kvfree(dirty_i->victim_secmap);
4301 }
4302 
4303 static void destroy_dirty_segmap(struct f2fs_sb_info *sbi)
4304 {
4305 	struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
4306 	int i;
4307 
4308 	if (!dirty_i)
4309 		return;
4310 
4311 	/* discard pre-free/dirty segments list */
4312 	for (i = 0; i < NR_DIRTY_TYPE; i++)
4313 		discard_dirty_segmap(sbi, i);
4314 
4315 	destroy_victim_secmap(sbi);
4316 	SM_I(sbi)->dirty_info = NULL;
4317 	kfree(dirty_i);
4318 }
4319 
4320 static void destroy_curseg(struct f2fs_sb_info *sbi)
4321 {
4322 	struct curseg_info *array = SM_I(sbi)->curseg_array;
4323 	int i;
4324 
4325 	if (!array)
4326 		return;
4327 	SM_I(sbi)->curseg_array = NULL;
4328 	for (i = 0; i < NR_CURSEG_TYPE; i++) {
4329 		kfree(array[i].sum_blk);
4330 		kfree(array[i].journal);
4331 	}
4332 	kfree(array);
4333 }
4334 
4335 static void destroy_free_segmap(struct f2fs_sb_info *sbi)
4336 {
4337 	struct free_segmap_info *free_i = SM_I(sbi)->free_info;
4338 	if (!free_i)
4339 		return;
4340 	SM_I(sbi)->free_info = NULL;
4341 	kvfree(free_i->free_segmap);
4342 	kvfree(free_i->free_secmap);
4343 	kfree(free_i);
4344 }
4345 
4346 static void destroy_sit_info(struct f2fs_sb_info *sbi)
4347 {
4348 	struct sit_info *sit_i = SIT_I(sbi);
4349 	unsigned int start;
4350 
4351 	if (!sit_i)
4352 		return;
4353 
4354 	if (sit_i->sentries) {
4355 		for (start = 0; start < MAIN_SEGS(sbi); start++) {
4356 			kfree(sit_i->sentries[start].cur_valid_map);
4357 #ifdef CONFIG_F2FS_CHECK_FS
4358 			kfree(sit_i->sentries[start].cur_valid_map_mir);
4359 #endif
4360 			kfree(sit_i->sentries[start].ckpt_valid_map);
4361 			kfree(sit_i->sentries[start].discard_map);
4362 		}
4363 	}
4364 	kfree(sit_i->tmp_map);
4365 
4366 	kvfree(sit_i->sentries);
4367 	kvfree(sit_i->sec_entries);
4368 	kvfree(sit_i->dirty_sentries_bitmap);
4369 
4370 	SM_I(sbi)->sit_info = NULL;
4371 	kfree(sit_i->sit_bitmap);
4372 #ifdef CONFIG_F2FS_CHECK_FS
4373 	kfree(sit_i->sit_bitmap_mir);
4374 #endif
4375 	kfree(sit_i);
4376 }
4377 
4378 void f2fs_destroy_segment_manager(struct f2fs_sb_info *sbi)
4379 {
4380 	struct f2fs_sm_info *sm_info = SM_I(sbi);
4381 
4382 	if (!sm_info)
4383 		return;
4384 	f2fs_destroy_flush_cmd_control(sbi, true);
4385 	destroy_discard_cmd_control(sbi);
4386 	destroy_dirty_segmap(sbi);
4387 	destroy_curseg(sbi);
4388 	destroy_free_segmap(sbi);
4389 	destroy_sit_info(sbi);
4390 	sbi->sm_info = NULL;
4391 	kfree(sm_info);
4392 }
4393 
4394 int __init f2fs_create_segment_manager_caches(void)
4395 {
4396 	discard_entry_slab = f2fs_kmem_cache_create("discard_entry",
4397 			sizeof(struct discard_entry));
4398 	if (!discard_entry_slab)
4399 		goto fail;
4400 
4401 	discard_cmd_slab = f2fs_kmem_cache_create("discard_cmd",
4402 			sizeof(struct discard_cmd));
4403 	if (!discard_cmd_slab)
4404 		goto destroy_discard_entry;
4405 
4406 	sit_entry_set_slab = f2fs_kmem_cache_create("sit_entry_set",
4407 			sizeof(struct sit_entry_set));
4408 	if (!sit_entry_set_slab)
4409 		goto destroy_discard_cmd;
4410 
4411 	inmem_entry_slab = f2fs_kmem_cache_create("inmem_page_entry",
4412 			sizeof(struct inmem_pages));
4413 	if (!inmem_entry_slab)
4414 		goto destroy_sit_entry_set;
4415 	return 0;
4416 
4417 destroy_sit_entry_set:
4418 	kmem_cache_destroy(sit_entry_set_slab);
4419 destroy_discard_cmd:
4420 	kmem_cache_destroy(discard_cmd_slab);
4421 destroy_discard_entry:
4422 	kmem_cache_destroy(discard_entry_slab);
4423 fail:
4424 	return -ENOMEM;
4425 }
4426 
4427 void f2fs_destroy_segment_manager_caches(void)
4428 {
4429 	kmem_cache_destroy(sit_entry_set_slab);
4430 	kmem_cache_destroy(discard_cmd_slab);
4431 	kmem_cache_destroy(discard_entry_slab);
4432 	kmem_cache_destroy(inmem_entry_slab);
4433 }
4434