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