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