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