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