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