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