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