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