1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Copyright (c) 2000-2006 Silicon Graphics, Inc.
4 * All Rights Reserved.
5 */
6#include <linux/iversion.h>
7
8#include "xfs.h"
9#include "xfs_fs.h"
10#include "xfs_shared.h"
11#include "xfs_format.h"
12#include "xfs_log_format.h"
13#include "xfs_trans_resv.h"
14#include "xfs_mount.h"
15#include "xfs_defer.h"
16#include "xfs_inode.h"
17#include "xfs_dir2.h"
18#include "xfs_attr.h"
19#include "xfs_bit.h"
20#include "xfs_trans_space.h"
21#include "xfs_trans.h"
22#include "xfs_buf_item.h"
23#include "xfs_inode_item.h"
24#include "xfs_iunlink_item.h"
25#include "xfs_ialloc.h"
26#include "xfs_bmap.h"
27#include "xfs_bmap_util.h"
28#include "xfs_errortag.h"
29#include "xfs_error.h"
30#include "xfs_quota.h"
31#include "xfs_filestream.h"
32#include "xfs_trace.h"
33#include "xfs_icache.h"
34#include "xfs_symlink.h"
35#include "xfs_trans_priv.h"
36#include "xfs_log.h"
37#include "xfs_bmap_btree.h"
38#include "xfs_reflink.h"
39#include "xfs_ag.h"
40#include "xfs_log_priv.h"
41#include "xfs_health.h"
42#include "xfs_pnfs.h"
43#include "xfs_parent.h"
44#include "xfs_xattr.h"
45
46struct kmem_cache *xfs_inode_cache;
47
48/*
49 * helper function to extract extent size hint from inode
50 */
51xfs_extlen_t
52xfs_get_extsz_hint(
53	struct xfs_inode	*ip)
54{
55	/*
56	 * No point in aligning allocations if we need to COW to actually
57	 * write to them.
58	 */
59	if (xfs_is_always_cow_inode(ip))
60		return 0;
61	if ((ip->i_diflags & XFS_DIFLAG_EXTSIZE) && ip->i_extsize)
62		return ip->i_extsize;
63	if (XFS_IS_REALTIME_INODE(ip) &&
64	    ip->i_mount->m_sb.sb_rextsize > 1)
65		return ip->i_mount->m_sb.sb_rextsize;
66	return 0;
67}
68
69/*
70 * Helper function to extract CoW extent size hint from inode.
71 * Between the extent size hint and the CoW extent size hint, we
72 * return the greater of the two.  If the value is zero (automatic),
73 * use the default size.
74 */
75xfs_extlen_t
76xfs_get_cowextsz_hint(
77	struct xfs_inode	*ip)
78{
79	xfs_extlen_t		a, b;
80
81	a = 0;
82	if (ip->i_diflags2 & XFS_DIFLAG2_COWEXTSIZE)
83		a = ip->i_cowextsize;
84	b = xfs_get_extsz_hint(ip);
85
86	a = max(a, b);
87	if (a == 0)
88		return XFS_DEFAULT_COWEXTSZ_HINT;
89	return a;
90}
91
92/*
93 * These two are wrapper routines around the xfs_ilock() routine used to
94 * centralize some grungy code.  They are used in places that wish to lock the
95 * inode solely for reading the extents.  The reason these places can't just
96 * call xfs_ilock(ip, XFS_ILOCK_SHARED) is that the inode lock also guards to
97 * bringing in of the extents from disk for a file in b-tree format.  If the
98 * inode is in b-tree format, then we need to lock the inode exclusively until
99 * the extents are read in.  Locking it exclusively all the time would limit
100 * our parallelism unnecessarily, though.  What we do instead is check to see
101 * if the extents have been read in yet, and only lock the inode exclusively
102 * if they have not.
103 *
104 * The functions return a value which should be given to the corresponding
105 * xfs_iunlock() call.
106 */
107uint
108xfs_ilock_data_map_shared(
109	struct xfs_inode	*ip)
110{
111	uint			lock_mode = XFS_ILOCK_SHARED;
112
113	if (xfs_need_iread_extents(&ip->i_df))
114		lock_mode = XFS_ILOCK_EXCL;
115	xfs_ilock(ip, lock_mode);
116	return lock_mode;
117}
118
119uint
120xfs_ilock_attr_map_shared(
121	struct xfs_inode	*ip)
122{
123	uint			lock_mode = XFS_ILOCK_SHARED;
124
125	if (xfs_inode_has_attr_fork(ip) && xfs_need_iread_extents(&ip->i_af))
126		lock_mode = XFS_ILOCK_EXCL;
127	xfs_ilock(ip, lock_mode);
128	return lock_mode;
129}
130
131/*
132 * You can't set both SHARED and EXCL for the same lock,
133 * and only XFS_IOLOCK_SHARED, XFS_IOLOCK_EXCL, XFS_MMAPLOCK_SHARED,
134 * XFS_MMAPLOCK_EXCL, XFS_ILOCK_SHARED, XFS_ILOCK_EXCL are valid values
135 * to set in lock_flags.
136 */
137static inline void
138xfs_lock_flags_assert(
139	uint		lock_flags)
140{
141	ASSERT((lock_flags & (XFS_IOLOCK_SHARED | XFS_IOLOCK_EXCL)) !=
142		(XFS_IOLOCK_SHARED | XFS_IOLOCK_EXCL));
143	ASSERT((lock_flags & (XFS_MMAPLOCK_SHARED | XFS_MMAPLOCK_EXCL)) !=
144		(XFS_MMAPLOCK_SHARED | XFS_MMAPLOCK_EXCL));
145	ASSERT((lock_flags & (XFS_ILOCK_SHARED | XFS_ILOCK_EXCL)) !=
146		(XFS_ILOCK_SHARED | XFS_ILOCK_EXCL));
147	ASSERT((lock_flags & ~(XFS_LOCK_MASK | XFS_LOCK_SUBCLASS_MASK)) == 0);
148	ASSERT(lock_flags != 0);
149}
150
151/*
152 * In addition to i_rwsem in the VFS inode, the xfs inode contains 2
153 * multi-reader locks: invalidate_lock and the i_lock.  This routine allows
154 * various combinations of the locks to be obtained.
155 *
156 * The 3 locks should always be ordered so that the IO lock is obtained first,
157 * the mmap lock second and the ilock last in order to prevent deadlock.
158 *
159 * Basic locking order:
160 *
161 * i_rwsem -> invalidate_lock -> page_lock -> i_ilock
162 *
163 * mmap_lock locking order:
164 *
165 * i_rwsem -> page lock -> mmap_lock
166 * mmap_lock -> invalidate_lock -> page_lock
167 *
168 * The difference in mmap_lock locking order mean that we cannot hold the
169 * invalidate_lock over syscall based read(2)/write(2) based IO. These IO paths
170 * can fault in pages during copy in/out (for buffered IO) or require the
171 * mmap_lock in get_user_pages() to map the user pages into the kernel address
172 * space for direct IO. Similarly the i_rwsem cannot be taken inside a page
173 * fault because page faults already hold the mmap_lock.
174 *
175 * Hence to serialise fully against both syscall and mmap based IO, we need to
176 * take both the i_rwsem and the invalidate_lock. These locks should *only* be
177 * both taken in places where we need to invalidate the page cache in a race
178 * free manner (e.g. truncate, hole punch and other extent manipulation
179 * functions).
180 */
181void
182xfs_ilock(
183	xfs_inode_t		*ip,
184	uint			lock_flags)
185{
186	trace_xfs_ilock(ip, lock_flags, _RET_IP_);
187
188	xfs_lock_flags_assert(lock_flags);
189
190	if (lock_flags & XFS_IOLOCK_EXCL) {
191		down_write_nested(&VFS_I(ip)->i_rwsem,
192				  XFS_IOLOCK_DEP(lock_flags));
193	} else if (lock_flags & XFS_IOLOCK_SHARED) {
194		down_read_nested(&VFS_I(ip)->i_rwsem,
195				 XFS_IOLOCK_DEP(lock_flags));
196	}
197
198	if (lock_flags & XFS_MMAPLOCK_EXCL) {
199		down_write_nested(&VFS_I(ip)->i_mapping->invalidate_lock,
200				  XFS_MMAPLOCK_DEP(lock_flags));
201	} else if (lock_flags & XFS_MMAPLOCK_SHARED) {
202		down_read_nested(&VFS_I(ip)->i_mapping->invalidate_lock,
203				 XFS_MMAPLOCK_DEP(lock_flags));
204	}
205
206	if (lock_flags & XFS_ILOCK_EXCL)
207		down_write_nested(&ip->i_lock, XFS_ILOCK_DEP(lock_flags));
208	else if (lock_flags & XFS_ILOCK_SHARED)
209		down_read_nested(&ip->i_lock, XFS_ILOCK_DEP(lock_flags));
210}
211
212/*
213 * This is just like xfs_ilock(), except that the caller
214 * is guaranteed not to sleep.  It returns 1 if it gets
215 * the requested locks and 0 otherwise.  If the IO lock is
216 * obtained but the inode lock cannot be, then the IO lock
217 * is dropped before returning.
218 *
219 * ip -- the inode being locked
220 * lock_flags -- this parameter indicates the inode's locks to be
221 *       to be locked.  See the comment for xfs_ilock() for a list
222 *	 of valid values.
223 */
224int
225xfs_ilock_nowait(
226	xfs_inode_t		*ip,
227	uint			lock_flags)
228{
229	trace_xfs_ilock_nowait(ip, lock_flags, _RET_IP_);
230
231	xfs_lock_flags_assert(lock_flags);
232
233	if (lock_flags & XFS_IOLOCK_EXCL) {
234		if (!down_write_trylock(&VFS_I(ip)->i_rwsem))
235			goto out;
236	} else if (lock_flags & XFS_IOLOCK_SHARED) {
237		if (!down_read_trylock(&VFS_I(ip)->i_rwsem))
238			goto out;
239	}
240
241	if (lock_flags & XFS_MMAPLOCK_EXCL) {
242		if (!down_write_trylock(&VFS_I(ip)->i_mapping->invalidate_lock))
243			goto out_undo_iolock;
244	} else if (lock_flags & XFS_MMAPLOCK_SHARED) {
245		if (!down_read_trylock(&VFS_I(ip)->i_mapping->invalidate_lock))
246			goto out_undo_iolock;
247	}
248
249	if (lock_flags & XFS_ILOCK_EXCL) {
250		if (!down_write_trylock(&ip->i_lock))
251			goto out_undo_mmaplock;
252	} else if (lock_flags & XFS_ILOCK_SHARED) {
253		if (!down_read_trylock(&ip->i_lock))
254			goto out_undo_mmaplock;
255	}
256	return 1;
257
258out_undo_mmaplock:
259	if (lock_flags & XFS_MMAPLOCK_EXCL)
260		up_write(&VFS_I(ip)->i_mapping->invalidate_lock);
261	else if (lock_flags & XFS_MMAPLOCK_SHARED)
262		up_read(&VFS_I(ip)->i_mapping->invalidate_lock);
263out_undo_iolock:
264	if (lock_flags & XFS_IOLOCK_EXCL)
265		up_write(&VFS_I(ip)->i_rwsem);
266	else if (lock_flags & XFS_IOLOCK_SHARED)
267		up_read(&VFS_I(ip)->i_rwsem);
268out:
269	return 0;
270}
271
272/*
273 * xfs_iunlock() is used to drop the inode locks acquired with
274 * xfs_ilock() and xfs_ilock_nowait().  The caller must pass
275 * in the flags given to xfs_ilock() or xfs_ilock_nowait() so
276 * that we know which locks to drop.
277 *
278 * ip -- the inode being unlocked
279 * lock_flags -- this parameter indicates the inode's locks to be
280 *       to be unlocked.  See the comment for xfs_ilock() for a list
281 *	 of valid values for this parameter.
282 *
283 */
284void
285xfs_iunlock(
286	xfs_inode_t		*ip,
287	uint			lock_flags)
288{
289	xfs_lock_flags_assert(lock_flags);
290
291	if (lock_flags & XFS_IOLOCK_EXCL)
292		up_write(&VFS_I(ip)->i_rwsem);
293	else if (lock_flags & XFS_IOLOCK_SHARED)
294		up_read(&VFS_I(ip)->i_rwsem);
295
296	if (lock_flags & XFS_MMAPLOCK_EXCL)
297		up_write(&VFS_I(ip)->i_mapping->invalidate_lock);
298	else if (lock_flags & XFS_MMAPLOCK_SHARED)
299		up_read(&VFS_I(ip)->i_mapping->invalidate_lock);
300
301	if (lock_flags & XFS_ILOCK_EXCL)
302		up_write(&ip->i_lock);
303	else if (lock_flags & XFS_ILOCK_SHARED)
304		up_read(&ip->i_lock);
305
306	trace_xfs_iunlock(ip, lock_flags, _RET_IP_);
307}
308
309/*
310 * give up write locks.  the i/o lock cannot be held nested
311 * if it is being demoted.
312 */
313void
314xfs_ilock_demote(
315	xfs_inode_t		*ip,
316	uint			lock_flags)
317{
318	ASSERT(lock_flags & (XFS_IOLOCK_EXCL|XFS_MMAPLOCK_EXCL|XFS_ILOCK_EXCL));
319	ASSERT((lock_flags &
320		~(XFS_IOLOCK_EXCL|XFS_MMAPLOCK_EXCL|XFS_ILOCK_EXCL)) == 0);
321
322	if (lock_flags & XFS_ILOCK_EXCL)
323		downgrade_write(&ip->i_lock);
324	if (lock_flags & XFS_MMAPLOCK_EXCL)
325		downgrade_write(&VFS_I(ip)->i_mapping->invalidate_lock);
326	if (lock_flags & XFS_IOLOCK_EXCL)
327		downgrade_write(&VFS_I(ip)->i_rwsem);
328
329	trace_xfs_ilock_demote(ip, lock_flags, _RET_IP_);
330}
331
332void
333xfs_assert_ilocked(
334	struct xfs_inode	*ip,
335	uint			lock_flags)
336{
337	/*
338	 * Sometimes we assert the ILOCK is held exclusively, but we're in
339	 * a workqueue, so lockdep doesn't know we're the owner.
340	 */
341	if (lock_flags & XFS_ILOCK_SHARED)
342		rwsem_assert_held(&ip->i_lock);
343	else if (lock_flags & XFS_ILOCK_EXCL)
344		rwsem_assert_held_write_nolockdep(&ip->i_lock);
345
346	if (lock_flags & XFS_MMAPLOCK_SHARED)
347		rwsem_assert_held(&VFS_I(ip)->i_mapping->invalidate_lock);
348	else if (lock_flags & XFS_MMAPLOCK_EXCL)
349		rwsem_assert_held_write(&VFS_I(ip)->i_mapping->invalidate_lock);
350
351	if (lock_flags & XFS_IOLOCK_SHARED)
352		rwsem_assert_held(&VFS_I(ip)->i_rwsem);
353	else if (lock_flags & XFS_IOLOCK_EXCL)
354		rwsem_assert_held_write(&VFS_I(ip)->i_rwsem);
355}
356
357/*
358 * xfs_lockdep_subclass_ok() is only used in an ASSERT, so is only called when
359 * DEBUG or XFS_WARN is set. And MAX_LOCKDEP_SUBCLASSES is then only defined
360 * when CONFIG_LOCKDEP is set. Hence the complex define below to avoid build
361 * errors and warnings.
362 */
363#if (defined(DEBUG) || defined(XFS_WARN)) && defined(CONFIG_LOCKDEP)
364static bool
365xfs_lockdep_subclass_ok(
366	int subclass)
367{
368	return subclass < MAX_LOCKDEP_SUBCLASSES;
369}
370#else
371#define xfs_lockdep_subclass_ok(subclass)	(true)
372#endif
373
374/*
375 * Bump the subclass so xfs_lock_inodes() acquires each lock with a different
376 * value. This can be called for any type of inode lock combination, including
377 * parent locking. Care must be taken to ensure we don't overrun the subclass
378 * storage fields in the class mask we build.
379 */
380static inline uint
381xfs_lock_inumorder(
382	uint	lock_mode,
383	uint	subclass)
384{
385	uint	class = 0;
386
387	ASSERT(!(lock_mode & (XFS_ILOCK_PARENT | XFS_ILOCK_RTBITMAP |
388			      XFS_ILOCK_RTSUM)));
389	ASSERT(xfs_lockdep_subclass_ok(subclass));
390
391	if (lock_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL)) {
392		ASSERT(subclass <= XFS_IOLOCK_MAX_SUBCLASS);
393		class += subclass << XFS_IOLOCK_SHIFT;
394	}
395
396	if (lock_mode & (XFS_MMAPLOCK_SHARED|XFS_MMAPLOCK_EXCL)) {
397		ASSERT(subclass <= XFS_MMAPLOCK_MAX_SUBCLASS);
398		class += subclass << XFS_MMAPLOCK_SHIFT;
399	}
400
401	if (lock_mode & (XFS_ILOCK_SHARED|XFS_ILOCK_EXCL)) {
402		ASSERT(subclass <= XFS_ILOCK_MAX_SUBCLASS);
403		class += subclass << XFS_ILOCK_SHIFT;
404	}
405
406	return (lock_mode & ~XFS_LOCK_SUBCLASS_MASK) | class;
407}
408
409/*
410 * The following routine will lock n inodes in exclusive mode.  We assume the
411 * caller calls us with the inodes in i_ino order.
412 *
413 * We need to detect deadlock where an inode that we lock is in the AIL and we
414 * start waiting for another inode that is locked by a thread in a long running
415 * transaction (such as truncate). This can result in deadlock since the long
416 * running trans might need to wait for the inode we just locked in order to
417 * push the tail and free space in the log.
418 *
419 * xfs_lock_inodes() can only be used to lock one type of lock at a time -
420 * the iolock, the mmaplock or the ilock, but not more than one at a time. If we
421 * lock more than one at a time, lockdep will report false positives saying we
422 * have violated locking orders.
423 */
424void
425xfs_lock_inodes(
426	struct xfs_inode	**ips,
427	int			inodes,
428	uint			lock_mode)
429{
430	int			attempts = 0;
431	uint			i;
432	int			j;
433	bool			try_lock;
434	struct xfs_log_item	*lp;
435
436	/*
437	 * Currently supports between 2 and 5 inodes with exclusive locking.  We
438	 * support an arbitrary depth of locking here, but absolute limits on
439	 * inodes depend on the type of locking and the limits placed by
440	 * lockdep annotations in xfs_lock_inumorder.  These are all checked by
441	 * the asserts.
442	 */
443	ASSERT(ips && inodes >= 2 && inodes <= 5);
444	ASSERT(lock_mode & (XFS_IOLOCK_EXCL | XFS_MMAPLOCK_EXCL |
445			    XFS_ILOCK_EXCL));
446	ASSERT(!(lock_mode & (XFS_IOLOCK_SHARED | XFS_MMAPLOCK_SHARED |
447			      XFS_ILOCK_SHARED)));
448	ASSERT(!(lock_mode & XFS_MMAPLOCK_EXCL) ||
449		inodes <= XFS_MMAPLOCK_MAX_SUBCLASS + 1);
450	ASSERT(!(lock_mode & XFS_ILOCK_EXCL) ||
451		inodes <= XFS_ILOCK_MAX_SUBCLASS + 1);
452
453	if (lock_mode & XFS_IOLOCK_EXCL) {
454		ASSERT(!(lock_mode & (XFS_MMAPLOCK_EXCL | XFS_ILOCK_EXCL)));
455	} else if (lock_mode & XFS_MMAPLOCK_EXCL)
456		ASSERT(!(lock_mode & XFS_ILOCK_EXCL));
457
458again:
459	try_lock = false;
460	i = 0;
461	for (; i < inodes; i++) {
462		ASSERT(ips[i]);
463
464		if (i && (ips[i] == ips[i - 1]))	/* Already locked */
465			continue;
466
467		/*
468		 * If try_lock is not set yet, make sure all locked inodes are
469		 * not in the AIL.  If any are, set try_lock to be used later.
470		 */
471		if (!try_lock) {
472			for (j = (i - 1); j >= 0 && !try_lock; j--) {
473				lp = &ips[j]->i_itemp->ili_item;
474				if (lp && test_bit(XFS_LI_IN_AIL, &lp->li_flags))
475					try_lock = true;
476			}
477		}
478
479		/*
480		 * If any of the previous locks we have locked is in the AIL,
481		 * we must TRY to get the second and subsequent locks. If
482		 * we can't get any, we must release all we have
483		 * and try again.
484		 */
485		if (!try_lock) {
486			xfs_ilock(ips[i], xfs_lock_inumorder(lock_mode, i));
487			continue;
488		}
489
490		/* try_lock means we have an inode locked that is in the AIL. */
491		ASSERT(i != 0);
492		if (xfs_ilock_nowait(ips[i], xfs_lock_inumorder(lock_mode, i)))
493			continue;
494
495		/*
496		 * Unlock all previous guys and try again.  xfs_iunlock will try
497		 * to push the tail if the inode is in the AIL.
498		 */
499		attempts++;
500		for (j = i - 1; j >= 0; j--) {
501			/*
502			 * Check to see if we've already unlocked this one.  Not
503			 * the first one going back, and the inode ptr is the
504			 * same.
505			 */
506			if (j != (i - 1) && ips[j] == ips[j + 1])
507				continue;
508
509			xfs_iunlock(ips[j], lock_mode);
510		}
511
512		if ((attempts % 5) == 0) {
513			delay(1); /* Don't just spin the CPU */
514		}
515		goto again;
516	}
517}
518
519/*
520 * xfs_lock_two_inodes() can only be used to lock ilock. The iolock and
521 * mmaplock must be double-locked separately since we use i_rwsem and
522 * invalidate_lock for that. We now support taking one lock EXCL and the
523 * other SHARED.
524 */
525void
526xfs_lock_two_inodes(
527	struct xfs_inode	*ip0,
528	uint			ip0_mode,
529	struct xfs_inode	*ip1,
530	uint			ip1_mode)
531{
532	int			attempts = 0;
533	struct xfs_log_item	*lp;
534
535	ASSERT(hweight32(ip0_mode) == 1);
536	ASSERT(hweight32(ip1_mode) == 1);
537	ASSERT(!(ip0_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL)));
538	ASSERT(!(ip1_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL)));
539	ASSERT(!(ip0_mode & (XFS_MMAPLOCK_SHARED|XFS_MMAPLOCK_EXCL)));
540	ASSERT(!(ip1_mode & (XFS_MMAPLOCK_SHARED|XFS_MMAPLOCK_EXCL)));
541	ASSERT(ip0->i_ino != ip1->i_ino);
542
543	if (ip0->i_ino > ip1->i_ino) {
544		swap(ip0, ip1);
545		swap(ip0_mode, ip1_mode);
546	}
547
548 again:
549	xfs_ilock(ip0, xfs_lock_inumorder(ip0_mode, 0));
550
551	/*
552	 * If the first lock we have locked is in the AIL, we must TRY to get
553	 * the second lock. If we can't get it, we must release the first one
554	 * and try again.
555	 */
556	lp = &ip0->i_itemp->ili_item;
557	if (lp && test_bit(XFS_LI_IN_AIL, &lp->li_flags)) {
558		if (!xfs_ilock_nowait(ip1, xfs_lock_inumorder(ip1_mode, 1))) {
559			xfs_iunlock(ip0, ip0_mode);
560			if ((++attempts % 5) == 0)
561				delay(1); /* Don't just spin the CPU */
562			goto again;
563		}
564	} else {
565		xfs_ilock(ip1, xfs_lock_inumorder(ip1_mode, 1));
566	}
567}
568
569uint
570xfs_ip2xflags(
571	struct xfs_inode	*ip)
572{
573	uint			flags = 0;
574
575	if (ip->i_diflags & XFS_DIFLAG_ANY) {
576		if (ip->i_diflags & XFS_DIFLAG_REALTIME)
577			flags |= FS_XFLAG_REALTIME;
578		if (ip->i_diflags & XFS_DIFLAG_PREALLOC)
579			flags |= FS_XFLAG_PREALLOC;
580		if (ip->i_diflags & XFS_DIFLAG_IMMUTABLE)
581			flags |= FS_XFLAG_IMMUTABLE;
582		if (ip->i_diflags & XFS_DIFLAG_APPEND)
583			flags |= FS_XFLAG_APPEND;
584		if (ip->i_diflags & XFS_DIFLAG_SYNC)
585			flags |= FS_XFLAG_SYNC;
586		if (ip->i_diflags & XFS_DIFLAG_NOATIME)
587			flags |= FS_XFLAG_NOATIME;
588		if (ip->i_diflags & XFS_DIFLAG_NODUMP)
589			flags |= FS_XFLAG_NODUMP;
590		if (ip->i_diflags & XFS_DIFLAG_RTINHERIT)
591			flags |= FS_XFLAG_RTINHERIT;
592		if (ip->i_diflags & XFS_DIFLAG_PROJINHERIT)
593			flags |= FS_XFLAG_PROJINHERIT;
594		if (ip->i_diflags & XFS_DIFLAG_NOSYMLINKS)
595			flags |= FS_XFLAG_NOSYMLINKS;
596		if (ip->i_diflags & XFS_DIFLAG_EXTSIZE)
597			flags |= FS_XFLAG_EXTSIZE;
598		if (ip->i_diflags & XFS_DIFLAG_EXTSZINHERIT)
599			flags |= FS_XFLAG_EXTSZINHERIT;
600		if (ip->i_diflags & XFS_DIFLAG_NODEFRAG)
601			flags |= FS_XFLAG_NODEFRAG;
602		if (ip->i_diflags & XFS_DIFLAG_FILESTREAM)
603			flags |= FS_XFLAG_FILESTREAM;
604	}
605
606	if (ip->i_diflags2 & XFS_DIFLAG2_ANY) {
607		if (ip->i_diflags2 & XFS_DIFLAG2_DAX)
608			flags |= FS_XFLAG_DAX;
609		if (ip->i_diflags2 & XFS_DIFLAG2_COWEXTSIZE)
610			flags |= FS_XFLAG_COWEXTSIZE;
611	}
612
613	if (xfs_inode_has_attr_fork(ip))
614		flags |= FS_XFLAG_HASATTR;
615	return flags;
616}
617
618/*
619 * Lookups up an inode from "name". If ci_name is not NULL, then a CI match
620 * is allowed, otherwise it has to be an exact match. If a CI match is found,
621 * ci_name->name will point to a the actual name (caller must free) or
622 * will be set to NULL if an exact match is found.
623 */
624int
625xfs_lookup(
626	struct xfs_inode	*dp,
627	const struct xfs_name	*name,
628	struct xfs_inode	**ipp,
629	struct xfs_name		*ci_name)
630{
631	xfs_ino_t		inum;
632	int			error;
633
634	trace_xfs_lookup(dp, name);
635
636	if (xfs_is_shutdown(dp->i_mount))
637		return -EIO;
638	if (xfs_ifork_zapped(dp, XFS_DATA_FORK))
639		return -EIO;
640
641	error = xfs_dir_lookup(NULL, dp, name, &inum, ci_name);
642	if (error)
643		goto out_unlock;
644
645	error = xfs_iget(dp->i_mount, NULL, inum, 0, 0, ipp);
646	if (error)
647		goto out_free_name;
648
649	return 0;
650
651out_free_name:
652	if (ci_name)
653		kfree(ci_name->name);
654out_unlock:
655	*ipp = NULL;
656	return error;
657}
658
659/* Propagate di_flags from a parent inode to a child inode. */
660static void
661xfs_inode_inherit_flags(
662	struct xfs_inode	*ip,
663	const struct xfs_inode	*pip)
664{
665	unsigned int		di_flags = 0;
666	xfs_failaddr_t		failaddr;
667	umode_t			mode = VFS_I(ip)->i_mode;
668
669	if (S_ISDIR(mode)) {
670		if (pip->i_diflags & XFS_DIFLAG_RTINHERIT)
671			di_flags |= XFS_DIFLAG_RTINHERIT;
672		if (pip->i_diflags & XFS_DIFLAG_EXTSZINHERIT) {
673			di_flags |= XFS_DIFLAG_EXTSZINHERIT;
674			ip->i_extsize = pip->i_extsize;
675		}
676		if (pip->i_diflags & XFS_DIFLAG_PROJINHERIT)
677			di_flags |= XFS_DIFLAG_PROJINHERIT;
678	} else if (S_ISREG(mode)) {
679		if ((pip->i_diflags & XFS_DIFLAG_RTINHERIT) &&
680		    xfs_has_realtime(ip->i_mount))
681			di_flags |= XFS_DIFLAG_REALTIME;
682		if (pip->i_diflags & XFS_DIFLAG_EXTSZINHERIT) {
683			di_flags |= XFS_DIFLAG_EXTSIZE;
684			ip->i_extsize = pip->i_extsize;
685		}
686	}
687	if ((pip->i_diflags & XFS_DIFLAG_NOATIME) &&
688	    xfs_inherit_noatime)
689		di_flags |= XFS_DIFLAG_NOATIME;
690	if ((pip->i_diflags & XFS_DIFLAG_NODUMP) &&
691	    xfs_inherit_nodump)
692		di_flags |= XFS_DIFLAG_NODUMP;
693	if ((pip->i_diflags & XFS_DIFLAG_SYNC) &&
694	    xfs_inherit_sync)
695		di_flags |= XFS_DIFLAG_SYNC;
696	if ((pip->i_diflags & XFS_DIFLAG_NOSYMLINKS) &&
697	    xfs_inherit_nosymlinks)
698		di_flags |= XFS_DIFLAG_NOSYMLINKS;
699	if ((pip->i_diflags & XFS_DIFLAG_NODEFRAG) &&
700	    xfs_inherit_nodefrag)
701		di_flags |= XFS_DIFLAG_NODEFRAG;
702	if (pip->i_diflags & XFS_DIFLAG_FILESTREAM)
703		di_flags |= XFS_DIFLAG_FILESTREAM;
704
705	ip->i_diflags |= di_flags;
706
707	/*
708	 * Inode verifiers on older kernels only check that the extent size
709	 * hint is an integer multiple of the rt extent size on realtime files.
710	 * They did not check the hint alignment on a directory with both
711	 * rtinherit and extszinherit flags set.  If the misaligned hint is
712	 * propagated from a directory into a new realtime file, new file
713	 * allocations will fail due to math errors in the rt allocator and/or
714	 * trip the verifiers.  Validate the hint settings in the new file so
715	 * that we don't let broken hints propagate.
716	 */
717	failaddr = xfs_inode_validate_extsize(ip->i_mount, ip->i_extsize,
718			VFS_I(ip)->i_mode, ip->i_diflags);
719	if (failaddr) {
720		ip->i_diflags &= ~(XFS_DIFLAG_EXTSIZE |
721				   XFS_DIFLAG_EXTSZINHERIT);
722		ip->i_extsize = 0;
723	}
724}
725
726/* Propagate di_flags2 from a parent inode to a child inode. */
727static void
728xfs_inode_inherit_flags2(
729	struct xfs_inode	*ip,
730	const struct xfs_inode	*pip)
731{
732	xfs_failaddr_t		failaddr;
733
734	if (pip->i_diflags2 & XFS_DIFLAG2_COWEXTSIZE) {
735		ip->i_diflags2 |= XFS_DIFLAG2_COWEXTSIZE;
736		ip->i_cowextsize = pip->i_cowextsize;
737	}
738	if (pip->i_diflags2 & XFS_DIFLAG2_DAX)
739		ip->i_diflags2 |= XFS_DIFLAG2_DAX;
740
741	/* Don't let invalid cowextsize hints propagate. */
742	failaddr = xfs_inode_validate_cowextsize(ip->i_mount, ip->i_cowextsize,
743			VFS_I(ip)->i_mode, ip->i_diflags, ip->i_diflags2);
744	if (failaddr) {
745		ip->i_diflags2 &= ~XFS_DIFLAG2_COWEXTSIZE;
746		ip->i_cowextsize = 0;
747	}
748}
749
750/*
751 * Initialise a newly allocated inode and return the in-core inode to the
752 * caller locked exclusively.
753 *
754 * Caller is responsible for unlocking the inode manually upon return
755 */
756int
757xfs_init_new_inode(
758	struct mnt_idmap	*idmap,
759	struct xfs_trans	*tp,
760	struct xfs_inode	*pip,
761	xfs_ino_t		ino,
762	umode_t			mode,
763	xfs_nlink_t		nlink,
764	dev_t			rdev,
765	prid_t			prid,
766	bool			init_xattrs,
767	struct xfs_inode	**ipp)
768{
769	struct inode		*dir = pip ? VFS_I(pip) : NULL;
770	struct xfs_mount	*mp = tp->t_mountp;
771	struct xfs_inode	*ip;
772	unsigned int		flags;
773	int			error;
774	struct timespec64	tv;
775	struct inode		*inode;
776
777	/*
778	 * Protect against obviously corrupt allocation btree records. Later
779	 * xfs_iget checks will catch re-allocation of other active in-memory
780	 * and on-disk inodes. If we don't catch reallocating the parent inode
781	 * here we will deadlock in xfs_iget() so we have to do these checks
782	 * first.
783	 */
784	if ((pip && ino == pip->i_ino) || !xfs_verify_dir_ino(mp, ino)) {
785		xfs_alert(mp, "Allocated a known in-use inode 0x%llx!", ino);
786		xfs_agno_mark_sick(mp, XFS_INO_TO_AGNO(mp, ino),
787				XFS_SICK_AG_INOBT);
788		return -EFSCORRUPTED;
789	}
790
791	/*
792	 * Get the in-core inode with the lock held exclusively to prevent
793	 * others from looking at until we're done.
794	 */
795	error = xfs_iget(mp, tp, ino, XFS_IGET_CREATE, XFS_ILOCK_EXCL, &ip);
796	if (error)
797		return error;
798
799	ASSERT(ip != NULL);
800	inode = VFS_I(ip);
801	set_nlink(inode, nlink);
802	inode->i_rdev = rdev;
803	ip->i_projid = prid;
804
805	if (dir && !(dir->i_mode & S_ISGID) && xfs_has_grpid(mp)) {
806		inode_fsuid_set(inode, idmap);
807		inode->i_gid = dir->i_gid;
808		inode->i_mode = mode;
809	} else {
810		inode_init_owner(idmap, inode, dir, mode);
811	}
812
813	/*
814	 * If the group ID of the new file does not match the effective group
815	 * ID or one of the supplementary group IDs, the S_ISGID bit is cleared
816	 * (and only if the irix_sgid_inherit compatibility variable is set).
817	 */
818	if (irix_sgid_inherit && (inode->i_mode & S_ISGID) &&
819	    !vfsgid_in_group_p(i_gid_into_vfsgid(idmap, inode)))
820		inode->i_mode &= ~S_ISGID;
821
822	ip->i_disk_size = 0;
823	ip->i_df.if_nextents = 0;
824	ASSERT(ip->i_nblocks == 0);
825
826	tv = inode_set_ctime_current(inode);
827	inode_set_mtime_to_ts(inode, tv);
828	inode_set_atime_to_ts(inode, tv);
829
830	ip->i_extsize = 0;
831	ip->i_diflags = 0;
832
833	if (xfs_has_v3inodes(mp)) {
834		inode_set_iversion(inode, 1);
835		ip->i_cowextsize = 0;
836		ip->i_crtime = tv;
837	}
838
839	flags = XFS_ILOG_CORE;
840	switch (mode & S_IFMT) {
841	case S_IFIFO:
842	case S_IFCHR:
843	case S_IFBLK:
844	case S_IFSOCK:
845		ip->i_df.if_format = XFS_DINODE_FMT_DEV;
846		flags |= XFS_ILOG_DEV;
847		break;
848	case S_IFREG:
849	case S_IFDIR:
850		if (pip && (pip->i_diflags & XFS_DIFLAG_ANY))
851			xfs_inode_inherit_flags(ip, pip);
852		if (pip && (pip->i_diflags2 & XFS_DIFLAG2_ANY))
853			xfs_inode_inherit_flags2(ip, pip);
854		fallthrough;
855	case S_IFLNK:
856		ip->i_df.if_format = XFS_DINODE_FMT_EXTENTS;
857		ip->i_df.if_bytes = 0;
858		ip->i_df.if_data = NULL;
859		break;
860	default:
861		ASSERT(0);
862	}
863
864	/*
865	 * If we need to create attributes immediately after allocating the
866	 * inode, initialise an empty attribute fork right now. We use the
867	 * default fork offset for attributes here as we don't know exactly what
868	 * size or how many attributes we might be adding. We can do this
869	 * safely here because we know the data fork is completely empty and
870	 * this saves us from needing to run a separate transaction to set the
871	 * fork offset in the immediate future.
872	 */
873	if (init_xattrs && xfs_has_attr(mp)) {
874		ip->i_forkoff = xfs_default_attroffset(ip) >> 3;
875		xfs_ifork_init_attr(ip, XFS_DINODE_FMT_EXTENTS, 0);
876	}
877
878	/*
879	 * Log the new values stuffed into the inode.
880	 */
881	xfs_trans_ijoin(tp, ip, 0);
882	xfs_trans_log_inode(tp, ip, flags);
883
884	/* now that we have an i_mode we can setup the inode structure */
885	xfs_setup_inode(ip);
886
887	*ipp = ip;
888	return 0;
889}
890
891/*
892 * Decrement the link count on an inode & log the change.  If this causes the
893 * link count to go to zero, move the inode to AGI unlinked list so that it can
894 * be freed when the last active reference goes away via xfs_inactive().
895 */
896int
897xfs_droplink(
898	struct xfs_trans	*tp,
899	struct xfs_inode	*ip)
900{
901	struct inode		*inode = VFS_I(ip);
902
903	xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_CHG);
904
905	if (inode->i_nlink == 0) {
906		xfs_info_ratelimited(tp->t_mountp,
907 "Inode 0x%llx link count dropped below zero.  Pinning link count.",
908				ip->i_ino);
909		set_nlink(inode, XFS_NLINK_PINNED);
910	}
911	if (inode->i_nlink != XFS_NLINK_PINNED)
912		drop_nlink(inode);
913
914	xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
915
916	if (inode->i_nlink)
917		return 0;
918
919	return xfs_iunlink(tp, ip);
920}
921
922/*
923 * Increment the link count on an inode & log the change.
924 */
925void
926xfs_bumplink(
927	struct xfs_trans	*tp,
928	struct xfs_inode	*ip)
929{
930	struct inode		*inode = VFS_I(ip);
931
932	xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_CHG);
933
934	if (inode->i_nlink == XFS_NLINK_PINNED - 1)
935		xfs_info_ratelimited(tp->t_mountp,
936 "Inode 0x%llx link count exceeded maximum.  Pinning link count.",
937				ip->i_ino);
938	if (inode->i_nlink != XFS_NLINK_PINNED)
939		inc_nlink(inode);
940
941	xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
942}
943
944#ifdef CONFIG_XFS_LIVE_HOOKS
945/*
946 * Use a static key here to reduce the overhead of directory live update hooks.
947 * If the compiler supports jump labels, the static branch will be replaced by
948 * a nop sled when there are no hook users.  Online fsck is currently the only
949 * caller, so this is a reasonable tradeoff.
950 *
951 * Note: Patching the kernel code requires taking the cpu hotplug lock.  Other
952 * parts of the kernel allocate memory with that lock held, which means that
953 * XFS callers cannot hold any locks that might be used by memory reclaim or
954 * writeback when calling the static_branch_{inc,dec} functions.
955 */
956DEFINE_STATIC_XFS_HOOK_SWITCH(xfs_dir_hooks_switch);
957
958void
959xfs_dir_hook_disable(void)
960{
961	xfs_hooks_switch_off(&xfs_dir_hooks_switch);
962}
963
964void
965xfs_dir_hook_enable(void)
966{
967	xfs_hooks_switch_on(&xfs_dir_hooks_switch);
968}
969
970/* Call hooks for a directory update relating to a child dirent update. */
971inline void
972xfs_dir_update_hook(
973	struct xfs_inode		*dp,
974	struct xfs_inode		*ip,
975	int				delta,
976	const struct xfs_name		*name)
977{
978	if (xfs_hooks_switched_on(&xfs_dir_hooks_switch)) {
979		struct xfs_dir_update_params	p = {
980			.dp		= dp,
981			.ip		= ip,
982			.delta		= delta,
983			.name		= name,
984		};
985		struct xfs_mount	*mp = ip->i_mount;
986
987		xfs_hooks_call(&mp->m_dir_update_hooks, 0, &p);
988	}
989}
990
991/* Call the specified function during a directory update. */
992int
993xfs_dir_hook_add(
994	struct xfs_mount	*mp,
995	struct xfs_dir_hook	*hook)
996{
997	return xfs_hooks_add(&mp->m_dir_update_hooks, &hook->dirent_hook);
998}
999
1000/* Stop calling the specified function during a directory update. */
1001void
1002xfs_dir_hook_del(
1003	struct xfs_mount	*mp,
1004	struct xfs_dir_hook	*hook)
1005{
1006	xfs_hooks_del(&mp->m_dir_update_hooks, &hook->dirent_hook);
1007}
1008
1009/* Configure directory update hook functions. */
1010void
1011xfs_dir_hook_setup(
1012	struct xfs_dir_hook	*hook,
1013	notifier_fn_t		mod_fn)
1014{
1015	xfs_hook_setup(&hook->dirent_hook, mod_fn);
1016}
1017#endif /* CONFIG_XFS_LIVE_HOOKS */
1018
1019int
1020xfs_create(
1021	struct mnt_idmap	*idmap,
1022	struct xfs_inode	*dp,
1023	struct xfs_name		*name,
1024	umode_t			mode,
1025	dev_t			rdev,
1026	bool			init_xattrs,
1027	xfs_inode_t		**ipp)
1028{
1029	int			is_dir = S_ISDIR(mode);
1030	struct xfs_mount	*mp = dp->i_mount;
1031	struct xfs_inode	*ip = NULL;
1032	struct xfs_trans	*tp = NULL;
1033	int			error;
1034	bool			unlock_dp_on_error = false;
1035	prid_t			prid;
1036	struct xfs_dquot	*udqp = NULL;
1037	struct xfs_dquot	*gdqp = NULL;
1038	struct xfs_dquot	*pdqp = NULL;
1039	struct xfs_trans_res	*tres;
1040	uint			resblks;
1041	xfs_ino_t		ino;
1042	struct xfs_parent_args	*ppargs;
1043
1044	trace_xfs_create(dp, name);
1045
1046	if (xfs_is_shutdown(mp))
1047		return -EIO;
1048	if (xfs_ifork_zapped(dp, XFS_DATA_FORK))
1049		return -EIO;
1050
1051	prid = xfs_get_initial_prid(dp);
1052
1053	/*
1054	 * Make sure that we have allocated dquot(s) on disk.
1055	 */
1056	error = xfs_qm_vop_dqalloc(dp, mapped_fsuid(idmap, &init_user_ns),
1057			mapped_fsgid(idmap, &init_user_ns), prid,
1058			XFS_QMOPT_QUOTALL | XFS_QMOPT_INHERIT,
1059			&udqp, &gdqp, &pdqp);
1060	if (error)
1061		return error;
1062
1063	if (is_dir) {
1064		resblks = xfs_mkdir_space_res(mp, name->len);
1065		tres = &M_RES(mp)->tr_mkdir;
1066	} else {
1067		resblks = xfs_create_space_res(mp, name->len);
1068		tres = &M_RES(mp)->tr_create;
1069	}
1070
1071	error = xfs_parent_start(mp, &ppargs);
1072	if (error)
1073		goto out_release_dquots;
1074
1075	/*
1076	 * Initially assume that the file does not exist and
1077	 * reserve the resources for that case.  If that is not
1078	 * the case we'll drop the one we have and get a more
1079	 * appropriate transaction later.
1080	 */
1081	error = xfs_trans_alloc_icreate(mp, tres, udqp, gdqp, pdqp, resblks,
1082			&tp);
1083	if (error == -ENOSPC) {
1084		/* flush outstanding delalloc blocks and retry */
1085		xfs_flush_inodes(mp);
1086		error = xfs_trans_alloc_icreate(mp, tres, udqp, gdqp, pdqp,
1087				resblks, &tp);
1088	}
1089	if (error)
1090		goto out_parent;
1091
1092	xfs_ilock(dp, XFS_ILOCK_EXCL | XFS_ILOCK_PARENT);
1093	unlock_dp_on_error = true;
1094
1095	/*
1096	 * A newly created regular or special file just has one directory
1097	 * entry pointing to them, but a directory also the "." entry
1098	 * pointing to itself.
1099	 */
1100	error = xfs_dialloc(&tp, dp->i_ino, mode, &ino);
1101	if (!error)
1102		error = xfs_init_new_inode(idmap, tp, dp, ino, mode,
1103				is_dir ? 2 : 1, rdev, prid, init_xattrs, &ip);
1104	if (error)
1105		goto out_trans_cancel;
1106
1107	/*
1108	 * Now we join the directory inode to the transaction.  We do not do it
1109	 * earlier because xfs_dialloc might commit the previous transaction
1110	 * (and release all the locks).  An error from here on will result in
1111	 * the transaction cancel unlocking dp so don't do it explicitly in the
1112	 * error path.
1113	 */
1114	xfs_trans_ijoin(tp, dp, 0);
1115
1116	error = xfs_dir_createname(tp, dp, name, ip->i_ino,
1117					resblks - XFS_IALLOC_SPACE_RES(mp));
1118	if (error) {
1119		ASSERT(error != -ENOSPC);
1120		goto out_trans_cancel;
1121	}
1122	xfs_trans_ichgtime(tp, dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
1123	xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
1124
1125	if (is_dir) {
1126		error = xfs_dir_init(tp, ip, dp);
1127		if (error)
1128			goto out_trans_cancel;
1129
1130		xfs_bumplink(tp, dp);
1131	}
1132
1133	/*
1134	 * If we have parent pointers, we need to add the attribute containing
1135	 * the parent information now.
1136	 */
1137	if (ppargs) {
1138		error = xfs_parent_addname(tp, ppargs, dp, name, ip);
1139		if (error)
1140			goto out_trans_cancel;
1141	}
1142
1143	/*
1144	 * Create ip with a reference from dp, and add '.' and '..' references
1145	 * if it's a directory.
1146	 */
1147	xfs_dir_update_hook(dp, ip, 1, name);
1148
1149	/*
1150	 * If this is a synchronous mount, make sure that the
1151	 * create transaction goes to disk before returning to
1152	 * the user.
1153	 */
1154	if (xfs_has_wsync(mp) || xfs_has_dirsync(mp))
1155		xfs_trans_set_sync(tp);
1156
1157	/*
1158	 * Attach the dquot(s) to the inodes and modify them incore.
1159	 * These ids of the inode couldn't have changed since the new
1160	 * inode has been locked ever since it was created.
1161	 */
1162	xfs_qm_vop_create_dqattach(tp, ip, udqp, gdqp, pdqp);
1163
1164	error = xfs_trans_commit(tp);
1165	if (error)
1166		goto out_release_inode;
1167
1168	xfs_qm_dqrele(udqp);
1169	xfs_qm_dqrele(gdqp);
1170	xfs_qm_dqrele(pdqp);
1171
1172	*ipp = ip;
1173	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1174	xfs_iunlock(dp, XFS_ILOCK_EXCL);
1175	xfs_parent_finish(mp, ppargs);
1176	return 0;
1177
1178 out_trans_cancel:
1179	xfs_trans_cancel(tp);
1180 out_release_inode:
1181	/*
1182	 * Wait until after the current transaction is aborted to finish the
1183	 * setup of the inode and release the inode.  This prevents recursive
1184	 * transactions and deadlocks from xfs_inactive.
1185	 */
1186	if (ip) {
1187		xfs_iunlock(ip, XFS_ILOCK_EXCL);
1188		xfs_finish_inode_setup(ip);
1189		xfs_irele(ip);
1190	}
1191 out_parent:
1192	xfs_parent_finish(mp, ppargs);
1193 out_release_dquots:
1194	xfs_qm_dqrele(udqp);
1195	xfs_qm_dqrele(gdqp);
1196	xfs_qm_dqrele(pdqp);
1197
1198	if (unlock_dp_on_error)
1199		xfs_iunlock(dp, XFS_ILOCK_EXCL);
1200	return error;
1201}
1202
1203int
1204xfs_create_tmpfile(
1205	struct mnt_idmap	*idmap,
1206	struct xfs_inode	*dp,
1207	umode_t			mode,
1208	bool			init_xattrs,
1209	struct xfs_inode	**ipp)
1210{
1211	struct xfs_mount	*mp = dp->i_mount;
1212	struct xfs_inode	*ip = NULL;
1213	struct xfs_trans	*tp = NULL;
1214	int			error;
1215	prid_t                  prid;
1216	struct xfs_dquot	*udqp = NULL;
1217	struct xfs_dquot	*gdqp = NULL;
1218	struct xfs_dquot	*pdqp = NULL;
1219	struct xfs_trans_res	*tres;
1220	uint			resblks;
1221	xfs_ino_t		ino;
1222
1223	if (xfs_is_shutdown(mp))
1224		return -EIO;
1225
1226	prid = xfs_get_initial_prid(dp);
1227
1228	/*
1229	 * Make sure that we have allocated dquot(s) on disk.
1230	 */
1231	error = xfs_qm_vop_dqalloc(dp, mapped_fsuid(idmap, &init_user_ns),
1232			mapped_fsgid(idmap, &init_user_ns), prid,
1233			XFS_QMOPT_QUOTALL | XFS_QMOPT_INHERIT,
1234			&udqp, &gdqp, &pdqp);
1235	if (error)
1236		return error;
1237
1238	resblks = XFS_IALLOC_SPACE_RES(mp);
1239	tres = &M_RES(mp)->tr_create_tmpfile;
1240
1241	error = xfs_trans_alloc_icreate(mp, tres, udqp, gdqp, pdqp, resblks,
1242			&tp);
1243	if (error)
1244		goto out_release_dquots;
1245
1246	error = xfs_dialloc(&tp, dp->i_ino, mode, &ino);
1247	if (!error)
1248		error = xfs_init_new_inode(idmap, tp, dp, ino, mode,
1249				0, 0, prid, init_xattrs, &ip);
1250	if (error)
1251		goto out_trans_cancel;
1252
1253	if (xfs_has_wsync(mp))
1254		xfs_trans_set_sync(tp);
1255
1256	/*
1257	 * Attach the dquot(s) to the inodes and modify them incore.
1258	 * These ids of the inode couldn't have changed since the new
1259	 * inode has been locked ever since it was created.
1260	 */
1261	xfs_qm_vop_create_dqattach(tp, ip, udqp, gdqp, pdqp);
1262
1263	error = xfs_iunlink(tp, ip);
1264	if (error)
1265		goto out_trans_cancel;
1266
1267	error = xfs_trans_commit(tp);
1268	if (error)
1269		goto out_release_inode;
1270
1271	xfs_qm_dqrele(udqp);
1272	xfs_qm_dqrele(gdqp);
1273	xfs_qm_dqrele(pdqp);
1274
1275	*ipp = ip;
1276	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1277	return 0;
1278
1279 out_trans_cancel:
1280	xfs_trans_cancel(tp);
1281 out_release_inode:
1282	/*
1283	 * Wait until after the current transaction is aborted to finish the
1284	 * setup of the inode and release the inode.  This prevents recursive
1285	 * transactions and deadlocks from xfs_inactive.
1286	 */
1287	if (ip) {
1288		xfs_iunlock(ip, XFS_ILOCK_EXCL);
1289		xfs_finish_inode_setup(ip);
1290		xfs_irele(ip);
1291	}
1292 out_release_dquots:
1293	xfs_qm_dqrele(udqp);
1294	xfs_qm_dqrele(gdqp);
1295	xfs_qm_dqrele(pdqp);
1296
1297	return error;
1298}
1299
1300int
1301xfs_link(
1302	struct xfs_inode	*tdp,
1303	struct xfs_inode	*sip,
1304	struct xfs_name		*target_name)
1305{
1306	struct xfs_mount	*mp = tdp->i_mount;
1307	struct xfs_trans	*tp;
1308	int			error, nospace_error = 0;
1309	int			resblks;
1310	struct xfs_parent_args	*ppargs;
1311
1312	trace_xfs_link(tdp, target_name);
1313
1314	ASSERT(!S_ISDIR(VFS_I(sip)->i_mode));
1315
1316	if (xfs_is_shutdown(mp))
1317		return -EIO;
1318	if (xfs_ifork_zapped(tdp, XFS_DATA_FORK))
1319		return -EIO;
1320
1321	error = xfs_qm_dqattach(sip);
1322	if (error)
1323		goto std_return;
1324
1325	error = xfs_qm_dqattach(tdp);
1326	if (error)
1327		goto std_return;
1328
1329	error = xfs_parent_start(mp, &ppargs);
1330	if (error)
1331		goto std_return;
1332
1333	resblks = xfs_link_space_res(mp, target_name->len);
1334	error = xfs_trans_alloc_dir(tdp, &M_RES(mp)->tr_link, sip, &resblks,
1335			&tp, &nospace_error);
1336	if (error)
1337		goto out_parent;
1338
1339	/*
1340	 * We don't allow reservationless or quotaless hardlinking when parent
1341	 * pointers are enabled because we can't back out if the xattrs must
1342	 * grow.
1343	 */
1344	if (ppargs && nospace_error) {
1345		error = nospace_error;
1346		goto error_return;
1347	}
1348
1349	/*
1350	 * If we are using project inheritance, we only allow hard link
1351	 * creation in our tree when the project IDs are the same; else
1352	 * the tree quota mechanism could be circumvented.
1353	 */
1354	if (unlikely((tdp->i_diflags & XFS_DIFLAG_PROJINHERIT) &&
1355		     tdp->i_projid != sip->i_projid)) {
1356		/*
1357		 * Project quota setup skips special files which can
1358		 * leave inodes in a PROJINHERIT directory without a
1359		 * project ID set. We need to allow links to be made
1360		 * to these "project-less" inodes because userspace
1361		 * expects them to succeed after project ID setup,
1362		 * but everything else should be rejected.
1363		 */
1364		if (!special_file(VFS_I(sip)->i_mode) ||
1365		    sip->i_projid != 0) {
1366			error = -EXDEV;
1367			goto error_return;
1368		}
1369	}
1370
1371	if (!resblks) {
1372		error = xfs_dir_canenter(tp, tdp, target_name);
1373		if (error)
1374			goto error_return;
1375	}
1376
1377	/*
1378	 * Handle initial link state of O_TMPFILE inode
1379	 */
1380	if (VFS_I(sip)->i_nlink == 0) {
1381		struct xfs_perag	*pag;
1382
1383		pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, sip->i_ino));
1384		error = xfs_iunlink_remove(tp, pag, sip);
1385		xfs_perag_put(pag);
1386		if (error)
1387			goto error_return;
1388	}
1389
1390	error = xfs_dir_createname(tp, tdp, target_name, sip->i_ino,
1391				   resblks);
1392	if (error)
1393		goto error_return;
1394	xfs_trans_ichgtime(tp, tdp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
1395	xfs_trans_log_inode(tp, tdp, XFS_ILOG_CORE);
1396
1397	xfs_bumplink(tp, sip);
1398
1399	/*
1400	 * If we have parent pointers, we now need to add the parent record to
1401	 * the attribute fork of the inode. If this is the initial parent
1402	 * attribute, we need to create it correctly, otherwise we can just add
1403	 * the parent to the inode.
1404	 */
1405	if (ppargs) {
1406		error = xfs_parent_addname(tp, ppargs, tdp, target_name, sip);
1407		if (error)
1408			goto error_return;
1409	}
1410
1411	xfs_dir_update_hook(tdp, sip, 1, target_name);
1412
1413	/*
1414	 * If this is a synchronous mount, make sure that the
1415	 * link transaction goes to disk before returning to
1416	 * the user.
1417	 */
1418	if (xfs_has_wsync(mp) || xfs_has_dirsync(mp))
1419		xfs_trans_set_sync(tp);
1420
1421	error = xfs_trans_commit(tp);
1422	xfs_iunlock(tdp, XFS_ILOCK_EXCL);
1423	xfs_iunlock(sip, XFS_ILOCK_EXCL);
1424	xfs_parent_finish(mp, ppargs);
1425	return error;
1426
1427 error_return:
1428	xfs_trans_cancel(tp);
1429	xfs_iunlock(tdp, XFS_ILOCK_EXCL);
1430	xfs_iunlock(sip, XFS_ILOCK_EXCL);
1431 out_parent:
1432	xfs_parent_finish(mp, ppargs);
1433 std_return:
1434	if (error == -ENOSPC && nospace_error)
1435		error = nospace_error;
1436	return error;
1437}
1438
1439/* Clear the reflink flag and the cowblocks tag if possible. */
1440static void
1441xfs_itruncate_clear_reflink_flags(
1442	struct xfs_inode	*ip)
1443{
1444	struct xfs_ifork	*dfork;
1445	struct xfs_ifork	*cfork;
1446
1447	if (!xfs_is_reflink_inode(ip))
1448		return;
1449	dfork = xfs_ifork_ptr(ip, XFS_DATA_FORK);
1450	cfork = xfs_ifork_ptr(ip, XFS_COW_FORK);
1451	if (dfork->if_bytes == 0 && cfork->if_bytes == 0)
1452		ip->i_diflags2 &= ~XFS_DIFLAG2_REFLINK;
1453	if (cfork->if_bytes == 0)
1454		xfs_inode_clear_cowblocks_tag(ip);
1455}
1456
1457/*
1458 * Free up the underlying blocks past new_size.  The new size must be smaller
1459 * than the current size.  This routine can be used both for the attribute and
1460 * data fork, and does not modify the inode size, which is left to the caller.
1461 *
1462 * The transaction passed to this routine must have made a permanent log
1463 * reservation of at least XFS_ITRUNCATE_LOG_RES.  This routine may commit the
1464 * given transaction and start new ones, so make sure everything involved in
1465 * the transaction is tidy before calling here.  Some transaction will be
1466 * returned to the caller to be committed.  The incoming transaction must
1467 * already include the inode, and both inode locks must be held exclusively.
1468 * The inode must also be "held" within the transaction.  On return the inode
1469 * will be "held" within the returned transaction.  This routine does NOT
1470 * require any disk space to be reserved for it within the transaction.
1471 *
1472 * If we get an error, we must return with the inode locked and linked into the
1473 * current transaction. This keeps things simple for the higher level code,
1474 * because it always knows that the inode is locked and held in the transaction
1475 * that returns to it whether errors occur or not.  We don't mark the inode
1476 * dirty on error so that transactions can be easily aborted if possible.
1477 */
1478int
1479xfs_itruncate_extents_flags(
1480	struct xfs_trans	**tpp,
1481	struct xfs_inode	*ip,
1482	int			whichfork,
1483	xfs_fsize_t		new_size,
1484	int			flags)
1485{
1486	struct xfs_mount	*mp = ip->i_mount;
1487	struct xfs_trans	*tp = *tpp;
1488	xfs_fileoff_t		first_unmap_block;
1489	int			error = 0;
1490
1491	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL);
1492	if (atomic_read(&VFS_I(ip)->i_count))
1493		xfs_assert_ilocked(ip, XFS_IOLOCK_EXCL);
1494	ASSERT(new_size <= XFS_ISIZE(ip));
1495	ASSERT(tp->t_flags & XFS_TRANS_PERM_LOG_RES);
1496	ASSERT(ip->i_itemp != NULL);
1497	ASSERT(ip->i_itemp->ili_lock_flags == 0);
1498	ASSERT(!XFS_NOT_DQATTACHED(mp, ip));
1499
1500	trace_xfs_itruncate_extents_start(ip, new_size);
1501
1502	flags |= xfs_bmapi_aflag(whichfork);
1503
1504	/*
1505	 * Since it is possible for space to become allocated beyond
1506	 * the end of the file (in a crash where the space is allocated
1507	 * but the inode size is not yet updated), simply remove any
1508	 * blocks which show up between the new EOF and the maximum
1509	 * possible file size.
1510	 *
1511	 * We have to free all the blocks to the bmbt maximum offset, even if
1512	 * the page cache can't scale that far.
1513	 */
1514	first_unmap_block = XFS_B_TO_FSB(mp, (xfs_ufsize_t)new_size);
1515	if (!xfs_verify_fileoff(mp, first_unmap_block)) {
1516		WARN_ON_ONCE(first_unmap_block > XFS_MAX_FILEOFF);
1517		return 0;
1518	}
1519
1520	error = xfs_bunmapi_range(&tp, ip, flags, first_unmap_block,
1521			XFS_MAX_FILEOFF);
1522	if (error)
1523		goto out;
1524
1525	if (whichfork == XFS_DATA_FORK) {
1526		/* Remove all pending CoW reservations. */
1527		error = xfs_reflink_cancel_cow_blocks(ip, &tp,
1528				first_unmap_block, XFS_MAX_FILEOFF, true);
1529		if (error)
1530			goto out;
1531
1532		xfs_itruncate_clear_reflink_flags(ip);
1533	}
1534
1535	/*
1536	 * Always re-log the inode so that our permanent transaction can keep
1537	 * on rolling it forward in the log.
1538	 */
1539	xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1540
1541	trace_xfs_itruncate_extents_end(ip, new_size);
1542
1543out:
1544	*tpp = tp;
1545	return error;
1546}
1547
1548int
1549xfs_release(
1550	xfs_inode_t	*ip)
1551{
1552	xfs_mount_t	*mp = ip->i_mount;
1553	int		error = 0;
1554
1555	if (!S_ISREG(VFS_I(ip)->i_mode) || (VFS_I(ip)->i_mode == 0))
1556		return 0;
1557
1558	/* If this is a read-only mount, don't do this (would generate I/O) */
1559	if (xfs_is_readonly(mp))
1560		return 0;
1561
1562	if (!xfs_is_shutdown(mp)) {
1563		int truncated;
1564
1565		/*
1566		 * If we previously truncated this file and removed old data
1567		 * in the process, we want to initiate "early" writeout on
1568		 * the last close.  This is an attempt to combat the notorious
1569		 * NULL files problem which is particularly noticeable from a
1570		 * truncate down, buffered (re-)write (delalloc), followed by
1571		 * a crash.  What we are effectively doing here is
1572		 * significantly reducing the time window where we'd otherwise
1573		 * be exposed to that problem.
1574		 */
1575		truncated = xfs_iflags_test_and_clear(ip, XFS_ITRUNCATED);
1576		if (truncated) {
1577			xfs_iflags_clear(ip, XFS_IDIRTY_RELEASE);
1578			if (ip->i_delayed_blks > 0) {
1579				error = filemap_flush(VFS_I(ip)->i_mapping);
1580				if (error)
1581					return error;
1582			}
1583		}
1584	}
1585
1586	if (VFS_I(ip)->i_nlink == 0)
1587		return 0;
1588
1589	/*
1590	 * If we can't get the iolock just skip truncating the blocks past EOF
1591	 * because we could deadlock with the mmap_lock otherwise. We'll get
1592	 * another chance to drop them once the last reference to the inode is
1593	 * dropped, so we'll never leak blocks permanently.
1594	 */
1595	if (!xfs_ilock_nowait(ip, XFS_IOLOCK_EXCL))
1596		return 0;
1597
1598	if (xfs_can_free_eofblocks(ip, false)) {
1599		/*
1600		 * Check if the inode is being opened, written and closed
1601		 * frequently and we have delayed allocation blocks outstanding
1602		 * (e.g. streaming writes from the NFS server), truncating the
1603		 * blocks past EOF will cause fragmentation to occur.
1604		 *
1605		 * In this case don't do the truncation, but we have to be
1606		 * careful how we detect this case. Blocks beyond EOF show up as
1607		 * i_delayed_blks even when the inode is clean, so we need to
1608		 * truncate them away first before checking for a dirty release.
1609		 * Hence on the first dirty close we will still remove the
1610		 * speculative allocation, but after that we will leave it in
1611		 * place.
1612		 */
1613		if (xfs_iflags_test(ip, XFS_IDIRTY_RELEASE))
1614			goto out_unlock;
1615
1616		error = xfs_free_eofblocks(ip);
1617		if (error)
1618			goto out_unlock;
1619
1620		/* delalloc blocks after truncation means it really is dirty */
1621		if (ip->i_delayed_blks)
1622			xfs_iflags_set(ip, XFS_IDIRTY_RELEASE);
1623	}
1624
1625out_unlock:
1626	xfs_iunlock(ip, XFS_IOLOCK_EXCL);
1627	return error;
1628}
1629
1630/*
1631 * Mark all the buffers attached to this directory stale.  In theory we should
1632 * never be freeing a directory with any blocks at all, but this covers the
1633 * case where we've recovered a directory swap with a "temporary" directory
1634 * created by online repair and now need to dump it.
1635 */
1636STATIC void
1637xfs_inactive_dir(
1638	struct xfs_inode	*dp)
1639{
1640	struct xfs_iext_cursor	icur;
1641	struct xfs_bmbt_irec	got;
1642	struct xfs_mount	*mp = dp->i_mount;
1643	struct xfs_da_geometry	*geo = mp->m_dir_geo;
1644	struct xfs_ifork	*ifp = xfs_ifork_ptr(dp, XFS_DATA_FORK);
1645	xfs_fileoff_t		off;
1646
1647	/*
1648	 * Invalidate each directory block.  All directory blocks are of
1649	 * fsbcount length and alignment, so we only need to walk those same
1650	 * offsets.  We hold the only reference to this inode, so we must wait
1651	 * for the buffer locks.
1652	 */
1653	for_each_xfs_iext(ifp, &icur, &got) {
1654		for (off = round_up(got.br_startoff, geo->fsbcount);
1655		     off < got.br_startoff + got.br_blockcount;
1656		     off += geo->fsbcount) {
1657			struct xfs_buf	*bp = NULL;
1658			xfs_fsblock_t	fsbno;
1659			int		error;
1660
1661			fsbno = (off - got.br_startoff) + got.br_startblock;
1662			error = xfs_buf_incore(mp->m_ddev_targp,
1663					XFS_FSB_TO_DADDR(mp, fsbno),
1664					XFS_FSB_TO_BB(mp, geo->fsbcount),
1665					XBF_LIVESCAN, &bp);
1666			if (error)
1667				continue;
1668
1669			xfs_buf_stale(bp);
1670			xfs_buf_relse(bp);
1671		}
1672	}
1673}
1674
1675/*
1676 * xfs_inactive_truncate
1677 *
1678 * Called to perform a truncate when an inode becomes unlinked.
1679 */
1680STATIC int
1681xfs_inactive_truncate(
1682	struct xfs_inode *ip)
1683{
1684	struct xfs_mount	*mp = ip->i_mount;
1685	struct xfs_trans	*tp;
1686	int			error;
1687
1688	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_itruncate, 0, 0, 0, &tp);
1689	if (error) {
1690		ASSERT(xfs_is_shutdown(mp));
1691		return error;
1692	}
1693	xfs_ilock(ip, XFS_ILOCK_EXCL);
1694	xfs_trans_ijoin(tp, ip, 0);
1695
1696	/*
1697	 * Log the inode size first to prevent stale data exposure in the event
1698	 * of a system crash before the truncate completes. See the related
1699	 * comment in xfs_vn_setattr_size() for details.
1700	 */
1701	ip->i_disk_size = 0;
1702	xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1703
1704	error = xfs_itruncate_extents(&tp, ip, XFS_DATA_FORK, 0);
1705	if (error)
1706		goto error_trans_cancel;
1707
1708	ASSERT(ip->i_df.if_nextents == 0);
1709
1710	error = xfs_trans_commit(tp);
1711	if (error)
1712		goto error_unlock;
1713
1714	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1715	return 0;
1716
1717error_trans_cancel:
1718	xfs_trans_cancel(tp);
1719error_unlock:
1720	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1721	return error;
1722}
1723
1724/*
1725 * xfs_inactive_ifree()
1726 *
1727 * Perform the inode free when an inode is unlinked.
1728 */
1729STATIC int
1730xfs_inactive_ifree(
1731	struct xfs_inode *ip)
1732{
1733	struct xfs_mount	*mp = ip->i_mount;
1734	struct xfs_trans	*tp;
1735	int			error;
1736
1737	/*
1738	 * We try to use a per-AG reservation for any block needed by the finobt
1739	 * tree, but as the finobt feature predates the per-AG reservation
1740	 * support a degraded file system might not have enough space for the
1741	 * reservation at mount time.  In that case try to dip into the reserved
1742	 * pool and pray.
1743	 *
1744	 * Send a warning if the reservation does happen to fail, as the inode
1745	 * now remains allocated and sits on the unlinked list until the fs is
1746	 * repaired.
1747	 */
1748	if (unlikely(mp->m_finobt_nores)) {
1749		error = xfs_trans_alloc(mp, &M_RES(mp)->tr_ifree,
1750				XFS_IFREE_SPACE_RES(mp), 0, XFS_TRANS_RESERVE,
1751				&tp);
1752	} else {
1753		error = xfs_trans_alloc(mp, &M_RES(mp)->tr_ifree, 0, 0, 0, &tp);
1754	}
1755	if (error) {
1756		if (error == -ENOSPC) {
1757			xfs_warn_ratelimited(mp,
1758			"Failed to remove inode(s) from unlinked list. "
1759			"Please free space, unmount and run xfs_repair.");
1760		} else {
1761			ASSERT(xfs_is_shutdown(mp));
1762		}
1763		return error;
1764	}
1765
1766	/*
1767	 * We do not hold the inode locked across the entire rolling transaction
1768	 * here. We only need to hold it for the first transaction that
1769	 * xfs_ifree() builds, which may mark the inode XFS_ISTALE if the
1770	 * underlying cluster buffer is freed. Relogging an XFS_ISTALE inode
1771	 * here breaks the relationship between cluster buffer invalidation and
1772	 * stale inode invalidation on cluster buffer item journal commit
1773	 * completion, and can result in leaving dirty stale inodes hanging
1774	 * around in memory.
1775	 *
1776	 * We have no need for serialising this inode operation against other
1777	 * operations - we freed the inode and hence reallocation is required
1778	 * and that will serialise on reallocating the space the deferops need
1779	 * to free. Hence we can unlock the inode on the first commit of
1780	 * the transaction rather than roll it right through the deferops. This
1781	 * avoids relogging the XFS_ISTALE inode.
1782	 *
1783	 * We check that xfs_ifree() hasn't grown an internal transaction roll
1784	 * by asserting that the inode is still locked when it returns.
1785	 */
1786	xfs_ilock(ip, XFS_ILOCK_EXCL);
1787	xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
1788
1789	error = xfs_ifree(tp, ip);
1790	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL);
1791	if (error) {
1792		/*
1793		 * If we fail to free the inode, shut down.  The cancel
1794		 * might do that, we need to make sure.  Otherwise the
1795		 * inode might be lost for a long time or forever.
1796		 */
1797		if (!xfs_is_shutdown(mp)) {
1798			xfs_notice(mp, "%s: xfs_ifree returned error %d",
1799				__func__, error);
1800			xfs_force_shutdown(mp, SHUTDOWN_META_IO_ERROR);
1801		}
1802		xfs_trans_cancel(tp);
1803		return error;
1804	}
1805
1806	/*
1807	 * Credit the quota account(s). The inode is gone.
1808	 */
1809	xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_ICOUNT, -1);
1810
1811	return xfs_trans_commit(tp);
1812}
1813
1814/*
1815 * Returns true if we need to update the on-disk metadata before we can free
1816 * the memory used by this inode.  Updates include freeing post-eof
1817 * preallocations; freeing COW staging extents; and marking the inode free in
1818 * the inobt if it is on the unlinked list.
1819 */
1820bool
1821xfs_inode_needs_inactive(
1822	struct xfs_inode	*ip)
1823{
1824	struct xfs_mount	*mp = ip->i_mount;
1825	struct xfs_ifork	*cow_ifp = xfs_ifork_ptr(ip, XFS_COW_FORK);
1826
1827	/*
1828	 * If the inode is already free, then there can be nothing
1829	 * to clean up here.
1830	 */
1831	if (VFS_I(ip)->i_mode == 0)
1832		return false;
1833
1834	/*
1835	 * If this is a read-only mount, don't do this (would generate I/O)
1836	 * unless we're in log recovery and cleaning the iunlinked list.
1837	 */
1838	if (xfs_is_readonly(mp) && !xlog_recovery_needed(mp->m_log))
1839		return false;
1840
1841	/* If the log isn't running, push inodes straight to reclaim. */
1842	if (xfs_is_shutdown(mp) || xfs_has_norecovery(mp))
1843		return false;
1844
1845	/* Metadata inodes require explicit resource cleanup. */
1846	if (xfs_is_metadata_inode(ip))
1847		return false;
1848
1849	/* Want to clean out the cow blocks if there are any. */
1850	if (cow_ifp && cow_ifp->if_bytes > 0)
1851		return true;
1852
1853	/* Unlinked files must be freed. */
1854	if (VFS_I(ip)->i_nlink == 0)
1855		return true;
1856
1857	/*
1858	 * This file isn't being freed, so check if there are post-eof blocks
1859	 * to free.  @force is true because we are evicting an inode from the
1860	 * cache.  Post-eof blocks must be freed, lest we end up with broken
1861	 * free space accounting.
1862	 *
1863	 * Note: don't bother with iolock here since lockdep complains about
1864	 * acquiring it in reclaim context. We have the only reference to the
1865	 * inode at this point anyways.
1866	 */
1867	return xfs_can_free_eofblocks(ip, true);
1868}
1869
1870/*
1871 * Save health status somewhere, if we're dumping an inode with uncorrected
1872 * errors and online repair isn't running.
1873 */
1874static inline void
1875xfs_inactive_health(
1876	struct xfs_inode	*ip)
1877{
1878	struct xfs_mount	*mp = ip->i_mount;
1879	struct xfs_perag	*pag;
1880	unsigned int		sick;
1881	unsigned int		checked;
1882
1883	xfs_inode_measure_sickness(ip, &sick, &checked);
1884	if (!sick)
1885		return;
1886
1887	trace_xfs_inode_unfixed_corruption(ip, sick);
1888
1889	if (sick & XFS_SICK_INO_FORGET)
1890		return;
1891
1892	pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, ip->i_ino));
1893	if (!pag) {
1894		/* There had better still be a perag structure! */
1895		ASSERT(0);
1896		return;
1897	}
1898
1899	xfs_ag_mark_sick(pag, XFS_SICK_AG_INODES);
1900	xfs_perag_put(pag);
1901}
1902
1903/*
1904 * xfs_inactive
1905 *
1906 * This is called when the vnode reference count for the vnode
1907 * goes to zero.  If the file has been unlinked, then it must
1908 * now be truncated.  Also, we clear all of the read-ahead state
1909 * kept for the inode here since the file is now closed.
1910 */
1911int
1912xfs_inactive(
1913	xfs_inode_t	*ip)
1914{
1915	struct xfs_mount	*mp;
1916	int			error = 0;
1917	int			truncate = 0;
1918
1919	/*
1920	 * If the inode is already free, then there can be nothing
1921	 * to clean up here.
1922	 */
1923	if (VFS_I(ip)->i_mode == 0) {
1924		ASSERT(ip->i_df.if_broot_bytes == 0);
1925		goto out;
1926	}
1927
1928	mp = ip->i_mount;
1929	ASSERT(!xfs_iflags_test(ip, XFS_IRECOVERY));
1930
1931	xfs_inactive_health(ip);
1932
1933	/*
1934	 * If this is a read-only mount, don't do this (would generate I/O)
1935	 * unless we're in log recovery and cleaning the iunlinked list.
1936	 */
1937	if (xfs_is_readonly(mp) && !xlog_recovery_needed(mp->m_log))
1938		goto out;
1939
1940	/* Metadata inodes require explicit resource cleanup. */
1941	if (xfs_is_metadata_inode(ip))
1942		goto out;
1943
1944	/* Try to clean out the cow blocks if there are any. */
1945	if (xfs_inode_has_cow_data(ip))
1946		xfs_reflink_cancel_cow_range(ip, 0, NULLFILEOFF, true);
1947
1948	if (VFS_I(ip)->i_nlink != 0) {
1949		/*
1950		 * force is true because we are evicting an inode from the
1951		 * cache. Post-eof blocks must be freed, lest we end up with
1952		 * broken free space accounting.
1953		 *
1954		 * Note: don't bother with iolock here since lockdep complains
1955		 * about acquiring it in reclaim context. We have the only
1956		 * reference to the inode at this point anyways.
1957		 */
1958		if (xfs_can_free_eofblocks(ip, true))
1959			error = xfs_free_eofblocks(ip);
1960
1961		goto out;
1962	}
1963
1964	if (S_ISREG(VFS_I(ip)->i_mode) &&
1965	    (ip->i_disk_size != 0 || XFS_ISIZE(ip) != 0 ||
1966	     ip->i_df.if_nextents > 0 || ip->i_delayed_blks > 0))
1967		truncate = 1;
1968
1969	if (xfs_iflags_test(ip, XFS_IQUOTAUNCHECKED)) {
1970		/*
1971		 * If this inode is being inactivated during a quotacheck and
1972		 * has not yet been scanned by quotacheck, we /must/ remove
1973		 * the dquots from the inode before inactivation changes the
1974		 * block and inode counts.  Most probably this is a result of
1975		 * reloading the incore iunlinked list to purge unrecovered
1976		 * unlinked inodes.
1977		 */
1978		xfs_qm_dqdetach(ip);
1979	} else {
1980		error = xfs_qm_dqattach(ip);
1981		if (error)
1982			goto out;
1983	}
1984
1985	if (S_ISDIR(VFS_I(ip)->i_mode) && ip->i_df.if_nextents > 0) {
1986		xfs_inactive_dir(ip);
1987		truncate = 1;
1988	}
1989
1990	if (S_ISLNK(VFS_I(ip)->i_mode))
1991		error = xfs_inactive_symlink(ip);
1992	else if (truncate)
1993		error = xfs_inactive_truncate(ip);
1994	if (error)
1995		goto out;
1996
1997	/*
1998	 * If there are attributes associated with the file then blow them away
1999	 * now.  The code calls a routine that recursively deconstructs the
2000	 * attribute fork. If also blows away the in-core attribute fork.
2001	 */
2002	if (xfs_inode_has_attr_fork(ip)) {
2003		error = xfs_attr_inactive(ip);
2004		if (error)
2005			goto out;
2006	}
2007
2008	ASSERT(ip->i_forkoff == 0);
2009
2010	/*
2011	 * Free the inode.
2012	 */
2013	error = xfs_inactive_ifree(ip);
2014
2015out:
2016	/*
2017	 * We're done making metadata updates for this inode, so we can release
2018	 * the attached dquots.
2019	 */
2020	xfs_qm_dqdetach(ip);
2021	return error;
2022}
2023
2024/*
2025 * In-Core Unlinked List Lookups
2026 * =============================
2027 *
2028 * Every inode is supposed to be reachable from some other piece of metadata
2029 * with the exception of the root directory.  Inodes with a connection to a
2030 * file descriptor but not linked from anywhere in the on-disk directory tree
2031 * are collectively known as unlinked inodes, though the filesystem itself
2032 * maintains links to these inodes so that on-disk metadata are consistent.
2033 *
2034 * XFS implements a per-AG on-disk hash table of unlinked inodes.  The AGI
2035 * header contains a number of buckets that point to an inode, and each inode
2036 * record has a pointer to the next inode in the hash chain.  This
2037 * singly-linked list causes scaling problems in the iunlink remove function
2038 * because we must walk that list to find the inode that points to the inode
2039 * being removed from the unlinked hash bucket list.
2040 *
2041 * Hence we keep an in-memory double linked list to link each inode on an
2042 * unlinked list. Because there are 64 unlinked lists per AGI, keeping pointer
2043 * based lists would require having 64 list heads in the perag, one for each
2044 * list. This is expensive in terms of memory (think millions of AGs) and cache
2045 * misses on lookups. Instead, use the fact that inodes on the unlinked list
2046 * must be referenced at the VFS level to keep them on the list and hence we
2047 * have an existence guarantee for inodes on the unlinked list.
2048 *
2049 * Given we have an existence guarantee, we can use lockless inode cache lookups
2050 * to resolve aginos to xfs inodes. This means we only need 8 bytes per inode
2051 * for the double linked unlinked list, and we don't need any extra locking to
2052 * keep the list safe as all manipulations are done under the AGI buffer lock.
2053 * Keeping the list up to date does not require memory allocation, just finding
2054 * the XFS inode and updating the next/prev unlinked list aginos.
2055 */
2056
2057/*
2058 * Find an inode on the unlinked list. This does not take references to the
2059 * inode as we have existence guarantees by holding the AGI buffer lock and that
2060 * only unlinked, referenced inodes can be on the unlinked inode list.  If we
2061 * don't find the inode in cache, then let the caller handle the situation.
2062 */
2063struct xfs_inode *
2064xfs_iunlink_lookup(
2065	struct xfs_perag	*pag,
2066	xfs_agino_t		agino)
2067{
2068	struct xfs_inode	*ip;
2069
2070	rcu_read_lock();
2071	ip = radix_tree_lookup(&pag->pag_ici_root, agino);
2072	if (!ip) {
2073		/* Caller can handle inode not being in memory. */
2074		rcu_read_unlock();
2075		return NULL;
2076	}
2077
2078	/*
2079	 * Inode in RCU freeing limbo should not happen.  Warn about this and
2080	 * let the caller handle the failure.
2081	 */
2082	if (WARN_ON_ONCE(!ip->i_ino)) {
2083		rcu_read_unlock();
2084		return NULL;
2085	}
2086	ASSERT(!xfs_iflags_test(ip, XFS_IRECLAIMABLE | XFS_IRECLAIM));
2087	rcu_read_unlock();
2088	return ip;
2089}
2090
2091/*
2092 * Update the prev pointer of the next agino.  Returns -ENOLINK if the inode
2093 * is not in cache.
2094 */
2095static int
2096xfs_iunlink_update_backref(
2097	struct xfs_perag	*pag,
2098	xfs_agino_t		prev_agino,
2099	xfs_agino_t		next_agino)
2100{
2101	struct xfs_inode	*ip;
2102
2103	/* No update necessary if we are at the end of the list. */
2104	if (next_agino == NULLAGINO)
2105		return 0;
2106
2107	ip = xfs_iunlink_lookup(pag, next_agino);
2108	if (!ip)
2109		return -ENOLINK;
2110
2111	ip->i_prev_unlinked = prev_agino;
2112	return 0;
2113}
2114
2115/*
2116 * Point the AGI unlinked bucket at an inode and log the results.  The caller
2117 * is responsible for validating the old value.
2118 */
2119STATIC int
2120xfs_iunlink_update_bucket(
2121	struct xfs_trans	*tp,
2122	struct xfs_perag	*pag,
2123	struct xfs_buf		*agibp,
2124	unsigned int		bucket_index,
2125	xfs_agino_t		new_agino)
2126{
2127	struct xfs_agi		*agi = agibp->b_addr;
2128	xfs_agino_t		old_value;
2129	int			offset;
2130
2131	ASSERT(xfs_verify_agino_or_null(pag, new_agino));
2132
2133	old_value = be32_to_cpu(agi->agi_unlinked[bucket_index]);
2134	trace_xfs_iunlink_update_bucket(tp->t_mountp, pag->pag_agno, bucket_index,
2135			old_value, new_agino);
2136
2137	/*
2138	 * We should never find the head of the list already set to the value
2139	 * passed in because either we're adding or removing ourselves from the
2140	 * head of the list.
2141	 */
2142	if (old_value == new_agino) {
2143		xfs_buf_mark_corrupt(agibp);
2144		xfs_ag_mark_sick(pag, XFS_SICK_AG_AGI);
2145		return -EFSCORRUPTED;
2146	}
2147
2148	agi->agi_unlinked[bucket_index] = cpu_to_be32(new_agino);
2149	offset = offsetof(struct xfs_agi, agi_unlinked) +
2150			(sizeof(xfs_agino_t) * bucket_index);
2151	xfs_trans_log_buf(tp, agibp, offset, offset + sizeof(xfs_agino_t) - 1);
2152	return 0;
2153}
2154
2155/*
2156 * Load the inode @next_agino into the cache and set its prev_unlinked pointer
2157 * to @prev_agino.  Caller must hold the AGI to synchronize with other changes
2158 * to the unlinked list.
2159 */
2160STATIC int
2161xfs_iunlink_reload_next(
2162	struct xfs_trans	*tp,
2163	struct xfs_buf		*agibp,
2164	xfs_agino_t		prev_agino,
2165	xfs_agino_t		next_agino)
2166{
2167	struct xfs_perag	*pag = agibp->b_pag;
2168	struct xfs_mount	*mp = pag->pag_mount;
2169	struct xfs_inode	*next_ip = NULL;
2170	xfs_ino_t		ino;
2171	int			error;
2172
2173	ASSERT(next_agino != NULLAGINO);
2174
2175#ifdef DEBUG
2176	rcu_read_lock();
2177	next_ip = radix_tree_lookup(&pag->pag_ici_root, next_agino);
2178	ASSERT(next_ip == NULL);
2179	rcu_read_unlock();
2180#endif
2181
2182	xfs_info_ratelimited(mp,
2183 "Found unrecovered unlinked inode 0x%x in AG 0x%x.  Initiating recovery.",
2184			next_agino, pag->pag_agno);
2185
2186	/*
2187	 * Use an untrusted lookup just to be cautious in case the AGI has been
2188	 * corrupted and now points at a free inode.  That shouldn't happen,
2189	 * but we'd rather shut down now since we're already running in a weird
2190	 * situation.
2191	 */
2192	ino = XFS_AGINO_TO_INO(mp, pag->pag_agno, next_agino);
2193	error = xfs_iget(mp, tp, ino, XFS_IGET_UNTRUSTED, 0, &next_ip);
2194	if (error) {
2195		xfs_ag_mark_sick(pag, XFS_SICK_AG_AGI);
2196		return error;
2197	}
2198
2199	/* If this is not an unlinked inode, something is very wrong. */
2200	if (VFS_I(next_ip)->i_nlink != 0) {
2201		xfs_ag_mark_sick(pag, XFS_SICK_AG_AGI);
2202		error = -EFSCORRUPTED;
2203		goto rele;
2204	}
2205
2206	next_ip->i_prev_unlinked = prev_agino;
2207	trace_xfs_iunlink_reload_next(next_ip);
2208rele:
2209	ASSERT(!(VFS_I(next_ip)->i_state & I_DONTCACHE));
2210	if (xfs_is_quotacheck_running(mp) && next_ip)
2211		xfs_iflags_set(next_ip, XFS_IQUOTAUNCHECKED);
2212	xfs_irele(next_ip);
2213	return error;
2214}
2215
2216static int
2217xfs_iunlink_insert_inode(
2218	struct xfs_trans	*tp,
2219	struct xfs_perag	*pag,
2220	struct xfs_buf		*agibp,
2221	struct xfs_inode	*ip)
2222{
2223	struct xfs_mount	*mp = tp->t_mountp;
2224	struct xfs_agi		*agi = agibp->b_addr;
2225	xfs_agino_t		next_agino;
2226	xfs_agino_t		agino = XFS_INO_TO_AGINO(mp, ip->i_ino);
2227	short			bucket_index = agino % XFS_AGI_UNLINKED_BUCKETS;
2228	int			error;
2229
2230	/*
2231	 * Get the index into the agi hash table for the list this inode will
2232	 * go on.  Make sure the pointer isn't garbage and that this inode
2233	 * isn't already on the list.
2234	 */
2235	next_agino = be32_to_cpu(agi->agi_unlinked[bucket_index]);
2236	if (next_agino == agino ||
2237	    !xfs_verify_agino_or_null(pag, next_agino)) {
2238		xfs_buf_mark_corrupt(agibp);
2239		xfs_ag_mark_sick(pag, XFS_SICK_AG_AGI);
2240		return -EFSCORRUPTED;
2241	}
2242
2243	/*
2244	 * Update the prev pointer in the next inode to point back to this
2245	 * inode.
2246	 */
2247	error = xfs_iunlink_update_backref(pag, agino, next_agino);
2248	if (error == -ENOLINK)
2249		error = xfs_iunlink_reload_next(tp, agibp, agino, next_agino);
2250	if (error)
2251		return error;
2252
2253	if (next_agino != NULLAGINO) {
2254		/*
2255		 * There is already another inode in the bucket, so point this
2256		 * inode to the current head of the list.
2257		 */
2258		error = xfs_iunlink_log_inode(tp, ip, pag, next_agino);
2259		if (error)
2260			return error;
2261		ip->i_next_unlinked = next_agino;
2262	}
2263
2264	/* Point the head of the list to point to this inode. */
2265	ip->i_prev_unlinked = NULLAGINO;
2266	return xfs_iunlink_update_bucket(tp, pag, agibp, bucket_index, agino);
2267}
2268
2269/*
2270 * This is called when the inode's link count has gone to 0 or we are creating
2271 * a tmpfile via O_TMPFILE.  The inode @ip must have nlink == 0.
2272 *
2273 * We place the on-disk inode on a list in the AGI.  It will be pulled from this
2274 * list when the inode is freed.
2275 */
2276int
2277xfs_iunlink(
2278	struct xfs_trans	*tp,
2279	struct xfs_inode	*ip)
2280{
2281	struct xfs_mount	*mp = tp->t_mountp;
2282	struct xfs_perag	*pag;
2283	struct xfs_buf		*agibp;
2284	int			error;
2285
2286	ASSERT(VFS_I(ip)->i_nlink == 0);
2287	ASSERT(VFS_I(ip)->i_mode != 0);
2288	trace_xfs_iunlink(ip);
2289
2290	pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, ip->i_ino));
2291
2292	/* Get the agi buffer first.  It ensures lock ordering on the list. */
2293	error = xfs_read_agi(pag, tp, 0, &agibp);
2294	if (error)
2295		goto out;
2296
2297	error = xfs_iunlink_insert_inode(tp, pag, agibp, ip);
2298out:
2299	xfs_perag_put(pag);
2300	return error;
2301}
2302
2303static int
2304xfs_iunlink_remove_inode(
2305	struct xfs_trans	*tp,
2306	struct xfs_perag	*pag,
2307	struct xfs_buf		*agibp,
2308	struct xfs_inode	*ip)
2309{
2310	struct xfs_mount	*mp = tp->t_mountp;
2311	struct xfs_agi		*agi = agibp->b_addr;
2312	xfs_agino_t		agino = XFS_INO_TO_AGINO(mp, ip->i_ino);
2313	xfs_agino_t		head_agino;
2314	short			bucket_index = agino % XFS_AGI_UNLINKED_BUCKETS;
2315	int			error;
2316
2317	trace_xfs_iunlink_remove(ip);
2318
2319	/*
2320	 * Get the index into the agi hash table for the list this inode will
2321	 * go on.  Make sure the head pointer isn't garbage.
2322	 */
2323	head_agino = be32_to_cpu(agi->agi_unlinked[bucket_index]);
2324	if (!xfs_verify_agino(pag, head_agino)) {
2325		XFS_CORRUPTION_ERROR(__func__, XFS_ERRLEVEL_LOW, mp,
2326				agi, sizeof(*agi));
2327		xfs_ag_mark_sick(pag, XFS_SICK_AG_AGI);
2328		return -EFSCORRUPTED;
2329	}
2330
2331	/*
2332	 * Set our inode's next_unlinked pointer to NULL and then return
2333	 * the old pointer value so that we can update whatever was previous
2334	 * to us in the list to point to whatever was next in the list.
2335	 */
2336	error = xfs_iunlink_log_inode(tp, ip, pag, NULLAGINO);
2337	if (error)
2338		return error;
2339
2340	/*
2341	 * Update the prev pointer in the next inode to point back to previous
2342	 * inode in the chain.
2343	 */
2344	error = xfs_iunlink_update_backref(pag, ip->i_prev_unlinked,
2345			ip->i_next_unlinked);
2346	if (error == -ENOLINK)
2347		error = xfs_iunlink_reload_next(tp, agibp, ip->i_prev_unlinked,
2348				ip->i_next_unlinked);
2349	if (error)
2350		return error;
2351
2352	if (head_agino != agino) {
2353		struct xfs_inode	*prev_ip;
2354
2355		prev_ip = xfs_iunlink_lookup(pag, ip->i_prev_unlinked);
2356		if (!prev_ip) {
2357			xfs_inode_mark_sick(ip, XFS_SICK_INO_CORE);
2358			return -EFSCORRUPTED;
2359		}
2360
2361		error = xfs_iunlink_log_inode(tp, prev_ip, pag,
2362				ip->i_next_unlinked);
2363		prev_ip->i_next_unlinked = ip->i_next_unlinked;
2364	} else {
2365		/* Point the head of the list to the next unlinked inode. */
2366		error = xfs_iunlink_update_bucket(tp, pag, agibp, bucket_index,
2367				ip->i_next_unlinked);
2368	}
2369
2370	ip->i_next_unlinked = NULLAGINO;
2371	ip->i_prev_unlinked = 0;
2372	return error;
2373}
2374
2375/*
2376 * Pull the on-disk inode from the AGI unlinked list.
2377 */
2378int
2379xfs_iunlink_remove(
2380	struct xfs_trans	*tp,
2381	struct xfs_perag	*pag,
2382	struct xfs_inode	*ip)
2383{
2384	struct xfs_buf		*agibp;
2385	int			error;
2386
2387	trace_xfs_iunlink_remove(ip);
2388
2389	/* Get the agi buffer first.  It ensures lock ordering on the list. */
2390	error = xfs_read_agi(pag, tp, 0, &agibp);
2391	if (error)
2392		return error;
2393
2394	return xfs_iunlink_remove_inode(tp, pag, agibp, ip);
2395}
2396
2397/*
2398 * Look up the inode number specified and if it is not already marked XFS_ISTALE
2399 * mark it stale. We should only find clean inodes in this lookup that aren't
2400 * already stale.
2401 */
2402static void
2403xfs_ifree_mark_inode_stale(
2404	struct xfs_perag	*pag,
2405	struct xfs_inode	*free_ip,
2406	xfs_ino_t		inum)
2407{
2408	struct xfs_mount	*mp = pag->pag_mount;
2409	struct xfs_inode_log_item *iip;
2410	struct xfs_inode	*ip;
2411
2412retry:
2413	rcu_read_lock();
2414	ip = radix_tree_lookup(&pag->pag_ici_root, XFS_INO_TO_AGINO(mp, inum));
2415
2416	/* Inode not in memory, nothing to do */
2417	if (!ip) {
2418		rcu_read_unlock();
2419		return;
2420	}
2421
2422	/*
2423	 * because this is an RCU protected lookup, we could find a recently
2424	 * freed or even reallocated inode during the lookup. We need to check
2425	 * under the i_flags_lock for a valid inode here. Skip it if it is not
2426	 * valid, the wrong inode or stale.
2427	 */
2428	spin_lock(&ip->i_flags_lock);
2429	if (ip->i_ino != inum || __xfs_iflags_test(ip, XFS_ISTALE))
2430		goto out_iflags_unlock;
2431
2432	/*
2433	 * Don't try to lock/unlock the current inode, but we _cannot_ skip the
2434	 * other inodes that we did not find in the list attached to the buffer
2435	 * and are not already marked stale. If we can't lock it, back off and
2436	 * retry.
2437	 */
2438	if (ip != free_ip) {
2439		if (!xfs_ilock_nowait(ip, XFS_ILOCK_EXCL)) {
2440			spin_unlock(&ip->i_flags_lock);
2441			rcu_read_unlock();
2442			delay(1);
2443			goto retry;
2444		}
2445	}
2446	ip->i_flags |= XFS_ISTALE;
2447
2448	/*
2449	 * If the inode is flushing, it is already attached to the buffer.  All
2450	 * we needed to do here is mark the inode stale so buffer IO completion
2451	 * will remove it from the AIL.
2452	 */
2453	iip = ip->i_itemp;
2454	if (__xfs_iflags_test(ip, XFS_IFLUSHING)) {
2455		ASSERT(!list_empty(&iip->ili_item.li_bio_list));
2456		ASSERT(iip->ili_last_fields);
2457		goto out_iunlock;
2458	}
2459
2460	/*
2461	 * Inodes not attached to the buffer can be released immediately.
2462	 * Everything else has to go through xfs_iflush_abort() on journal
2463	 * commit as the flock synchronises removal of the inode from the
2464	 * cluster buffer against inode reclaim.
2465	 */
2466	if (!iip || list_empty(&iip->ili_item.li_bio_list))
2467		goto out_iunlock;
2468
2469	__xfs_iflags_set(ip, XFS_IFLUSHING);
2470	spin_unlock(&ip->i_flags_lock);
2471	rcu_read_unlock();
2472
2473	/* we have a dirty inode in memory that has not yet been flushed. */
2474	spin_lock(&iip->ili_lock);
2475	iip->ili_last_fields = iip->ili_fields;
2476	iip->ili_fields = 0;
2477	iip->ili_fsync_fields = 0;
2478	spin_unlock(&iip->ili_lock);
2479	ASSERT(iip->ili_last_fields);
2480
2481	if (ip != free_ip)
2482		xfs_iunlock(ip, XFS_ILOCK_EXCL);
2483	return;
2484
2485out_iunlock:
2486	if (ip != free_ip)
2487		xfs_iunlock(ip, XFS_ILOCK_EXCL);
2488out_iflags_unlock:
2489	spin_unlock(&ip->i_flags_lock);
2490	rcu_read_unlock();
2491}
2492
2493/*
2494 * A big issue when freeing the inode cluster is that we _cannot_ skip any
2495 * inodes that are in memory - they all must be marked stale and attached to
2496 * the cluster buffer.
2497 */
2498static int
2499xfs_ifree_cluster(
2500	struct xfs_trans	*tp,
2501	struct xfs_perag	*pag,
2502	struct xfs_inode	*free_ip,
2503	struct xfs_icluster	*xic)
2504{
2505	struct xfs_mount	*mp = free_ip->i_mount;
2506	struct xfs_ino_geometry	*igeo = M_IGEO(mp);
2507	struct xfs_buf		*bp;
2508	xfs_daddr_t		blkno;
2509	xfs_ino_t		inum = xic->first_ino;
2510	int			nbufs;
2511	int			i, j;
2512	int			ioffset;
2513	int			error;
2514
2515	nbufs = igeo->ialloc_blks / igeo->blocks_per_cluster;
2516
2517	for (j = 0; j < nbufs; j++, inum += igeo->inodes_per_cluster) {
2518		/*
2519		 * The allocation bitmap tells us which inodes of the chunk were
2520		 * physically allocated. Skip the cluster if an inode falls into
2521		 * a sparse region.
2522		 */
2523		ioffset = inum - xic->first_ino;
2524		if ((xic->alloc & XFS_INOBT_MASK(ioffset)) == 0) {
2525			ASSERT(ioffset % igeo->inodes_per_cluster == 0);
2526			continue;
2527		}
2528
2529		blkno = XFS_AGB_TO_DADDR(mp, XFS_INO_TO_AGNO(mp, inum),
2530					 XFS_INO_TO_AGBNO(mp, inum));
2531
2532		/*
2533		 * We obtain and lock the backing buffer first in the process
2534		 * here to ensure dirty inodes attached to the buffer remain in
2535		 * the flushing state while we mark them stale.
2536		 *
2537		 * If we scan the in-memory inodes first, then buffer IO can
2538		 * complete before we get a lock on it, and hence we may fail
2539		 * to mark all the active inodes on the buffer stale.
2540		 */
2541		error = xfs_trans_get_buf(tp, mp->m_ddev_targp, blkno,
2542				mp->m_bsize * igeo->blocks_per_cluster,
2543				XBF_UNMAPPED, &bp);
2544		if (error)
2545			return error;
2546
2547		/*
2548		 * This buffer may not have been correctly initialised as we
2549		 * didn't read it from disk. That's not important because we are
2550		 * only using to mark the buffer as stale in the log, and to
2551		 * attach stale cached inodes on it. That means it will never be
2552		 * dispatched for IO. If it is, we want to know about it, and we
2553		 * want it to fail. We can acheive this by adding a write
2554		 * verifier to the buffer.
2555		 */
2556		bp->b_ops = &xfs_inode_buf_ops;
2557
2558		/*
2559		 * Now we need to set all the cached clean inodes as XFS_ISTALE,
2560		 * too. This requires lookups, and will skip inodes that we've
2561		 * already marked XFS_ISTALE.
2562		 */
2563		for (i = 0; i < igeo->inodes_per_cluster; i++)
2564			xfs_ifree_mark_inode_stale(pag, free_ip, inum + i);
2565
2566		xfs_trans_stale_inode_buf(tp, bp);
2567		xfs_trans_binval(tp, bp);
2568	}
2569	return 0;
2570}
2571
2572/*
2573 * This is called to return an inode to the inode free list.  The inode should
2574 * already be truncated to 0 length and have no pages associated with it.  This
2575 * routine also assumes that the inode is already a part of the transaction.
2576 *
2577 * The on-disk copy of the inode will have been added to the list of unlinked
2578 * inodes in the AGI. We need to remove the inode from that list atomically with
2579 * respect to freeing it here.
2580 */
2581int
2582xfs_ifree(
2583	struct xfs_trans	*tp,
2584	struct xfs_inode	*ip)
2585{
2586	struct xfs_mount	*mp = ip->i_mount;
2587	struct xfs_perag	*pag;
2588	struct xfs_icluster	xic = { 0 };
2589	struct xfs_inode_log_item *iip = ip->i_itemp;
2590	int			error;
2591
2592	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL);
2593	ASSERT(VFS_I(ip)->i_nlink == 0);
2594	ASSERT(ip->i_df.if_nextents == 0);
2595	ASSERT(ip->i_disk_size == 0 || !S_ISREG(VFS_I(ip)->i_mode));
2596	ASSERT(ip->i_nblocks == 0);
2597
2598	pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, ip->i_ino));
2599
2600	/*
2601	 * Free the inode first so that we guarantee that the AGI lock is going
2602	 * to be taken before we remove the inode from the unlinked list. This
2603	 * makes the AGI lock -> unlinked list modification order the same as
2604	 * used in O_TMPFILE creation.
2605	 */
2606	error = xfs_difree(tp, pag, ip->i_ino, &xic);
2607	if (error)
2608		goto out;
2609
2610	error = xfs_iunlink_remove(tp, pag, ip);
2611	if (error)
2612		goto out;
2613
2614	/*
2615	 * Free any local-format data sitting around before we reset the
2616	 * data fork to extents format.  Note that the attr fork data has
2617	 * already been freed by xfs_attr_inactive.
2618	 */
2619	if (ip->i_df.if_format == XFS_DINODE_FMT_LOCAL) {
2620		kfree(ip->i_df.if_data);
2621		ip->i_df.if_data = NULL;
2622		ip->i_df.if_bytes = 0;
2623	}
2624
2625	VFS_I(ip)->i_mode = 0;		/* mark incore inode as free */
2626	ip->i_diflags = 0;
2627	ip->i_diflags2 = mp->m_ino_geo.new_diflags2;
2628	ip->i_forkoff = 0;		/* mark the attr fork not in use */
2629	ip->i_df.if_format = XFS_DINODE_FMT_EXTENTS;
2630	if (xfs_iflags_test(ip, XFS_IPRESERVE_DM_FIELDS))
2631		xfs_iflags_clear(ip, XFS_IPRESERVE_DM_FIELDS);
2632
2633	/* Don't attempt to replay owner changes for a deleted inode */
2634	spin_lock(&iip->ili_lock);
2635	iip->ili_fields &= ~(XFS_ILOG_AOWNER | XFS_ILOG_DOWNER);
2636	spin_unlock(&iip->ili_lock);
2637
2638	/*
2639	 * Bump the generation count so no one will be confused
2640	 * by reincarnations of this inode.
2641	 */
2642	VFS_I(ip)->i_generation++;
2643	xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
2644
2645	if (xic.deleted)
2646		error = xfs_ifree_cluster(tp, pag, ip, &xic);
2647out:
2648	xfs_perag_put(pag);
2649	return error;
2650}
2651
2652/*
2653 * This is called to unpin an inode.  The caller must have the inode locked
2654 * in at least shared mode so that the buffer cannot be subsequently pinned
2655 * once someone is waiting for it to be unpinned.
2656 */
2657static void
2658xfs_iunpin(
2659	struct xfs_inode	*ip)
2660{
2661	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL | XFS_ILOCK_SHARED);
2662
2663	trace_xfs_inode_unpin_nowait(ip, _RET_IP_);
2664
2665	/* Give the log a push to start the unpinning I/O */
2666	xfs_log_force_seq(ip->i_mount, ip->i_itemp->ili_commit_seq, 0, NULL);
2667
2668}
2669
2670static void
2671__xfs_iunpin_wait(
2672	struct xfs_inode	*ip)
2673{
2674	wait_queue_head_t *wq = bit_waitqueue(&ip->i_flags, __XFS_IPINNED_BIT);
2675	DEFINE_WAIT_BIT(wait, &ip->i_flags, __XFS_IPINNED_BIT);
2676
2677	xfs_iunpin(ip);
2678
2679	do {
2680		prepare_to_wait(wq, &wait.wq_entry, TASK_UNINTERRUPTIBLE);
2681		if (xfs_ipincount(ip))
2682			io_schedule();
2683	} while (xfs_ipincount(ip));
2684	finish_wait(wq, &wait.wq_entry);
2685}
2686
2687void
2688xfs_iunpin_wait(
2689	struct xfs_inode	*ip)
2690{
2691	if (xfs_ipincount(ip))
2692		__xfs_iunpin_wait(ip);
2693}
2694
2695/*
2696 * Removing an inode from the namespace involves removing the directory entry
2697 * and dropping the link count on the inode. Removing the directory entry can
2698 * result in locking an AGF (directory blocks were freed) and removing a link
2699 * count can result in placing the inode on an unlinked list which results in
2700 * locking an AGI.
2701 *
2702 * The big problem here is that we have an ordering constraint on AGF and AGI
2703 * locking - inode allocation locks the AGI, then can allocate a new extent for
2704 * new inodes, locking the AGF after the AGI. Similarly, freeing the inode
2705 * removes the inode from the unlinked list, requiring that we lock the AGI
2706 * first, and then freeing the inode can result in an inode chunk being freed
2707 * and hence freeing disk space requiring that we lock an AGF.
2708 *
2709 * Hence the ordering that is imposed by other parts of the code is AGI before
2710 * AGF. This means we cannot remove the directory entry before we drop the inode
2711 * reference count and put it on the unlinked list as this results in a lock
2712 * order of AGF then AGI, and this can deadlock against inode allocation and
2713 * freeing. Therefore we must drop the link counts before we remove the
2714 * directory entry.
2715 *
2716 * This is still safe from a transactional point of view - it is not until we
2717 * get to xfs_defer_finish() that we have the possibility of multiple
2718 * transactions in this operation. Hence as long as we remove the directory
2719 * entry and drop the link count in the first transaction of the remove
2720 * operation, there are no transactional constraints on the ordering here.
2721 */
2722int
2723xfs_remove(
2724	struct xfs_inode	*dp,
2725	struct xfs_name		*name,
2726	struct xfs_inode	*ip)
2727{
2728	struct xfs_mount	*mp = dp->i_mount;
2729	struct xfs_trans	*tp = NULL;
2730	int			is_dir = S_ISDIR(VFS_I(ip)->i_mode);
2731	int			dontcare;
2732	int                     error = 0;
2733	uint			resblks;
2734	struct xfs_parent_args	*ppargs;
2735
2736	trace_xfs_remove(dp, name);
2737
2738	if (xfs_is_shutdown(mp))
2739		return -EIO;
2740	if (xfs_ifork_zapped(dp, XFS_DATA_FORK))
2741		return -EIO;
2742
2743	error = xfs_qm_dqattach(dp);
2744	if (error)
2745		goto std_return;
2746
2747	error = xfs_qm_dqattach(ip);
2748	if (error)
2749		goto std_return;
2750
2751	error = xfs_parent_start(mp, &ppargs);
2752	if (error)
2753		goto std_return;
2754
2755	/*
2756	 * We try to get the real space reservation first, allowing for
2757	 * directory btree deletion(s) implying possible bmap insert(s).  If we
2758	 * can't get the space reservation then we use 0 instead, and avoid the
2759	 * bmap btree insert(s) in the directory code by, if the bmap insert
2760	 * tries to happen, instead trimming the LAST block from the directory.
2761	 *
2762	 * Ignore EDQUOT and ENOSPC being returned via nospace_error because
2763	 * the directory code can handle a reservationless update and we don't
2764	 * want to prevent a user from trying to free space by deleting things.
2765	 */
2766	resblks = xfs_remove_space_res(mp, name->len);
2767	error = xfs_trans_alloc_dir(dp, &M_RES(mp)->tr_remove, ip, &resblks,
2768			&tp, &dontcare);
2769	if (error) {
2770		ASSERT(error != -ENOSPC);
2771		goto out_parent;
2772	}
2773
2774	/*
2775	 * If we're removing a directory perform some additional validation.
2776	 */
2777	if (is_dir) {
2778		ASSERT(VFS_I(ip)->i_nlink >= 2);
2779		if (VFS_I(ip)->i_nlink != 2) {
2780			error = -ENOTEMPTY;
2781			goto out_trans_cancel;
2782		}
2783		if (!xfs_dir_isempty(ip)) {
2784			error = -ENOTEMPTY;
2785			goto out_trans_cancel;
2786		}
2787
2788		/* Drop the link from ip's "..".  */
2789		error = xfs_droplink(tp, dp);
2790		if (error)
2791			goto out_trans_cancel;
2792
2793		/* Drop the "." link from ip to self.  */
2794		error = xfs_droplink(tp, ip);
2795		if (error)
2796			goto out_trans_cancel;
2797
2798		/*
2799		 * Point the unlinked child directory's ".." entry to the root
2800		 * directory to eliminate back-references to inodes that may
2801		 * get freed before the child directory is closed.  If the fs
2802		 * gets shrunk, this can lead to dirent inode validation errors.
2803		 */
2804		if (dp->i_ino != tp->t_mountp->m_sb.sb_rootino) {
2805			error = xfs_dir_replace(tp, ip, &xfs_name_dotdot,
2806					tp->t_mountp->m_sb.sb_rootino, 0);
2807			if (error)
2808				goto out_trans_cancel;
2809		}
2810	} else {
2811		/*
2812		 * When removing a non-directory we need to log the parent
2813		 * inode here.  For a directory this is done implicitly
2814		 * by the xfs_droplink call for the ".." entry.
2815		 */
2816		xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
2817	}
2818	xfs_trans_ichgtime(tp, dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
2819
2820	/* Drop the link from dp to ip. */
2821	error = xfs_droplink(tp, ip);
2822	if (error)
2823		goto out_trans_cancel;
2824
2825	error = xfs_dir_removename(tp, dp, name, ip->i_ino, resblks);
2826	if (error) {
2827		ASSERT(error != -ENOENT);
2828		goto out_trans_cancel;
2829	}
2830
2831	/* Remove parent pointer. */
2832	if (ppargs) {
2833		error = xfs_parent_removename(tp, ppargs, dp, name, ip);
2834		if (error)
2835			goto out_trans_cancel;
2836	}
2837
2838	/*
2839	 * Drop the link from dp to ip, and if ip was a directory, remove the
2840	 * '.' and '..' references since we freed the directory.
2841	 */
2842	xfs_dir_update_hook(dp, ip, -1, name);
2843
2844	/*
2845	 * If this is a synchronous mount, make sure that the
2846	 * remove transaction goes to disk before returning to
2847	 * the user.
2848	 */
2849	if (xfs_has_wsync(mp) || xfs_has_dirsync(mp))
2850		xfs_trans_set_sync(tp);
2851
2852	error = xfs_trans_commit(tp);
2853	if (error)
2854		goto out_unlock;
2855
2856	if (is_dir && xfs_inode_is_filestream(ip))
2857		xfs_filestream_deassociate(ip);
2858
2859	xfs_iunlock(ip, XFS_ILOCK_EXCL);
2860	xfs_iunlock(dp, XFS_ILOCK_EXCL);
2861	xfs_parent_finish(mp, ppargs);
2862	return 0;
2863
2864 out_trans_cancel:
2865	xfs_trans_cancel(tp);
2866 out_unlock:
2867	xfs_iunlock(ip, XFS_ILOCK_EXCL);
2868	xfs_iunlock(dp, XFS_ILOCK_EXCL);
2869 out_parent:
2870	xfs_parent_finish(mp, ppargs);
2871 std_return:
2872	return error;
2873}
2874
2875static inline void
2876xfs_iunlock_rename(
2877	struct xfs_inode	**i_tab,
2878	int			num_inodes)
2879{
2880	int			i;
2881
2882	for (i = num_inodes - 1; i >= 0; i--) {
2883		/* Skip duplicate inodes if src and target dps are the same */
2884		if (!i_tab[i] || (i > 0 && i_tab[i] == i_tab[i - 1]))
2885			continue;
2886		xfs_iunlock(i_tab[i], XFS_ILOCK_EXCL);
2887	}
2888}
2889
2890/*
2891 * Enter all inodes for a rename transaction into a sorted array.
2892 */
2893#define __XFS_SORT_INODES	5
2894STATIC void
2895xfs_sort_for_rename(
2896	struct xfs_inode	*dp1,	/* in: old (source) directory inode */
2897	struct xfs_inode	*dp2,	/* in: new (target) directory inode */
2898	struct xfs_inode	*ip1,	/* in: inode of old entry */
2899	struct xfs_inode	*ip2,	/* in: inode of new entry */
2900	struct xfs_inode	*wip,	/* in: whiteout inode */
2901	struct xfs_inode	**i_tab,/* out: sorted array of inodes */
2902	int			*num_inodes)  /* in/out: inodes in array */
2903{
2904	int			i;
2905
2906	ASSERT(*num_inodes == __XFS_SORT_INODES);
2907	memset(i_tab, 0, *num_inodes * sizeof(struct xfs_inode *));
2908
2909	/*
2910	 * i_tab contains a list of pointers to inodes.  We initialize
2911	 * the table here & we'll sort it.  We will then use it to
2912	 * order the acquisition of the inode locks.
2913	 *
2914	 * Note that the table may contain duplicates.  e.g., dp1 == dp2.
2915	 */
2916	i = 0;
2917	i_tab[i++] = dp1;
2918	i_tab[i++] = dp2;
2919	i_tab[i++] = ip1;
2920	if (ip2)
2921		i_tab[i++] = ip2;
2922	if (wip)
2923		i_tab[i++] = wip;
2924	*num_inodes = i;
2925
2926	xfs_sort_inodes(i_tab, *num_inodes);
2927}
2928
2929void
2930xfs_sort_inodes(
2931	struct xfs_inode	**i_tab,
2932	unsigned int		num_inodes)
2933{
2934	int			i, j;
2935
2936	ASSERT(num_inodes <= __XFS_SORT_INODES);
2937
2938	/*
2939	 * Sort the elements via bubble sort.  (Remember, there are at
2940	 * most 5 elements to sort, so this is adequate.)
2941	 */
2942	for (i = 0; i < num_inodes; i++) {
2943		for (j = 1; j < num_inodes; j++) {
2944			if (i_tab[j]->i_ino < i_tab[j-1]->i_ino)
2945				swap(i_tab[j], i_tab[j - 1]);
2946		}
2947	}
2948}
2949
2950static int
2951xfs_finish_rename(
2952	struct xfs_trans	*tp)
2953{
2954	/*
2955	 * If this is a synchronous mount, make sure that the rename transaction
2956	 * goes to disk before returning to the user.
2957	 */
2958	if (xfs_has_wsync(tp->t_mountp) || xfs_has_dirsync(tp->t_mountp))
2959		xfs_trans_set_sync(tp);
2960
2961	return xfs_trans_commit(tp);
2962}
2963
2964/*
2965 * xfs_cross_rename()
2966 *
2967 * responsible for handling RENAME_EXCHANGE flag in renameat2() syscall
2968 */
2969STATIC int
2970xfs_cross_rename(
2971	struct xfs_trans	*tp,
2972	struct xfs_inode	*dp1,
2973	struct xfs_name		*name1,
2974	struct xfs_inode	*ip1,
2975	struct xfs_parent_args	*ip1_ppargs,
2976	struct xfs_inode	*dp2,
2977	struct xfs_name		*name2,
2978	struct xfs_inode	*ip2,
2979	struct xfs_parent_args	*ip2_ppargs,
2980	int			spaceres)
2981{
2982	int			error = 0;
2983	int			ip1_flags = 0;
2984	int			ip2_flags = 0;
2985	int			dp2_flags = 0;
2986
2987	/* Swap inode number for dirent in first parent */
2988	error = xfs_dir_replace(tp, dp1, name1, ip2->i_ino, spaceres);
2989	if (error)
2990		goto out_trans_abort;
2991
2992	/* Swap inode number for dirent in second parent */
2993	error = xfs_dir_replace(tp, dp2, name2, ip1->i_ino, spaceres);
2994	if (error)
2995		goto out_trans_abort;
2996
2997	/*
2998	 * If we're renaming one or more directories across different parents,
2999	 * update the respective ".." entries (and link counts) to match the new
3000	 * parents.
3001	 */
3002	if (dp1 != dp2) {
3003		dp2_flags = XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG;
3004
3005		if (S_ISDIR(VFS_I(ip2)->i_mode)) {
3006			error = xfs_dir_replace(tp, ip2, &xfs_name_dotdot,
3007						dp1->i_ino, spaceres);
3008			if (error)
3009				goto out_trans_abort;
3010
3011			/* transfer ip2 ".." reference to dp1 */
3012			if (!S_ISDIR(VFS_I(ip1)->i_mode)) {
3013				error = xfs_droplink(tp, dp2);
3014				if (error)
3015					goto out_trans_abort;
3016				xfs_bumplink(tp, dp1);
3017			}
3018
3019			/*
3020			 * Although ip1 isn't changed here, userspace needs
3021			 * to be warned about the change, so that applications
3022			 * relying on it (like backup ones), will properly
3023			 * notify the change
3024			 */
3025			ip1_flags |= XFS_ICHGTIME_CHG;
3026			ip2_flags |= XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG;
3027		}
3028
3029		if (S_ISDIR(VFS_I(ip1)->i_mode)) {
3030			error = xfs_dir_replace(tp, ip1, &xfs_name_dotdot,
3031						dp2->i_ino, spaceres);
3032			if (error)
3033				goto out_trans_abort;
3034
3035			/* transfer ip1 ".." reference to dp2 */
3036			if (!S_ISDIR(VFS_I(ip2)->i_mode)) {
3037				error = xfs_droplink(tp, dp1);
3038				if (error)
3039					goto out_trans_abort;
3040				xfs_bumplink(tp, dp2);
3041			}
3042
3043			/*
3044			 * Although ip2 isn't changed here, userspace needs
3045			 * to be warned about the change, so that applications
3046			 * relying on it (like backup ones), will properly
3047			 * notify the change
3048			 */
3049			ip1_flags |= XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG;
3050			ip2_flags |= XFS_ICHGTIME_CHG;
3051		}
3052	}
3053
3054	/* Schedule parent pointer replacements */
3055	if (ip1_ppargs) {
3056		error = xfs_parent_replacename(tp, ip1_ppargs, dp1, name1, dp2,
3057				name2, ip1);
3058		if (error)
3059			goto out_trans_abort;
3060	}
3061
3062	if (ip2_ppargs) {
3063		error = xfs_parent_replacename(tp, ip2_ppargs, dp2, name2, dp1,
3064				name1, ip2);
3065		if (error)
3066			goto out_trans_abort;
3067	}
3068
3069	if (ip1_flags) {
3070		xfs_trans_ichgtime(tp, ip1, ip1_flags);
3071		xfs_trans_log_inode(tp, ip1, XFS_ILOG_CORE);
3072	}
3073	if (ip2_flags) {
3074		xfs_trans_ichgtime(tp, ip2, ip2_flags);
3075		xfs_trans_log_inode(tp, ip2, XFS_ILOG_CORE);
3076	}
3077	if (dp2_flags) {
3078		xfs_trans_ichgtime(tp, dp2, dp2_flags);
3079		xfs_trans_log_inode(tp, dp2, XFS_ILOG_CORE);
3080	}
3081	xfs_trans_ichgtime(tp, dp1, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
3082	xfs_trans_log_inode(tp, dp1, XFS_ILOG_CORE);
3083
3084	/*
3085	 * Inform our hook clients that we've finished an exchange operation as
3086	 * follows: removed the source and target files from their directories;
3087	 * added the target to the source directory; and added the source to
3088	 * the target directory.  All inodes are locked, so it's ok to model a
3089	 * rename this way so long as we say we deleted entries before we add
3090	 * new ones.
3091	 */
3092	xfs_dir_update_hook(dp1, ip1, -1, name1);
3093	xfs_dir_update_hook(dp2, ip2, -1, name2);
3094	xfs_dir_update_hook(dp1, ip2, 1, name1);
3095	xfs_dir_update_hook(dp2, ip1, 1, name2);
3096
3097	return xfs_finish_rename(tp);
3098
3099out_trans_abort:
3100	xfs_trans_cancel(tp);
3101	return error;
3102}
3103
3104/*
3105 * xfs_rename_alloc_whiteout()
3106 *
3107 * Return a referenced, unlinked, unlocked inode that can be used as a
3108 * whiteout in a rename transaction. We use a tmpfile inode here so that if we
3109 * crash between allocating the inode and linking it into the rename transaction
3110 * recovery will free the inode and we won't leak it.
3111 */
3112static int
3113xfs_rename_alloc_whiteout(
3114	struct mnt_idmap	*idmap,
3115	struct xfs_name		*src_name,
3116	struct xfs_inode	*dp,
3117	struct xfs_inode	**wip)
3118{
3119	struct xfs_inode	*tmpfile;
3120	struct qstr		name;
3121	int			error;
3122
3123	error = xfs_create_tmpfile(idmap, dp, S_IFCHR | WHITEOUT_MODE,
3124			xfs_has_parent(dp->i_mount), &tmpfile);
3125	if (error)
3126		return error;
3127
3128	name.name = src_name->name;
3129	name.len = src_name->len;
3130	error = xfs_inode_init_security(VFS_I(tmpfile), VFS_I(dp), &name);
3131	if (error) {
3132		xfs_finish_inode_setup(tmpfile);
3133		xfs_irele(tmpfile);
3134		return error;
3135	}
3136
3137	/*
3138	 * Prepare the tmpfile inode as if it were created through the VFS.
3139	 * Complete the inode setup and flag it as linkable.  nlink is already
3140	 * zero, so we can skip the drop_nlink.
3141	 */
3142	xfs_setup_iops(tmpfile);
3143	xfs_finish_inode_setup(tmpfile);
3144	VFS_I(tmpfile)->i_state |= I_LINKABLE;
3145
3146	*wip = tmpfile;
3147	return 0;
3148}
3149
3150/*
3151 * xfs_rename
3152 */
3153int
3154xfs_rename(
3155	struct mnt_idmap	*idmap,
3156	struct xfs_inode	*src_dp,
3157	struct xfs_name		*src_name,
3158	struct xfs_inode	*src_ip,
3159	struct xfs_inode	*target_dp,
3160	struct xfs_name		*target_name,
3161	struct xfs_inode	*target_ip,
3162	unsigned int		flags)
3163{
3164	struct xfs_mount	*mp = src_dp->i_mount;
3165	struct xfs_trans	*tp;
3166	struct xfs_inode	*wip = NULL;		/* whiteout inode */
3167	struct xfs_inode	*inodes[__XFS_SORT_INODES];
3168	struct xfs_parent_args	*src_ppargs = NULL;
3169	struct xfs_parent_args	*tgt_ppargs = NULL;
3170	struct xfs_parent_args	*wip_ppargs = NULL;
3171	int			i;
3172	int			num_inodes = __XFS_SORT_INODES;
3173	bool			new_parent = (src_dp != target_dp);
3174	bool			src_is_directory = S_ISDIR(VFS_I(src_ip)->i_mode);
3175	int			spaceres;
3176	bool			retried = false;
3177	int			error, nospace_error = 0;
3178
3179	trace_xfs_rename(src_dp, target_dp, src_name, target_name);
3180
3181	if ((flags & RENAME_EXCHANGE) && !target_ip)
3182		return -EINVAL;
3183
3184	/*
3185	 * If we are doing a whiteout operation, allocate the whiteout inode
3186	 * we will be placing at the target and ensure the type is set
3187	 * appropriately.
3188	 */
3189	if (flags & RENAME_WHITEOUT) {
3190		error = xfs_rename_alloc_whiteout(idmap, src_name,
3191						  target_dp, &wip);
3192		if (error)
3193			return error;
3194
3195		/* setup target dirent info as whiteout */
3196		src_name->type = XFS_DIR3_FT_CHRDEV;
3197	}
3198
3199	xfs_sort_for_rename(src_dp, target_dp, src_ip, target_ip, wip,
3200				inodes, &num_inodes);
3201
3202	error = xfs_parent_start(mp, &src_ppargs);
3203	if (error)
3204		goto out_release_wip;
3205
3206	if (wip) {
3207		error = xfs_parent_start(mp, &wip_ppargs);
3208		if (error)
3209			goto out_src_ppargs;
3210	}
3211
3212	if (target_ip) {
3213		error = xfs_parent_start(mp, &tgt_ppargs);
3214		if (error)
3215			goto out_wip_ppargs;
3216	}
3217
3218retry:
3219	nospace_error = 0;
3220	spaceres = xfs_rename_space_res(mp, src_name->len, target_ip != NULL,
3221			target_name->len, wip != NULL);
3222	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_rename, spaceres, 0, 0, &tp);
3223	if (error == -ENOSPC) {
3224		nospace_error = error;
3225		spaceres = 0;
3226		error = xfs_trans_alloc(mp, &M_RES(mp)->tr_rename, 0, 0, 0,
3227				&tp);
3228	}
3229	if (error)
3230		goto out_tgt_ppargs;
3231
3232	/*
3233	 * We don't allow reservationless renaming when parent pointers are
3234	 * enabled because we can't back out if the xattrs must grow.
3235	 */
3236	if (src_ppargs && nospace_error) {
3237		error = nospace_error;
3238		xfs_trans_cancel(tp);
3239		goto out_tgt_ppargs;
3240	}
3241
3242	/*
3243	 * Attach the dquots to the inodes
3244	 */
3245	error = xfs_qm_vop_rename_dqattach(inodes);
3246	if (error) {
3247		xfs_trans_cancel(tp);
3248		goto out_tgt_ppargs;
3249	}
3250
3251	/*
3252	 * Lock all the participating inodes. Depending upon whether
3253	 * the target_name exists in the target directory, and
3254	 * whether the target directory is the same as the source
3255	 * directory, we can lock from 2 to 5 inodes.
3256	 */
3257	xfs_lock_inodes(inodes, num_inodes, XFS_ILOCK_EXCL);
3258
3259	/*
3260	 * Join all the inodes to the transaction.
3261	 */
3262	xfs_trans_ijoin(tp, src_dp, 0);
3263	if (new_parent)
3264		xfs_trans_ijoin(tp, target_dp, 0);
3265	xfs_trans_ijoin(tp, src_ip, 0);
3266	if (target_ip)
3267		xfs_trans_ijoin(tp, target_ip, 0);
3268	if (wip)
3269		xfs_trans_ijoin(tp, wip, 0);
3270
3271	/*
3272	 * If we are using project inheritance, we only allow renames
3273	 * into our tree when the project IDs are the same; else the
3274	 * tree quota mechanism would be circumvented.
3275	 */
3276	if (unlikely((target_dp->i_diflags & XFS_DIFLAG_PROJINHERIT) &&
3277		     target_dp->i_projid != src_ip->i_projid)) {
3278		error = -EXDEV;
3279		goto out_trans_cancel;
3280	}
3281
3282	/* RENAME_EXCHANGE is unique from here on. */
3283	if (flags & RENAME_EXCHANGE) {
3284		error = xfs_cross_rename(tp, src_dp, src_name, src_ip,
3285				src_ppargs, target_dp, target_name, target_ip,
3286				tgt_ppargs, spaceres);
3287		nospace_error = 0;
3288		goto out_unlock;
3289	}
3290
3291	/*
3292	 * Try to reserve quota to handle an expansion of the target directory.
3293	 * We'll allow the rename to continue in reservationless mode if we hit
3294	 * a space usage constraint.  If we trigger reservationless mode, save
3295	 * the errno if there isn't any free space in the target directory.
3296	 */
3297	if (spaceres != 0) {
3298		error = xfs_trans_reserve_quota_nblks(tp, target_dp, spaceres,
3299				0, false);
3300		if (error == -EDQUOT || error == -ENOSPC) {
3301			if (!retried) {
3302				xfs_trans_cancel(tp);
3303				xfs_iunlock_rename(inodes, num_inodes);
3304				xfs_blockgc_free_quota(target_dp, 0);
3305				retried = true;
3306				goto retry;
3307			}
3308
3309			nospace_error = error;
3310			spaceres = 0;
3311			error = 0;
3312		}
3313		if (error)
3314			goto out_trans_cancel;
3315	}
3316
3317	/*
3318	 * We don't allow quotaless renaming when parent pointers are enabled
3319	 * because we can't back out if the xattrs must grow.
3320	 */
3321	if (src_ppargs && nospace_error) {
3322		error = nospace_error;
3323		goto out_trans_cancel;
3324	}
3325
3326	/*
3327	 * Check for expected errors before we dirty the transaction
3328	 * so we can return an error without a transaction abort.
3329	 */
3330	if (target_ip == NULL) {
3331		/*
3332		 * If there's no space reservation, check the entry will
3333		 * fit before actually inserting it.
3334		 */
3335		if (!spaceres) {
3336			error = xfs_dir_canenter(tp, target_dp, target_name);
3337			if (error)
3338				goto out_trans_cancel;
3339		}
3340	} else {
3341		/*
3342		 * If target exists and it's a directory, check that whether
3343		 * it can be destroyed.
3344		 */
3345		if (S_ISDIR(VFS_I(target_ip)->i_mode) &&
3346		    (!xfs_dir_isempty(target_ip) ||
3347		     (VFS_I(target_ip)->i_nlink > 2))) {
3348			error = -EEXIST;
3349			goto out_trans_cancel;
3350		}
3351	}
3352
3353	/*
3354	 * Lock the AGI buffers we need to handle bumping the nlink of the
3355	 * whiteout inode off the unlinked list and to handle dropping the
3356	 * nlink of the target inode.  Per locking order rules, do this in
3357	 * increasing AG order and before directory block allocation tries to
3358	 * grab AGFs because we grab AGIs before AGFs.
3359	 *
3360	 * The (vfs) caller must ensure that if src is a directory then
3361	 * target_ip is either null or an empty directory.
3362	 */
3363	for (i = 0; i < num_inodes && inodes[i] != NULL; i++) {
3364		if (inodes[i] == wip ||
3365		    (inodes[i] == target_ip &&
3366		     (VFS_I(target_ip)->i_nlink == 1 || src_is_directory))) {
3367			struct xfs_perag	*pag;
3368			struct xfs_buf		*bp;
3369
3370			pag = xfs_perag_get(mp,
3371					XFS_INO_TO_AGNO(mp, inodes[i]->i_ino));
3372			error = xfs_read_agi(pag, tp, 0, &bp);
3373			xfs_perag_put(pag);
3374			if (error)
3375				goto out_trans_cancel;
3376		}
3377	}
3378
3379	/*
3380	 * Directory entry creation below may acquire the AGF. Remove
3381	 * the whiteout from the unlinked list first to preserve correct
3382	 * AGI/AGF locking order. This dirties the transaction so failures
3383	 * after this point will abort and log recovery will clean up the
3384	 * mess.
3385	 *
3386	 * For whiteouts, we need to bump the link count on the whiteout
3387	 * inode. After this point, we have a real link, clear the tmpfile
3388	 * state flag from the inode so it doesn't accidentally get misused
3389	 * in future.
3390	 */
3391	if (wip) {
3392		struct xfs_perag	*pag;
3393
3394		ASSERT(VFS_I(wip)->i_nlink == 0);
3395
3396		pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, wip->i_ino));
3397		error = xfs_iunlink_remove(tp, pag, wip);
3398		xfs_perag_put(pag);
3399		if (error)
3400			goto out_trans_cancel;
3401
3402		xfs_bumplink(tp, wip);
3403		VFS_I(wip)->i_state &= ~I_LINKABLE;
3404	}
3405
3406	/*
3407	 * Set up the target.
3408	 */
3409	if (target_ip == NULL) {
3410		/*
3411		 * If target does not exist and the rename crosses
3412		 * directories, adjust the target directory link count
3413		 * to account for the ".." reference from the new entry.
3414		 */
3415		error = xfs_dir_createname(tp, target_dp, target_name,
3416					   src_ip->i_ino, spaceres);
3417		if (error)
3418			goto out_trans_cancel;
3419
3420		xfs_trans_ichgtime(tp, target_dp,
3421					XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
3422
3423		if (new_parent && src_is_directory) {
3424			xfs_bumplink(tp, target_dp);
3425		}
3426	} else { /* target_ip != NULL */
3427		/*
3428		 * Link the source inode under the target name.
3429		 * If the source inode is a directory and we are moving
3430		 * it across directories, its ".." entry will be
3431		 * inconsistent until we replace that down below.
3432		 *
3433		 * In case there is already an entry with the same
3434		 * name at the destination directory, remove it first.
3435		 */
3436		error = xfs_dir_replace(tp, target_dp, target_name,
3437					src_ip->i_ino, spaceres);
3438		if (error)
3439			goto out_trans_cancel;
3440
3441		xfs_trans_ichgtime(tp, target_dp,
3442					XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
3443
3444		/*
3445		 * Decrement the link count on the target since the target
3446		 * dir no longer points to it.
3447		 */
3448		error = xfs_droplink(tp, target_ip);
3449		if (error)
3450			goto out_trans_cancel;
3451
3452		if (src_is_directory) {
3453			/*
3454			 * Drop the link from the old "." entry.
3455			 */
3456			error = xfs_droplink(tp, target_ip);
3457			if (error)
3458				goto out_trans_cancel;
3459		}
3460	} /* target_ip != NULL */
3461
3462	/*
3463	 * Remove the source.
3464	 */
3465	if (new_parent && src_is_directory) {
3466		/*
3467		 * Rewrite the ".." entry to point to the new
3468		 * directory.
3469		 */
3470		error = xfs_dir_replace(tp, src_ip, &xfs_name_dotdot,
3471					target_dp->i_ino, spaceres);
3472		ASSERT(error != -EEXIST);
3473		if (error)
3474			goto out_trans_cancel;
3475	}
3476
3477	/*
3478	 * We always want to hit the ctime on the source inode.
3479	 *
3480	 * This isn't strictly required by the standards since the source
3481	 * inode isn't really being changed, but old unix file systems did
3482	 * it and some incremental backup programs won't work without it.
3483	 */
3484	xfs_trans_ichgtime(tp, src_ip, XFS_ICHGTIME_CHG);
3485	xfs_trans_log_inode(tp, src_ip, XFS_ILOG_CORE);
3486
3487	/*
3488	 * Adjust the link count on src_dp.  This is necessary when
3489	 * renaming a directory, either within one parent when
3490	 * the target existed, or across two parent directories.
3491	 */
3492	if (src_is_directory && (new_parent || target_ip != NULL)) {
3493
3494		/*
3495		 * Decrement link count on src_directory since the
3496		 * entry that's moved no longer points to it.
3497		 */
3498		error = xfs_droplink(tp, src_dp);
3499		if (error)
3500			goto out_trans_cancel;
3501	}
3502
3503	/*
3504	 * For whiteouts, we only need to update the source dirent with the
3505	 * inode number of the whiteout inode rather than removing it
3506	 * altogether.
3507	 */
3508	if (wip)
3509		error = xfs_dir_replace(tp, src_dp, src_name, wip->i_ino,
3510					spaceres);
3511	else
3512		error = xfs_dir_removename(tp, src_dp, src_name, src_ip->i_ino,
3513					   spaceres);
3514
3515	if (error)
3516		goto out_trans_cancel;
3517
3518	/* Schedule parent pointer updates. */
3519	if (wip_ppargs) {
3520		error = xfs_parent_addname(tp, wip_ppargs, src_dp, src_name,
3521				wip);
3522		if (error)
3523			goto out_trans_cancel;
3524	}
3525
3526	if (src_ppargs) {
3527		error = xfs_parent_replacename(tp, src_ppargs, src_dp,
3528				src_name, target_dp, target_name, src_ip);
3529		if (error)
3530			goto out_trans_cancel;
3531	}
3532
3533	if (tgt_ppargs) {
3534		error = xfs_parent_removename(tp, tgt_ppargs, target_dp,
3535				target_name, target_ip);
3536		if (error)
3537			goto out_trans_cancel;
3538	}
3539
3540	xfs_trans_ichgtime(tp, src_dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
3541	xfs_trans_log_inode(tp, src_dp, XFS_ILOG_CORE);
3542	if (new_parent)
3543		xfs_trans_log_inode(tp, target_dp, XFS_ILOG_CORE);
3544
3545	/*
3546	 * Inform our hook clients that we've finished a rename operation as
3547	 * follows: removed the source and target files from their directories;
3548	 * that we've added the source to the target directory; and finally
3549	 * that we've added the whiteout, if there was one.  All inodes are
3550	 * locked, so it's ok to model a rename this way so long as we say we
3551	 * deleted entries before we add new ones.
3552	 */
3553	if (target_ip)
3554		xfs_dir_update_hook(target_dp, target_ip, -1, target_name);
3555	xfs_dir_update_hook(src_dp, src_ip, -1, src_name);
3556	xfs_dir_update_hook(target_dp, src_ip, 1, target_name);
3557	if (wip)
3558		xfs_dir_update_hook(src_dp, wip, 1, src_name);
3559
3560	error = xfs_finish_rename(tp);
3561	nospace_error = 0;
3562	goto out_unlock;
3563
3564out_trans_cancel:
3565	xfs_trans_cancel(tp);
3566out_unlock:
3567	xfs_iunlock_rename(inodes, num_inodes);
3568out_tgt_ppargs:
3569	xfs_parent_finish(mp, tgt_ppargs);
3570out_wip_ppargs:
3571	xfs_parent_finish(mp, wip_ppargs);
3572out_src_ppargs:
3573	xfs_parent_finish(mp, src_ppargs);
3574out_release_wip:
3575	if (wip)
3576		xfs_irele(wip);
3577	if (error == -ENOSPC && nospace_error)
3578		error = nospace_error;
3579	return error;
3580}
3581
3582static int
3583xfs_iflush(
3584	struct xfs_inode	*ip,
3585	struct xfs_buf		*bp)
3586{
3587	struct xfs_inode_log_item *iip = ip->i_itemp;
3588	struct xfs_dinode	*dip;
3589	struct xfs_mount	*mp = ip->i_mount;
3590	int			error;
3591
3592	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL | XFS_ILOCK_SHARED);
3593	ASSERT(xfs_iflags_test(ip, XFS_IFLUSHING));
3594	ASSERT(ip->i_df.if_format != XFS_DINODE_FMT_BTREE ||
3595	       ip->i_df.if_nextents > XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK));
3596	ASSERT(iip->ili_item.li_buf == bp);
3597
3598	dip = xfs_buf_offset(bp, ip->i_imap.im_boffset);
3599
3600	/*
3601	 * We don't flush the inode if any of the following checks fail, but we
3602	 * do still update the log item and attach to the backing buffer as if
3603	 * the flush happened. This is a formality to facilitate predictable
3604	 * error handling as the caller will shutdown and fail the buffer.
3605	 */
3606	error = -EFSCORRUPTED;
3607	if (XFS_TEST_ERROR(dip->di_magic != cpu_to_be16(XFS_DINODE_MAGIC),
3608			       mp, XFS_ERRTAG_IFLUSH_1)) {
3609		xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
3610			"%s: Bad inode %llu magic number 0x%x, ptr "PTR_FMT,
3611			__func__, ip->i_ino, be16_to_cpu(dip->di_magic), dip);
3612		goto flush_out;
3613	}
3614	if (S_ISREG(VFS_I(ip)->i_mode)) {
3615		if (XFS_TEST_ERROR(
3616		    ip->i_df.if_format != XFS_DINODE_FMT_EXTENTS &&
3617		    ip->i_df.if_format != XFS_DINODE_FMT_BTREE,
3618		    mp, XFS_ERRTAG_IFLUSH_3)) {
3619			xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
3620				"%s: Bad regular inode %llu, ptr "PTR_FMT,
3621				__func__, ip->i_ino, ip);
3622			goto flush_out;
3623		}
3624	} else if (S_ISDIR(VFS_I(ip)->i_mode)) {
3625		if (XFS_TEST_ERROR(
3626		    ip->i_df.if_format != XFS_DINODE_FMT_EXTENTS &&
3627		    ip->i_df.if_format != XFS_DINODE_FMT_BTREE &&
3628		    ip->i_df.if_format != XFS_DINODE_FMT_LOCAL,
3629		    mp, XFS_ERRTAG_IFLUSH_4)) {
3630			xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
3631				"%s: Bad directory inode %llu, ptr "PTR_FMT,
3632				__func__, ip->i_ino, ip);
3633			goto flush_out;
3634		}
3635	}
3636	if (XFS_TEST_ERROR(ip->i_df.if_nextents + xfs_ifork_nextents(&ip->i_af) >
3637				ip->i_nblocks, mp, XFS_ERRTAG_IFLUSH_5)) {
3638		xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
3639			"%s: detected corrupt incore inode %llu, "
3640			"total extents = %llu nblocks = %lld, ptr "PTR_FMT,
3641			__func__, ip->i_ino,
3642			ip->i_df.if_nextents + xfs_ifork_nextents(&ip->i_af),
3643			ip->i_nblocks, ip);
3644		goto flush_out;
3645	}
3646	if (XFS_TEST_ERROR(ip->i_forkoff > mp->m_sb.sb_inodesize,
3647				mp, XFS_ERRTAG_IFLUSH_6)) {
3648		xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
3649			"%s: bad inode %llu, forkoff 0x%x, ptr "PTR_FMT,
3650			__func__, ip->i_ino, ip->i_forkoff, ip);
3651		goto flush_out;
3652	}
3653
3654	/*
3655	 * Inode item log recovery for v2 inodes are dependent on the flushiter
3656	 * count for correct sequencing.  We bump the flush iteration count so
3657	 * we can detect flushes which postdate a log record during recovery.
3658	 * This is redundant as we now log every change and hence this can't
3659	 * happen but we need to still do it to ensure backwards compatibility
3660	 * with old kernels that predate logging all inode changes.
3661	 */
3662	if (!xfs_has_v3inodes(mp))
3663		ip->i_flushiter++;
3664
3665	/*
3666	 * If there are inline format data / attr forks attached to this inode,
3667	 * make sure they are not corrupt.
3668	 */
3669	if (ip->i_df.if_format == XFS_DINODE_FMT_LOCAL &&
3670	    xfs_ifork_verify_local_data(ip))
3671		goto flush_out;
3672	if (xfs_inode_has_attr_fork(ip) &&
3673	    ip->i_af.if_format == XFS_DINODE_FMT_LOCAL &&
3674	    xfs_ifork_verify_local_attr(ip))
3675		goto flush_out;
3676
3677	/*
3678	 * Copy the dirty parts of the inode into the on-disk inode.  We always
3679	 * copy out the core of the inode, because if the inode is dirty at all
3680	 * the core must be.
3681	 */
3682	xfs_inode_to_disk(ip, dip, iip->ili_item.li_lsn);
3683
3684	/* Wrap, we never let the log put out DI_MAX_FLUSH */
3685	if (!xfs_has_v3inodes(mp)) {
3686		if (ip->i_flushiter == DI_MAX_FLUSH)
3687			ip->i_flushiter = 0;
3688	}
3689
3690	xfs_iflush_fork(ip, dip, iip, XFS_DATA_FORK);
3691	if (xfs_inode_has_attr_fork(ip))
3692		xfs_iflush_fork(ip, dip, iip, XFS_ATTR_FORK);
3693
3694	/*
3695	 * We've recorded everything logged in the inode, so we'd like to clear
3696	 * the ili_fields bits so we don't log and flush things unnecessarily.
3697	 * However, we can't stop logging all this information until the data
3698	 * we've copied into the disk buffer is written to disk.  If we did we
3699	 * might overwrite the copy of the inode in the log with all the data
3700	 * after re-logging only part of it, and in the face of a crash we
3701	 * wouldn't have all the data we need to recover.
3702	 *
3703	 * What we do is move the bits to the ili_last_fields field.  When
3704	 * logging the inode, these bits are moved back to the ili_fields field.
3705	 * In the xfs_buf_inode_iodone() routine we clear ili_last_fields, since
3706	 * we know that the information those bits represent is permanently on
3707	 * disk.  As long as the flush completes before the inode is logged
3708	 * again, then both ili_fields and ili_last_fields will be cleared.
3709	 */
3710	error = 0;
3711flush_out:
3712	spin_lock(&iip->ili_lock);
3713	iip->ili_last_fields = iip->ili_fields;
3714	iip->ili_fields = 0;
3715	iip->ili_fsync_fields = 0;
3716	spin_unlock(&iip->ili_lock);
3717
3718	/*
3719	 * Store the current LSN of the inode so that we can tell whether the
3720	 * item has moved in the AIL from xfs_buf_inode_iodone().
3721	 */
3722	xfs_trans_ail_copy_lsn(mp->m_ail, &iip->ili_flush_lsn,
3723				&iip->ili_item.li_lsn);
3724
3725	/* generate the checksum. */
3726	xfs_dinode_calc_crc(mp, dip);
3727	if (error)
3728		xfs_inode_mark_sick(ip, XFS_SICK_INO_CORE);
3729	return error;
3730}
3731
3732/*
3733 * Non-blocking flush of dirty inode metadata into the backing buffer.
3734 *
3735 * The caller must have a reference to the inode and hold the cluster buffer
3736 * locked. The function will walk across all the inodes on the cluster buffer it
3737 * can find and lock without blocking, and flush them to the cluster buffer.
3738 *
3739 * On successful flushing of at least one inode, the caller must write out the
3740 * buffer and release it. If no inodes are flushed, -EAGAIN will be returned and
3741 * the caller needs to release the buffer. On failure, the filesystem will be
3742 * shut down, the buffer will have been unlocked and released, and EFSCORRUPTED
3743 * will be returned.
3744 */
3745int
3746xfs_iflush_cluster(
3747	struct xfs_buf		*bp)
3748{
3749	struct xfs_mount	*mp = bp->b_mount;
3750	struct xfs_log_item	*lip, *n;
3751	struct xfs_inode	*ip;
3752	struct xfs_inode_log_item *iip;
3753	int			clcount = 0;
3754	int			error = 0;
3755
3756	/*
3757	 * We must use the safe variant here as on shutdown xfs_iflush_abort()
3758	 * will remove itself from the list.
3759	 */
3760	list_for_each_entry_safe(lip, n, &bp->b_li_list, li_bio_list) {
3761		iip = (struct xfs_inode_log_item *)lip;
3762		ip = iip->ili_inode;
3763
3764		/*
3765		 * Quick and dirty check to avoid locks if possible.
3766		 */
3767		if (__xfs_iflags_test(ip, XFS_IRECLAIM | XFS_IFLUSHING))
3768			continue;
3769		if (xfs_ipincount(ip))
3770			continue;
3771
3772		/*
3773		 * The inode is still attached to the buffer, which means it is
3774		 * dirty but reclaim might try to grab it. Check carefully for
3775		 * that, and grab the ilock while still holding the i_flags_lock
3776		 * to guarantee reclaim will not be able to reclaim this inode
3777		 * once we drop the i_flags_lock.
3778		 */
3779		spin_lock(&ip->i_flags_lock);
3780		ASSERT(!__xfs_iflags_test(ip, XFS_ISTALE));
3781		if (__xfs_iflags_test(ip, XFS_IRECLAIM | XFS_IFLUSHING)) {
3782			spin_unlock(&ip->i_flags_lock);
3783			continue;
3784		}
3785
3786		/*
3787		 * ILOCK will pin the inode against reclaim and prevent
3788		 * concurrent transactions modifying the inode while we are
3789		 * flushing the inode. If we get the lock, set the flushing
3790		 * state before we drop the i_flags_lock.
3791		 */
3792		if (!xfs_ilock_nowait(ip, XFS_ILOCK_SHARED)) {
3793			spin_unlock(&ip->i_flags_lock);
3794			continue;
3795		}
3796		__xfs_iflags_set(ip, XFS_IFLUSHING);
3797		spin_unlock(&ip->i_flags_lock);
3798
3799		/*
3800		 * Abort flushing this inode if we are shut down because the
3801		 * inode may not currently be in the AIL. This can occur when
3802		 * log I/O failure unpins the inode without inserting into the
3803		 * AIL, leaving a dirty/unpinned inode attached to the buffer
3804		 * that otherwise looks like it should be flushed.
3805		 */
3806		if (xlog_is_shutdown(mp->m_log)) {
3807			xfs_iunpin_wait(ip);
3808			xfs_iflush_abort(ip);
3809			xfs_iunlock(ip, XFS_ILOCK_SHARED);
3810			error = -EIO;
3811			continue;
3812		}
3813
3814		/* don't block waiting on a log force to unpin dirty inodes */
3815		if (xfs_ipincount(ip)) {
3816			xfs_iflags_clear(ip, XFS_IFLUSHING);
3817			xfs_iunlock(ip, XFS_ILOCK_SHARED);
3818			continue;
3819		}
3820
3821		if (!xfs_inode_clean(ip))
3822			error = xfs_iflush(ip, bp);
3823		else
3824			xfs_iflags_clear(ip, XFS_IFLUSHING);
3825		xfs_iunlock(ip, XFS_ILOCK_SHARED);
3826		if (error)
3827			break;
3828		clcount++;
3829	}
3830
3831	if (error) {
3832		/*
3833		 * Shutdown first so we kill the log before we release this
3834		 * buffer. If it is an INODE_ALLOC buffer and pins the tail
3835		 * of the log, failing it before the _log_ is shut down can
3836		 * result in the log tail being moved forward in the journal
3837		 * on disk because log writes can still be taking place. Hence
3838		 * unpinning the tail will allow the ICREATE intent to be
3839		 * removed from the log an recovery will fail with uninitialised
3840		 * inode cluster buffers.
3841		 */
3842		xfs_force_shutdown(mp, SHUTDOWN_CORRUPT_INCORE);
3843		bp->b_flags |= XBF_ASYNC;
3844		xfs_buf_ioend_fail(bp);
3845		return error;
3846	}
3847
3848	if (!clcount)
3849		return -EAGAIN;
3850
3851	XFS_STATS_INC(mp, xs_icluster_flushcnt);
3852	XFS_STATS_ADD(mp, xs_icluster_flushinode, clcount);
3853	return 0;
3854
3855}
3856
3857/* Release an inode. */
3858void
3859xfs_irele(
3860	struct xfs_inode	*ip)
3861{
3862	trace_xfs_irele(ip, _RET_IP_);
3863	iput(VFS_I(ip));
3864}
3865
3866/*
3867 * Ensure all commited transactions touching the inode are written to the log.
3868 */
3869int
3870xfs_log_force_inode(
3871	struct xfs_inode	*ip)
3872{
3873	xfs_csn_t		seq = 0;
3874
3875	xfs_ilock(ip, XFS_ILOCK_SHARED);
3876	if (xfs_ipincount(ip))
3877		seq = ip->i_itemp->ili_commit_seq;
3878	xfs_iunlock(ip, XFS_ILOCK_SHARED);
3879
3880	if (!seq)
3881		return 0;
3882	return xfs_log_force_seq(ip->i_mount, seq, XFS_LOG_SYNC, NULL);
3883}
3884
3885/*
3886 * Grab the exclusive iolock for a data copy from src to dest, making sure to
3887 * abide vfs locking order (lowest pointer value goes first) and breaking the
3888 * layout leases before proceeding.  The loop is needed because we cannot call
3889 * the blocking break_layout() with the iolocks held, and therefore have to
3890 * back out both locks.
3891 */
3892static int
3893xfs_iolock_two_inodes_and_break_layout(
3894	struct inode		*src,
3895	struct inode		*dest)
3896{
3897	int			error;
3898
3899	if (src > dest)
3900		swap(src, dest);
3901
3902retry:
3903	/* Wait to break both inodes' layouts before we start locking. */
3904	error = break_layout(src, true);
3905	if (error)
3906		return error;
3907	if (src != dest) {
3908		error = break_layout(dest, true);
3909		if (error)
3910			return error;
3911	}
3912
3913	/* Lock one inode and make sure nobody got in and leased it. */
3914	inode_lock(src);
3915	error = break_layout(src, false);
3916	if (error) {
3917		inode_unlock(src);
3918		if (error == -EWOULDBLOCK)
3919			goto retry;
3920		return error;
3921	}
3922
3923	if (src == dest)
3924		return 0;
3925
3926	/* Lock the other inode and make sure nobody got in and leased it. */
3927	inode_lock_nested(dest, I_MUTEX_NONDIR2);
3928	error = break_layout(dest, false);
3929	if (error) {
3930		inode_unlock(src);
3931		inode_unlock(dest);
3932		if (error == -EWOULDBLOCK)
3933			goto retry;
3934		return error;
3935	}
3936
3937	return 0;
3938}
3939
3940static int
3941xfs_mmaplock_two_inodes_and_break_dax_layout(
3942	struct xfs_inode	*ip1,
3943	struct xfs_inode	*ip2)
3944{
3945	int			error;
3946	bool			retry;
3947	struct page		*page;
3948
3949	if (ip1->i_ino > ip2->i_ino)
3950		swap(ip1, ip2);
3951
3952again:
3953	retry = false;
3954	/* Lock the first inode */
3955	xfs_ilock(ip1, XFS_MMAPLOCK_EXCL);
3956	error = xfs_break_dax_layouts(VFS_I(ip1), &retry);
3957	if (error || retry) {
3958		xfs_iunlock(ip1, XFS_MMAPLOCK_EXCL);
3959		if (error == 0 && retry)
3960			goto again;
3961		return error;
3962	}
3963
3964	if (ip1 == ip2)
3965		return 0;
3966
3967	/* Nested lock the second inode */
3968	xfs_ilock(ip2, xfs_lock_inumorder(XFS_MMAPLOCK_EXCL, 1));
3969	/*
3970	 * We cannot use xfs_break_dax_layouts() directly here because it may
3971	 * need to unlock & lock the XFS_MMAPLOCK_EXCL which is not suitable
3972	 * for this nested lock case.
3973	 */
3974	page = dax_layout_busy_page(VFS_I(ip2)->i_mapping);
3975	if (page && page_ref_count(page) != 1) {
3976		xfs_iunlock(ip2, XFS_MMAPLOCK_EXCL);
3977		xfs_iunlock(ip1, XFS_MMAPLOCK_EXCL);
3978		goto again;
3979	}
3980
3981	return 0;
3982}
3983
3984/*
3985 * Lock two inodes so that userspace cannot initiate I/O via file syscalls or
3986 * mmap activity.
3987 */
3988int
3989xfs_ilock2_io_mmap(
3990	struct xfs_inode	*ip1,
3991	struct xfs_inode	*ip2)
3992{
3993	int			ret;
3994
3995	ret = xfs_iolock_two_inodes_and_break_layout(VFS_I(ip1), VFS_I(ip2));
3996	if (ret)
3997		return ret;
3998
3999	if (IS_DAX(VFS_I(ip1)) && IS_DAX(VFS_I(ip2))) {
4000		ret = xfs_mmaplock_two_inodes_and_break_dax_layout(ip1, ip2);
4001		if (ret) {
4002			inode_unlock(VFS_I(ip2));
4003			if (ip1 != ip2)
4004				inode_unlock(VFS_I(ip1));
4005			return ret;
4006		}
4007	} else
4008		filemap_invalidate_lock_two(VFS_I(ip1)->i_mapping,
4009					    VFS_I(ip2)->i_mapping);
4010
4011	return 0;
4012}
4013
4014/* Unlock both inodes to allow IO and mmap activity. */
4015void
4016xfs_iunlock2_io_mmap(
4017	struct xfs_inode	*ip1,
4018	struct xfs_inode	*ip2)
4019{
4020	if (IS_DAX(VFS_I(ip1)) && IS_DAX(VFS_I(ip2))) {
4021		xfs_iunlock(ip2, XFS_MMAPLOCK_EXCL);
4022		if (ip1 != ip2)
4023			xfs_iunlock(ip1, XFS_MMAPLOCK_EXCL);
4024	} else
4025		filemap_invalidate_unlock_two(VFS_I(ip1)->i_mapping,
4026					      VFS_I(ip2)->i_mapping);
4027
4028	inode_unlock(VFS_I(ip2));
4029	if (ip1 != ip2)
4030		inode_unlock(VFS_I(ip1));
4031}
4032
4033/* Drop the MMAPLOCK and the IOLOCK after a remap completes. */
4034void
4035xfs_iunlock2_remapping(
4036	struct xfs_inode	*ip1,
4037	struct xfs_inode	*ip2)
4038{
4039	xfs_iflags_clear(ip1, XFS_IREMAPPING);
4040
4041	if (ip1 != ip2)
4042		xfs_iunlock(ip1, XFS_MMAPLOCK_SHARED);
4043	xfs_iunlock(ip2, XFS_MMAPLOCK_EXCL);
4044
4045	if (ip1 != ip2)
4046		inode_unlock_shared(VFS_I(ip1));
4047	inode_unlock(VFS_I(ip2));
4048}
4049
4050/*
4051 * Reload the incore inode list for this inode.  Caller should ensure that
4052 * the link count cannot change, either by taking ILOCK_SHARED or otherwise
4053 * preventing other threads from executing.
4054 */
4055int
4056xfs_inode_reload_unlinked_bucket(
4057	struct xfs_trans	*tp,
4058	struct xfs_inode	*ip)
4059{
4060	struct xfs_mount	*mp = tp->t_mountp;
4061	struct xfs_buf		*agibp;
4062	struct xfs_agi		*agi;
4063	struct xfs_perag	*pag;
4064	xfs_agnumber_t		agno = XFS_INO_TO_AGNO(mp, ip->i_ino);
4065	xfs_agino_t		agino = XFS_INO_TO_AGINO(mp, ip->i_ino);
4066	xfs_agino_t		prev_agino, next_agino;
4067	unsigned int		bucket;
4068	bool			foundit = false;
4069	int			error;
4070
4071	/* Grab the first inode in the list */
4072	pag = xfs_perag_get(mp, agno);
4073	error = xfs_ialloc_read_agi(pag, tp, 0, &agibp);
4074	xfs_perag_put(pag);
4075	if (error)
4076		return error;
4077
4078	/*
4079	 * We've taken ILOCK_SHARED and the AGI buffer lock to stabilize the
4080	 * incore unlinked list pointers for this inode.  Check once more to
4081	 * see if we raced with anyone else to reload the unlinked list.
4082	 */
4083	if (!xfs_inode_unlinked_incomplete(ip)) {
4084		foundit = true;
4085		goto out_agibp;
4086	}
4087
4088	bucket = agino % XFS_AGI_UNLINKED_BUCKETS;
4089	agi = agibp->b_addr;
4090
4091	trace_xfs_inode_reload_unlinked_bucket(ip);
4092
4093	xfs_info_ratelimited(mp,
4094 "Found unrecovered unlinked inode 0x%x in AG 0x%x.  Initiating list recovery.",
4095			agino, agno);
4096
4097	prev_agino = NULLAGINO;
4098	next_agino = be32_to_cpu(agi->agi_unlinked[bucket]);
4099	while (next_agino != NULLAGINO) {
4100		struct xfs_inode	*next_ip = NULL;
4101
4102		/* Found this caller's inode, set its backlink. */
4103		if (next_agino == agino) {
4104			next_ip = ip;
4105			next_ip->i_prev_unlinked = prev_agino;
4106			foundit = true;
4107			goto next_inode;
4108		}
4109
4110		/* Try in-memory lookup first. */
4111		next_ip = xfs_iunlink_lookup(pag, next_agino);
4112		if (next_ip)
4113			goto next_inode;
4114
4115		/* Inode not in memory, try reloading it. */
4116		error = xfs_iunlink_reload_next(tp, agibp, prev_agino,
4117				next_agino);
4118		if (error)
4119			break;
4120
4121		/* Grab the reloaded inode. */
4122		next_ip = xfs_iunlink_lookup(pag, next_agino);
4123		if (!next_ip) {
4124			/* No incore inode at all?  We reloaded it... */
4125			ASSERT(next_ip != NULL);
4126			error = -EFSCORRUPTED;
4127			break;
4128		}
4129
4130next_inode:
4131		prev_agino = next_agino;
4132		next_agino = next_ip->i_next_unlinked;
4133	}
4134
4135out_agibp:
4136	xfs_trans_brelse(tp, agibp);
4137	/* Should have found this inode somewhere in the iunlinked bucket. */
4138	if (!error && !foundit)
4139		error = -EFSCORRUPTED;
4140	return error;
4141}
4142
4143/* Decide if this inode is missing its unlinked list and reload it. */
4144int
4145xfs_inode_reload_unlinked(
4146	struct xfs_inode	*ip)
4147{
4148	struct xfs_trans	*tp;
4149	int			error;
4150
4151	error = xfs_trans_alloc_empty(ip->i_mount, &tp);
4152	if (error)
4153		return error;
4154
4155	xfs_ilock(ip, XFS_ILOCK_SHARED);
4156	if (xfs_inode_unlinked_incomplete(ip))
4157		error = xfs_inode_reload_unlinked_bucket(tp, ip);
4158	xfs_iunlock(ip, XFS_ILOCK_SHARED);
4159	xfs_trans_cancel(tp);
4160
4161	return error;
4162}
4163
4164/* Has this inode fork been zapped by repair? */
4165bool
4166xfs_ifork_zapped(
4167	const struct xfs_inode	*ip,
4168	int			whichfork)
4169{
4170	unsigned int		datamask = 0;
4171
4172	switch (whichfork) {
4173	case XFS_DATA_FORK:
4174		switch (ip->i_vnode.i_mode & S_IFMT) {
4175		case S_IFDIR:
4176			datamask = XFS_SICK_INO_DIR_ZAPPED;
4177			break;
4178		case S_IFLNK:
4179			datamask = XFS_SICK_INO_SYMLINK_ZAPPED;
4180			break;
4181		}
4182		return ip->i_sick & (XFS_SICK_INO_BMBTD_ZAPPED | datamask);
4183	case XFS_ATTR_FORK:
4184		return ip->i_sick & XFS_SICK_INO_BMBTA_ZAPPED;
4185	default:
4186		return false;
4187	}
4188}
4189
4190/* Compute the number of data and realtime blocks used by a file. */
4191void
4192xfs_inode_count_blocks(
4193	struct xfs_trans	*tp,
4194	struct xfs_inode	*ip,
4195	xfs_filblks_t		*dblocks,
4196	xfs_filblks_t		*rblocks)
4197{
4198	struct xfs_ifork	*ifp = xfs_ifork_ptr(ip, XFS_DATA_FORK);
4199
4200	*rblocks = 0;
4201	if (XFS_IS_REALTIME_INODE(ip))
4202		xfs_bmap_count_leaves(ifp, rblocks);
4203	*dblocks = ip->i_nblocks - *rblocks;
4204}
4205
4206static void
4207xfs_wait_dax_page(
4208	struct inode		*inode)
4209{
4210	struct xfs_inode        *ip = XFS_I(inode);
4211
4212	xfs_iunlock(ip, XFS_MMAPLOCK_EXCL);
4213	schedule();
4214	xfs_ilock(ip, XFS_MMAPLOCK_EXCL);
4215}
4216
4217int
4218xfs_break_dax_layouts(
4219	struct inode		*inode,
4220	bool			*retry)
4221{
4222	struct page		*page;
4223
4224	xfs_assert_ilocked(XFS_I(inode), XFS_MMAPLOCK_EXCL);
4225
4226	page = dax_layout_busy_page(inode->i_mapping);
4227	if (!page)
4228		return 0;
4229
4230	*retry = true;
4231	return ___wait_var_event(&page->_refcount,
4232			atomic_read(&page->_refcount) == 1, TASK_INTERRUPTIBLE,
4233			0, 0, xfs_wait_dax_page(inode));
4234}
4235
4236int
4237xfs_break_layouts(
4238	struct inode		*inode,
4239	uint			*iolock,
4240	enum layout_break_reason reason)
4241{
4242	bool			retry;
4243	int			error;
4244
4245	xfs_assert_ilocked(XFS_I(inode), XFS_IOLOCK_SHARED | XFS_IOLOCK_EXCL);
4246
4247	do {
4248		retry = false;
4249		switch (reason) {
4250		case BREAK_UNMAP:
4251			error = xfs_break_dax_layouts(inode, &retry);
4252			if (error || retry)
4253				break;
4254			fallthrough;
4255		case BREAK_WRITE:
4256			error = xfs_break_leased_layouts(inode, iolock, &retry);
4257			break;
4258		default:
4259			WARN_ON_ONCE(1);
4260			error = -EINVAL;
4261		}
4262	} while (error == 0 && retry);
4263
4264	return error;
4265}
4266
4267/* Returns the size of fundamental allocation unit for a file, in bytes. */
4268unsigned int
4269xfs_inode_alloc_unitsize(
4270	struct xfs_inode	*ip)
4271{
4272	unsigned int		blocks = 1;
4273
4274	if (XFS_IS_REALTIME_INODE(ip))
4275		blocks = ip->i_mount->m_sb.sb_rextsize;
4276
4277	return XFS_FSB_TO_B(ip->i_mount, blocks);
4278}
4279