1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2006 Silicon Graphics, Inc.
4  * All Rights Reserved.
5  */
6 #include <linux/iversion.h>
7 
8 #include "xfs.h"
9 #include "xfs_fs.h"
10 #include "xfs_shared.h"
11 #include "xfs_format.h"
12 #include "xfs_log_format.h"
13 #include "xfs_trans_resv.h"
14 #include "xfs_mount.h"
15 #include "xfs_defer.h"
16 #include "xfs_inode.h"
17 #include "xfs_dir2.h"
18 #include "xfs_attr.h"
19 #include "xfs_bit.h"
20 #include "xfs_trans_space.h"
21 #include "xfs_trans.h"
22 #include "xfs_buf_item.h"
23 #include "xfs_inode_item.h"
24 #include "xfs_iunlink_item.h"
25 #include "xfs_ialloc.h"
26 #include "xfs_bmap.h"
27 #include "xfs_bmap_util.h"
28 #include "xfs_errortag.h"
29 #include "xfs_error.h"
30 #include "xfs_quota.h"
31 #include "xfs_filestream.h"
32 #include "xfs_trace.h"
33 #include "xfs_icache.h"
34 #include "xfs_symlink.h"
35 #include "xfs_trans_priv.h"
36 #include "xfs_log.h"
37 #include "xfs_bmap_btree.h"
38 #include "xfs_reflink.h"
39 #include "xfs_ag.h"
40 #include "xfs_log_priv.h"
41 #include "xfs_health.h"
42 #include "xfs_pnfs.h"
43 #include "xfs_parent.h"
44 #include "xfs_xattr.h"
45 #include "xfs_inode_util.h"
46 
47 struct kmem_cache *xfs_inode_cache;
48 
49 /*
50  * These two are wrapper routines around the xfs_ilock() routine used to
51  * centralize some grungy code.  They are used in places that wish to lock the
52  * inode solely for reading the extents.  The reason these places can't just
53  * call xfs_ilock(ip, XFS_ILOCK_SHARED) is that the inode lock also guards to
54  * bringing in of the extents from disk for a file in b-tree format.  If the
55  * inode is in b-tree format, then we need to lock the inode exclusively until
56  * the extents are read in.  Locking it exclusively all the time would limit
57  * our parallelism unnecessarily, though.  What we do instead is check to see
58  * if the extents have been read in yet, and only lock the inode exclusively
59  * if they have not.
60  *
61  * The functions return a value which should be given to the corresponding
62  * xfs_iunlock() call.
63  */
64 uint
xfs_ilock_data_map_shared(struct xfs_inode * ip)65 xfs_ilock_data_map_shared(
66 	struct xfs_inode	*ip)
67 {
68 	uint			lock_mode = XFS_ILOCK_SHARED;
69 
70 	if (xfs_need_iread_extents(&ip->i_df))
71 		lock_mode = XFS_ILOCK_EXCL;
72 	xfs_ilock(ip, lock_mode);
73 	return lock_mode;
74 }
75 
76 uint
xfs_ilock_attr_map_shared(struct xfs_inode * ip)77 xfs_ilock_attr_map_shared(
78 	struct xfs_inode	*ip)
79 {
80 	uint			lock_mode = XFS_ILOCK_SHARED;
81 
82 	if (xfs_inode_has_attr_fork(ip) && xfs_need_iread_extents(&ip->i_af))
83 		lock_mode = XFS_ILOCK_EXCL;
84 	xfs_ilock(ip, lock_mode);
85 	return lock_mode;
86 }
87 
88 /*
89  * You can't set both SHARED and EXCL for the same lock,
90  * and only XFS_IOLOCK_SHARED, XFS_IOLOCK_EXCL, XFS_MMAPLOCK_SHARED,
91  * XFS_MMAPLOCK_EXCL, XFS_ILOCK_SHARED, XFS_ILOCK_EXCL are valid values
92  * to set in lock_flags.
93  */
94 static inline void
xfs_lock_flags_assert(uint lock_flags)95 xfs_lock_flags_assert(
96 	uint		lock_flags)
97 {
98 	ASSERT((lock_flags & (XFS_IOLOCK_SHARED | XFS_IOLOCK_EXCL)) !=
99 		(XFS_IOLOCK_SHARED | XFS_IOLOCK_EXCL));
100 	ASSERT((lock_flags & (XFS_MMAPLOCK_SHARED | XFS_MMAPLOCK_EXCL)) !=
101 		(XFS_MMAPLOCK_SHARED | XFS_MMAPLOCK_EXCL));
102 	ASSERT((lock_flags & (XFS_ILOCK_SHARED | XFS_ILOCK_EXCL)) !=
103 		(XFS_ILOCK_SHARED | XFS_ILOCK_EXCL));
104 	ASSERT((lock_flags & ~(XFS_LOCK_MASK | XFS_LOCK_SUBCLASS_MASK)) == 0);
105 	ASSERT(lock_flags != 0);
106 }
107 
108 /*
109  * In addition to i_rwsem in the VFS inode, the xfs inode contains 2
110  * multi-reader locks: invalidate_lock and the i_lock.  This routine allows
111  * various combinations of the locks to be obtained.
112  *
113  * The 3 locks should always be ordered so that the IO lock is obtained first,
114  * the mmap lock second and the ilock last in order to prevent deadlock.
115  *
116  * Basic locking order:
117  *
118  * i_rwsem -> invalidate_lock -> page_lock -> i_ilock
119  *
120  * mmap_lock locking order:
121  *
122  * i_rwsem -> page lock -> mmap_lock
123  * mmap_lock -> invalidate_lock -> page_lock
124  *
125  * The difference in mmap_lock locking order mean that we cannot hold the
126  * invalidate_lock over syscall based read(2)/write(2) based IO. These IO paths
127  * can fault in pages during copy in/out (for buffered IO) or require the
128  * mmap_lock in get_user_pages() to map the user pages into the kernel address
129  * space for direct IO. Similarly the i_rwsem cannot be taken inside a page
130  * fault because page faults already hold the mmap_lock.
131  *
132  * Hence to serialise fully against both syscall and mmap based IO, we need to
133  * take both the i_rwsem and the invalidate_lock. These locks should *only* be
134  * both taken in places where we need to invalidate the page cache in a race
135  * free manner (e.g. truncate, hole punch and other extent manipulation
136  * functions).
137  */
138 void
xfs_ilock(xfs_inode_t * ip,uint lock_flags)139 xfs_ilock(
140 	xfs_inode_t		*ip,
141 	uint			lock_flags)
142 {
143 	trace_xfs_ilock(ip, lock_flags, _RET_IP_);
144 
145 	xfs_lock_flags_assert(lock_flags);
146 
147 	if (lock_flags & XFS_IOLOCK_EXCL) {
148 		down_write_nested(&VFS_I(ip)->i_rwsem,
149 				  XFS_IOLOCK_DEP(lock_flags));
150 	} else if (lock_flags & XFS_IOLOCK_SHARED) {
151 		down_read_nested(&VFS_I(ip)->i_rwsem,
152 				 XFS_IOLOCK_DEP(lock_flags));
153 	}
154 
155 	if (lock_flags & XFS_MMAPLOCK_EXCL) {
156 		down_write_nested(&VFS_I(ip)->i_mapping->invalidate_lock,
157 				  XFS_MMAPLOCK_DEP(lock_flags));
158 	} else if (lock_flags & XFS_MMAPLOCK_SHARED) {
159 		down_read_nested(&VFS_I(ip)->i_mapping->invalidate_lock,
160 				 XFS_MMAPLOCK_DEP(lock_flags));
161 	}
162 
163 	if (lock_flags & XFS_ILOCK_EXCL)
164 		down_write_nested(&ip->i_lock, XFS_ILOCK_DEP(lock_flags));
165 	else if (lock_flags & XFS_ILOCK_SHARED)
166 		down_read_nested(&ip->i_lock, XFS_ILOCK_DEP(lock_flags));
167 }
168 
169 /*
170  * This is just like xfs_ilock(), except that the caller
171  * is guaranteed not to sleep.  It returns 1 if it gets
172  * the requested locks and 0 otherwise.  If the IO lock is
173  * obtained but the inode lock cannot be, then the IO lock
174  * is dropped before returning.
175  *
176  * ip -- the inode being locked
177  * lock_flags -- this parameter indicates the inode's locks to be
178  *       to be locked.  See the comment for xfs_ilock() for a list
179  *	 of valid values.
180  */
181 int
xfs_ilock_nowait(xfs_inode_t * ip,uint lock_flags)182 xfs_ilock_nowait(
183 	xfs_inode_t		*ip,
184 	uint			lock_flags)
185 {
186 	trace_xfs_ilock_nowait(ip, lock_flags, _RET_IP_);
187 
188 	xfs_lock_flags_assert(lock_flags);
189 
190 	if (lock_flags & XFS_IOLOCK_EXCL) {
191 		if (!down_write_trylock(&VFS_I(ip)->i_rwsem))
192 			goto out;
193 	} else if (lock_flags & XFS_IOLOCK_SHARED) {
194 		if (!down_read_trylock(&VFS_I(ip)->i_rwsem))
195 			goto out;
196 	}
197 
198 	if (lock_flags & XFS_MMAPLOCK_EXCL) {
199 		if (!down_write_trylock(&VFS_I(ip)->i_mapping->invalidate_lock))
200 			goto out_undo_iolock;
201 	} else if (lock_flags & XFS_MMAPLOCK_SHARED) {
202 		if (!down_read_trylock(&VFS_I(ip)->i_mapping->invalidate_lock))
203 			goto out_undo_iolock;
204 	}
205 
206 	if (lock_flags & XFS_ILOCK_EXCL) {
207 		if (!down_write_trylock(&ip->i_lock))
208 			goto out_undo_mmaplock;
209 	} else if (lock_flags & XFS_ILOCK_SHARED) {
210 		if (!down_read_trylock(&ip->i_lock))
211 			goto out_undo_mmaplock;
212 	}
213 	return 1;
214 
215 out_undo_mmaplock:
216 	if (lock_flags & XFS_MMAPLOCK_EXCL)
217 		up_write(&VFS_I(ip)->i_mapping->invalidate_lock);
218 	else if (lock_flags & XFS_MMAPLOCK_SHARED)
219 		up_read(&VFS_I(ip)->i_mapping->invalidate_lock);
220 out_undo_iolock:
221 	if (lock_flags & XFS_IOLOCK_EXCL)
222 		up_write(&VFS_I(ip)->i_rwsem);
223 	else if (lock_flags & XFS_IOLOCK_SHARED)
224 		up_read(&VFS_I(ip)->i_rwsem);
225 out:
226 	return 0;
227 }
228 
229 /*
230  * xfs_iunlock() is used to drop the inode locks acquired with
231  * xfs_ilock() and xfs_ilock_nowait().  The caller must pass
232  * in the flags given to xfs_ilock() or xfs_ilock_nowait() so
233  * that we know which locks to drop.
234  *
235  * ip -- the inode being unlocked
236  * lock_flags -- this parameter indicates the inode's locks to be
237  *       to be unlocked.  See the comment for xfs_ilock() for a list
238  *	 of valid values for this parameter.
239  *
240  */
241 void
xfs_iunlock(xfs_inode_t * ip,uint lock_flags)242 xfs_iunlock(
243 	xfs_inode_t		*ip,
244 	uint			lock_flags)
245 {
246 	xfs_lock_flags_assert(lock_flags);
247 
248 	if (lock_flags & XFS_IOLOCK_EXCL)
249 		up_write(&VFS_I(ip)->i_rwsem);
250 	else if (lock_flags & XFS_IOLOCK_SHARED)
251 		up_read(&VFS_I(ip)->i_rwsem);
252 
253 	if (lock_flags & XFS_MMAPLOCK_EXCL)
254 		up_write(&VFS_I(ip)->i_mapping->invalidate_lock);
255 	else if (lock_flags & XFS_MMAPLOCK_SHARED)
256 		up_read(&VFS_I(ip)->i_mapping->invalidate_lock);
257 
258 	if (lock_flags & XFS_ILOCK_EXCL)
259 		up_write(&ip->i_lock);
260 	else if (lock_flags & XFS_ILOCK_SHARED)
261 		up_read(&ip->i_lock);
262 
263 	trace_xfs_iunlock(ip, lock_flags, _RET_IP_);
264 }
265 
266 /*
267  * give up write locks.  the i/o lock cannot be held nested
268  * if it is being demoted.
269  */
270 void
xfs_ilock_demote(xfs_inode_t * ip,uint lock_flags)271 xfs_ilock_demote(
272 	xfs_inode_t		*ip,
273 	uint			lock_flags)
274 {
275 	ASSERT(lock_flags & (XFS_IOLOCK_EXCL|XFS_MMAPLOCK_EXCL|XFS_ILOCK_EXCL));
276 	ASSERT((lock_flags &
277 		~(XFS_IOLOCK_EXCL|XFS_MMAPLOCK_EXCL|XFS_ILOCK_EXCL)) == 0);
278 
279 	if (lock_flags & XFS_ILOCK_EXCL)
280 		downgrade_write(&ip->i_lock);
281 	if (lock_flags & XFS_MMAPLOCK_EXCL)
282 		downgrade_write(&VFS_I(ip)->i_mapping->invalidate_lock);
283 	if (lock_flags & XFS_IOLOCK_EXCL)
284 		downgrade_write(&VFS_I(ip)->i_rwsem);
285 
286 	trace_xfs_ilock_demote(ip, lock_flags, _RET_IP_);
287 }
288 
289 void
xfs_assert_ilocked(struct xfs_inode * ip,uint lock_flags)290 xfs_assert_ilocked(
291 	struct xfs_inode	*ip,
292 	uint			lock_flags)
293 {
294 	/*
295 	 * Sometimes we assert the ILOCK is held exclusively, but we're in
296 	 * a workqueue, so lockdep doesn't know we're the owner.
297 	 */
298 	if (lock_flags & XFS_ILOCK_SHARED)
299 		rwsem_assert_held(&ip->i_lock);
300 	else if (lock_flags & XFS_ILOCK_EXCL)
301 		rwsem_assert_held_write_nolockdep(&ip->i_lock);
302 
303 	if (lock_flags & XFS_MMAPLOCK_SHARED)
304 		rwsem_assert_held(&VFS_I(ip)->i_mapping->invalidate_lock);
305 	else if (lock_flags & XFS_MMAPLOCK_EXCL)
306 		rwsem_assert_held_write(&VFS_I(ip)->i_mapping->invalidate_lock);
307 
308 	if (lock_flags & XFS_IOLOCK_SHARED)
309 		rwsem_assert_held(&VFS_I(ip)->i_rwsem);
310 	else if (lock_flags & XFS_IOLOCK_EXCL)
311 		rwsem_assert_held_write(&VFS_I(ip)->i_rwsem);
312 }
313 
314 /*
315  * xfs_lockdep_subclass_ok() is only used in an ASSERT, so is only called when
316  * DEBUG or XFS_WARN is set. And MAX_LOCKDEP_SUBCLASSES is then only defined
317  * when CONFIG_LOCKDEP is set. Hence the complex define below to avoid build
318  * errors and warnings.
319  */
320 #if (defined(DEBUG) || defined(XFS_WARN)) && defined(CONFIG_LOCKDEP)
321 static bool
xfs_lockdep_subclass_ok(int subclass)322 xfs_lockdep_subclass_ok(
323 	int subclass)
324 {
325 	return subclass < MAX_LOCKDEP_SUBCLASSES;
326 }
327 #else
328 #define xfs_lockdep_subclass_ok(subclass)	(true)
329 #endif
330 
331 /*
332  * Bump the subclass so xfs_lock_inodes() acquires each lock with a different
333  * value. This can be called for any type of inode lock combination, including
334  * parent locking. Care must be taken to ensure we don't overrun the subclass
335  * storage fields in the class mask we build.
336  */
337 static inline uint
xfs_lock_inumorder(uint lock_mode,uint subclass)338 xfs_lock_inumorder(
339 	uint	lock_mode,
340 	uint	subclass)
341 {
342 	uint	class = 0;
343 
344 	ASSERT(!(lock_mode & (XFS_ILOCK_PARENT | XFS_ILOCK_RTBITMAP |
345 			      XFS_ILOCK_RTSUM)));
346 	ASSERT(xfs_lockdep_subclass_ok(subclass));
347 
348 	if (lock_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL)) {
349 		ASSERT(subclass <= XFS_IOLOCK_MAX_SUBCLASS);
350 		class += subclass << XFS_IOLOCK_SHIFT;
351 	}
352 
353 	if (lock_mode & (XFS_MMAPLOCK_SHARED|XFS_MMAPLOCK_EXCL)) {
354 		ASSERT(subclass <= XFS_MMAPLOCK_MAX_SUBCLASS);
355 		class += subclass << XFS_MMAPLOCK_SHIFT;
356 	}
357 
358 	if (lock_mode & (XFS_ILOCK_SHARED|XFS_ILOCK_EXCL)) {
359 		ASSERT(subclass <= XFS_ILOCK_MAX_SUBCLASS);
360 		class += subclass << XFS_ILOCK_SHIFT;
361 	}
362 
363 	return (lock_mode & ~XFS_LOCK_SUBCLASS_MASK) | class;
364 }
365 
366 /*
367  * The following routine will lock n inodes in exclusive mode.  We assume the
368  * caller calls us with the inodes in i_ino order.
369  *
370  * We need to detect deadlock where an inode that we lock is in the AIL and we
371  * start waiting for another inode that is locked by a thread in a long running
372  * transaction (such as truncate). This can result in deadlock since the long
373  * running trans might need to wait for the inode we just locked in order to
374  * push the tail and free space in the log.
375  *
376  * xfs_lock_inodes() can only be used to lock one type of lock at a time -
377  * the iolock, the mmaplock or the ilock, but not more than one at a time. If we
378  * lock more than one at a time, lockdep will report false positives saying we
379  * have violated locking orders.
380  */
381 void
xfs_lock_inodes(struct xfs_inode ** ips,int inodes,uint lock_mode)382 xfs_lock_inodes(
383 	struct xfs_inode	**ips,
384 	int			inodes,
385 	uint			lock_mode)
386 {
387 	int			attempts = 0;
388 	uint			i;
389 	int			j;
390 	bool			try_lock;
391 	struct xfs_log_item	*lp;
392 
393 	/*
394 	 * Currently supports between 2 and 5 inodes with exclusive locking.  We
395 	 * support an arbitrary depth of locking here, but absolute limits on
396 	 * inodes depend on the type of locking and the limits placed by
397 	 * lockdep annotations in xfs_lock_inumorder.  These are all checked by
398 	 * the asserts.
399 	 */
400 	ASSERT(ips && inodes >= 2 && inodes <= 5);
401 	ASSERT(lock_mode & (XFS_IOLOCK_EXCL | XFS_MMAPLOCK_EXCL |
402 			    XFS_ILOCK_EXCL));
403 	ASSERT(!(lock_mode & (XFS_IOLOCK_SHARED | XFS_MMAPLOCK_SHARED |
404 			      XFS_ILOCK_SHARED)));
405 	ASSERT(!(lock_mode & XFS_MMAPLOCK_EXCL) ||
406 		inodes <= XFS_MMAPLOCK_MAX_SUBCLASS + 1);
407 	ASSERT(!(lock_mode & XFS_ILOCK_EXCL) ||
408 		inodes <= XFS_ILOCK_MAX_SUBCLASS + 1);
409 
410 	if (lock_mode & XFS_IOLOCK_EXCL) {
411 		ASSERT(!(lock_mode & (XFS_MMAPLOCK_EXCL | XFS_ILOCK_EXCL)));
412 	} else if (lock_mode & XFS_MMAPLOCK_EXCL)
413 		ASSERT(!(lock_mode & XFS_ILOCK_EXCL));
414 
415 again:
416 	try_lock = false;
417 	i = 0;
418 	for (; i < inodes; i++) {
419 		ASSERT(ips[i]);
420 
421 		if (i && (ips[i] == ips[i - 1]))	/* Already locked */
422 			continue;
423 
424 		/*
425 		 * If try_lock is not set yet, make sure all locked inodes are
426 		 * not in the AIL.  If any are, set try_lock to be used later.
427 		 */
428 		if (!try_lock) {
429 			for (j = (i - 1); j >= 0 && !try_lock; j--) {
430 				lp = &ips[j]->i_itemp->ili_item;
431 				if (lp && test_bit(XFS_LI_IN_AIL, &lp->li_flags))
432 					try_lock = true;
433 			}
434 		}
435 
436 		/*
437 		 * If any of the previous locks we have locked is in the AIL,
438 		 * we must TRY to get the second and subsequent locks. If
439 		 * we can't get any, we must release all we have
440 		 * and try again.
441 		 */
442 		if (!try_lock) {
443 			xfs_ilock(ips[i], xfs_lock_inumorder(lock_mode, i));
444 			continue;
445 		}
446 
447 		/* try_lock means we have an inode locked that is in the AIL. */
448 		ASSERT(i != 0);
449 		if (xfs_ilock_nowait(ips[i], xfs_lock_inumorder(lock_mode, i)))
450 			continue;
451 
452 		/*
453 		 * Unlock all previous guys and try again.  xfs_iunlock will try
454 		 * to push the tail if the inode is in the AIL.
455 		 */
456 		attempts++;
457 		for (j = i - 1; j >= 0; j--) {
458 			/*
459 			 * Check to see if we've already unlocked this one.  Not
460 			 * the first one going back, and the inode ptr is the
461 			 * same.
462 			 */
463 			if (j != (i - 1) && ips[j] == ips[j + 1])
464 				continue;
465 
466 			xfs_iunlock(ips[j], lock_mode);
467 		}
468 
469 		if ((attempts % 5) == 0) {
470 			delay(1); /* Don't just spin the CPU */
471 		}
472 		goto again;
473 	}
474 }
475 
476 /*
477  * xfs_lock_two_inodes() can only be used to lock ilock. The iolock and
478  * mmaplock must be double-locked separately since we use i_rwsem and
479  * invalidate_lock for that. We now support taking one lock EXCL and the
480  * other SHARED.
481  */
482 void
xfs_lock_two_inodes(struct xfs_inode * ip0,uint ip0_mode,struct xfs_inode * ip1,uint ip1_mode)483 xfs_lock_two_inodes(
484 	struct xfs_inode	*ip0,
485 	uint			ip0_mode,
486 	struct xfs_inode	*ip1,
487 	uint			ip1_mode)
488 {
489 	int			attempts = 0;
490 	struct xfs_log_item	*lp;
491 
492 	ASSERT(hweight32(ip0_mode) == 1);
493 	ASSERT(hweight32(ip1_mode) == 1);
494 	ASSERT(!(ip0_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL)));
495 	ASSERT(!(ip1_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL)));
496 	ASSERT(!(ip0_mode & (XFS_MMAPLOCK_SHARED|XFS_MMAPLOCK_EXCL)));
497 	ASSERT(!(ip1_mode & (XFS_MMAPLOCK_SHARED|XFS_MMAPLOCK_EXCL)));
498 	ASSERT(ip0->i_ino != ip1->i_ino);
499 
500 	if (ip0->i_ino > ip1->i_ino) {
501 		swap(ip0, ip1);
502 		swap(ip0_mode, ip1_mode);
503 	}
504 
505  again:
506 	xfs_ilock(ip0, xfs_lock_inumorder(ip0_mode, 0));
507 
508 	/*
509 	 * If the first lock we have locked is in the AIL, we must TRY to get
510 	 * the second lock. If we can't get it, we must release the first one
511 	 * and try again.
512 	 */
513 	lp = &ip0->i_itemp->ili_item;
514 	if (lp && test_bit(XFS_LI_IN_AIL, &lp->li_flags)) {
515 		if (!xfs_ilock_nowait(ip1, xfs_lock_inumorder(ip1_mode, 1))) {
516 			xfs_iunlock(ip0, ip0_mode);
517 			if ((++attempts % 5) == 0)
518 				delay(1); /* Don't just spin the CPU */
519 			goto again;
520 		}
521 	} else {
522 		xfs_ilock(ip1, xfs_lock_inumorder(ip1_mode, 1));
523 	}
524 }
525 
526 /*
527  * Lookups up an inode from "name". If ci_name is not NULL, then a CI match
528  * is allowed, otherwise it has to be an exact match. If a CI match is found,
529  * ci_name->name will point to a the actual name (caller must free) or
530  * will be set to NULL if an exact match is found.
531  */
532 int
xfs_lookup(struct xfs_inode * dp,const struct xfs_name * name,struct xfs_inode ** ipp,struct xfs_name * ci_name)533 xfs_lookup(
534 	struct xfs_inode	*dp,
535 	const struct xfs_name	*name,
536 	struct xfs_inode	**ipp,
537 	struct xfs_name		*ci_name)
538 {
539 	xfs_ino_t		inum;
540 	int			error;
541 
542 	trace_xfs_lookup(dp, name);
543 
544 	if (xfs_is_shutdown(dp->i_mount))
545 		return -EIO;
546 	if (xfs_ifork_zapped(dp, XFS_DATA_FORK))
547 		return -EIO;
548 
549 	error = xfs_dir_lookup(NULL, dp, name, &inum, ci_name);
550 	if (error)
551 		goto out_unlock;
552 
553 	error = xfs_iget(dp->i_mount, NULL, inum, 0, 0, ipp);
554 	if (error)
555 		goto out_free_name;
556 
557 	return 0;
558 
559 out_free_name:
560 	if (ci_name)
561 		kfree(ci_name->name);
562 out_unlock:
563 	*ipp = NULL;
564 	return error;
565 }
566 
567 /*
568  * Initialise a newly allocated inode and return the in-core inode to the
569  * caller locked exclusively.
570  *
571  * Caller is responsible for unlocking the inode manually upon return
572  */
573 int
xfs_icreate(struct xfs_trans * tp,xfs_ino_t ino,const struct xfs_icreate_args * args,struct xfs_inode ** ipp)574 xfs_icreate(
575 	struct xfs_trans	*tp,
576 	xfs_ino_t		ino,
577 	const struct xfs_icreate_args *args,
578 	struct xfs_inode	**ipp)
579 {
580 	struct xfs_mount	*mp = tp->t_mountp;
581 	struct xfs_inode	*ip = NULL;
582 	int			error;
583 
584 	/*
585 	 * Get the in-core inode with the lock held exclusively to prevent
586 	 * others from looking at until we're done.
587 	 */
588 	error = xfs_iget(mp, tp, ino, XFS_IGET_CREATE, XFS_ILOCK_EXCL, &ip);
589 	if (error)
590 		return error;
591 
592 	ASSERT(ip != NULL);
593 	xfs_trans_ijoin(tp, ip, 0);
594 	xfs_inode_init(tp, args, ip);
595 
596 	/* now that we have an i_mode we can setup the inode structure */
597 	xfs_setup_inode(ip);
598 
599 	*ipp = ip;
600 	return 0;
601 }
602 
603 /* Return dquots for the ids that will be assigned to a new file. */
604 int
xfs_icreate_dqalloc(const struct xfs_icreate_args * args,struct xfs_dquot ** udqpp,struct xfs_dquot ** gdqpp,struct xfs_dquot ** pdqpp)605 xfs_icreate_dqalloc(
606 	const struct xfs_icreate_args	*args,
607 	struct xfs_dquot		**udqpp,
608 	struct xfs_dquot		**gdqpp,
609 	struct xfs_dquot		**pdqpp)
610 {
611 	struct inode			*dir = VFS_I(args->pip);
612 	kuid_t				uid = GLOBAL_ROOT_UID;
613 	kgid_t				gid = GLOBAL_ROOT_GID;
614 	prid_t				prid = 0;
615 	unsigned int			flags = XFS_QMOPT_QUOTALL;
616 
617 	if (args->idmap) {
618 		/*
619 		 * The uid/gid computation code must match what the VFS uses to
620 		 * assign i_[ug]id.  INHERIT adjusts the gid computation for
621 		 * setgid/grpid systems.
622 		 */
623 		uid = mapped_fsuid(args->idmap, i_user_ns(dir));
624 		gid = mapped_fsgid(args->idmap, i_user_ns(dir));
625 		prid = xfs_get_initial_prid(args->pip);
626 		flags |= XFS_QMOPT_INHERIT;
627 	}
628 
629 	*udqpp = *gdqpp = *pdqpp = NULL;
630 
631 	return xfs_qm_vop_dqalloc(args->pip, uid, gid, prid, flags, udqpp,
632 			gdqpp, pdqpp);
633 }
634 
635 int
xfs_create(const struct xfs_icreate_args * args,struct xfs_name * name,struct xfs_inode ** ipp)636 xfs_create(
637 	const struct xfs_icreate_args *args,
638 	struct xfs_name		*name,
639 	struct xfs_inode	**ipp)
640 {
641 	struct xfs_inode	*dp = args->pip;
642 	struct xfs_dir_update	du = {
643 		.dp		= dp,
644 		.name		= name,
645 	};
646 	struct xfs_mount	*mp = dp->i_mount;
647 	struct xfs_trans	*tp = NULL;
648 	struct xfs_dquot	*udqp;
649 	struct xfs_dquot	*gdqp;
650 	struct xfs_dquot	*pdqp;
651 	struct xfs_trans_res	*tres;
652 	xfs_ino_t		ino;
653 	bool			unlock_dp_on_error = false;
654 	bool			is_dir = S_ISDIR(args->mode);
655 	uint			resblks;
656 	int			error;
657 
658 	trace_xfs_create(dp, name);
659 
660 	if (xfs_is_shutdown(mp))
661 		return -EIO;
662 	if (xfs_ifork_zapped(dp, XFS_DATA_FORK))
663 		return -EIO;
664 
665 	/* Make sure that we have allocated dquot(s) on disk. */
666 	error = xfs_icreate_dqalloc(args, &udqp, &gdqp, &pdqp);
667 	if (error)
668 		return error;
669 
670 	if (is_dir) {
671 		resblks = xfs_mkdir_space_res(mp, name->len);
672 		tres = &M_RES(mp)->tr_mkdir;
673 	} else {
674 		resblks = xfs_create_space_res(mp, name->len);
675 		tres = &M_RES(mp)->tr_create;
676 	}
677 
678 	error = xfs_parent_start(mp, &du.ppargs);
679 	if (error)
680 		goto out_release_dquots;
681 
682 	/*
683 	 * Initially assume that the file does not exist and
684 	 * reserve the resources for that case.  If that is not
685 	 * the case we'll drop the one we have and get a more
686 	 * appropriate transaction later.
687 	 */
688 	error = xfs_trans_alloc_icreate(mp, tres, udqp, gdqp, pdqp, resblks,
689 			&tp);
690 	if (error == -ENOSPC) {
691 		/* flush outstanding delalloc blocks and retry */
692 		xfs_flush_inodes(mp);
693 		error = xfs_trans_alloc_icreate(mp, tres, udqp, gdqp, pdqp,
694 				resblks, &tp);
695 	}
696 	if (error)
697 		goto out_parent;
698 
699 	xfs_ilock(dp, XFS_ILOCK_EXCL | XFS_ILOCK_PARENT);
700 	unlock_dp_on_error = true;
701 
702 	/*
703 	 * A newly created regular or special file just has one directory
704 	 * entry pointing to them, but a directory also the "." entry
705 	 * pointing to itself.
706 	 */
707 	error = xfs_dialloc(&tp, args, &ino);
708 	if (!error)
709 		error = xfs_icreate(tp, ino, args, &du.ip);
710 	if (error)
711 		goto out_trans_cancel;
712 
713 	/*
714 	 * Now we join the directory inode to the transaction.  We do not do it
715 	 * earlier because xfs_dialloc might commit the previous transaction
716 	 * (and release all the locks).  An error from here on will result in
717 	 * the transaction cancel unlocking dp so don't do it explicitly in the
718 	 * error path.
719 	 */
720 	xfs_trans_ijoin(tp, dp, 0);
721 
722 	error = xfs_dir_create_child(tp, resblks, &du);
723 	if (error)
724 		goto out_trans_cancel;
725 
726 	/*
727 	 * If this is a synchronous mount, make sure that the
728 	 * create transaction goes to disk before returning to
729 	 * the user.
730 	 */
731 	if (xfs_has_wsync(mp) || xfs_has_dirsync(mp))
732 		xfs_trans_set_sync(tp);
733 
734 	/*
735 	 * Attach the dquot(s) to the inodes and modify them incore.
736 	 * These ids of the inode couldn't have changed since the new
737 	 * inode has been locked ever since it was created.
738 	 */
739 	xfs_qm_vop_create_dqattach(tp, du.ip, udqp, gdqp, pdqp);
740 
741 	error = xfs_trans_commit(tp);
742 	if (error)
743 		goto out_release_inode;
744 
745 	xfs_qm_dqrele(udqp);
746 	xfs_qm_dqrele(gdqp);
747 	xfs_qm_dqrele(pdqp);
748 
749 	*ipp = du.ip;
750 	xfs_iunlock(du.ip, XFS_ILOCK_EXCL);
751 	xfs_iunlock(dp, XFS_ILOCK_EXCL);
752 	xfs_parent_finish(mp, du.ppargs);
753 	return 0;
754 
755  out_trans_cancel:
756 	xfs_trans_cancel(tp);
757  out_release_inode:
758 	/*
759 	 * Wait until after the current transaction is aborted to finish the
760 	 * setup of the inode and release the inode.  This prevents recursive
761 	 * transactions and deadlocks from xfs_inactive.
762 	 */
763 	if (du.ip) {
764 		xfs_iunlock(du.ip, XFS_ILOCK_EXCL);
765 		xfs_finish_inode_setup(du.ip);
766 		xfs_irele(du.ip);
767 	}
768  out_parent:
769 	xfs_parent_finish(mp, du.ppargs);
770  out_release_dquots:
771 	xfs_qm_dqrele(udqp);
772 	xfs_qm_dqrele(gdqp);
773 	xfs_qm_dqrele(pdqp);
774 
775 	if (unlock_dp_on_error)
776 		xfs_iunlock(dp, XFS_ILOCK_EXCL);
777 	return error;
778 }
779 
780 int
xfs_create_tmpfile(const struct xfs_icreate_args * args,struct xfs_inode ** ipp)781 xfs_create_tmpfile(
782 	const struct xfs_icreate_args *args,
783 	struct xfs_inode	**ipp)
784 {
785 	struct xfs_inode	*dp = args->pip;
786 	struct xfs_mount	*mp = dp->i_mount;
787 	struct xfs_inode	*ip = NULL;
788 	struct xfs_trans	*tp = NULL;
789 	struct xfs_dquot	*udqp;
790 	struct xfs_dquot	*gdqp;
791 	struct xfs_dquot	*pdqp;
792 	struct xfs_trans_res	*tres;
793 	xfs_ino_t		ino;
794 	uint			resblks;
795 	int			error;
796 
797 	ASSERT(args->flags & XFS_ICREATE_TMPFILE);
798 
799 	if (xfs_is_shutdown(mp))
800 		return -EIO;
801 
802 	/* Make sure that we have allocated dquot(s) on disk. */
803 	error = xfs_icreate_dqalloc(args, &udqp, &gdqp, &pdqp);
804 	if (error)
805 		return error;
806 
807 	resblks = XFS_IALLOC_SPACE_RES(mp);
808 	tres = &M_RES(mp)->tr_create_tmpfile;
809 
810 	error = xfs_trans_alloc_icreate(mp, tres, udqp, gdqp, pdqp, resblks,
811 			&tp);
812 	if (error)
813 		goto out_release_dquots;
814 
815 	error = xfs_dialloc(&tp, args, &ino);
816 	if (!error)
817 		error = xfs_icreate(tp, ino, args, &ip);
818 	if (error)
819 		goto out_trans_cancel;
820 
821 	if (xfs_has_wsync(mp))
822 		xfs_trans_set_sync(tp);
823 
824 	/*
825 	 * Attach the dquot(s) to the inodes and modify them incore.
826 	 * These ids of the inode couldn't have changed since the new
827 	 * inode has been locked ever since it was created.
828 	 */
829 	xfs_qm_vop_create_dqattach(tp, ip, udqp, gdqp, pdqp);
830 
831 	error = xfs_iunlink(tp, ip);
832 	if (error)
833 		goto out_trans_cancel;
834 
835 	error = xfs_trans_commit(tp);
836 	if (error)
837 		goto out_release_inode;
838 
839 	xfs_qm_dqrele(udqp);
840 	xfs_qm_dqrele(gdqp);
841 	xfs_qm_dqrele(pdqp);
842 
843 	*ipp = ip;
844 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
845 	return 0;
846 
847  out_trans_cancel:
848 	xfs_trans_cancel(tp);
849  out_release_inode:
850 	/*
851 	 * Wait until after the current transaction is aborted to finish the
852 	 * setup of the inode and release the inode.  This prevents recursive
853 	 * transactions and deadlocks from xfs_inactive.
854 	 */
855 	if (ip) {
856 		xfs_iunlock(ip, XFS_ILOCK_EXCL);
857 		xfs_finish_inode_setup(ip);
858 		xfs_irele(ip);
859 	}
860  out_release_dquots:
861 	xfs_qm_dqrele(udqp);
862 	xfs_qm_dqrele(gdqp);
863 	xfs_qm_dqrele(pdqp);
864 
865 	return error;
866 }
867 
868 int
xfs_link(struct xfs_inode * tdp,struct xfs_inode * sip,struct xfs_name * target_name)869 xfs_link(
870 	struct xfs_inode	*tdp,
871 	struct xfs_inode	*sip,
872 	struct xfs_name		*target_name)
873 {
874 	struct xfs_dir_update	du = {
875 		.dp		= tdp,
876 		.name		= target_name,
877 		.ip		= sip,
878 	};
879 	struct xfs_mount	*mp = tdp->i_mount;
880 	struct xfs_trans	*tp;
881 	int			error, nospace_error = 0;
882 	int			resblks;
883 
884 	trace_xfs_link(tdp, target_name);
885 
886 	ASSERT(!S_ISDIR(VFS_I(sip)->i_mode));
887 
888 	if (xfs_is_shutdown(mp))
889 		return -EIO;
890 	if (xfs_ifork_zapped(tdp, XFS_DATA_FORK))
891 		return -EIO;
892 
893 	error = xfs_qm_dqattach(sip);
894 	if (error)
895 		goto std_return;
896 
897 	error = xfs_qm_dqattach(tdp);
898 	if (error)
899 		goto std_return;
900 
901 	error = xfs_parent_start(mp, &du.ppargs);
902 	if (error)
903 		goto std_return;
904 
905 	resblks = xfs_link_space_res(mp, target_name->len);
906 	error = xfs_trans_alloc_dir(tdp, &M_RES(mp)->tr_link, sip, &resblks,
907 			&tp, &nospace_error);
908 	if (error)
909 		goto out_parent;
910 
911 	/*
912 	 * We don't allow reservationless or quotaless hardlinking when parent
913 	 * pointers are enabled because we can't back out if the xattrs must
914 	 * grow.
915 	 */
916 	if (du.ppargs && nospace_error) {
917 		error = nospace_error;
918 		goto error_return;
919 	}
920 
921 	/*
922 	 * If we are using project inheritance, we only allow hard link
923 	 * creation in our tree when the project IDs are the same; else
924 	 * the tree quota mechanism could be circumvented.
925 	 */
926 	if (unlikely((tdp->i_diflags & XFS_DIFLAG_PROJINHERIT) &&
927 		     tdp->i_projid != sip->i_projid)) {
928 		/*
929 		 * Project quota setup skips special files which can
930 		 * leave inodes in a PROJINHERIT directory without a
931 		 * project ID set. We need to allow links to be made
932 		 * to these "project-less" inodes because userspace
933 		 * expects them to succeed after project ID setup,
934 		 * but everything else should be rejected.
935 		 */
936 		if (!special_file(VFS_I(sip)->i_mode) ||
937 		    sip->i_projid != 0) {
938 			error = -EXDEV;
939 			goto error_return;
940 		}
941 	}
942 
943 	error = xfs_dir_add_child(tp, resblks, &du);
944 	if (error)
945 		goto error_return;
946 
947 	/*
948 	 * If this is a synchronous mount, make sure that the
949 	 * link transaction goes to disk before returning to
950 	 * the user.
951 	 */
952 	if (xfs_has_wsync(mp) || xfs_has_dirsync(mp))
953 		xfs_trans_set_sync(tp);
954 
955 	error = xfs_trans_commit(tp);
956 	xfs_iunlock(tdp, XFS_ILOCK_EXCL);
957 	xfs_iunlock(sip, XFS_ILOCK_EXCL);
958 	xfs_parent_finish(mp, du.ppargs);
959 	return error;
960 
961  error_return:
962 	xfs_trans_cancel(tp);
963 	xfs_iunlock(tdp, XFS_ILOCK_EXCL);
964 	xfs_iunlock(sip, XFS_ILOCK_EXCL);
965  out_parent:
966 	xfs_parent_finish(mp, du.ppargs);
967  std_return:
968 	if (error == -ENOSPC && nospace_error)
969 		error = nospace_error;
970 	return error;
971 }
972 
973 /* Clear the reflink flag and the cowblocks tag if possible. */
974 static void
xfs_itruncate_clear_reflink_flags(struct xfs_inode * ip)975 xfs_itruncate_clear_reflink_flags(
976 	struct xfs_inode	*ip)
977 {
978 	struct xfs_ifork	*dfork;
979 	struct xfs_ifork	*cfork;
980 
981 	if (!xfs_is_reflink_inode(ip))
982 		return;
983 	dfork = xfs_ifork_ptr(ip, XFS_DATA_FORK);
984 	cfork = xfs_ifork_ptr(ip, XFS_COW_FORK);
985 	if (dfork->if_bytes == 0 && cfork->if_bytes == 0)
986 		ip->i_diflags2 &= ~XFS_DIFLAG2_REFLINK;
987 	if (cfork->if_bytes == 0)
988 		xfs_inode_clear_cowblocks_tag(ip);
989 }
990 
991 /*
992  * Free up the underlying blocks past new_size.  The new size must be smaller
993  * than the current size.  This routine can be used both for the attribute and
994  * data fork, and does not modify the inode size, which is left to the caller.
995  *
996  * The transaction passed to this routine must have made a permanent log
997  * reservation of at least XFS_ITRUNCATE_LOG_RES.  This routine may commit the
998  * given transaction and start new ones, so make sure everything involved in
999  * the transaction is tidy before calling here.  Some transaction will be
1000  * returned to the caller to be committed.  The incoming transaction must
1001  * already include the inode, and both inode locks must be held exclusively.
1002  * The inode must also be "held" within the transaction.  On return the inode
1003  * will be "held" within the returned transaction.  This routine does NOT
1004  * require any disk space to be reserved for it within the transaction.
1005  *
1006  * If we get an error, we must return with the inode locked and linked into the
1007  * current transaction. This keeps things simple for the higher level code,
1008  * because it always knows that the inode is locked and held in the transaction
1009  * that returns to it whether errors occur or not.  We don't mark the inode
1010  * dirty on error so that transactions can be easily aborted if possible.
1011  */
1012 int
xfs_itruncate_extents_flags(struct xfs_trans ** tpp,struct xfs_inode * ip,int whichfork,xfs_fsize_t new_size,int flags)1013 xfs_itruncate_extents_flags(
1014 	struct xfs_trans	**tpp,
1015 	struct xfs_inode	*ip,
1016 	int			whichfork,
1017 	xfs_fsize_t		new_size,
1018 	int			flags)
1019 {
1020 	struct xfs_mount	*mp = ip->i_mount;
1021 	struct xfs_trans	*tp = *tpp;
1022 	xfs_fileoff_t		first_unmap_block;
1023 	int			error = 0;
1024 
1025 	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL);
1026 	if (atomic_read(&VFS_I(ip)->i_count))
1027 		xfs_assert_ilocked(ip, XFS_IOLOCK_EXCL);
1028 	ASSERT(new_size <= XFS_ISIZE(ip));
1029 	ASSERT(tp->t_flags & XFS_TRANS_PERM_LOG_RES);
1030 	ASSERT(ip->i_itemp != NULL);
1031 	ASSERT(ip->i_itemp->ili_lock_flags == 0);
1032 	ASSERT(!XFS_NOT_DQATTACHED(mp, ip));
1033 
1034 	trace_xfs_itruncate_extents_start(ip, new_size);
1035 
1036 	flags |= xfs_bmapi_aflag(whichfork);
1037 
1038 	/*
1039 	 * Since it is possible for space to become allocated beyond
1040 	 * the end of the file (in a crash where the space is allocated
1041 	 * but the inode size is not yet updated), simply remove any
1042 	 * blocks which show up between the new EOF and the maximum
1043 	 * possible file size.
1044 	 *
1045 	 * We have to free all the blocks to the bmbt maximum offset, even if
1046 	 * the page cache can't scale that far.
1047 	 */
1048 	first_unmap_block = XFS_B_TO_FSB(mp, (xfs_ufsize_t)new_size);
1049 	if (!xfs_verify_fileoff(mp, first_unmap_block)) {
1050 		WARN_ON_ONCE(first_unmap_block > XFS_MAX_FILEOFF);
1051 		return 0;
1052 	}
1053 
1054 	error = xfs_bunmapi_range(&tp, ip, flags, first_unmap_block,
1055 			XFS_MAX_FILEOFF);
1056 	if (error)
1057 		goto out;
1058 
1059 	if (whichfork == XFS_DATA_FORK) {
1060 		/* Remove all pending CoW reservations. */
1061 		error = xfs_reflink_cancel_cow_blocks(ip, &tp,
1062 				first_unmap_block, XFS_MAX_FILEOFF, true);
1063 		if (error)
1064 			goto out;
1065 
1066 		xfs_itruncate_clear_reflink_flags(ip);
1067 	}
1068 
1069 	/*
1070 	 * Always re-log the inode so that our permanent transaction can keep
1071 	 * on rolling it forward in the log.
1072 	 */
1073 	xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1074 
1075 	trace_xfs_itruncate_extents_end(ip, new_size);
1076 
1077 out:
1078 	*tpp = tp;
1079 	return error;
1080 }
1081 
1082 /*
1083  * Mark all the buffers attached to this directory stale.  In theory we should
1084  * never be freeing a directory with any blocks at all, but this covers the
1085  * case where we've recovered a directory swap with a "temporary" directory
1086  * created by online repair and now need to dump it.
1087  */
1088 STATIC void
xfs_inactive_dir(struct xfs_inode * dp)1089 xfs_inactive_dir(
1090 	struct xfs_inode	*dp)
1091 {
1092 	struct xfs_iext_cursor	icur;
1093 	struct xfs_bmbt_irec	got;
1094 	struct xfs_mount	*mp = dp->i_mount;
1095 	struct xfs_da_geometry	*geo = mp->m_dir_geo;
1096 	struct xfs_ifork	*ifp = xfs_ifork_ptr(dp, XFS_DATA_FORK);
1097 	xfs_fileoff_t		off;
1098 
1099 	/*
1100 	 * Invalidate each directory block.  All directory blocks are of
1101 	 * fsbcount length and alignment, so we only need to walk those same
1102 	 * offsets.  We hold the only reference to this inode, so we must wait
1103 	 * for the buffer locks.
1104 	 */
1105 	for_each_xfs_iext(ifp, &icur, &got) {
1106 		for (off = round_up(got.br_startoff, geo->fsbcount);
1107 		     off < got.br_startoff + got.br_blockcount;
1108 		     off += geo->fsbcount) {
1109 			struct xfs_buf	*bp = NULL;
1110 			xfs_fsblock_t	fsbno;
1111 			int		error;
1112 
1113 			fsbno = (off - got.br_startoff) + got.br_startblock;
1114 			error = xfs_buf_incore(mp->m_ddev_targp,
1115 					XFS_FSB_TO_DADDR(mp, fsbno),
1116 					XFS_FSB_TO_BB(mp, geo->fsbcount),
1117 					XBF_LIVESCAN, &bp);
1118 			if (error)
1119 				continue;
1120 
1121 			xfs_buf_stale(bp);
1122 			xfs_buf_relse(bp);
1123 		}
1124 	}
1125 }
1126 
1127 /*
1128  * xfs_inactive_truncate
1129  *
1130  * Called to perform a truncate when an inode becomes unlinked.
1131  */
1132 STATIC int
xfs_inactive_truncate(struct xfs_inode * ip)1133 xfs_inactive_truncate(
1134 	struct xfs_inode *ip)
1135 {
1136 	struct xfs_mount	*mp = ip->i_mount;
1137 	struct xfs_trans	*tp;
1138 	int			error;
1139 
1140 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_itruncate, 0, 0, 0, &tp);
1141 	if (error) {
1142 		ASSERT(xfs_is_shutdown(mp));
1143 		return error;
1144 	}
1145 	xfs_ilock(ip, XFS_ILOCK_EXCL);
1146 	xfs_trans_ijoin(tp, ip, 0);
1147 
1148 	/*
1149 	 * Log the inode size first to prevent stale data exposure in the event
1150 	 * of a system crash before the truncate completes. See the related
1151 	 * comment in xfs_vn_setattr_size() for details.
1152 	 */
1153 	ip->i_disk_size = 0;
1154 	xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1155 
1156 	error = xfs_itruncate_extents(&tp, ip, XFS_DATA_FORK, 0);
1157 	if (error)
1158 		goto error_trans_cancel;
1159 
1160 	ASSERT(ip->i_df.if_nextents == 0);
1161 
1162 	error = xfs_trans_commit(tp);
1163 	if (error)
1164 		goto error_unlock;
1165 
1166 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1167 	return 0;
1168 
1169 error_trans_cancel:
1170 	xfs_trans_cancel(tp);
1171 error_unlock:
1172 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1173 	return error;
1174 }
1175 
1176 /*
1177  * xfs_inactive_ifree()
1178  *
1179  * Perform the inode free when an inode is unlinked.
1180  */
1181 STATIC int
xfs_inactive_ifree(struct xfs_inode * ip)1182 xfs_inactive_ifree(
1183 	struct xfs_inode *ip)
1184 {
1185 	struct xfs_mount	*mp = ip->i_mount;
1186 	struct xfs_trans	*tp;
1187 	int			error;
1188 
1189 	/*
1190 	 * We try to use a per-AG reservation for any block needed by the finobt
1191 	 * tree, but as the finobt feature predates the per-AG reservation
1192 	 * support a degraded file system might not have enough space for the
1193 	 * reservation at mount time.  In that case try to dip into the reserved
1194 	 * pool and pray.
1195 	 *
1196 	 * Send a warning if the reservation does happen to fail, as the inode
1197 	 * now remains allocated and sits on the unlinked list until the fs is
1198 	 * repaired.
1199 	 */
1200 	if (unlikely(mp->m_finobt_nores)) {
1201 		error = xfs_trans_alloc(mp, &M_RES(mp)->tr_ifree,
1202 				XFS_IFREE_SPACE_RES(mp), 0, XFS_TRANS_RESERVE,
1203 				&tp);
1204 	} else {
1205 		error = xfs_trans_alloc(mp, &M_RES(mp)->tr_ifree, 0, 0, 0, &tp);
1206 	}
1207 	if (error) {
1208 		if (error == -ENOSPC) {
1209 			xfs_warn_ratelimited(mp,
1210 			"Failed to remove inode(s) from unlinked list. "
1211 			"Please free space, unmount and run xfs_repair.");
1212 		} else {
1213 			ASSERT(xfs_is_shutdown(mp));
1214 		}
1215 		return error;
1216 	}
1217 
1218 	/*
1219 	 * We do not hold the inode locked across the entire rolling transaction
1220 	 * here. We only need to hold it for the first transaction that
1221 	 * xfs_ifree() builds, which may mark the inode XFS_ISTALE if the
1222 	 * underlying cluster buffer is freed. Relogging an XFS_ISTALE inode
1223 	 * here breaks the relationship between cluster buffer invalidation and
1224 	 * stale inode invalidation on cluster buffer item journal commit
1225 	 * completion, and can result in leaving dirty stale inodes hanging
1226 	 * around in memory.
1227 	 *
1228 	 * We have no need for serialising this inode operation against other
1229 	 * operations - we freed the inode and hence reallocation is required
1230 	 * and that will serialise on reallocating the space the deferops need
1231 	 * to free. Hence we can unlock the inode on the first commit of
1232 	 * the transaction rather than roll it right through the deferops. This
1233 	 * avoids relogging the XFS_ISTALE inode.
1234 	 *
1235 	 * We check that xfs_ifree() hasn't grown an internal transaction roll
1236 	 * by asserting that the inode is still locked when it returns.
1237 	 */
1238 	xfs_ilock(ip, XFS_ILOCK_EXCL);
1239 	xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
1240 
1241 	error = xfs_ifree(tp, ip);
1242 	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL);
1243 	if (error) {
1244 		/*
1245 		 * If we fail to free the inode, shut down.  The cancel
1246 		 * might do that, we need to make sure.  Otherwise the
1247 		 * inode might be lost for a long time or forever.
1248 		 */
1249 		if (!xfs_is_shutdown(mp)) {
1250 			xfs_notice(mp, "%s: xfs_ifree returned error %d",
1251 				__func__, error);
1252 			xfs_force_shutdown(mp, SHUTDOWN_META_IO_ERROR);
1253 		}
1254 		xfs_trans_cancel(tp);
1255 		return error;
1256 	}
1257 
1258 	/*
1259 	 * Credit the quota account(s). The inode is gone.
1260 	 */
1261 	xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_ICOUNT, -1);
1262 
1263 	return xfs_trans_commit(tp);
1264 }
1265 
1266 /*
1267  * Returns true if we need to update the on-disk metadata before we can free
1268  * the memory used by this inode.  Updates include freeing post-eof
1269  * preallocations; freeing COW staging extents; and marking the inode free in
1270  * the inobt if it is on the unlinked list.
1271  */
1272 bool
xfs_inode_needs_inactive(struct xfs_inode * ip)1273 xfs_inode_needs_inactive(
1274 	struct xfs_inode	*ip)
1275 {
1276 	struct xfs_mount	*mp = ip->i_mount;
1277 	struct xfs_ifork	*cow_ifp = xfs_ifork_ptr(ip, XFS_COW_FORK);
1278 
1279 	/*
1280 	 * If the inode is already free, then there can be nothing
1281 	 * to clean up here.
1282 	 */
1283 	if (VFS_I(ip)->i_mode == 0)
1284 		return false;
1285 
1286 	/*
1287 	 * If this is a read-only mount, don't do this (would generate I/O)
1288 	 * unless we're in log recovery and cleaning the iunlinked list.
1289 	 */
1290 	if (xfs_is_readonly(mp) && !xlog_recovery_needed(mp->m_log))
1291 		return false;
1292 
1293 	/* If the log isn't running, push inodes straight to reclaim. */
1294 	if (xfs_is_shutdown(mp) || xfs_has_norecovery(mp))
1295 		return false;
1296 
1297 	/* Metadata inodes require explicit resource cleanup. */
1298 	if (xfs_is_metadata_inode(ip))
1299 		return false;
1300 
1301 	/* Want to clean out the cow blocks if there are any. */
1302 	if (cow_ifp && cow_ifp->if_bytes > 0)
1303 		return true;
1304 
1305 	/* Unlinked files must be freed. */
1306 	if (VFS_I(ip)->i_nlink == 0)
1307 		return true;
1308 
1309 	/*
1310 	 * This file isn't being freed, so check if there are post-eof blocks
1311 	 * to free.
1312 	 *
1313 	 * Note: don't bother with iolock here since lockdep complains about
1314 	 * acquiring it in reclaim context. We have the only reference to the
1315 	 * inode at this point anyways.
1316 	 */
1317 	return xfs_can_free_eofblocks(ip);
1318 }
1319 
1320 /*
1321  * Save health status somewhere, if we're dumping an inode with uncorrected
1322  * errors and online repair isn't running.
1323  */
1324 static inline void
xfs_inactive_health(struct xfs_inode * ip)1325 xfs_inactive_health(
1326 	struct xfs_inode	*ip)
1327 {
1328 	struct xfs_mount	*mp = ip->i_mount;
1329 	struct xfs_perag	*pag;
1330 	unsigned int		sick;
1331 	unsigned int		checked;
1332 
1333 	xfs_inode_measure_sickness(ip, &sick, &checked);
1334 	if (!sick)
1335 		return;
1336 
1337 	trace_xfs_inode_unfixed_corruption(ip, sick);
1338 
1339 	if (sick & XFS_SICK_INO_FORGET)
1340 		return;
1341 
1342 	pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, ip->i_ino));
1343 	if (!pag) {
1344 		/* There had better still be a perag structure! */
1345 		ASSERT(0);
1346 		return;
1347 	}
1348 
1349 	xfs_ag_mark_sick(pag, XFS_SICK_AG_INODES);
1350 	xfs_perag_put(pag);
1351 }
1352 
1353 /*
1354  * xfs_inactive
1355  *
1356  * This is called when the vnode reference count for the vnode
1357  * goes to zero.  If the file has been unlinked, then it must
1358  * now be truncated.  Also, we clear all of the read-ahead state
1359  * kept for the inode here since the file is now closed.
1360  */
1361 int
xfs_inactive(xfs_inode_t * ip)1362 xfs_inactive(
1363 	xfs_inode_t	*ip)
1364 {
1365 	struct xfs_mount	*mp;
1366 	int			error = 0;
1367 	int			truncate = 0;
1368 
1369 	/*
1370 	 * If the inode is already free, then there can be nothing
1371 	 * to clean up here.
1372 	 */
1373 	if (VFS_I(ip)->i_mode == 0) {
1374 		ASSERT(ip->i_df.if_broot_bytes == 0);
1375 		goto out;
1376 	}
1377 
1378 	mp = ip->i_mount;
1379 	ASSERT(!xfs_iflags_test(ip, XFS_IRECOVERY));
1380 
1381 	xfs_inactive_health(ip);
1382 
1383 	/*
1384 	 * If this is a read-only mount, don't do this (would generate I/O)
1385 	 * unless we're in log recovery and cleaning the iunlinked list.
1386 	 */
1387 	if (xfs_is_readonly(mp) && !xlog_recovery_needed(mp->m_log))
1388 		goto out;
1389 
1390 	/* Metadata inodes require explicit resource cleanup. */
1391 	if (xfs_is_metadata_inode(ip))
1392 		goto out;
1393 
1394 	/* Try to clean out the cow blocks if there are any. */
1395 	if (xfs_inode_has_cow_data(ip)) {
1396 		error = xfs_reflink_cancel_cow_range(ip, 0, NULLFILEOFF, true);
1397 		if (error)
1398 			goto out;
1399 	}
1400 
1401 	if (VFS_I(ip)->i_nlink != 0) {
1402 		/*
1403 		 * Note: don't bother with iolock here since lockdep complains
1404 		 * about acquiring it in reclaim context. We have the only
1405 		 * reference to the inode at this point anyways.
1406 		 */
1407 		if (xfs_can_free_eofblocks(ip))
1408 			error = xfs_free_eofblocks(ip);
1409 
1410 		goto out;
1411 	}
1412 
1413 	if (S_ISREG(VFS_I(ip)->i_mode) &&
1414 	    (ip->i_disk_size != 0 || XFS_ISIZE(ip) != 0 ||
1415 	     xfs_inode_has_filedata(ip)))
1416 		truncate = 1;
1417 
1418 	if (xfs_iflags_test(ip, XFS_IQUOTAUNCHECKED)) {
1419 		/*
1420 		 * If this inode is being inactivated during a quotacheck and
1421 		 * has not yet been scanned by quotacheck, we /must/ remove
1422 		 * the dquots from the inode before inactivation changes the
1423 		 * block and inode counts.  Most probably this is a result of
1424 		 * reloading the incore iunlinked list to purge unrecovered
1425 		 * unlinked inodes.
1426 		 */
1427 		xfs_qm_dqdetach(ip);
1428 	} else {
1429 		error = xfs_qm_dqattach(ip);
1430 		if (error)
1431 			goto out;
1432 	}
1433 
1434 	if (S_ISDIR(VFS_I(ip)->i_mode) && ip->i_df.if_nextents > 0) {
1435 		xfs_inactive_dir(ip);
1436 		truncate = 1;
1437 	}
1438 
1439 	if (S_ISLNK(VFS_I(ip)->i_mode))
1440 		error = xfs_inactive_symlink(ip);
1441 	else if (truncate)
1442 		error = xfs_inactive_truncate(ip);
1443 	if (error)
1444 		goto out;
1445 
1446 	/*
1447 	 * If there are attributes associated with the file then blow them away
1448 	 * now.  The code calls a routine that recursively deconstructs the
1449 	 * attribute fork. If also blows away the in-core attribute fork.
1450 	 */
1451 	if (xfs_inode_has_attr_fork(ip)) {
1452 		error = xfs_attr_inactive(ip);
1453 		if (error)
1454 			goto out;
1455 	}
1456 
1457 	ASSERT(ip->i_forkoff == 0);
1458 
1459 	/*
1460 	 * Free the inode.
1461 	 */
1462 	error = xfs_inactive_ifree(ip);
1463 
1464 out:
1465 	/*
1466 	 * We're done making metadata updates for this inode, so we can release
1467 	 * the attached dquots.
1468 	 */
1469 	xfs_qm_dqdetach(ip);
1470 	return error;
1471 }
1472 
1473 /*
1474  * Find an inode on the unlinked list. This does not take references to the
1475  * inode as we have existence guarantees by holding the AGI buffer lock and that
1476  * only unlinked, referenced inodes can be on the unlinked inode list.  If we
1477  * don't find the inode in cache, then let the caller handle the situation.
1478  */
1479 struct xfs_inode *
xfs_iunlink_lookup(struct xfs_perag * pag,xfs_agino_t agino)1480 xfs_iunlink_lookup(
1481 	struct xfs_perag	*pag,
1482 	xfs_agino_t		agino)
1483 {
1484 	struct xfs_inode	*ip;
1485 
1486 	rcu_read_lock();
1487 	ip = radix_tree_lookup(&pag->pag_ici_root, agino);
1488 	if (!ip) {
1489 		/* Caller can handle inode not being in memory. */
1490 		rcu_read_unlock();
1491 		return NULL;
1492 	}
1493 
1494 	/*
1495 	 * Inode in RCU freeing limbo should not happen.  Warn about this and
1496 	 * let the caller handle the failure.
1497 	 */
1498 	if (WARN_ON_ONCE(!ip->i_ino)) {
1499 		rcu_read_unlock();
1500 		return NULL;
1501 	}
1502 	ASSERT(!xfs_iflags_test(ip, XFS_IRECLAIMABLE | XFS_IRECLAIM));
1503 	rcu_read_unlock();
1504 	return ip;
1505 }
1506 
1507 /*
1508  * Load the inode @next_agino into the cache and set its prev_unlinked pointer
1509  * to @prev_agino.  Caller must hold the AGI to synchronize with other changes
1510  * to the unlinked list.
1511  */
1512 int
xfs_iunlink_reload_next(struct xfs_trans * tp,struct xfs_buf * agibp,xfs_agino_t prev_agino,xfs_agino_t next_agino)1513 xfs_iunlink_reload_next(
1514 	struct xfs_trans	*tp,
1515 	struct xfs_buf		*agibp,
1516 	xfs_agino_t		prev_agino,
1517 	xfs_agino_t		next_agino)
1518 {
1519 	struct xfs_perag	*pag = agibp->b_pag;
1520 	struct xfs_mount	*mp = pag->pag_mount;
1521 	struct xfs_inode	*next_ip = NULL;
1522 	xfs_ino_t		ino;
1523 	int			error;
1524 
1525 	ASSERT(next_agino != NULLAGINO);
1526 
1527 #ifdef DEBUG
1528 	rcu_read_lock();
1529 	next_ip = radix_tree_lookup(&pag->pag_ici_root, next_agino);
1530 	ASSERT(next_ip == NULL);
1531 	rcu_read_unlock();
1532 #endif
1533 
1534 	xfs_info_ratelimited(mp,
1535  "Found unrecovered unlinked inode 0x%x in AG 0x%x.  Initiating recovery.",
1536 			next_agino, pag->pag_agno);
1537 
1538 	/*
1539 	 * Use an untrusted lookup just to be cautious in case the AGI has been
1540 	 * corrupted and now points at a free inode.  That shouldn't happen,
1541 	 * but we'd rather shut down now since we're already running in a weird
1542 	 * situation.
1543 	 */
1544 	ino = XFS_AGINO_TO_INO(mp, pag->pag_agno, next_agino);
1545 	error = xfs_iget(mp, tp, ino, XFS_IGET_UNTRUSTED, 0, &next_ip);
1546 	if (error) {
1547 		xfs_ag_mark_sick(pag, XFS_SICK_AG_AGI);
1548 		return error;
1549 	}
1550 
1551 	/* If this is not an unlinked inode, something is very wrong. */
1552 	if (VFS_I(next_ip)->i_nlink != 0) {
1553 		xfs_ag_mark_sick(pag, XFS_SICK_AG_AGI);
1554 		error = -EFSCORRUPTED;
1555 		goto rele;
1556 	}
1557 
1558 	next_ip->i_prev_unlinked = prev_agino;
1559 	trace_xfs_iunlink_reload_next(next_ip);
1560 rele:
1561 	ASSERT(!(VFS_I(next_ip)->i_state & I_DONTCACHE));
1562 	if (xfs_is_quotacheck_running(mp) && next_ip)
1563 		xfs_iflags_set(next_ip, XFS_IQUOTAUNCHECKED);
1564 	xfs_irele(next_ip);
1565 	return error;
1566 }
1567 
1568 /*
1569  * Look up the inode number specified and if it is not already marked XFS_ISTALE
1570  * mark it stale. We should only find clean inodes in this lookup that aren't
1571  * already stale.
1572  */
1573 static void
xfs_ifree_mark_inode_stale(struct xfs_perag * pag,struct xfs_inode * free_ip,xfs_ino_t inum)1574 xfs_ifree_mark_inode_stale(
1575 	struct xfs_perag	*pag,
1576 	struct xfs_inode	*free_ip,
1577 	xfs_ino_t		inum)
1578 {
1579 	struct xfs_mount	*mp = pag->pag_mount;
1580 	struct xfs_inode_log_item *iip;
1581 	struct xfs_inode	*ip;
1582 
1583 retry:
1584 	rcu_read_lock();
1585 	ip = radix_tree_lookup(&pag->pag_ici_root, XFS_INO_TO_AGINO(mp, inum));
1586 
1587 	/* Inode not in memory, nothing to do */
1588 	if (!ip) {
1589 		rcu_read_unlock();
1590 		return;
1591 	}
1592 
1593 	/*
1594 	 * because this is an RCU protected lookup, we could find a recently
1595 	 * freed or even reallocated inode during the lookup. We need to check
1596 	 * under the i_flags_lock for a valid inode here. Skip it if it is not
1597 	 * valid, the wrong inode or stale.
1598 	 */
1599 	spin_lock(&ip->i_flags_lock);
1600 	if (ip->i_ino != inum || __xfs_iflags_test(ip, XFS_ISTALE))
1601 		goto out_iflags_unlock;
1602 
1603 	/*
1604 	 * Don't try to lock/unlock the current inode, but we _cannot_ skip the
1605 	 * other inodes that we did not find in the list attached to the buffer
1606 	 * and are not already marked stale. If we can't lock it, back off and
1607 	 * retry.
1608 	 */
1609 	if (ip != free_ip) {
1610 		if (!xfs_ilock_nowait(ip, XFS_ILOCK_EXCL)) {
1611 			spin_unlock(&ip->i_flags_lock);
1612 			rcu_read_unlock();
1613 			delay(1);
1614 			goto retry;
1615 		}
1616 	}
1617 	ip->i_flags |= XFS_ISTALE;
1618 
1619 	/*
1620 	 * If the inode is flushing, it is already attached to the buffer.  All
1621 	 * we needed to do here is mark the inode stale so buffer IO completion
1622 	 * will remove it from the AIL.
1623 	 */
1624 	iip = ip->i_itemp;
1625 	if (__xfs_iflags_test(ip, XFS_IFLUSHING)) {
1626 		ASSERT(!list_empty(&iip->ili_item.li_bio_list));
1627 		ASSERT(iip->ili_last_fields);
1628 		goto out_iunlock;
1629 	}
1630 
1631 	/*
1632 	 * Inodes not attached to the buffer can be released immediately.
1633 	 * Everything else has to go through xfs_iflush_abort() on journal
1634 	 * commit as the flock synchronises removal of the inode from the
1635 	 * cluster buffer against inode reclaim.
1636 	 */
1637 	if (!iip || list_empty(&iip->ili_item.li_bio_list))
1638 		goto out_iunlock;
1639 
1640 	__xfs_iflags_set(ip, XFS_IFLUSHING);
1641 	spin_unlock(&ip->i_flags_lock);
1642 	rcu_read_unlock();
1643 
1644 	/* we have a dirty inode in memory that has not yet been flushed. */
1645 	spin_lock(&iip->ili_lock);
1646 	iip->ili_last_fields = iip->ili_fields;
1647 	iip->ili_fields = 0;
1648 	iip->ili_fsync_fields = 0;
1649 	spin_unlock(&iip->ili_lock);
1650 	ASSERT(iip->ili_last_fields);
1651 
1652 	if (ip != free_ip)
1653 		xfs_iunlock(ip, XFS_ILOCK_EXCL);
1654 	return;
1655 
1656 out_iunlock:
1657 	if (ip != free_ip)
1658 		xfs_iunlock(ip, XFS_ILOCK_EXCL);
1659 out_iflags_unlock:
1660 	spin_unlock(&ip->i_flags_lock);
1661 	rcu_read_unlock();
1662 }
1663 
1664 /*
1665  * A big issue when freeing the inode cluster is that we _cannot_ skip any
1666  * inodes that are in memory - they all must be marked stale and attached to
1667  * the cluster buffer.
1668  */
1669 static int
xfs_ifree_cluster(struct xfs_trans * tp,struct xfs_perag * pag,struct xfs_inode * free_ip,struct xfs_icluster * xic)1670 xfs_ifree_cluster(
1671 	struct xfs_trans	*tp,
1672 	struct xfs_perag	*pag,
1673 	struct xfs_inode	*free_ip,
1674 	struct xfs_icluster	*xic)
1675 {
1676 	struct xfs_mount	*mp = free_ip->i_mount;
1677 	struct xfs_ino_geometry	*igeo = M_IGEO(mp);
1678 	struct xfs_buf		*bp;
1679 	xfs_daddr_t		blkno;
1680 	xfs_ino_t		inum = xic->first_ino;
1681 	int			nbufs;
1682 	int			i, j;
1683 	int			ioffset;
1684 	int			error;
1685 
1686 	nbufs = igeo->ialloc_blks / igeo->blocks_per_cluster;
1687 
1688 	for (j = 0; j < nbufs; j++, inum += igeo->inodes_per_cluster) {
1689 		/*
1690 		 * The allocation bitmap tells us which inodes of the chunk were
1691 		 * physically allocated. Skip the cluster if an inode falls into
1692 		 * a sparse region.
1693 		 */
1694 		ioffset = inum - xic->first_ino;
1695 		if ((xic->alloc & XFS_INOBT_MASK(ioffset)) == 0) {
1696 			ASSERT(ioffset % igeo->inodes_per_cluster == 0);
1697 			continue;
1698 		}
1699 
1700 		blkno = XFS_AGB_TO_DADDR(mp, XFS_INO_TO_AGNO(mp, inum),
1701 					 XFS_INO_TO_AGBNO(mp, inum));
1702 
1703 		/*
1704 		 * We obtain and lock the backing buffer first in the process
1705 		 * here to ensure dirty inodes attached to the buffer remain in
1706 		 * the flushing state while we mark them stale.
1707 		 *
1708 		 * If we scan the in-memory inodes first, then buffer IO can
1709 		 * complete before we get a lock on it, and hence we may fail
1710 		 * to mark all the active inodes on the buffer stale.
1711 		 */
1712 		error = xfs_trans_get_buf(tp, mp->m_ddev_targp, blkno,
1713 				mp->m_bsize * igeo->blocks_per_cluster,
1714 				XBF_UNMAPPED, &bp);
1715 		if (error)
1716 			return error;
1717 
1718 		/*
1719 		 * This buffer may not have been correctly initialised as we
1720 		 * didn't read it from disk. That's not important because we are
1721 		 * only using to mark the buffer as stale in the log, and to
1722 		 * attach stale cached inodes on it.
1723 		 *
1724 		 * For the inode that triggered the cluster freeing, this
1725 		 * attachment may occur in xfs_inode_item_precommit() after we
1726 		 * have marked this buffer stale.  If this buffer was not in
1727 		 * memory before xfs_ifree_cluster() started, it will not be
1728 		 * marked XBF_DONE and this will cause problems later in
1729 		 * xfs_inode_item_precommit() when we trip over a (stale, !done)
1730 		 * buffer to attached to the transaction.
1731 		 *
1732 		 * Hence we have to mark the buffer as XFS_DONE here. This is
1733 		 * safe because we are also marking the buffer as XBF_STALE and
1734 		 * XFS_BLI_STALE. That means it will never be dispatched for
1735 		 * IO and it won't be unlocked until the cluster freeing has
1736 		 * been committed to the journal and the buffer unpinned. If it
1737 		 * is written, we want to know about it, and we want it to
1738 		 * fail. We can acheive this by adding a write verifier to the
1739 		 * buffer.
1740 		 */
1741 		bp->b_flags |= XBF_DONE;
1742 		bp->b_ops = &xfs_inode_buf_ops;
1743 
1744 		/*
1745 		 * Now we need to set all the cached clean inodes as XFS_ISTALE,
1746 		 * too. This requires lookups, and will skip inodes that we've
1747 		 * already marked XFS_ISTALE.
1748 		 */
1749 		for (i = 0; i < igeo->inodes_per_cluster; i++)
1750 			xfs_ifree_mark_inode_stale(pag, free_ip, inum + i);
1751 
1752 		xfs_trans_stale_inode_buf(tp, bp);
1753 		xfs_trans_binval(tp, bp);
1754 	}
1755 	return 0;
1756 }
1757 
1758 /*
1759  * This is called to return an inode to the inode free list.  The inode should
1760  * already be truncated to 0 length and have no pages associated with it.  This
1761  * routine also assumes that the inode is already a part of the transaction.
1762  *
1763  * The on-disk copy of the inode will have been added to the list of unlinked
1764  * inodes in the AGI. We need to remove the inode from that list atomically with
1765  * respect to freeing it here.
1766  */
1767 int
xfs_ifree(struct xfs_trans * tp,struct xfs_inode * ip)1768 xfs_ifree(
1769 	struct xfs_trans	*tp,
1770 	struct xfs_inode	*ip)
1771 {
1772 	struct xfs_mount	*mp = ip->i_mount;
1773 	struct xfs_perag	*pag;
1774 	struct xfs_icluster	xic = { 0 };
1775 	struct xfs_inode_log_item *iip = ip->i_itemp;
1776 	int			error;
1777 
1778 	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL);
1779 	ASSERT(VFS_I(ip)->i_nlink == 0);
1780 	ASSERT(ip->i_df.if_nextents == 0);
1781 	ASSERT(ip->i_disk_size == 0 || !S_ISREG(VFS_I(ip)->i_mode));
1782 	ASSERT(ip->i_nblocks == 0);
1783 
1784 	pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, ip->i_ino));
1785 
1786 	error = xfs_inode_uninit(tp, pag, ip, &xic);
1787 	if (error)
1788 		goto out;
1789 
1790 	if (xfs_iflags_test(ip, XFS_IPRESERVE_DM_FIELDS))
1791 		xfs_iflags_clear(ip, XFS_IPRESERVE_DM_FIELDS);
1792 
1793 	/* Don't attempt to replay owner changes for a deleted inode */
1794 	spin_lock(&iip->ili_lock);
1795 	iip->ili_fields &= ~(XFS_ILOG_AOWNER | XFS_ILOG_DOWNER);
1796 	spin_unlock(&iip->ili_lock);
1797 
1798 	if (xic.deleted)
1799 		error = xfs_ifree_cluster(tp, pag, ip, &xic);
1800 out:
1801 	xfs_perag_put(pag);
1802 	return error;
1803 }
1804 
1805 /*
1806  * This is called to unpin an inode.  The caller must have the inode locked
1807  * in at least shared mode so that the buffer cannot be subsequently pinned
1808  * once someone is waiting for it to be unpinned.
1809  */
1810 static void
xfs_iunpin(struct xfs_inode * ip)1811 xfs_iunpin(
1812 	struct xfs_inode	*ip)
1813 {
1814 	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL | XFS_ILOCK_SHARED);
1815 
1816 	trace_xfs_inode_unpin_nowait(ip, _RET_IP_);
1817 
1818 	/* Give the log a push to start the unpinning I/O */
1819 	xfs_log_force_seq(ip->i_mount, ip->i_itemp->ili_commit_seq, 0, NULL);
1820 
1821 }
1822 
1823 static void
__xfs_iunpin_wait(struct xfs_inode * ip)1824 __xfs_iunpin_wait(
1825 	struct xfs_inode	*ip)
1826 {
1827 	wait_queue_head_t *wq = bit_waitqueue(&ip->i_flags, __XFS_IPINNED_BIT);
1828 	DEFINE_WAIT_BIT(wait, &ip->i_flags, __XFS_IPINNED_BIT);
1829 
1830 	xfs_iunpin(ip);
1831 
1832 	do {
1833 		prepare_to_wait(wq, &wait.wq_entry, TASK_UNINTERRUPTIBLE);
1834 		if (xfs_ipincount(ip))
1835 			io_schedule();
1836 	} while (xfs_ipincount(ip));
1837 	finish_wait(wq, &wait.wq_entry);
1838 }
1839 
1840 void
xfs_iunpin_wait(struct xfs_inode * ip)1841 xfs_iunpin_wait(
1842 	struct xfs_inode	*ip)
1843 {
1844 	if (xfs_ipincount(ip))
1845 		__xfs_iunpin_wait(ip);
1846 }
1847 
1848 /*
1849  * Removing an inode from the namespace involves removing the directory entry
1850  * and dropping the link count on the inode. Removing the directory entry can
1851  * result in locking an AGF (directory blocks were freed) and removing a link
1852  * count can result in placing the inode on an unlinked list which results in
1853  * locking an AGI.
1854  *
1855  * The big problem here is that we have an ordering constraint on AGF and AGI
1856  * locking - inode allocation locks the AGI, then can allocate a new extent for
1857  * new inodes, locking the AGF after the AGI. Similarly, freeing the inode
1858  * removes the inode from the unlinked list, requiring that we lock the AGI
1859  * first, and then freeing the inode can result in an inode chunk being freed
1860  * and hence freeing disk space requiring that we lock an AGF.
1861  *
1862  * Hence the ordering that is imposed by other parts of the code is AGI before
1863  * AGF. This means we cannot remove the directory entry before we drop the inode
1864  * reference count and put it on the unlinked list as this results in a lock
1865  * order of AGF then AGI, and this can deadlock against inode allocation and
1866  * freeing. Therefore we must drop the link counts before we remove the
1867  * directory entry.
1868  *
1869  * This is still safe from a transactional point of view - it is not until we
1870  * get to xfs_defer_finish() that we have the possibility of multiple
1871  * transactions in this operation. Hence as long as we remove the directory
1872  * entry and drop the link count in the first transaction of the remove
1873  * operation, there are no transactional constraints on the ordering here.
1874  */
1875 int
xfs_remove(struct xfs_inode * dp,struct xfs_name * name,struct xfs_inode * ip)1876 xfs_remove(
1877 	struct xfs_inode	*dp,
1878 	struct xfs_name		*name,
1879 	struct xfs_inode	*ip)
1880 {
1881 	struct xfs_dir_update	du = {
1882 		.dp		= dp,
1883 		.name		= name,
1884 		.ip		= ip,
1885 	};
1886 	struct xfs_mount	*mp = dp->i_mount;
1887 	struct xfs_trans	*tp = NULL;
1888 	int			is_dir = S_ISDIR(VFS_I(ip)->i_mode);
1889 	int			dontcare;
1890 	int                     error = 0;
1891 	uint			resblks;
1892 
1893 	trace_xfs_remove(dp, name);
1894 
1895 	if (xfs_is_shutdown(mp))
1896 		return -EIO;
1897 	if (xfs_ifork_zapped(dp, XFS_DATA_FORK))
1898 		return -EIO;
1899 
1900 	error = xfs_qm_dqattach(dp);
1901 	if (error)
1902 		goto std_return;
1903 
1904 	error = xfs_qm_dqattach(ip);
1905 	if (error)
1906 		goto std_return;
1907 
1908 	error = xfs_parent_start(mp, &du.ppargs);
1909 	if (error)
1910 		goto std_return;
1911 
1912 	/*
1913 	 * We try to get the real space reservation first, allowing for
1914 	 * directory btree deletion(s) implying possible bmap insert(s).  If we
1915 	 * can't get the space reservation then we use 0 instead, and avoid the
1916 	 * bmap btree insert(s) in the directory code by, if the bmap insert
1917 	 * tries to happen, instead trimming the LAST block from the directory.
1918 	 *
1919 	 * Ignore EDQUOT and ENOSPC being returned via nospace_error because
1920 	 * the directory code can handle a reservationless update and we don't
1921 	 * want to prevent a user from trying to free space by deleting things.
1922 	 */
1923 	resblks = xfs_remove_space_res(mp, name->len);
1924 	error = xfs_trans_alloc_dir(dp, &M_RES(mp)->tr_remove, ip, &resblks,
1925 			&tp, &dontcare);
1926 	if (error) {
1927 		ASSERT(error != -ENOSPC);
1928 		goto out_parent;
1929 	}
1930 
1931 	error = xfs_dir_remove_child(tp, resblks, &du);
1932 	if (error)
1933 		goto out_trans_cancel;
1934 
1935 	/*
1936 	 * If this is a synchronous mount, make sure that the
1937 	 * remove transaction goes to disk before returning to
1938 	 * the user.
1939 	 */
1940 	if (xfs_has_wsync(mp) || xfs_has_dirsync(mp))
1941 		xfs_trans_set_sync(tp);
1942 
1943 	error = xfs_trans_commit(tp);
1944 	if (error)
1945 		goto out_unlock;
1946 
1947 	if (is_dir && xfs_inode_is_filestream(ip))
1948 		xfs_filestream_deassociate(ip);
1949 
1950 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1951 	xfs_iunlock(dp, XFS_ILOCK_EXCL);
1952 	xfs_parent_finish(mp, du.ppargs);
1953 	return 0;
1954 
1955  out_trans_cancel:
1956 	xfs_trans_cancel(tp);
1957  out_unlock:
1958 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1959 	xfs_iunlock(dp, XFS_ILOCK_EXCL);
1960  out_parent:
1961 	xfs_parent_finish(mp, du.ppargs);
1962  std_return:
1963 	return error;
1964 }
1965 
1966 static inline void
xfs_iunlock_rename(struct xfs_inode ** i_tab,int num_inodes)1967 xfs_iunlock_rename(
1968 	struct xfs_inode	**i_tab,
1969 	int			num_inodes)
1970 {
1971 	int			i;
1972 
1973 	for (i = num_inodes - 1; i >= 0; i--) {
1974 		/* Skip duplicate inodes if src and target dps are the same */
1975 		if (!i_tab[i] || (i > 0 && i_tab[i] == i_tab[i - 1]))
1976 			continue;
1977 		xfs_iunlock(i_tab[i], XFS_ILOCK_EXCL);
1978 	}
1979 }
1980 
1981 /*
1982  * Enter all inodes for a rename transaction into a sorted array.
1983  */
1984 #define __XFS_SORT_INODES	5
1985 STATIC void
xfs_sort_for_rename(struct xfs_inode * dp1,struct xfs_inode * dp2,struct xfs_inode * ip1,struct xfs_inode * ip2,struct xfs_inode * wip,struct xfs_inode ** i_tab,int * num_inodes)1986 xfs_sort_for_rename(
1987 	struct xfs_inode	*dp1,	/* in: old (source) directory inode */
1988 	struct xfs_inode	*dp2,	/* in: new (target) directory inode */
1989 	struct xfs_inode	*ip1,	/* in: inode of old entry */
1990 	struct xfs_inode	*ip2,	/* in: inode of new entry */
1991 	struct xfs_inode	*wip,	/* in: whiteout inode */
1992 	struct xfs_inode	**i_tab,/* out: sorted array of inodes */
1993 	int			*num_inodes)  /* in/out: inodes in array */
1994 {
1995 	int			i;
1996 
1997 	ASSERT(*num_inodes == __XFS_SORT_INODES);
1998 	memset(i_tab, 0, *num_inodes * sizeof(struct xfs_inode *));
1999 
2000 	/*
2001 	 * i_tab contains a list of pointers to inodes.  We initialize
2002 	 * the table here & we'll sort it.  We will then use it to
2003 	 * order the acquisition of the inode locks.
2004 	 *
2005 	 * Note that the table may contain duplicates.  e.g., dp1 == dp2.
2006 	 */
2007 	i = 0;
2008 	i_tab[i++] = dp1;
2009 	i_tab[i++] = dp2;
2010 	i_tab[i++] = ip1;
2011 	if (ip2)
2012 		i_tab[i++] = ip2;
2013 	if (wip)
2014 		i_tab[i++] = wip;
2015 	*num_inodes = i;
2016 
2017 	xfs_sort_inodes(i_tab, *num_inodes);
2018 }
2019 
2020 void
xfs_sort_inodes(struct xfs_inode ** i_tab,unsigned int num_inodes)2021 xfs_sort_inodes(
2022 	struct xfs_inode	**i_tab,
2023 	unsigned int		num_inodes)
2024 {
2025 	int			i, j;
2026 
2027 	ASSERT(num_inodes <= __XFS_SORT_INODES);
2028 
2029 	/*
2030 	 * Sort the elements via bubble sort.  (Remember, there are at
2031 	 * most 5 elements to sort, so this is adequate.)
2032 	 */
2033 	for (i = 0; i < num_inodes; i++) {
2034 		for (j = 1; j < num_inodes; j++) {
2035 			if (i_tab[j]->i_ino < i_tab[j-1]->i_ino)
2036 				swap(i_tab[j], i_tab[j - 1]);
2037 		}
2038 	}
2039 }
2040 
2041 /*
2042  * xfs_rename_alloc_whiteout()
2043  *
2044  * Return a referenced, unlinked, unlocked inode that can be used as a
2045  * whiteout in a rename transaction. We use a tmpfile inode here so that if we
2046  * crash between allocating the inode and linking it into the rename transaction
2047  * recovery will free the inode and we won't leak it.
2048  */
2049 static int
xfs_rename_alloc_whiteout(struct mnt_idmap * idmap,struct xfs_name * src_name,struct xfs_inode * dp,struct xfs_inode ** wip)2050 xfs_rename_alloc_whiteout(
2051 	struct mnt_idmap	*idmap,
2052 	struct xfs_name		*src_name,
2053 	struct xfs_inode	*dp,
2054 	struct xfs_inode	**wip)
2055 {
2056 	struct xfs_icreate_args	args = {
2057 		.idmap		= idmap,
2058 		.pip		= dp,
2059 		.mode		= S_IFCHR | WHITEOUT_MODE,
2060 		.flags		= XFS_ICREATE_TMPFILE,
2061 	};
2062 	struct xfs_inode	*tmpfile;
2063 	struct qstr		name;
2064 	int			error;
2065 
2066 	error = xfs_create_tmpfile(&args, &tmpfile);
2067 	if (error)
2068 		return error;
2069 
2070 	name.name = src_name->name;
2071 	name.len = src_name->len;
2072 	error = xfs_inode_init_security(VFS_I(tmpfile), VFS_I(dp), &name);
2073 	if (error) {
2074 		xfs_finish_inode_setup(tmpfile);
2075 		xfs_irele(tmpfile);
2076 		return error;
2077 	}
2078 
2079 	/*
2080 	 * Prepare the tmpfile inode as if it were created through the VFS.
2081 	 * Complete the inode setup and flag it as linkable.  nlink is already
2082 	 * zero, so we can skip the drop_nlink.
2083 	 */
2084 	xfs_setup_iops(tmpfile);
2085 	xfs_finish_inode_setup(tmpfile);
2086 	VFS_I(tmpfile)->i_state |= I_LINKABLE;
2087 
2088 	*wip = tmpfile;
2089 	return 0;
2090 }
2091 
2092 /*
2093  * xfs_rename
2094  */
2095 int
xfs_rename(struct mnt_idmap * idmap,struct xfs_inode * src_dp,struct xfs_name * src_name,struct xfs_inode * src_ip,struct xfs_inode * target_dp,struct xfs_name * target_name,struct xfs_inode * target_ip,unsigned int flags)2096 xfs_rename(
2097 	struct mnt_idmap	*idmap,
2098 	struct xfs_inode	*src_dp,
2099 	struct xfs_name		*src_name,
2100 	struct xfs_inode	*src_ip,
2101 	struct xfs_inode	*target_dp,
2102 	struct xfs_name		*target_name,
2103 	struct xfs_inode	*target_ip,
2104 	unsigned int		flags)
2105 {
2106 	struct xfs_dir_update	du_src = {
2107 		.dp		= src_dp,
2108 		.name		= src_name,
2109 		.ip		= src_ip,
2110 	};
2111 	struct xfs_dir_update	du_tgt = {
2112 		.dp		= target_dp,
2113 		.name		= target_name,
2114 		.ip		= target_ip,
2115 	};
2116 	struct xfs_dir_update	du_wip = { };
2117 	struct xfs_mount	*mp = src_dp->i_mount;
2118 	struct xfs_trans	*tp;
2119 	struct xfs_inode	*inodes[__XFS_SORT_INODES];
2120 	int			i;
2121 	int			num_inodes = __XFS_SORT_INODES;
2122 	bool			new_parent = (src_dp != target_dp);
2123 	bool			src_is_directory = S_ISDIR(VFS_I(src_ip)->i_mode);
2124 	int			spaceres;
2125 	bool			retried = false;
2126 	int			error, nospace_error = 0;
2127 
2128 	trace_xfs_rename(src_dp, target_dp, src_name, target_name);
2129 
2130 	if ((flags & RENAME_EXCHANGE) && !target_ip)
2131 		return -EINVAL;
2132 
2133 	/*
2134 	 * If we are doing a whiteout operation, allocate the whiteout inode
2135 	 * we will be placing at the target and ensure the type is set
2136 	 * appropriately.
2137 	 */
2138 	if (flags & RENAME_WHITEOUT) {
2139 		error = xfs_rename_alloc_whiteout(idmap, src_name, target_dp,
2140 				&du_wip.ip);
2141 		if (error)
2142 			return error;
2143 
2144 		/* setup target dirent info as whiteout */
2145 		src_name->type = XFS_DIR3_FT_CHRDEV;
2146 	}
2147 
2148 	xfs_sort_for_rename(src_dp, target_dp, src_ip, target_ip, du_wip.ip,
2149 			inodes, &num_inodes);
2150 
2151 	error = xfs_parent_start(mp, &du_src.ppargs);
2152 	if (error)
2153 		goto out_release_wip;
2154 
2155 	if (du_wip.ip) {
2156 		error = xfs_parent_start(mp, &du_wip.ppargs);
2157 		if (error)
2158 			goto out_src_ppargs;
2159 	}
2160 
2161 	if (target_ip) {
2162 		error = xfs_parent_start(mp, &du_tgt.ppargs);
2163 		if (error)
2164 			goto out_wip_ppargs;
2165 	}
2166 
2167 retry:
2168 	nospace_error = 0;
2169 	spaceres = xfs_rename_space_res(mp, src_name->len, target_ip != NULL,
2170 			target_name->len, du_wip.ip != NULL);
2171 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_rename, spaceres, 0, 0, &tp);
2172 	if (error == -ENOSPC) {
2173 		nospace_error = error;
2174 		spaceres = 0;
2175 		error = xfs_trans_alloc(mp, &M_RES(mp)->tr_rename, 0, 0, 0,
2176 				&tp);
2177 	}
2178 	if (error)
2179 		goto out_tgt_ppargs;
2180 
2181 	/*
2182 	 * We don't allow reservationless renaming when parent pointers are
2183 	 * enabled because we can't back out if the xattrs must grow.
2184 	 */
2185 	if (du_src.ppargs && nospace_error) {
2186 		error = nospace_error;
2187 		xfs_trans_cancel(tp);
2188 		goto out_tgt_ppargs;
2189 	}
2190 
2191 	/*
2192 	 * Attach the dquots to the inodes
2193 	 */
2194 	error = xfs_qm_vop_rename_dqattach(inodes);
2195 	if (error) {
2196 		xfs_trans_cancel(tp);
2197 		goto out_tgt_ppargs;
2198 	}
2199 
2200 	/*
2201 	 * Lock all the participating inodes. Depending upon whether
2202 	 * the target_name exists in the target directory, and
2203 	 * whether the target directory is the same as the source
2204 	 * directory, we can lock from 2 to 5 inodes.
2205 	 */
2206 	xfs_lock_inodes(inodes, num_inodes, XFS_ILOCK_EXCL);
2207 
2208 	/*
2209 	 * Join all the inodes to the transaction.
2210 	 */
2211 	xfs_trans_ijoin(tp, src_dp, 0);
2212 	if (new_parent)
2213 		xfs_trans_ijoin(tp, target_dp, 0);
2214 	xfs_trans_ijoin(tp, src_ip, 0);
2215 	if (target_ip)
2216 		xfs_trans_ijoin(tp, target_ip, 0);
2217 	if (du_wip.ip)
2218 		xfs_trans_ijoin(tp, du_wip.ip, 0);
2219 
2220 	/*
2221 	 * If we are using project inheritance, we only allow renames
2222 	 * into our tree when the project IDs are the same; else the
2223 	 * tree quota mechanism would be circumvented.
2224 	 */
2225 	if (unlikely((target_dp->i_diflags & XFS_DIFLAG_PROJINHERIT) &&
2226 		     target_dp->i_projid != src_ip->i_projid)) {
2227 		error = -EXDEV;
2228 		goto out_trans_cancel;
2229 	}
2230 
2231 	/* RENAME_EXCHANGE is unique from here on. */
2232 	if (flags & RENAME_EXCHANGE) {
2233 		error = xfs_dir_exchange_children(tp, &du_src, &du_tgt,
2234 				spaceres);
2235 		if (error)
2236 			goto out_trans_cancel;
2237 		goto out_commit;
2238 	}
2239 
2240 	/*
2241 	 * Try to reserve quota to handle an expansion of the target directory.
2242 	 * We'll allow the rename to continue in reservationless mode if we hit
2243 	 * a space usage constraint.  If we trigger reservationless mode, save
2244 	 * the errno if there isn't any free space in the target directory.
2245 	 */
2246 	if (spaceres != 0) {
2247 		error = xfs_trans_reserve_quota_nblks(tp, target_dp, spaceres,
2248 				0, false);
2249 		if (error == -EDQUOT || error == -ENOSPC) {
2250 			if (!retried) {
2251 				xfs_trans_cancel(tp);
2252 				xfs_iunlock_rename(inodes, num_inodes);
2253 				xfs_blockgc_free_quota(target_dp, 0);
2254 				retried = true;
2255 				goto retry;
2256 			}
2257 
2258 			nospace_error = error;
2259 			spaceres = 0;
2260 			error = 0;
2261 		}
2262 		if (error)
2263 			goto out_trans_cancel;
2264 	}
2265 
2266 	/*
2267 	 * We don't allow quotaless renaming when parent pointers are enabled
2268 	 * because we can't back out if the xattrs must grow.
2269 	 */
2270 	if (du_src.ppargs && nospace_error) {
2271 		error = nospace_error;
2272 		goto out_trans_cancel;
2273 	}
2274 
2275 	/*
2276 	 * Lock the AGI buffers we need to handle bumping the nlink of the
2277 	 * whiteout inode off the unlinked list and to handle dropping the
2278 	 * nlink of the target inode.  Per locking order rules, do this in
2279 	 * increasing AG order and before directory block allocation tries to
2280 	 * grab AGFs because we grab AGIs before AGFs.
2281 	 *
2282 	 * The (vfs) caller must ensure that if src is a directory then
2283 	 * target_ip is either null or an empty directory.
2284 	 */
2285 	for (i = 0; i < num_inodes && inodes[i] != NULL; i++) {
2286 		if (inodes[i] == du_wip.ip ||
2287 		    (inodes[i] == target_ip &&
2288 		     (VFS_I(target_ip)->i_nlink == 1 || src_is_directory))) {
2289 			struct xfs_perag	*pag;
2290 			struct xfs_buf		*bp;
2291 
2292 			pag = xfs_perag_get(mp,
2293 					XFS_INO_TO_AGNO(mp, inodes[i]->i_ino));
2294 			error = xfs_read_agi(pag, tp, 0, &bp);
2295 			xfs_perag_put(pag);
2296 			if (error)
2297 				goto out_trans_cancel;
2298 		}
2299 	}
2300 
2301 	error = xfs_dir_rename_children(tp, &du_src, &du_tgt, spaceres,
2302 			&du_wip);
2303 	if (error)
2304 		goto out_trans_cancel;
2305 
2306 	if (du_wip.ip) {
2307 		/*
2308 		 * Now we have a real link, clear the "I'm a tmpfile" state
2309 		 * flag from the inode so it doesn't accidentally get misused in
2310 		 * future.
2311 		 */
2312 		VFS_I(du_wip.ip)->i_state &= ~I_LINKABLE;
2313 	}
2314 
2315 out_commit:
2316 	/*
2317 	 * If this is a synchronous mount, make sure that the rename
2318 	 * transaction goes to disk before returning to the user.
2319 	 */
2320 	if (xfs_has_wsync(tp->t_mountp) || xfs_has_dirsync(tp->t_mountp))
2321 		xfs_trans_set_sync(tp);
2322 
2323 	error = xfs_trans_commit(tp);
2324 	nospace_error = 0;
2325 	goto out_unlock;
2326 
2327 out_trans_cancel:
2328 	xfs_trans_cancel(tp);
2329 out_unlock:
2330 	xfs_iunlock_rename(inodes, num_inodes);
2331 out_tgt_ppargs:
2332 	xfs_parent_finish(mp, du_tgt.ppargs);
2333 out_wip_ppargs:
2334 	xfs_parent_finish(mp, du_wip.ppargs);
2335 out_src_ppargs:
2336 	xfs_parent_finish(mp, du_src.ppargs);
2337 out_release_wip:
2338 	if (du_wip.ip)
2339 		xfs_irele(du_wip.ip);
2340 	if (error == -ENOSPC && nospace_error)
2341 		error = nospace_error;
2342 	return error;
2343 }
2344 
2345 static int
xfs_iflush(struct xfs_inode * ip,struct xfs_buf * bp)2346 xfs_iflush(
2347 	struct xfs_inode	*ip,
2348 	struct xfs_buf		*bp)
2349 {
2350 	struct xfs_inode_log_item *iip = ip->i_itemp;
2351 	struct xfs_dinode	*dip;
2352 	struct xfs_mount	*mp = ip->i_mount;
2353 	int			error;
2354 
2355 	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL | XFS_ILOCK_SHARED);
2356 	ASSERT(xfs_iflags_test(ip, XFS_IFLUSHING));
2357 	ASSERT(ip->i_df.if_format != XFS_DINODE_FMT_BTREE ||
2358 	       ip->i_df.if_nextents > XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK));
2359 	ASSERT(iip->ili_item.li_buf == bp);
2360 
2361 	dip = xfs_buf_offset(bp, ip->i_imap.im_boffset);
2362 
2363 	/*
2364 	 * We don't flush the inode if any of the following checks fail, but we
2365 	 * do still update the log item and attach to the backing buffer as if
2366 	 * the flush happened. This is a formality to facilitate predictable
2367 	 * error handling as the caller will shutdown and fail the buffer.
2368 	 */
2369 	error = -EFSCORRUPTED;
2370 	if (XFS_TEST_ERROR(dip->di_magic != cpu_to_be16(XFS_DINODE_MAGIC),
2371 			       mp, XFS_ERRTAG_IFLUSH_1)) {
2372 		xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
2373 			"%s: Bad inode %llu magic number 0x%x, ptr "PTR_FMT,
2374 			__func__, ip->i_ino, be16_to_cpu(dip->di_magic), dip);
2375 		goto flush_out;
2376 	}
2377 	if (S_ISREG(VFS_I(ip)->i_mode)) {
2378 		if (XFS_TEST_ERROR(
2379 		    ip->i_df.if_format != XFS_DINODE_FMT_EXTENTS &&
2380 		    ip->i_df.if_format != XFS_DINODE_FMT_BTREE,
2381 		    mp, XFS_ERRTAG_IFLUSH_3)) {
2382 			xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
2383 				"%s: Bad regular inode %llu, ptr "PTR_FMT,
2384 				__func__, ip->i_ino, ip);
2385 			goto flush_out;
2386 		}
2387 	} else if (S_ISDIR(VFS_I(ip)->i_mode)) {
2388 		if (XFS_TEST_ERROR(
2389 		    ip->i_df.if_format != XFS_DINODE_FMT_EXTENTS &&
2390 		    ip->i_df.if_format != XFS_DINODE_FMT_BTREE &&
2391 		    ip->i_df.if_format != XFS_DINODE_FMT_LOCAL,
2392 		    mp, XFS_ERRTAG_IFLUSH_4)) {
2393 			xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
2394 				"%s: Bad directory inode %llu, ptr "PTR_FMT,
2395 				__func__, ip->i_ino, ip);
2396 			goto flush_out;
2397 		}
2398 	}
2399 	if (XFS_TEST_ERROR(ip->i_df.if_nextents + xfs_ifork_nextents(&ip->i_af) >
2400 				ip->i_nblocks, mp, XFS_ERRTAG_IFLUSH_5)) {
2401 		xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
2402 			"%s: detected corrupt incore inode %llu, "
2403 			"total extents = %llu nblocks = %lld, ptr "PTR_FMT,
2404 			__func__, ip->i_ino,
2405 			ip->i_df.if_nextents + xfs_ifork_nextents(&ip->i_af),
2406 			ip->i_nblocks, ip);
2407 		goto flush_out;
2408 	}
2409 	if (XFS_TEST_ERROR(ip->i_forkoff > mp->m_sb.sb_inodesize,
2410 				mp, XFS_ERRTAG_IFLUSH_6)) {
2411 		xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
2412 			"%s: bad inode %llu, forkoff 0x%x, ptr "PTR_FMT,
2413 			__func__, ip->i_ino, ip->i_forkoff, ip);
2414 		goto flush_out;
2415 	}
2416 
2417 	/*
2418 	 * Inode item log recovery for v2 inodes are dependent on the flushiter
2419 	 * count for correct sequencing.  We bump the flush iteration count so
2420 	 * we can detect flushes which postdate a log record during recovery.
2421 	 * This is redundant as we now log every change and hence this can't
2422 	 * happen but we need to still do it to ensure backwards compatibility
2423 	 * with old kernels that predate logging all inode changes.
2424 	 */
2425 	if (!xfs_has_v3inodes(mp))
2426 		ip->i_flushiter++;
2427 
2428 	/*
2429 	 * If there are inline format data / attr forks attached to this inode,
2430 	 * make sure they are not corrupt.
2431 	 */
2432 	if (ip->i_df.if_format == XFS_DINODE_FMT_LOCAL &&
2433 	    xfs_ifork_verify_local_data(ip))
2434 		goto flush_out;
2435 	if (xfs_inode_has_attr_fork(ip) &&
2436 	    ip->i_af.if_format == XFS_DINODE_FMT_LOCAL &&
2437 	    xfs_ifork_verify_local_attr(ip))
2438 		goto flush_out;
2439 
2440 	/*
2441 	 * Copy the dirty parts of the inode into the on-disk inode.  We always
2442 	 * copy out the core of the inode, because if the inode is dirty at all
2443 	 * the core must be.
2444 	 */
2445 	xfs_inode_to_disk(ip, dip, iip->ili_item.li_lsn);
2446 
2447 	/* Wrap, we never let the log put out DI_MAX_FLUSH */
2448 	if (!xfs_has_v3inodes(mp)) {
2449 		if (ip->i_flushiter == DI_MAX_FLUSH)
2450 			ip->i_flushiter = 0;
2451 	}
2452 
2453 	xfs_iflush_fork(ip, dip, iip, XFS_DATA_FORK);
2454 	if (xfs_inode_has_attr_fork(ip))
2455 		xfs_iflush_fork(ip, dip, iip, XFS_ATTR_FORK);
2456 
2457 	/*
2458 	 * We've recorded everything logged in the inode, so we'd like to clear
2459 	 * the ili_fields bits so we don't log and flush things unnecessarily.
2460 	 * However, we can't stop logging all this information until the data
2461 	 * we've copied into the disk buffer is written to disk.  If we did we
2462 	 * might overwrite the copy of the inode in the log with all the data
2463 	 * after re-logging only part of it, and in the face of a crash we
2464 	 * wouldn't have all the data we need to recover.
2465 	 *
2466 	 * What we do is move the bits to the ili_last_fields field.  When
2467 	 * logging the inode, these bits are moved back to the ili_fields field.
2468 	 * In the xfs_buf_inode_iodone() routine we clear ili_last_fields, since
2469 	 * we know that the information those bits represent is permanently on
2470 	 * disk.  As long as the flush completes before the inode is logged
2471 	 * again, then both ili_fields and ili_last_fields will be cleared.
2472 	 */
2473 	error = 0;
2474 flush_out:
2475 	spin_lock(&iip->ili_lock);
2476 	iip->ili_last_fields = iip->ili_fields;
2477 	iip->ili_fields = 0;
2478 	iip->ili_fsync_fields = 0;
2479 	set_bit(XFS_LI_FLUSHING, &iip->ili_item.li_flags);
2480 	spin_unlock(&iip->ili_lock);
2481 
2482 	/*
2483 	 * Store the current LSN of the inode so that we can tell whether the
2484 	 * item has moved in the AIL from xfs_buf_inode_iodone().
2485 	 */
2486 	xfs_trans_ail_copy_lsn(mp->m_ail, &iip->ili_flush_lsn,
2487 				&iip->ili_item.li_lsn);
2488 
2489 	/* generate the checksum. */
2490 	xfs_dinode_calc_crc(mp, dip);
2491 	if (error)
2492 		xfs_inode_mark_sick(ip, XFS_SICK_INO_CORE);
2493 	return error;
2494 }
2495 
2496 /*
2497  * Non-blocking flush of dirty inode metadata into the backing buffer.
2498  *
2499  * The caller must have a reference to the inode and hold the cluster buffer
2500  * locked. The function will walk across all the inodes on the cluster buffer it
2501  * can find and lock without blocking, and flush them to the cluster buffer.
2502  *
2503  * On successful flushing of at least one inode, the caller must write out the
2504  * buffer and release it. If no inodes are flushed, -EAGAIN will be returned and
2505  * the caller needs to release the buffer. On failure, the filesystem will be
2506  * shut down, the buffer will have been unlocked and released, and EFSCORRUPTED
2507  * will be returned.
2508  */
2509 int
xfs_iflush_cluster(struct xfs_buf * bp)2510 xfs_iflush_cluster(
2511 	struct xfs_buf		*bp)
2512 {
2513 	struct xfs_mount	*mp = bp->b_mount;
2514 	struct xfs_log_item	*lip, *n;
2515 	struct xfs_inode	*ip;
2516 	struct xfs_inode_log_item *iip;
2517 	int			clcount = 0;
2518 	int			error = 0;
2519 
2520 	/*
2521 	 * We must use the safe variant here as on shutdown xfs_iflush_abort()
2522 	 * will remove itself from the list.
2523 	 */
2524 	list_for_each_entry_safe(lip, n, &bp->b_li_list, li_bio_list) {
2525 		iip = (struct xfs_inode_log_item *)lip;
2526 		ip = iip->ili_inode;
2527 
2528 		/*
2529 		 * Quick and dirty check to avoid locks if possible.
2530 		 */
2531 		if (__xfs_iflags_test(ip, XFS_IRECLAIM | XFS_IFLUSHING))
2532 			continue;
2533 		if (xfs_ipincount(ip))
2534 			continue;
2535 
2536 		/*
2537 		 * The inode is still attached to the buffer, which means it is
2538 		 * dirty but reclaim might try to grab it. Check carefully for
2539 		 * that, and grab the ilock while still holding the i_flags_lock
2540 		 * to guarantee reclaim will not be able to reclaim this inode
2541 		 * once we drop the i_flags_lock.
2542 		 */
2543 		spin_lock(&ip->i_flags_lock);
2544 		ASSERT(!__xfs_iflags_test(ip, XFS_ISTALE));
2545 		if (__xfs_iflags_test(ip, XFS_IRECLAIM | XFS_IFLUSHING)) {
2546 			spin_unlock(&ip->i_flags_lock);
2547 			continue;
2548 		}
2549 
2550 		/*
2551 		 * ILOCK will pin the inode against reclaim and prevent
2552 		 * concurrent transactions modifying the inode while we are
2553 		 * flushing the inode. If we get the lock, set the flushing
2554 		 * state before we drop the i_flags_lock.
2555 		 */
2556 		if (!xfs_ilock_nowait(ip, XFS_ILOCK_SHARED)) {
2557 			spin_unlock(&ip->i_flags_lock);
2558 			continue;
2559 		}
2560 		__xfs_iflags_set(ip, XFS_IFLUSHING);
2561 		spin_unlock(&ip->i_flags_lock);
2562 
2563 		/*
2564 		 * Abort flushing this inode if we are shut down because the
2565 		 * inode may not currently be in the AIL. This can occur when
2566 		 * log I/O failure unpins the inode without inserting into the
2567 		 * AIL, leaving a dirty/unpinned inode attached to the buffer
2568 		 * that otherwise looks like it should be flushed.
2569 		 */
2570 		if (xlog_is_shutdown(mp->m_log)) {
2571 			xfs_iunpin_wait(ip);
2572 			xfs_iflush_abort(ip);
2573 			xfs_iunlock(ip, XFS_ILOCK_SHARED);
2574 			error = -EIO;
2575 			continue;
2576 		}
2577 
2578 		/* don't block waiting on a log force to unpin dirty inodes */
2579 		if (xfs_ipincount(ip)) {
2580 			xfs_iflags_clear(ip, XFS_IFLUSHING);
2581 			xfs_iunlock(ip, XFS_ILOCK_SHARED);
2582 			continue;
2583 		}
2584 
2585 		if (!xfs_inode_clean(ip))
2586 			error = xfs_iflush(ip, bp);
2587 		else
2588 			xfs_iflags_clear(ip, XFS_IFLUSHING);
2589 		xfs_iunlock(ip, XFS_ILOCK_SHARED);
2590 		if (error)
2591 			break;
2592 		clcount++;
2593 	}
2594 
2595 	if (error) {
2596 		/*
2597 		 * Shutdown first so we kill the log before we release this
2598 		 * buffer. If it is an INODE_ALLOC buffer and pins the tail
2599 		 * of the log, failing it before the _log_ is shut down can
2600 		 * result in the log tail being moved forward in the journal
2601 		 * on disk because log writes can still be taking place. Hence
2602 		 * unpinning the tail will allow the ICREATE intent to be
2603 		 * removed from the log an recovery will fail with uninitialised
2604 		 * inode cluster buffers.
2605 		 */
2606 		xfs_force_shutdown(mp, SHUTDOWN_CORRUPT_INCORE);
2607 		bp->b_flags |= XBF_ASYNC;
2608 		xfs_buf_ioend_fail(bp);
2609 		return error;
2610 	}
2611 
2612 	if (!clcount)
2613 		return -EAGAIN;
2614 
2615 	XFS_STATS_INC(mp, xs_icluster_flushcnt);
2616 	XFS_STATS_ADD(mp, xs_icluster_flushinode, clcount);
2617 	return 0;
2618 
2619 }
2620 
2621 /* Release an inode. */
2622 void
xfs_irele(struct xfs_inode * ip)2623 xfs_irele(
2624 	struct xfs_inode	*ip)
2625 {
2626 	trace_xfs_irele(ip, _RET_IP_);
2627 	iput(VFS_I(ip));
2628 }
2629 
2630 /*
2631  * Ensure all commited transactions touching the inode are written to the log.
2632  */
2633 int
xfs_log_force_inode(struct xfs_inode * ip)2634 xfs_log_force_inode(
2635 	struct xfs_inode	*ip)
2636 {
2637 	xfs_csn_t		seq = 0;
2638 
2639 	xfs_ilock(ip, XFS_ILOCK_SHARED);
2640 	if (xfs_ipincount(ip))
2641 		seq = ip->i_itemp->ili_commit_seq;
2642 	xfs_iunlock(ip, XFS_ILOCK_SHARED);
2643 
2644 	if (!seq)
2645 		return 0;
2646 	return xfs_log_force_seq(ip->i_mount, seq, XFS_LOG_SYNC, NULL);
2647 }
2648 
2649 /*
2650  * Grab the exclusive iolock for a data copy from src to dest, making sure to
2651  * abide vfs locking order (lowest pointer value goes first) and breaking the
2652  * layout leases before proceeding.  The loop is needed because we cannot call
2653  * the blocking break_layout() with the iolocks held, and therefore have to
2654  * back out both locks.
2655  */
2656 static int
xfs_iolock_two_inodes_and_break_layout(struct inode * src,struct inode * dest)2657 xfs_iolock_two_inodes_and_break_layout(
2658 	struct inode		*src,
2659 	struct inode		*dest)
2660 {
2661 	int			error;
2662 
2663 	if (src > dest)
2664 		swap(src, dest);
2665 
2666 retry:
2667 	/* Wait to break both inodes' layouts before we start locking. */
2668 	error = break_layout(src, true);
2669 	if (error)
2670 		return error;
2671 	if (src != dest) {
2672 		error = break_layout(dest, true);
2673 		if (error)
2674 			return error;
2675 	}
2676 
2677 	/* Lock one inode and make sure nobody got in and leased it. */
2678 	inode_lock(src);
2679 	error = break_layout(src, false);
2680 	if (error) {
2681 		inode_unlock(src);
2682 		if (error == -EWOULDBLOCK)
2683 			goto retry;
2684 		return error;
2685 	}
2686 
2687 	if (src == dest)
2688 		return 0;
2689 
2690 	/* Lock the other inode and make sure nobody got in and leased it. */
2691 	inode_lock_nested(dest, I_MUTEX_NONDIR2);
2692 	error = break_layout(dest, false);
2693 	if (error) {
2694 		inode_unlock(src);
2695 		inode_unlock(dest);
2696 		if (error == -EWOULDBLOCK)
2697 			goto retry;
2698 		return error;
2699 	}
2700 
2701 	return 0;
2702 }
2703 
2704 static int
xfs_mmaplock_two_inodes_and_break_dax_layout(struct xfs_inode * ip1,struct xfs_inode * ip2)2705 xfs_mmaplock_two_inodes_and_break_dax_layout(
2706 	struct xfs_inode	*ip1,
2707 	struct xfs_inode	*ip2)
2708 {
2709 	int			error;
2710 	bool			retry;
2711 	struct page		*page;
2712 
2713 	if (ip1->i_ino > ip2->i_ino)
2714 		swap(ip1, ip2);
2715 
2716 again:
2717 	retry = false;
2718 	/* Lock the first inode */
2719 	xfs_ilock(ip1, XFS_MMAPLOCK_EXCL);
2720 	error = xfs_break_dax_layouts(VFS_I(ip1), &retry);
2721 	if (error || retry) {
2722 		xfs_iunlock(ip1, XFS_MMAPLOCK_EXCL);
2723 		if (error == 0 && retry)
2724 			goto again;
2725 		return error;
2726 	}
2727 
2728 	if (ip1 == ip2)
2729 		return 0;
2730 
2731 	/* Nested lock the second inode */
2732 	xfs_ilock(ip2, xfs_lock_inumorder(XFS_MMAPLOCK_EXCL, 1));
2733 	/*
2734 	 * We cannot use xfs_break_dax_layouts() directly here because it may
2735 	 * need to unlock & lock the XFS_MMAPLOCK_EXCL which is not suitable
2736 	 * for this nested lock case.
2737 	 */
2738 	page = dax_layout_busy_page(VFS_I(ip2)->i_mapping);
2739 	if (page && page_ref_count(page) != 1) {
2740 		xfs_iunlock(ip2, XFS_MMAPLOCK_EXCL);
2741 		xfs_iunlock(ip1, XFS_MMAPLOCK_EXCL);
2742 		goto again;
2743 	}
2744 
2745 	return 0;
2746 }
2747 
2748 /*
2749  * Lock two inodes so that userspace cannot initiate I/O via file syscalls or
2750  * mmap activity.
2751  */
2752 int
xfs_ilock2_io_mmap(struct xfs_inode * ip1,struct xfs_inode * ip2)2753 xfs_ilock2_io_mmap(
2754 	struct xfs_inode	*ip1,
2755 	struct xfs_inode	*ip2)
2756 {
2757 	int			ret;
2758 
2759 	ret = xfs_iolock_two_inodes_and_break_layout(VFS_I(ip1), VFS_I(ip2));
2760 	if (ret)
2761 		return ret;
2762 
2763 	if (IS_DAX(VFS_I(ip1)) && IS_DAX(VFS_I(ip2))) {
2764 		ret = xfs_mmaplock_two_inodes_and_break_dax_layout(ip1, ip2);
2765 		if (ret) {
2766 			inode_unlock(VFS_I(ip2));
2767 			if (ip1 != ip2)
2768 				inode_unlock(VFS_I(ip1));
2769 			return ret;
2770 		}
2771 	} else
2772 		filemap_invalidate_lock_two(VFS_I(ip1)->i_mapping,
2773 					    VFS_I(ip2)->i_mapping);
2774 
2775 	return 0;
2776 }
2777 
2778 /* Unlock both inodes to allow IO and mmap activity. */
2779 void
xfs_iunlock2_io_mmap(struct xfs_inode * ip1,struct xfs_inode * ip2)2780 xfs_iunlock2_io_mmap(
2781 	struct xfs_inode	*ip1,
2782 	struct xfs_inode	*ip2)
2783 {
2784 	if (IS_DAX(VFS_I(ip1)) && IS_DAX(VFS_I(ip2))) {
2785 		xfs_iunlock(ip2, XFS_MMAPLOCK_EXCL);
2786 		if (ip1 != ip2)
2787 			xfs_iunlock(ip1, XFS_MMAPLOCK_EXCL);
2788 	} else
2789 		filemap_invalidate_unlock_two(VFS_I(ip1)->i_mapping,
2790 					      VFS_I(ip2)->i_mapping);
2791 
2792 	inode_unlock(VFS_I(ip2));
2793 	if (ip1 != ip2)
2794 		inode_unlock(VFS_I(ip1));
2795 }
2796 
2797 /* Drop the MMAPLOCK and the IOLOCK after a remap completes. */
2798 void
xfs_iunlock2_remapping(struct xfs_inode * ip1,struct xfs_inode * ip2)2799 xfs_iunlock2_remapping(
2800 	struct xfs_inode	*ip1,
2801 	struct xfs_inode	*ip2)
2802 {
2803 	xfs_iflags_clear(ip1, XFS_IREMAPPING);
2804 
2805 	if (ip1 != ip2)
2806 		xfs_iunlock(ip1, XFS_MMAPLOCK_SHARED);
2807 	xfs_iunlock(ip2, XFS_MMAPLOCK_EXCL);
2808 
2809 	if (ip1 != ip2)
2810 		inode_unlock_shared(VFS_I(ip1));
2811 	inode_unlock(VFS_I(ip2));
2812 }
2813 
2814 /*
2815  * Reload the incore inode list for this inode.  Caller should ensure that
2816  * the link count cannot change, either by taking ILOCK_SHARED or otherwise
2817  * preventing other threads from executing.
2818  */
2819 int
xfs_inode_reload_unlinked_bucket(struct xfs_trans * tp,struct xfs_inode * ip)2820 xfs_inode_reload_unlinked_bucket(
2821 	struct xfs_trans	*tp,
2822 	struct xfs_inode	*ip)
2823 {
2824 	struct xfs_mount	*mp = tp->t_mountp;
2825 	struct xfs_buf		*agibp;
2826 	struct xfs_agi		*agi;
2827 	struct xfs_perag	*pag;
2828 	xfs_agnumber_t		agno = XFS_INO_TO_AGNO(mp, ip->i_ino);
2829 	xfs_agino_t		agino = XFS_INO_TO_AGINO(mp, ip->i_ino);
2830 	xfs_agino_t		prev_agino, next_agino;
2831 	unsigned int		bucket;
2832 	bool			foundit = false;
2833 	int			error;
2834 
2835 	/* Grab the first inode in the list */
2836 	pag = xfs_perag_get(mp, agno);
2837 	error = xfs_ialloc_read_agi(pag, tp, 0, &agibp);
2838 	xfs_perag_put(pag);
2839 	if (error)
2840 		return error;
2841 
2842 	/*
2843 	 * We've taken ILOCK_SHARED and the AGI buffer lock to stabilize the
2844 	 * incore unlinked list pointers for this inode.  Check once more to
2845 	 * see if we raced with anyone else to reload the unlinked list.
2846 	 */
2847 	if (!xfs_inode_unlinked_incomplete(ip)) {
2848 		foundit = true;
2849 		goto out_agibp;
2850 	}
2851 
2852 	bucket = agino % XFS_AGI_UNLINKED_BUCKETS;
2853 	agi = agibp->b_addr;
2854 
2855 	trace_xfs_inode_reload_unlinked_bucket(ip);
2856 
2857 	xfs_info_ratelimited(mp,
2858  "Found unrecovered unlinked inode 0x%x in AG 0x%x.  Initiating list recovery.",
2859 			agino, agno);
2860 
2861 	prev_agino = NULLAGINO;
2862 	next_agino = be32_to_cpu(agi->agi_unlinked[bucket]);
2863 	while (next_agino != NULLAGINO) {
2864 		struct xfs_inode	*next_ip = NULL;
2865 
2866 		/* Found this caller's inode, set its backlink. */
2867 		if (next_agino == agino) {
2868 			next_ip = ip;
2869 			next_ip->i_prev_unlinked = prev_agino;
2870 			foundit = true;
2871 			goto next_inode;
2872 		}
2873 
2874 		/* Try in-memory lookup first. */
2875 		next_ip = xfs_iunlink_lookup(pag, next_agino);
2876 		if (next_ip)
2877 			goto next_inode;
2878 
2879 		/* Inode not in memory, try reloading it. */
2880 		error = xfs_iunlink_reload_next(tp, agibp, prev_agino,
2881 				next_agino);
2882 		if (error)
2883 			break;
2884 
2885 		/* Grab the reloaded inode. */
2886 		next_ip = xfs_iunlink_lookup(pag, next_agino);
2887 		if (!next_ip) {
2888 			/* No incore inode at all?  We reloaded it... */
2889 			ASSERT(next_ip != NULL);
2890 			error = -EFSCORRUPTED;
2891 			break;
2892 		}
2893 
2894 next_inode:
2895 		prev_agino = next_agino;
2896 		next_agino = next_ip->i_next_unlinked;
2897 	}
2898 
2899 out_agibp:
2900 	xfs_trans_brelse(tp, agibp);
2901 	/* Should have found this inode somewhere in the iunlinked bucket. */
2902 	if (!error && !foundit)
2903 		error = -EFSCORRUPTED;
2904 	return error;
2905 }
2906 
2907 /* Decide if this inode is missing its unlinked list and reload it. */
2908 int
xfs_inode_reload_unlinked(struct xfs_inode * ip)2909 xfs_inode_reload_unlinked(
2910 	struct xfs_inode	*ip)
2911 {
2912 	struct xfs_trans	*tp;
2913 	int			error;
2914 
2915 	error = xfs_trans_alloc_empty(ip->i_mount, &tp);
2916 	if (error)
2917 		return error;
2918 
2919 	xfs_ilock(ip, XFS_ILOCK_SHARED);
2920 	if (xfs_inode_unlinked_incomplete(ip))
2921 		error = xfs_inode_reload_unlinked_bucket(tp, ip);
2922 	xfs_iunlock(ip, XFS_ILOCK_SHARED);
2923 	xfs_trans_cancel(tp);
2924 
2925 	return error;
2926 }
2927 
2928 /* Has this inode fork been zapped by repair? */
2929 bool
xfs_ifork_zapped(const struct xfs_inode * ip,int whichfork)2930 xfs_ifork_zapped(
2931 	const struct xfs_inode	*ip,
2932 	int			whichfork)
2933 {
2934 	unsigned int		datamask = 0;
2935 
2936 	switch (whichfork) {
2937 	case XFS_DATA_FORK:
2938 		switch (ip->i_vnode.i_mode & S_IFMT) {
2939 		case S_IFDIR:
2940 			datamask = XFS_SICK_INO_DIR_ZAPPED;
2941 			break;
2942 		case S_IFLNK:
2943 			datamask = XFS_SICK_INO_SYMLINK_ZAPPED;
2944 			break;
2945 		}
2946 		return ip->i_sick & (XFS_SICK_INO_BMBTD_ZAPPED | datamask);
2947 	case XFS_ATTR_FORK:
2948 		return ip->i_sick & XFS_SICK_INO_BMBTA_ZAPPED;
2949 	default:
2950 		return false;
2951 	}
2952 }
2953 
2954 /* Compute the number of data and realtime blocks used by a file. */
2955 void
xfs_inode_count_blocks(struct xfs_trans * tp,struct xfs_inode * ip,xfs_filblks_t * dblocks,xfs_filblks_t * rblocks)2956 xfs_inode_count_blocks(
2957 	struct xfs_trans	*tp,
2958 	struct xfs_inode	*ip,
2959 	xfs_filblks_t		*dblocks,
2960 	xfs_filblks_t		*rblocks)
2961 {
2962 	struct xfs_ifork	*ifp = xfs_ifork_ptr(ip, XFS_DATA_FORK);
2963 
2964 	*rblocks = 0;
2965 	if (XFS_IS_REALTIME_INODE(ip))
2966 		xfs_bmap_count_leaves(ifp, rblocks);
2967 	*dblocks = ip->i_nblocks - *rblocks;
2968 }
2969 
2970 static void
xfs_wait_dax_page(struct inode * inode)2971 xfs_wait_dax_page(
2972 	struct inode		*inode)
2973 {
2974 	struct xfs_inode        *ip = XFS_I(inode);
2975 
2976 	xfs_iunlock(ip, XFS_MMAPLOCK_EXCL);
2977 	schedule();
2978 	xfs_ilock(ip, XFS_MMAPLOCK_EXCL);
2979 }
2980 
2981 int
xfs_break_dax_layouts(struct inode * inode,bool * retry)2982 xfs_break_dax_layouts(
2983 	struct inode		*inode,
2984 	bool			*retry)
2985 {
2986 	struct page		*page;
2987 
2988 	xfs_assert_ilocked(XFS_I(inode), XFS_MMAPLOCK_EXCL);
2989 
2990 	page = dax_layout_busy_page(inode->i_mapping);
2991 	if (!page)
2992 		return 0;
2993 
2994 	*retry = true;
2995 	return ___wait_var_event(&page->_refcount,
2996 			atomic_read(&page->_refcount) == 1, TASK_INTERRUPTIBLE,
2997 			0, 0, xfs_wait_dax_page(inode));
2998 }
2999 
3000 int
xfs_break_layouts(struct inode * inode,uint * iolock,enum layout_break_reason reason)3001 xfs_break_layouts(
3002 	struct inode		*inode,
3003 	uint			*iolock,
3004 	enum layout_break_reason reason)
3005 {
3006 	bool			retry;
3007 	int			error;
3008 
3009 	xfs_assert_ilocked(XFS_I(inode), XFS_IOLOCK_SHARED | XFS_IOLOCK_EXCL);
3010 
3011 	do {
3012 		retry = false;
3013 		switch (reason) {
3014 		case BREAK_UNMAP:
3015 			error = xfs_break_dax_layouts(inode, &retry);
3016 			if (error || retry)
3017 				break;
3018 			fallthrough;
3019 		case BREAK_WRITE:
3020 			error = xfs_break_leased_layouts(inode, iolock, &retry);
3021 			break;
3022 		default:
3023 			WARN_ON_ONCE(1);
3024 			error = -EINVAL;
3025 		}
3026 	} while (error == 0 && retry);
3027 
3028 	return error;
3029 }
3030 
3031 /* Returns the size of fundamental allocation unit for a file, in bytes. */
3032 unsigned int
xfs_inode_alloc_unitsize(struct xfs_inode * ip)3033 xfs_inode_alloc_unitsize(
3034 	struct xfs_inode	*ip)
3035 {
3036 	unsigned int		blocks = 1;
3037 
3038 	if (XFS_IS_REALTIME_INODE(ip))
3039 		blocks = ip->i_mount->m_sb.sb_rextsize;
3040 
3041 	return XFS_FSB_TO_B(ip->i_mount, blocks);
3042 }
3043 
3044 /* Should we always be using copy on write for file writes? */
3045 bool
xfs_is_always_cow_inode(struct xfs_inode * ip)3046 xfs_is_always_cow_inode(
3047 	struct xfs_inode	*ip)
3048 {
3049 	return ip->i_mount->m_always_cow && xfs_has_reflink(ip->i_mount);
3050 }
3051