xref: /linux/fs/xfs/xfs_icache.c (revision 9b64ca202f364a6bf8e19bdd20953bc2d776c67f)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2005 Silicon Graphics, Inc.
4  * All Rights Reserved.
5  */
6 #include "xfs_platform.h"
7 #include "xfs_fs.h"
8 #include "xfs_shared.h"
9 #include "xfs_format.h"
10 #include "xfs_log_format.h"
11 #include "xfs_trans_resv.h"
12 #include "xfs_mount.h"
13 #include "xfs_inode.h"
14 #include "xfs_trans.h"
15 #include "xfs_trans_priv.h"
16 #include "xfs_inode_item.h"
17 #include "xfs_quota.h"
18 #include "xfs_trace.h"
19 #include "xfs_icache.h"
20 #include "xfs_bmap_util.h"
21 #include "xfs_dquot_item.h"
22 #include "xfs_dquot.h"
23 #include "xfs_reflink.h"
24 #include "xfs_ialloc.h"
25 #include "xfs_ag.h"
26 #include "xfs_log_priv.h"
27 #include "xfs_health.h"
28 #include "xfs_da_format.h"
29 #include "xfs_dir2.h"
30 #include "xfs_metafile.h"
31 
32 #include <linux/iversion.h>
33 
34 /* Radix tree tags for incore inode tree. */
35 
36 /* inode is to be reclaimed */
37 #define XFS_ICI_RECLAIM_TAG	0
38 /* Inode has speculative preallocations (posteof or cow) to clean. */
39 #define XFS_ICI_BLOCKGC_TAG	1
40 
41 /*
42  * The goal for walking incore inodes.  These can correspond with incore inode
43  * radix tree tags when convenient.  Avoid existing XFS_IWALK namespace.
44  */
45 enum xfs_icwalk_goal {
46 	/* Goals directly associated with tagged inodes. */
47 	XFS_ICWALK_BLOCKGC	= XFS_ICI_BLOCKGC_TAG,
48 	XFS_ICWALK_RECLAIM	= XFS_ICI_RECLAIM_TAG,
49 };
50 
51 static int xfs_icwalk(struct xfs_mount *mp,
52 		enum xfs_icwalk_goal goal, struct xfs_icwalk *icw);
53 static int xfs_icwalk_ag(struct xfs_perag *pag,
54 		enum xfs_icwalk_goal goal, struct xfs_icwalk *icw);
55 
56 /*
57  * Private inode cache walk flags for struct xfs_icwalk.  Must not
58  * coincide with XFS_ICWALK_FLAGS_VALID.
59  */
60 
61 /* Stop scanning after icw_scan_limit inodes. */
62 #define XFS_ICWALK_FLAG_SCAN_LIMIT	(1U << 28)
63 
64 #define XFS_ICWALK_FLAG_RECLAIM_SICK	(1U << 27)
65 #define XFS_ICWALK_FLAG_UNION		(1U << 26) /* union filter algorithm */
66 
67 #define XFS_ICWALK_PRIVATE_FLAGS	(XFS_ICWALK_FLAG_SCAN_LIMIT | \
68 					 XFS_ICWALK_FLAG_RECLAIM_SICK | \
69 					 XFS_ICWALK_FLAG_UNION)
70 
71 /* Marks for the perag xarray */
72 #define XFS_PERAG_RECLAIM_MARK	XA_MARK_0
73 #define XFS_PERAG_BLOCKGC_MARK	XA_MARK_1
74 
75 static inline xa_mark_t ici_tag_to_mark(unsigned int tag)
76 {
77 	if (tag == XFS_ICI_RECLAIM_TAG)
78 		return XFS_PERAG_RECLAIM_MARK;
79 	ASSERT(tag == XFS_ICI_BLOCKGC_TAG);
80 	return XFS_PERAG_BLOCKGC_MARK;
81 }
82 
83 /*
84  * Allocate and initialise an xfs_inode.
85  */
86 struct xfs_inode *
87 xfs_inode_alloc(
88 	struct xfs_mount	*mp,
89 	xfs_ino_t		ino)
90 {
91 	struct xfs_inode	*ip;
92 
93 	/*
94 	 * XXX: If this didn't occur in transactions, we could drop GFP_NOFAIL
95 	 * and return NULL here on ENOMEM.
96 	 */
97 	ip = alloc_inode_sb(mp->m_super, xfs_inode_cache, GFP_KERNEL | __GFP_NOFAIL);
98 
99 	if (inode_init_always(mp->m_super, VFS_I(ip))) {
100 		kmem_cache_free(xfs_inode_cache, ip);
101 		return NULL;
102 	}
103 
104 	VFS_I(ip)->i_ino = ino;
105 	/* VFS doesn't initialise i_mode! */
106 	VFS_I(ip)->i_mode = 0;
107 	mapping_set_folio_min_order(VFS_I(ip)->i_mapping,
108 				    M_IGEO(mp)->min_folio_order);
109 
110 	XFS_STATS_INC(mp, xs_inodes_active);
111 	ASSERT(atomic_read(&ip->i_pincount) == 0);
112 
113 	/* initialise the xfs inode */
114 	ip->i_mount = mp;
115 	memset(&ip->i_imap, 0, sizeof(struct xfs_imap));
116 	ip->i_cowfp = NULL;
117 	memset(&ip->i_af, 0, sizeof(ip->i_af));
118 	ip->i_af.if_format = XFS_DINODE_FMT_EXTENTS;
119 	memset(&ip->i_df, 0, sizeof(ip->i_df));
120 	ip->i_flags = 0;
121 	ip->i_delayed_blks = 0;
122 	ip->i_diflags2 = mp->m_ino_geo.new_diflags2;
123 	ip->i_nblocks = 0;
124 	ip->i_forkoff = 0;
125 	ip->i_sick = 0;
126 	ip->i_checked = 0;
127 	INIT_WORK(&ip->i_ioend_work, xfs_end_io);
128 	INIT_LIST_HEAD(&ip->i_ioend_list);
129 	spin_lock_init(&ip->i_ioend_lock);
130 	ip->i_next_unlinked = NULLAGINO;
131 	ip->i_prev_unlinked = 0;
132 
133 	return ip;
134 }
135 
136 STATIC void
137 xfs_inode_free_callback(
138 	struct rcu_head		*head)
139 {
140 	struct inode		*inode = container_of(head, struct inode, i_rcu);
141 	struct xfs_inode	*ip = XFS_I(inode);
142 
143 	switch (VFS_I(ip)->i_mode & S_IFMT) {
144 	case S_IFREG:
145 	case S_IFDIR:
146 	case S_IFLNK:
147 		xfs_idestroy_fork(&ip->i_df);
148 		break;
149 	}
150 
151 	xfs_ifork_zap_attr(ip);
152 
153 	if (ip->i_cowfp) {
154 		xfs_idestroy_fork(ip->i_cowfp);
155 		kmem_cache_free(xfs_ifork_cache, ip->i_cowfp);
156 	}
157 	if (ip->i_itemp) {
158 		ASSERT(!test_bit(XFS_LI_IN_AIL,
159 				 &ip->i_itemp->ili_item.li_flags));
160 		xfs_inode_item_destroy(ip);
161 	}
162 
163 	kmem_cache_free(xfs_inode_cache, ip);
164 }
165 
166 static void
167 __xfs_inode_free(
168 	struct xfs_inode	*ip)
169 {
170 	/* asserts to verify all state is correct here */
171 	ASSERT(atomic_read(&ip->i_pincount) == 0);
172 	ASSERT(!ip->i_itemp || list_empty(&ip->i_itemp->ili_item.li_bio_list));
173 	if (xfs_is_metadir_inode(ip))
174 		XFS_STATS_DEC(ip->i_mount, xs_inodes_meta);
175 	else
176 		XFS_STATS_DEC(ip->i_mount, xs_inodes_active);
177 
178 	call_rcu(&VFS_I(ip)->i_rcu, xfs_inode_free_callback);
179 }
180 
181 void
182 xfs_inode_free(
183 	struct xfs_inode	*ip)
184 {
185 	ASSERT(!xfs_iflags_test(ip, XFS_IFLUSHING));
186 
187 	/*
188 	 * Because we use RCU freeing we need to ensure the inode always
189 	 * appears to be reclaimed with an invalid inode number when in the
190 	 * free state. The ip->i_flags_lock provides the barrier against lookup
191 	 * races.
192 	 */
193 	spin_lock(&ip->i_flags_lock);
194 	ip->i_flags = XFS_IRECLAIM;
195 	VFS_I(ip)->i_ino = 0;
196 	spin_unlock(&ip->i_flags_lock);
197 
198 	__xfs_inode_free(ip);
199 }
200 
201 /*
202  * Queue background inode reclaim work if there are reclaimable inodes and there
203  * isn't reclaim work already scheduled or in progress.
204  */
205 static void
206 xfs_reclaim_work_queue(
207 	struct xfs_mount        *mp)
208 {
209 
210 	rcu_read_lock();
211 	if (xfs_group_marked(mp, XG_TYPE_AG, XFS_PERAG_RECLAIM_MARK)) {
212 		queue_delayed_work(mp->m_reclaim_workqueue, &mp->m_reclaim_work,
213 			msecs_to_jiffies(xfs_syncd_centisecs / 6 * 10));
214 	}
215 	rcu_read_unlock();
216 }
217 
218 /*
219  * Background scanning to trim preallocated space. This is queued based on the
220  * 'speculative_prealloc_lifetime' tunable (5m by default).
221  */
222 static inline void
223 xfs_blockgc_queue(
224 	struct xfs_perag	*pag)
225 {
226 	struct xfs_mount	*mp = pag_mount(pag);
227 
228 	if (!xfs_is_blockgc_enabled(mp))
229 		return;
230 
231 	rcu_read_lock();
232 	if (radix_tree_tagged(&pag->pag_ici_root, XFS_ICI_BLOCKGC_TAG))
233 		queue_delayed_work(mp->m_blockgc_wq, &pag->pag_blockgc_work,
234 				   secs_to_jiffies(xfs_blockgc_secs));
235 	rcu_read_unlock();
236 }
237 
238 /* Set a tag on both the AG incore inode tree and the AG radix tree. */
239 static void
240 xfs_perag_set_inode_tag(
241 	struct xfs_perag	*pag,
242 	xfs_agino_t		agino,
243 	unsigned int		tag)
244 {
245 	bool			was_tagged;
246 
247 	lockdep_assert_held(&pag->pag_ici_lock);
248 
249 	was_tagged = radix_tree_tagged(&pag->pag_ici_root, tag);
250 	radix_tree_tag_set(&pag->pag_ici_root, agino, tag);
251 
252 	if (tag == XFS_ICI_RECLAIM_TAG)
253 		pag->pag_ici_reclaimable++;
254 
255 	if (was_tagged)
256 		return;
257 
258 	/* propagate the tag up into the pag xarray tree */
259 	xfs_group_set_mark(pag_group(pag), ici_tag_to_mark(tag));
260 
261 	/* start background work */
262 	switch (tag) {
263 	case XFS_ICI_RECLAIM_TAG:
264 		xfs_reclaim_work_queue(pag_mount(pag));
265 		break;
266 	case XFS_ICI_BLOCKGC_TAG:
267 		xfs_blockgc_queue(pag);
268 		break;
269 	}
270 
271 	trace_xfs_perag_set_inode_tag(pag, _RET_IP_);
272 }
273 
274 /* Clear a tag on both the AG incore inode tree and the AG radix tree. */
275 static void
276 xfs_perag_clear_inode_tag(
277 	struct xfs_perag	*pag,
278 	xfs_agino_t		agino,
279 	unsigned int		tag)
280 {
281 	lockdep_assert_held(&pag->pag_ici_lock);
282 
283 	/*
284 	 * Reclaim can signal (with a null agino) that it cleared its own tag
285 	 * by removing the inode from the radix tree.
286 	 */
287 	if (agino != NULLAGINO)
288 		radix_tree_tag_clear(&pag->pag_ici_root, agino, tag);
289 	else
290 		ASSERT(tag == XFS_ICI_RECLAIM_TAG);
291 
292 	if (tag == XFS_ICI_RECLAIM_TAG)
293 		pag->pag_ici_reclaimable--;
294 
295 	if (radix_tree_tagged(&pag->pag_ici_root, tag))
296 		return;
297 
298 	/* clear the tag from the pag xarray */
299 	xfs_group_clear_mark(pag_group(pag), ici_tag_to_mark(tag));
300 	trace_xfs_perag_clear_inode_tag(pag, _RET_IP_);
301 }
302 
303 /*
304  * Find the next AG after @pag, or the first AG if @pag is NULL.
305  */
306 static struct xfs_perag *
307 xfs_perag_grab_next_tag(
308 	struct xfs_mount	*mp,
309 	struct xfs_perag	*pag,
310 	int			tag)
311 {
312 	return to_perag(xfs_group_grab_next_mark(mp,
313 			pag ? pag_group(pag) : NULL,
314 			ici_tag_to_mark(tag), XG_TYPE_AG));
315 }
316 
317 /*
318  * When we recycle a reclaimable inode, we need to re-initialise the VFS inode
319  * part of the structure. This is made more complex by the fact we store
320  * information about the on-disk values in the VFS inode and so we can't just
321  * overwrite the values unconditionally. Hence we save the parameters we
322  * need to retain across reinitialisation, and rewrite them into the VFS inode
323  * after reinitialisation even if it fails.
324  */
325 static int
326 xfs_reinit_inode(
327 	struct xfs_mount	*mp,
328 	struct inode		*inode)
329 {
330 	int			error;
331 	u64			ino = inode->i_ino;
332 	uint32_t		nlink = inode->i_nlink;
333 	uint32_t		generation = inode->i_generation;
334 	uint64_t		version = inode_peek_iversion(inode);
335 	umode_t			mode = inode->i_mode;
336 	dev_t			dev = inode->i_rdev;
337 	kuid_t			uid = inode->i_uid;
338 	kgid_t			gid = inode->i_gid;
339 	unsigned long		state = inode_state_read_once(inode);
340 
341 	error = inode_init_always(mp->m_super, inode);
342 
343 	inode->i_ino = ino;
344 	set_nlink(inode, nlink);
345 	inode->i_generation = generation;
346 	inode_set_iversion_queried(inode, version);
347 	inode->i_mode = mode;
348 	inode->i_rdev = dev;
349 	inode->i_uid = uid;
350 	inode->i_gid = gid;
351 	inode_state_assign_raw(inode, state);
352 	mapping_set_folio_min_order(inode->i_mapping,
353 				    M_IGEO(mp)->min_folio_order);
354 	return error;
355 }
356 
357 /*
358  * Carefully nudge an inode whose VFS state has been torn down back into a
359  * usable state.  Drops the i_flags_lock and the rcu read lock.
360  */
361 static int
362 xfs_iget_recycle(
363 	struct xfs_perag	*pag,
364 	struct xfs_inode	*ip)
365 {
366 	struct xfs_mount	*mp = ip->i_mount;
367 	struct inode		*inode = VFS_I(ip);
368 	int			error;
369 
370 	trace_xfs_iget_recycle(ip);
371 
372 	ASSERT(!rwsem_is_locked(&inode->i_rwsem));
373 	error = xfs_reinit_inode(mp, inode);
374 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
375 	if (error) {
376 		/*
377 		 * Re-initializing the inode failed, and we are in deep
378 		 * trouble.  Try to re-add it to the reclaim list.
379 		 */
380 		rcu_read_lock();
381 		spin_lock(&ip->i_flags_lock);
382 		ip->i_flags &= ~(XFS_INEW | XFS_IRECLAIM);
383 		ASSERT(ip->i_flags & XFS_IRECLAIMABLE);
384 		spin_unlock(&ip->i_flags_lock);
385 		rcu_read_unlock();
386 
387 		trace_xfs_iget_recycle_fail(ip);
388 		return error;
389 	}
390 
391 	spin_lock(&pag->pag_ici_lock);
392 	spin_lock(&ip->i_flags_lock);
393 
394 	/*
395 	 * Clear the per-lifetime state in the inode as we are now effectively
396 	 * a new inode and need to return to the initial state before reuse
397 	 * occurs.
398 	 */
399 	ip->i_flags &= ~XFS_IRECLAIM_RESET_FLAGS;
400 	ip->i_flags |= XFS_INEW;
401 	xfs_perag_clear_inode_tag(pag, XFS_INODE_TO_AGINO(ip),
402 			XFS_ICI_RECLAIM_TAG);
403 	inode_state_assign_raw(inode, I_NEW);
404 	spin_unlock(&ip->i_flags_lock);
405 	spin_unlock(&pag->pag_ici_lock);
406 
407 	return 0;
408 }
409 
410 /*
411  * If we are allocating a new inode, then check what was returned is
412  * actually a free, empty inode. If we are not allocating an inode,
413  * then check we didn't find a free inode.
414  *
415  * Returns:
416  *	0		if the inode free state matches the lookup context
417  *	-ENOENT		if the inode is free and we are not allocating
418  *	-EFSCORRUPTED	if there is any state mismatch at all
419  */
420 static int
421 xfs_iget_check_free_state(
422 	struct xfs_inode	*ip,
423 	int			flags)
424 {
425 	if (flags & XFS_IGET_CREATE) {
426 		/* should be a free inode */
427 		if (VFS_I(ip)->i_mode != 0) {
428 			xfs_warn(ip->i_mount,
429 "Corruption detected! Free inode 0x%llx not marked free! (mode 0x%x)",
430 				I_INO(ip), VFS_I(ip)->i_mode);
431 			xfs_agno_mark_sick(ip->i_mount, XFS_INODE_TO_AGNO(ip),
432 					XFS_SICK_AG_INOBT);
433 			return -EFSCORRUPTED;
434 		}
435 
436 		if (ip->i_nblocks != 0) {
437 			xfs_warn(ip->i_mount,
438 "Corruption detected! Free inode 0x%llx has blocks allocated!",
439 				I_INO(ip));
440 			xfs_agno_mark_sick(ip->i_mount, XFS_INODE_TO_AGNO(ip),
441 					XFS_SICK_AG_INOBT);
442 			return -EFSCORRUPTED;
443 		}
444 		return 0;
445 	}
446 
447 	/* should be an allocated inode */
448 	if (VFS_I(ip)->i_mode == 0)
449 		return -ENOENT;
450 
451 	return 0;
452 }
453 
454 /* Make all pending inactivation work start immediately. */
455 static bool
456 xfs_inodegc_queue_all(
457 	struct xfs_mount	*mp)
458 {
459 	struct xfs_inodegc	*gc;
460 	int			cpu;
461 	bool			ret = false;
462 
463 	for_each_cpu(cpu, &mp->m_inodegc_cpumask) {
464 		gc = per_cpu_ptr(mp->m_inodegc, cpu);
465 		if (!llist_empty(&gc->list)) {
466 			mod_delayed_work_on(cpu, mp->m_inodegc_wq, &gc->work, 0);
467 			ret = true;
468 		}
469 	}
470 
471 	return ret;
472 }
473 
474 /* Wait for all queued work and collect errors */
475 static int
476 xfs_inodegc_wait_all(
477 	struct xfs_mount	*mp)
478 {
479 	int			cpu;
480 	int			error = 0;
481 
482 	flush_workqueue(mp->m_inodegc_wq);
483 	for_each_cpu(cpu, &mp->m_inodegc_cpumask) {
484 		struct xfs_inodegc	*gc;
485 
486 		gc = per_cpu_ptr(mp->m_inodegc, cpu);
487 		if (gc->error && !error)
488 			error = gc->error;
489 		gc->error = 0;
490 	}
491 
492 	return error;
493 }
494 
495 /*
496  * Check the validity of the inode we just found it the cache
497  */
498 static int
499 xfs_iget_cache_hit(
500 	struct xfs_perag	*pag,
501 	struct xfs_inode	*ip,
502 	xfs_ino_t		ino,
503 	int			flags,
504 	int			lock_flags) __releases(RCU)
505 {
506 	struct inode		*inode = VFS_I(ip);
507 	struct xfs_mount	*mp = ip->i_mount;
508 	int			error;
509 
510 	/*
511 	 * check for re-use of an inode within an RCU grace period due to the
512 	 * radix tree nodes not being updated yet. We monitor for this by
513 	 * setting the inode number to zero before freeing the inode structure.
514 	 * If the inode has been reallocated and set up, then the inode number
515 	 * will not match, so check for that, too.
516 	 */
517 	spin_lock(&ip->i_flags_lock);
518 	if (I_INO(ip) != ino)
519 		goto out_skip;
520 
521 	/*
522 	 * If we are racing with another cache hit that is currently
523 	 * instantiating this inode or currently recycling it out of
524 	 * reclaimable state, wait for the initialisation to complete
525 	 * before continuing.
526 	 *
527 	 * If we're racing with the inactivation worker we also want to wait.
528 	 * If we're creating a new file, it's possible that the worker
529 	 * previously marked the inode as free on disk but hasn't finished
530 	 * updating the incore state yet.  The AGI buffer will be dirty and
531 	 * locked to the icreate transaction, so a synchronous push of the
532 	 * inodegc workers would result in deadlock.  For a regular iget, the
533 	 * worker is running already, so we might as well wait.
534 	 *
535 	 * XXX(hch): eventually we should do something equivalent to
536 	 *	     wait_on_inode to wait for these flags to be cleared
537 	 *	     instead of polling for it.
538 	 */
539 	if (ip->i_flags & (XFS_INEW | XFS_IRECLAIM | XFS_INACTIVATING))
540 		goto out_skip;
541 
542 	if (ip->i_flags & XFS_NEED_INACTIVE) {
543 		/* Unlinked inodes cannot be re-grabbed. */
544 		if (VFS_I(ip)->i_nlink == 0) {
545 			error = -ENOENT;
546 			goto out_error;
547 		}
548 		goto out_inodegc_flush;
549 	}
550 
551 	/*
552 	 * Check the inode free state is valid. This also detects lookup
553 	 * racing with unlinks.
554 	 */
555 	error = xfs_iget_check_free_state(ip, flags);
556 	if (error)
557 		goto out_error;
558 
559 	/* Skip inodes that have no vfs state. */
560 	if ((flags & XFS_IGET_INCORE) &&
561 	    (ip->i_flags & XFS_IRECLAIMABLE))
562 		goto out_skip;
563 
564 	/* The inode fits the selection criteria; process it. */
565 	if (ip->i_flags & XFS_IRECLAIMABLE) {
566 		/*
567 		 * We need to make it look like the inode is being reclaimed to
568 		 * prevent the actual reclaim workers from stomping over us
569 		 * while we recycle the inode.  We can't clear the radix tree
570 		 * tag yet as it requires pag_ici_lock to be held exclusive.
571 		 */
572 		if (!xfs_ilock_nowait(ip, XFS_ILOCK_EXCL))
573 			goto out_skip;
574 		ip->i_flags |= XFS_IRECLAIM;
575 		spin_unlock(&ip->i_flags_lock);
576 		rcu_read_unlock();
577 
578 		error = xfs_iget_recycle(pag, ip);
579 		if (error)
580 			return error;
581 	} else {
582 		/* If the VFS inode is being torn down, pause and try again. */
583 		if (!igrab(inode))
584 			goto out_skip;
585 
586 		/* We've got a live one. */
587 		spin_unlock(&ip->i_flags_lock);
588 		rcu_read_unlock();
589 		trace_xfs_iget_hit(ip);
590 	}
591 
592 	if (lock_flags != 0)
593 		xfs_ilock(ip, lock_flags);
594 
595 	if (!(flags & XFS_IGET_INCORE))
596 		xfs_iflags_clear(ip, XFS_ISTALE);
597 	XFS_STATS_INC(mp, xs_ig_found);
598 
599 	return 0;
600 
601 out_skip:
602 	trace_xfs_iget_skip(ip);
603 	XFS_STATS_INC(mp, xs_ig_frecycle);
604 	error = -EAGAIN;
605 out_error:
606 	spin_unlock(&ip->i_flags_lock);
607 	rcu_read_unlock();
608 	return error;
609 
610 out_inodegc_flush:
611 	spin_unlock(&ip->i_flags_lock);
612 	rcu_read_unlock();
613 	/*
614 	 * Do not wait for the workers, because the caller could hold an AGI
615 	 * buffer lock.  We're just going to sleep in a loop anyway.
616 	 */
617 	if (xfs_is_inodegc_enabled(mp))
618 		xfs_inodegc_queue_all(mp);
619 	return -EAGAIN;
620 }
621 
622 static int
623 xfs_iget_cache_miss(
624 	struct xfs_mount	*mp,
625 	struct xfs_perag	*pag,
626 	xfs_trans_t		*tp,
627 	xfs_ino_t		ino,
628 	struct xfs_inode	**ipp,
629 	int			flags,
630 	int			lock_flags)
631 {
632 	struct xfs_inode	*ip;
633 	int			error;
634 	xfs_agino_t		agino = XFS_INO_TO_AGINO(mp, ino);
635 
636 	ip = xfs_inode_alloc(mp, ino);
637 	if (!ip)
638 		return -ENOMEM;
639 
640 	/*
641 	 * Set XFS_INEW as early as possible so that the health code won't pass
642 	 * the inode to the fserror code if the ondisk inode cannot be loaded.
643 	 * We're going to free the xfs_inode immediately if that happens, which
644 	 * would lead to UAF problems.
645 	 */
646 	xfs_iflags_set(ip, XFS_INEW);
647 
648 	error = xfs_imap(pag, tp, I_INO(ip), &ip->i_imap, flags);
649 	if (error)
650 		goto out_destroy;
651 
652 	/*
653 	 * For version 5 superblocks, if we are initialising a new inode, we
654 	 * simply build the new inode core with a random generation number.
655 	 *
656 	 * For version 4 (and older) superblocks, log recovery is dependent on
657 	 * the i_flushiter field being initialised from the current on-disk
658 	 * value and hence we must also read the inode off disk even when
659 	 * initializing new inodes.
660 	 */
661 	if (xfs_has_v3inodes(mp) && (flags & XFS_IGET_CREATE)) {
662 		VFS_I(ip)->i_generation = get_random_u32();
663 	} else {
664 		struct xfs_buf		*bp;
665 
666 		error = xfs_read_icluster(pag, tp, ip->i_imap.im_agbno, &bp);
667 		if (error)
668 			goto out_destroy;
669 
670 		error = xfs_inode_from_disk(ip,
671 				xfs_buf_offset(bp, ip->i_imap.im_boffset));
672 		if (!error)
673 			xfs_buf_set_ref(bp, XFS_INO_REF);
674 		else
675 			xfs_inode_mark_sick(ip, XFS_SICK_INO_CORE);
676 		xfs_trans_brelse(tp, bp);
677 
678 		if (error)
679 			goto out_destroy;
680 	}
681 
682 	trace_xfs_iget_miss(ip);
683 
684 	/*
685 	 * Check the inode free state is valid. This also detects lookup
686 	 * racing with unlinks.
687 	 */
688 	error = xfs_iget_check_free_state(ip, flags);
689 	if (error)
690 		goto out_destroy;
691 
692 	/*
693 	 * Preload the radix tree so we can insert safely under the
694 	 * write spinlock. Note that we cannot sleep inside the preload
695 	 * region.
696 	 */
697 	if (radix_tree_preload(GFP_KERNEL | __GFP_NOLOCKDEP)) {
698 		error = -EAGAIN;
699 		goto out_destroy;
700 	}
701 
702 	/*
703 	 * Because the inode hasn't been added to the radix-tree yet it can't
704 	 * be found by another thread, so we can do the non-sleeping lock here.
705 	 */
706 	if (lock_flags) {
707 		if (!xfs_ilock_nowait(ip, lock_flags))
708 			BUG();
709 	}
710 
711 	/*
712 	 * These values must be set before inserting the inode into the radix
713 	 * tree as the moment it is inserted a concurrent lookup (allowed by the
714 	 * RCU locking mechanism) can find it and that lookup must see that this
715 	 * is an inode currently under construction (i.e. that XFS_INEW is set).
716 	 * The ip->i_flags_lock that protects the XFS_INEW flag forms the
717 	 * memory barrier that ensures this detection works correctly at lookup
718 	 * time.
719 	 */
720 	if (flags & XFS_IGET_DONTCACHE)
721 		d_mark_dontcache(VFS_I(ip));
722 	ip->i_udquot = NULL;
723 	ip->i_gdquot = NULL;
724 	ip->i_pdquot = NULL;
725 
726 	/* insert the new inode */
727 	spin_lock(&pag->pag_ici_lock);
728 	error = radix_tree_insert(&pag->pag_ici_root, agino, ip);
729 	if (unlikely(error)) {
730 		WARN_ON(error != -EEXIST);
731 		XFS_STATS_INC(mp, xs_ig_dup);
732 		error = -EAGAIN;
733 		goto out_preload_end;
734 	}
735 	spin_unlock(&pag->pag_ici_lock);
736 	radix_tree_preload_end();
737 
738 	*ipp = ip;
739 	return 0;
740 
741 out_preload_end:
742 	spin_unlock(&pag->pag_ici_lock);
743 	radix_tree_preload_end();
744 	if (lock_flags)
745 		xfs_iunlock(ip, lock_flags);
746 out_destroy:
747 	__destroy_inode(VFS_I(ip));
748 	xfs_inode_free(ip);
749 	return error;
750 }
751 
752 /*
753  * Look up an inode by number in the given file system.  The inode is looked up
754  * in the cache held in each AG.  If the inode is found in the cache, initialise
755  * the vfs inode if necessary.
756  *
757  * If it is not in core, read it in from the file system's device, add it to the
758  * cache and initialise the vfs inode.
759  *
760  * The inode is locked according to the value of the lock_flags parameter.
761  * Inode lookup is only done during metadata operations and not as part of the
762  * data IO path. Hence we only allow locking of the XFS_ILOCK during lookup.
763  */
764 int
765 xfs_iget(
766 	struct xfs_mount	*mp,
767 	struct xfs_trans	*tp,
768 	xfs_ino_t		ino,
769 	uint			flags,
770 	uint			lock_flags,
771 	struct xfs_inode	**ipp)
772 {
773 	struct xfs_inode	*ip;
774 	struct xfs_perag	*pag;
775 	xfs_agino_t		agino;
776 	int			error;
777 
778 	ASSERT((lock_flags & (XFS_IOLOCK_EXCL | XFS_IOLOCK_SHARED)) == 0);
779 
780 	/* reject inode numbers outside existing AGs */
781 	if (!xfs_verify_ino(mp, ino))
782 		return -EINVAL;
783 
784 	XFS_STATS_INC(mp, xs_ig_attempts);
785 
786 	/* get the perag structure and ensure that it's inode capable */
787 	pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, ino));
788 	agino = XFS_INO_TO_AGINO(mp, ino);
789 
790 again:
791 	error = 0;
792 	rcu_read_lock();
793 	ip = radix_tree_lookup(&pag->pag_ici_root, agino);
794 
795 	if (ip) {
796 		error = xfs_iget_cache_hit(pag, ip, ino, flags, lock_flags);
797 		if (error)
798 			goto out_error_or_again;
799 	} else {
800 		rcu_read_unlock();
801 		if (flags & XFS_IGET_INCORE) {
802 			error = -ENODATA;
803 			goto out_error_or_again;
804 		}
805 		XFS_STATS_INC(mp, xs_ig_missed);
806 
807 		error = xfs_iget_cache_miss(mp, pag, tp, ino, &ip,
808 							flags, lock_flags);
809 		if (error)
810 			goto out_error_or_again;
811 	}
812 	xfs_perag_put(pag);
813 
814 	*ipp = ip;
815 
816 	/*
817 	 * If we have a real type for an on-disk inode, we can setup the inode
818 	 * now.	 If it's a new inode being created, xfs_init_new_inode will
819 	 * handle it.
820 	 */
821 	if (xfs_iflags_test(ip, XFS_INEW) && VFS_I(ip)->i_mode != 0) {
822 		xfs_setup_inode(ip);
823 		xfs_setup_iops(ip);
824 		xfs_finish_inode_setup(ip);
825 	}
826 	return 0;
827 
828 out_error_or_again:
829 	if (!(flags & (XFS_IGET_INCORE | XFS_IGET_NORETRY)) &&
830 	    error == -EAGAIN) {
831 		delay(1);
832 		goto again;
833 	}
834 	xfs_perag_put(pag);
835 	return error;
836 }
837 
838 /*
839  * Get a metadata inode.
840  *
841  * The metafile type must match the file mode exactly, and for files in the
842  * metadata directory tree, it must match the inode's metatype exactly.
843  */
844 int
845 xfs_trans_metafile_iget(
846 	struct xfs_trans	*tp,
847 	xfs_ino_t		ino,
848 	enum xfs_metafile_type	metafile_type,
849 	struct xfs_inode	**ipp)
850 {
851 	struct xfs_mount	*mp = tp->t_mountp;
852 	struct xfs_inode	*ip;
853 	umode_t			mode;
854 	int			error;
855 
856 	error = xfs_iget(mp, tp, ino, 0, 0, &ip);
857 	if (error == -EFSCORRUPTED || error == -EINVAL)
858 		goto whine;
859 	if (error)
860 		return error;
861 
862 	if (VFS_I(ip)->i_nlink == 0)
863 		goto bad_rele;
864 
865 	if (metafile_type == XFS_METAFILE_DIR)
866 		mode = S_IFDIR;
867 	else
868 		mode = S_IFREG;
869 	if (inode_wrong_type(VFS_I(ip), mode))
870 		goto bad_rele;
871 	if (xfs_has_metadir(mp)) {
872 		if (!xfs_is_metadir_inode(ip))
873 			goto bad_rele;
874 		if (metafile_type != ip->i_metatype)
875 			goto bad_rele;
876 	}
877 
878 	*ipp = ip;
879 	return 0;
880 bad_rele:
881 	xfs_irele(ip);
882 whine:
883 	xfs_err(mp, "metadata inode 0x%llx type %u is corrupt", ino,
884 			metafile_type);
885 	xfs_fs_mark_sick(mp, XFS_SICK_FS_METADIR);
886 	return -EFSCORRUPTED;
887 }
888 
889 /* Grab a metadata file if the caller doesn't already have a transaction. */
890 int
891 xfs_metafile_iget(
892 	struct xfs_mount	*mp,
893 	xfs_ino_t		ino,
894 	enum xfs_metafile_type	metafile_type,
895 	struct xfs_inode	**ipp)
896 {
897 	struct xfs_trans	*tp;
898 	int			error;
899 
900 	tp = xfs_trans_alloc_empty(mp);
901 	error = xfs_trans_metafile_iget(tp, ino, metafile_type, ipp);
902 	xfs_trans_cancel(tp);
903 	return error;
904 }
905 
906 /*
907  * Grab the inode for reclaim exclusively.
908  *
909  * We have found this inode via a lookup under RCU, so the inode may have
910  * already been freed, or it may be in the process of being recycled by
911  * xfs_iget(). In both cases, the inode will have XFS_IRECLAIM set. If the inode
912  * has been fully recycled by the time we get the i_flags_lock, XFS_IRECLAIMABLE
913  * will not be set. Hence we need to check for both these flag conditions to
914  * avoid inodes that are no longer reclaim candidates.
915  *
916  * Note: checking for other state flags here, under the i_flags_lock or not, is
917  * racy and should be avoided. Those races should be resolved only after we have
918  * ensured that we are able to reclaim this inode and the world can see that we
919  * are going to reclaim it.
920  *
921  * Return true if we grabbed it, false otherwise.
922  */
923 static bool
924 xfs_reclaim_igrab(
925 	struct xfs_inode	*ip,
926 	struct xfs_icwalk	*icw)
927 {
928 	ASSERT(rcu_read_lock_held());
929 
930 	spin_lock(&ip->i_flags_lock);
931 	if (!__xfs_iflags_test(ip, XFS_IRECLAIMABLE) ||
932 	    __xfs_iflags_test(ip, XFS_IRECLAIM)) {
933 		/* not a reclaim candidate. */
934 		spin_unlock(&ip->i_flags_lock);
935 		return false;
936 	}
937 
938 	/* Don't reclaim a sick inode unless the caller asked for it. */
939 	if (ip->i_sick &&
940 	    (!icw || !(icw->icw_flags & XFS_ICWALK_FLAG_RECLAIM_SICK))) {
941 		spin_unlock(&ip->i_flags_lock);
942 		return false;
943 	}
944 
945 	__xfs_iflags_set(ip, XFS_IRECLAIM);
946 	spin_unlock(&ip->i_flags_lock);
947 	return true;
948 }
949 
950 /*
951  * Inode reclaim is non-blocking, so the default action if progress cannot be
952  * made is to "requeue" the inode for reclaim by unlocking it and clearing the
953  * XFS_IRECLAIM flag.  If we are in a shutdown state, we don't care about
954  * blocking anymore and hence we can wait for the inode to be able to reclaim
955  * it.
956  *
957  * We do no IO here - if callers require inodes to be cleaned they must push the
958  * AIL first to trigger writeback of dirty inodes.  This enables writeback to be
959  * done in the background in a non-blocking manner, and enables memory reclaim
960  * to make progress without blocking.
961  */
962 static void
963 xfs_reclaim_inode(
964 	struct xfs_inode	*ip,
965 	struct xfs_perag	*pag)
966 {
967 	xfs_ino_t		ino = I_INO(ip); /* for radix_tree_delete */
968 
969 	if (!xfs_ilock_nowait(ip, XFS_ILOCK_EXCL))
970 		goto out;
971 	if (xfs_iflags_test_and_set(ip, XFS_IFLUSHING))
972 		goto out_iunlock;
973 
974 	/*
975 	 * Check for log shutdown because aborting the inode can move the log
976 	 * tail and corrupt in memory state. This is fine if the log is shut
977 	 * down, but if the log is still active and only the mount is shut down
978 	 * then the in-memory log tail movement caused by the abort can be
979 	 * incorrectly propagated to disk.
980 	 */
981 	if (xlog_is_shutdown(ip->i_mount->m_log)) {
982 		xfs_iunpin_wait(ip);
983 		/*
984 		 * Avoid a ABBA deadlock on the inode cluster buffer vs
985 		 * concurrent xfs_ifree_cluster() trying to mark the inode
986 		 * stale. We don't need the inode locked to run the flush abort
987 		 * code, but the flush abort needs to lock the cluster buffer.
988 		 */
989 		xfs_iunlock(ip, XFS_ILOCK_EXCL);
990 		xfs_iflush_shutdown_abort(ip);
991 		xfs_ilock(ip, XFS_ILOCK_EXCL);
992 		goto reclaim;
993 	}
994 	if (xfs_ipincount(ip))
995 		goto out_clear_flush;
996 	if (!xfs_inode_clean(ip))
997 		goto out_clear_flush;
998 
999 	xfs_iflags_clear(ip, XFS_IFLUSHING);
1000 reclaim:
1001 	trace_xfs_inode_reclaiming(ip);
1002 
1003 	/*
1004 	 * Because we use RCU freeing we need to ensure the inode always appears
1005 	 * to be reclaimed with an invalid inode number when in the free state.
1006 	 * We do this as early as possible under the ILOCK so that
1007 	 * xfs_iflush_cluster() and xfs_ifree_cluster() can be guaranteed to
1008 	 * detect races with us here. By doing this, we guarantee that once
1009 	 * xfs_iflush_cluster() or xfs_ifree_cluster() has locked XFS_ILOCK that
1010 	 * it will see either a valid inode that will serialise correctly, or it
1011 	 * will see an invalid inode that it can skip.
1012 	 */
1013 	spin_lock(&ip->i_flags_lock);
1014 	ip->i_flags = XFS_IRECLAIM;
1015 	VFS_I(ip)->i_ino = 0;
1016 	ip->i_sick = 0;
1017 	ip->i_checked = 0;
1018 	spin_unlock(&ip->i_flags_lock);
1019 
1020 	ASSERT(!ip->i_itemp || ip->i_itemp->ili_item.li_buf == NULL);
1021 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1022 
1023 	XFS_STATS_INC(ip->i_mount, xs_ig_reclaims);
1024 	/*
1025 	 * Remove the inode from the per-AG radix tree.
1026 	 *
1027 	 * Because radix_tree_delete won't complain even if the item was never
1028 	 * added to the tree assert that it's been there before to catch
1029 	 * problems with the inode life time early on.
1030 	 */
1031 	spin_lock(&pag->pag_ici_lock);
1032 	if (!radix_tree_delete(&pag->pag_ici_root,
1033 				XFS_INO_TO_AGINO(ip->i_mount, ino)))
1034 		ASSERT(0);
1035 	xfs_perag_clear_inode_tag(pag, NULLAGINO, XFS_ICI_RECLAIM_TAG);
1036 	spin_unlock(&pag->pag_ici_lock);
1037 
1038 	/*
1039 	 * Here we do an (almost) spurious inode lock in order to coordinate
1040 	 * with inode cache radix tree lookups.  This is because the lookup
1041 	 * can reference the inodes in the cache without taking references.
1042 	 *
1043 	 * We make that OK here by ensuring that we wait until the inode is
1044 	 * unlocked after the lookup before we go ahead and free it.
1045 	 */
1046 	xfs_ilock(ip, XFS_ILOCK_EXCL);
1047 	ASSERT(!ip->i_udquot && !ip->i_gdquot && !ip->i_pdquot);
1048 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1049 	ASSERT(xfs_inode_clean(ip));
1050 
1051 	__xfs_inode_free(ip);
1052 	return;
1053 
1054 out_clear_flush:
1055 	xfs_iflags_clear(ip, XFS_IFLUSHING);
1056 out_iunlock:
1057 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1058 out:
1059 	xfs_iflags_clear(ip, XFS_IRECLAIM);
1060 }
1061 
1062 /* Reclaim sick inodes if we're unmounting or the fs went down. */
1063 static inline bool
1064 xfs_want_reclaim_sick(
1065 	struct xfs_mount	*mp)
1066 {
1067 	return xfs_is_unmounting(mp) || xfs_has_norecovery(mp) ||
1068 	       xfs_is_shutdown(mp);
1069 }
1070 
1071 void
1072 xfs_reclaim_inodes(
1073 	struct xfs_mount	*mp)
1074 {
1075 	struct xfs_icwalk	icw = {
1076 		.icw_flags	= 0,
1077 	};
1078 
1079 	if (xfs_want_reclaim_sick(mp))
1080 		icw.icw_flags |= XFS_ICWALK_FLAG_RECLAIM_SICK;
1081 
1082 	while (xfs_group_marked(mp, XG_TYPE_AG, XFS_PERAG_RECLAIM_MARK)) {
1083 		xfs_ail_push_all_sync(mp->m_ail);
1084 		xfs_icwalk(mp, XFS_ICWALK_RECLAIM, &icw);
1085 	}
1086 }
1087 
1088 /*
1089  * The shrinker infrastructure determines how many inodes we should scan for
1090  * reclaim. We want as many clean inodes ready to reclaim as possible, so we
1091  * push the AIL here. We also want to proactively free up memory if we can to
1092  * minimise the amount of work memory reclaim has to do so we kick the
1093  * background reclaim if it isn't already scheduled.
1094  */
1095 long
1096 xfs_reclaim_inodes_nr(
1097 	struct xfs_mount	*mp,
1098 	unsigned long		nr_to_scan)
1099 {
1100 	struct xfs_icwalk	icw = {
1101 		.icw_flags	= XFS_ICWALK_FLAG_SCAN_LIMIT,
1102 		.icw_scan_limit	= min_t(unsigned long, LONG_MAX, nr_to_scan),
1103 	};
1104 
1105 	if (xfs_want_reclaim_sick(mp))
1106 		icw.icw_flags |= XFS_ICWALK_FLAG_RECLAIM_SICK;
1107 
1108 	/* kick background reclaimer and push the AIL */
1109 	xfs_reclaim_work_queue(mp);
1110 	xfs_ail_push_all(mp->m_ail);
1111 
1112 	xfs_icwalk(mp, XFS_ICWALK_RECLAIM, &icw);
1113 	return 0;
1114 }
1115 
1116 /*
1117  * Return the number of reclaimable inodes in the filesystem for
1118  * the shrinker to determine how much to reclaim.
1119  */
1120 long
1121 xfs_reclaim_inodes_count(
1122 	struct xfs_mount	*mp)
1123 {
1124 	XA_STATE		(xas, &mp->m_groups[XG_TYPE_AG].xa, 0);
1125 	long			reclaimable = 0;
1126 	struct xfs_perag	*pag;
1127 
1128 	rcu_read_lock();
1129 	xas_for_each_marked(&xas, pag, ULONG_MAX, XFS_PERAG_RECLAIM_MARK) {
1130 		trace_xfs_reclaim_inodes_count(pag, _THIS_IP_);
1131 		reclaimable += pag->pag_ici_reclaimable;
1132 	}
1133 	rcu_read_unlock();
1134 
1135 	return reclaimable;
1136 }
1137 
1138 STATIC bool
1139 xfs_icwalk_match_id(
1140 	struct xfs_inode	*ip,
1141 	struct xfs_icwalk	*icw)
1142 {
1143 	if ((icw->icw_flags & XFS_ICWALK_FLAG_UID) &&
1144 	    !uid_eq(VFS_I(ip)->i_uid, icw->icw_uid))
1145 		return false;
1146 
1147 	if ((icw->icw_flags & XFS_ICWALK_FLAG_GID) &&
1148 	    !gid_eq(VFS_I(ip)->i_gid, icw->icw_gid))
1149 		return false;
1150 
1151 	if ((icw->icw_flags & XFS_ICWALK_FLAG_PRID) &&
1152 	    ip->i_projid != icw->icw_prid)
1153 		return false;
1154 
1155 	return true;
1156 }
1157 
1158 /*
1159  * A union-based inode filtering algorithm. Process the inode if any of the
1160  * criteria match. This is for global/internal scans only.
1161  */
1162 STATIC bool
1163 xfs_icwalk_match_id_union(
1164 	struct xfs_inode	*ip,
1165 	struct xfs_icwalk	*icw)
1166 {
1167 	if ((icw->icw_flags & XFS_ICWALK_FLAG_UID) &&
1168 	    uid_eq(VFS_I(ip)->i_uid, icw->icw_uid))
1169 		return true;
1170 
1171 	if ((icw->icw_flags & XFS_ICWALK_FLAG_GID) &&
1172 	    gid_eq(VFS_I(ip)->i_gid, icw->icw_gid))
1173 		return true;
1174 
1175 	if ((icw->icw_flags & XFS_ICWALK_FLAG_PRID) &&
1176 	    ip->i_projid == icw->icw_prid)
1177 		return true;
1178 
1179 	return false;
1180 }
1181 
1182 /*
1183  * Is this inode @ip eligible for eof/cow block reclamation, given some
1184  * filtering parameters @icw?  The inode is eligible if @icw is null or
1185  * if the predicate functions match.
1186  */
1187 static bool
1188 xfs_icwalk_match(
1189 	struct xfs_inode	*ip,
1190 	struct xfs_icwalk	*icw)
1191 {
1192 	bool			match;
1193 
1194 	if (!icw)
1195 		return true;
1196 
1197 	if (icw->icw_flags & XFS_ICWALK_FLAG_UNION)
1198 		match = xfs_icwalk_match_id_union(ip, icw);
1199 	else
1200 		match = xfs_icwalk_match_id(ip, icw);
1201 	if (!match)
1202 		return false;
1203 
1204 	/* skip the inode if the file size is too small */
1205 	if ((icw->icw_flags & XFS_ICWALK_FLAG_MINFILESIZE) &&
1206 	    XFS_ISIZE(ip) < icw->icw_min_file_size)
1207 		return false;
1208 
1209 	return true;
1210 }
1211 
1212 /*
1213  * This is a fast pass over the inode cache to try to get reclaim moving on as
1214  * many inodes as possible in a short period of time. It kicks itself every few
1215  * seconds, as well as being kicked by the inode cache shrinker when memory
1216  * goes low.
1217  */
1218 void
1219 xfs_reclaim_worker(
1220 	struct work_struct *work)
1221 {
1222 	struct xfs_mount *mp = container_of(to_delayed_work(work),
1223 					struct xfs_mount, m_reclaim_work);
1224 
1225 	xfs_icwalk(mp, XFS_ICWALK_RECLAIM, NULL);
1226 	xfs_reclaim_work_queue(mp);
1227 }
1228 
1229 STATIC int
1230 xfs_inode_free_eofblocks(
1231 	struct xfs_inode	*ip,
1232 	struct xfs_icwalk	*icw,
1233 	unsigned int		*lockflags)
1234 {
1235 	bool			wait;
1236 
1237 	wait = icw && (icw->icw_flags & XFS_ICWALK_FLAG_SYNC);
1238 
1239 	if (!xfs_iflags_test(ip, XFS_IEOFBLOCKS))
1240 		return 0;
1241 
1242 	/*
1243 	 * If the mapping is dirty the operation can block and wait for some
1244 	 * time. Unless we are waiting, skip it.
1245 	 */
1246 	if (!wait && mapping_tagged(VFS_I(ip)->i_mapping, PAGECACHE_TAG_DIRTY))
1247 		return 0;
1248 
1249 	if (!xfs_icwalk_match(ip, icw))
1250 		return 0;
1251 
1252 	/*
1253 	 * If the caller is waiting, return -EAGAIN to keep the background
1254 	 * scanner moving and revisit the inode in a subsequent pass.
1255 	 */
1256 	if (!xfs_ilock_nowait(ip, XFS_IOLOCK_EXCL)) {
1257 		if (wait)
1258 			return -EAGAIN;
1259 		return 0;
1260 	}
1261 	*lockflags |= XFS_IOLOCK_EXCL;
1262 
1263 	if (xfs_can_free_eofblocks(ip))
1264 		return xfs_free_eofblocks(ip);
1265 
1266 	/* inode could be preallocated */
1267 	trace_xfs_inode_free_eofblocks_invalid(ip);
1268 	xfs_inode_clear_eofblocks_tag(ip);
1269 	return 0;
1270 }
1271 
1272 static void
1273 xfs_blockgc_set_iflag(
1274 	struct xfs_inode	*ip,
1275 	unsigned long		iflag)
1276 {
1277 	struct xfs_mount	*mp = ip->i_mount;
1278 	struct xfs_perag	*pag;
1279 
1280 	ASSERT((iflag & ~(XFS_IEOFBLOCKS | XFS_ICOWBLOCKS)) == 0);
1281 
1282 	/*
1283 	 * Don't bother locking the AG and looking up in the radix trees
1284 	 * if we already know that we have the tag set.
1285 	 */
1286 	if (ip->i_flags & iflag)
1287 		return;
1288 	spin_lock(&ip->i_flags_lock);
1289 	ip->i_flags |= iflag;
1290 	spin_unlock(&ip->i_flags_lock);
1291 
1292 	pag = xfs_perag_get(mp, XFS_INODE_TO_AGNO(ip));
1293 	spin_lock(&pag->pag_ici_lock);
1294 
1295 	xfs_perag_set_inode_tag(pag, XFS_INODE_TO_AGINO(ip),
1296 			XFS_ICI_BLOCKGC_TAG);
1297 
1298 	spin_unlock(&pag->pag_ici_lock);
1299 	xfs_perag_put(pag);
1300 }
1301 
1302 void
1303 xfs_inode_set_eofblocks_tag(
1304 	xfs_inode_t	*ip)
1305 {
1306 	trace_xfs_inode_set_eofblocks_tag(ip);
1307 	return xfs_blockgc_set_iflag(ip, XFS_IEOFBLOCKS);
1308 }
1309 
1310 static void
1311 xfs_blockgc_clear_iflag(
1312 	struct xfs_inode	*ip,
1313 	unsigned long		iflag)
1314 {
1315 	struct xfs_mount	*mp = ip->i_mount;
1316 	struct xfs_perag	*pag;
1317 	bool			clear_tag;
1318 
1319 	ASSERT((iflag & ~(XFS_IEOFBLOCKS | XFS_ICOWBLOCKS)) == 0);
1320 
1321 	spin_lock(&ip->i_flags_lock);
1322 	ip->i_flags &= ~iflag;
1323 	clear_tag = (ip->i_flags & (XFS_IEOFBLOCKS | XFS_ICOWBLOCKS)) == 0;
1324 	spin_unlock(&ip->i_flags_lock);
1325 
1326 	if (!clear_tag)
1327 		return;
1328 
1329 	pag = xfs_perag_get(mp, XFS_INODE_TO_AGNO(ip));
1330 	spin_lock(&pag->pag_ici_lock);
1331 
1332 	xfs_perag_clear_inode_tag(pag, XFS_INODE_TO_AGINO(ip),
1333 			XFS_ICI_BLOCKGC_TAG);
1334 
1335 	spin_unlock(&pag->pag_ici_lock);
1336 	xfs_perag_put(pag);
1337 }
1338 
1339 void
1340 xfs_inode_clear_eofblocks_tag(
1341 	xfs_inode_t	*ip)
1342 {
1343 	trace_xfs_inode_clear_eofblocks_tag(ip);
1344 	return xfs_blockgc_clear_iflag(ip, XFS_IEOFBLOCKS);
1345 }
1346 
1347 /*
1348  * Prepare to free COW fork blocks from an inode.
1349  */
1350 static bool
1351 xfs_prep_free_cowblocks(
1352 	struct xfs_inode	*ip,
1353 	struct xfs_icwalk	*icw)
1354 {
1355 	bool			sync;
1356 
1357 	sync = icw && (icw->icw_flags & XFS_ICWALK_FLAG_SYNC);
1358 
1359 	/*
1360 	 * Just clear the tag if we have an empty cow fork or none at all. It's
1361 	 * possible the inode was fully unshared since it was originally tagged.
1362 	 */
1363 	if (!xfs_inode_has_cow_data(ip)) {
1364 		trace_xfs_inode_free_cowblocks_invalid(ip);
1365 		xfs_inode_clear_cowblocks_tag(ip);
1366 		return false;
1367 	}
1368 
1369 	/*
1370 	 * A cowblocks trim of an inode can have a significant effect on
1371 	 * fragmentation even when a reasonable COW extent size hint is set.
1372 	 * Therefore, we prefer to not process cowblocks unless they are clean
1373 	 * and idle. We can never process a cowblocks inode that is dirty or has
1374 	 * in-flight I/O under any circumstances, because outstanding writeback
1375 	 * or dio expects targeted COW fork blocks exist through write
1376 	 * completion where they can be remapped into the data fork.
1377 	 *
1378 	 * Therefore, the heuristic used here is to never process inodes
1379 	 * currently opened for write from background (i.e. non-sync) scans. For
1380 	 * sync scans, use the pagecache/dio state of the inode to ensure we
1381 	 * never free COW fork blocks out from under pending I/O.
1382 	 */
1383 	if (!sync && inode_is_open_for_write(VFS_I(ip)))
1384 		return false;
1385 	return xfs_can_free_cowblocks(ip);
1386 }
1387 
1388 /*
1389  * Automatic CoW Reservation Freeing
1390  *
1391  * These functions automatically garbage collect leftover CoW reservations
1392  * that were made on behalf of a cowextsize hint when we start to run out
1393  * of quota or when the reservations sit around for too long.  If the file
1394  * has dirty pages or is undergoing writeback, its CoW reservations will
1395  * be retained.
1396  *
1397  * The actual garbage collection piggybacks off the same code that runs
1398  * the speculative EOF preallocation garbage collector.
1399  */
1400 STATIC int
1401 xfs_inode_free_cowblocks(
1402 	struct xfs_inode	*ip,
1403 	struct xfs_icwalk	*icw,
1404 	unsigned int		*lockflags)
1405 {
1406 	bool			wait;
1407 	int			ret = 0;
1408 
1409 	wait = icw && (icw->icw_flags & XFS_ICWALK_FLAG_SYNC);
1410 
1411 	if (!xfs_iflags_test(ip, XFS_ICOWBLOCKS))
1412 		return 0;
1413 
1414 	if (!xfs_prep_free_cowblocks(ip, icw))
1415 		return 0;
1416 
1417 	if (!xfs_icwalk_match(ip, icw))
1418 		return 0;
1419 
1420 	/*
1421 	 * If the caller is waiting, return -EAGAIN to keep the background
1422 	 * scanner moving and revisit the inode in a subsequent pass.
1423 	 */
1424 	if (!(*lockflags & XFS_IOLOCK_EXCL) &&
1425 	    !xfs_ilock_nowait(ip, XFS_IOLOCK_EXCL)) {
1426 		if (wait)
1427 			return -EAGAIN;
1428 		return 0;
1429 	}
1430 	*lockflags |= XFS_IOLOCK_EXCL;
1431 
1432 	if (!xfs_ilock_nowait(ip, XFS_MMAPLOCK_EXCL)) {
1433 		if (wait)
1434 			return -EAGAIN;
1435 		return 0;
1436 	}
1437 	*lockflags |= XFS_MMAPLOCK_EXCL;
1438 
1439 	/*
1440 	 * Check again, nobody else should be able to dirty blocks or change
1441 	 * the reflink iflag now that we have the first two locks held.
1442 	 */
1443 	if (xfs_prep_free_cowblocks(ip, icw))
1444 		ret = xfs_reflink_cancel_cow_range(ip, 0, NULLFILEOFF, false);
1445 	return ret;
1446 }
1447 
1448 void
1449 xfs_inode_set_cowblocks_tag(
1450 	xfs_inode_t	*ip)
1451 {
1452 	trace_xfs_inode_set_cowblocks_tag(ip);
1453 	return xfs_blockgc_set_iflag(ip, XFS_ICOWBLOCKS);
1454 }
1455 
1456 void
1457 xfs_inode_clear_cowblocks_tag(
1458 	xfs_inode_t	*ip)
1459 {
1460 	trace_xfs_inode_clear_cowblocks_tag(ip);
1461 	return xfs_blockgc_clear_iflag(ip, XFS_ICOWBLOCKS);
1462 }
1463 
1464 /* Disable post-EOF and CoW block auto-reclamation. */
1465 void
1466 xfs_blockgc_stop(
1467 	struct xfs_mount	*mp)
1468 {
1469 	struct xfs_perag	*pag = NULL;
1470 
1471 	if (!xfs_clear_blockgc_enabled(mp))
1472 		return;
1473 
1474 	while ((pag = xfs_perag_next(mp, pag)))
1475 		cancel_delayed_work_sync(&pag->pag_blockgc_work);
1476 	trace_xfs_blockgc_stop(mp, __return_address);
1477 }
1478 
1479 /* Enable post-EOF and CoW block auto-reclamation. */
1480 void
1481 xfs_blockgc_start(
1482 	struct xfs_mount	*mp)
1483 {
1484 	struct xfs_perag	*pag = NULL;
1485 
1486 	if (xfs_set_blockgc_enabled(mp))
1487 		return;
1488 
1489 	trace_xfs_blockgc_start(mp, __return_address);
1490 	while ((pag = xfs_perag_grab_next_tag(mp, pag, XFS_ICI_BLOCKGC_TAG)))
1491 		xfs_blockgc_queue(pag);
1492 }
1493 
1494 /* Don't try to run block gc on an inode that's in any of these states. */
1495 #define XFS_BLOCKGC_NOGRAB_IFLAGS	(XFS_INEW | \
1496 					 XFS_NEED_INACTIVE | \
1497 					 XFS_INACTIVATING | \
1498 					 XFS_IRECLAIMABLE | \
1499 					 XFS_IRECLAIM)
1500 /*
1501  * Decide if the given @ip is eligible for garbage collection of speculative
1502  * preallocations, and grab it if so.  Returns true if it's ready to go or
1503  * false if we should just ignore it.
1504  */
1505 static bool
1506 xfs_blockgc_igrab(
1507 	struct xfs_inode	*ip)
1508 {
1509 	struct inode		*inode = VFS_I(ip);
1510 
1511 	ASSERT(rcu_read_lock_held());
1512 
1513 	/* Check for stale RCU freed inode */
1514 	spin_lock(&ip->i_flags_lock);
1515 	if (!I_INO(ip))
1516 		goto out_unlock_noent;
1517 
1518 	if (ip->i_flags & XFS_BLOCKGC_NOGRAB_IFLAGS)
1519 		goto out_unlock_noent;
1520 	spin_unlock(&ip->i_flags_lock);
1521 
1522 	/* nothing to sync during shutdown */
1523 	if (xfs_is_shutdown(ip->i_mount))
1524 		return false;
1525 
1526 	/* If we can't grab the inode, it must on it's way to reclaim. */
1527 	if (!igrab(inode))
1528 		return false;
1529 
1530 	/* inode is valid */
1531 	return true;
1532 
1533 out_unlock_noent:
1534 	spin_unlock(&ip->i_flags_lock);
1535 	return false;
1536 }
1537 
1538 /* Scan one incore inode for block preallocations that we can remove. */
1539 static int
1540 xfs_blockgc_scan_inode(
1541 	struct xfs_inode	*ip,
1542 	struct xfs_icwalk	*icw)
1543 {
1544 	unsigned int		lockflags = 0;
1545 	int			error;
1546 
1547 	error = xfs_inode_free_eofblocks(ip, icw, &lockflags);
1548 	if (error)
1549 		goto unlock;
1550 
1551 	error = xfs_inode_free_cowblocks(ip, icw, &lockflags);
1552 unlock:
1553 	if (lockflags)
1554 		xfs_iunlock(ip, lockflags);
1555 	xfs_irele(ip);
1556 	return error;
1557 }
1558 
1559 /* Background worker that trims preallocated space. */
1560 void
1561 xfs_blockgc_worker(
1562 	struct work_struct	*work)
1563 {
1564 	struct xfs_perag	*pag = container_of(to_delayed_work(work),
1565 					struct xfs_perag, pag_blockgc_work);
1566 	struct xfs_mount	*mp = pag_mount(pag);
1567 	int			error;
1568 
1569 	trace_xfs_blockgc_worker(mp, __return_address);
1570 
1571 	error = xfs_icwalk_ag(pag, XFS_ICWALK_BLOCKGC, NULL);
1572 	if (error)
1573 		xfs_info(mp, "AG %u preallocation gc worker failed, err=%d",
1574 				pag_agno(pag), error);
1575 	xfs_blockgc_queue(pag);
1576 }
1577 
1578 /*
1579  * Try to free space in the filesystem by purging inactive inodes, eofblocks
1580  * and cowblocks.
1581  */
1582 int
1583 xfs_blockgc_free_space(
1584 	struct xfs_mount	*mp,
1585 	struct xfs_icwalk	*icw)
1586 {
1587 	int			error;
1588 
1589 	trace_xfs_blockgc_free_space(mp, icw, _RET_IP_);
1590 
1591 	error = xfs_icwalk(mp, XFS_ICWALK_BLOCKGC, icw);
1592 	if (error)
1593 		return error;
1594 
1595 	return xfs_inodegc_flush(mp);
1596 }
1597 
1598 /*
1599  * Reclaim all the free space that we can by scheduling the background blockgc
1600  * and inodegc workers immediately and waiting for them all to clear.
1601  */
1602 int
1603 xfs_blockgc_flush_all(
1604 	struct xfs_mount	*mp)
1605 {
1606 	struct xfs_perag	*pag = NULL;
1607 
1608 	trace_xfs_blockgc_flush_all(mp, __return_address);
1609 
1610 	/*
1611 	 * For each blockgc worker, move its queue time up to now.  If it wasn't
1612 	 * queued, it will not be requeued.  Then flush whatever is left.
1613 	 */
1614 	while ((pag = xfs_perag_grab_next_tag(mp, pag, XFS_ICI_BLOCKGC_TAG)))
1615 		mod_delayed_work(mp->m_blockgc_wq, &pag->pag_blockgc_work, 0);
1616 
1617 	while ((pag = xfs_perag_grab_next_tag(mp, pag, XFS_ICI_BLOCKGC_TAG)))
1618 		flush_delayed_work(&pag->pag_blockgc_work);
1619 
1620 	return xfs_inodegc_flush(mp);
1621 }
1622 
1623 /*
1624  * Run cow/eofblocks scans on the supplied dquots.  We don't know exactly which
1625  * quota caused an allocation failure, so we make a best effort by including
1626  * each quota under low free space conditions (less than 1% free space) in the
1627  * scan.
1628  *
1629  * Callers must not hold any inode's ILOCK.  If requesting a synchronous scan
1630  * (XFS_ICWALK_FLAG_SYNC), the caller also must not hold any inode's IOLOCK or
1631  * MMAPLOCK.
1632  */
1633 int
1634 xfs_blockgc_free_dquots(
1635 	struct xfs_mount	*mp,
1636 	struct xfs_dquot	*udqp,
1637 	struct xfs_dquot	*gdqp,
1638 	struct xfs_dquot	*pdqp,
1639 	unsigned int		iwalk_flags)
1640 {
1641 	struct xfs_icwalk	icw = {0};
1642 	bool			do_work = false;
1643 
1644 	if (!udqp && !gdqp && !pdqp)
1645 		return 0;
1646 
1647 	/*
1648 	 * Run a scan to free blocks using the union filter to cover all
1649 	 * applicable quotas in a single scan.
1650 	 */
1651 	icw.icw_flags = XFS_ICWALK_FLAG_UNION | iwalk_flags;
1652 
1653 	if (XFS_IS_UQUOTA_ENFORCED(mp) && udqp && xfs_dquot_lowsp(udqp)) {
1654 		icw.icw_uid = make_kuid(mp->m_super->s_user_ns, udqp->q_id);
1655 		icw.icw_flags |= XFS_ICWALK_FLAG_UID;
1656 		do_work = true;
1657 	}
1658 
1659 	if (XFS_IS_UQUOTA_ENFORCED(mp) && gdqp && xfs_dquot_lowsp(gdqp)) {
1660 		icw.icw_gid = make_kgid(mp->m_super->s_user_ns, gdqp->q_id);
1661 		icw.icw_flags |= XFS_ICWALK_FLAG_GID;
1662 		do_work = true;
1663 	}
1664 
1665 	if (XFS_IS_PQUOTA_ENFORCED(mp) && pdqp && xfs_dquot_lowsp(pdqp)) {
1666 		icw.icw_prid = pdqp->q_id;
1667 		icw.icw_flags |= XFS_ICWALK_FLAG_PRID;
1668 		do_work = true;
1669 	}
1670 
1671 	if (!do_work)
1672 		return 0;
1673 
1674 	return xfs_blockgc_free_space(mp, &icw);
1675 }
1676 
1677 /* Run cow/eofblocks scans on the quotas attached to the inode. */
1678 int
1679 xfs_blockgc_free_quota(
1680 	struct xfs_inode	*ip,
1681 	unsigned int		iwalk_flags)
1682 {
1683 	return xfs_blockgc_free_dquots(ip->i_mount,
1684 			xfs_inode_dquot(ip, XFS_DQTYPE_USER),
1685 			xfs_inode_dquot(ip, XFS_DQTYPE_GROUP),
1686 			xfs_inode_dquot(ip, XFS_DQTYPE_PROJ), iwalk_flags);
1687 }
1688 
1689 /* XFS Inode Cache Walking Code */
1690 
1691 /*
1692  * The inode lookup is done in batches to keep the amount of lock traffic and
1693  * radix tree lookups to a minimum. The batch size is a trade off between
1694  * lookup reduction and stack usage. This is in the reclaim path, so we can't
1695  * be too greedy.
1696  */
1697 #define XFS_LOOKUP_BATCH	32
1698 
1699 
1700 /*
1701  * Decide if we want to grab this inode in anticipation of doing work towards
1702  * the goal.
1703  */
1704 static inline bool
1705 xfs_icwalk_igrab(
1706 	enum xfs_icwalk_goal	goal,
1707 	struct xfs_inode	*ip,
1708 	struct xfs_icwalk	*icw)
1709 {
1710 	switch (goal) {
1711 	case XFS_ICWALK_BLOCKGC:
1712 		return xfs_blockgc_igrab(ip);
1713 	case XFS_ICWALK_RECLAIM:
1714 		return xfs_reclaim_igrab(ip, icw);
1715 	default:
1716 		return false;
1717 	}
1718 }
1719 
1720 /*
1721  * Process an inode.  Each processing function must handle any state changes
1722  * made by the icwalk igrab function.  Return -EAGAIN to skip an inode.
1723  */
1724 static inline int
1725 xfs_icwalk_process_inode(
1726 	enum xfs_icwalk_goal	goal,
1727 	struct xfs_inode	*ip,
1728 	struct xfs_perag	*pag,
1729 	struct xfs_icwalk	*icw)
1730 {
1731 	int			error = 0;
1732 
1733 	switch (goal) {
1734 	case XFS_ICWALK_BLOCKGC:
1735 		error = xfs_blockgc_scan_inode(ip, icw);
1736 		break;
1737 	case XFS_ICWALK_RECLAIM:
1738 		xfs_reclaim_inode(ip, pag);
1739 		break;
1740 	}
1741 	return error;
1742 }
1743 
1744 /*
1745  * For a given per-AG structure @pag and a goal, grab qualifying inodes and
1746  * process them in some manner.
1747  */
1748 static int
1749 xfs_icwalk_ag(
1750 	struct xfs_perag	*pag,
1751 	enum xfs_icwalk_goal	goal,
1752 	struct xfs_icwalk	*icw)
1753 {
1754 	struct xfs_mount	*mp = pag_mount(pag);
1755 	uint32_t		first_index;
1756 	int			last_error = 0;
1757 	int			skipped;
1758 	bool			done;
1759 	int			nr_found;
1760 
1761 restart:
1762 	done = false;
1763 	skipped = 0;
1764 	if (goal == XFS_ICWALK_RECLAIM)
1765 		first_index = READ_ONCE(pag->pag_ici_reclaim_cursor);
1766 	else
1767 		first_index = 0;
1768 	nr_found = 0;
1769 	do {
1770 		struct xfs_inode *batch[XFS_LOOKUP_BATCH];
1771 		int		error = 0;
1772 		int		i;
1773 
1774 		rcu_read_lock();
1775 
1776 		nr_found = radix_tree_gang_lookup_tag(&pag->pag_ici_root,
1777 				(void **) batch, first_index,
1778 				XFS_LOOKUP_BATCH, goal);
1779 		if (!nr_found) {
1780 			done = true;
1781 			rcu_read_unlock();
1782 			break;
1783 		}
1784 
1785 		/*
1786 		 * Grab the inodes before we drop the lock. if we found
1787 		 * nothing, nr == 0 and the loop will be skipped.
1788 		 */
1789 		for (i = 0; i < nr_found; i++) {
1790 			struct xfs_inode *ip = batch[i];
1791 
1792 			if (done || !xfs_icwalk_igrab(goal, ip, icw))
1793 				batch[i] = NULL;
1794 
1795 			/*
1796 			 * Update the index for the next lookup. Catch
1797 			 * overflows into the next AG range which can occur if
1798 			 * we have inodes in the last block of the AG and we
1799 			 * are currently pointing to the last inode.
1800 			 *
1801 			 * Because we may see inodes that are from the wrong AG
1802 			 * due to RCU freeing and reallocation, only update the
1803 			 * index if it lies in this AG. It was a race that lead
1804 			 * us to see this inode, so another lookup from the
1805 			 * same index will not find it again.
1806 			 */
1807 			if (XFS_INODE_TO_AGNO(ip) != pag_agno(pag))
1808 				continue;
1809 			first_index = XFS_INO_TO_AGINO(mp, I_INO(ip) + 1);
1810 			if (first_index < XFS_INODE_TO_AGINO(ip))
1811 				done = true;
1812 		}
1813 
1814 		/* unlock now we've grabbed the inodes. */
1815 		rcu_read_unlock();
1816 
1817 		for (i = 0; i < nr_found; i++) {
1818 			if (!batch[i])
1819 				continue;
1820 			error = xfs_icwalk_process_inode(goal, batch[i], pag,
1821 					icw);
1822 			if (error == -EAGAIN) {
1823 				skipped++;
1824 				continue;
1825 			}
1826 			if (error && last_error != -EFSCORRUPTED)
1827 				last_error = error;
1828 		}
1829 
1830 		/* bail out if the filesystem is corrupted.  */
1831 		if (error == -EFSCORRUPTED)
1832 			break;
1833 
1834 		cond_resched();
1835 
1836 		if (icw && (icw->icw_flags & XFS_ICWALK_FLAG_SCAN_LIMIT)) {
1837 			icw->icw_scan_limit -= XFS_LOOKUP_BATCH;
1838 			if (icw->icw_scan_limit <= 0)
1839 				break;
1840 		}
1841 	} while (nr_found && !done);
1842 
1843 	if (goal == XFS_ICWALK_RECLAIM) {
1844 		if (done)
1845 			first_index = 0;
1846 		WRITE_ONCE(pag->pag_ici_reclaim_cursor, first_index);
1847 	}
1848 
1849 	if (skipped) {
1850 		delay(1);
1851 		goto restart;
1852 	}
1853 	return last_error;
1854 }
1855 
1856 /* Walk all incore inodes to achieve a given goal. */
1857 static int
1858 xfs_icwalk(
1859 	struct xfs_mount	*mp,
1860 	enum xfs_icwalk_goal	goal,
1861 	struct xfs_icwalk	*icw)
1862 {
1863 	struct xfs_perag	*pag = NULL;
1864 	int			error = 0;
1865 	int			last_error = 0;
1866 
1867 	while ((pag = xfs_perag_grab_next_tag(mp, pag, goal))) {
1868 		error = xfs_icwalk_ag(pag, goal, icw);
1869 		if (error) {
1870 			last_error = error;
1871 			if (error == -EFSCORRUPTED) {
1872 				xfs_perag_rele(pag);
1873 				break;
1874 			}
1875 		}
1876 	}
1877 	return last_error;
1878 	BUILD_BUG_ON(XFS_ICWALK_PRIVATE_FLAGS & XFS_ICWALK_FLAGS_VALID);
1879 }
1880 
1881 #ifdef DEBUG
1882 static void
1883 xfs_check_delalloc(
1884 	struct xfs_inode	*ip,
1885 	int			whichfork)
1886 {
1887 	struct xfs_ifork	*ifp = xfs_ifork_ptr(ip, whichfork);
1888 	struct xfs_bmbt_irec	got;
1889 	struct xfs_iext_cursor	icur;
1890 
1891 	if (!ifp || !xfs_iext_lookup_extent(ip, ifp, 0, &icur, &got))
1892 		return;
1893 	do {
1894 		if (isnullstartblock(got.br_startblock)) {
1895 			xfs_warn(ip->i_mount,
1896 	"ino %llx %s fork has delalloc extent at [0x%llx:0x%llx]",
1897 				I_INO(ip),
1898 				whichfork == XFS_DATA_FORK ? "data" : "cow",
1899 				got.br_startoff, got.br_blockcount);
1900 		}
1901 	} while (xfs_iext_next_extent(ifp, &icur, &got));
1902 }
1903 #else
1904 #define xfs_check_delalloc(ip, whichfork)	do { } while (0)
1905 #endif
1906 
1907 /* Schedule the inode for reclaim. */
1908 static void
1909 xfs_inodegc_set_reclaimable(
1910 	struct xfs_inode	*ip)
1911 {
1912 	struct xfs_mount	*mp = ip->i_mount;
1913 	struct xfs_perag	*pag;
1914 
1915 	if (!xfs_is_shutdown(mp) && ip->i_delayed_blks) {
1916 		xfs_check_delalloc(ip, XFS_DATA_FORK);
1917 		xfs_check_delalloc(ip, XFS_COW_FORK);
1918 		ASSERT(0);
1919 	}
1920 
1921 	pag = xfs_perag_get(mp, XFS_INODE_TO_AGNO(ip));
1922 	spin_lock(&pag->pag_ici_lock);
1923 	spin_lock(&ip->i_flags_lock);
1924 
1925 	trace_xfs_inode_set_reclaimable(ip);
1926 	ip->i_flags &= ~(XFS_NEED_INACTIVE | XFS_INACTIVATING);
1927 	ip->i_flags |= XFS_IRECLAIMABLE;
1928 	xfs_perag_set_inode_tag(pag, XFS_INODE_TO_AGINO(ip),
1929 			XFS_ICI_RECLAIM_TAG);
1930 
1931 	spin_unlock(&ip->i_flags_lock);
1932 	spin_unlock(&pag->pag_ici_lock);
1933 	xfs_perag_put(pag);
1934 }
1935 
1936 /*
1937  * Free all speculative preallocations and possibly even the inode itself.
1938  * This is the last chance to make changes to an otherwise unreferenced file
1939  * before incore reclamation happens.
1940  */
1941 static int
1942 xfs_inodegc_inactivate(
1943 	struct xfs_inode	*ip)
1944 {
1945 	int			error;
1946 
1947 	trace_xfs_inode_inactivating(ip);
1948 	error = xfs_inactive(ip);
1949 	xfs_inodegc_set_reclaimable(ip);
1950 	return error;
1951 
1952 }
1953 
1954 void
1955 xfs_inodegc_worker(
1956 	struct work_struct	*work)
1957 {
1958 	struct xfs_inodegc	*gc = container_of(to_delayed_work(work),
1959 						struct xfs_inodegc, work);
1960 	struct llist_node	*node = llist_del_all(&gc->list);
1961 	struct xfs_inode	*ip, *n;
1962 	struct xfs_mount	*mp = gc->mp;
1963 	unsigned int		nofs_flag;
1964 
1965 	/*
1966 	 * Clear the cpu mask bit and ensure that we have seen the latest
1967 	 * update of the gc structure associated with this CPU. This matches
1968 	 * with the release semantics used when setting the cpumask bit in
1969 	 * xfs_inodegc_queue.
1970 	 */
1971 	cpumask_clear_cpu(gc->cpu, &mp->m_inodegc_cpumask);
1972 	smp_mb__after_atomic();
1973 
1974 	WRITE_ONCE(gc->items, 0);
1975 
1976 	if (!node)
1977 		return;
1978 
1979 	/*
1980 	 * We can allocate memory here while doing writeback on behalf of
1981 	 * memory reclaim.  To avoid memory allocation deadlocks set the
1982 	 * task-wide nofs context for the following operations.
1983 	 */
1984 	nofs_flag = memalloc_nofs_save();
1985 
1986 	ip = llist_entry(node, struct xfs_inode, i_gclist);
1987 	trace_xfs_inodegc_worker(mp, READ_ONCE(gc->shrinker_hits));
1988 
1989 	WRITE_ONCE(gc->shrinker_hits, 0);
1990 	llist_for_each_entry_safe(ip, n, node, i_gclist) {
1991 		int	error;
1992 
1993 		xfs_iflags_set(ip, XFS_INACTIVATING);
1994 		error = xfs_inodegc_inactivate(ip);
1995 		if (error && !gc->error)
1996 			gc->error = error;
1997 	}
1998 
1999 	memalloc_nofs_restore(nofs_flag);
2000 }
2001 
2002 /*
2003  * Expedite all pending inodegc work to run immediately. This does not wait for
2004  * completion of the work.
2005  */
2006 void
2007 xfs_inodegc_push(
2008 	struct xfs_mount	*mp)
2009 {
2010 	if (!xfs_is_inodegc_enabled(mp))
2011 		return;
2012 	trace_xfs_inodegc_push(mp, __return_address);
2013 	xfs_inodegc_queue_all(mp);
2014 }
2015 
2016 /*
2017  * Force all currently queued inode inactivation work to run immediately and
2018  * wait for the work to finish.
2019  */
2020 int
2021 xfs_inodegc_flush(
2022 	struct xfs_mount	*mp)
2023 {
2024 	xfs_inodegc_push(mp);
2025 	trace_xfs_inodegc_flush(mp, __return_address);
2026 	return xfs_inodegc_wait_all(mp);
2027 }
2028 
2029 /*
2030  * Flush all the pending work and then disable the inode inactivation background
2031  * workers and wait for them to stop.  Caller must hold sb->s_umount to
2032  * coordinate changes in the inodegc_enabled state.
2033  */
2034 void
2035 xfs_inodegc_stop(
2036 	struct xfs_mount	*mp)
2037 {
2038 	bool			rerun;
2039 
2040 	if (!xfs_clear_inodegc_enabled(mp))
2041 		return;
2042 
2043 	/*
2044 	 * Drain all pending inodegc work, including inodes that could be
2045 	 * queued by racing xfs_inodegc_queue or xfs_inodegc_shrinker_scan
2046 	 * threads that sample the inodegc state just prior to us clearing it.
2047 	 * The inodegc flag state prevents new threads from queuing more
2048 	 * inodes, so we queue pending work items and flush the workqueue until
2049 	 * all inodegc lists are empty.  IOWs, we cannot use drain_workqueue
2050 	 * here because it does not allow other unserialized mechanisms to
2051 	 * reschedule inodegc work while this draining is in progress.
2052 	 */
2053 	xfs_inodegc_queue_all(mp);
2054 	do {
2055 		flush_workqueue(mp->m_inodegc_wq);
2056 		rerun = xfs_inodegc_queue_all(mp);
2057 	} while (rerun);
2058 
2059 	trace_xfs_inodegc_stop(mp, __return_address);
2060 }
2061 
2062 /*
2063  * Enable the inode inactivation background workers and schedule deferred inode
2064  * inactivation work if there is any.  Caller must hold sb->s_umount to
2065  * coordinate changes in the inodegc_enabled state.
2066  */
2067 void
2068 xfs_inodegc_start(
2069 	struct xfs_mount	*mp)
2070 {
2071 	if (xfs_set_inodegc_enabled(mp))
2072 		return;
2073 
2074 	trace_xfs_inodegc_start(mp, __return_address);
2075 	xfs_inodegc_queue_all(mp);
2076 }
2077 
2078 #ifdef CONFIG_XFS_RT
2079 static inline bool
2080 xfs_inodegc_want_queue_rt_file(
2081 	struct xfs_inode	*ip)
2082 {
2083 	struct xfs_mount	*mp = ip->i_mount;
2084 
2085 	if (!XFS_IS_REALTIME_INODE(ip) || xfs_has_zoned(mp))
2086 		return false;
2087 
2088 	if (xfs_compare_freecounter(mp, XC_FREE_RTEXTENTS,
2089 				mp->m_low_rtexts[XFS_LOWSP_5_PCNT],
2090 				XFS_FDBLOCKS_BATCH) < 0)
2091 		return true;
2092 
2093 	return false;
2094 }
2095 #else
2096 # define xfs_inodegc_want_queue_rt_file(ip)	(false)
2097 #endif /* CONFIG_XFS_RT */
2098 
2099 /*
2100  * Schedule the inactivation worker when:
2101  *
2102  *  - We've accumulated more than one inode cluster buffer's worth of inodes.
2103  *  - There is less than 5% free space left.
2104  *  - Any of the quotas for this inode are near an enforcement limit.
2105  */
2106 static inline bool
2107 xfs_inodegc_want_queue_work(
2108 	struct xfs_inode	*ip,
2109 	unsigned int		items)
2110 {
2111 	struct xfs_mount	*mp = ip->i_mount;
2112 
2113 	if (items > mp->m_ino_geo.inodes_per_cluster)
2114 		return true;
2115 
2116 	if (xfs_compare_freecounter(mp, XC_FREE_BLOCKS,
2117 				mp->m_low_space[XFS_LOWSP_5_PCNT],
2118 				XFS_FDBLOCKS_BATCH) < 0)
2119 		return true;
2120 
2121 	if (xfs_inodegc_want_queue_rt_file(ip))
2122 		return true;
2123 
2124 	if (xfs_inode_near_dquot_enforcement(ip, XFS_DQTYPE_USER))
2125 		return true;
2126 
2127 	if (xfs_inode_near_dquot_enforcement(ip, XFS_DQTYPE_GROUP))
2128 		return true;
2129 
2130 	if (xfs_inode_near_dquot_enforcement(ip, XFS_DQTYPE_PROJ))
2131 		return true;
2132 
2133 	return false;
2134 }
2135 
2136 /*
2137  * Upper bound on the number of inodes in each AG that can be queued for
2138  * inactivation at any given time, to avoid monopolizing the workqueue.
2139  */
2140 #define XFS_INODEGC_MAX_BACKLOG		(4 * XFS_INODES_PER_CHUNK)
2141 
2142 /*
2143  * Make the frontend wait for inactivations when:
2144  *
2145  *  - Memory shrinkers queued the inactivation worker and it hasn't finished.
2146  *  - The queue depth exceeds the maximum allowable percpu backlog.
2147  *
2148  * Note: If we are in a NOFS context here (e.g. current thread is running a
2149  * transaction) the we don't want to block here as inodegc progress may require
2150  * filesystem resources we hold to make progress and that could result in a
2151  * deadlock. Hence we skip out of here if we are in a scoped NOFS context.
2152  */
2153 static inline bool
2154 xfs_inodegc_want_flush_work(
2155 	struct xfs_inode	*ip,
2156 	unsigned int		items,
2157 	unsigned int		shrinker_hits)
2158 {
2159 	if (current->flags & PF_MEMALLOC_NOFS)
2160 		return false;
2161 
2162 	if (shrinker_hits > 0)
2163 		return true;
2164 
2165 	if (items > XFS_INODEGC_MAX_BACKLOG)
2166 		return true;
2167 
2168 	return false;
2169 }
2170 
2171 /*
2172  * Queue a background inactivation worker if there are inodes that need to be
2173  * inactivated and higher level xfs code hasn't disabled the background
2174  * workers.
2175  */
2176 static void
2177 xfs_inodegc_queue(
2178 	struct xfs_inode	*ip)
2179 {
2180 	struct xfs_mount	*mp = ip->i_mount;
2181 	struct xfs_inodegc	*gc;
2182 	int			items;
2183 	unsigned int		shrinker_hits;
2184 	unsigned int		cpu_nr;
2185 	unsigned long		queue_delay = 1;
2186 
2187 	trace_xfs_inode_set_need_inactive(ip);
2188 	spin_lock(&ip->i_flags_lock);
2189 	ip->i_flags |= XFS_NEED_INACTIVE;
2190 	spin_unlock(&ip->i_flags_lock);
2191 
2192 	cpu_nr = get_cpu();
2193 	gc = this_cpu_ptr(mp->m_inodegc);
2194 	llist_add(&ip->i_gclist, &gc->list);
2195 	items = READ_ONCE(gc->items);
2196 	WRITE_ONCE(gc->items, items + 1);
2197 	shrinker_hits = READ_ONCE(gc->shrinker_hits);
2198 
2199 	/*
2200 	 * Ensure the list add is always seen by anyone who finds the cpumask
2201 	 * bit set. This effectively gives the cpumask bit set operation
2202 	 * release ordering semantics.
2203 	 */
2204 	smp_mb__before_atomic();
2205 	if (!cpumask_test_cpu(cpu_nr, &mp->m_inodegc_cpumask))
2206 		cpumask_test_and_set_cpu(cpu_nr, &mp->m_inodegc_cpumask);
2207 
2208 	/*
2209 	 * We queue the work while holding the current CPU so that the work
2210 	 * is scheduled to run on this CPU.
2211 	 */
2212 	if (!xfs_is_inodegc_enabled(mp)) {
2213 		put_cpu();
2214 		return;
2215 	}
2216 
2217 	if (xfs_inodegc_want_queue_work(ip, items))
2218 		queue_delay = 0;
2219 
2220 	trace_xfs_inodegc_queue(mp, __return_address);
2221 	mod_delayed_work_on(current_cpu(), mp->m_inodegc_wq, &gc->work,
2222 			queue_delay);
2223 	put_cpu();
2224 
2225 	if (xfs_inodegc_want_flush_work(ip, items, shrinker_hits)) {
2226 		trace_xfs_inodegc_throttle(mp, __return_address);
2227 		flush_delayed_work(&gc->work);
2228 	}
2229 }
2230 
2231 /*
2232  * We set the inode flag atomically with the radix tree tag.  Once we get tag
2233  * lookups on the radix tree, this inode flag can go away.
2234  *
2235  * We always use background reclaim here because even if the inode is clean, it
2236  * still may be under IO and hence we have wait for IO completion to occur
2237  * before we can reclaim the inode. The background reclaim path handles this
2238  * more efficiently than we can here, so simply let background reclaim tear down
2239  * all inodes.
2240  */
2241 void
2242 xfs_inode_mark_reclaimable(
2243 	struct xfs_inode	*ip)
2244 {
2245 	struct xfs_mount	*mp = ip->i_mount;
2246 	bool			need_inactive;
2247 
2248 	XFS_STATS_INC(mp, xs_inode_mark_reclaimable);
2249 
2250 	/*
2251 	 * We should never get here with any of the reclaim flags already set.
2252 	 */
2253 	ASSERT_ALWAYS(!xfs_iflags_test(ip, XFS_ALL_IRECLAIM_FLAGS));
2254 
2255 	need_inactive = xfs_inode_needs_inactive(ip);
2256 	if (need_inactive) {
2257 		xfs_inodegc_queue(ip);
2258 		return;
2259 	}
2260 
2261 	/* Going straight to reclaim, so drop the dquots. */
2262 	xfs_qm_dqdetach(ip);
2263 	xfs_inodegc_set_reclaimable(ip);
2264 }
2265 
2266 /*
2267  * Register a phony shrinker so that we can run background inodegc sooner when
2268  * there's memory pressure.  Inactivation does not itself free any memory but
2269  * it does make inodes reclaimable, which eventually frees memory.
2270  *
2271  * The count function, seek value, and batch value are crafted to trigger the
2272  * scan function during the second round of scanning.  Hopefully this means
2273  * that we reclaimed enough memory that initiating metadata transactions won't
2274  * make things worse.
2275  */
2276 #define XFS_INODEGC_SHRINKER_COUNT	(1UL << DEF_PRIORITY)
2277 #define XFS_INODEGC_SHRINKER_BATCH	((XFS_INODEGC_SHRINKER_COUNT / 2) + 1)
2278 
2279 static unsigned long
2280 xfs_inodegc_shrinker_count(
2281 	struct shrinker		*shrink,
2282 	struct shrink_control	*sc)
2283 {
2284 	struct xfs_mount	*mp = shrink->private_data;
2285 	struct xfs_inodegc	*gc;
2286 	int			cpu;
2287 
2288 	if (!xfs_is_inodegc_enabled(mp))
2289 		return 0;
2290 
2291 	for_each_cpu(cpu, &mp->m_inodegc_cpumask) {
2292 		gc = per_cpu_ptr(mp->m_inodegc, cpu);
2293 		if (!llist_empty(&gc->list))
2294 			return XFS_INODEGC_SHRINKER_COUNT;
2295 	}
2296 
2297 	return 0;
2298 }
2299 
2300 static unsigned long
2301 xfs_inodegc_shrinker_scan(
2302 	struct shrinker		*shrink,
2303 	struct shrink_control	*sc)
2304 {
2305 	struct xfs_mount	*mp = shrink->private_data;
2306 	struct xfs_inodegc	*gc;
2307 	int			cpu;
2308 	bool			no_items = true;
2309 
2310 	if (!xfs_is_inodegc_enabled(mp))
2311 		return SHRINK_STOP;
2312 
2313 	trace_xfs_inodegc_shrinker_scan(mp, sc, __return_address);
2314 
2315 	for_each_cpu(cpu, &mp->m_inodegc_cpumask) {
2316 		gc = per_cpu_ptr(mp->m_inodegc, cpu);
2317 		if (!llist_empty(&gc->list)) {
2318 			unsigned int	h = READ_ONCE(gc->shrinker_hits);
2319 
2320 			WRITE_ONCE(gc->shrinker_hits, h + 1);
2321 			mod_delayed_work_on(cpu, mp->m_inodegc_wq, &gc->work, 0);
2322 			no_items = false;
2323 		}
2324 	}
2325 
2326 	/*
2327 	 * If there are no inodes to inactivate, we don't want the shrinker
2328 	 * to think there's deferred work to call us back about.
2329 	 */
2330 	if (no_items)
2331 		return LONG_MAX;
2332 
2333 	return SHRINK_STOP;
2334 }
2335 
2336 /* Register a shrinker so we can accelerate inodegc and throttle queuing. */
2337 int
2338 xfs_inodegc_register_shrinker(
2339 	struct xfs_mount	*mp)
2340 {
2341 	mp->m_inodegc_shrinker = shrinker_alloc(SHRINKER_NONSLAB,
2342 						"xfs-inodegc:%s",
2343 						mp->m_super->s_id);
2344 	if (!mp->m_inodegc_shrinker)
2345 		return -ENOMEM;
2346 
2347 	mp->m_inodegc_shrinker->count_objects = xfs_inodegc_shrinker_count;
2348 	mp->m_inodegc_shrinker->scan_objects = xfs_inodegc_shrinker_scan;
2349 	mp->m_inodegc_shrinker->seeks = 0;
2350 	mp->m_inodegc_shrinker->batch = XFS_INODEGC_SHRINKER_BATCH;
2351 	mp->m_inodegc_shrinker->private_data = mp;
2352 
2353 	shrinker_register(mp->m_inodegc_shrinker);
2354 
2355 	return 0;
2356 }
2357