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