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