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