xref: /linux/fs/f2fs/node.c (revision 7fe03f8ff55d33fe6398637f78a8620dd2a78b38)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * fs/f2fs/node.c
4  *
5  * Copyright (c) 2012 Samsung Electronics Co., Ltd.
6  *             http://www.samsung.com/
7  */
8 #include <linux/fs.h>
9 #include <linux/f2fs_fs.h>
10 #include <linux/mpage.h>
11 #include <linux/sched/mm.h>
12 #include <linux/blkdev.h>
13 #include <linux/pagevec.h>
14 #include <linux/swap.h>
15 
16 #include "f2fs.h"
17 #include "node.h"
18 #include "segment.h"
19 #include "xattr.h"
20 #include "iostat.h"
21 #include <trace/events/f2fs.h>
22 
23 #define on_f2fs_build_free_nids(nm_i) mutex_is_locked(&(nm_i)->build_lock)
24 
25 static struct kmem_cache *nat_entry_slab;
26 static struct kmem_cache *free_nid_slab;
27 static struct kmem_cache *nat_entry_set_slab;
28 static struct kmem_cache *fsync_node_entry_slab;
29 
30 /*
31  * Check whether the given nid is within node id range.
32  */
33 int f2fs_check_nid_range(struct f2fs_sb_info *sbi, nid_t nid)
34 {
35 	if (unlikely(nid < F2FS_ROOT_INO(sbi) || nid >= NM_I(sbi)->max_nid)) {
36 		set_sbi_flag(sbi, SBI_NEED_FSCK);
37 		f2fs_warn(sbi, "%s: out-of-range nid=%x, run fsck to fix.",
38 			  __func__, nid);
39 		f2fs_handle_error(sbi, ERROR_CORRUPTED_INODE);
40 		return -EFSCORRUPTED;
41 	}
42 	return 0;
43 }
44 
45 bool f2fs_available_free_memory(struct f2fs_sb_info *sbi, int type)
46 {
47 	struct f2fs_nm_info *nm_i = NM_I(sbi);
48 	struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
49 	struct sysinfo val;
50 	unsigned long avail_ram;
51 	unsigned long mem_size = 0;
52 	bool res = false;
53 
54 	if (!nm_i)
55 		return true;
56 
57 	si_meminfo(&val);
58 
59 	/* only uses low memory */
60 	avail_ram = val.totalram - val.totalhigh;
61 
62 	/*
63 	 * give 25%, 25%, 50%, 50%, 25%, 25% memory for each components respectively
64 	 */
65 	if (type == FREE_NIDS) {
66 		mem_size = (nm_i->nid_cnt[FREE_NID] *
67 				sizeof(struct free_nid)) >> PAGE_SHIFT;
68 		res = mem_size < ((avail_ram * nm_i->ram_thresh / 100) >> 2);
69 	} else if (type == NAT_ENTRIES) {
70 		mem_size = (nm_i->nat_cnt[TOTAL_NAT] *
71 				sizeof(struct nat_entry)) >> PAGE_SHIFT;
72 		res = mem_size < ((avail_ram * nm_i->ram_thresh / 100) >> 2);
73 		if (excess_cached_nats(sbi))
74 			res = false;
75 	} else if (type == DIRTY_DENTS) {
76 		if (sbi->sb->s_bdi->wb.dirty_exceeded)
77 			return false;
78 		mem_size = get_pages(sbi, F2FS_DIRTY_DENTS);
79 		res = mem_size < ((avail_ram * nm_i->ram_thresh / 100) >> 1);
80 	} else if (type == INO_ENTRIES) {
81 		int i;
82 
83 		for (i = 0; i < MAX_INO_ENTRY; i++)
84 			mem_size += sbi->im[i].ino_num *
85 						sizeof(struct ino_entry);
86 		mem_size >>= PAGE_SHIFT;
87 		res = mem_size < ((avail_ram * nm_i->ram_thresh / 100) >> 1);
88 	} else if (type == READ_EXTENT_CACHE || type == AGE_EXTENT_CACHE) {
89 		enum extent_type etype = type == READ_EXTENT_CACHE ?
90 						EX_READ : EX_BLOCK_AGE;
91 		struct extent_tree_info *eti = &sbi->extent_tree[etype];
92 
93 		mem_size = (atomic_read(&eti->total_ext_tree) *
94 				sizeof(struct extent_tree) +
95 				atomic_read(&eti->total_ext_node) *
96 				sizeof(struct extent_node)) >> PAGE_SHIFT;
97 		res = mem_size < ((avail_ram * nm_i->ram_thresh / 100) >> 2);
98 	} else if (type == DISCARD_CACHE) {
99 		mem_size = (atomic_read(&dcc->discard_cmd_cnt) *
100 				sizeof(struct discard_cmd)) >> PAGE_SHIFT;
101 		res = mem_size < (avail_ram * nm_i->ram_thresh / 100);
102 	} else if (type == COMPRESS_PAGE) {
103 #ifdef CONFIG_F2FS_FS_COMPRESSION
104 		unsigned long free_ram = val.freeram;
105 
106 		/*
107 		 * free memory is lower than watermark or cached page count
108 		 * exceed threshold, deny caching compress page.
109 		 */
110 		res = (free_ram > avail_ram * sbi->compress_watermark / 100) &&
111 			(COMPRESS_MAPPING(sbi)->nrpages <
112 			 free_ram * sbi->compress_percent / 100);
113 #else
114 		res = false;
115 #endif
116 	} else {
117 		if (!sbi->sb->s_bdi->wb.dirty_exceeded)
118 			return true;
119 	}
120 	return res;
121 }
122 
123 static void clear_node_page_dirty(struct page *page)
124 {
125 	if (PageDirty(page)) {
126 		f2fs_clear_page_cache_dirty_tag(page_folio(page));
127 		clear_page_dirty_for_io(page);
128 		dec_page_count(F2FS_P_SB(page), F2FS_DIRTY_NODES);
129 	}
130 	ClearPageUptodate(page);
131 }
132 
133 static struct page *get_current_nat_page(struct f2fs_sb_info *sbi, nid_t nid)
134 {
135 	return f2fs_get_meta_page_retry(sbi, current_nat_addr(sbi, nid));
136 }
137 
138 static struct page *get_next_nat_page(struct f2fs_sb_info *sbi, nid_t nid)
139 {
140 	struct page *src_page;
141 	struct page *dst_page;
142 	pgoff_t dst_off;
143 	void *src_addr;
144 	void *dst_addr;
145 	struct f2fs_nm_info *nm_i = NM_I(sbi);
146 
147 	dst_off = next_nat_addr(sbi, current_nat_addr(sbi, nid));
148 
149 	/* get current nat block page with lock */
150 	src_page = get_current_nat_page(sbi, nid);
151 	if (IS_ERR(src_page))
152 		return src_page;
153 	dst_page = f2fs_grab_meta_page(sbi, dst_off);
154 	f2fs_bug_on(sbi, PageDirty(src_page));
155 
156 	src_addr = page_address(src_page);
157 	dst_addr = page_address(dst_page);
158 	memcpy(dst_addr, src_addr, PAGE_SIZE);
159 	set_page_dirty(dst_page);
160 	f2fs_put_page(src_page, 1);
161 
162 	set_to_next_nat(nm_i, nid);
163 
164 	return dst_page;
165 }
166 
167 static struct nat_entry *__alloc_nat_entry(struct f2fs_sb_info *sbi,
168 						nid_t nid, bool no_fail)
169 {
170 	struct nat_entry *new;
171 
172 	new = f2fs_kmem_cache_alloc(nat_entry_slab,
173 					GFP_F2FS_ZERO, no_fail, sbi);
174 	if (new) {
175 		nat_set_nid(new, nid);
176 		nat_reset_flag(new);
177 	}
178 	return new;
179 }
180 
181 static void __free_nat_entry(struct nat_entry *e)
182 {
183 	kmem_cache_free(nat_entry_slab, e);
184 }
185 
186 /* must be locked by nat_tree_lock */
187 static struct nat_entry *__init_nat_entry(struct f2fs_nm_info *nm_i,
188 	struct nat_entry *ne, struct f2fs_nat_entry *raw_ne, bool no_fail)
189 {
190 	if (no_fail)
191 		f2fs_radix_tree_insert(&nm_i->nat_root, nat_get_nid(ne), ne);
192 	else if (radix_tree_insert(&nm_i->nat_root, nat_get_nid(ne), ne))
193 		return NULL;
194 
195 	if (raw_ne)
196 		node_info_from_raw_nat(&ne->ni, raw_ne);
197 
198 	spin_lock(&nm_i->nat_list_lock);
199 	list_add_tail(&ne->list, &nm_i->nat_entries);
200 	spin_unlock(&nm_i->nat_list_lock);
201 
202 	nm_i->nat_cnt[TOTAL_NAT]++;
203 	nm_i->nat_cnt[RECLAIMABLE_NAT]++;
204 	return ne;
205 }
206 
207 static struct nat_entry *__lookup_nat_cache(struct f2fs_nm_info *nm_i, nid_t n)
208 {
209 	struct nat_entry *ne;
210 
211 	ne = radix_tree_lookup(&nm_i->nat_root, n);
212 
213 	/* for recent accessed nat entry, move it to tail of lru list */
214 	if (ne && !get_nat_flag(ne, IS_DIRTY)) {
215 		spin_lock(&nm_i->nat_list_lock);
216 		if (!list_empty(&ne->list))
217 			list_move_tail(&ne->list, &nm_i->nat_entries);
218 		spin_unlock(&nm_i->nat_list_lock);
219 	}
220 
221 	return ne;
222 }
223 
224 static unsigned int __gang_lookup_nat_cache(struct f2fs_nm_info *nm_i,
225 		nid_t start, unsigned int nr, struct nat_entry **ep)
226 {
227 	return radix_tree_gang_lookup(&nm_i->nat_root, (void **)ep, start, nr);
228 }
229 
230 static void __del_from_nat_cache(struct f2fs_nm_info *nm_i, struct nat_entry *e)
231 {
232 	radix_tree_delete(&nm_i->nat_root, nat_get_nid(e));
233 	nm_i->nat_cnt[TOTAL_NAT]--;
234 	nm_i->nat_cnt[RECLAIMABLE_NAT]--;
235 	__free_nat_entry(e);
236 }
237 
238 static struct nat_entry_set *__grab_nat_entry_set(struct f2fs_nm_info *nm_i,
239 							struct nat_entry *ne)
240 {
241 	nid_t set = NAT_BLOCK_OFFSET(ne->ni.nid);
242 	struct nat_entry_set *head;
243 
244 	head = radix_tree_lookup(&nm_i->nat_set_root, set);
245 	if (!head) {
246 		head = f2fs_kmem_cache_alloc(nat_entry_set_slab,
247 						GFP_NOFS, true, NULL);
248 
249 		INIT_LIST_HEAD(&head->entry_list);
250 		INIT_LIST_HEAD(&head->set_list);
251 		head->set = set;
252 		head->entry_cnt = 0;
253 		f2fs_radix_tree_insert(&nm_i->nat_set_root, set, head);
254 	}
255 	return head;
256 }
257 
258 static void __set_nat_cache_dirty(struct f2fs_nm_info *nm_i,
259 						struct nat_entry *ne)
260 {
261 	struct nat_entry_set *head;
262 	bool new_ne = nat_get_blkaddr(ne) == NEW_ADDR;
263 
264 	if (!new_ne)
265 		head = __grab_nat_entry_set(nm_i, ne);
266 
267 	/*
268 	 * update entry_cnt in below condition:
269 	 * 1. update NEW_ADDR to valid block address;
270 	 * 2. update old block address to new one;
271 	 */
272 	if (!new_ne && (get_nat_flag(ne, IS_PREALLOC) ||
273 				!get_nat_flag(ne, IS_DIRTY)))
274 		head->entry_cnt++;
275 
276 	set_nat_flag(ne, IS_PREALLOC, new_ne);
277 
278 	if (get_nat_flag(ne, IS_DIRTY))
279 		goto refresh_list;
280 
281 	nm_i->nat_cnt[DIRTY_NAT]++;
282 	nm_i->nat_cnt[RECLAIMABLE_NAT]--;
283 	set_nat_flag(ne, IS_DIRTY, true);
284 refresh_list:
285 	spin_lock(&nm_i->nat_list_lock);
286 	if (new_ne)
287 		list_del_init(&ne->list);
288 	else
289 		list_move_tail(&ne->list, &head->entry_list);
290 	spin_unlock(&nm_i->nat_list_lock);
291 }
292 
293 static void __clear_nat_cache_dirty(struct f2fs_nm_info *nm_i,
294 		struct nat_entry_set *set, struct nat_entry *ne)
295 {
296 	spin_lock(&nm_i->nat_list_lock);
297 	list_move_tail(&ne->list, &nm_i->nat_entries);
298 	spin_unlock(&nm_i->nat_list_lock);
299 
300 	set_nat_flag(ne, IS_DIRTY, false);
301 	set->entry_cnt--;
302 	nm_i->nat_cnt[DIRTY_NAT]--;
303 	nm_i->nat_cnt[RECLAIMABLE_NAT]++;
304 }
305 
306 static unsigned int __gang_lookup_nat_set(struct f2fs_nm_info *nm_i,
307 		nid_t start, unsigned int nr, struct nat_entry_set **ep)
308 {
309 	return radix_tree_gang_lookup(&nm_i->nat_set_root, (void **)ep,
310 							start, nr);
311 }
312 
313 bool f2fs_in_warm_node_list(struct f2fs_sb_info *sbi, struct page *page)
314 {
315 	return NODE_MAPPING(sbi) == page->mapping &&
316 			IS_DNODE(page) && is_cold_node(page);
317 }
318 
319 void f2fs_init_fsync_node_info(struct f2fs_sb_info *sbi)
320 {
321 	spin_lock_init(&sbi->fsync_node_lock);
322 	INIT_LIST_HEAD(&sbi->fsync_node_list);
323 	sbi->fsync_seg_id = 0;
324 	sbi->fsync_node_num = 0;
325 }
326 
327 static unsigned int f2fs_add_fsync_node_entry(struct f2fs_sb_info *sbi,
328 							struct page *page)
329 {
330 	struct fsync_node_entry *fn;
331 	unsigned long flags;
332 	unsigned int seq_id;
333 
334 	fn = f2fs_kmem_cache_alloc(fsync_node_entry_slab,
335 					GFP_NOFS, true, NULL);
336 
337 	get_page(page);
338 	fn->page = page;
339 	INIT_LIST_HEAD(&fn->list);
340 
341 	spin_lock_irqsave(&sbi->fsync_node_lock, flags);
342 	list_add_tail(&fn->list, &sbi->fsync_node_list);
343 	fn->seq_id = sbi->fsync_seg_id++;
344 	seq_id = fn->seq_id;
345 	sbi->fsync_node_num++;
346 	spin_unlock_irqrestore(&sbi->fsync_node_lock, flags);
347 
348 	return seq_id;
349 }
350 
351 void f2fs_del_fsync_node_entry(struct f2fs_sb_info *sbi, struct page *page)
352 {
353 	struct fsync_node_entry *fn;
354 	unsigned long flags;
355 
356 	spin_lock_irqsave(&sbi->fsync_node_lock, flags);
357 	list_for_each_entry(fn, &sbi->fsync_node_list, list) {
358 		if (fn->page == page) {
359 			list_del(&fn->list);
360 			sbi->fsync_node_num--;
361 			spin_unlock_irqrestore(&sbi->fsync_node_lock, flags);
362 			kmem_cache_free(fsync_node_entry_slab, fn);
363 			put_page(page);
364 			return;
365 		}
366 	}
367 	spin_unlock_irqrestore(&sbi->fsync_node_lock, flags);
368 	f2fs_bug_on(sbi, 1);
369 }
370 
371 void f2fs_reset_fsync_node_info(struct f2fs_sb_info *sbi)
372 {
373 	unsigned long flags;
374 
375 	spin_lock_irqsave(&sbi->fsync_node_lock, flags);
376 	sbi->fsync_seg_id = 0;
377 	spin_unlock_irqrestore(&sbi->fsync_node_lock, flags);
378 }
379 
380 int f2fs_need_dentry_mark(struct f2fs_sb_info *sbi, nid_t nid)
381 {
382 	struct f2fs_nm_info *nm_i = NM_I(sbi);
383 	struct nat_entry *e;
384 	bool need = false;
385 
386 	f2fs_down_read(&nm_i->nat_tree_lock);
387 	e = __lookup_nat_cache(nm_i, nid);
388 	if (e) {
389 		if (!get_nat_flag(e, IS_CHECKPOINTED) &&
390 				!get_nat_flag(e, HAS_FSYNCED_INODE))
391 			need = true;
392 	}
393 	f2fs_up_read(&nm_i->nat_tree_lock);
394 	return need;
395 }
396 
397 bool f2fs_is_checkpointed_node(struct f2fs_sb_info *sbi, nid_t nid)
398 {
399 	struct f2fs_nm_info *nm_i = NM_I(sbi);
400 	struct nat_entry *e;
401 	bool is_cp = true;
402 
403 	f2fs_down_read(&nm_i->nat_tree_lock);
404 	e = __lookup_nat_cache(nm_i, nid);
405 	if (e && !get_nat_flag(e, IS_CHECKPOINTED))
406 		is_cp = false;
407 	f2fs_up_read(&nm_i->nat_tree_lock);
408 	return is_cp;
409 }
410 
411 bool f2fs_need_inode_block_update(struct f2fs_sb_info *sbi, nid_t ino)
412 {
413 	struct f2fs_nm_info *nm_i = NM_I(sbi);
414 	struct nat_entry *e;
415 	bool need_update = true;
416 
417 	f2fs_down_read(&nm_i->nat_tree_lock);
418 	e = __lookup_nat_cache(nm_i, ino);
419 	if (e && get_nat_flag(e, HAS_LAST_FSYNC) &&
420 			(get_nat_flag(e, IS_CHECKPOINTED) ||
421 			 get_nat_flag(e, HAS_FSYNCED_INODE)))
422 		need_update = false;
423 	f2fs_up_read(&nm_i->nat_tree_lock);
424 	return need_update;
425 }
426 
427 /* must be locked by nat_tree_lock */
428 static void cache_nat_entry(struct f2fs_sb_info *sbi, nid_t nid,
429 						struct f2fs_nat_entry *ne)
430 {
431 	struct f2fs_nm_info *nm_i = NM_I(sbi);
432 	struct nat_entry *new, *e;
433 
434 	/* Let's mitigate lock contention of nat_tree_lock during checkpoint */
435 	if (f2fs_rwsem_is_locked(&sbi->cp_global_sem))
436 		return;
437 
438 	new = __alloc_nat_entry(sbi, nid, false);
439 	if (!new)
440 		return;
441 
442 	f2fs_down_write(&nm_i->nat_tree_lock);
443 	e = __lookup_nat_cache(nm_i, nid);
444 	if (!e)
445 		e = __init_nat_entry(nm_i, new, ne, false);
446 	else
447 		f2fs_bug_on(sbi, nat_get_ino(e) != le32_to_cpu(ne->ino) ||
448 				nat_get_blkaddr(e) !=
449 					le32_to_cpu(ne->block_addr) ||
450 				nat_get_version(e) != ne->version);
451 	f2fs_up_write(&nm_i->nat_tree_lock);
452 	if (e != new)
453 		__free_nat_entry(new);
454 }
455 
456 static void set_node_addr(struct f2fs_sb_info *sbi, struct node_info *ni,
457 			block_t new_blkaddr, bool fsync_done)
458 {
459 	struct f2fs_nm_info *nm_i = NM_I(sbi);
460 	struct nat_entry *e;
461 	struct nat_entry *new = __alloc_nat_entry(sbi, ni->nid, true);
462 
463 	f2fs_down_write(&nm_i->nat_tree_lock);
464 	e = __lookup_nat_cache(nm_i, ni->nid);
465 	if (!e) {
466 		e = __init_nat_entry(nm_i, new, NULL, true);
467 		copy_node_info(&e->ni, ni);
468 		f2fs_bug_on(sbi, ni->blk_addr == NEW_ADDR);
469 	} else if (new_blkaddr == NEW_ADDR) {
470 		/*
471 		 * when nid is reallocated,
472 		 * previous nat entry can be remained in nat cache.
473 		 * So, reinitialize it with new information.
474 		 */
475 		copy_node_info(&e->ni, ni);
476 		f2fs_bug_on(sbi, ni->blk_addr != NULL_ADDR);
477 	}
478 	/* let's free early to reduce memory consumption */
479 	if (e != new)
480 		__free_nat_entry(new);
481 
482 	/* sanity check */
483 	f2fs_bug_on(sbi, nat_get_blkaddr(e) != ni->blk_addr);
484 	f2fs_bug_on(sbi, nat_get_blkaddr(e) == NULL_ADDR &&
485 			new_blkaddr == NULL_ADDR);
486 	f2fs_bug_on(sbi, nat_get_blkaddr(e) == NEW_ADDR &&
487 			new_blkaddr == NEW_ADDR);
488 	f2fs_bug_on(sbi, __is_valid_data_blkaddr(nat_get_blkaddr(e)) &&
489 			new_blkaddr == NEW_ADDR);
490 
491 	/* increment version no as node is removed */
492 	if (nat_get_blkaddr(e) != NEW_ADDR && new_blkaddr == NULL_ADDR) {
493 		unsigned char version = nat_get_version(e);
494 
495 		nat_set_version(e, inc_node_version(version));
496 	}
497 
498 	/* change address */
499 	nat_set_blkaddr(e, new_blkaddr);
500 	if (!__is_valid_data_blkaddr(new_blkaddr))
501 		set_nat_flag(e, IS_CHECKPOINTED, false);
502 	__set_nat_cache_dirty(nm_i, e);
503 
504 	/* update fsync_mark if its inode nat entry is still alive */
505 	if (ni->nid != ni->ino)
506 		e = __lookup_nat_cache(nm_i, ni->ino);
507 	if (e) {
508 		if (fsync_done && ni->nid == ni->ino)
509 			set_nat_flag(e, HAS_FSYNCED_INODE, true);
510 		set_nat_flag(e, HAS_LAST_FSYNC, fsync_done);
511 	}
512 	f2fs_up_write(&nm_i->nat_tree_lock);
513 }
514 
515 int f2fs_try_to_free_nats(struct f2fs_sb_info *sbi, int nr_shrink)
516 {
517 	struct f2fs_nm_info *nm_i = NM_I(sbi);
518 	int nr = nr_shrink;
519 
520 	if (!f2fs_down_write_trylock(&nm_i->nat_tree_lock))
521 		return 0;
522 
523 	spin_lock(&nm_i->nat_list_lock);
524 	while (nr_shrink) {
525 		struct nat_entry *ne;
526 
527 		if (list_empty(&nm_i->nat_entries))
528 			break;
529 
530 		ne = list_first_entry(&nm_i->nat_entries,
531 					struct nat_entry, list);
532 		list_del(&ne->list);
533 		spin_unlock(&nm_i->nat_list_lock);
534 
535 		__del_from_nat_cache(nm_i, ne);
536 		nr_shrink--;
537 
538 		spin_lock(&nm_i->nat_list_lock);
539 	}
540 	spin_unlock(&nm_i->nat_list_lock);
541 
542 	f2fs_up_write(&nm_i->nat_tree_lock);
543 	return nr - nr_shrink;
544 }
545 
546 int f2fs_get_node_info(struct f2fs_sb_info *sbi, nid_t nid,
547 				struct node_info *ni, bool checkpoint_context)
548 {
549 	struct f2fs_nm_info *nm_i = NM_I(sbi);
550 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_HOT_DATA);
551 	struct f2fs_journal *journal = curseg->journal;
552 	nid_t start_nid = START_NID(nid);
553 	struct f2fs_nat_block *nat_blk;
554 	struct page *page = NULL;
555 	struct f2fs_nat_entry ne;
556 	struct nat_entry *e;
557 	pgoff_t index;
558 	block_t blkaddr;
559 	int i;
560 
561 	ni->flag = 0;
562 	ni->nid = nid;
563 retry:
564 	/* Check nat cache */
565 	f2fs_down_read(&nm_i->nat_tree_lock);
566 	e = __lookup_nat_cache(nm_i, nid);
567 	if (e) {
568 		ni->ino = nat_get_ino(e);
569 		ni->blk_addr = nat_get_blkaddr(e);
570 		ni->version = nat_get_version(e);
571 		f2fs_up_read(&nm_i->nat_tree_lock);
572 		return 0;
573 	}
574 
575 	/*
576 	 * Check current segment summary by trying to grab journal_rwsem first.
577 	 * This sem is on the critical path on the checkpoint requiring the above
578 	 * nat_tree_lock. Therefore, we should retry, if we failed to grab here
579 	 * while not bothering checkpoint.
580 	 */
581 	if (!f2fs_rwsem_is_locked(&sbi->cp_global_sem) || checkpoint_context) {
582 		down_read(&curseg->journal_rwsem);
583 	} else if (f2fs_rwsem_is_contended(&nm_i->nat_tree_lock) ||
584 				!down_read_trylock(&curseg->journal_rwsem)) {
585 		f2fs_up_read(&nm_i->nat_tree_lock);
586 		goto retry;
587 	}
588 
589 	i = f2fs_lookup_journal_in_cursum(journal, NAT_JOURNAL, nid, 0);
590 	if (i >= 0) {
591 		ne = nat_in_journal(journal, i);
592 		node_info_from_raw_nat(ni, &ne);
593 	}
594 	up_read(&curseg->journal_rwsem);
595 	if (i >= 0) {
596 		f2fs_up_read(&nm_i->nat_tree_lock);
597 		goto cache;
598 	}
599 
600 	/* Fill node_info from nat page */
601 	index = current_nat_addr(sbi, nid);
602 	f2fs_up_read(&nm_i->nat_tree_lock);
603 
604 	page = f2fs_get_meta_page(sbi, index);
605 	if (IS_ERR(page))
606 		return PTR_ERR(page);
607 
608 	nat_blk = (struct f2fs_nat_block *)page_address(page);
609 	ne = nat_blk->entries[nid - start_nid];
610 	node_info_from_raw_nat(ni, &ne);
611 	f2fs_put_page(page, 1);
612 cache:
613 	blkaddr = le32_to_cpu(ne.block_addr);
614 	if (__is_valid_data_blkaddr(blkaddr) &&
615 		!f2fs_is_valid_blkaddr(sbi, blkaddr, DATA_GENERIC_ENHANCE))
616 		return -EFAULT;
617 
618 	/* cache nat entry */
619 	cache_nat_entry(sbi, nid, &ne);
620 	return 0;
621 }
622 
623 /*
624  * readahead MAX_RA_NODE number of node pages.
625  */
626 static void f2fs_ra_node_pages(struct page *parent, int start, int n)
627 {
628 	struct f2fs_sb_info *sbi = F2FS_P_SB(parent);
629 	struct blk_plug plug;
630 	int i, end;
631 	nid_t nid;
632 
633 	blk_start_plug(&plug);
634 
635 	/* Then, try readahead for siblings of the desired node */
636 	end = start + n;
637 	end = min(end, (int)NIDS_PER_BLOCK);
638 	for (i = start; i < end; i++) {
639 		nid = get_nid(parent, i, false);
640 		f2fs_ra_node_page(sbi, nid);
641 	}
642 
643 	blk_finish_plug(&plug);
644 }
645 
646 pgoff_t f2fs_get_next_page_offset(struct dnode_of_data *dn, pgoff_t pgofs)
647 {
648 	const long direct_index = ADDRS_PER_INODE(dn->inode);
649 	const long direct_blks = ADDRS_PER_BLOCK(dn->inode);
650 	const long indirect_blks = ADDRS_PER_BLOCK(dn->inode) * NIDS_PER_BLOCK;
651 	unsigned int skipped_unit = ADDRS_PER_BLOCK(dn->inode);
652 	int cur_level = dn->cur_level;
653 	int max_level = dn->max_level;
654 	pgoff_t base = 0;
655 
656 	if (!dn->max_level)
657 		return pgofs + 1;
658 
659 	while (max_level-- > cur_level)
660 		skipped_unit *= NIDS_PER_BLOCK;
661 
662 	switch (dn->max_level) {
663 	case 3:
664 		base += 2 * indirect_blks;
665 		fallthrough;
666 	case 2:
667 		base += 2 * direct_blks;
668 		fallthrough;
669 	case 1:
670 		base += direct_index;
671 		break;
672 	default:
673 		f2fs_bug_on(F2FS_I_SB(dn->inode), 1);
674 	}
675 
676 	return ((pgofs - base) / skipped_unit + 1) * skipped_unit + base;
677 }
678 
679 /*
680  * The maximum depth is four.
681  * Offset[0] will have raw inode offset.
682  */
683 static int get_node_path(struct inode *inode, long block,
684 				int offset[4], unsigned int noffset[4])
685 {
686 	const long direct_index = ADDRS_PER_INODE(inode);
687 	const long direct_blks = ADDRS_PER_BLOCK(inode);
688 	const long dptrs_per_blk = NIDS_PER_BLOCK;
689 	const long indirect_blks = ADDRS_PER_BLOCK(inode) * NIDS_PER_BLOCK;
690 	const long dindirect_blks = indirect_blks * NIDS_PER_BLOCK;
691 	int n = 0;
692 	int level = 0;
693 
694 	noffset[0] = 0;
695 
696 	if (block < direct_index) {
697 		offset[n] = block;
698 		goto got;
699 	}
700 	block -= direct_index;
701 	if (block < direct_blks) {
702 		offset[n++] = NODE_DIR1_BLOCK;
703 		noffset[n] = 1;
704 		offset[n] = block;
705 		level = 1;
706 		goto got;
707 	}
708 	block -= direct_blks;
709 	if (block < direct_blks) {
710 		offset[n++] = NODE_DIR2_BLOCK;
711 		noffset[n] = 2;
712 		offset[n] = block;
713 		level = 1;
714 		goto got;
715 	}
716 	block -= direct_blks;
717 	if (block < indirect_blks) {
718 		offset[n++] = NODE_IND1_BLOCK;
719 		noffset[n] = 3;
720 		offset[n++] = block / direct_blks;
721 		noffset[n] = 4 + offset[n - 1];
722 		offset[n] = block % direct_blks;
723 		level = 2;
724 		goto got;
725 	}
726 	block -= indirect_blks;
727 	if (block < indirect_blks) {
728 		offset[n++] = NODE_IND2_BLOCK;
729 		noffset[n] = 4 + dptrs_per_blk;
730 		offset[n++] = block / direct_blks;
731 		noffset[n] = 5 + dptrs_per_blk + offset[n - 1];
732 		offset[n] = block % direct_blks;
733 		level = 2;
734 		goto got;
735 	}
736 	block -= indirect_blks;
737 	if (block < dindirect_blks) {
738 		offset[n++] = NODE_DIND_BLOCK;
739 		noffset[n] = 5 + (dptrs_per_blk * 2);
740 		offset[n++] = block / indirect_blks;
741 		noffset[n] = 6 + (dptrs_per_blk * 2) +
742 			      offset[n - 1] * (dptrs_per_blk + 1);
743 		offset[n++] = (block / direct_blks) % dptrs_per_blk;
744 		noffset[n] = 7 + (dptrs_per_blk * 2) +
745 			      offset[n - 2] * (dptrs_per_blk + 1) +
746 			      offset[n - 1];
747 		offset[n] = block % direct_blks;
748 		level = 3;
749 		goto got;
750 	} else {
751 		return -E2BIG;
752 	}
753 got:
754 	return level;
755 }
756 
757 /*
758  * Caller should call f2fs_put_dnode(dn).
759  * Also, it should grab and release a rwsem by calling f2fs_lock_op() and
760  * f2fs_unlock_op() only if mode is set with ALLOC_NODE.
761  */
762 int f2fs_get_dnode_of_data(struct dnode_of_data *dn, pgoff_t index, int mode)
763 {
764 	struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
765 	struct page *npage[4];
766 	struct page *parent = NULL;
767 	int offset[4];
768 	unsigned int noffset[4];
769 	nid_t nids[4];
770 	int level, i = 0;
771 	int err = 0;
772 
773 	level = get_node_path(dn->inode, index, offset, noffset);
774 	if (level < 0)
775 		return level;
776 
777 	nids[0] = dn->inode->i_ino;
778 	npage[0] = dn->inode_page;
779 
780 	if (!npage[0]) {
781 		npage[0] = f2fs_get_node_page(sbi, nids[0]);
782 		if (IS_ERR(npage[0]))
783 			return PTR_ERR(npage[0]);
784 	}
785 
786 	/* if inline_data is set, should not report any block indices */
787 	if (f2fs_has_inline_data(dn->inode) && index) {
788 		err = -ENOENT;
789 		f2fs_put_page(npage[0], 1);
790 		goto release_out;
791 	}
792 
793 	parent = npage[0];
794 	if (level != 0)
795 		nids[1] = get_nid(parent, offset[0], true);
796 	dn->inode_page = npage[0];
797 	dn->inode_page_locked = true;
798 
799 	/* get indirect or direct nodes */
800 	for (i = 1; i <= level; i++) {
801 		bool done = false;
802 
803 		if (!nids[i] && mode == ALLOC_NODE) {
804 			/* alloc new node */
805 			if (!f2fs_alloc_nid(sbi, &(nids[i]))) {
806 				err = -ENOSPC;
807 				goto release_pages;
808 			}
809 
810 			dn->nid = nids[i];
811 			npage[i] = f2fs_new_node_page(dn, noffset[i]);
812 			if (IS_ERR(npage[i])) {
813 				f2fs_alloc_nid_failed(sbi, nids[i]);
814 				err = PTR_ERR(npage[i]);
815 				goto release_pages;
816 			}
817 
818 			set_nid(parent, offset[i - 1], nids[i], i == 1);
819 			f2fs_alloc_nid_done(sbi, nids[i]);
820 			done = true;
821 		} else if (mode == LOOKUP_NODE_RA && i == level && level > 1) {
822 			npage[i] = f2fs_get_node_page_ra(parent, offset[i - 1]);
823 			if (IS_ERR(npage[i])) {
824 				err = PTR_ERR(npage[i]);
825 				goto release_pages;
826 			}
827 			done = true;
828 		}
829 		if (i == 1) {
830 			dn->inode_page_locked = false;
831 			unlock_page(parent);
832 		} else {
833 			f2fs_put_page(parent, 1);
834 		}
835 
836 		if (!done) {
837 			npage[i] = f2fs_get_node_page(sbi, nids[i]);
838 			if (IS_ERR(npage[i])) {
839 				err = PTR_ERR(npage[i]);
840 				f2fs_put_page(npage[0], 0);
841 				goto release_out;
842 			}
843 		}
844 		if (i < level) {
845 			parent = npage[i];
846 			nids[i + 1] = get_nid(parent, offset[i], false);
847 		}
848 	}
849 	dn->nid = nids[level];
850 	dn->ofs_in_node = offset[level];
851 	dn->node_page = npage[level];
852 	dn->data_blkaddr = f2fs_data_blkaddr(dn);
853 
854 	if (is_inode_flag_set(dn->inode, FI_COMPRESSED_FILE) &&
855 					f2fs_sb_has_readonly(sbi)) {
856 		unsigned int cluster_size = F2FS_I(dn->inode)->i_cluster_size;
857 		unsigned int ofs_in_node = dn->ofs_in_node;
858 		pgoff_t fofs = index;
859 		unsigned int c_len;
860 		block_t blkaddr;
861 
862 		/* should align fofs and ofs_in_node to cluster_size */
863 		if (fofs % cluster_size) {
864 			fofs = round_down(fofs, cluster_size);
865 			ofs_in_node = round_down(ofs_in_node, cluster_size);
866 		}
867 
868 		c_len = f2fs_cluster_blocks_are_contiguous(dn, ofs_in_node);
869 		if (!c_len)
870 			goto out;
871 
872 		blkaddr = data_blkaddr(dn->inode, dn->node_page, ofs_in_node);
873 		if (blkaddr == COMPRESS_ADDR)
874 			blkaddr = data_blkaddr(dn->inode, dn->node_page,
875 						ofs_in_node + 1);
876 
877 		f2fs_update_read_extent_tree_range_compressed(dn->inode,
878 					fofs, blkaddr, cluster_size, c_len);
879 	}
880 out:
881 	return 0;
882 
883 release_pages:
884 	f2fs_put_page(parent, 1);
885 	if (i > 1)
886 		f2fs_put_page(npage[0], 0);
887 release_out:
888 	dn->inode_page = NULL;
889 	dn->node_page = NULL;
890 	if (err == -ENOENT) {
891 		dn->cur_level = i;
892 		dn->max_level = level;
893 		dn->ofs_in_node = offset[level];
894 	}
895 	return err;
896 }
897 
898 static int truncate_node(struct dnode_of_data *dn)
899 {
900 	struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
901 	struct node_info ni;
902 	int err;
903 	pgoff_t index;
904 
905 	err = f2fs_get_node_info(sbi, dn->nid, &ni, false);
906 	if (err)
907 		return err;
908 
909 	if (ni.blk_addr != NEW_ADDR &&
910 		!f2fs_is_valid_blkaddr(sbi, ni.blk_addr, DATA_GENERIC_ENHANCE)) {
911 		f2fs_err_ratelimited(sbi,
912 			"nat entry is corrupted, run fsck to fix it, ino:%u, "
913 			"nid:%u, blkaddr:%u", ni.ino, ni.nid, ni.blk_addr);
914 		set_sbi_flag(sbi, SBI_NEED_FSCK);
915 		f2fs_handle_error(sbi, ERROR_INCONSISTENT_NAT);
916 		return -EFSCORRUPTED;
917 	}
918 
919 	/* Deallocate node address */
920 	f2fs_invalidate_blocks(sbi, ni.blk_addr, 1);
921 	dec_valid_node_count(sbi, dn->inode, dn->nid == dn->inode->i_ino);
922 	set_node_addr(sbi, &ni, NULL_ADDR, false);
923 
924 	if (dn->nid == dn->inode->i_ino) {
925 		f2fs_remove_orphan_inode(sbi, dn->nid);
926 		dec_valid_inode_count(sbi);
927 		f2fs_inode_synced(dn->inode);
928 	}
929 
930 	clear_node_page_dirty(dn->node_page);
931 	set_sbi_flag(sbi, SBI_IS_DIRTY);
932 
933 	index = page_folio(dn->node_page)->index;
934 	f2fs_put_page(dn->node_page, 1);
935 
936 	invalidate_mapping_pages(NODE_MAPPING(sbi),
937 			index, index);
938 
939 	dn->node_page = NULL;
940 	trace_f2fs_truncate_node(dn->inode, dn->nid, ni.blk_addr);
941 
942 	return 0;
943 }
944 
945 static int truncate_dnode(struct dnode_of_data *dn)
946 {
947 	struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
948 	struct page *page;
949 	int err;
950 
951 	if (dn->nid == 0)
952 		return 1;
953 
954 	/* get direct node */
955 	page = f2fs_get_node_page(sbi, dn->nid);
956 	if (PTR_ERR(page) == -ENOENT)
957 		return 1;
958 	else if (IS_ERR(page))
959 		return PTR_ERR(page);
960 
961 	if (IS_INODE(page) || ino_of_node(page) != dn->inode->i_ino) {
962 		f2fs_err(sbi, "incorrect node reference, ino: %lu, nid: %u, ino_of_node: %u",
963 				dn->inode->i_ino, dn->nid, ino_of_node(page));
964 		set_sbi_flag(sbi, SBI_NEED_FSCK);
965 		f2fs_handle_error(sbi, ERROR_INVALID_NODE_REFERENCE);
966 		f2fs_put_page(page, 1);
967 		return -EFSCORRUPTED;
968 	}
969 
970 	/* Make dnode_of_data for parameter */
971 	dn->node_page = page;
972 	dn->ofs_in_node = 0;
973 	f2fs_truncate_data_blocks_range(dn, ADDRS_PER_BLOCK(dn->inode));
974 	err = truncate_node(dn);
975 	if (err) {
976 		f2fs_put_page(page, 1);
977 		return err;
978 	}
979 
980 	return 1;
981 }
982 
983 static int truncate_nodes(struct dnode_of_data *dn, unsigned int nofs,
984 						int ofs, int depth)
985 {
986 	struct dnode_of_data rdn = *dn;
987 	struct page *page;
988 	struct f2fs_node *rn;
989 	nid_t child_nid;
990 	unsigned int child_nofs;
991 	int freed = 0;
992 	int i, ret;
993 
994 	if (dn->nid == 0)
995 		return NIDS_PER_BLOCK + 1;
996 
997 	trace_f2fs_truncate_nodes_enter(dn->inode, dn->nid, dn->data_blkaddr);
998 
999 	page = f2fs_get_node_page(F2FS_I_SB(dn->inode), dn->nid);
1000 	if (IS_ERR(page)) {
1001 		trace_f2fs_truncate_nodes_exit(dn->inode, PTR_ERR(page));
1002 		return PTR_ERR(page);
1003 	}
1004 
1005 	f2fs_ra_node_pages(page, ofs, NIDS_PER_BLOCK);
1006 
1007 	rn = F2FS_NODE(page);
1008 	if (depth < 3) {
1009 		for (i = ofs; i < NIDS_PER_BLOCK; i++, freed++) {
1010 			child_nid = le32_to_cpu(rn->in.nid[i]);
1011 			if (child_nid == 0)
1012 				continue;
1013 			rdn.nid = child_nid;
1014 			ret = truncate_dnode(&rdn);
1015 			if (ret < 0)
1016 				goto out_err;
1017 			if (set_nid(page, i, 0, false))
1018 				dn->node_changed = true;
1019 		}
1020 	} else {
1021 		child_nofs = nofs + ofs * (NIDS_PER_BLOCK + 1) + 1;
1022 		for (i = ofs; i < NIDS_PER_BLOCK; i++) {
1023 			child_nid = le32_to_cpu(rn->in.nid[i]);
1024 			if (child_nid == 0) {
1025 				child_nofs += NIDS_PER_BLOCK + 1;
1026 				continue;
1027 			}
1028 			rdn.nid = child_nid;
1029 			ret = truncate_nodes(&rdn, child_nofs, 0, depth - 1);
1030 			if (ret == (NIDS_PER_BLOCK + 1)) {
1031 				if (set_nid(page, i, 0, false))
1032 					dn->node_changed = true;
1033 				child_nofs += ret;
1034 			} else if (ret < 0 && ret != -ENOENT) {
1035 				goto out_err;
1036 			}
1037 		}
1038 		freed = child_nofs;
1039 	}
1040 
1041 	if (!ofs) {
1042 		/* remove current indirect node */
1043 		dn->node_page = page;
1044 		ret = truncate_node(dn);
1045 		if (ret)
1046 			goto out_err;
1047 		freed++;
1048 	} else {
1049 		f2fs_put_page(page, 1);
1050 	}
1051 	trace_f2fs_truncate_nodes_exit(dn->inode, freed);
1052 	return freed;
1053 
1054 out_err:
1055 	f2fs_put_page(page, 1);
1056 	trace_f2fs_truncate_nodes_exit(dn->inode, ret);
1057 	return ret;
1058 }
1059 
1060 static int truncate_partial_nodes(struct dnode_of_data *dn,
1061 			struct f2fs_inode *ri, int *offset, int depth)
1062 {
1063 	struct page *pages[2];
1064 	nid_t nid[3];
1065 	nid_t child_nid;
1066 	int err = 0;
1067 	int i;
1068 	int idx = depth - 2;
1069 
1070 	nid[0] = get_nid(dn->inode_page, offset[0], true);
1071 	if (!nid[0])
1072 		return 0;
1073 
1074 	/* get indirect nodes in the path */
1075 	for (i = 0; i < idx + 1; i++) {
1076 		/* reference count'll be increased */
1077 		pages[i] = f2fs_get_node_page(F2FS_I_SB(dn->inode), nid[i]);
1078 		if (IS_ERR(pages[i])) {
1079 			err = PTR_ERR(pages[i]);
1080 			idx = i - 1;
1081 			goto fail;
1082 		}
1083 		nid[i + 1] = get_nid(pages[i], offset[i + 1], false);
1084 	}
1085 
1086 	f2fs_ra_node_pages(pages[idx], offset[idx + 1], NIDS_PER_BLOCK);
1087 
1088 	/* free direct nodes linked to a partial indirect node */
1089 	for (i = offset[idx + 1]; i < NIDS_PER_BLOCK; i++) {
1090 		child_nid = get_nid(pages[idx], i, false);
1091 		if (!child_nid)
1092 			continue;
1093 		dn->nid = child_nid;
1094 		err = truncate_dnode(dn);
1095 		if (err < 0)
1096 			goto fail;
1097 		if (set_nid(pages[idx], i, 0, false))
1098 			dn->node_changed = true;
1099 	}
1100 
1101 	if (offset[idx + 1] == 0) {
1102 		dn->node_page = pages[idx];
1103 		dn->nid = nid[idx];
1104 		err = truncate_node(dn);
1105 		if (err)
1106 			goto fail;
1107 	} else {
1108 		f2fs_put_page(pages[idx], 1);
1109 	}
1110 	offset[idx]++;
1111 	offset[idx + 1] = 0;
1112 	idx--;
1113 fail:
1114 	for (i = idx; i >= 0; i--)
1115 		f2fs_put_page(pages[i], 1);
1116 
1117 	trace_f2fs_truncate_partial_nodes(dn->inode, nid, depth, err);
1118 
1119 	return err;
1120 }
1121 
1122 /*
1123  * All the block addresses of data and nodes should be nullified.
1124  */
1125 int f2fs_truncate_inode_blocks(struct inode *inode, pgoff_t from)
1126 {
1127 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1128 	int err = 0, cont = 1;
1129 	int level, offset[4], noffset[4];
1130 	unsigned int nofs = 0;
1131 	struct f2fs_inode *ri;
1132 	struct dnode_of_data dn;
1133 	struct page *page;
1134 
1135 	trace_f2fs_truncate_inode_blocks_enter(inode, from);
1136 
1137 	level = get_node_path(inode, from, offset, noffset);
1138 	if (level < 0) {
1139 		trace_f2fs_truncate_inode_blocks_exit(inode, level);
1140 		return level;
1141 	}
1142 
1143 	page = f2fs_get_node_page(sbi, inode->i_ino);
1144 	if (IS_ERR(page)) {
1145 		trace_f2fs_truncate_inode_blocks_exit(inode, PTR_ERR(page));
1146 		return PTR_ERR(page);
1147 	}
1148 
1149 	set_new_dnode(&dn, inode, page, NULL, 0);
1150 	unlock_page(page);
1151 
1152 	ri = F2FS_INODE(page);
1153 	switch (level) {
1154 	case 0:
1155 	case 1:
1156 		nofs = noffset[1];
1157 		break;
1158 	case 2:
1159 		nofs = noffset[1];
1160 		if (!offset[level - 1])
1161 			goto skip_partial;
1162 		err = truncate_partial_nodes(&dn, ri, offset, level);
1163 		if (err < 0 && err != -ENOENT)
1164 			goto fail;
1165 		nofs += 1 + NIDS_PER_BLOCK;
1166 		break;
1167 	case 3:
1168 		nofs = 5 + 2 * NIDS_PER_BLOCK;
1169 		if (!offset[level - 1])
1170 			goto skip_partial;
1171 		err = truncate_partial_nodes(&dn, ri, offset, level);
1172 		if (err < 0 && err != -ENOENT)
1173 			goto fail;
1174 		break;
1175 	default:
1176 		BUG();
1177 	}
1178 
1179 skip_partial:
1180 	while (cont) {
1181 		dn.nid = get_nid(page, offset[0], true);
1182 		switch (offset[0]) {
1183 		case NODE_DIR1_BLOCK:
1184 		case NODE_DIR2_BLOCK:
1185 			err = truncate_dnode(&dn);
1186 			break;
1187 
1188 		case NODE_IND1_BLOCK:
1189 		case NODE_IND2_BLOCK:
1190 			err = truncate_nodes(&dn, nofs, offset[1], 2);
1191 			break;
1192 
1193 		case NODE_DIND_BLOCK:
1194 			err = truncate_nodes(&dn, nofs, offset[1], 3);
1195 			cont = 0;
1196 			break;
1197 
1198 		default:
1199 			BUG();
1200 		}
1201 		if (err == -ENOENT) {
1202 			set_sbi_flag(F2FS_P_SB(page), SBI_NEED_FSCK);
1203 			f2fs_handle_error(sbi, ERROR_INVALID_BLKADDR);
1204 			f2fs_err_ratelimited(sbi,
1205 				"truncate node fail, ino:%lu, nid:%u, "
1206 				"offset[0]:%d, offset[1]:%d, nofs:%d",
1207 				inode->i_ino, dn.nid, offset[0],
1208 				offset[1], nofs);
1209 			err = 0;
1210 		}
1211 		if (err < 0)
1212 			goto fail;
1213 		if (offset[1] == 0 && get_nid(page, offset[0], true)) {
1214 			lock_page(page);
1215 			BUG_ON(page->mapping != NODE_MAPPING(sbi));
1216 			set_nid(page, offset[0], 0, true);
1217 			unlock_page(page);
1218 		}
1219 		offset[1] = 0;
1220 		offset[0]++;
1221 		nofs += err;
1222 	}
1223 fail:
1224 	f2fs_put_page(page, 0);
1225 	trace_f2fs_truncate_inode_blocks_exit(inode, err);
1226 	return err > 0 ? 0 : err;
1227 }
1228 
1229 /* caller must lock inode page */
1230 int f2fs_truncate_xattr_node(struct inode *inode)
1231 {
1232 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1233 	nid_t nid = F2FS_I(inode)->i_xattr_nid;
1234 	struct dnode_of_data dn;
1235 	struct page *npage;
1236 	int err;
1237 
1238 	if (!nid)
1239 		return 0;
1240 
1241 	npage = f2fs_get_node_page(sbi, nid);
1242 	if (IS_ERR(npage))
1243 		return PTR_ERR(npage);
1244 
1245 	set_new_dnode(&dn, inode, NULL, npage, nid);
1246 	err = truncate_node(&dn);
1247 	if (err) {
1248 		f2fs_put_page(npage, 1);
1249 		return err;
1250 	}
1251 
1252 	f2fs_i_xnid_write(inode, 0);
1253 
1254 	return 0;
1255 }
1256 
1257 /*
1258  * Caller should grab and release a rwsem by calling f2fs_lock_op() and
1259  * f2fs_unlock_op().
1260  */
1261 int f2fs_remove_inode_page(struct inode *inode)
1262 {
1263 	struct dnode_of_data dn;
1264 	int err;
1265 
1266 	set_new_dnode(&dn, inode, NULL, NULL, inode->i_ino);
1267 	err = f2fs_get_dnode_of_data(&dn, 0, LOOKUP_NODE);
1268 	if (err)
1269 		return err;
1270 
1271 	err = f2fs_truncate_xattr_node(inode);
1272 	if (err) {
1273 		f2fs_put_dnode(&dn);
1274 		return err;
1275 	}
1276 
1277 	/* remove potential inline_data blocks */
1278 	if (!IS_DEVICE_ALIASING(inode) &&
1279 	    (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
1280 	     S_ISLNK(inode->i_mode)))
1281 		f2fs_truncate_data_blocks_range(&dn, 1);
1282 
1283 	/* 0 is possible, after f2fs_new_inode() has failed */
1284 	if (unlikely(f2fs_cp_error(F2FS_I_SB(inode)))) {
1285 		f2fs_put_dnode(&dn);
1286 		return -EIO;
1287 	}
1288 
1289 	if (unlikely(inode->i_blocks != 0 && inode->i_blocks != 8)) {
1290 		f2fs_warn(F2FS_I_SB(inode),
1291 			"f2fs_remove_inode_page: inconsistent i_blocks, ino:%lu, iblocks:%llu",
1292 			inode->i_ino, (unsigned long long)inode->i_blocks);
1293 		set_sbi_flag(F2FS_I_SB(inode), SBI_NEED_FSCK);
1294 	}
1295 
1296 	/* will put inode & node pages */
1297 	err = truncate_node(&dn);
1298 	if (err) {
1299 		f2fs_put_dnode(&dn);
1300 		return err;
1301 	}
1302 	return 0;
1303 }
1304 
1305 struct page *f2fs_new_inode_page(struct inode *inode)
1306 {
1307 	struct dnode_of_data dn;
1308 
1309 	/* allocate inode page for new inode */
1310 	set_new_dnode(&dn, inode, NULL, NULL, inode->i_ino);
1311 
1312 	/* caller should f2fs_put_page(page, 1); */
1313 	return f2fs_new_node_page(&dn, 0);
1314 }
1315 
1316 struct page *f2fs_new_node_page(struct dnode_of_data *dn, unsigned int ofs)
1317 {
1318 	struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
1319 	struct node_info new_ni;
1320 	struct page *page;
1321 	int err;
1322 
1323 	if (unlikely(is_inode_flag_set(dn->inode, FI_NO_ALLOC)))
1324 		return ERR_PTR(-EPERM);
1325 
1326 	page = f2fs_grab_cache_page(NODE_MAPPING(sbi), dn->nid, false);
1327 	if (!page)
1328 		return ERR_PTR(-ENOMEM);
1329 
1330 	if (unlikely((err = inc_valid_node_count(sbi, dn->inode, !ofs))))
1331 		goto fail;
1332 
1333 #ifdef CONFIG_F2FS_CHECK_FS
1334 	err = f2fs_get_node_info(sbi, dn->nid, &new_ni, false);
1335 	if (err) {
1336 		dec_valid_node_count(sbi, dn->inode, !ofs);
1337 		goto fail;
1338 	}
1339 	if (unlikely(new_ni.blk_addr != NULL_ADDR)) {
1340 		err = -EFSCORRUPTED;
1341 		dec_valid_node_count(sbi, dn->inode, !ofs);
1342 		set_sbi_flag(sbi, SBI_NEED_FSCK);
1343 		f2fs_warn_ratelimited(sbi,
1344 			"f2fs_new_node_page: inconsistent nat entry, "
1345 			"ino:%u, nid:%u, blkaddr:%u, ver:%u, flag:%u",
1346 			new_ni.ino, new_ni.nid, new_ni.blk_addr,
1347 			new_ni.version, new_ni.flag);
1348 		f2fs_handle_error(sbi, ERROR_INCONSISTENT_NAT);
1349 		goto fail;
1350 	}
1351 #endif
1352 	new_ni.nid = dn->nid;
1353 	new_ni.ino = dn->inode->i_ino;
1354 	new_ni.blk_addr = NULL_ADDR;
1355 	new_ni.flag = 0;
1356 	new_ni.version = 0;
1357 	set_node_addr(sbi, &new_ni, NEW_ADDR, false);
1358 
1359 	f2fs_wait_on_page_writeback(page, NODE, true, true);
1360 	fill_node_footer(page, dn->nid, dn->inode->i_ino, ofs, true);
1361 	set_cold_node(page, S_ISDIR(dn->inode->i_mode));
1362 	if (!PageUptodate(page))
1363 		SetPageUptodate(page);
1364 	if (set_page_dirty(page))
1365 		dn->node_changed = true;
1366 
1367 	if (f2fs_has_xattr_block(ofs))
1368 		f2fs_i_xnid_write(dn->inode, dn->nid);
1369 
1370 	if (ofs == 0)
1371 		inc_valid_inode_count(sbi);
1372 	return page;
1373 fail:
1374 	clear_node_page_dirty(page);
1375 	f2fs_put_page(page, 1);
1376 	return ERR_PTR(err);
1377 }
1378 
1379 /*
1380  * Caller should do after getting the following values.
1381  * 0: f2fs_put_page(page, 0)
1382  * LOCKED_PAGE or error: f2fs_put_page(page, 1)
1383  */
1384 static int read_node_page(struct page *page, blk_opf_t op_flags)
1385 {
1386 	struct folio *folio = page_folio(page);
1387 	struct f2fs_sb_info *sbi = F2FS_P_SB(page);
1388 	struct node_info ni;
1389 	struct f2fs_io_info fio = {
1390 		.sbi = sbi,
1391 		.type = NODE,
1392 		.op = REQ_OP_READ,
1393 		.op_flags = op_flags,
1394 		.page = page,
1395 		.encrypted_page = NULL,
1396 	};
1397 	int err;
1398 
1399 	if (folio_test_uptodate(folio)) {
1400 		if (!f2fs_inode_chksum_verify(sbi, page)) {
1401 			folio_clear_uptodate(folio);
1402 			return -EFSBADCRC;
1403 		}
1404 		return LOCKED_PAGE;
1405 	}
1406 
1407 	err = f2fs_get_node_info(sbi, folio->index, &ni, false);
1408 	if (err)
1409 		return err;
1410 
1411 	/* NEW_ADDR can be seen, after cp_error drops some dirty node pages */
1412 	if (unlikely(ni.blk_addr == NULL_ADDR || ni.blk_addr == NEW_ADDR)) {
1413 		folio_clear_uptodate(folio);
1414 		return -ENOENT;
1415 	}
1416 
1417 	fio.new_blkaddr = fio.old_blkaddr = ni.blk_addr;
1418 
1419 	err = f2fs_submit_page_bio(&fio);
1420 
1421 	if (!err)
1422 		f2fs_update_iostat(sbi, NULL, FS_NODE_READ_IO, F2FS_BLKSIZE);
1423 
1424 	return err;
1425 }
1426 
1427 /*
1428  * Readahead a node page
1429  */
1430 void f2fs_ra_node_page(struct f2fs_sb_info *sbi, nid_t nid)
1431 {
1432 	struct page *apage;
1433 	int err;
1434 
1435 	if (!nid)
1436 		return;
1437 	if (f2fs_check_nid_range(sbi, nid))
1438 		return;
1439 
1440 	apage = xa_load(&NODE_MAPPING(sbi)->i_pages, nid);
1441 	if (apage)
1442 		return;
1443 
1444 	apage = f2fs_grab_cache_page(NODE_MAPPING(sbi), nid, false);
1445 	if (!apage)
1446 		return;
1447 
1448 	err = read_node_page(apage, REQ_RAHEAD);
1449 	f2fs_put_page(apage, err ? 1 : 0);
1450 }
1451 
1452 static struct page *__get_node_page(struct f2fs_sb_info *sbi, pgoff_t nid,
1453 					struct page *parent, int start)
1454 {
1455 	struct page *page;
1456 	int err;
1457 
1458 	if (!nid)
1459 		return ERR_PTR(-ENOENT);
1460 	if (f2fs_check_nid_range(sbi, nid))
1461 		return ERR_PTR(-EINVAL);
1462 repeat:
1463 	page = f2fs_grab_cache_page(NODE_MAPPING(sbi), nid, false);
1464 	if (!page)
1465 		return ERR_PTR(-ENOMEM);
1466 
1467 	err = read_node_page(page, 0);
1468 	if (err < 0) {
1469 		goto out_put_err;
1470 	} else if (err == LOCKED_PAGE) {
1471 		err = 0;
1472 		goto page_hit;
1473 	}
1474 
1475 	if (parent)
1476 		f2fs_ra_node_pages(parent, start + 1, MAX_RA_NODE);
1477 
1478 	lock_page(page);
1479 
1480 	if (unlikely(page->mapping != NODE_MAPPING(sbi))) {
1481 		f2fs_put_page(page, 1);
1482 		goto repeat;
1483 	}
1484 
1485 	if (unlikely(!PageUptodate(page))) {
1486 		err = -EIO;
1487 		goto out_err;
1488 	}
1489 
1490 	if (!f2fs_inode_chksum_verify(sbi, page)) {
1491 		err = -EFSBADCRC;
1492 		goto out_err;
1493 	}
1494 page_hit:
1495 	if (likely(nid == nid_of_node(page)))
1496 		return page;
1497 
1498 	f2fs_warn(sbi, "inconsistent node block, nid:%lu, node_footer[nid:%u,ino:%u,ofs:%u,cpver:%llu,blkaddr:%u]",
1499 			  nid, nid_of_node(page), ino_of_node(page),
1500 			  ofs_of_node(page), cpver_of_node(page),
1501 			  next_blkaddr_of_node(page));
1502 	set_sbi_flag(sbi, SBI_NEED_FSCK);
1503 	f2fs_handle_error(sbi, ERROR_INCONSISTENT_FOOTER);
1504 	err = -EFSCORRUPTED;
1505 out_err:
1506 	ClearPageUptodate(page);
1507 out_put_err:
1508 	/* ENOENT comes from read_node_page which is not an error. */
1509 	if (err != -ENOENT)
1510 		f2fs_handle_page_eio(sbi, page_folio(page), NODE);
1511 	f2fs_put_page(page, 1);
1512 	return ERR_PTR(err);
1513 }
1514 
1515 struct page *f2fs_get_node_page(struct f2fs_sb_info *sbi, pgoff_t nid)
1516 {
1517 	return __get_node_page(sbi, nid, NULL, 0);
1518 }
1519 
1520 struct page *f2fs_get_node_page_ra(struct page *parent, int start)
1521 {
1522 	struct f2fs_sb_info *sbi = F2FS_P_SB(parent);
1523 	nid_t nid = get_nid(parent, start, false);
1524 
1525 	return __get_node_page(sbi, nid, parent, start);
1526 }
1527 
1528 static void flush_inline_data(struct f2fs_sb_info *sbi, nid_t ino)
1529 {
1530 	struct inode *inode;
1531 	struct page *page;
1532 	int ret;
1533 
1534 	/* should flush inline_data before evict_inode */
1535 	inode = ilookup(sbi->sb, ino);
1536 	if (!inode)
1537 		return;
1538 
1539 	page = f2fs_pagecache_get_page(inode->i_mapping, 0,
1540 					FGP_LOCK|FGP_NOWAIT, 0);
1541 	if (!page)
1542 		goto iput_out;
1543 
1544 	if (!PageUptodate(page))
1545 		goto page_out;
1546 
1547 	if (!PageDirty(page))
1548 		goto page_out;
1549 
1550 	if (!clear_page_dirty_for_io(page))
1551 		goto page_out;
1552 
1553 	ret = f2fs_write_inline_data(inode, page_folio(page));
1554 	inode_dec_dirty_pages(inode);
1555 	f2fs_remove_dirty_inode(inode);
1556 	if (ret)
1557 		set_page_dirty(page);
1558 page_out:
1559 	f2fs_put_page(page, 1);
1560 iput_out:
1561 	iput(inode);
1562 }
1563 
1564 static struct page *last_fsync_dnode(struct f2fs_sb_info *sbi, nid_t ino)
1565 {
1566 	pgoff_t index;
1567 	struct folio_batch fbatch;
1568 	struct page *last_page = NULL;
1569 	int nr_folios;
1570 
1571 	folio_batch_init(&fbatch);
1572 	index = 0;
1573 
1574 	while ((nr_folios = filemap_get_folios_tag(NODE_MAPPING(sbi), &index,
1575 					(pgoff_t)-1, PAGECACHE_TAG_DIRTY,
1576 					&fbatch))) {
1577 		int i;
1578 
1579 		for (i = 0; i < nr_folios; i++) {
1580 			struct page *page = &fbatch.folios[i]->page;
1581 
1582 			if (unlikely(f2fs_cp_error(sbi))) {
1583 				f2fs_put_page(last_page, 0);
1584 				folio_batch_release(&fbatch);
1585 				return ERR_PTR(-EIO);
1586 			}
1587 
1588 			if (!IS_DNODE(page) || !is_cold_node(page))
1589 				continue;
1590 			if (ino_of_node(page) != ino)
1591 				continue;
1592 
1593 			lock_page(page);
1594 
1595 			if (unlikely(page->mapping != NODE_MAPPING(sbi))) {
1596 continue_unlock:
1597 				unlock_page(page);
1598 				continue;
1599 			}
1600 			if (ino_of_node(page) != ino)
1601 				goto continue_unlock;
1602 
1603 			if (!PageDirty(page)) {
1604 				/* someone wrote it for us */
1605 				goto continue_unlock;
1606 			}
1607 
1608 			if (last_page)
1609 				f2fs_put_page(last_page, 0);
1610 
1611 			get_page(page);
1612 			last_page = page;
1613 			unlock_page(page);
1614 		}
1615 		folio_batch_release(&fbatch);
1616 		cond_resched();
1617 	}
1618 	return last_page;
1619 }
1620 
1621 static int __write_node_page(struct page *page, bool atomic, bool *submitted,
1622 				struct writeback_control *wbc, bool do_balance,
1623 				enum iostat_type io_type, unsigned int *seq_id)
1624 {
1625 	struct f2fs_sb_info *sbi = F2FS_P_SB(page);
1626 	struct folio *folio = page_folio(page);
1627 	nid_t nid;
1628 	struct node_info ni;
1629 	struct f2fs_io_info fio = {
1630 		.sbi = sbi,
1631 		.ino = ino_of_node(page),
1632 		.type = NODE,
1633 		.op = REQ_OP_WRITE,
1634 		.op_flags = wbc_to_write_flags(wbc),
1635 		.page = page,
1636 		.encrypted_page = NULL,
1637 		.submitted = 0,
1638 		.io_type = io_type,
1639 		.io_wbc = wbc,
1640 	};
1641 	unsigned int seq;
1642 
1643 	trace_f2fs_writepage(folio, NODE);
1644 
1645 	if (unlikely(f2fs_cp_error(sbi))) {
1646 		/* keep node pages in remount-ro mode */
1647 		if (F2FS_OPTION(sbi).errors == MOUNT_ERRORS_READONLY)
1648 			goto redirty_out;
1649 		folio_clear_uptodate(folio);
1650 		dec_page_count(sbi, F2FS_DIRTY_NODES);
1651 		folio_unlock(folio);
1652 		return 0;
1653 	}
1654 
1655 	if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
1656 		goto redirty_out;
1657 
1658 	if (!is_sbi_flag_set(sbi, SBI_CP_DISABLED) &&
1659 			wbc->sync_mode == WB_SYNC_NONE &&
1660 			IS_DNODE(page) && is_cold_node(page))
1661 		goto redirty_out;
1662 
1663 	/* get old block addr of this node page */
1664 	nid = nid_of_node(page);
1665 	f2fs_bug_on(sbi, folio->index != nid);
1666 
1667 	if (f2fs_get_node_info(sbi, nid, &ni, !do_balance))
1668 		goto redirty_out;
1669 
1670 	if (wbc->for_reclaim) {
1671 		if (!f2fs_down_read_trylock(&sbi->node_write))
1672 			goto redirty_out;
1673 	} else {
1674 		f2fs_down_read(&sbi->node_write);
1675 	}
1676 
1677 	/* This page is already truncated */
1678 	if (unlikely(ni.blk_addr == NULL_ADDR)) {
1679 		folio_clear_uptodate(folio);
1680 		dec_page_count(sbi, F2FS_DIRTY_NODES);
1681 		f2fs_up_read(&sbi->node_write);
1682 		folio_unlock(folio);
1683 		return 0;
1684 	}
1685 
1686 	if (__is_valid_data_blkaddr(ni.blk_addr) &&
1687 		!f2fs_is_valid_blkaddr(sbi, ni.blk_addr,
1688 					DATA_GENERIC_ENHANCE)) {
1689 		f2fs_up_read(&sbi->node_write);
1690 		goto redirty_out;
1691 	}
1692 
1693 	if (atomic && !test_opt(sbi, NOBARRIER))
1694 		fio.op_flags |= REQ_PREFLUSH | REQ_FUA;
1695 
1696 	/* should add to global list before clearing PAGECACHE status */
1697 	if (f2fs_in_warm_node_list(sbi, page)) {
1698 		seq = f2fs_add_fsync_node_entry(sbi, page);
1699 		if (seq_id)
1700 			*seq_id = seq;
1701 	}
1702 
1703 	folio_start_writeback(folio);
1704 
1705 	fio.old_blkaddr = ni.blk_addr;
1706 	f2fs_do_write_node_page(nid, &fio);
1707 	set_node_addr(sbi, &ni, fio.new_blkaddr, is_fsync_dnode(page));
1708 	dec_page_count(sbi, F2FS_DIRTY_NODES);
1709 	f2fs_up_read(&sbi->node_write);
1710 
1711 	if (wbc->for_reclaim) {
1712 		f2fs_submit_merged_write_cond(sbi, NULL, page, 0, NODE);
1713 		submitted = NULL;
1714 	}
1715 
1716 	folio_unlock(folio);
1717 
1718 	if (unlikely(f2fs_cp_error(sbi))) {
1719 		f2fs_submit_merged_write(sbi, NODE);
1720 		submitted = NULL;
1721 	}
1722 	if (submitted)
1723 		*submitted = fio.submitted;
1724 
1725 	if (do_balance)
1726 		f2fs_balance_fs(sbi, false);
1727 	return 0;
1728 
1729 redirty_out:
1730 	folio_redirty_for_writepage(wbc, folio);
1731 	return AOP_WRITEPAGE_ACTIVATE;
1732 }
1733 
1734 int f2fs_move_node_page(struct page *node_page, int gc_type)
1735 {
1736 	int err = 0;
1737 
1738 	if (gc_type == FG_GC) {
1739 		struct writeback_control wbc = {
1740 			.sync_mode = WB_SYNC_ALL,
1741 			.nr_to_write = 1,
1742 			.for_reclaim = 0,
1743 		};
1744 
1745 		f2fs_wait_on_page_writeback(node_page, NODE, true, true);
1746 
1747 		set_page_dirty(node_page);
1748 
1749 		if (!clear_page_dirty_for_io(node_page)) {
1750 			err = -EAGAIN;
1751 			goto out_page;
1752 		}
1753 
1754 		if (__write_node_page(node_page, false, NULL,
1755 					&wbc, false, FS_GC_NODE_IO, NULL)) {
1756 			err = -EAGAIN;
1757 			unlock_page(node_page);
1758 		}
1759 		goto release_page;
1760 	} else {
1761 		/* set page dirty and write it */
1762 		if (!folio_test_writeback(page_folio(node_page)))
1763 			set_page_dirty(node_page);
1764 	}
1765 out_page:
1766 	unlock_page(node_page);
1767 release_page:
1768 	f2fs_put_page(node_page, 0);
1769 	return err;
1770 }
1771 
1772 static int f2fs_write_node_page(struct page *page,
1773 				struct writeback_control *wbc)
1774 {
1775 	return __write_node_page(page, false, NULL, wbc, false,
1776 						FS_NODE_IO, NULL);
1777 }
1778 
1779 int f2fs_fsync_node_pages(struct f2fs_sb_info *sbi, struct inode *inode,
1780 			struct writeback_control *wbc, bool atomic,
1781 			unsigned int *seq_id)
1782 {
1783 	pgoff_t index;
1784 	struct folio_batch fbatch;
1785 	int ret = 0;
1786 	struct page *last_page = NULL;
1787 	bool marked = false;
1788 	nid_t ino = inode->i_ino;
1789 	int nr_folios;
1790 	int nwritten = 0;
1791 
1792 	if (atomic) {
1793 		last_page = last_fsync_dnode(sbi, ino);
1794 		if (IS_ERR_OR_NULL(last_page))
1795 			return PTR_ERR_OR_ZERO(last_page);
1796 	}
1797 retry:
1798 	folio_batch_init(&fbatch);
1799 	index = 0;
1800 
1801 	while ((nr_folios = filemap_get_folios_tag(NODE_MAPPING(sbi), &index,
1802 					(pgoff_t)-1, PAGECACHE_TAG_DIRTY,
1803 					&fbatch))) {
1804 		int i;
1805 
1806 		for (i = 0; i < nr_folios; i++) {
1807 			struct page *page = &fbatch.folios[i]->page;
1808 			bool submitted = false;
1809 
1810 			if (unlikely(f2fs_cp_error(sbi))) {
1811 				f2fs_put_page(last_page, 0);
1812 				folio_batch_release(&fbatch);
1813 				ret = -EIO;
1814 				goto out;
1815 			}
1816 
1817 			if (!IS_DNODE(page) || !is_cold_node(page))
1818 				continue;
1819 			if (ino_of_node(page) != ino)
1820 				continue;
1821 
1822 			lock_page(page);
1823 
1824 			if (unlikely(page->mapping != NODE_MAPPING(sbi))) {
1825 continue_unlock:
1826 				unlock_page(page);
1827 				continue;
1828 			}
1829 			if (ino_of_node(page) != ino)
1830 				goto continue_unlock;
1831 
1832 			if (!PageDirty(page) && page != last_page) {
1833 				/* someone wrote it for us */
1834 				goto continue_unlock;
1835 			}
1836 
1837 			f2fs_wait_on_page_writeback(page, NODE, true, true);
1838 
1839 			set_fsync_mark(page, 0);
1840 			set_dentry_mark(page, 0);
1841 
1842 			if (!atomic || page == last_page) {
1843 				set_fsync_mark(page, 1);
1844 				percpu_counter_inc(&sbi->rf_node_block_count);
1845 				if (IS_INODE(page)) {
1846 					if (is_inode_flag_set(inode,
1847 								FI_DIRTY_INODE))
1848 						f2fs_update_inode(inode, page);
1849 					set_dentry_mark(page,
1850 						f2fs_need_dentry_mark(sbi, ino));
1851 				}
1852 				/* may be written by other thread */
1853 				if (!PageDirty(page))
1854 					set_page_dirty(page);
1855 			}
1856 
1857 			if (!clear_page_dirty_for_io(page))
1858 				goto continue_unlock;
1859 
1860 			ret = __write_node_page(page, atomic &&
1861 						page == last_page,
1862 						&submitted, wbc, true,
1863 						FS_NODE_IO, seq_id);
1864 			if (ret) {
1865 				unlock_page(page);
1866 				f2fs_put_page(last_page, 0);
1867 				break;
1868 			} else if (submitted) {
1869 				nwritten++;
1870 			}
1871 
1872 			if (page == last_page) {
1873 				f2fs_put_page(page, 0);
1874 				marked = true;
1875 				break;
1876 			}
1877 		}
1878 		folio_batch_release(&fbatch);
1879 		cond_resched();
1880 
1881 		if (ret || marked)
1882 			break;
1883 	}
1884 	if (!ret && atomic && !marked) {
1885 		f2fs_debug(sbi, "Retry to write fsync mark: ino=%u, idx=%lx",
1886 			   ino, page_folio(last_page)->index);
1887 		lock_page(last_page);
1888 		f2fs_wait_on_page_writeback(last_page, NODE, true, true);
1889 		set_page_dirty(last_page);
1890 		unlock_page(last_page);
1891 		goto retry;
1892 	}
1893 out:
1894 	if (nwritten)
1895 		f2fs_submit_merged_write_cond(sbi, NULL, NULL, ino, NODE);
1896 	return ret ? -EIO : 0;
1897 }
1898 
1899 static int f2fs_match_ino(struct inode *inode, unsigned long ino, void *data)
1900 {
1901 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1902 	bool clean;
1903 
1904 	if (inode->i_ino != ino)
1905 		return 0;
1906 
1907 	if (!is_inode_flag_set(inode, FI_DIRTY_INODE))
1908 		return 0;
1909 
1910 	spin_lock(&sbi->inode_lock[DIRTY_META]);
1911 	clean = list_empty(&F2FS_I(inode)->gdirty_list);
1912 	spin_unlock(&sbi->inode_lock[DIRTY_META]);
1913 
1914 	if (clean)
1915 		return 0;
1916 
1917 	inode = igrab(inode);
1918 	if (!inode)
1919 		return 0;
1920 	return 1;
1921 }
1922 
1923 static bool flush_dirty_inode(struct page *page)
1924 {
1925 	struct f2fs_sb_info *sbi = F2FS_P_SB(page);
1926 	struct inode *inode;
1927 	nid_t ino = ino_of_node(page);
1928 
1929 	inode = find_inode_nowait(sbi->sb, ino, f2fs_match_ino, NULL);
1930 	if (!inode)
1931 		return false;
1932 
1933 	f2fs_update_inode(inode, page);
1934 	unlock_page(page);
1935 
1936 	iput(inode);
1937 	return true;
1938 }
1939 
1940 void f2fs_flush_inline_data(struct f2fs_sb_info *sbi)
1941 {
1942 	pgoff_t index = 0;
1943 	struct folio_batch fbatch;
1944 	int nr_folios;
1945 
1946 	folio_batch_init(&fbatch);
1947 
1948 	while ((nr_folios = filemap_get_folios_tag(NODE_MAPPING(sbi), &index,
1949 					(pgoff_t)-1, PAGECACHE_TAG_DIRTY,
1950 					&fbatch))) {
1951 		int i;
1952 
1953 		for (i = 0; i < nr_folios; i++) {
1954 			struct page *page = &fbatch.folios[i]->page;
1955 
1956 			if (!IS_INODE(page))
1957 				continue;
1958 
1959 			lock_page(page);
1960 
1961 			if (unlikely(page->mapping != NODE_MAPPING(sbi))) {
1962 continue_unlock:
1963 				unlock_page(page);
1964 				continue;
1965 			}
1966 
1967 			if (!PageDirty(page)) {
1968 				/* someone wrote it for us */
1969 				goto continue_unlock;
1970 			}
1971 
1972 			/* flush inline_data, if it's async context. */
1973 			if (page_private_inline(page)) {
1974 				clear_page_private_inline(page);
1975 				unlock_page(page);
1976 				flush_inline_data(sbi, ino_of_node(page));
1977 				continue;
1978 			}
1979 			unlock_page(page);
1980 		}
1981 		folio_batch_release(&fbatch);
1982 		cond_resched();
1983 	}
1984 }
1985 
1986 int f2fs_sync_node_pages(struct f2fs_sb_info *sbi,
1987 				struct writeback_control *wbc,
1988 				bool do_balance, enum iostat_type io_type)
1989 {
1990 	pgoff_t index;
1991 	struct folio_batch fbatch;
1992 	int step = 0;
1993 	int nwritten = 0;
1994 	int ret = 0;
1995 	int nr_folios, done = 0;
1996 
1997 	folio_batch_init(&fbatch);
1998 
1999 next_step:
2000 	index = 0;
2001 
2002 	while (!done && (nr_folios = filemap_get_folios_tag(NODE_MAPPING(sbi),
2003 				&index, (pgoff_t)-1, PAGECACHE_TAG_DIRTY,
2004 				&fbatch))) {
2005 		int i;
2006 
2007 		for (i = 0; i < nr_folios; i++) {
2008 			struct page *page = &fbatch.folios[i]->page;
2009 			bool submitted = false;
2010 
2011 			/* give a priority to WB_SYNC threads */
2012 			if (atomic_read(&sbi->wb_sync_req[NODE]) &&
2013 					wbc->sync_mode == WB_SYNC_NONE) {
2014 				done = 1;
2015 				break;
2016 			}
2017 
2018 			/*
2019 			 * flushing sequence with step:
2020 			 * 0. indirect nodes
2021 			 * 1. dentry dnodes
2022 			 * 2. file dnodes
2023 			 */
2024 			if (step == 0 && IS_DNODE(page))
2025 				continue;
2026 			if (step == 1 && (!IS_DNODE(page) ||
2027 						is_cold_node(page)))
2028 				continue;
2029 			if (step == 2 && (!IS_DNODE(page) ||
2030 						!is_cold_node(page)))
2031 				continue;
2032 lock_node:
2033 			if (wbc->sync_mode == WB_SYNC_ALL)
2034 				lock_page(page);
2035 			else if (!trylock_page(page))
2036 				continue;
2037 
2038 			if (unlikely(page->mapping != NODE_MAPPING(sbi))) {
2039 continue_unlock:
2040 				unlock_page(page);
2041 				continue;
2042 			}
2043 
2044 			if (!PageDirty(page)) {
2045 				/* someone wrote it for us */
2046 				goto continue_unlock;
2047 			}
2048 
2049 			/* flush inline_data/inode, if it's async context. */
2050 			if (!do_balance)
2051 				goto write_node;
2052 
2053 			/* flush inline_data */
2054 			if (page_private_inline(page)) {
2055 				clear_page_private_inline(page);
2056 				unlock_page(page);
2057 				flush_inline_data(sbi, ino_of_node(page));
2058 				goto lock_node;
2059 			}
2060 
2061 			/* flush dirty inode */
2062 			if (IS_INODE(page) && flush_dirty_inode(page))
2063 				goto lock_node;
2064 write_node:
2065 			f2fs_wait_on_page_writeback(page, NODE, true, true);
2066 
2067 			if (!clear_page_dirty_for_io(page))
2068 				goto continue_unlock;
2069 
2070 			set_fsync_mark(page, 0);
2071 			set_dentry_mark(page, 0);
2072 
2073 			ret = __write_node_page(page, false, &submitted,
2074 						wbc, do_balance, io_type, NULL);
2075 			if (ret)
2076 				unlock_page(page);
2077 			else if (submitted)
2078 				nwritten++;
2079 
2080 			if (--wbc->nr_to_write == 0)
2081 				break;
2082 		}
2083 		folio_batch_release(&fbatch);
2084 		cond_resched();
2085 
2086 		if (wbc->nr_to_write == 0) {
2087 			step = 2;
2088 			break;
2089 		}
2090 	}
2091 
2092 	if (step < 2) {
2093 		if (!is_sbi_flag_set(sbi, SBI_CP_DISABLED) &&
2094 				wbc->sync_mode == WB_SYNC_NONE && step == 1)
2095 			goto out;
2096 		step++;
2097 		goto next_step;
2098 	}
2099 out:
2100 	if (nwritten)
2101 		f2fs_submit_merged_write(sbi, NODE);
2102 
2103 	if (unlikely(f2fs_cp_error(sbi)))
2104 		return -EIO;
2105 	return ret;
2106 }
2107 
2108 int f2fs_wait_on_node_pages_writeback(struct f2fs_sb_info *sbi,
2109 						unsigned int seq_id)
2110 {
2111 	struct fsync_node_entry *fn;
2112 	struct page *page;
2113 	struct list_head *head = &sbi->fsync_node_list;
2114 	unsigned long flags;
2115 	unsigned int cur_seq_id = 0;
2116 
2117 	while (seq_id && cur_seq_id < seq_id) {
2118 		spin_lock_irqsave(&sbi->fsync_node_lock, flags);
2119 		if (list_empty(head)) {
2120 			spin_unlock_irqrestore(&sbi->fsync_node_lock, flags);
2121 			break;
2122 		}
2123 		fn = list_first_entry(head, struct fsync_node_entry, list);
2124 		if (fn->seq_id > seq_id) {
2125 			spin_unlock_irqrestore(&sbi->fsync_node_lock, flags);
2126 			break;
2127 		}
2128 		cur_seq_id = fn->seq_id;
2129 		page = fn->page;
2130 		get_page(page);
2131 		spin_unlock_irqrestore(&sbi->fsync_node_lock, flags);
2132 
2133 		f2fs_wait_on_page_writeback(page, NODE, true, false);
2134 
2135 		put_page(page);
2136 	}
2137 
2138 	return filemap_check_errors(NODE_MAPPING(sbi));
2139 }
2140 
2141 static int f2fs_write_node_pages(struct address_space *mapping,
2142 			    struct writeback_control *wbc)
2143 {
2144 	struct f2fs_sb_info *sbi = F2FS_M_SB(mapping);
2145 	struct blk_plug plug;
2146 	long diff;
2147 
2148 	if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
2149 		goto skip_write;
2150 
2151 	/* balancing f2fs's metadata in background */
2152 	f2fs_balance_fs_bg(sbi, true);
2153 
2154 	/* collect a number of dirty node pages and write together */
2155 	if (wbc->sync_mode != WB_SYNC_ALL &&
2156 			get_pages(sbi, F2FS_DIRTY_NODES) <
2157 					nr_pages_to_skip(sbi, NODE))
2158 		goto skip_write;
2159 
2160 	if (wbc->sync_mode == WB_SYNC_ALL)
2161 		atomic_inc(&sbi->wb_sync_req[NODE]);
2162 	else if (atomic_read(&sbi->wb_sync_req[NODE])) {
2163 		/* to avoid potential deadlock */
2164 		if (current->plug)
2165 			blk_finish_plug(current->plug);
2166 		goto skip_write;
2167 	}
2168 
2169 	trace_f2fs_writepages(mapping->host, wbc, NODE);
2170 
2171 	diff = nr_pages_to_write(sbi, NODE, wbc);
2172 	blk_start_plug(&plug);
2173 	f2fs_sync_node_pages(sbi, wbc, true, FS_NODE_IO);
2174 	blk_finish_plug(&plug);
2175 	wbc->nr_to_write = max((long)0, wbc->nr_to_write - diff);
2176 
2177 	if (wbc->sync_mode == WB_SYNC_ALL)
2178 		atomic_dec(&sbi->wb_sync_req[NODE]);
2179 	return 0;
2180 
2181 skip_write:
2182 	wbc->pages_skipped += get_pages(sbi, F2FS_DIRTY_NODES);
2183 	trace_f2fs_writepages(mapping->host, wbc, NODE);
2184 	return 0;
2185 }
2186 
2187 static bool f2fs_dirty_node_folio(struct address_space *mapping,
2188 		struct folio *folio)
2189 {
2190 	trace_f2fs_set_page_dirty(folio, NODE);
2191 
2192 	if (!folio_test_uptodate(folio))
2193 		folio_mark_uptodate(folio);
2194 #ifdef CONFIG_F2FS_CHECK_FS
2195 	if (IS_INODE(&folio->page))
2196 		f2fs_inode_chksum_set(F2FS_M_SB(mapping), &folio->page);
2197 #endif
2198 	if (filemap_dirty_folio(mapping, folio)) {
2199 		inc_page_count(F2FS_M_SB(mapping), F2FS_DIRTY_NODES);
2200 		set_page_private_reference(&folio->page);
2201 		return true;
2202 	}
2203 	return false;
2204 }
2205 
2206 /*
2207  * Structure of the f2fs node operations
2208  */
2209 const struct address_space_operations f2fs_node_aops = {
2210 	.writepage	= f2fs_write_node_page,
2211 	.writepages	= f2fs_write_node_pages,
2212 	.dirty_folio	= f2fs_dirty_node_folio,
2213 	.invalidate_folio = f2fs_invalidate_folio,
2214 	.release_folio	= f2fs_release_folio,
2215 	.migrate_folio	= filemap_migrate_folio,
2216 };
2217 
2218 static struct free_nid *__lookup_free_nid_list(struct f2fs_nm_info *nm_i,
2219 						nid_t n)
2220 {
2221 	return radix_tree_lookup(&nm_i->free_nid_root, n);
2222 }
2223 
2224 static int __insert_free_nid(struct f2fs_sb_info *sbi,
2225 				struct free_nid *i)
2226 {
2227 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2228 	int err = radix_tree_insert(&nm_i->free_nid_root, i->nid, i);
2229 
2230 	if (err)
2231 		return err;
2232 
2233 	nm_i->nid_cnt[FREE_NID]++;
2234 	list_add_tail(&i->list, &nm_i->free_nid_list);
2235 	return 0;
2236 }
2237 
2238 static void __remove_free_nid(struct f2fs_sb_info *sbi,
2239 			struct free_nid *i, enum nid_state state)
2240 {
2241 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2242 
2243 	f2fs_bug_on(sbi, state != i->state);
2244 	nm_i->nid_cnt[state]--;
2245 	if (state == FREE_NID)
2246 		list_del(&i->list);
2247 	radix_tree_delete(&nm_i->free_nid_root, i->nid);
2248 }
2249 
2250 static void __move_free_nid(struct f2fs_sb_info *sbi, struct free_nid *i,
2251 			enum nid_state org_state, enum nid_state dst_state)
2252 {
2253 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2254 
2255 	f2fs_bug_on(sbi, org_state != i->state);
2256 	i->state = dst_state;
2257 	nm_i->nid_cnt[org_state]--;
2258 	nm_i->nid_cnt[dst_state]++;
2259 
2260 	switch (dst_state) {
2261 	case PREALLOC_NID:
2262 		list_del(&i->list);
2263 		break;
2264 	case FREE_NID:
2265 		list_add_tail(&i->list, &nm_i->free_nid_list);
2266 		break;
2267 	default:
2268 		BUG_ON(1);
2269 	}
2270 }
2271 
2272 bool f2fs_nat_bitmap_enabled(struct f2fs_sb_info *sbi)
2273 {
2274 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2275 	unsigned int i;
2276 	bool ret = true;
2277 
2278 	f2fs_down_read(&nm_i->nat_tree_lock);
2279 	for (i = 0; i < nm_i->nat_blocks; i++) {
2280 		if (!test_bit_le(i, nm_i->nat_block_bitmap)) {
2281 			ret = false;
2282 			break;
2283 		}
2284 	}
2285 	f2fs_up_read(&nm_i->nat_tree_lock);
2286 
2287 	return ret;
2288 }
2289 
2290 static void update_free_nid_bitmap(struct f2fs_sb_info *sbi, nid_t nid,
2291 							bool set, bool build)
2292 {
2293 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2294 	unsigned int nat_ofs = NAT_BLOCK_OFFSET(nid);
2295 	unsigned int nid_ofs = nid - START_NID(nid);
2296 
2297 	if (!test_bit_le(nat_ofs, nm_i->nat_block_bitmap))
2298 		return;
2299 
2300 	if (set) {
2301 		if (test_bit_le(nid_ofs, nm_i->free_nid_bitmap[nat_ofs]))
2302 			return;
2303 		__set_bit_le(nid_ofs, nm_i->free_nid_bitmap[nat_ofs]);
2304 		nm_i->free_nid_count[nat_ofs]++;
2305 	} else {
2306 		if (!test_bit_le(nid_ofs, nm_i->free_nid_bitmap[nat_ofs]))
2307 			return;
2308 		__clear_bit_le(nid_ofs, nm_i->free_nid_bitmap[nat_ofs]);
2309 		if (!build)
2310 			nm_i->free_nid_count[nat_ofs]--;
2311 	}
2312 }
2313 
2314 /* return if the nid is recognized as free */
2315 static bool add_free_nid(struct f2fs_sb_info *sbi,
2316 				nid_t nid, bool build, bool update)
2317 {
2318 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2319 	struct free_nid *i, *e;
2320 	struct nat_entry *ne;
2321 	int err = -EINVAL;
2322 	bool ret = false;
2323 
2324 	/* 0 nid should not be used */
2325 	if (unlikely(nid == 0))
2326 		return false;
2327 
2328 	if (unlikely(f2fs_check_nid_range(sbi, nid)))
2329 		return false;
2330 
2331 	i = f2fs_kmem_cache_alloc(free_nid_slab, GFP_NOFS, true, NULL);
2332 	i->nid = nid;
2333 	i->state = FREE_NID;
2334 
2335 	radix_tree_preload(GFP_NOFS | __GFP_NOFAIL);
2336 
2337 	spin_lock(&nm_i->nid_list_lock);
2338 
2339 	if (build) {
2340 		/*
2341 		 *   Thread A             Thread B
2342 		 *  - f2fs_create
2343 		 *   - f2fs_new_inode
2344 		 *    - f2fs_alloc_nid
2345 		 *     - __insert_nid_to_list(PREALLOC_NID)
2346 		 *                     - f2fs_balance_fs_bg
2347 		 *                      - f2fs_build_free_nids
2348 		 *                       - __f2fs_build_free_nids
2349 		 *                        - scan_nat_page
2350 		 *                         - add_free_nid
2351 		 *                          - __lookup_nat_cache
2352 		 *  - f2fs_add_link
2353 		 *   - f2fs_init_inode_metadata
2354 		 *    - f2fs_new_inode_page
2355 		 *     - f2fs_new_node_page
2356 		 *      - set_node_addr
2357 		 *  - f2fs_alloc_nid_done
2358 		 *   - __remove_nid_from_list(PREALLOC_NID)
2359 		 *                         - __insert_nid_to_list(FREE_NID)
2360 		 */
2361 		ne = __lookup_nat_cache(nm_i, nid);
2362 		if (ne && (!get_nat_flag(ne, IS_CHECKPOINTED) ||
2363 				nat_get_blkaddr(ne) != NULL_ADDR))
2364 			goto err_out;
2365 
2366 		e = __lookup_free_nid_list(nm_i, nid);
2367 		if (e) {
2368 			if (e->state == FREE_NID)
2369 				ret = true;
2370 			goto err_out;
2371 		}
2372 	}
2373 	ret = true;
2374 	err = __insert_free_nid(sbi, i);
2375 err_out:
2376 	if (update) {
2377 		update_free_nid_bitmap(sbi, nid, ret, build);
2378 		if (!build)
2379 			nm_i->available_nids++;
2380 	}
2381 	spin_unlock(&nm_i->nid_list_lock);
2382 	radix_tree_preload_end();
2383 
2384 	if (err)
2385 		kmem_cache_free(free_nid_slab, i);
2386 	return ret;
2387 }
2388 
2389 static void remove_free_nid(struct f2fs_sb_info *sbi, nid_t nid)
2390 {
2391 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2392 	struct free_nid *i;
2393 	bool need_free = false;
2394 
2395 	spin_lock(&nm_i->nid_list_lock);
2396 	i = __lookup_free_nid_list(nm_i, nid);
2397 	if (i && i->state == FREE_NID) {
2398 		__remove_free_nid(sbi, i, FREE_NID);
2399 		need_free = true;
2400 	}
2401 	spin_unlock(&nm_i->nid_list_lock);
2402 
2403 	if (need_free)
2404 		kmem_cache_free(free_nid_slab, i);
2405 }
2406 
2407 static int scan_nat_page(struct f2fs_sb_info *sbi,
2408 			struct page *nat_page, nid_t start_nid)
2409 {
2410 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2411 	struct f2fs_nat_block *nat_blk = page_address(nat_page);
2412 	block_t blk_addr;
2413 	unsigned int nat_ofs = NAT_BLOCK_OFFSET(start_nid);
2414 	int i;
2415 
2416 	__set_bit_le(nat_ofs, nm_i->nat_block_bitmap);
2417 
2418 	i = start_nid % NAT_ENTRY_PER_BLOCK;
2419 
2420 	for (; i < NAT_ENTRY_PER_BLOCK; i++, start_nid++) {
2421 		if (unlikely(start_nid >= nm_i->max_nid))
2422 			break;
2423 
2424 		blk_addr = le32_to_cpu(nat_blk->entries[i].block_addr);
2425 
2426 		if (blk_addr == NEW_ADDR)
2427 			return -EFSCORRUPTED;
2428 
2429 		if (blk_addr == NULL_ADDR) {
2430 			add_free_nid(sbi, start_nid, true, true);
2431 		} else {
2432 			spin_lock(&NM_I(sbi)->nid_list_lock);
2433 			update_free_nid_bitmap(sbi, start_nid, false, true);
2434 			spin_unlock(&NM_I(sbi)->nid_list_lock);
2435 		}
2436 	}
2437 
2438 	return 0;
2439 }
2440 
2441 static void scan_curseg_cache(struct f2fs_sb_info *sbi)
2442 {
2443 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_HOT_DATA);
2444 	struct f2fs_journal *journal = curseg->journal;
2445 	int i;
2446 
2447 	down_read(&curseg->journal_rwsem);
2448 	for (i = 0; i < nats_in_cursum(journal); i++) {
2449 		block_t addr;
2450 		nid_t nid;
2451 
2452 		addr = le32_to_cpu(nat_in_journal(journal, i).block_addr);
2453 		nid = le32_to_cpu(nid_in_journal(journal, i));
2454 		if (addr == NULL_ADDR)
2455 			add_free_nid(sbi, nid, true, false);
2456 		else
2457 			remove_free_nid(sbi, nid);
2458 	}
2459 	up_read(&curseg->journal_rwsem);
2460 }
2461 
2462 static void scan_free_nid_bits(struct f2fs_sb_info *sbi)
2463 {
2464 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2465 	unsigned int i, idx;
2466 	nid_t nid;
2467 
2468 	f2fs_down_read(&nm_i->nat_tree_lock);
2469 
2470 	for (i = 0; i < nm_i->nat_blocks; i++) {
2471 		if (!test_bit_le(i, nm_i->nat_block_bitmap))
2472 			continue;
2473 		if (!nm_i->free_nid_count[i])
2474 			continue;
2475 		for (idx = 0; idx < NAT_ENTRY_PER_BLOCK; idx++) {
2476 			idx = find_next_bit_le(nm_i->free_nid_bitmap[i],
2477 						NAT_ENTRY_PER_BLOCK, idx);
2478 			if (idx >= NAT_ENTRY_PER_BLOCK)
2479 				break;
2480 
2481 			nid = i * NAT_ENTRY_PER_BLOCK + idx;
2482 			add_free_nid(sbi, nid, true, false);
2483 
2484 			if (nm_i->nid_cnt[FREE_NID] >= MAX_FREE_NIDS)
2485 				goto out;
2486 		}
2487 	}
2488 out:
2489 	scan_curseg_cache(sbi);
2490 
2491 	f2fs_up_read(&nm_i->nat_tree_lock);
2492 }
2493 
2494 static int __f2fs_build_free_nids(struct f2fs_sb_info *sbi,
2495 						bool sync, bool mount)
2496 {
2497 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2498 	int i = 0, ret;
2499 	nid_t nid = nm_i->next_scan_nid;
2500 
2501 	if (unlikely(nid >= nm_i->max_nid))
2502 		nid = 0;
2503 
2504 	if (unlikely(nid % NAT_ENTRY_PER_BLOCK))
2505 		nid = NAT_BLOCK_OFFSET(nid) * NAT_ENTRY_PER_BLOCK;
2506 
2507 	/* Enough entries */
2508 	if (nm_i->nid_cnt[FREE_NID] >= NAT_ENTRY_PER_BLOCK)
2509 		return 0;
2510 
2511 	if (!sync && !f2fs_available_free_memory(sbi, FREE_NIDS))
2512 		return 0;
2513 
2514 	if (!mount) {
2515 		/* try to find free nids in free_nid_bitmap */
2516 		scan_free_nid_bits(sbi);
2517 
2518 		if (nm_i->nid_cnt[FREE_NID] >= NAT_ENTRY_PER_BLOCK)
2519 			return 0;
2520 	}
2521 
2522 	/* readahead nat pages to be scanned */
2523 	f2fs_ra_meta_pages(sbi, NAT_BLOCK_OFFSET(nid), FREE_NID_PAGES,
2524 							META_NAT, true);
2525 
2526 	f2fs_down_read(&nm_i->nat_tree_lock);
2527 
2528 	while (1) {
2529 		if (!test_bit_le(NAT_BLOCK_OFFSET(nid),
2530 						nm_i->nat_block_bitmap)) {
2531 			struct page *page = get_current_nat_page(sbi, nid);
2532 
2533 			if (IS_ERR(page)) {
2534 				ret = PTR_ERR(page);
2535 			} else {
2536 				ret = scan_nat_page(sbi, page, nid);
2537 				f2fs_put_page(page, 1);
2538 			}
2539 
2540 			if (ret) {
2541 				f2fs_up_read(&nm_i->nat_tree_lock);
2542 
2543 				if (ret == -EFSCORRUPTED) {
2544 					f2fs_err(sbi, "NAT is corrupt, run fsck to fix it");
2545 					set_sbi_flag(sbi, SBI_NEED_FSCK);
2546 					f2fs_handle_error(sbi,
2547 						ERROR_INCONSISTENT_NAT);
2548 				}
2549 
2550 				return ret;
2551 			}
2552 		}
2553 
2554 		nid += (NAT_ENTRY_PER_BLOCK - (nid % NAT_ENTRY_PER_BLOCK));
2555 		if (unlikely(nid >= nm_i->max_nid))
2556 			nid = 0;
2557 
2558 		if (++i >= FREE_NID_PAGES)
2559 			break;
2560 	}
2561 
2562 	/* go to the next free nat pages to find free nids abundantly */
2563 	nm_i->next_scan_nid = nid;
2564 
2565 	/* find free nids from current sum_pages */
2566 	scan_curseg_cache(sbi);
2567 
2568 	f2fs_up_read(&nm_i->nat_tree_lock);
2569 
2570 	f2fs_ra_meta_pages(sbi, NAT_BLOCK_OFFSET(nm_i->next_scan_nid),
2571 					nm_i->ra_nid_pages, META_NAT, false);
2572 
2573 	return 0;
2574 }
2575 
2576 int f2fs_build_free_nids(struct f2fs_sb_info *sbi, bool sync, bool mount)
2577 {
2578 	int ret;
2579 
2580 	mutex_lock(&NM_I(sbi)->build_lock);
2581 	ret = __f2fs_build_free_nids(sbi, sync, mount);
2582 	mutex_unlock(&NM_I(sbi)->build_lock);
2583 
2584 	return ret;
2585 }
2586 
2587 /*
2588  * If this function returns success, caller can obtain a new nid
2589  * from second parameter of this function.
2590  * The returned nid could be used ino as well as nid when inode is created.
2591  */
2592 bool f2fs_alloc_nid(struct f2fs_sb_info *sbi, nid_t *nid)
2593 {
2594 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2595 	struct free_nid *i = NULL;
2596 retry:
2597 	if (time_to_inject(sbi, FAULT_ALLOC_NID))
2598 		return false;
2599 
2600 	spin_lock(&nm_i->nid_list_lock);
2601 
2602 	if (unlikely(nm_i->available_nids == 0)) {
2603 		spin_unlock(&nm_i->nid_list_lock);
2604 		return false;
2605 	}
2606 
2607 	/* We should not use stale free nids created by f2fs_build_free_nids */
2608 	if (nm_i->nid_cnt[FREE_NID] && !on_f2fs_build_free_nids(nm_i)) {
2609 		f2fs_bug_on(sbi, list_empty(&nm_i->free_nid_list));
2610 		i = list_first_entry(&nm_i->free_nid_list,
2611 					struct free_nid, list);
2612 		*nid = i->nid;
2613 
2614 		__move_free_nid(sbi, i, FREE_NID, PREALLOC_NID);
2615 		nm_i->available_nids--;
2616 
2617 		update_free_nid_bitmap(sbi, *nid, false, false);
2618 
2619 		spin_unlock(&nm_i->nid_list_lock);
2620 		return true;
2621 	}
2622 	spin_unlock(&nm_i->nid_list_lock);
2623 
2624 	/* Let's scan nat pages and its caches to get free nids */
2625 	if (!f2fs_build_free_nids(sbi, true, false))
2626 		goto retry;
2627 	return false;
2628 }
2629 
2630 /*
2631  * f2fs_alloc_nid() should be called prior to this function.
2632  */
2633 void f2fs_alloc_nid_done(struct f2fs_sb_info *sbi, nid_t nid)
2634 {
2635 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2636 	struct free_nid *i;
2637 
2638 	spin_lock(&nm_i->nid_list_lock);
2639 	i = __lookup_free_nid_list(nm_i, nid);
2640 	f2fs_bug_on(sbi, !i);
2641 	__remove_free_nid(sbi, i, PREALLOC_NID);
2642 	spin_unlock(&nm_i->nid_list_lock);
2643 
2644 	kmem_cache_free(free_nid_slab, i);
2645 }
2646 
2647 /*
2648  * f2fs_alloc_nid() should be called prior to this function.
2649  */
2650 void f2fs_alloc_nid_failed(struct f2fs_sb_info *sbi, nid_t nid)
2651 {
2652 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2653 	struct free_nid *i;
2654 	bool need_free = false;
2655 
2656 	if (!nid)
2657 		return;
2658 
2659 	spin_lock(&nm_i->nid_list_lock);
2660 	i = __lookup_free_nid_list(nm_i, nid);
2661 	f2fs_bug_on(sbi, !i);
2662 
2663 	if (!f2fs_available_free_memory(sbi, FREE_NIDS)) {
2664 		__remove_free_nid(sbi, i, PREALLOC_NID);
2665 		need_free = true;
2666 	} else {
2667 		__move_free_nid(sbi, i, PREALLOC_NID, FREE_NID);
2668 	}
2669 
2670 	nm_i->available_nids++;
2671 
2672 	update_free_nid_bitmap(sbi, nid, true, false);
2673 
2674 	spin_unlock(&nm_i->nid_list_lock);
2675 
2676 	if (need_free)
2677 		kmem_cache_free(free_nid_slab, i);
2678 }
2679 
2680 int f2fs_try_to_free_nids(struct f2fs_sb_info *sbi, int nr_shrink)
2681 {
2682 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2683 	int nr = nr_shrink;
2684 
2685 	if (nm_i->nid_cnt[FREE_NID] <= MAX_FREE_NIDS)
2686 		return 0;
2687 
2688 	if (!mutex_trylock(&nm_i->build_lock))
2689 		return 0;
2690 
2691 	while (nr_shrink && nm_i->nid_cnt[FREE_NID] > MAX_FREE_NIDS) {
2692 		struct free_nid *i, *next;
2693 		unsigned int batch = SHRINK_NID_BATCH_SIZE;
2694 
2695 		spin_lock(&nm_i->nid_list_lock);
2696 		list_for_each_entry_safe(i, next, &nm_i->free_nid_list, list) {
2697 			if (!nr_shrink || !batch ||
2698 				nm_i->nid_cnt[FREE_NID] <= MAX_FREE_NIDS)
2699 				break;
2700 			__remove_free_nid(sbi, i, FREE_NID);
2701 			kmem_cache_free(free_nid_slab, i);
2702 			nr_shrink--;
2703 			batch--;
2704 		}
2705 		spin_unlock(&nm_i->nid_list_lock);
2706 	}
2707 
2708 	mutex_unlock(&nm_i->build_lock);
2709 
2710 	return nr - nr_shrink;
2711 }
2712 
2713 int f2fs_recover_inline_xattr(struct inode *inode, struct page *page)
2714 {
2715 	void *src_addr, *dst_addr;
2716 	size_t inline_size;
2717 	struct page *ipage;
2718 	struct f2fs_inode *ri;
2719 
2720 	ipage = f2fs_get_node_page(F2FS_I_SB(inode), inode->i_ino);
2721 	if (IS_ERR(ipage))
2722 		return PTR_ERR(ipage);
2723 
2724 	ri = F2FS_INODE(page);
2725 	if (ri->i_inline & F2FS_INLINE_XATTR) {
2726 		if (!f2fs_has_inline_xattr(inode)) {
2727 			set_inode_flag(inode, FI_INLINE_XATTR);
2728 			stat_inc_inline_xattr(inode);
2729 		}
2730 	} else {
2731 		if (f2fs_has_inline_xattr(inode)) {
2732 			stat_dec_inline_xattr(inode);
2733 			clear_inode_flag(inode, FI_INLINE_XATTR);
2734 		}
2735 		goto update_inode;
2736 	}
2737 
2738 	dst_addr = inline_xattr_addr(inode, ipage);
2739 	src_addr = inline_xattr_addr(inode, page);
2740 	inline_size = inline_xattr_size(inode);
2741 
2742 	f2fs_wait_on_page_writeback(ipage, NODE, true, true);
2743 	memcpy(dst_addr, src_addr, inline_size);
2744 update_inode:
2745 	f2fs_update_inode(inode, ipage);
2746 	f2fs_put_page(ipage, 1);
2747 	return 0;
2748 }
2749 
2750 int f2fs_recover_xattr_data(struct inode *inode, struct page *page)
2751 {
2752 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2753 	nid_t prev_xnid = F2FS_I(inode)->i_xattr_nid;
2754 	nid_t new_xnid;
2755 	struct dnode_of_data dn;
2756 	struct node_info ni;
2757 	struct page *xpage;
2758 	int err;
2759 
2760 	if (!prev_xnid)
2761 		goto recover_xnid;
2762 
2763 	/* 1: invalidate the previous xattr nid */
2764 	err = f2fs_get_node_info(sbi, prev_xnid, &ni, false);
2765 	if (err)
2766 		return err;
2767 
2768 	f2fs_invalidate_blocks(sbi, ni.blk_addr, 1);
2769 	dec_valid_node_count(sbi, inode, false);
2770 	set_node_addr(sbi, &ni, NULL_ADDR, false);
2771 
2772 recover_xnid:
2773 	/* 2: update xattr nid in inode */
2774 	if (!f2fs_alloc_nid(sbi, &new_xnid))
2775 		return -ENOSPC;
2776 
2777 	set_new_dnode(&dn, inode, NULL, NULL, new_xnid);
2778 	xpage = f2fs_new_node_page(&dn, XATTR_NODE_OFFSET);
2779 	if (IS_ERR(xpage)) {
2780 		f2fs_alloc_nid_failed(sbi, new_xnid);
2781 		return PTR_ERR(xpage);
2782 	}
2783 
2784 	f2fs_alloc_nid_done(sbi, new_xnid);
2785 	f2fs_update_inode_page(inode);
2786 
2787 	/* 3: update and set xattr node page dirty */
2788 	if (page) {
2789 		memcpy(F2FS_NODE(xpage), F2FS_NODE(page),
2790 				VALID_XATTR_BLOCK_SIZE);
2791 		set_page_dirty(xpage);
2792 	}
2793 	f2fs_put_page(xpage, 1);
2794 
2795 	return 0;
2796 }
2797 
2798 int f2fs_recover_inode_page(struct f2fs_sb_info *sbi, struct page *page)
2799 {
2800 	struct f2fs_inode *src, *dst;
2801 	nid_t ino = ino_of_node(page);
2802 	struct node_info old_ni, new_ni;
2803 	struct page *ipage;
2804 	int err;
2805 
2806 	err = f2fs_get_node_info(sbi, ino, &old_ni, false);
2807 	if (err)
2808 		return err;
2809 
2810 	if (unlikely(old_ni.blk_addr != NULL_ADDR))
2811 		return -EINVAL;
2812 retry:
2813 	ipage = f2fs_grab_cache_page(NODE_MAPPING(sbi), ino, false);
2814 	if (!ipage) {
2815 		memalloc_retry_wait(GFP_NOFS);
2816 		goto retry;
2817 	}
2818 
2819 	/* Should not use this inode from free nid list */
2820 	remove_free_nid(sbi, ino);
2821 
2822 	if (!PageUptodate(ipage))
2823 		SetPageUptodate(ipage);
2824 	fill_node_footer(ipage, ino, ino, 0, true);
2825 	set_cold_node(ipage, false);
2826 
2827 	src = F2FS_INODE(page);
2828 	dst = F2FS_INODE(ipage);
2829 
2830 	memcpy(dst, src, offsetof(struct f2fs_inode, i_ext));
2831 	dst->i_size = 0;
2832 	dst->i_blocks = cpu_to_le64(1);
2833 	dst->i_links = cpu_to_le32(1);
2834 	dst->i_xattr_nid = 0;
2835 	dst->i_inline = src->i_inline & (F2FS_INLINE_XATTR | F2FS_EXTRA_ATTR);
2836 	if (dst->i_inline & F2FS_EXTRA_ATTR) {
2837 		dst->i_extra_isize = src->i_extra_isize;
2838 
2839 		if (f2fs_sb_has_flexible_inline_xattr(sbi) &&
2840 			F2FS_FITS_IN_INODE(src, le16_to_cpu(src->i_extra_isize),
2841 							i_inline_xattr_size))
2842 			dst->i_inline_xattr_size = src->i_inline_xattr_size;
2843 
2844 		if (f2fs_sb_has_project_quota(sbi) &&
2845 			F2FS_FITS_IN_INODE(src, le16_to_cpu(src->i_extra_isize),
2846 								i_projid))
2847 			dst->i_projid = src->i_projid;
2848 
2849 		if (f2fs_sb_has_inode_crtime(sbi) &&
2850 			F2FS_FITS_IN_INODE(src, le16_to_cpu(src->i_extra_isize),
2851 							i_crtime_nsec)) {
2852 			dst->i_crtime = src->i_crtime;
2853 			dst->i_crtime_nsec = src->i_crtime_nsec;
2854 		}
2855 	}
2856 
2857 	new_ni = old_ni;
2858 	new_ni.ino = ino;
2859 
2860 	if (unlikely(inc_valid_node_count(sbi, NULL, true)))
2861 		WARN_ON(1);
2862 	set_node_addr(sbi, &new_ni, NEW_ADDR, false);
2863 	inc_valid_inode_count(sbi);
2864 	set_page_dirty(ipage);
2865 	f2fs_put_page(ipage, 1);
2866 	return 0;
2867 }
2868 
2869 int f2fs_restore_node_summary(struct f2fs_sb_info *sbi,
2870 			unsigned int segno, struct f2fs_summary_block *sum)
2871 {
2872 	struct f2fs_node *rn;
2873 	struct f2fs_summary *sum_entry;
2874 	block_t addr;
2875 	int i, idx, last_offset, nrpages;
2876 
2877 	/* scan the node segment */
2878 	last_offset = BLKS_PER_SEG(sbi);
2879 	addr = START_BLOCK(sbi, segno);
2880 	sum_entry = &sum->entries[0];
2881 
2882 	for (i = 0; i < last_offset; i += nrpages, addr += nrpages) {
2883 		nrpages = bio_max_segs(last_offset - i);
2884 
2885 		/* readahead node pages */
2886 		f2fs_ra_meta_pages(sbi, addr, nrpages, META_POR, true);
2887 
2888 		for (idx = addr; idx < addr + nrpages; idx++) {
2889 			struct page *page = f2fs_get_tmp_page(sbi, idx);
2890 
2891 			if (IS_ERR(page))
2892 				return PTR_ERR(page);
2893 
2894 			rn = F2FS_NODE(page);
2895 			sum_entry->nid = rn->footer.nid;
2896 			sum_entry->version = 0;
2897 			sum_entry->ofs_in_node = 0;
2898 			sum_entry++;
2899 			f2fs_put_page(page, 1);
2900 		}
2901 
2902 		invalidate_mapping_pages(META_MAPPING(sbi), addr,
2903 							addr + nrpages);
2904 	}
2905 	return 0;
2906 }
2907 
2908 static void remove_nats_in_journal(struct f2fs_sb_info *sbi)
2909 {
2910 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2911 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_HOT_DATA);
2912 	struct f2fs_journal *journal = curseg->journal;
2913 	int i;
2914 
2915 	down_write(&curseg->journal_rwsem);
2916 	for (i = 0; i < nats_in_cursum(journal); i++) {
2917 		struct nat_entry *ne;
2918 		struct f2fs_nat_entry raw_ne;
2919 		nid_t nid = le32_to_cpu(nid_in_journal(journal, i));
2920 
2921 		if (f2fs_check_nid_range(sbi, nid))
2922 			continue;
2923 
2924 		raw_ne = nat_in_journal(journal, i);
2925 
2926 		ne = __lookup_nat_cache(nm_i, nid);
2927 		if (!ne) {
2928 			ne = __alloc_nat_entry(sbi, nid, true);
2929 			__init_nat_entry(nm_i, ne, &raw_ne, true);
2930 		}
2931 
2932 		/*
2933 		 * if a free nat in journal has not been used after last
2934 		 * checkpoint, we should remove it from available nids,
2935 		 * since later we will add it again.
2936 		 */
2937 		if (!get_nat_flag(ne, IS_DIRTY) &&
2938 				le32_to_cpu(raw_ne.block_addr) == NULL_ADDR) {
2939 			spin_lock(&nm_i->nid_list_lock);
2940 			nm_i->available_nids--;
2941 			spin_unlock(&nm_i->nid_list_lock);
2942 		}
2943 
2944 		__set_nat_cache_dirty(nm_i, ne);
2945 	}
2946 	update_nats_in_cursum(journal, -i);
2947 	up_write(&curseg->journal_rwsem);
2948 }
2949 
2950 static void __adjust_nat_entry_set(struct nat_entry_set *nes,
2951 						struct list_head *head, int max)
2952 {
2953 	struct nat_entry_set *cur;
2954 
2955 	if (nes->entry_cnt >= max)
2956 		goto add_out;
2957 
2958 	list_for_each_entry(cur, head, set_list) {
2959 		if (cur->entry_cnt >= nes->entry_cnt) {
2960 			list_add(&nes->set_list, cur->set_list.prev);
2961 			return;
2962 		}
2963 	}
2964 add_out:
2965 	list_add_tail(&nes->set_list, head);
2966 }
2967 
2968 static void __update_nat_bits(struct f2fs_nm_info *nm_i, unsigned int nat_ofs,
2969 							unsigned int valid)
2970 {
2971 	if (valid == 0) {
2972 		__set_bit_le(nat_ofs, nm_i->empty_nat_bits);
2973 		__clear_bit_le(nat_ofs, nm_i->full_nat_bits);
2974 		return;
2975 	}
2976 
2977 	__clear_bit_le(nat_ofs, nm_i->empty_nat_bits);
2978 	if (valid == NAT_ENTRY_PER_BLOCK)
2979 		__set_bit_le(nat_ofs, nm_i->full_nat_bits);
2980 	else
2981 		__clear_bit_le(nat_ofs, nm_i->full_nat_bits);
2982 }
2983 
2984 static void update_nat_bits(struct f2fs_sb_info *sbi, nid_t start_nid,
2985 						struct page *page)
2986 {
2987 	struct f2fs_nm_info *nm_i = NM_I(sbi);
2988 	unsigned int nat_index = start_nid / NAT_ENTRY_PER_BLOCK;
2989 	struct f2fs_nat_block *nat_blk = page_address(page);
2990 	int valid = 0;
2991 	int i = 0;
2992 
2993 	if (!is_set_ckpt_flags(sbi, CP_NAT_BITS_FLAG))
2994 		return;
2995 
2996 	if (nat_index == 0) {
2997 		valid = 1;
2998 		i = 1;
2999 	}
3000 	for (; i < NAT_ENTRY_PER_BLOCK; i++) {
3001 		if (le32_to_cpu(nat_blk->entries[i].block_addr) != NULL_ADDR)
3002 			valid++;
3003 	}
3004 
3005 	__update_nat_bits(nm_i, nat_index, valid);
3006 }
3007 
3008 void f2fs_enable_nat_bits(struct f2fs_sb_info *sbi)
3009 {
3010 	struct f2fs_nm_info *nm_i = NM_I(sbi);
3011 	unsigned int nat_ofs;
3012 
3013 	f2fs_down_read(&nm_i->nat_tree_lock);
3014 
3015 	for (nat_ofs = 0; nat_ofs < nm_i->nat_blocks; nat_ofs++) {
3016 		unsigned int valid = 0, nid_ofs = 0;
3017 
3018 		/* handle nid zero due to it should never be used */
3019 		if (unlikely(nat_ofs == 0)) {
3020 			valid = 1;
3021 			nid_ofs = 1;
3022 		}
3023 
3024 		for (; nid_ofs < NAT_ENTRY_PER_BLOCK; nid_ofs++) {
3025 			if (!test_bit_le(nid_ofs,
3026 					nm_i->free_nid_bitmap[nat_ofs]))
3027 				valid++;
3028 		}
3029 
3030 		__update_nat_bits(nm_i, nat_ofs, valid);
3031 	}
3032 
3033 	f2fs_up_read(&nm_i->nat_tree_lock);
3034 }
3035 
3036 static int __flush_nat_entry_set(struct f2fs_sb_info *sbi,
3037 		struct nat_entry_set *set, struct cp_control *cpc)
3038 {
3039 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_HOT_DATA);
3040 	struct f2fs_journal *journal = curseg->journal;
3041 	nid_t start_nid = set->set * NAT_ENTRY_PER_BLOCK;
3042 	bool to_journal = true;
3043 	struct f2fs_nat_block *nat_blk;
3044 	struct nat_entry *ne, *cur;
3045 	struct page *page = NULL;
3046 
3047 	/*
3048 	 * there are two steps to flush nat entries:
3049 	 * #1, flush nat entries to journal in current hot data summary block.
3050 	 * #2, flush nat entries to nat page.
3051 	 */
3052 	if ((cpc->reason & CP_UMOUNT) ||
3053 		!__has_cursum_space(journal, set->entry_cnt, NAT_JOURNAL))
3054 		to_journal = false;
3055 
3056 	if (to_journal) {
3057 		down_write(&curseg->journal_rwsem);
3058 	} else {
3059 		page = get_next_nat_page(sbi, start_nid);
3060 		if (IS_ERR(page))
3061 			return PTR_ERR(page);
3062 
3063 		nat_blk = page_address(page);
3064 		f2fs_bug_on(sbi, !nat_blk);
3065 	}
3066 
3067 	/* flush dirty nats in nat entry set */
3068 	list_for_each_entry_safe(ne, cur, &set->entry_list, list) {
3069 		struct f2fs_nat_entry *raw_ne;
3070 		nid_t nid = nat_get_nid(ne);
3071 		int offset;
3072 
3073 		f2fs_bug_on(sbi, nat_get_blkaddr(ne) == NEW_ADDR);
3074 
3075 		if (to_journal) {
3076 			offset = f2fs_lookup_journal_in_cursum(journal,
3077 							NAT_JOURNAL, nid, 1);
3078 			f2fs_bug_on(sbi, offset < 0);
3079 			raw_ne = &nat_in_journal(journal, offset);
3080 			nid_in_journal(journal, offset) = cpu_to_le32(nid);
3081 		} else {
3082 			raw_ne = &nat_blk->entries[nid - start_nid];
3083 		}
3084 		raw_nat_from_node_info(raw_ne, &ne->ni);
3085 		nat_reset_flag(ne);
3086 		__clear_nat_cache_dirty(NM_I(sbi), set, ne);
3087 		if (nat_get_blkaddr(ne) == NULL_ADDR) {
3088 			add_free_nid(sbi, nid, false, true);
3089 		} else {
3090 			spin_lock(&NM_I(sbi)->nid_list_lock);
3091 			update_free_nid_bitmap(sbi, nid, false, false);
3092 			spin_unlock(&NM_I(sbi)->nid_list_lock);
3093 		}
3094 	}
3095 
3096 	if (to_journal) {
3097 		up_write(&curseg->journal_rwsem);
3098 	} else {
3099 		update_nat_bits(sbi, start_nid, page);
3100 		f2fs_put_page(page, 1);
3101 	}
3102 
3103 	/* Allow dirty nats by node block allocation in write_begin */
3104 	if (!set->entry_cnt) {
3105 		radix_tree_delete(&NM_I(sbi)->nat_set_root, set->set);
3106 		kmem_cache_free(nat_entry_set_slab, set);
3107 	}
3108 	return 0;
3109 }
3110 
3111 /*
3112  * This function is called during the checkpointing process.
3113  */
3114 int f2fs_flush_nat_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc)
3115 {
3116 	struct f2fs_nm_info *nm_i = NM_I(sbi);
3117 	struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_HOT_DATA);
3118 	struct f2fs_journal *journal = curseg->journal;
3119 	struct nat_entry_set *setvec[NAT_VEC_SIZE];
3120 	struct nat_entry_set *set, *tmp;
3121 	unsigned int found;
3122 	nid_t set_idx = 0;
3123 	LIST_HEAD(sets);
3124 	int err = 0;
3125 
3126 	/*
3127 	 * during unmount, let's flush nat_bits before checking
3128 	 * nat_cnt[DIRTY_NAT].
3129 	 */
3130 	if (cpc->reason & CP_UMOUNT) {
3131 		f2fs_down_write(&nm_i->nat_tree_lock);
3132 		remove_nats_in_journal(sbi);
3133 		f2fs_up_write(&nm_i->nat_tree_lock);
3134 	}
3135 
3136 	if (!nm_i->nat_cnt[DIRTY_NAT])
3137 		return 0;
3138 
3139 	f2fs_down_write(&nm_i->nat_tree_lock);
3140 
3141 	/*
3142 	 * if there are no enough space in journal to store dirty nat
3143 	 * entries, remove all entries from journal and merge them
3144 	 * into nat entry set.
3145 	 */
3146 	if (cpc->reason & CP_UMOUNT ||
3147 		!__has_cursum_space(journal,
3148 			nm_i->nat_cnt[DIRTY_NAT], NAT_JOURNAL))
3149 		remove_nats_in_journal(sbi);
3150 
3151 	while ((found = __gang_lookup_nat_set(nm_i,
3152 					set_idx, NAT_VEC_SIZE, setvec))) {
3153 		unsigned idx;
3154 
3155 		set_idx = setvec[found - 1]->set + 1;
3156 		for (idx = 0; idx < found; idx++)
3157 			__adjust_nat_entry_set(setvec[idx], &sets,
3158 						MAX_NAT_JENTRIES(journal));
3159 	}
3160 
3161 	/* flush dirty nats in nat entry set */
3162 	list_for_each_entry_safe(set, tmp, &sets, set_list) {
3163 		err = __flush_nat_entry_set(sbi, set, cpc);
3164 		if (err)
3165 			break;
3166 	}
3167 
3168 	f2fs_up_write(&nm_i->nat_tree_lock);
3169 	/* Allow dirty nats by node block allocation in write_begin */
3170 
3171 	return err;
3172 }
3173 
3174 static int __get_nat_bitmaps(struct f2fs_sb_info *sbi)
3175 {
3176 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
3177 	struct f2fs_nm_info *nm_i = NM_I(sbi);
3178 	unsigned int nat_bits_bytes = nm_i->nat_blocks / BITS_PER_BYTE;
3179 	unsigned int i;
3180 	__u64 cp_ver = cur_cp_version(ckpt);
3181 	block_t nat_bits_addr;
3182 
3183 	nm_i->nat_bits_blocks = F2FS_BLK_ALIGN((nat_bits_bytes << 1) + 8);
3184 	nm_i->nat_bits = f2fs_kvzalloc(sbi,
3185 			F2FS_BLK_TO_BYTES(nm_i->nat_bits_blocks), GFP_KERNEL);
3186 	if (!nm_i->nat_bits)
3187 		return -ENOMEM;
3188 
3189 	nm_i->full_nat_bits = nm_i->nat_bits + 8;
3190 	nm_i->empty_nat_bits = nm_i->full_nat_bits + nat_bits_bytes;
3191 
3192 	if (!is_set_ckpt_flags(sbi, CP_NAT_BITS_FLAG))
3193 		return 0;
3194 
3195 	nat_bits_addr = __start_cp_addr(sbi) + BLKS_PER_SEG(sbi) -
3196 						nm_i->nat_bits_blocks;
3197 	for (i = 0; i < nm_i->nat_bits_blocks; i++) {
3198 		struct page *page;
3199 
3200 		page = f2fs_get_meta_page(sbi, nat_bits_addr++);
3201 		if (IS_ERR(page))
3202 			return PTR_ERR(page);
3203 
3204 		memcpy(nm_i->nat_bits + F2FS_BLK_TO_BYTES(i),
3205 					page_address(page), F2FS_BLKSIZE);
3206 		f2fs_put_page(page, 1);
3207 	}
3208 
3209 	cp_ver |= (cur_cp_crc(ckpt) << 32);
3210 	if (cpu_to_le64(cp_ver) != *(__le64 *)nm_i->nat_bits) {
3211 		clear_ckpt_flags(sbi, CP_NAT_BITS_FLAG);
3212 		f2fs_notice(sbi, "Disable nat_bits due to incorrect cp_ver (%llu, %llu)",
3213 			cp_ver, le64_to_cpu(*(__le64 *)nm_i->nat_bits));
3214 		return 0;
3215 	}
3216 
3217 	f2fs_notice(sbi, "Found nat_bits in checkpoint");
3218 	return 0;
3219 }
3220 
3221 static inline void load_free_nid_bitmap(struct f2fs_sb_info *sbi)
3222 {
3223 	struct f2fs_nm_info *nm_i = NM_I(sbi);
3224 	unsigned int i = 0;
3225 	nid_t nid, last_nid;
3226 
3227 	if (!is_set_ckpt_flags(sbi, CP_NAT_BITS_FLAG))
3228 		return;
3229 
3230 	for (i = 0; i < nm_i->nat_blocks; i++) {
3231 		i = find_next_bit_le(nm_i->empty_nat_bits, nm_i->nat_blocks, i);
3232 		if (i >= nm_i->nat_blocks)
3233 			break;
3234 
3235 		__set_bit_le(i, nm_i->nat_block_bitmap);
3236 
3237 		nid = i * NAT_ENTRY_PER_BLOCK;
3238 		last_nid = nid + NAT_ENTRY_PER_BLOCK;
3239 
3240 		spin_lock(&NM_I(sbi)->nid_list_lock);
3241 		for (; nid < last_nid; nid++)
3242 			update_free_nid_bitmap(sbi, nid, true, true);
3243 		spin_unlock(&NM_I(sbi)->nid_list_lock);
3244 	}
3245 
3246 	for (i = 0; i < nm_i->nat_blocks; i++) {
3247 		i = find_next_bit_le(nm_i->full_nat_bits, nm_i->nat_blocks, i);
3248 		if (i >= nm_i->nat_blocks)
3249 			break;
3250 
3251 		__set_bit_le(i, nm_i->nat_block_bitmap);
3252 	}
3253 }
3254 
3255 static int init_node_manager(struct f2fs_sb_info *sbi)
3256 {
3257 	struct f2fs_super_block *sb_raw = F2FS_RAW_SUPER(sbi);
3258 	struct f2fs_nm_info *nm_i = NM_I(sbi);
3259 	unsigned char *version_bitmap;
3260 	unsigned int nat_segs;
3261 	int err;
3262 
3263 	nm_i->nat_blkaddr = le32_to_cpu(sb_raw->nat_blkaddr);
3264 
3265 	/* segment_count_nat includes pair segment so divide to 2. */
3266 	nat_segs = le32_to_cpu(sb_raw->segment_count_nat) >> 1;
3267 	nm_i->nat_blocks = nat_segs << le32_to_cpu(sb_raw->log_blocks_per_seg);
3268 	nm_i->max_nid = NAT_ENTRY_PER_BLOCK * nm_i->nat_blocks;
3269 
3270 	/* not used nids: 0, node, meta, (and root counted as valid node) */
3271 	nm_i->available_nids = nm_i->max_nid - sbi->total_valid_node_count -
3272 						F2FS_RESERVED_NODE_NUM;
3273 	nm_i->nid_cnt[FREE_NID] = 0;
3274 	nm_i->nid_cnt[PREALLOC_NID] = 0;
3275 	nm_i->ram_thresh = DEF_RAM_THRESHOLD;
3276 	nm_i->ra_nid_pages = DEF_RA_NID_PAGES;
3277 	nm_i->dirty_nats_ratio = DEF_DIRTY_NAT_RATIO_THRESHOLD;
3278 	nm_i->max_rf_node_blocks = DEF_RF_NODE_BLOCKS;
3279 
3280 	INIT_RADIX_TREE(&nm_i->free_nid_root, GFP_ATOMIC);
3281 	INIT_LIST_HEAD(&nm_i->free_nid_list);
3282 	INIT_RADIX_TREE(&nm_i->nat_root, GFP_NOIO);
3283 	INIT_RADIX_TREE(&nm_i->nat_set_root, GFP_NOIO);
3284 	INIT_LIST_HEAD(&nm_i->nat_entries);
3285 	spin_lock_init(&nm_i->nat_list_lock);
3286 
3287 	mutex_init(&nm_i->build_lock);
3288 	spin_lock_init(&nm_i->nid_list_lock);
3289 	init_f2fs_rwsem(&nm_i->nat_tree_lock);
3290 
3291 	nm_i->next_scan_nid = le32_to_cpu(sbi->ckpt->next_free_nid);
3292 	nm_i->bitmap_size = __bitmap_size(sbi, NAT_BITMAP);
3293 	version_bitmap = __bitmap_ptr(sbi, NAT_BITMAP);
3294 	nm_i->nat_bitmap = kmemdup(version_bitmap, nm_i->bitmap_size,
3295 					GFP_KERNEL);
3296 	if (!nm_i->nat_bitmap)
3297 		return -ENOMEM;
3298 
3299 	err = __get_nat_bitmaps(sbi);
3300 	if (err)
3301 		return err;
3302 
3303 #ifdef CONFIG_F2FS_CHECK_FS
3304 	nm_i->nat_bitmap_mir = kmemdup(version_bitmap, nm_i->bitmap_size,
3305 					GFP_KERNEL);
3306 	if (!nm_i->nat_bitmap_mir)
3307 		return -ENOMEM;
3308 #endif
3309 
3310 	return 0;
3311 }
3312 
3313 static int init_free_nid_cache(struct f2fs_sb_info *sbi)
3314 {
3315 	struct f2fs_nm_info *nm_i = NM_I(sbi);
3316 	int i;
3317 
3318 	nm_i->free_nid_bitmap =
3319 		f2fs_kvzalloc(sbi, array_size(sizeof(unsigned char *),
3320 					      nm_i->nat_blocks),
3321 			      GFP_KERNEL);
3322 	if (!nm_i->free_nid_bitmap)
3323 		return -ENOMEM;
3324 
3325 	for (i = 0; i < nm_i->nat_blocks; i++) {
3326 		nm_i->free_nid_bitmap[i] = f2fs_kvzalloc(sbi,
3327 			f2fs_bitmap_size(NAT_ENTRY_PER_BLOCK), GFP_KERNEL);
3328 		if (!nm_i->free_nid_bitmap[i])
3329 			return -ENOMEM;
3330 	}
3331 
3332 	nm_i->nat_block_bitmap = f2fs_kvzalloc(sbi, nm_i->nat_blocks / 8,
3333 								GFP_KERNEL);
3334 	if (!nm_i->nat_block_bitmap)
3335 		return -ENOMEM;
3336 
3337 	nm_i->free_nid_count =
3338 		f2fs_kvzalloc(sbi, array_size(sizeof(unsigned short),
3339 					      nm_i->nat_blocks),
3340 			      GFP_KERNEL);
3341 	if (!nm_i->free_nid_count)
3342 		return -ENOMEM;
3343 	return 0;
3344 }
3345 
3346 int f2fs_build_node_manager(struct f2fs_sb_info *sbi)
3347 {
3348 	int err;
3349 
3350 	sbi->nm_info = f2fs_kzalloc(sbi, sizeof(struct f2fs_nm_info),
3351 							GFP_KERNEL);
3352 	if (!sbi->nm_info)
3353 		return -ENOMEM;
3354 
3355 	err = init_node_manager(sbi);
3356 	if (err)
3357 		return err;
3358 
3359 	err = init_free_nid_cache(sbi);
3360 	if (err)
3361 		return err;
3362 
3363 	/* load free nid status from nat_bits table */
3364 	load_free_nid_bitmap(sbi);
3365 
3366 	return f2fs_build_free_nids(sbi, true, true);
3367 }
3368 
3369 void f2fs_destroy_node_manager(struct f2fs_sb_info *sbi)
3370 {
3371 	struct f2fs_nm_info *nm_i = NM_I(sbi);
3372 	struct free_nid *i, *next_i;
3373 	void *vec[NAT_VEC_SIZE];
3374 	struct nat_entry **natvec = (struct nat_entry **)vec;
3375 	struct nat_entry_set **setvec = (struct nat_entry_set **)vec;
3376 	nid_t nid = 0;
3377 	unsigned int found;
3378 
3379 	if (!nm_i)
3380 		return;
3381 
3382 	/* destroy free nid list */
3383 	spin_lock(&nm_i->nid_list_lock);
3384 	list_for_each_entry_safe(i, next_i, &nm_i->free_nid_list, list) {
3385 		__remove_free_nid(sbi, i, FREE_NID);
3386 		spin_unlock(&nm_i->nid_list_lock);
3387 		kmem_cache_free(free_nid_slab, i);
3388 		spin_lock(&nm_i->nid_list_lock);
3389 	}
3390 	f2fs_bug_on(sbi, nm_i->nid_cnt[FREE_NID]);
3391 	f2fs_bug_on(sbi, nm_i->nid_cnt[PREALLOC_NID]);
3392 	f2fs_bug_on(sbi, !list_empty(&nm_i->free_nid_list));
3393 	spin_unlock(&nm_i->nid_list_lock);
3394 
3395 	/* destroy nat cache */
3396 	f2fs_down_write(&nm_i->nat_tree_lock);
3397 	while ((found = __gang_lookup_nat_cache(nm_i,
3398 					nid, NAT_VEC_SIZE, natvec))) {
3399 		unsigned idx;
3400 
3401 		nid = nat_get_nid(natvec[found - 1]) + 1;
3402 		for (idx = 0; idx < found; idx++) {
3403 			spin_lock(&nm_i->nat_list_lock);
3404 			list_del(&natvec[idx]->list);
3405 			spin_unlock(&nm_i->nat_list_lock);
3406 
3407 			__del_from_nat_cache(nm_i, natvec[idx]);
3408 		}
3409 	}
3410 	f2fs_bug_on(sbi, nm_i->nat_cnt[TOTAL_NAT]);
3411 
3412 	/* destroy nat set cache */
3413 	nid = 0;
3414 	memset(vec, 0, sizeof(void *) * NAT_VEC_SIZE);
3415 	while ((found = __gang_lookup_nat_set(nm_i,
3416 					nid, NAT_VEC_SIZE, setvec))) {
3417 		unsigned idx;
3418 
3419 		nid = setvec[found - 1]->set + 1;
3420 		for (idx = 0; idx < found; idx++) {
3421 			/* entry_cnt is not zero, when cp_error was occurred */
3422 			f2fs_bug_on(sbi, !list_empty(&setvec[idx]->entry_list));
3423 			radix_tree_delete(&nm_i->nat_set_root, setvec[idx]->set);
3424 			kmem_cache_free(nat_entry_set_slab, setvec[idx]);
3425 		}
3426 	}
3427 	f2fs_up_write(&nm_i->nat_tree_lock);
3428 
3429 	kvfree(nm_i->nat_block_bitmap);
3430 	if (nm_i->free_nid_bitmap) {
3431 		int i;
3432 
3433 		for (i = 0; i < nm_i->nat_blocks; i++)
3434 			kvfree(nm_i->free_nid_bitmap[i]);
3435 		kvfree(nm_i->free_nid_bitmap);
3436 	}
3437 	kvfree(nm_i->free_nid_count);
3438 
3439 	kvfree(nm_i->nat_bitmap);
3440 	kvfree(nm_i->nat_bits);
3441 #ifdef CONFIG_F2FS_CHECK_FS
3442 	kvfree(nm_i->nat_bitmap_mir);
3443 #endif
3444 	sbi->nm_info = NULL;
3445 	kfree(nm_i);
3446 }
3447 
3448 int __init f2fs_create_node_manager_caches(void)
3449 {
3450 	nat_entry_slab = f2fs_kmem_cache_create("f2fs_nat_entry",
3451 			sizeof(struct nat_entry));
3452 	if (!nat_entry_slab)
3453 		goto fail;
3454 
3455 	free_nid_slab = f2fs_kmem_cache_create("f2fs_free_nid",
3456 			sizeof(struct free_nid));
3457 	if (!free_nid_slab)
3458 		goto destroy_nat_entry;
3459 
3460 	nat_entry_set_slab = f2fs_kmem_cache_create("f2fs_nat_entry_set",
3461 			sizeof(struct nat_entry_set));
3462 	if (!nat_entry_set_slab)
3463 		goto destroy_free_nid;
3464 
3465 	fsync_node_entry_slab = f2fs_kmem_cache_create("f2fs_fsync_node_entry",
3466 			sizeof(struct fsync_node_entry));
3467 	if (!fsync_node_entry_slab)
3468 		goto destroy_nat_entry_set;
3469 	return 0;
3470 
3471 destroy_nat_entry_set:
3472 	kmem_cache_destroy(nat_entry_set_slab);
3473 destroy_free_nid:
3474 	kmem_cache_destroy(free_nid_slab);
3475 destroy_nat_entry:
3476 	kmem_cache_destroy(nat_entry_slab);
3477 fail:
3478 	return -ENOMEM;
3479 }
3480 
3481 void f2fs_destroy_node_manager_caches(void)
3482 {
3483 	kmem_cache_destroy(fsync_node_entry_slab);
3484 	kmem_cache_destroy(nat_entry_set_slab);
3485 	kmem_cache_destroy(free_nid_slab);
3486 	kmem_cache_destroy(nat_entry_slab);
3487 }
3488