xfs_inode.c 111 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
Linus Torvalds's avatar
Linus Torvalds committed
2
/*
3
 * Copyright (c) 2000-2006 Silicon Graphics, Inc.
4
 * All Rights Reserved.
Linus Torvalds's avatar
Linus Torvalds committed
5
 */
6
#include <linux/iversion.h>
7

Linus Torvalds's avatar
Linus Torvalds committed
8
#include "xfs.h"
9
#include "xfs_fs.h"
10
#include "xfs_shared.h"
11 12 13
#include "xfs_format.h"
#include "xfs_log_format.h"
#include "xfs_trans_resv.h"
Linus Torvalds's avatar
Linus Torvalds committed
14
#include "xfs_mount.h"
15
#include "xfs_defer.h"
16
#include "xfs_inode.h"
Dave Chinner's avatar
Dave Chinner committed
17 18
#include "xfs_dir2.h"
#include "xfs_attr.h"
19
#include "xfs_bit.h"
20 21
#include "xfs_trans_space.h"
#include "xfs_trans.h"
Linus Torvalds's avatar
Linus Torvalds committed
22
#include "xfs_buf_item.h"
23
#include "xfs_inode_item.h"
24
#include "xfs_iunlink_item.h"
25 26
#include "xfs_ialloc.h"
#include "xfs_bmap.h"
27
#include "xfs_bmap_util.h"
28
#include "xfs_errortag.h"
Linus Torvalds's avatar
Linus Torvalds committed
29 30
#include "xfs_error.h"
#include "xfs_quota.h"
31
#include "xfs_filestream.h"
32
#include "xfs_trace.h"
Dave Chinner's avatar
Dave Chinner committed
33
#include "xfs_icache.h"
Dave Chinner's avatar
Dave Chinner committed
34
#include "xfs_symlink.h"
35 36
#include "xfs_trans_priv.h"
#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"
Linus Torvalds's avatar
Linus Torvalds committed
43

44
struct kmem_cache *xfs_inode_cache;
Linus Torvalds's avatar
Linus Torvalds committed
45

46 47 48 49 50 51 52
/*
 * helper function to extract extent size hint from inode
 */
xfs_extlen_t
xfs_get_extsz_hint(
	struct xfs_inode	*ip)
{
53 54 55 56 57 58
	/*
	 * No point in aligning allocations if we need to COW to actually
	 * write to them.
	 */
	if (xfs_is_always_cow_inode(ip))
		return 0;
59
	if ((ip->i_diflags & XFS_DIFLAG_EXTSIZE) && ip->i_extsize)
60
		return ip->i_extsize;
61 62 63 64 65
	if (XFS_IS_REALTIME_INODE(ip))
		return ip->i_mount->m_sb.sb_rextsize;
	return 0;
}

66 67 68
/*
 * Helper function to extract CoW extent size hint from inode.
 * Between the extent size hint and the CoW extent size hint, we
69 70
 * return the greater of the two.  If the value is zero (automatic),
 * use the default size.
71 72 73 74 75 76 77 78
 */
xfs_extlen_t
xfs_get_cowextsz_hint(
	struct xfs_inode	*ip)
{
	xfs_extlen_t		a, b;

	a = 0;
79
	if (ip->i_diflags2 & XFS_DIFLAG2_COWEXTSIZE)
80
		a = ip->i_cowextsize;
81 82
	b = xfs_get_extsz_hint(ip);

83 84 85 86
	a = max(a, b);
	if (a == 0)
		return XFS_DEFAULT_COWEXTSZ_HINT;
	return a;
87 88
}

89
/*
90 91 92 93 94 95 96 97 98 99
 * These two are wrapper routines around the xfs_ilock() routine used to
 * centralize some grungy code.  They are used in places that wish to lock the
 * inode solely for reading the extents.  The reason these places can't just
 * call xfs_ilock(ip, XFS_ILOCK_SHARED) is that the inode lock also guards to
 * bringing in of the extents from disk for a file in b-tree format.  If the
 * inode is in b-tree format, then we need to lock the inode exclusively until
 * the extents are read in.  Locking it exclusively all the time would limit
 * our parallelism unnecessarily, though.  What we do instead is check to see
 * if the extents have been read in yet, and only lock the inode exclusively
 * if they have not.
100
 *
101
 * The functions return a value which should be given to the corresponding
102
 * xfs_iunlock() call.
103 104
 */
uint
105 106
xfs_ilock_data_map_shared(
	struct xfs_inode	*ip)
107
{
108
	uint			lock_mode = XFS_ILOCK_SHARED;
109

110
	if (xfs_need_iread_extents(&ip->i_df))
111 112 113 114 115
		lock_mode = XFS_ILOCK_EXCL;
	xfs_ilock(ip, lock_mode);
	return lock_mode;
}

116 117 118
uint
xfs_ilock_attr_map_shared(
	struct xfs_inode	*ip)
119
{
120 121
	uint			lock_mode = XFS_ILOCK_SHARED;

122
	if (xfs_inode_has_attr_fork(ip) && xfs_need_iread_extents(&ip->i_af))
123 124 125
		lock_mode = XFS_ILOCK_EXCL;
	xfs_ilock(ip, lock_mode);
	return lock_mode;
126 127
}

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
/*
 * You can't set both SHARED and EXCL for the same lock,
 * and only XFS_IOLOCK_SHARED, XFS_IOLOCK_EXCL, XFS_MMAPLOCK_SHARED,
 * XFS_MMAPLOCK_EXCL, XFS_ILOCK_SHARED, XFS_ILOCK_EXCL are valid values
 * to set in lock_flags.
 */
static inline void
xfs_lock_flags_assert(
	uint		lock_flags)
{
	ASSERT((lock_flags & (XFS_IOLOCK_SHARED | XFS_IOLOCK_EXCL)) !=
		(XFS_IOLOCK_SHARED | XFS_IOLOCK_EXCL));
	ASSERT((lock_flags & (XFS_MMAPLOCK_SHARED | XFS_MMAPLOCK_EXCL)) !=
		(XFS_MMAPLOCK_SHARED | XFS_MMAPLOCK_EXCL));
	ASSERT((lock_flags & (XFS_ILOCK_SHARED | XFS_ILOCK_EXCL)) !=
		(XFS_ILOCK_SHARED | XFS_ILOCK_EXCL));
	ASSERT((lock_flags & ~(XFS_LOCK_MASK | XFS_LOCK_SUBCLASS_MASK)) == 0);
	ASSERT(lock_flags != 0);
}

148
/*
149
 * In addition to i_rwsem in the VFS inode, the xfs inode contains 2
150
 * multi-reader locks: invalidate_lock and the i_lock.  This routine allows
151
 * various combinations of the locks to be obtained.
152
 *
153 154
 * The 3 locks should always be ordered so that the IO lock is obtained first,
 * the mmap lock second and the ilock last in order to prevent deadlock.
155
 *
156 157
 * Basic locking order:
 *
158
 * i_rwsem -> invalidate_lock -> page_lock -> i_ilock
159
 *
160
 * mmap_lock locking order:
161
 *
162
 * i_rwsem -> page lock -> mmap_lock
163
 * mmap_lock -> invalidate_lock -> page_lock
164
 *
165
 * The difference in mmap_lock locking order mean that we cannot hold the
166 167 168 169 170
 * invalidate_lock over syscall based read(2)/write(2) based IO. These IO paths
 * can fault in pages during copy in/out (for buffered IO) or require the
 * mmap_lock in get_user_pages() to map the user pages into the kernel address
 * space for direct IO. Similarly the i_rwsem cannot be taken inside a page
 * fault because page faults already hold the mmap_lock.
171 172
 *
 * Hence to serialise fully against both syscall and mmap based IO, we need to
173 174
 * take both the i_rwsem and the invalidate_lock. These locks should *only* be
 * both taken in places where we need to invalidate the page cache in a race
175 176
 * free manner (e.g. truncate, hole punch and other extent manipulation
 * functions).
177 178 179 180 181 182 183 184
 */
void
xfs_ilock(
	xfs_inode_t		*ip,
	uint			lock_flags)
{
	trace_xfs_ilock(ip, lock_flags, _RET_IP_);

185
	xfs_lock_flags_assert(lock_flags);
186

187 188 189 190 191 192 193
	if (lock_flags & XFS_IOLOCK_EXCL) {
		down_write_nested(&VFS_I(ip)->i_rwsem,
				  XFS_IOLOCK_DEP(lock_flags));
	} else if (lock_flags & XFS_IOLOCK_SHARED) {
		down_read_nested(&VFS_I(ip)->i_rwsem,
				 XFS_IOLOCK_DEP(lock_flags));
	}
194

195 196 197 198 199 200 201
	if (lock_flags & XFS_MMAPLOCK_EXCL) {
		down_write_nested(&VFS_I(ip)->i_mapping->invalidate_lock,
				  XFS_MMAPLOCK_DEP(lock_flags));
	} else if (lock_flags & XFS_MMAPLOCK_SHARED) {
		down_read_nested(&VFS_I(ip)->i_mapping->invalidate_lock,
				 XFS_MMAPLOCK_DEP(lock_flags));
	}
202

203
	if (lock_flags & XFS_ILOCK_EXCL)
204
		down_write_nested(&ip->i_lock, XFS_ILOCK_DEP(lock_flags));
205
	else if (lock_flags & XFS_ILOCK_SHARED)
206
		down_read_nested(&ip->i_lock, XFS_ILOCK_DEP(lock_flags));
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
}

/*
 * This is just like xfs_ilock(), except that the caller
 * is guaranteed not to sleep.  It returns 1 if it gets
 * the requested locks and 0 otherwise.  If the IO lock is
 * obtained but the inode lock cannot be, then the IO lock
 * is dropped before returning.
 *
 * ip -- the inode being locked
 * lock_flags -- this parameter indicates the inode's locks to be
 *       to be locked.  See the comment for xfs_ilock() for a list
 *	 of valid values.
 */
int
xfs_ilock_nowait(
	xfs_inode_t		*ip,
	uint			lock_flags)
{
	trace_xfs_ilock_nowait(ip, lock_flags, _RET_IP_);

228
	xfs_lock_flags_assert(lock_flags);
229 230

	if (lock_flags & XFS_IOLOCK_EXCL) {
231
		if (!down_write_trylock(&VFS_I(ip)->i_rwsem))
232 233
			goto out;
	} else if (lock_flags & XFS_IOLOCK_SHARED) {
234
		if (!down_read_trylock(&VFS_I(ip)->i_rwsem))
235 236
			goto out;
	}
237 238

	if (lock_flags & XFS_MMAPLOCK_EXCL) {
239
		if (!down_write_trylock(&VFS_I(ip)->i_mapping->invalidate_lock))
240 241
			goto out_undo_iolock;
	} else if (lock_flags & XFS_MMAPLOCK_SHARED) {
242
		if (!down_read_trylock(&VFS_I(ip)->i_mapping->invalidate_lock))
243 244 245
			goto out_undo_iolock;
	}

246
	if (lock_flags & XFS_ILOCK_EXCL) {
247
		if (!down_write_trylock(&ip->i_lock))
248
			goto out_undo_mmaplock;
249
	} else if (lock_flags & XFS_ILOCK_SHARED) {
250
		if (!down_read_trylock(&ip->i_lock))
251
			goto out_undo_mmaplock;
252 253 254
	}
	return 1;

255 256
out_undo_mmaplock:
	if (lock_flags & XFS_MMAPLOCK_EXCL)
257
		up_write(&VFS_I(ip)->i_mapping->invalidate_lock);
258
	else if (lock_flags & XFS_MMAPLOCK_SHARED)
259
		up_read(&VFS_I(ip)->i_mapping->invalidate_lock);
260
out_undo_iolock:
261
	if (lock_flags & XFS_IOLOCK_EXCL)
262
		up_write(&VFS_I(ip)->i_rwsem);
263
	else if (lock_flags & XFS_IOLOCK_SHARED)
264
		up_read(&VFS_I(ip)->i_rwsem);
265
out:
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
	return 0;
}

/*
 * xfs_iunlock() is used to drop the inode locks acquired with
 * xfs_ilock() and xfs_ilock_nowait().  The caller must pass
 * in the flags given to xfs_ilock() or xfs_ilock_nowait() so
 * that we know which locks to drop.
 *
 * ip -- the inode being unlocked
 * lock_flags -- this parameter indicates the inode's locks to be
 *       to be unlocked.  See the comment for xfs_ilock() for a list
 *	 of valid values for this parameter.
 *
 */
void
xfs_iunlock(
	xfs_inode_t		*ip,
	uint			lock_flags)
{
286
	xfs_lock_flags_assert(lock_flags);
287 288

	if (lock_flags & XFS_IOLOCK_EXCL)
289
		up_write(&VFS_I(ip)->i_rwsem);
290
	else if (lock_flags & XFS_IOLOCK_SHARED)
291
		up_read(&VFS_I(ip)->i_rwsem);
292

293
	if (lock_flags & XFS_MMAPLOCK_EXCL)
294
		up_write(&VFS_I(ip)->i_mapping->invalidate_lock);
295
	else if (lock_flags & XFS_MMAPLOCK_SHARED)
296
		up_read(&VFS_I(ip)->i_mapping->invalidate_lock);
297

298
	if (lock_flags & XFS_ILOCK_EXCL)
299
		up_write(&ip->i_lock);
300
	else if (lock_flags & XFS_ILOCK_SHARED)
301
		up_read(&ip->i_lock);
302 303 304 305 306 307 308 309 310 311 312 313 314

	trace_xfs_iunlock(ip, lock_flags, _RET_IP_);
}

/*
 * give up write locks.  the i/o lock cannot be held nested
 * if it is being demoted.
 */
void
xfs_ilock_demote(
	xfs_inode_t		*ip,
	uint			lock_flags)
{
315 316 317
	ASSERT(lock_flags & (XFS_IOLOCK_EXCL|XFS_MMAPLOCK_EXCL|XFS_ILOCK_EXCL));
	ASSERT((lock_flags &
		~(XFS_IOLOCK_EXCL|XFS_MMAPLOCK_EXCL|XFS_ILOCK_EXCL)) == 0);
318 319

	if (lock_flags & XFS_ILOCK_EXCL)
320
		downgrade_write(&ip->i_lock);
321
	if (lock_flags & XFS_MMAPLOCK_EXCL)
322
		downgrade_write(&VFS_I(ip)->i_mapping->invalidate_lock);
323
	if (lock_flags & XFS_IOLOCK_EXCL)
324
		downgrade_write(&VFS_I(ip)->i_rwsem);
325 326 327 328

	trace_xfs_ilock_demote(ip, lock_flags, _RET_IP_);
}

329 330
void
xfs_assert_ilocked(
331
	struct xfs_inode	*ip,
332 333
	uint			lock_flags)
{
334 335 336 337
	/*
	 * Sometimes we assert the ILOCK is held exclusively, but we're in
	 * a workqueue, so lockdep doesn't know we're the owner.
	 */
338
	if (lock_flags & XFS_ILOCK_SHARED)
339
		rwsem_assert_held(&ip->i_lock);
340
	else if (lock_flags & XFS_ILOCK_EXCL)
341
		rwsem_assert_held_write_nolockdep(&ip->i_lock);
342 343 344 345 346 347 348 349 350 351

	if (lock_flags & XFS_MMAPLOCK_SHARED)
		rwsem_assert_held(&VFS_I(ip)->i_mapping->invalidate_lock);
	else if (lock_flags & XFS_MMAPLOCK_EXCL)
		rwsem_assert_held_write(&VFS_I(ip)->i_mapping->invalidate_lock);

	if (lock_flags & XFS_IOLOCK_SHARED)
		rwsem_assert_held(&VFS_I(ip)->i_rwsem);
	else if (lock_flags & XFS_IOLOCK_EXCL)
		rwsem_assert_held_write(&VFS_I(ip)->i_rwsem);
352 353
}

354 355 356 357 358 359 360
/*
 * xfs_lockdep_subclass_ok() is only used in an ASSERT, so is only called when
 * DEBUG or XFS_WARN is set. And MAX_LOCKDEP_SUBCLASSES is then only defined
 * when CONFIG_LOCKDEP is set. Hence the complex define below to avoid build
 * errors and warnings.
 */
#if (defined(DEBUG) || defined(XFS_WARN)) && defined(CONFIG_LOCKDEP)
361 362 363 364 365 366 367 368 369 370
static bool
xfs_lockdep_subclass_ok(
	int subclass)
{
	return subclass < MAX_LOCKDEP_SUBCLASSES;
}
#else
#define xfs_lockdep_subclass_ok(subclass)	(true)
#endif

Dave Chinner's avatar
Dave Chinner committed
371
/*
372
 * Bump the subclass so xfs_lock_inodes() acquires each lock with a different
373 374 375
 * value. This can be called for any type of inode lock combination, including
 * parent locking. Care must be taken to ensure we don't overrun the subclass
 * storage fields in the class mask we build.
Dave Chinner's avatar
Dave Chinner committed
376
 */
377 378 379 380
static inline uint
xfs_lock_inumorder(
	uint	lock_mode,
	uint	subclass)
Dave Chinner's avatar
Dave Chinner committed
381
{
382
	uint	class = 0;
383 384 385

	ASSERT(!(lock_mode & (XFS_ILOCK_PARENT | XFS_ILOCK_RTBITMAP |
			      XFS_ILOCK_RTSUM)));
386
	ASSERT(xfs_lockdep_subclass_ok(subclass));
387

388
	if (lock_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL)) {
389 390
		ASSERT(subclass <= XFS_IOLOCK_MAX_SUBCLASS);
		class += subclass << XFS_IOLOCK_SHIFT;
391 392 393
	}

	if (lock_mode & (XFS_MMAPLOCK_SHARED|XFS_MMAPLOCK_EXCL)) {
394 395
		ASSERT(subclass <= XFS_MMAPLOCK_MAX_SUBCLASS);
		class += subclass << XFS_MMAPLOCK_SHIFT;
396 397
	}

398 399 400 401
	if (lock_mode & (XFS_ILOCK_SHARED|XFS_ILOCK_EXCL)) {
		ASSERT(subclass <= XFS_ILOCK_MAX_SUBCLASS);
		class += subclass << XFS_ILOCK_SHIFT;
	}
Dave Chinner's avatar
Dave Chinner committed
402

403
	return (lock_mode & ~XFS_LOCK_SUBCLASS_MASK) | class;
Dave Chinner's avatar
Dave Chinner committed
404 405 406
}

/*
407 408
 * The following routine will lock n inodes in exclusive mode.  We assume the
 * caller calls us with the inodes in i_ino order.
Dave Chinner's avatar
Dave Chinner committed
409
 *
410 411 412 413 414
 * We need to detect deadlock where an inode that we lock is in the AIL and we
 * start waiting for another inode that is locked by a thread in a long running
 * transaction (such as truncate). This can result in deadlock since the long
 * running trans might need to wait for the inode we just locked in order to
 * push the tail and free space in the log.
415 416 417 418 419
 *
 * xfs_lock_inodes() can only be used to lock one type of lock at a time -
 * the iolock, the mmaplock or the ilock, but not more than one at a time. If we
 * lock more than one at a time, lockdep will report false positives saying we
 * have violated locking orders.
Dave Chinner's avatar
Dave Chinner committed
420
 */
421
void
Dave Chinner's avatar
Dave Chinner committed
422
xfs_lock_inodes(
423 424 425
	struct xfs_inode	**ips,
	int			inodes,
	uint			lock_mode)
Dave Chinner's avatar
Dave Chinner committed
426
{
427 428 429 430
	int			attempts = 0;
	uint			i;
	int			j;
	bool			try_lock;
431
	struct xfs_log_item	*lp;
Dave Chinner's avatar
Dave Chinner committed
432

433 434 435
	/*
	 * Currently supports between 2 and 5 inodes with exclusive locking.  We
	 * support an arbitrary depth of locking here, but absolute limits on
436
	 * inodes depend on the type of locking and the limits placed by
437 438 439
	 * lockdep annotations in xfs_lock_inumorder.  These are all checked by
	 * the asserts.
	 */
440
	ASSERT(ips && inodes >= 2 && inodes <= 5);
441 442 443 444 445 446 447 448 449 450 451 452 453
	ASSERT(lock_mode & (XFS_IOLOCK_EXCL | XFS_MMAPLOCK_EXCL |
			    XFS_ILOCK_EXCL));
	ASSERT(!(lock_mode & (XFS_IOLOCK_SHARED | XFS_MMAPLOCK_SHARED |
			      XFS_ILOCK_SHARED)));
	ASSERT(!(lock_mode & XFS_MMAPLOCK_EXCL) ||
		inodes <= XFS_MMAPLOCK_MAX_SUBCLASS + 1);
	ASSERT(!(lock_mode & XFS_ILOCK_EXCL) ||
		inodes <= XFS_ILOCK_MAX_SUBCLASS + 1);

	if (lock_mode & XFS_IOLOCK_EXCL) {
		ASSERT(!(lock_mode & (XFS_MMAPLOCK_EXCL | XFS_ILOCK_EXCL)));
	} else if (lock_mode & XFS_MMAPLOCK_EXCL)
		ASSERT(!(lock_mode & XFS_ILOCK_EXCL));
Dave Chinner's avatar
Dave Chinner committed
454 455

again:
456 457
	try_lock = false;
	i = 0;
Dave Chinner's avatar
Dave Chinner committed
458 459 460
	for (; i < inodes; i++) {
		ASSERT(ips[i]);

461
		if (i && (ips[i] == ips[i - 1]))	/* Already locked */
Dave Chinner's avatar
Dave Chinner committed
462 463 464
			continue;

		/*
465 466
		 * If try_lock is not set yet, make sure all locked inodes are
		 * not in the AIL.  If any are, set try_lock to be used later.
Dave Chinner's avatar
Dave Chinner committed
467 468 469
		 */
		if (!try_lock) {
			for (j = (i - 1); j >= 0 && !try_lock; j--) {
470
				lp = &ips[j]->i_itemp->ili_item;
471
				if (lp && test_bit(XFS_LI_IN_AIL, &lp->li_flags))
472
					try_lock = true;
Dave Chinner's avatar
Dave Chinner committed
473 474 475 476 477 478 479 480 481
			}
		}

		/*
		 * If any of the previous locks we have locked is in the AIL,
		 * we must TRY to get the second and subsequent locks. If
		 * we can't get any, we must release all we have
		 * and try again.
		 */
482 483 484 485 486 487 488 489 490
		if (!try_lock) {
			xfs_ilock(ips[i], xfs_lock_inumorder(lock_mode, i));
			continue;
		}

		/* try_lock means we have an inode locked that is in the AIL. */
		ASSERT(i != 0);
		if (xfs_ilock_nowait(ips[i], xfs_lock_inumorder(lock_mode, i)))
			continue;
Dave Chinner's avatar
Dave Chinner committed
491

492 493 494 495 496 497
		/*
		 * Unlock all previous guys and try again.  xfs_iunlock will try
		 * to push the tail if the inode is in the AIL.
		 */
		attempts++;
		for (j = i - 1; j >= 0; j--) {
Dave Chinner's avatar
Dave Chinner committed
498
			/*
499 500 501
			 * Check to see if we've already unlocked this one.  Not
			 * the first one going back, and the inode ptr is the
			 * same.
Dave Chinner's avatar
Dave Chinner committed
502
			 */
503 504
			if (j != (i - 1) && ips[j] == ips[j + 1])
				continue;
Dave Chinner's avatar
Dave Chinner committed
505

506 507
			xfs_iunlock(ips[j], lock_mode);
		}
Dave Chinner's avatar
Dave Chinner committed
508

509 510
		if ((attempts % 5) == 0) {
			delay(1); /* Don't just spin the CPU */
Dave Chinner's avatar
Dave Chinner committed
511
		}
512
		goto again;
Dave Chinner's avatar
Dave Chinner committed
513 514 515 516
	}
}

/*
517 518 519 520
 * xfs_lock_two_inodes() can only be used to lock ilock. The iolock and
 * mmaplock must be double-locked separately since we use i_rwsem and
 * invalidate_lock for that. We now support taking one lock EXCL and the
 * other SHARED.
Dave Chinner's avatar
Dave Chinner committed
521 522 523
 */
void
xfs_lock_two_inodes(
524 525 526 527
	struct xfs_inode	*ip0,
	uint			ip0_mode,
	struct xfs_inode	*ip1,
	uint			ip1_mode)
Dave Chinner's avatar
Dave Chinner committed
528 529
{
	int			attempts = 0;
530
	struct xfs_log_item	*lp;
Dave Chinner's avatar
Dave Chinner committed
531

532 533 534 535
	ASSERT(hweight32(ip0_mode) == 1);
	ASSERT(hweight32(ip1_mode) == 1);
	ASSERT(!(ip0_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL)));
	ASSERT(!(ip1_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL)));
536 537
	ASSERT(!(ip0_mode & (XFS_MMAPLOCK_SHARED|XFS_MMAPLOCK_EXCL)));
	ASSERT(!(ip1_mode & (XFS_MMAPLOCK_SHARED|XFS_MMAPLOCK_EXCL)));
Dave Chinner's avatar
Dave Chinner committed
538 539 540
	ASSERT(ip0->i_ino != ip1->i_ino);

	if (ip0->i_ino > ip1->i_ino) {
541 542
		swap(ip0, ip1);
		swap(ip0_mode, ip1_mode);
Dave Chinner's avatar
Dave Chinner committed
543 544 545
	}

 again:
546
	xfs_ilock(ip0, xfs_lock_inumorder(ip0_mode, 0));
Dave Chinner's avatar
Dave Chinner committed
547 548 549 550 551 552

	/*
	 * If the first lock we have locked is in the AIL, we must TRY to get
	 * the second lock. If we can't get it, we must release the first one
	 * and try again.
	 */
553
	lp = &ip0->i_itemp->ili_item;
554
	if (lp && test_bit(XFS_LI_IN_AIL, &lp->li_flags)) {
555 556
		if (!xfs_ilock_nowait(ip1, xfs_lock_inumorder(ip1_mode, 1))) {
			xfs_iunlock(ip0, ip0_mode);
Dave Chinner's avatar
Dave Chinner committed
557 558 559 560 561
			if ((++attempts % 5) == 0)
				delay(1); /* Don't just spin the CPU */
			goto again;
		}
	} else {
562
		xfs_ilock(ip1, xfs_lock_inumorder(ip1_mode, 1));
Dave Chinner's avatar
Dave Chinner committed
563 564 565
	}
}

566 567 568
uint
xfs_ip2xflags(
	struct xfs_inode	*ip)
Linus Torvalds's avatar
Linus Torvalds committed
569 570 571
{
	uint			flags = 0;

572 573
	if (ip->i_diflags & XFS_DIFLAG_ANY) {
		if (ip->i_diflags & XFS_DIFLAG_REALTIME)
574
			flags |= FS_XFLAG_REALTIME;
575
		if (ip->i_diflags & XFS_DIFLAG_PREALLOC)
576
			flags |= FS_XFLAG_PREALLOC;
577
		if (ip->i_diflags & XFS_DIFLAG_IMMUTABLE)
578
			flags |= FS_XFLAG_IMMUTABLE;
579
		if (ip->i_diflags & XFS_DIFLAG_APPEND)
580
			flags |= FS_XFLAG_APPEND;
581
		if (ip->i_diflags & XFS_DIFLAG_SYNC)
582
			flags |= FS_XFLAG_SYNC;
583
		if (ip->i_diflags & XFS_DIFLAG_NOATIME)
584
			flags |= FS_XFLAG_NOATIME;
585
		if (ip->i_diflags & XFS_DIFLAG_NODUMP)
586
			flags |= FS_XFLAG_NODUMP;
587
		if (ip->i_diflags & XFS_DIFLAG_RTINHERIT)
588
			flags |= FS_XFLAG_RTINHERIT;
589
		if (ip->i_diflags & XFS_DIFLAG_PROJINHERIT)
590
			flags |= FS_XFLAG_PROJINHERIT;
591
		if (ip->i_diflags & XFS_DIFLAG_NOSYMLINKS)
592
			flags |= FS_XFLAG_NOSYMLINKS;
593
		if (ip->i_diflags & XFS_DIFLAG_EXTSIZE)
594
			flags |= FS_XFLAG_EXTSIZE;
595
		if (ip->i_diflags & XFS_DIFLAG_EXTSZINHERIT)
596
			flags |= FS_XFLAG_EXTSZINHERIT;
597
		if (ip->i_diflags & XFS_DIFLAG_NODEFRAG)
598
			flags |= FS_XFLAG_NODEFRAG;
599
		if (ip->i_diflags & XFS_DIFLAG_FILESTREAM)
600
			flags |= FS_XFLAG_FILESTREAM;
Linus Torvalds's avatar
Linus Torvalds committed
601 602
	}

603 604
	if (ip->i_diflags2 & XFS_DIFLAG2_ANY) {
		if (ip->i_diflags2 & XFS_DIFLAG2_DAX)
605
			flags |= FS_XFLAG_DAX;
606
		if (ip->i_diflags2 & XFS_DIFLAG2_COWEXTSIZE)
607
			flags |= FS_XFLAG_COWEXTSIZE;
608 609
	}

610
	if (xfs_inode_has_attr_fork(ip))
611
		flags |= FS_XFLAG_HASATTR;
Linus Torvalds's avatar
Linus Torvalds committed
612 613 614
	return flags;
}

Dave Chinner's avatar
Dave Chinner committed
615 616 617 618 619 620 621 622
/*
 * Lookups up an inode from "name". If ci_name is not NULL, then a CI match
 * is allowed, otherwise it has to be an exact match. If a CI match is found,
 * ci_name->name will point to a the actual name (caller must free) or
 * will be set to NULL if an exact match is found.
 */
int
xfs_lookup(
623 624 625
	struct xfs_inode	*dp,
	const struct xfs_name	*name,
	struct xfs_inode	**ipp,
Dave Chinner's avatar
Dave Chinner committed
626 627 628 629 630 631 632
	struct xfs_name		*ci_name)
{
	xfs_ino_t		inum;
	int			error;

	trace_xfs_lookup(dp, name);

633
	if (xfs_is_shutdown(dp->i_mount))
634
		return -EIO;
635 636
	if (xfs_ifork_zapped(dp, XFS_DATA_FORK))
		return -EIO;
Dave Chinner's avatar
Dave Chinner committed
637 638 639

	error = xfs_dir_lookup(NULL, dp, name, &inum, ci_name);
	if (error)
640
		goto out_unlock;
Dave Chinner's avatar
Dave Chinner committed
641 642 643 644 645 646 647 648 649

	error = xfs_iget(dp->i_mount, NULL, inum, 0, 0, ipp);
	if (error)
		goto out_free_name;

	return 0;

out_free_name:
	if (ci_name)
650
		kfree(ci_name->name);
651
out_unlock:
Dave Chinner's avatar
Dave Chinner committed
652 653 654 655
	*ipp = NULL;
	return error;
}

656 657 658 659 660 661 662
/* Propagate di_flags from a parent inode to a child inode. */
static void
xfs_inode_inherit_flags(
	struct xfs_inode	*ip,
	const struct xfs_inode	*pip)
{
	unsigned int		di_flags = 0;
663
	xfs_failaddr_t		failaddr;
664 665 666
	umode_t			mode = VFS_I(ip)->i_mode;

	if (S_ISDIR(mode)) {
667
		if (pip->i_diflags & XFS_DIFLAG_RTINHERIT)
668
			di_flags |= XFS_DIFLAG_RTINHERIT;
669
		if (pip->i_diflags & XFS_DIFLAG_EXTSZINHERIT) {
670
			di_flags |= XFS_DIFLAG_EXTSZINHERIT;
671
			ip->i_extsize = pip->i_extsize;
672
		}
673
		if (pip->i_diflags & XFS_DIFLAG_PROJINHERIT)
674 675
			di_flags |= XFS_DIFLAG_PROJINHERIT;
	} else if (S_ISREG(mode)) {
676
		if ((pip->i_diflags & XFS_DIFLAG_RTINHERIT) &&
677
		    xfs_has_realtime(ip->i_mount))
678
			di_flags |= XFS_DIFLAG_REALTIME;
679
		if (pip->i_diflags & XFS_DIFLAG_EXTSZINHERIT) {
680
			di_flags |= XFS_DIFLAG_EXTSIZE;
681
			ip->i_extsize = pip->i_extsize;
682 683
		}
	}
684
	if ((pip->i_diflags & XFS_DIFLAG_NOATIME) &&
685 686
	    xfs_inherit_noatime)
		di_flags |= XFS_DIFLAG_NOATIME;
687
	if ((pip->i_diflags & XFS_DIFLAG_NODUMP) &&
688 689
	    xfs_inherit_nodump)
		di_flags |= XFS_DIFLAG_NODUMP;
690
	if ((pip->i_diflags & XFS_DIFLAG_SYNC) &&
691 692
	    xfs_inherit_sync)
		di_flags |= XFS_DIFLAG_SYNC;
693
	if ((pip->i_diflags & XFS_DIFLAG_NOSYMLINKS) &&
694 695
	    xfs_inherit_nosymlinks)
		di_flags |= XFS_DIFLAG_NOSYMLINKS;
696
	if ((pip->i_diflags & XFS_DIFLAG_NODEFRAG) &&
697 698
	    xfs_inherit_nodefrag)
		di_flags |= XFS_DIFLAG_NODEFRAG;
699
	if (pip->i_diflags & XFS_DIFLAG_FILESTREAM)
700 701
		di_flags |= XFS_DIFLAG_FILESTREAM;

702
	ip->i_diflags |= di_flags;
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720

	/*
	 * Inode verifiers on older kernels only check that the extent size
	 * hint is an integer multiple of the rt extent size on realtime files.
	 * They did not check the hint alignment on a directory with both
	 * rtinherit and extszinherit flags set.  If the misaligned hint is
	 * propagated from a directory into a new realtime file, new file
	 * allocations will fail due to math errors in the rt allocator and/or
	 * trip the verifiers.  Validate the hint settings in the new file so
	 * that we don't let broken hints propagate.
	 */
	failaddr = xfs_inode_validate_extsize(ip->i_mount, ip->i_extsize,
			VFS_I(ip)->i_mode, ip->i_diflags);
	if (failaddr) {
		ip->i_diflags &= ~(XFS_DIFLAG_EXTSIZE |
				   XFS_DIFLAG_EXTSZINHERIT);
		ip->i_extsize = 0;
	}
721 722 723 724 725 726 727 728
}

/* Propagate di_flags2 from a parent inode to a child inode. */
static void
xfs_inode_inherit_flags2(
	struct xfs_inode	*ip,
	const struct xfs_inode	*pip)
{
729 730
	xfs_failaddr_t		failaddr;

731 732
	if (pip->i_diflags2 & XFS_DIFLAG2_COWEXTSIZE) {
		ip->i_diflags2 |= XFS_DIFLAG2_COWEXTSIZE;
733
		ip->i_cowextsize = pip->i_cowextsize;
734
	}
735 736
	if (pip->i_diflags2 & XFS_DIFLAG2_DAX)
		ip->i_diflags2 |= XFS_DIFLAG2_DAX;
737 738 739 740 741 742 743 744

	/* Don't let invalid cowextsize hints propagate. */
	failaddr = xfs_inode_validate_cowextsize(ip->i_mount, ip->i_cowextsize,
			VFS_I(ip)->i_mode, ip->i_diflags, ip->i_diflags2);
	if (failaddr) {
		ip->i_diflags2 &= ~XFS_DIFLAG2_COWEXTSIZE;
		ip->i_cowextsize = 0;
	}
745 746
}

Linus Torvalds's avatar
Linus Torvalds committed
747
/*
748 749
 * Initialise a newly allocated inode and return the in-core inode to the
 * caller locked exclusively.
Linus Torvalds's avatar
Linus Torvalds committed
750
 */
751
int
752
xfs_init_new_inode(
753
	struct mnt_idmap	*idmap,
754 755 756 757 758 759 760
	struct xfs_trans	*tp,
	struct xfs_inode	*pip,
	xfs_ino_t		ino,
	umode_t			mode,
	xfs_nlink_t		nlink,
	dev_t			rdev,
	prid_t			prid,
761
	bool			init_xattrs,
762
	struct xfs_inode	**ipp)
Linus Torvalds's avatar
Linus Torvalds committed
763
{
764
	struct inode		*dir = pip ? VFS_I(pip) : NULL;
765 766 767 768 769 770
	struct xfs_mount	*mp = tp->t_mountp;
	struct xfs_inode	*ip;
	unsigned int		flags;
	int			error;
	struct timespec64	tv;
	struct inode		*inode;
Linus Torvalds's avatar
Linus Torvalds committed
771

772 773 774 775 776 777 778 779 780
	/*
	 * Protect against obviously corrupt allocation btree records. Later
	 * xfs_iget checks will catch re-allocation of other active in-memory
	 * and on-disk inodes. If we don't catch reallocating the parent inode
	 * here we will deadlock in xfs_iget() so we have to do these checks
	 * first.
	 */
	if ((pip && ino == pip->i_ino) || !xfs_verify_dir_ino(mp, ino)) {
		xfs_alert(mp, "Allocated a known in-use inode 0x%llx!", ino);
781 782
		xfs_agno_mark_sick(mp, XFS_INO_TO_AGNO(mp, ino),
				XFS_SICK_AG_INOBT);
783 784 785
		return -EFSCORRUPTED;
	}

Linus Torvalds's avatar
Linus Torvalds committed
786
	/*
787 788
	 * Get the in-core inode with the lock held exclusively to prevent
	 * others from looking at until we're done.
Linus Torvalds's avatar
Linus Torvalds committed
789
	 */
790
	error = xfs_iget(mp, tp, ino, XFS_IGET_CREATE, XFS_ILOCK_EXCL, &ip);
791
	if (error)
Linus Torvalds's avatar
Linus Torvalds committed
792
		return error;
793

Linus Torvalds's avatar
Linus Torvalds committed
794
	ASSERT(ip != NULL);
795
	inode = VFS_I(ip);
796
	set_nlink(inode, nlink);
Christoph Hellwig's avatar
Christoph Hellwig committed
797
	inode->i_rdev = rdev;
798
	ip->i_projid = prid;
Linus Torvalds's avatar
Linus Torvalds committed
799

800
	if (dir && !(dir->i_mode & S_ISGID) && xfs_has_grpid(mp)) {
801
		inode_fsuid_set(inode, idmap);
802 803
		inode->i_gid = dir->i_gid;
		inode->i_mode = mode;
804
	} else {
805
		inode_init_owner(idmap, inode, dir, mode);
Linus Torvalds's avatar
Linus Torvalds committed
806 807 808 809 810 811 812
	}

	/*
	 * If the group ID of the new file does not match the effective group
	 * ID or one of the supplementary group IDs, the S_ISGID bit is cleared
	 * (and only if the irix_sgid_inherit compatibility variable is set).
	 */
813
	if (irix_sgid_inherit && (inode->i_mode & S_ISGID) &&
814
	    !vfsgid_in_group_p(i_gid_into_vfsgid(idmap, inode)))
815
		inode->i_mode &= ~S_ISGID;
Linus Torvalds's avatar
Linus Torvalds committed
816

817
	ip->i_disk_size = 0;
818
	ip->i_df.if_nextents = 0;
819
	ASSERT(ip->i_nblocks == 0);
820

821
	tv = inode_set_ctime_current(inode);
822 823
	inode_set_mtime_to_ts(inode, tv);
	inode_set_atime_to_ts(inode, tv);
824

825
	ip->i_extsize = 0;
826
	ip->i_diflags = 0;
827

828
	if (xfs_has_v3inodes(mp)) {
829
		inode_set_iversion(inode, 1);
830
		ip->i_cowextsize = 0;
831
		ip->i_crtime = tv;
832 833
	}

Linus Torvalds's avatar
Linus Torvalds committed
834 835 836 837 838 839
	flags = XFS_ILOG_CORE;
	switch (mode & S_IFMT) {
	case S_IFIFO:
	case S_IFCHR:
	case S_IFBLK:
	case S_IFSOCK:
840
		ip->i_df.if_format = XFS_DINODE_FMT_DEV;
Linus Torvalds's avatar
Linus Torvalds committed
841 842 843 844
		flags |= XFS_ILOG_DEV;
		break;
	case S_IFREG:
	case S_IFDIR:
845
		if (pip && (pip->i_diflags & XFS_DIFLAG_ANY))
846
			xfs_inode_inherit_flags(ip, pip);
847
		if (pip && (pip->i_diflags2 & XFS_DIFLAG2_ANY))
848
			xfs_inode_inherit_flags2(ip, pip);
849
		fallthrough;
Linus Torvalds's avatar
Linus Torvalds committed
850
	case S_IFLNK:
851
		ip->i_df.if_format = XFS_DINODE_FMT_EXTENTS;
852
		ip->i_df.if_bytes = 0;
853
		ip->i_df.if_data = NULL;
Linus Torvalds's avatar
Linus Torvalds committed
854 855 856 857 858
		break;
	default:
		ASSERT(0);
	}

859 860 861 862 863 864 865 866 867
	/*
	 * If we need to create attributes immediately after allocating the
	 * inode, initialise an empty attribute fork right now. We use the
	 * default fork offset for attributes here as we don't know exactly what
	 * size or how many attributes we might be adding. We can do this
	 * safely here because we know the data fork is completely empty and
	 * this saves us from needing to run a separate transaction to set the
	 * fork offset in the immediate future.
	 */
868
	if (init_xattrs && xfs_has_attr(mp)) {
869
		ip->i_forkoff = xfs_default_attroffset(ip) >> 3;
870
		xfs_ifork_init_attr(ip, XFS_DINODE_FMT_EXTENTS, 0);
871 872
	}

Linus Torvalds's avatar
Linus Torvalds committed
873 874 875
	/*
	 * Log the new values stuffed into the inode.
	 */
876
	xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
Linus Torvalds's avatar
Linus Torvalds committed
877 878
	xfs_trans_log_inode(tp, ip, flags);

879
	/* now that we have an i_mode we can setup the inode structure */
880
	xfs_setup_inode(ip);
Linus Torvalds's avatar
Linus Torvalds committed
881 882 883 884 885

	*ipp = ip;
	return 0;
}

Dave Chinner's avatar
Dave Chinner committed
886
/*
887 888 889
 * Decrement the link count on an inode & log the change.  If this causes the
 * link count to go to zero, move the inode to AGI unlinked list so that it can
 * be freed when the last active reference goes away via xfs_inactive().
Dave Chinner's avatar
Dave Chinner committed
890
 */
891
static int			/* error */
Dave Chinner's avatar
Dave Chinner committed
892
xfs_droplink(
893 894
	struct xfs_trans	*tp,
	struct xfs_inode	*ip)
Dave Chinner's avatar
Dave Chinner committed
895
{
896
	struct inode		*inode = VFS_I(ip);
897

Dave Chinner's avatar
Dave Chinner committed
898 899
	xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_CHG);

900 901 902 903 904 905 906 907 908
	if (inode->i_nlink == 0) {
		xfs_info_ratelimited(tp->t_mountp,
 "Inode 0x%llx link count dropped below zero.  Pinning link count.",
				ip->i_ino);
		set_nlink(inode, XFS_NLINK_PINNED);
	}
	if (inode->i_nlink != XFS_NLINK_PINNED)
		drop_nlink(inode);

Dave Chinner's avatar
Dave Chinner committed
909 910
	xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);

911
	if (inode->i_nlink)
912 913 914
		return 0;

	return xfs_iunlink(tp, ip);
Dave Chinner's avatar
Dave Chinner committed
915 916 917 918 919
}

/*
 * Increment the link count on an inode & log the change.
 */
920
void
Dave Chinner's avatar
Dave Chinner committed
921
xfs_bumplink(
922 923
	struct xfs_trans	*tp,
	struct xfs_inode	*ip)
Dave Chinner's avatar
Dave Chinner committed
924
{
925 926
	struct inode		*inode = VFS_I(ip);

Dave Chinner's avatar
Dave Chinner committed
927 928
	xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_CHG);

929 930 931 932 933 934 935
	if (inode->i_nlink == XFS_NLINK_PINNED - 1)
		xfs_info_ratelimited(tp->t_mountp,
 "Inode 0x%llx link count exceeded maximum.  Pinning link count.",
				ip->i_ino);
	if (inode->i_nlink != XFS_NLINK_PINNED)
		inc_nlink(inode);

Dave Chinner's avatar
Dave Chinner committed
936 937 938
	xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
}

939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
#ifdef CONFIG_XFS_LIVE_HOOKS
/*
 * Use a static key here to reduce the overhead of directory live update hooks.
 * If the compiler supports jump labels, the static branch will be replaced by
 * a nop sled when there are no hook users.  Online fsck is currently the only
 * caller, so this is a reasonable tradeoff.
 *
 * Note: Patching the kernel code requires taking the cpu hotplug lock.  Other
 * parts of the kernel allocate memory with that lock held, which means that
 * XFS callers cannot hold any locks that might be used by memory reclaim or
 * writeback when calling the static_branch_{inc,dec} functions.
 */
DEFINE_STATIC_XFS_HOOK_SWITCH(xfs_dir_hooks_switch);

void
xfs_dir_hook_disable(void)
{
	xfs_hooks_switch_off(&xfs_dir_hooks_switch);
}

void
xfs_dir_hook_enable(void)
{
	xfs_hooks_switch_on(&xfs_dir_hooks_switch);
}

/* Call hooks for a directory update relating to a child dirent update. */
inline void
xfs_dir_update_hook(
	struct xfs_inode		*dp,
	struct xfs_inode		*ip,
	int				delta,
	const struct xfs_name		*name)
{
	if (xfs_hooks_switched_on(&xfs_dir_hooks_switch)) {
		struct xfs_dir_update_params	p = {
			.dp		= dp,
			.ip		= ip,
			.delta		= delta,
			.name		= name,
		};
		struct xfs_mount	*mp = ip->i_mount;

		xfs_hooks_call(&mp->m_dir_update_hooks, 0, &p);
	}
}

/* Call the specified function during a directory update. */
int
xfs_dir_hook_add(
	struct xfs_mount	*mp,
	struct xfs_dir_hook	*hook)
{
	return xfs_hooks_add(&mp->m_dir_update_hooks, &hook->dirent_hook);
}

/* Stop calling the specified function during a directory update. */
void
xfs_dir_hook_del(
	struct xfs_mount	*mp,
	struct xfs_dir_hook	*hook)
{
	xfs_hooks_del(&mp->m_dir_update_hooks, &hook->dirent_hook);
}

/* Configure directory update hook functions. */
void
xfs_dir_hook_setup(
	struct xfs_dir_hook	*hook,
	notifier_fn_t		mod_fn)
{
	xfs_hook_setup(&hook->dirent_hook, mod_fn);
}
#endif /* CONFIG_XFS_LIVE_HOOKS */

Dave Chinner's avatar
Dave Chinner committed
1014 1015
int
xfs_create(
1016
	struct mnt_idmap	*idmap,
Dave Chinner's avatar
Dave Chinner committed
1017 1018 1019
	xfs_inode_t		*dp,
	struct xfs_name		*name,
	umode_t			mode,
Christoph Hellwig's avatar
Christoph Hellwig committed
1020
	dev_t			rdev,
1021
	bool			init_xattrs,
Dave Chinner's avatar
Dave Chinner committed
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
	xfs_inode_t		**ipp)
{
	int			is_dir = S_ISDIR(mode);
	struct xfs_mount	*mp = dp->i_mount;
	struct xfs_inode	*ip = NULL;
	struct xfs_trans	*tp = NULL;
	int			error;
	bool                    unlock_dp_on_error = false;
	prid_t			prid;
	struct xfs_dquot	*udqp = NULL;
	struct xfs_dquot	*gdqp = NULL;
	struct xfs_dquot	*pdqp = NULL;
1034
	struct xfs_trans_res	*tres;
Dave Chinner's avatar
Dave Chinner committed
1035
	uint			resblks;
1036
	xfs_ino_t		ino;
Dave Chinner's avatar
Dave Chinner committed
1037 1038 1039

	trace_xfs_create(dp, name);

1040
	if (xfs_is_shutdown(mp))
1041
		return -EIO;
1042 1043
	if (xfs_ifork_zapped(dp, XFS_DATA_FORK))
		return -EIO;
Dave Chinner's avatar
Dave Chinner committed
1044

1045
	prid = xfs_get_initial_prid(dp);
Dave Chinner's avatar
Dave Chinner committed
1046 1047 1048 1049

	/*
	 * Make sure that we have allocated dquot(s) on disk.
	 */
1050 1051
	error = xfs_qm_vop_dqalloc(dp, mapped_fsuid(idmap, &init_user_ns),
			mapped_fsgid(idmap, &init_user_ns), prid,
1052 1053
			XFS_QMOPT_QUOTALL | XFS_QMOPT_INHERIT,
			&udqp, &gdqp, &pdqp);
Dave Chinner's avatar
Dave Chinner committed
1054 1055 1056 1057 1058
	if (error)
		return error;

	if (is_dir) {
		resblks = XFS_MKDIR_SPACE_RES(mp, name->len);
1059
		tres = &M_RES(mp)->tr_mkdir;
Dave Chinner's avatar
Dave Chinner committed
1060 1061
	} else {
		resblks = XFS_CREATE_SPACE_RES(mp, name->len);
1062
		tres = &M_RES(mp)->tr_create;
Dave Chinner's avatar
Dave Chinner committed
1063 1064 1065 1066 1067 1068 1069 1070
	}

	/*
	 * Initially assume that the file does not exist and
	 * reserve the resources for that case.  If that is not
	 * the case we'll drop the one we have and get a more
	 * appropriate transaction later.
	 */
1071 1072
	error = xfs_trans_alloc_icreate(mp, tres, udqp, gdqp, pdqp, resblks,
			&tp);
1073
	if (error == -ENOSPC) {
Dave Chinner's avatar
Dave Chinner committed
1074 1075
		/* flush outstanding delalloc blocks and retry */
		xfs_flush_inodes(mp);
1076 1077
		error = xfs_trans_alloc_icreate(mp, tres, udqp, gdqp, pdqp,
				resblks, &tp);
Dave Chinner's avatar
Dave Chinner committed
1078
	}
1079
	if (error)
1080
		goto out_release_dquots;
Dave Chinner's avatar
Dave Chinner committed
1081

1082
	xfs_ilock(dp, XFS_ILOCK_EXCL | XFS_ILOCK_PARENT);
Dave Chinner's avatar
Dave Chinner committed
1083 1084 1085 1086 1087 1088 1089
	unlock_dp_on_error = true;

	/*
	 * A newly created regular or special file just has one directory
	 * entry pointing to them, but a directory also the "." entry
	 * pointing to itself.
	 */
1090 1091
	error = xfs_dialloc(&tp, dp->i_ino, mode, &ino);
	if (!error)
1092
		error = xfs_init_new_inode(idmap, tp, dp, ino, mode,
1093
				is_dir ? 2 : 1, rdev, prid, init_xattrs, &ip);
1094
	if (error)
1095
		goto out_trans_cancel;
Dave Chinner's avatar
Dave Chinner committed
1096 1097 1098

	/*
	 * Now we join the directory inode to the transaction.  We do not do it
1099
	 * earlier because xfs_dialloc might commit the previous transaction
Dave Chinner's avatar
Dave Chinner committed
1100 1101 1102 1103
	 * (and release all the locks).  An error from here on will result in
	 * the transaction cancel unlocking dp so don't do it explicitly in the
	 * error path.
	 */
1104
	xfs_trans_ijoin(tp, dp, XFS_ILOCK_EXCL);
Dave Chinner's avatar
Dave Chinner committed
1105 1106
	unlock_dp_on_error = false;

1107
	error = xfs_dir_createname(tp, dp, name, ip->i_ino,
1108
					resblks - XFS_IALLOC_SPACE_RES(mp));
Dave Chinner's avatar
Dave Chinner committed
1109
	if (error) {
1110
		ASSERT(error != -ENOSPC);
1111
		goto out_trans_cancel;
Dave Chinner's avatar
Dave Chinner committed
1112 1113 1114 1115 1116 1117 1118
	}
	xfs_trans_ichgtime(tp, dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
	xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);

	if (is_dir) {
		error = xfs_dir_init(tp, ip, dp);
		if (error)
1119
			goto out_trans_cancel;
Dave Chinner's avatar
Dave Chinner committed
1120

1121
		xfs_bumplink(tp, dp);
Dave Chinner's avatar
Dave Chinner committed
1122 1123
	}

1124 1125 1126 1127 1128 1129
	/*
	 * Create ip with a reference from dp, and add '.' and '..' references
	 * if it's a directory.
	 */
	xfs_dir_update_hook(dp, ip, 1, name);

Dave Chinner's avatar
Dave Chinner committed
1130 1131 1132 1133 1134
	/*
	 * If this is a synchronous mount, make sure that the
	 * create transaction goes to disk before returning to
	 * the user.
	 */
1135
	if (xfs_has_wsync(mp) || xfs_has_dirsync(mp))
Dave Chinner's avatar
Dave Chinner committed
1136 1137 1138 1139 1140 1141 1142 1143 1144
		xfs_trans_set_sync(tp);

	/*
	 * Attach the dquot(s) to the inodes and modify them incore.
	 * These ids of the inode couldn't have changed since the new
	 * inode has been locked ever since it was created.
	 */
	xfs_qm_vop_create_dqattach(tp, ip, udqp, gdqp, pdqp);

1145
	error = xfs_trans_commit(tp);
Dave Chinner's avatar
Dave Chinner committed
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
	if (error)
		goto out_release_inode;

	xfs_qm_dqrele(udqp);
	xfs_qm_dqrele(gdqp);
	xfs_qm_dqrele(pdqp);

	*ipp = ip;
	return 0;

 out_trans_cancel:
1157
	xfs_trans_cancel(tp);
Dave Chinner's avatar
Dave Chinner committed
1158 1159
 out_release_inode:
	/*
1160 1161 1162
	 * Wait until after the current transaction is aborted to finish the
	 * setup of the inode and release the inode.  This prevents recursive
	 * transactions and deadlocks from xfs_inactive.
Dave Chinner's avatar
Dave Chinner committed
1163
	 */
1164 1165
	if (ip) {
		xfs_finish_inode_setup(ip);
1166
		xfs_irele(ip);
1167
	}
1168
 out_release_dquots:
Dave Chinner's avatar
Dave Chinner committed
1169 1170 1171 1172 1173
	xfs_qm_dqrele(udqp);
	xfs_qm_dqrele(gdqp);
	xfs_qm_dqrele(pdqp);

	if (unlock_dp_on_error)
1174
		xfs_iunlock(dp, XFS_ILOCK_EXCL);
Dave Chinner's avatar
Dave Chinner committed
1175 1176 1177
	return error;
}

Zhi Yong Wu's avatar
Zhi Yong Wu committed
1178 1179
int
xfs_create_tmpfile(
1180
	struct mnt_idmap	*idmap,
Zhi Yong Wu's avatar
Zhi Yong Wu committed
1181
	struct xfs_inode	*dp,
1182 1183
	umode_t			mode,
	struct xfs_inode	**ipp)
Zhi Yong Wu's avatar
Zhi Yong Wu committed
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
{
	struct xfs_mount	*mp = dp->i_mount;
	struct xfs_inode	*ip = NULL;
	struct xfs_trans	*tp = NULL;
	int			error;
	prid_t                  prid;
	struct xfs_dquot	*udqp = NULL;
	struct xfs_dquot	*gdqp = NULL;
	struct xfs_dquot	*pdqp = NULL;
	struct xfs_trans_res	*tres;
	uint			resblks;
1195
	xfs_ino_t		ino;
Zhi Yong Wu's avatar
Zhi Yong Wu committed
1196

1197
	if (xfs_is_shutdown(mp))
1198
		return -EIO;
Zhi Yong Wu's avatar
Zhi Yong Wu committed
1199 1200 1201 1202 1203 1204

	prid = xfs_get_initial_prid(dp);

	/*
	 * Make sure that we have allocated dquot(s) on disk.
	 */
1205 1206
	error = xfs_qm_vop_dqalloc(dp, mapped_fsuid(idmap, &init_user_ns),
			mapped_fsgid(idmap, &init_user_ns), prid,
1207 1208
			XFS_QMOPT_QUOTALL | XFS_QMOPT_INHERIT,
			&udqp, &gdqp, &pdqp);
Zhi Yong Wu's avatar
Zhi Yong Wu committed
1209 1210 1211 1212 1213
	if (error)
		return error;

	resblks = XFS_IALLOC_SPACE_RES(mp);
	tres = &M_RES(mp)->tr_create_tmpfile;
1214

1215 1216
	error = xfs_trans_alloc_icreate(mp, tres, udqp, gdqp, pdqp, resblks,
			&tp);
Zhi Yong Wu's avatar
Zhi Yong Wu committed
1217
	if (error)
1218
		goto out_release_dquots;
Zhi Yong Wu's avatar
Zhi Yong Wu committed
1219

1220 1221
	error = xfs_dialloc(&tp, dp->i_ino, mode, &ino);
	if (!error)
1222
		error = xfs_init_new_inode(idmap, tp, dp, ino, mode,
1223
				0, 0, prid, false, &ip);
1224
	if (error)
1225
		goto out_trans_cancel;
Zhi Yong Wu's avatar
Zhi Yong Wu committed
1226

1227
	if (xfs_has_wsync(mp))
Zhi Yong Wu's avatar
Zhi Yong Wu committed
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
		xfs_trans_set_sync(tp);

	/*
	 * Attach the dquot(s) to the inodes and modify them incore.
	 * These ids of the inode couldn't have changed since the new
	 * inode has been locked ever since it was created.
	 */
	xfs_qm_vop_create_dqattach(tp, ip, udqp, gdqp, pdqp);

	error = xfs_iunlink(tp, ip);
	if (error)
1239
		goto out_trans_cancel;
Zhi Yong Wu's avatar
Zhi Yong Wu committed
1240

1241
	error = xfs_trans_commit(tp);
Zhi Yong Wu's avatar
Zhi Yong Wu committed
1242 1243 1244 1245 1246 1247 1248
	if (error)
		goto out_release_inode;

	xfs_qm_dqrele(udqp);
	xfs_qm_dqrele(gdqp);
	xfs_qm_dqrele(pdqp);

1249
	*ipp = ip;
Zhi Yong Wu's avatar
Zhi Yong Wu committed
1250 1251 1252
	return 0;

 out_trans_cancel:
1253
	xfs_trans_cancel(tp);
Zhi Yong Wu's avatar
Zhi Yong Wu committed
1254 1255
 out_release_inode:
	/*
1256 1257 1258
	 * Wait until after the current transaction is aborted to finish the
	 * setup of the inode and release the inode.  This prevents recursive
	 * transactions and deadlocks from xfs_inactive.
Zhi Yong Wu's avatar
Zhi Yong Wu committed
1259
	 */
1260 1261
	if (ip) {
		xfs_finish_inode_setup(ip);
1262
		xfs_irele(ip);
1263
	}
1264
 out_release_dquots:
Zhi Yong Wu's avatar
Zhi Yong Wu committed
1265 1266 1267 1268 1269 1270 1271
	xfs_qm_dqrele(udqp);
	xfs_qm_dqrele(gdqp);
	xfs_qm_dqrele(pdqp);

	return error;
}

Dave Chinner's avatar
Dave Chinner committed
1272 1273 1274 1275 1276 1277 1278 1279
int
xfs_link(
	xfs_inode_t		*tdp,
	xfs_inode_t		*sip,
	struct xfs_name		*target_name)
{
	xfs_mount_t		*mp = tdp->i_mount;
	xfs_trans_t		*tp;
1280
	int			error, nospace_error = 0;
Dave Chinner's avatar
Dave Chinner committed
1281 1282 1283 1284
	int			resblks;

	trace_xfs_link(tdp, target_name);

1285
	ASSERT(!S_ISDIR(VFS_I(sip)->i_mode));
Dave Chinner's avatar
Dave Chinner committed
1286

1287
	if (xfs_is_shutdown(mp))
1288
		return -EIO;
1289 1290
	if (xfs_ifork_zapped(tdp, XFS_DATA_FORK))
		return -EIO;
Dave Chinner's avatar
Dave Chinner committed
1291

1292
	error = xfs_qm_dqattach(sip);
Dave Chinner's avatar
Dave Chinner committed
1293 1294 1295
	if (error)
		goto std_return;

1296
	error = xfs_qm_dqattach(tdp);
Dave Chinner's avatar
Dave Chinner committed
1297 1298 1299 1300
	if (error)
		goto std_return;

	resblks = XFS_LINK_SPACE_RES(mp, target_name->len);
1301 1302
	error = xfs_trans_alloc_dir(tdp, &M_RES(mp)->tr_link, sip, &resblks,
			&tp, &nospace_error);
1303
	if (error)
1304
		goto std_return;
Dave Chinner's avatar
Dave Chinner committed
1305 1306 1307 1308 1309 1310

	/*
	 * If we are using project inheritance, we only allow hard link
	 * creation in our tree when the project IDs are the same; else
	 * the tree quota mechanism could be circumvented.
	 */
1311
	if (unlikely((tdp->i_diflags & XFS_DIFLAG_PROJINHERIT) &&
1312
		     tdp->i_projid != sip->i_projid)) {
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
		/*
		 * Project quota setup skips special files which can
		 * leave inodes in a PROJINHERIT directory without a
		 * project ID set. We need to allow links to be made
		 * to these "project-less" inodes because userspace
		 * expects them to succeed after project ID setup,
		 * but everything else should be rejected.
		 */
		if (!special_file(VFS_I(sip)->i_mode) ||
		    sip->i_projid != 0) {
			error = -EXDEV;
			goto error_return;
		}
Dave Chinner's avatar
Dave Chinner committed
1326 1327
	}

1328 1329 1330 1331 1332
	if (!resblks) {
		error = xfs_dir_canenter(tp, tdp, target_name);
		if (error)
			goto error_return;
	}
Dave Chinner's avatar
Dave Chinner committed
1333

1334 1335 1336 1337
	/*
	 * Handle initial link state of O_TMPFILE inode
	 */
	if (VFS_I(sip)->i_nlink == 0) {
1338 1339 1340 1341 1342
		struct xfs_perag	*pag;

		pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, sip->i_ino));
		error = xfs_iunlink_remove(tp, pag, sip);
		xfs_perag_put(pag);
1343
		if (error)
1344
			goto error_return;
1345 1346
	}

Dave Chinner's avatar
Dave Chinner committed
1347
	error = xfs_dir_createname(tp, tdp, target_name, sip->i_ino,
1348
				   resblks);
Dave Chinner's avatar
Dave Chinner committed
1349
	if (error)
1350
		goto error_return;
Dave Chinner's avatar
Dave Chinner committed
1351 1352 1353
	xfs_trans_ichgtime(tp, tdp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
	xfs_trans_log_inode(tp, tdp, XFS_ILOG_CORE);

1354
	xfs_bumplink(tp, sip);
1355
	xfs_dir_update_hook(tdp, sip, 1, target_name);
Dave Chinner's avatar
Dave Chinner committed
1356 1357 1358 1359 1360 1361

	/*
	 * If this is a synchronous mount, make sure that the
	 * link transaction goes to disk before returning to
	 * the user.
	 */
1362
	if (xfs_has_wsync(mp) || xfs_has_dirsync(mp))
Dave Chinner's avatar
Dave Chinner committed
1363 1364
		xfs_trans_set_sync(tp);

1365
	return xfs_trans_commit(tp);
Dave Chinner's avatar
Dave Chinner committed
1366 1367

 error_return:
1368
	xfs_trans_cancel(tp);
Dave Chinner's avatar
Dave Chinner committed
1369
 std_return:
1370 1371
	if (error == -ENOSPC && nospace_error)
		error = nospace_error;
Dave Chinner's avatar
Dave Chinner committed
1372 1373 1374
	return error;
}

1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
/* Clear the reflink flag and the cowblocks tag if possible. */
static void
xfs_itruncate_clear_reflink_flags(
	struct xfs_inode	*ip)
{
	struct xfs_ifork	*dfork;
	struct xfs_ifork	*cfork;

	if (!xfs_is_reflink_inode(ip))
		return;
1385 1386
	dfork = xfs_ifork_ptr(ip, XFS_DATA_FORK);
	cfork = xfs_ifork_ptr(ip, XFS_COW_FORK);
1387
	if (dfork->if_bytes == 0 && cfork->if_bytes == 0)
1388
		ip->i_diflags2 &= ~XFS_DIFLAG2_REFLINK;
1389 1390 1391 1392
	if (cfork->if_bytes == 0)
		xfs_inode_clear_cowblocks_tag(ip);
}

Linus Torvalds's avatar
Linus Torvalds committed
1393
/*
1394 1395 1396
 * Free up the underlying blocks past new_size.  The new size must be smaller
 * than the current size.  This routine can be used both for the attribute and
 * data fork, and does not modify the inode size, which is left to the caller.
Linus Torvalds's avatar
Linus Torvalds committed
1397
 *
1398 1399 1400 1401 1402 1403 1404 1405 1406
 * The transaction passed to this routine must have made a permanent log
 * reservation of at least XFS_ITRUNCATE_LOG_RES.  This routine may commit the
 * given transaction and start new ones, so make sure everything involved in
 * the transaction is tidy before calling here.  Some transaction will be
 * returned to the caller to be committed.  The incoming transaction must
 * already include the inode, and both inode locks must be held exclusively.
 * The inode must also be "held" within the transaction.  On return the inode
 * will be "held" within the returned transaction.  This routine does NOT
 * require any disk space to be reserved for it within the transaction.
Linus Torvalds's avatar
Linus Torvalds committed
1407
 *
1408 1409 1410 1411 1412
 * If we get an error, we must return with the inode locked and linked into the
 * current transaction. This keeps things simple for the higher level code,
 * because it always knows that the inode is locked and held in the transaction
 * that returns to it whether errors occur or not.  We don't mark the inode
 * dirty on error so that transactions can be easily aborted if possible.
Linus Torvalds's avatar
Linus Torvalds committed
1413 1414
 */
int
1415
xfs_itruncate_extents_flags(
1416 1417 1418
	struct xfs_trans	**tpp,
	struct xfs_inode	*ip,
	int			whichfork,
1419
	xfs_fsize_t		new_size,
1420
	int			flags)
Linus Torvalds's avatar
Linus Torvalds committed
1421
{
1422 1423 1424 1425
	struct xfs_mount	*mp = ip->i_mount;
	struct xfs_trans	*tp = *tpp;
	xfs_fileoff_t		first_unmap_block;
	int			error = 0;
Linus Torvalds's avatar
Linus Torvalds committed
1426

1427 1428 1429
	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL);
	if (atomic_read(&VFS_I(ip)->i_count))
		xfs_assert_ilocked(ip, XFS_IOLOCK_EXCL);
1430
	ASSERT(new_size <= XFS_ISIZE(ip));
1431
	ASSERT(tp->t_flags & XFS_TRANS_PERM_LOG_RES);
Linus Torvalds's avatar
Linus Torvalds committed
1432
	ASSERT(ip->i_itemp != NULL);
1433
	ASSERT(ip->i_itemp->ili_lock_flags == 0);
1434
	ASSERT(!XFS_NOT_DQATTACHED(mp, ip));
Linus Torvalds's avatar
Linus Torvalds committed
1435

1436 1437
	trace_xfs_itruncate_extents_start(ip, new_size);

1438
	flags |= xfs_bmapi_aflag(whichfork);
1439

Linus Torvalds's avatar
Linus Torvalds committed
1440 1441 1442 1443 1444
	/*
	 * Since it is possible for space to become allocated beyond
	 * the end of the file (in a crash where the space is allocated
	 * but the inode size is not yet updated), simply remove any
	 * blocks which show up between the new EOF and the maximum
1445 1446 1447 1448
	 * possible file size.
	 *
	 * We have to free all the blocks to the bmbt maximum offset, even if
	 * the page cache can't scale that far.
Linus Torvalds's avatar
Linus Torvalds committed
1449
	 */
1450
	first_unmap_block = XFS_B_TO_FSB(mp, (xfs_ufsize_t)new_size);
1451
	if (!xfs_verify_fileoff(mp, first_unmap_block)) {
1452
		WARN_ON_ONCE(first_unmap_block > XFS_MAX_FILEOFF);
1453
		return 0;
1454
	}
1455

1456 1457 1458 1459
	error = xfs_bunmapi_range(&tp, ip, flags, first_unmap_block,
			XFS_MAX_FILEOFF);
	if (error)
		goto out;
1460

1461 1462 1463
	if (whichfork == XFS_DATA_FORK) {
		/* Remove all pending CoW reservations. */
		error = xfs_reflink_cancel_cow_blocks(ip, &tp,
1464
				first_unmap_block, XFS_MAX_FILEOFF, true);
1465 1466
		if (error)
			goto out;
1467

1468 1469
		xfs_itruncate_clear_reflink_flags(ip);
	}
1470

1471 1472 1473 1474 1475 1476 1477 1478
	/*
	 * Always re-log the inode so that our permanent transaction can keep
	 * on rolling it forward in the log.
	 */
	xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);

	trace_xfs_itruncate_extents_end(ip, new_size);

1479 1480 1481 1482 1483
out:
	*tpp = tp;
	return error;
}

Dave Chinner's avatar
Dave Chinner committed
1484 1485 1486 1487 1488
int
xfs_release(
	xfs_inode_t	*ip)
{
	xfs_mount_t	*mp = ip->i_mount;
1489
	int		error = 0;
Dave Chinner's avatar
Dave Chinner committed
1490

1491
	if (!S_ISREG(VFS_I(ip)->i_mode) || (VFS_I(ip)->i_mode == 0))
Dave Chinner's avatar
Dave Chinner committed
1492 1493 1494
		return 0;

	/* If this is a read-only mount, don't do this (would generate I/O) */
1495
	if (xfs_is_readonly(mp))
Dave Chinner's avatar
Dave Chinner committed
1496 1497
		return 0;

1498
	if (!xfs_is_shutdown(mp)) {
Dave Chinner's avatar
Dave Chinner committed
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
		int truncated;

		/*
		 * If we previously truncated this file and removed old data
		 * in the process, we want to initiate "early" writeout on
		 * the last close.  This is an attempt to combat the notorious
		 * NULL files problem which is particularly noticeable from a
		 * truncate down, buffered (re-)write (delalloc), followed by
		 * a crash.  What we are effectively doing here is
		 * significantly reducing the time window where we'd otherwise
		 * be exposed to that problem.
		 */
		truncated = xfs_iflags_test_and_clear(ip, XFS_ITRUNCATED);
		if (truncated) {
			xfs_iflags_clear(ip, XFS_IDIRTY_RELEASE);
Dave Chinner's avatar
Dave Chinner committed
1514
			if (ip->i_delayed_blks > 0) {
1515
				error = filemap_flush(VFS_I(ip)->i_mapping);
Dave Chinner's avatar
Dave Chinner committed
1516 1517 1518 1519 1520 1521
				if (error)
					return error;
			}
		}
	}

1522
	if (VFS_I(ip)->i_nlink == 0)
Dave Chinner's avatar
Dave Chinner committed
1523 1524
		return 0;

1525 1526 1527 1528 1529 1530 1531 1532
	/*
	 * If we can't get the iolock just skip truncating the blocks past EOF
	 * because we could deadlock with the mmap_lock otherwise. We'll get
	 * another chance to drop them once the last reference to the inode is
	 * dropped, so we'll never leak blocks permanently.
	 */
	if (!xfs_ilock_nowait(ip, XFS_IOLOCK_EXCL))
		return 0;
Dave Chinner's avatar
Dave Chinner committed
1533

1534
	if (xfs_can_free_eofblocks(ip, false)) {
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
		/*
		 * Check if the inode is being opened, written and closed
		 * frequently and we have delayed allocation blocks outstanding
		 * (e.g. streaming writes from the NFS server), truncating the
		 * blocks past EOF will cause fragmentation to occur.
		 *
		 * In this case don't do the truncation, but we have to be
		 * careful how we detect this case. Blocks beyond EOF show up as
		 * i_delayed_blks even when the inode is clean, so we need to
		 * truncate them away first before checking for a dirty release.
		 * Hence on the first dirty close we will still remove the
		 * speculative allocation, but after that we will leave it in
		 * place.
		 */
		if (xfs_iflags_test(ip, XFS_IDIRTY_RELEASE))
1550 1551 1552 1553 1554
			goto out_unlock;

		error = xfs_free_eofblocks(ip);
		if (error)
			goto out_unlock;
Dave Chinner's avatar
Dave Chinner committed
1555 1556 1557 1558 1559

		/* delalloc blocks after truncation means it really is dirty */
		if (ip->i_delayed_blks)
			xfs_iflags_set(ip, XFS_IDIRTY_RELEASE);
	}
1560 1561 1562 1563

out_unlock:
	xfs_iunlock(ip, XFS_IOLOCK_EXCL);
	return error;
Dave Chinner's avatar
Dave Chinner committed
1564 1565
}

1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
/*
 * Mark all the buffers attached to this directory stale.  In theory we should
 * never be freeing a directory with any blocks at all, but this covers the
 * case where we've recovered a directory swap with a "temporary" directory
 * created by online repair and now need to dump it.
 */
STATIC void
xfs_inactive_dir(
	struct xfs_inode	*dp)
{
	struct xfs_iext_cursor	icur;
	struct xfs_bmbt_irec	got;
	struct xfs_mount	*mp = dp->i_mount;
	struct xfs_da_geometry	*geo = mp->m_dir_geo;
	struct xfs_ifork	*ifp = xfs_ifork_ptr(dp, XFS_DATA_FORK);
	xfs_fileoff_t		off;

	/*
	 * Invalidate each directory block.  All directory blocks are of
	 * fsbcount length and alignment, so we only need to walk those same
	 * offsets.  We hold the only reference to this inode, so we must wait
	 * for the buffer locks.
	 */
	for_each_xfs_iext(ifp, &icur, &got) {
		for (off = round_up(got.br_startoff, geo->fsbcount);
		     off < got.br_startoff + got.br_blockcount;
		     off += geo->fsbcount) {
			struct xfs_buf	*bp = NULL;
			xfs_fsblock_t	fsbno;
			int		error;

			fsbno = (off - got.br_startoff) + got.br_startblock;
			error = xfs_buf_incore(mp->m_ddev_targp,
					XFS_FSB_TO_DADDR(mp, fsbno),
					XFS_FSB_TO_BB(mp, geo->fsbcount),
					XBF_LIVESCAN, &bp);
			if (error)
				continue;

			xfs_buf_stale(bp);
			xfs_buf_relse(bp);
		}
	}
}

1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
/*
 * xfs_inactive_truncate
 *
 * Called to perform a truncate when an inode becomes unlinked.
 */
STATIC int
xfs_inactive_truncate(
	struct xfs_inode *ip)
{
	struct xfs_mount	*mp = ip->i_mount;
	struct xfs_trans	*tp;
	int			error;

1624
	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_itruncate, 0, 0, 0, &tp);
1625
	if (error) {
1626
		ASSERT(xfs_is_shutdown(mp));
1627 1628 1629 1630 1631 1632 1633 1634
		return error;
	}
	xfs_ilock(ip, XFS_ILOCK_EXCL);
	xfs_trans_ijoin(tp, ip, 0);

	/*
	 * Log the inode size first to prevent stale data exposure in the event
	 * of a system crash before the truncate completes. See the related
1635
	 * comment in xfs_vn_setattr_size() for details.
1636
	 */
1637
	ip->i_disk_size = 0;
1638 1639 1640 1641 1642 1643
	xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);

	error = xfs_itruncate_extents(&tp, ip, XFS_DATA_FORK, 0);
	if (error)
		goto error_trans_cancel;

1644
	ASSERT(ip->i_df.if_nextents == 0);
1645

1646
	error = xfs_trans_commit(tp);
1647 1648 1649 1650 1651 1652 1653
	if (error)
		goto error_unlock;

	xfs_iunlock(ip, XFS_ILOCK_EXCL);
	return 0;

error_trans_cancel:
1654
	xfs_trans_cancel(tp);
1655 1656 1657 1658 1659
error_unlock:
	xfs_iunlock(ip, XFS_ILOCK_EXCL);
	return error;
}

1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
/*
 * xfs_inactive_ifree()
 *
 * Perform the inode free when an inode is unlinked.
 */
STATIC int
xfs_inactive_ifree(
	struct xfs_inode *ip)
{
	struct xfs_mount	*mp = ip->i_mount;
	struct xfs_trans	*tp;
	int			error;

1673
	/*
1674 1675 1676 1677 1678
	 * We try to use a per-AG reservation for any block needed by the finobt
	 * tree, but as the finobt feature predates the per-AG reservation
	 * support a degraded file system might not have enough space for the
	 * reservation at mount time.  In that case try to dip into the reserved
	 * pool and pray.
1679 1680 1681 1682 1683
	 *
	 * Send a warning if the reservation does happen to fail, as the inode
	 * now remains allocated and sits on the unlinked list until the fs is
	 * repaired.
	 */
1684
	if (unlikely(mp->m_finobt_nores)) {
1685 1686 1687 1688 1689 1690
		error = xfs_trans_alloc(mp, &M_RES(mp)->tr_ifree,
				XFS_IFREE_SPACE_RES(mp), 0, XFS_TRANS_RESERVE,
				&tp);
	} else {
		error = xfs_trans_alloc(mp, &M_RES(mp)->tr_ifree, 0, 0, 0, &tp);
	}
1691
	if (error) {
1692
		if (error == -ENOSPC) {
1693 1694 1695 1696
			xfs_warn_ratelimited(mp,
			"Failed to remove inode(s) from unlinked list. "
			"Please free space, unmount and run xfs_repair.");
		} else {
1697
			ASSERT(xfs_is_shutdown(mp));
1698
		}
1699 1700 1701
		return error;
	}

1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
	/*
	 * We do not hold the inode locked across the entire rolling transaction
	 * here. We only need to hold it for the first transaction that
	 * xfs_ifree() builds, which may mark the inode XFS_ISTALE if the
	 * underlying cluster buffer is freed. Relogging an XFS_ISTALE inode
	 * here breaks the relationship between cluster buffer invalidation and
	 * stale inode invalidation on cluster buffer item journal commit
	 * completion, and can result in leaving dirty stale inodes hanging
	 * around in memory.
	 *
	 * We have no need for serialising this inode operation against other
	 * operations - we freed the inode and hence reallocation is required
	 * and that will serialise on reallocating the space the deferops need
	 * to free. Hence we can unlock the inode on the first commit of
	 * the transaction rather than roll it right through the deferops. This
	 * avoids relogging the XFS_ISTALE inode.
	 *
	 * We check that xfs_ifree() hasn't grown an internal transaction roll
	 * by asserting that the inode is still locked when it returns.
	 */
1722
	xfs_ilock(ip, XFS_ILOCK_EXCL);
1723
	xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
1724

1725
	error = xfs_ifree(tp, ip);
1726
	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL);
1727 1728 1729 1730 1731 1732
	if (error) {
		/*
		 * If we fail to free the inode, shut down.  The cancel
		 * might do that, we need to make sure.  Otherwise the
		 * inode might be lost for a long time or forever.
		 */
1733
		if (!xfs_is_shutdown(mp)) {
1734 1735 1736 1737
			xfs_notice(mp, "%s: xfs_ifree returned error %d",
				__func__, error);
			xfs_force_shutdown(mp, SHUTDOWN_META_IO_ERROR);
		}
1738
		xfs_trans_cancel(tp);
1739 1740 1741 1742 1743 1744 1745 1746
		return error;
	}

	/*
	 * Credit the quota account(s). The inode is gone.
	 */
	xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_ICOUNT, -1);

1747
	return xfs_trans_commit(tp);
1748 1749
}

1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
/*
 * Returns true if we need to update the on-disk metadata before we can free
 * the memory used by this inode.  Updates include freeing post-eof
 * preallocations; freeing COW staging extents; and marking the inode free in
 * the inobt if it is on the unlinked list.
 */
bool
xfs_inode_needs_inactive(
	struct xfs_inode	*ip)
{
	struct xfs_mount	*mp = ip->i_mount;
1761
	struct xfs_ifork	*cow_ifp = xfs_ifork_ptr(ip, XFS_COW_FORK);
1762 1763 1764 1765 1766 1767 1768 1769

	/*
	 * If the inode is already free, then there can be nothing
	 * to clean up here.
	 */
	if (VFS_I(ip)->i_mode == 0)
		return false;

1770 1771 1772 1773 1774
	/*
	 * If this is a read-only mount, don't do this (would generate I/O)
	 * unless we're in log recovery and cleaning the iunlinked list.
	 */
	if (xfs_is_readonly(mp) && !xlog_recovery_needed(mp->m_log))
1775 1776 1777
		return false;

	/* If the log isn't running, push inodes straight to reclaim. */
1778
	if (xfs_is_shutdown(mp) || xfs_has_norecovery(mp))
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
		return false;

	/* Metadata inodes require explicit resource cleanup. */
	if (xfs_is_metadata_inode(ip))
		return false;

	/* Want to clean out the cow blocks if there are any. */
	if (cow_ifp && cow_ifp->if_bytes > 0)
		return true;

	/* Unlinked files must be freed. */
	if (VFS_I(ip)->i_nlink == 0)
		return true;

	/*
	 * This file isn't being freed, so check if there are post-eof blocks
	 * to free.  @force is true because we are evicting an inode from the
	 * cache.  Post-eof blocks must be freed, lest we end up with broken
	 * free space accounting.
	 *
	 * Note: don't bother with iolock here since lockdep complains about
	 * acquiring it in reclaim context. We have the only reference to the
	 * inode at this point anyways.
	 */
	return xfs_can_free_eofblocks(ip, true);
}

1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
/*
 * Save health status somewhere, if we're dumping an inode with uncorrected
 * errors and online repair isn't running.
 */
static inline void
xfs_inactive_health(
	struct xfs_inode	*ip)
{
	struct xfs_mount	*mp = ip->i_mount;
	struct xfs_perag	*pag;
	unsigned int		sick;
	unsigned int		checked;

	xfs_inode_measure_sickness(ip, &sick, &checked);
	if (!sick)
		return;

	trace_xfs_inode_unfixed_corruption(ip, sick);

	if (sick & XFS_SICK_INO_FORGET)
		return;

	pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, ip->i_ino));
	if (!pag) {
		/* There had better still be a perag structure! */
		ASSERT(0);
		return;
	}

	xfs_ag_mark_sick(pag, XFS_SICK_AG_INODES);
	xfs_perag_put(pag);
}

Dave Chinner's avatar
Dave Chinner committed
1839 1840 1841 1842 1843 1844 1845 1846
/*
 * xfs_inactive
 *
 * This is called when the vnode reference count for the vnode
 * goes to zero.  If the file has been unlinked, then it must
 * now be truncated.  Also, we clear all of the read-ahead state
 * kept for the inode here since the file is now closed.
 */
1847
int
Dave Chinner's avatar
Dave Chinner committed
1848 1849 1850
xfs_inactive(
	xfs_inode_t	*ip)
{
1851
	struct xfs_mount	*mp;
1852
	int			error = 0;
1853
	int			truncate = 0;
Dave Chinner's avatar
Dave Chinner committed
1854 1855 1856 1857 1858

	/*
	 * If the inode is already free, then there can be nothing
	 * to clean up here.
	 */
1859
	if (VFS_I(ip)->i_mode == 0) {
Dave Chinner's avatar
Dave Chinner committed
1860
		ASSERT(ip->i_df.if_broot_bytes == 0);
1861
		goto out;
Dave Chinner's avatar
Dave Chinner committed
1862 1863 1864
	}

	mp = ip->i_mount;
1865
	ASSERT(!xfs_iflags_test(ip, XFS_IRECOVERY));
Dave Chinner's avatar
Dave Chinner committed
1866

1867 1868
	xfs_inactive_health(ip);

1869 1870 1871 1872 1873
	/*
	 * If this is a read-only mount, don't do this (would generate I/O)
	 * unless we're in log recovery and cleaning the iunlinked list.
	 */
	if (xfs_is_readonly(mp) && !xlog_recovery_needed(mp->m_log))
1874
		goto out;
Dave Chinner's avatar
Dave Chinner committed
1875

1876 1877
	/* Metadata inodes require explicit resource cleanup. */
	if (xfs_is_metadata_inode(ip))
1878
		goto out;
1879

1880
	/* Try to clean out the cow blocks if there are any. */
1881
	if (xfs_inode_has_cow_data(ip))
1882 1883
		xfs_reflink_cancel_cow_range(ip, 0, NULLFILEOFF, true);

1884
	if (VFS_I(ip)->i_nlink != 0) {
Dave Chinner's avatar
Dave Chinner committed
1885 1886 1887 1888
		/*
		 * force is true because we are evicting an inode from the
		 * cache. Post-eof blocks must be freed, lest we end up with
		 * broken free space accounting.
1889 1890 1891 1892
		 *
		 * Note: don't bother with iolock here since lockdep complains
		 * about acquiring it in reclaim context. We have the only
		 * reference to the inode at this point anyways.
Dave Chinner's avatar
Dave Chinner committed
1893
		 */
1894
		if (xfs_can_free_eofblocks(ip, true))
1895
			error = xfs_free_eofblocks(ip);
1896

1897
		goto out;
Dave Chinner's avatar
Dave Chinner committed
1898 1899
	}

1900
	if (S_ISREG(VFS_I(ip)->i_mode) &&
1901
	    (ip->i_disk_size != 0 || XFS_ISIZE(ip) != 0 ||
1902
	     ip->i_df.if_nextents > 0 || ip->i_delayed_blks > 0))
Dave Chinner's avatar
Dave Chinner committed
1903 1904
		truncate = 1;

1905
	if (xfs_iflags_test(ip, XFS_IQUOTAUNCHECKED)) {
1906 1907 1908 1909 1910 1911 1912 1913
		/*
		 * If this inode is being inactivated during a quotacheck and
		 * has not yet been scanned by quotacheck, we /must/ remove
		 * the dquots from the inode before inactivation changes the
		 * block and inode counts.  Most probably this is a result of
		 * reloading the incore iunlinked list to purge unrecovered
		 * unlinked inodes.
		 */
1914 1915 1916 1917 1918 1919
		xfs_qm_dqdetach(ip);
	} else {
		error = xfs_qm_dqattach(ip);
		if (error)
			goto out;
	}
Dave Chinner's avatar
Dave Chinner committed
1920

1921 1922 1923 1924 1925
	if (S_ISDIR(VFS_I(ip)->i_mode) && ip->i_df.if_nextents > 0) {
		xfs_inactive_dir(ip);
		truncate = 1;
	}

1926
	if (S_ISLNK(VFS_I(ip)->i_mode))
1927
		error = xfs_inactive_symlink(ip);
1928 1929 1930
	else if (truncate)
		error = xfs_inactive_truncate(ip);
	if (error)
1931
		goto out;
Dave Chinner's avatar
Dave Chinner committed
1932 1933 1934 1935

	/*
	 * If there are attributes associated with the file then blow them away
	 * now.  The code calls a routine that recursively deconstructs the
1936
	 * attribute fork. If also blows away the in-core attribute fork.
Dave Chinner's avatar
Dave Chinner committed
1937
	 */
1938
	if (xfs_inode_has_attr_fork(ip)) {
Dave Chinner's avatar
Dave Chinner committed
1939 1940
		error = xfs_attr_inactive(ip);
		if (error)
1941
			goto out;
Dave Chinner's avatar
Dave Chinner committed
1942 1943
	}

1944
	ASSERT(ip->i_forkoff == 0);
Dave Chinner's avatar
Dave Chinner committed
1945 1946 1947 1948

	/*
	 * Free the inode.
	 */
1949
	error = xfs_inactive_ifree(ip);
Dave Chinner's avatar
Dave Chinner committed
1950

1951
out:
Dave Chinner's avatar
Dave Chinner committed
1952
	/*
1953 1954
	 * We're done making metadata updates for this inode, so we can release
	 * the attached dquots.
Dave Chinner's avatar
Dave Chinner committed
1955 1956
	 */
	xfs_qm_dqdetach(ip);
1957
	return error;
Dave Chinner's avatar
Dave Chinner committed
1958 1959
}

1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
/*
 * In-Core Unlinked List Lookups
 * =============================
 *
 * Every inode is supposed to be reachable from some other piece of metadata
 * with the exception of the root directory.  Inodes with a connection to a
 * file descriptor but not linked from anywhere in the on-disk directory tree
 * are collectively known as unlinked inodes, though the filesystem itself
 * maintains links to these inodes so that on-disk metadata are consistent.
 *
 * XFS implements a per-AG on-disk hash table of unlinked inodes.  The AGI
 * header contains a number of buckets that point to an inode, and each inode
 * record has a pointer to the next inode in the hash chain.  This
 * singly-linked list causes scaling problems in the iunlink remove function
 * because we must walk that list to find the inode that points to the inode
 * being removed from the unlinked hash bucket list.
 *
1977 1978 1979 1980 1981 1982 1983
 * Hence we keep an in-memory double linked list to link each inode on an
 * unlinked list. Because there are 64 unlinked lists per AGI, keeping pointer
 * based lists would require having 64 list heads in the perag, one for each
 * list. This is expensive in terms of memory (think millions of AGs) and cache
 * misses on lookups. Instead, use the fact that inodes on the unlinked list
 * must be referenced at the VFS level to keep them on the list and hence we
 * have an existence guarantee for inodes on the unlinked list.
1984
 *
1985 1986 1987 1988 1989 1990
 * Given we have an existence guarantee, we can use lockless inode cache lookups
 * to resolve aginos to xfs inodes. This means we only need 8 bytes per inode
 * for the double linked unlinked list, and we don't need any extra locking to
 * keep the list safe as all manipulations are done under the AGI buffer lock.
 * Keeping the list up to date does not require memory allocation, just finding
 * the XFS inode and updating the next/prev unlinked list aginos.
1991 1992 1993
 */

/*
1994 1995 1996 1997
 * Find an inode on the unlinked list. This does not take references to the
 * inode as we have existence guarantees by holding the AGI buffer lock and that
 * only unlinked, referenced inodes can be on the unlinked inode list.  If we
 * don't find the inode in cache, then let the caller handle the situation.
1998
 */
1999
struct xfs_inode *
2000
xfs_iunlink_lookup(
2001 2002 2003
	struct xfs_perag	*pag,
	xfs_agino_t		agino)
{
2004
	struct xfs_inode	*ip;
2005

2006 2007
	rcu_read_lock();
	ip = radix_tree_lookup(&pag->pag_ici_root, agino);
2008 2009 2010 2011 2012
	if (!ip) {
		/* Caller can handle inode not being in memory. */
		rcu_read_unlock();
		return NULL;
	}
2013 2014

	/*
2015 2016
	 * Inode in RCU freeing limbo should not happen.  Warn about this and
	 * let the caller handle the failure.
2017
	 */
2018
	if (WARN_ON_ONCE(!ip->i_ino)) {
2019 2020
		rcu_read_unlock();
		return NULL;
2021
	}
2022 2023 2024
	ASSERT(!xfs_iflags_test(ip, XFS_IRECLAIMABLE | XFS_IRECLAIM));
	rcu_read_unlock();
	return ip;
2025 2026
}

2027 2028 2029 2030
/*
 * Update the prev pointer of the next agino.  Returns -ENOLINK if the inode
 * is not in cache.
 */
2031
static int
2032
xfs_iunlink_update_backref(
2033 2034
	struct xfs_perag	*pag,
	xfs_agino_t		prev_agino,
2035
	xfs_agino_t		next_agino)
2036
{
2037
	struct xfs_inode	*ip;
2038

2039 2040
	/* No update necessary if we are at the end of the list. */
	if (next_agino == NULLAGINO)
2041 2042
		return 0;

2043 2044
	ip = xfs_iunlink_lookup(pag, next_agino);
	if (!ip)
2045 2046
		return -ENOLINK;

2047 2048
	ip->i_prev_unlinked = prev_agino;
	return 0;
2049 2050
}

2051 2052 2053 2054 2055 2056 2057
/*
 * Point the AGI unlinked bucket at an inode and log the results.  The caller
 * is responsible for validating the old value.
 */
STATIC int
xfs_iunlink_update_bucket(
	struct xfs_trans	*tp,
2058
	struct xfs_perag	*pag,
2059 2060 2061 2062
	struct xfs_buf		*agibp,
	unsigned int		bucket_index,
	xfs_agino_t		new_agino)
{
2063
	struct xfs_agi		*agi = agibp->b_addr;
2064 2065 2066
	xfs_agino_t		old_value;
	int			offset;

2067
	ASSERT(xfs_verify_agino_or_null(pag, new_agino));
2068 2069

	old_value = be32_to_cpu(agi->agi_unlinked[bucket_index]);
2070
	trace_xfs_iunlink_update_bucket(tp->t_mountp, pag->pag_agno, bucket_index,
2071 2072 2073 2074 2075 2076 2077
			old_value, new_agino);

	/*
	 * We should never find the head of the list already set to the value
	 * passed in because either we're adding or removing ourselves from the
	 * head of the list.
	 */
2078
	if (old_value == new_agino) {
2079
		xfs_buf_mark_corrupt(agibp);
2080
		xfs_ag_mark_sick(pag, XFS_SICK_AG_AGI);
2081
		return -EFSCORRUPTED;
2082
	}
2083 2084 2085 2086 2087 2088 2089 2090

	agi->agi_unlinked[bucket_index] = cpu_to_be32(new_agino);
	offset = offsetof(struct xfs_agi, agi_unlinked) +
			(sizeof(xfs_agino_t) * bucket_index);
	xfs_trans_log_buf(tp, agibp, offset, offset + sizeof(xfs_agino_t) - 1);
	return 0;
}

2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
/*
 * Load the inode @next_agino into the cache and set its prev_unlinked pointer
 * to @prev_agino.  Caller must hold the AGI to synchronize with other changes
 * to the unlinked list.
 */
STATIC int
xfs_iunlink_reload_next(
	struct xfs_trans	*tp,
	struct xfs_buf		*agibp,
	xfs_agino_t		prev_agino,
	xfs_agino_t		next_agino)
{
	struct xfs_perag	*pag = agibp->b_pag;
	struct xfs_mount	*mp = pag->pag_mount;
	struct xfs_inode	*next_ip = NULL;
	xfs_ino_t		ino;
	int			error;

	ASSERT(next_agino != NULLAGINO);

#ifdef DEBUG
	rcu_read_lock();
	next_ip = radix_tree_lookup(&pag->pag_ici_root, next_agino);
	ASSERT(next_ip == NULL);
	rcu_read_unlock();
#endif

	xfs_info_ratelimited(mp,
 "Found unrecovered unlinked inode 0x%x in AG 0x%x.  Initiating recovery.",
			next_agino, pag->pag_agno);

	/*
	 * Use an untrusted lookup just to be cautious in case the AGI has been
	 * corrupted and now points at a free inode.  That shouldn't happen,
	 * but we'd rather shut down now since we're already running in a weird
	 * situation.
	 */
	ino = XFS_AGINO_TO_INO(mp, pag->pag_agno, next_agino);
	error = xfs_iget(mp, tp, ino, XFS_IGET_UNTRUSTED, 0, &next_ip);
2130 2131
	if (error) {
		xfs_ag_mark_sick(pag, XFS_SICK_AG_AGI);
2132
		return error;
2133
	}
2134 2135 2136

	/* If this is not an unlinked inode, something is very wrong. */
	if (VFS_I(next_ip)->i_nlink != 0) {
2137
		xfs_ag_mark_sick(pag, XFS_SICK_AG_AGI);
2138 2139 2140 2141 2142 2143 2144 2145
		error = -EFSCORRUPTED;
		goto rele;
	}

	next_ip->i_prev_unlinked = prev_agino;
	trace_xfs_iunlink_reload_next(next_ip);
rele:
	ASSERT(!(VFS_I(next_ip)->i_state & I_DONTCACHE));
2146 2147
	if (xfs_is_quotacheck_running(mp) && next_ip)
		xfs_iflags_set(next_ip, XFS_IQUOTAUNCHECKED);
2148 2149 2150 2151
	xfs_irele(next_ip);
	return error;
}

2152 2153
static int
xfs_iunlink_insert_inode(
2154
	struct xfs_trans	*tp,
2155
	struct xfs_perag	*pag,
2156
	struct xfs_buf		*agibp,
2157
	struct xfs_inode	*ip)
2158 2159
{
	struct xfs_mount	*mp = tp->t_mountp;
2160
	struct xfs_agi		*agi = agibp->b_addr;
2161
	xfs_agino_t		next_agino;
2162 2163
	xfs_agino_t		agino = XFS_INO_TO_AGINO(mp, ip->i_ino);
	short			bucket_index = agino % XFS_AGI_UNLINKED_BUCKETS;
2164 2165
	int			error;

Linus Torvalds's avatar
Linus Torvalds committed
2166
	/*
2167 2168 2169
	 * Get the index into the agi hash table for the list this inode will
	 * go on.  Make sure the pointer isn't garbage and that this inode
	 * isn't already on the list.
Linus Torvalds's avatar
Linus Torvalds committed
2170
	 */
2171 2172
	next_agino = be32_to_cpu(agi->agi_unlinked[bucket_index]);
	if (next_agino == agino ||
2173
	    !xfs_verify_agino_or_null(pag, next_agino)) {
2174
		xfs_buf_mark_corrupt(agibp);
2175
		xfs_ag_mark_sick(pag, XFS_SICK_AG_AGI);
2176
		return -EFSCORRUPTED;
2177 2178 2179
	}

	/*
2180 2181
	 * Update the prev pointer in the next inode to point back to this
	 * inode.
2182
	 */
2183
	error = xfs_iunlink_update_backref(pag, agino, next_agino);
2184 2185
	if (error == -ENOLINK)
		error = xfs_iunlink_reload_next(tp, agibp, agino, next_agino);
2186 2187 2188
	if (error)
		return error;

2189
	if (next_agino != NULLAGINO) {
Linus Torvalds's avatar
Linus Torvalds committed
2190
		/*
2191 2192
		 * There is already another inode in the bucket, so point this
		 * inode to the current head of the list.
Linus Torvalds's avatar
Linus Torvalds committed
2193
		 */
2194
		error = xfs_iunlink_log_inode(tp, ip, pag, next_agino);
2195
		if (error)
2196
			return error;
2197
		ip->i_next_unlinked = next_agino;
2198 2199
	}

2200
	/* Point the head of the list to point to this inode. */
2201
	ip->i_prev_unlinked = NULLAGINO;
2202
	return xfs_iunlink_update_bucket(tp, pag, agibp, bucket_index, agino);
2203 2204
}

Linus Torvalds's avatar
Linus Torvalds committed
2205
/*
2206 2207
 * This is called when the inode's link count has gone to 0 or we are creating
 * a tmpfile via O_TMPFILE.  The inode @ip must have nlink == 0.
2208 2209 2210
 *
 * We place the on-disk inode on a list in the AGI.  It will be pulled from this
 * list when the inode is freed.
Linus Torvalds's avatar
Linus Torvalds committed
2211
 */
2212
int
Linus Torvalds's avatar
Linus Torvalds committed
2213
xfs_iunlink(
2214 2215
	struct xfs_trans	*tp,
	struct xfs_inode	*ip)
Linus Torvalds's avatar
Linus Torvalds committed
2216
{
2217
	struct xfs_mount	*mp = tp->t_mountp;
2218
	struct xfs_perag	*pag;
2219 2220
	struct xfs_buf		*agibp;
	int			error;
Linus Torvalds's avatar
Linus Torvalds committed
2221

2222
	ASSERT(VFS_I(ip)->i_nlink == 0);
2223
	ASSERT(VFS_I(ip)->i_mode != 0);
2224
	trace_xfs_iunlink(ip);
Linus Torvalds's avatar
Linus Torvalds committed
2225

2226 2227
	pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, ip->i_ino));

2228
	/* Get the agi buffer first.  It ensures lock ordering on the list. */
2229
	error = xfs_read_agi(pag, tp, 0, &agibp);
2230
	if (error)
2231
		goto out;
2232

2233
	error = xfs_iunlink_insert_inode(tp, pag, agibp, ip);
2234 2235 2236
out:
	xfs_perag_put(pag);
	return error;
Linus Torvalds's avatar
Linus Torvalds committed
2237 2238
}

2239 2240
static int
xfs_iunlink_remove_inode(
2241
	struct xfs_trans	*tp,
2242
	struct xfs_perag	*pag,
2243
	struct xfs_buf		*agibp,
2244
	struct xfs_inode	*ip)
Linus Torvalds's avatar
Linus Torvalds committed
2245
{
2246
	struct xfs_mount	*mp = tp->t_mountp;
2247
	struct xfs_agi		*agi = agibp->b_addr;
2248
	xfs_agino_t		agino = XFS_INO_TO_AGINO(mp, ip->i_ino);
2249
	xfs_agino_t		head_agino;
2250 2251
	short			bucket_index = agino % XFS_AGI_UNLINKED_BUCKETS;
	int			error;
Linus Torvalds's avatar
Linus Torvalds committed
2252

2253 2254
	trace_xfs_iunlink_remove(ip);

Linus Torvalds's avatar
Linus Torvalds committed
2255
	/*
2256 2257
	 * Get the index into the agi hash table for the list this inode will
	 * go on.  Make sure the head pointer isn't garbage.
Linus Torvalds's avatar
Linus Torvalds committed
2258
	 */
2259
	head_agino = be32_to_cpu(agi->agi_unlinked[bucket_index]);
2260
	if (!xfs_verify_agino(pag, head_agino)) {
2261 2262
		XFS_CORRUPTION_ERROR(__func__, XFS_ERRLEVEL_LOW, mp,
				agi, sizeof(*agi));
2263
		xfs_ag_mark_sick(pag, XFS_SICK_AG_AGI);
2264 2265
		return -EFSCORRUPTED;
	}
Linus Torvalds's avatar
Linus Torvalds committed
2266

2267 2268 2269 2270 2271
	/*
	 * Set our inode's next_unlinked pointer to NULL and then return
	 * the old pointer value so that we can update whatever was previous
	 * to us in the list to point to whatever was next in the list.
	 */
2272
	error = xfs_iunlink_log_inode(tp, ip, pag, NULLAGINO);
2273 2274
	if (error)
		return error;
2275

2276
	/*
2277 2278
	 * Update the prev pointer in the next inode to point back to previous
	 * inode in the chain.
2279
	 */
2280 2281
	error = xfs_iunlink_update_backref(pag, ip->i_prev_unlinked,
			ip->i_next_unlinked);
2282 2283 2284
	if (error == -ENOLINK)
		error = xfs_iunlink_reload_next(tp, agibp, ip->i_prev_unlinked,
				ip->i_next_unlinked);
2285 2286
	if (error)
		return error;
2287

2288
	if (head_agino != agino) {
2289
		struct xfs_inode	*prev_ip;
2290

2291
		prev_ip = xfs_iunlink_lookup(pag, ip->i_prev_unlinked);
2292 2293
		if (!prev_ip) {
			xfs_inode_mark_sick(ip, XFS_SICK_INO_CORE);
2294
			return -EFSCORRUPTED;
2295
		}
2296

2297
		error = xfs_iunlink_log_inode(tp, prev_ip, pag,
2298
				ip->i_next_unlinked);
2299
		prev_ip->i_next_unlinked = ip->i_next_unlinked;
2300 2301 2302 2303
	} else {
		/* Point the head of the list to the next unlinked inode. */
		error = xfs_iunlink_update_bucket(tp, pag, agibp, bucket_index,
				ip->i_next_unlinked);
Linus Torvalds's avatar
Linus Torvalds committed
2304
	}
2305

2306
	ip->i_next_unlinked = NULLAGINO;
2307
	ip->i_prev_unlinked = 0;
2308
	return error;
Linus Torvalds's avatar
Linus Torvalds committed
2309 2310
}

2311 2312 2313
/*
 * Pull the on-disk inode from the AGI unlinked list.
 */
2314
int
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
xfs_iunlink_remove(
	struct xfs_trans	*tp,
	struct xfs_perag	*pag,
	struct xfs_inode	*ip)
{
	struct xfs_buf		*agibp;
	int			error;

	trace_xfs_iunlink_remove(ip);

	/* Get the agi buffer first.  It ensures lock ordering on the list. */
2326
	error = xfs_read_agi(pag, tp, 0, &agibp);
2327 2328 2329 2330
	if (error)
		return error;

	return xfs_iunlink_remove_inode(tp, pag, agibp, ip);
Linus Torvalds's avatar
Linus Torvalds committed
2331 2332
}

2333
/*
2334 2335 2336
 * Look up the inode number specified and if it is not already marked XFS_ISTALE
 * mark it stale. We should only find clean inodes in this lookup that aren't
 * already stale.
2337
 */
2338 2339
static void
xfs_ifree_mark_inode_stale(
2340
	struct xfs_perag	*pag,
2341
	struct xfs_inode	*free_ip,
2342
	xfs_ino_t		inum)
2343
{
2344
	struct xfs_mount	*mp = pag->pag_mount;
2345
	struct xfs_inode_log_item *iip;
2346 2347 2348 2349 2350 2351 2352
	struct xfs_inode	*ip;

retry:
	rcu_read_lock();
	ip = radix_tree_lookup(&pag->pag_ici_root, XFS_INO_TO_AGINO(mp, inum));

	/* Inode not in memory, nothing to do */
2353 2354 2355 2356
	if (!ip) {
		rcu_read_unlock();
		return;
	}
2357 2358 2359 2360 2361 2362 2363 2364

	/*
	 * because this is an RCU protected lookup, we could find a recently
	 * freed or even reallocated inode during the lookup. We need to check
	 * under the i_flags_lock for a valid inode here. Skip it if it is not
	 * valid, the wrong inode or stale.
	 */
	spin_lock(&ip->i_flags_lock);
2365 2366
	if (ip->i_ino != inum || __xfs_iflags_test(ip, XFS_ISTALE))
		goto out_iflags_unlock;
2367 2368 2369 2370 2371 2372 2373 2374 2375

	/*
	 * Don't try to lock/unlock the current inode, but we _cannot_ skip the
	 * other inodes that we did not find in the list attached to the buffer
	 * and are not already marked stale. If we can't lock it, back off and
	 * retry.
	 */
	if (ip != free_ip) {
		if (!xfs_ilock_nowait(ip, XFS_ILOCK_EXCL)) {
2376
			spin_unlock(&ip->i_flags_lock);
2377 2378 2379 2380 2381
			rcu_read_unlock();
			delay(1);
			goto retry;
		}
	}
2382
	ip->i_flags |= XFS_ISTALE;
2383

2384
	/*
2385
	 * If the inode is flushing, it is already attached to the buffer.  All
2386 2387 2388 2389
	 * we needed to do here is mark the inode stale so buffer IO completion
	 * will remove it from the AIL.
	 */
	iip = ip->i_itemp;
2390
	if (__xfs_iflags_test(ip, XFS_IFLUSHING)) {
2391 2392 2393 2394
		ASSERT(!list_empty(&iip->ili_item.li_bio_list));
		ASSERT(iip->ili_last_fields);
		goto out_iunlock;
	}
2395 2396

	/*
2397 2398 2399 2400
	 * Inodes not attached to the buffer can be released immediately.
	 * Everything else has to go through xfs_iflush_abort() on journal
	 * commit as the flock synchronises removal of the inode from the
	 * cluster buffer against inode reclaim.
2401
	 */
2402
	if (!iip || list_empty(&iip->ili_item.li_bio_list))
2403
		goto out_iunlock;
2404 2405 2406 2407

	__xfs_iflags_set(ip, XFS_IFLUSHING);
	spin_unlock(&ip->i_flags_lock);
	rcu_read_unlock();
2408

2409 2410 2411 2412 2413 2414 2415 2416
	/* we have a dirty inode in memory that has not yet been flushed. */
	spin_lock(&iip->ili_lock);
	iip->ili_last_fields = iip->ili_fields;
	iip->ili_fields = 0;
	iip->ili_fsync_fields = 0;
	spin_unlock(&iip->ili_lock);
	ASSERT(iip->ili_last_fields);

2417 2418 2419 2420
	if (ip != free_ip)
		xfs_iunlock(ip, XFS_ILOCK_EXCL);
	return;

2421 2422 2423
out_iunlock:
	if (ip != free_ip)
		xfs_iunlock(ip, XFS_ILOCK_EXCL);
2424 2425 2426
out_iflags_unlock:
	spin_unlock(&ip->i_flags_lock);
	rcu_read_unlock();
2427 2428
}

2429
/*
2430
 * A big issue when freeing the inode cluster is that we _cannot_ skip any
2431 2432 2433
 * inodes that are in memory - they all must be marked stale and attached to
 * the cluster buffer.
 */
2434
static int
Linus Torvalds's avatar
Linus Torvalds committed
2435
xfs_ifree_cluster(
2436
	struct xfs_trans	*tp,
2437 2438
	struct xfs_perag	*pag,
	struct xfs_inode	*free_ip,
2439
	struct xfs_icluster	*xic)
Linus Torvalds's avatar
Linus Torvalds committed
2440
{
2441 2442 2443 2444 2445
	struct xfs_mount	*mp = free_ip->i_mount;
	struct xfs_ino_geometry	*igeo = M_IGEO(mp);
	struct xfs_buf		*bp;
	xfs_daddr_t		blkno;
	xfs_ino_t		inum = xic->first_ino;
Linus Torvalds's avatar
Linus Torvalds committed
2446
	int			nbufs;
2447
	int			i, j;
2448
	int			ioffset;
2449
	int			error;
Linus Torvalds's avatar
Linus Torvalds committed
2450

2451
	nbufs = igeo->ialloc_blks / igeo->blocks_per_cluster;
Linus Torvalds's avatar
Linus Torvalds committed
2452

2453
	for (j = 0; j < nbufs; j++, inum += igeo->inodes_per_cluster) {
2454 2455 2456 2457 2458
		/*
		 * The allocation bitmap tells us which inodes of the chunk were
		 * physically allocated. Skip the cluster if an inode falls into
		 * a sparse region.
		 */
2459 2460
		ioffset = inum - xic->first_ino;
		if ((xic->alloc & XFS_INOBT_MASK(ioffset)) == 0) {
2461
			ASSERT(ioffset % igeo->inodes_per_cluster == 0);
2462 2463 2464
			continue;
		}

Linus Torvalds's avatar
Linus Torvalds committed
2465 2466 2467
		blkno = XFS_AGB_TO_DADDR(mp, XFS_INO_TO_AGNO(mp, inum),
					 XFS_INO_TO_AGBNO(mp, inum));

2468 2469
		/*
		 * We obtain and lock the backing buffer first in the process
2470 2471 2472
		 * here to ensure dirty inodes attached to the buffer remain in
		 * the flushing state while we mark them stale.
		 *
2473 2474 2475 2476
		 * If we scan the in-memory inodes first, then buffer IO can
		 * complete before we get a lock on it, and hence we may fail
		 * to mark all the active inodes on the buffer stale.
		 */
2477 2478 2479
		error = xfs_trans_get_buf(tp, mp->m_ddev_targp, blkno,
				mp->m_bsize * igeo->blocks_per_cluster,
				XBF_UNMAPPED, &bp);
2480
		if (error)
2481
			return error;
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491

		/*
		 * This buffer may not have been correctly initialised as we
		 * didn't read it from disk. That's not important because we are
		 * only using to mark the buffer as stale in the log, and to
		 * attach stale cached inodes on it. That means it will never be
		 * dispatched for IO. If it is, we want to know about it, and we
		 * want it to fail. We can acheive this by adding a write
		 * verifier to the buffer.
		 */
2492
		bp->b_ops = &xfs_inode_buf_ops;
2493

2494
		/*
2495 2496 2497
		 * Now we need to set all the cached clean inodes as XFS_ISTALE,
		 * too. This requires lookups, and will skip inodes that we've
		 * already marked XFS_ISTALE.
Linus Torvalds's avatar
Linus Torvalds committed
2498
		 */
2499
		for (i = 0; i < igeo->inodes_per_cluster; i++)
2500
			xfs_ifree_mark_inode_stale(pag, free_ip, inum + i);
Linus Torvalds's avatar
Linus Torvalds committed
2501

2502
		xfs_trans_stale_inode_buf(tp, bp);
Linus Torvalds's avatar
Linus Torvalds committed
2503 2504
		xfs_trans_binval(tp, bp);
	}
2505
	return 0;
Linus Torvalds's avatar
Linus Torvalds committed
2506 2507 2508
}

/*
2509 2510 2511
 * This is called to return an inode to the inode free list.  The inode should
 * already be truncated to 0 length and have no pages associated with it.  This
 * routine also assumes that the inode is already a part of the transaction.
Linus Torvalds's avatar
Linus Torvalds committed
2512
 *
2513 2514 2515
 * The on-disk copy of the inode will have been added to the list of unlinked
 * inodes in the AGI. We need to remove the inode from that list atomically with
 * respect to freeing it here.
Linus Torvalds's avatar
Linus Torvalds committed
2516 2517 2518
 */
int
xfs_ifree(
2519 2520
	struct xfs_trans	*tp,
	struct xfs_inode	*ip)
Linus Torvalds's avatar
Linus Torvalds committed
2521
{
2522 2523
	struct xfs_mount	*mp = ip->i_mount;
	struct xfs_perag	*pag;
2524
	struct xfs_icluster	xic = { 0 };
Dave Chinner's avatar
Dave Chinner committed
2525
	struct xfs_inode_log_item *iip = ip->i_itemp;
2526
	int			error;
Linus Torvalds's avatar
Linus Torvalds committed
2527

2528
	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL);
2529
	ASSERT(VFS_I(ip)->i_nlink == 0);
2530
	ASSERT(ip->i_df.if_nextents == 0);
2531
	ASSERT(ip->i_disk_size == 0 || !S_ISREG(VFS_I(ip)->i_mode));
2532
	ASSERT(ip->i_nblocks == 0);
Linus Torvalds's avatar
Linus Torvalds committed
2533

2534 2535
	pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, ip->i_ino));

Linus Torvalds's avatar
Linus Torvalds committed
2536
	/*
2537 2538 2539 2540
	 * Free the inode first so that we guarantee that the AGI lock is going
	 * to be taken before we remove the inode from the unlinked list. This
	 * makes the AGI lock -> unlinked list modification order the same as
	 * used in O_TMPFILE creation.
Linus Torvalds's avatar
Linus Torvalds committed
2541
	 */
2542
	error = xfs_difree(tp, pag, ip->i_ino, &xic);
2543
	if (error)
2544
		goto out;
Linus Torvalds's avatar
Linus Torvalds committed
2545

2546
	error = xfs_iunlink_remove(tp, pag, ip);
2547
	if (error)
2548
		goto out;
2549

2550 2551 2552 2553 2554
	/*
	 * Free any local-format data sitting around before we reset the
	 * data fork to extents format.  Note that the attr fork data has
	 * already been freed by xfs_attr_inactive.
	 */
2555
	if (ip->i_df.if_format == XFS_DINODE_FMT_LOCAL) {
2556
		kfree(ip->i_df.if_data);
2557
		ip->i_df.if_data = NULL;
2558 2559
		ip->i_df.if_bytes = 0;
	}
2560

2561
	VFS_I(ip)->i_mode = 0;		/* mark incore inode as free */
2562
	ip->i_diflags = 0;
2563
	ip->i_diflags2 = mp->m_ino_geo.new_diflags2;
2564
	ip->i_forkoff = 0;		/* mark the attr fork not in use */
2565
	ip->i_df.if_format = XFS_DINODE_FMT_EXTENTS;
2566 2567
	if (xfs_iflags_test(ip, XFS_IPRESERVE_DM_FIELDS))
		xfs_iflags_clear(ip, XFS_IPRESERVE_DM_FIELDS);
2568 2569

	/* Don't attempt to replay owner changes for a deleted inode */
Dave Chinner's avatar
Dave Chinner committed
2570 2571 2572
	spin_lock(&iip->ili_lock);
	iip->ili_fields &= ~(XFS_ILOG_AOWNER | XFS_ILOG_DOWNER);
	spin_unlock(&iip->ili_lock);
2573

Linus Torvalds's avatar
Linus Torvalds committed
2574 2575 2576 2577
	/*
	 * Bump the generation count so no one will be confused
	 * by reincarnations of this inode.
	 */
2578
	VFS_I(ip)->i_generation++;
Linus Torvalds's avatar
Linus Torvalds committed
2579 2580
	xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);

2581
	if (xic.deleted)
2582 2583 2584
		error = xfs_ifree_cluster(tp, pag, ip, &xic);
out:
	xfs_perag_put(pag);
2585
	return error;
Linus Torvalds's avatar
Linus Torvalds committed
2586 2587 2588
}

/*
2589 2590 2591
 * This is called to unpin an inode.  The caller must have the inode locked
 * in at least shared mode so that the buffer cannot be subsequently pinned
 * once someone is waiting for it to be unpinned.
Linus Torvalds's avatar
Linus Torvalds committed
2592
 */
2593
static void
2594
xfs_iunpin(
2595
	struct xfs_inode	*ip)
Linus Torvalds's avatar
Linus Torvalds committed
2596
{
2597
	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL | XFS_ILOCK_SHARED);
Linus Torvalds's avatar
Linus Torvalds committed
2598

2599 2600
	trace_xfs_inode_unpin_nowait(ip, _RET_IP_);

2601
	/* Give the log a push to start the unpinning I/O */
2602
	xfs_log_force_seq(ip->i_mount, ip->i_itemp->ili_commit_seq, 0, NULL);
2603

2604
}
Linus Torvalds's avatar
Linus Torvalds committed
2605

2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
static void
__xfs_iunpin_wait(
	struct xfs_inode	*ip)
{
	wait_queue_head_t *wq = bit_waitqueue(&ip->i_flags, __XFS_IPINNED_BIT);
	DEFINE_WAIT_BIT(wait, &ip->i_flags, __XFS_IPINNED_BIT);

	xfs_iunpin(ip);

	do {
2616
		prepare_to_wait(wq, &wait.wq_entry, TASK_UNINTERRUPTIBLE);
2617 2618 2619
		if (xfs_ipincount(ip))
			io_schedule();
	} while (xfs_ipincount(ip));
2620
	finish_wait(wq, &wait.wq_entry);
2621 2622
}

2623
void
2624
xfs_iunpin_wait(
2625
	struct xfs_inode	*ip)
2626
{
2627 2628
	if (xfs_ipincount(ip))
		__xfs_iunpin_wait(ip);
Linus Torvalds's avatar
Linus Torvalds committed
2629 2630
}

2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
/*
 * Removing an inode from the namespace involves removing the directory entry
 * and dropping the link count on the inode. Removing the directory entry can
 * result in locking an AGF (directory blocks were freed) and removing a link
 * count can result in placing the inode on an unlinked list which results in
 * locking an AGI.
 *
 * The big problem here is that we have an ordering constraint on AGF and AGI
 * locking - inode allocation locks the AGI, then can allocate a new extent for
 * new inodes, locking the AGF after the AGI. Similarly, freeing the inode
 * removes the inode from the unlinked list, requiring that we lock the AGI
 * first, and then freeing the inode can result in an inode chunk being freed
 * and hence freeing disk space requiring that we lock an AGF.
 *
 * Hence the ordering that is imposed by other parts of the code is AGI before
 * AGF. This means we cannot remove the directory entry before we drop the inode
 * reference count and put it on the unlinked list as this results in a lock
 * order of AGF then AGI, and this can deadlock against inode allocation and
 * freeing. Therefore we must drop the link counts before we remove the
 * directory entry.
 *
 * This is still safe from a transactional point of view - it is not until we
2653
 * get to xfs_defer_finish() that we have the possibility of multiple
2654 2655 2656 2657
 * transactions in this operation. Hence as long as we remove the directory
 * entry and drop the link count in the first transaction of the remove
 * operation, there are no transactional constraints on the ordering here.
 */
Dave Chinner's avatar
Dave Chinner committed
2658 2659 2660 2661 2662 2663 2664 2665
int
xfs_remove(
	xfs_inode_t             *dp,
	struct xfs_name		*name,
	xfs_inode_t		*ip)
{
	xfs_mount_t		*mp = dp->i_mount;
	xfs_trans_t             *tp = NULL;
2666
	int			is_dir = S_ISDIR(VFS_I(ip)->i_mode);
2667
	int			dontcare;
Dave Chinner's avatar
Dave Chinner committed
2668 2669 2670 2671 2672
	int                     error = 0;
	uint			resblks;

	trace_xfs_remove(dp, name);

2673
	if (xfs_is_shutdown(mp))
2674
		return -EIO;
2675 2676
	if (xfs_ifork_zapped(dp, XFS_DATA_FORK))
		return -EIO;
Dave Chinner's avatar
Dave Chinner committed
2677

2678
	error = xfs_qm_dqattach(dp);
Dave Chinner's avatar
Dave Chinner committed
2679 2680 2681
	if (error)
		goto std_return;

2682
	error = xfs_qm_dqattach(ip);
Dave Chinner's avatar
Dave Chinner committed
2683 2684 2685 2686
	if (error)
		goto std_return;

	/*
2687 2688 2689 2690 2691 2692 2693 2694 2695
	 * We try to get the real space reservation first, allowing for
	 * directory btree deletion(s) implying possible bmap insert(s).  If we
	 * can't get the space reservation then we use 0 instead, and avoid the
	 * bmap btree insert(s) in the directory code by, if the bmap insert
	 * tries to happen, instead trimming the LAST block from the directory.
	 *
	 * Ignore EDQUOT and ENOSPC being returned via nospace_error because
	 * the directory code can handle a reservationless update and we don't
	 * want to prevent a user from trying to free space by deleting things.
Dave Chinner's avatar
Dave Chinner committed
2696 2697
	 */
	resblks = XFS_REMOVE_SPACE_RES(mp);
2698 2699
	error = xfs_trans_alloc_dir(dp, &M_RES(mp)->tr_remove, ip, &resblks,
			&tp, &dontcare);
Dave Chinner's avatar
Dave Chinner committed
2700
	if (error) {
2701
		ASSERT(error != -ENOSPC);
2702
		goto std_return;
Dave Chinner's avatar
Dave Chinner committed
2703 2704 2705 2706 2707 2708
	}

	/*
	 * If we're removing a directory perform some additional validation.
	 */
	if (is_dir) {
2709 2710
		ASSERT(VFS_I(ip)->i_nlink >= 2);
		if (VFS_I(ip)->i_nlink != 2) {
2711
			error = -ENOTEMPTY;
Dave Chinner's avatar
Dave Chinner committed
2712 2713 2714
			goto out_trans_cancel;
		}
		if (!xfs_dir_isempty(ip)) {
2715
			error = -ENOTEMPTY;
Dave Chinner's avatar
Dave Chinner committed
2716 2717 2718
			goto out_trans_cancel;
		}

2719
		/* Drop the link from ip's "..".  */
Dave Chinner's avatar
Dave Chinner committed
2720 2721
		error = xfs_droplink(tp, dp);
		if (error)
2722
			goto out_trans_cancel;
Dave Chinner's avatar
Dave Chinner committed
2723

2724
		/* Drop the "." link from ip to self.  */
Dave Chinner's avatar
Dave Chinner committed
2725 2726
		error = xfs_droplink(tp, ip);
		if (error)
2727
			goto out_trans_cancel;
2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738

		/*
		 * Point the unlinked child directory's ".." entry to the root
		 * directory to eliminate back-references to inodes that may
		 * get freed before the child directory is closed.  If the fs
		 * gets shrunk, this can lead to dirent inode validation errors.
		 */
		if (dp->i_ino != tp->t_mountp->m_sb.sb_rootino) {
			error = xfs_dir_replace(tp, ip, &xfs_name_dotdot,
					tp->t_mountp->m_sb.sb_rootino, 0);
			if (error)
2739
				goto out_trans_cancel;
2740
		}
Dave Chinner's avatar
Dave Chinner committed
2741 2742 2743 2744 2745 2746 2747 2748
	} else {
		/*
		 * When removing a non-directory we need to log the parent
		 * inode here.  For a directory this is done implicitly
		 * by the xfs_droplink call for the ".." entry.
		 */
		xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
	}
2749
	xfs_trans_ichgtime(tp, dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
Dave Chinner's avatar
Dave Chinner committed
2750

2751
	/* Drop the link from dp to ip. */
Dave Chinner's avatar
Dave Chinner committed
2752 2753
	error = xfs_droplink(tp, ip);
	if (error)
2754
		goto out_trans_cancel;
Dave Chinner's avatar
Dave Chinner committed
2755

2756
	error = xfs_dir_removename(tp, dp, name, ip->i_ino, resblks);
2757
	if (error) {
2758
		ASSERT(error != -ENOENT);
2759
		goto out_trans_cancel;
2760 2761
	}

2762 2763 2764 2765 2766 2767
	/*
	 * Drop the link from dp to ip, and if ip was a directory, remove the
	 * '.' and '..' references since we freed the directory.
	 */
	xfs_dir_update_hook(dp, ip, -1, name);

Dave Chinner's avatar
Dave Chinner committed
2768 2769 2770 2771 2772
	/*
	 * If this is a synchronous mount, make sure that the
	 * remove transaction goes to disk before returning to
	 * the user.
	 */
2773
	if (xfs_has_wsync(mp) || xfs_has_dirsync(mp))
Dave Chinner's avatar
Dave Chinner committed
2774 2775
		xfs_trans_set_sync(tp);

2776
	error = xfs_trans_commit(tp);
Dave Chinner's avatar
Dave Chinner committed
2777 2778 2779
	if (error)
		goto std_return;

2780
	if (is_dir && xfs_inode_is_filestream(ip))
Dave Chinner's avatar
Dave Chinner committed
2781 2782 2783 2784 2785
		xfs_filestream_deassociate(ip);

	return 0;

 out_trans_cancel:
2786
	xfs_trans_cancel(tp);
Dave Chinner's avatar
Dave Chinner committed
2787 2788 2789 2790
 std_return:
	return error;
}

Dave Chinner's avatar
Dave Chinner committed
2791 2792 2793
/*
 * Enter all inodes for a rename transaction into a sorted array.
 */
2794
#define __XFS_SORT_INODES	5
Dave Chinner's avatar
Dave Chinner committed
2795 2796
STATIC void
xfs_sort_for_rename(
2797 2798 2799 2800 2801 2802 2803
	struct xfs_inode	*dp1,	/* in: old (source) directory inode */
	struct xfs_inode	*dp2,	/* in: new (target) directory inode */
	struct xfs_inode	*ip1,	/* in: inode of old entry */
	struct xfs_inode	*ip2,	/* in: inode of new entry */
	struct xfs_inode	*wip,	/* in: whiteout inode */
	struct xfs_inode	**i_tab,/* out: sorted array of inodes */
	int			*num_inodes)  /* in/out: inodes in array */
Dave Chinner's avatar
Dave Chinner committed
2804
{
2805
	int			i;
Dave Chinner's avatar
Dave Chinner committed
2806

2807 2808 2809
	ASSERT(*num_inodes == __XFS_SORT_INODES);
	memset(i_tab, 0, *num_inodes * sizeof(struct xfs_inode *));

Dave Chinner's avatar
Dave Chinner committed
2810 2811 2812 2813 2814 2815 2816
	/*
	 * i_tab contains a list of pointers to inodes.  We initialize
	 * the table here & we'll sort it.  We will then use it to
	 * order the acquisition of the inode locks.
	 *
	 * Note that the table may contain duplicates.  e.g., dp1 == dp2.
	 */
2817 2818 2819 2820 2821 2822 2823 2824 2825
	i = 0;
	i_tab[i++] = dp1;
	i_tab[i++] = dp2;
	i_tab[i++] = ip1;
	if (ip2)
		i_tab[i++] = ip2;
	if (wip)
		i_tab[i++] = wip;
	*num_inodes = i;
Dave Chinner's avatar
Dave Chinner committed
2826

2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838
	xfs_sort_inodes(i_tab, *num_inodes);
}

void
xfs_sort_inodes(
	struct xfs_inode	**i_tab,
	unsigned int		num_inodes)
{
	int			i, j;

	ASSERT(num_inodes <= __XFS_SORT_INODES);

Dave Chinner's avatar
Dave Chinner committed
2839 2840
	/*
	 * Sort the elements via bubble sort.  (Remember, there are at
2841
	 * most 5 elements to sort, so this is adequate.)
Dave Chinner's avatar
Dave Chinner committed
2842
	 */
2843 2844 2845 2846
	for (i = 0; i < num_inodes; i++) {
		for (j = 1; j < num_inodes; j++) {
			if (i_tab[j]->i_ino < i_tab[j-1]->i_ino)
				swap(i_tab[j], i_tab[j - 1]);
Dave Chinner's avatar
Dave Chinner committed
2847 2848 2849 2850
		}
	}
}

2851 2852
static int
xfs_finish_rename(
2853
	struct xfs_trans	*tp)
2854 2855 2856 2857 2858
{
	/*
	 * If this is a synchronous mount, make sure that the rename transaction
	 * goes to disk before returning to the user.
	 */
2859
	if (xfs_has_wsync(tp->t_mountp) || xfs_has_dirsync(tp->t_mountp))
2860 2861
		xfs_trans_set_sync(tp);

2862
	return xfs_trans_commit(tp);
2863 2864
}

2865 2866 2867
/*
 * xfs_cross_rename()
 *
2868
 * responsible for handling RENAME_EXCHANGE flag in renameat2() syscall
2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886
 */
STATIC int
xfs_cross_rename(
	struct xfs_trans	*tp,
	struct xfs_inode	*dp1,
	struct xfs_name		*name1,
	struct xfs_inode	*ip1,
	struct xfs_inode	*dp2,
	struct xfs_name		*name2,
	struct xfs_inode	*ip2,
	int			spaceres)
{
	int		error = 0;
	int		ip1_flags = 0;
	int		ip2_flags = 0;
	int		dp2_flags = 0;

	/* Swap inode number for dirent in first parent */
2887
	error = xfs_dir_replace(tp, dp1, name1, ip2->i_ino, spaceres);
2888
	if (error)
2889
		goto out_trans_abort;
2890 2891

	/* Swap inode number for dirent in second parent */
2892
	error = xfs_dir_replace(tp, dp2, name2, ip1->i_ino, spaceres);
2893
	if (error)
2894
		goto out_trans_abort;
2895 2896 2897 2898 2899 2900 2901 2902 2903

	/*
	 * If we're renaming one or more directories across different parents,
	 * update the respective ".." entries (and link counts) to match the new
	 * parents.
	 */
	if (dp1 != dp2) {
		dp2_flags = XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG;

2904
		if (S_ISDIR(VFS_I(ip2)->i_mode)) {
2905
			error = xfs_dir_replace(tp, ip2, &xfs_name_dotdot,
2906
						dp1->i_ino, spaceres);
2907
			if (error)
2908
				goto out_trans_abort;
2909 2910

			/* transfer ip2 ".." reference to dp1 */
2911
			if (!S_ISDIR(VFS_I(ip1)->i_mode)) {
2912 2913
				error = xfs_droplink(tp, dp2);
				if (error)
2914
					goto out_trans_abort;
2915
				xfs_bumplink(tp, dp1);
2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927
			}

			/*
			 * Although ip1 isn't changed here, userspace needs
			 * to be warned about the change, so that applications
			 * relying on it (like backup ones), will properly
			 * notify the change
			 */
			ip1_flags |= XFS_ICHGTIME_CHG;
			ip2_flags |= XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG;
		}

2928
		if (S_ISDIR(VFS_I(ip1)->i_mode)) {
2929
			error = xfs_dir_replace(tp, ip1, &xfs_name_dotdot,
2930
						dp2->i_ino, spaceres);
2931
			if (error)
2932
				goto out_trans_abort;
2933 2934

			/* transfer ip1 ".." reference to dp2 */
2935
			if (!S_ISDIR(VFS_I(ip2)->i_mode)) {
2936 2937
				error = xfs_droplink(tp, dp1);
				if (error)
2938
					goto out_trans_abort;
2939
				xfs_bumplink(tp, dp2);
2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966
			}

			/*
			 * Although ip2 isn't changed here, userspace needs
			 * to be warned about the change, so that applications
			 * relying on it (like backup ones), will properly
			 * notify the change
			 */
			ip1_flags |= XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG;
			ip2_flags |= XFS_ICHGTIME_CHG;
		}
	}

	if (ip1_flags) {
		xfs_trans_ichgtime(tp, ip1, ip1_flags);
		xfs_trans_log_inode(tp, ip1, XFS_ILOG_CORE);
	}
	if (ip2_flags) {
		xfs_trans_ichgtime(tp, ip2, ip2_flags);
		xfs_trans_log_inode(tp, ip2, XFS_ILOG_CORE);
	}
	if (dp2_flags) {
		xfs_trans_ichgtime(tp, dp2, dp2_flags);
		xfs_trans_log_inode(tp, dp2, XFS_ILOG_CORE);
	}
	xfs_trans_ichgtime(tp, dp1, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
	xfs_trans_log_inode(tp, dp1, XFS_ILOG_CORE);
2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980

	/*
	 * Inform our hook clients that we've finished an exchange operation as
	 * follows: removed the source and target files from their directories;
	 * added the target to the source directory; and added the source to
	 * the target directory.  All inodes are locked, so it's ok to model a
	 * rename this way so long as we say we deleted entries before we add
	 * new ones.
	 */
	xfs_dir_update_hook(dp1, ip1, -1, name1);
	xfs_dir_update_hook(dp2, ip2, -1, name2);
	xfs_dir_update_hook(dp1, ip2, 1, name1);
	xfs_dir_update_hook(dp2, ip1, 1, name2);

2981
	return xfs_finish_rename(tp);
2982 2983

out_trans_abort:
2984
	xfs_trans_cancel(tp);
2985 2986 2987
	return error;
}

2988 2989 2990
/*
 * xfs_rename_alloc_whiteout()
 *
2991
 * Return a referenced, unlinked, unlocked inode that can be used as a
2992 2993 2994 2995 2996 2997
 * whiteout in a rename transaction. We use a tmpfile inode here so that if we
 * crash between allocating the inode and linking it into the rename transaction
 * recovery will free the inode and we won't leak it.
 */
static int
xfs_rename_alloc_whiteout(
2998
	struct mnt_idmap	*idmap,
2999
	struct xfs_name		*src_name,
3000 3001 3002 3003
	struct xfs_inode	*dp,
	struct xfs_inode	**wip)
{
	struct xfs_inode	*tmpfile;
3004
	struct qstr		name;
3005 3006
	int			error;

3007
	error = xfs_create_tmpfile(idmap, dp, S_IFCHR | WHITEOUT_MODE,
3008
				   &tmpfile);
3009 3010 3011
	if (error)
		return error;

3012 3013 3014 3015 3016 3017 3018 3019 3020
	name.name = src_name->name;
	name.len = src_name->len;
	error = xfs_inode_init_security(VFS_I(tmpfile), VFS_I(dp), &name);
	if (error) {
		xfs_finish_inode_setup(tmpfile);
		xfs_irele(tmpfile);
		return error;
	}

3021 3022
	/*
	 * Prepare the tmpfile inode as if it were created through the VFS.
3023 3024
	 * Complete the inode setup and flag it as linkable.  nlink is already
	 * zero, so we can skip the drop_nlink.
3025
	 */
3026
	xfs_setup_iops(tmpfile);
3027 3028 3029 3030 3031 3032 3033
	xfs_finish_inode_setup(tmpfile);
	VFS_I(tmpfile)->i_state |= I_LINKABLE;

	*wip = tmpfile;
	return 0;
}

Dave Chinner's avatar
Dave Chinner committed
3034 3035 3036 3037 3038
/*
 * xfs_rename
 */
int
xfs_rename(
3039
	struct mnt_idmap	*idmap,
3040 3041 3042 3043 3044 3045 3046
	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)
Dave Chinner's avatar
Dave Chinner committed
3047
{
3048 3049 3050 3051
	struct xfs_mount	*mp = src_dp->i_mount;
	struct xfs_trans	*tp;
	struct xfs_inode	*wip = NULL;		/* whiteout inode */
	struct xfs_inode	*inodes[__XFS_SORT_INODES];
3052
	int			i;
3053
	int			num_inodes = __XFS_SORT_INODES;
3054
	bool			new_parent = (src_dp != target_dp);
3055
	bool			src_is_directory = S_ISDIR(VFS_I(src_ip)->i_mode);
3056
	int			spaceres;
3057 3058
	bool			retried = false;
	int			error, nospace_error = 0;
Dave Chinner's avatar
Dave Chinner committed
3059 3060 3061

	trace_xfs_rename(src_dp, target_dp, src_name, target_name);

3062 3063 3064
	if ((flags & RENAME_EXCHANGE) && !target_ip)
		return -EINVAL;

3065 3066 3067 3068 3069 3070
	/*
	 * If we are doing a whiteout operation, allocate the whiteout inode
	 * we will be placing at the target and ensure the type is set
	 * appropriately.
	 */
	if (flags & RENAME_WHITEOUT) {
3071
		error = xfs_rename_alloc_whiteout(idmap, src_name,
3072
						  target_dp, &wip);
3073 3074 3075 3076 3077 3078
		if (error)
			return error;

		/* setup target dirent info as whiteout */
		src_name->type = XFS_DIR3_FT_CHRDEV;
	}
Dave Chinner's avatar
Dave Chinner committed
3079

3080
	xfs_sort_for_rename(src_dp, target_dp, src_ip, target_ip, wip,
Dave Chinner's avatar
Dave Chinner committed
3081 3082
				inodes, &num_inodes);

3083 3084
retry:
	nospace_error = 0;
Dave Chinner's avatar
Dave Chinner committed
3085
	spaceres = XFS_RENAME_SPACE_RES(mp, target_name->len);
3086
	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_rename, spaceres, 0, 0, &tp);
3087
	if (error == -ENOSPC) {
3088
		nospace_error = error;
Dave Chinner's avatar
Dave Chinner committed
3089
		spaceres = 0;
3090 3091
		error = xfs_trans_alloc(mp, &M_RES(mp)->tr_rename, 0, 0, 0,
				&tp);
Dave Chinner's avatar
Dave Chinner committed
3092
	}
3093
	if (error)
3094
		goto out_release_wip;
Dave Chinner's avatar
Dave Chinner committed
3095 3096 3097 3098 3099

	/*
	 * Attach the dquots to the inodes
	 */
	error = xfs_qm_vop_rename_dqattach(inodes);
3100 3101
	if (error)
		goto out_trans_cancel;
Dave Chinner's avatar
Dave Chinner committed
3102 3103 3104 3105 3106

	/*
	 * Lock all the participating inodes. Depending upon whether
	 * the target_name exists in the target directory, and
	 * whether the target directory is the same as the source
3107
	 * directory, we can lock from 2 to 5 inodes.
Dave Chinner's avatar
Dave Chinner committed
3108 3109 3110 3111 3112 3113 3114 3115
	 */
	xfs_lock_inodes(inodes, num_inodes, XFS_ILOCK_EXCL);

	/*
	 * Join all the inodes to the transaction. From this point on,
	 * we can rely on either trans_commit or trans_cancel to unlock
	 * them.
	 */
3116
	xfs_trans_ijoin(tp, src_dp, XFS_ILOCK_EXCL);
Dave Chinner's avatar
Dave Chinner committed
3117
	if (new_parent)
3118
		xfs_trans_ijoin(tp, target_dp, XFS_ILOCK_EXCL);
Dave Chinner's avatar
Dave Chinner committed
3119 3120 3121
	xfs_trans_ijoin(tp, src_ip, XFS_ILOCK_EXCL);
	if (target_ip)
		xfs_trans_ijoin(tp, target_ip, XFS_ILOCK_EXCL);
3122 3123
	if (wip)
		xfs_trans_ijoin(tp, wip, XFS_ILOCK_EXCL);
Dave Chinner's avatar
Dave Chinner committed
3124 3125 3126 3127 3128 3129

	/*
	 * If we are using project inheritance, we only allow renames
	 * into our tree when the project IDs are the same; else the
	 * tree quota mechanism would be circumvented.
	 */
3130
	if (unlikely((target_dp->i_diflags & XFS_DIFLAG_PROJINHERIT) &&
3131
		     target_dp->i_projid != src_ip->i_projid)) {
3132
		error = -EXDEV;
3133
		goto out_trans_cancel;
Dave Chinner's avatar
Dave Chinner committed
3134 3135
	}

3136 3137 3138 3139
	/* RENAME_EXCHANGE is unique from here on. */
	if (flags & RENAME_EXCHANGE)
		return xfs_cross_rename(tp, src_dp, src_name, src_ip,
					target_dp, target_name, target_ip,
3140
					spaceres);
3141

3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166
	/*
	 * Try to reserve quota to handle an expansion of the target directory.
	 * We'll allow the rename to continue in reservationless mode if we hit
	 * a space usage constraint.  If we trigger reservationless mode, save
	 * the errno if there isn't any free space in the target directory.
	 */
	if (spaceres != 0) {
		error = xfs_trans_reserve_quota_nblks(tp, target_dp, spaceres,
				0, false);
		if (error == -EDQUOT || error == -ENOSPC) {
			if (!retried) {
				xfs_trans_cancel(tp);
				xfs_blockgc_free_quota(target_dp, 0);
				retried = true;
				goto retry;
			}

			nospace_error = error;
			spaceres = 0;
			error = 0;
		}
		if (error)
			goto out_trans_cancel;
	}

Dave Chinner's avatar
Dave Chinner committed
3167
	/*
3168 3169
	 * Check for expected errors before we dirty the transaction
	 * so we can return an error without a transaction abort.
Dave Chinner's avatar
Dave Chinner committed
3170 3171 3172 3173 3174 3175
	 */
	if (target_ip == NULL) {
		/*
		 * If there's no space reservation, check the entry will
		 * fit before actually inserting it.
		 */
3176 3177 3178
		if (!spaceres) {
			error = xfs_dir_canenter(tp, target_dp, target_name);
			if (error)
3179
				goto out_trans_cancel;
3180
		}
3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193
	} else {
		/*
		 * If target exists and it's a directory, check that whether
		 * it can be destroyed.
		 */
		if (S_ISDIR(VFS_I(target_ip)->i_mode) &&
		    (!xfs_dir_isempty(target_ip) ||
		     (VFS_I(target_ip)->i_nlink > 2))) {
			error = -EEXIST;
			goto out_trans_cancel;
		}
	}

3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207
	/*
	 * Lock the AGI buffers we need to handle bumping the nlink of the
	 * whiteout inode off the unlinked list and to handle dropping the
	 * nlink of the target inode.  Per locking order rules, do this in
	 * increasing AG order and before directory block allocation tries to
	 * grab AGFs because we grab AGIs before AGFs.
	 *
	 * The (vfs) caller must ensure that if src is a directory then
	 * target_ip is either null or an empty directory.
	 */
	for (i = 0; i < num_inodes && inodes[i] != NULL; i++) {
		if (inodes[i] == wip ||
		    (inodes[i] == target_ip &&
		     (VFS_I(target_ip)->i_nlink == 1 || src_is_directory))) {
3208 3209
			struct xfs_perag	*pag;
			struct xfs_buf		*bp;
3210

3211 3212
			pag = xfs_perag_get(mp,
					XFS_INO_TO_AGNO(mp, inodes[i]->i_ino));
3213
			error = xfs_read_agi(pag, tp, 0, &bp);
3214
			xfs_perag_put(pag);
3215 3216 3217 3218 3219
			if (error)
				goto out_trans_cancel;
		}
	}

3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232
	/*
	 * Directory entry creation below may acquire the AGF. Remove
	 * the whiteout from the unlinked list first to preserve correct
	 * AGI/AGF locking order. This dirties the transaction so failures
	 * after this point will abort and log recovery will clean up the
	 * mess.
	 *
	 * For whiteouts, we need to bump the link count on the whiteout
	 * inode. After this point, we have a real link, clear the tmpfile
	 * state flag from the inode so it doesn't accidentally get misused
	 * in future.
	 */
	if (wip) {
3233 3234
		struct xfs_perag	*pag;

3235
		ASSERT(VFS_I(wip)->i_nlink == 0);
3236 3237 3238 3239

		pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, wip->i_ino));
		error = xfs_iunlink_remove(tp, pag, wip);
		xfs_perag_put(pag);
3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250
		if (error)
			goto out_trans_cancel;

		xfs_bumplink(tp, wip);
		VFS_I(wip)->i_state &= ~I_LINKABLE;
	}

	/*
	 * Set up the target.
	 */
	if (target_ip == NULL) {
Dave Chinner's avatar
Dave Chinner committed
3251 3252 3253 3254 3255 3256
		/*
		 * If target does not exist and the rename crosses
		 * directories, adjust the target directory link count
		 * to account for the ".." reference from the new entry.
		 */
		error = xfs_dir_createname(tp, target_dp, target_name,
3257
					   src_ip->i_ino, spaceres);
Dave Chinner's avatar
Dave Chinner committed
3258
		if (error)
3259
			goto out_trans_cancel;
Dave Chinner's avatar
Dave Chinner committed
3260 3261 3262 3263 3264

		xfs_trans_ichgtime(tp, target_dp,
					XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);

		if (new_parent && src_is_directory) {
3265
			xfs_bumplink(tp, target_dp);
Dave Chinner's avatar
Dave Chinner committed
3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277
		}
	} else { /* target_ip != NULL */
		/*
		 * Link the source inode under the target name.
		 * If the source inode is a directory and we are moving
		 * it across directories, its ".." entry will be
		 * inconsistent until we replace that down below.
		 *
		 * In case there is already an entry with the same
		 * name at the destination directory, remove it first.
		 */
		error = xfs_dir_replace(tp, target_dp, target_name,
3278
					src_ip->i_ino, spaceres);
Dave Chinner's avatar
Dave Chinner committed
3279
		if (error)
3280
			goto out_trans_cancel;
Dave Chinner's avatar
Dave Chinner committed
3281 3282 3283 3284 3285 3286 3287 3288 3289 3290

		xfs_trans_ichgtime(tp, target_dp,
					XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);

		/*
		 * Decrement the link count on the target since the target
		 * dir no longer points to it.
		 */
		error = xfs_droplink(tp, target_ip);
		if (error)
3291
			goto out_trans_cancel;
Dave Chinner's avatar
Dave Chinner committed
3292 3293 3294 3295 3296 3297 3298

		if (src_is_directory) {
			/*
			 * Drop the link from the old "." entry.
			 */
			error = xfs_droplink(tp, target_ip);
			if (error)
3299
				goto out_trans_cancel;
Dave Chinner's avatar
Dave Chinner committed
3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311
		}
	} /* target_ip != NULL */

	/*
	 * Remove the source.
	 */
	if (new_parent && src_is_directory) {
		/*
		 * Rewrite the ".." entry to point to the new
		 * directory.
		 */
		error = xfs_dir_replace(tp, src_ip, &xfs_name_dotdot,
3312
					target_dp->i_ino, spaceres);
3313
		ASSERT(error != -EEXIST);
Dave Chinner's avatar
Dave Chinner committed
3314
		if (error)
3315
			goto out_trans_cancel;
Dave Chinner's avatar
Dave Chinner committed
3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340
	}

	/*
	 * We always want to hit the ctime on the source inode.
	 *
	 * This isn't strictly required by the standards since the source
	 * inode isn't really being changed, but old unix file systems did
	 * it and some incremental backup programs won't work without it.
	 */
	xfs_trans_ichgtime(tp, src_ip, XFS_ICHGTIME_CHG);
	xfs_trans_log_inode(tp, src_ip, XFS_ILOG_CORE);

	/*
	 * Adjust the link count on src_dp.  This is necessary when
	 * renaming a directory, either within one parent when
	 * the target existed, or across two parent directories.
	 */
	if (src_is_directory && (new_parent || target_ip != NULL)) {

		/*
		 * Decrement link count on src_directory since the
		 * entry that's moved no longer points to it.
		 */
		error = xfs_droplink(tp, src_dp);
		if (error)
3341
			goto out_trans_cancel;
Dave Chinner's avatar
Dave Chinner committed
3342 3343
	}

3344 3345 3346 3347 3348
	/*
	 * For whiteouts, we only need to update the source dirent with the
	 * inode number of the whiteout inode rather than removing it
	 * altogether.
	 */
3349
	if (wip)
3350
		error = xfs_dir_replace(tp, src_dp, src_name, wip->i_ino,
3351
					spaceres);
3352
	else
3353
		error = xfs_dir_removename(tp, src_dp, src_name, src_ip->i_ino,
3354
					   spaceres);
3355

Dave Chinner's avatar
Dave Chinner committed
3356
	if (error)
3357
		goto out_trans_cancel;
Dave Chinner's avatar
Dave Chinner committed
3358 3359 3360 3361 3362 3363

	xfs_trans_ichgtime(tp, src_dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
	xfs_trans_log_inode(tp, src_dp, XFS_ILOG_CORE);
	if (new_parent)
		xfs_trans_log_inode(tp, target_dp, XFS_ILOG_CORE);

3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378
	/*
	 * Inform our hook clients that we've finished a rename operation as
	 * follows: removed the source and target files from their directories;
	 * that we've added the source to the target directory; and finally
	 * that we've added the whiteout, if there was one.  All inodes are
	 * locked, so it's ok to model a rename this way so long as we say we
	 * deleted entries before we add new ones.
	 */
	if (target_ip)
		xfs_dir_update_hook(target_dp, target_ip, -1, target_name);
	xfs_dir_update_hook(src_dp, src_ip, -1, src_name);
	xfs_dir_update_hook(target_dp, src_ip, 1, target_name);
	if (wip)
		xfs_dir_update_hook(src_dp, wip, 1, src_name);

3379
	error = xfs_finish_rename(tp);
3380
	if (wip)
3381
		xfs_irele(wip);
3382
	return error;
Dave Chinner's avatar
Dave Chinner committed
3383

3384
out_trans_cancel:
3385
	xfs_trans_cancel(tp);
3386
out_release_wip:
3387
	if (wip)
3388
		xfs_irele(wip);
3389 3390
	if (error == -ENOSPC && nospace_error)
		error = nospace_error;
Dave Chinner's avatar
Dave Chinner committed
3391 3392 3393
	return error;
}

3394 3395
static int
xfs_iflush(
3396 3397
	struct xfs_inode	*ip,
	struct xfs_buf		*bp)
Linus Torvalds's avatar
Linus Torvalds committed
3398
{
3399 3400 3401
	struct xfs_inode_log_item *iip = ip->i_itemp;
	struct xfs_dinode	*dip;
	struct xfs_mount	*mp = ip->i_mount;
3402
	int			error;
Linus Torvalds's avatar
Linus Torvalds committed
3403

3404
	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL | XFS_ILOCK_SHARED);
3405
	ASSERT(xfs_iflags_test(ip, XFS_IFLUSHING));
3406
	ASSERT(ip->i_df.if_format != XFS_DINODE_FMT_BTREE ||
3407
	       ip->i_df.if_nextents > XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK));
3408
	ASSERT(iip->ili_item.li_buf == bp);
Linus Torvalds's avatar
Linus Torvalds committed
3409

3410
	dip = xfs_buf_offset(bp, ip->i_imap.im_boffset);
Linus Torvalds's avatar
Linus Torvalds committed
3411

3412 3413 3414 3415 3416 3417 3418
	/*
	 * We don't flush the inode if any of the following checks fail, but we
	 * do still update the log item and attach to the backing buffer as if
	 * the flush happened. This is a formality to facilitate predictable
	 * error handling as the caller will shutdown and fail the buffer.
	 */
	error = -EFSCORRUPTED;
3419
	if (XFS_TEST_ERROR(dip->di_magic != cpu_to_be16(XFS_DINODE_MAGIC),
3420
			       mp, XFS_ERRTAG_IFLUSH_1)) {
3421
		xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
3422
			"%s: Bad inode %llu magic number 0x%x, ptr "PTR_FMT,
3423
			__func__, ip->i_ino, be16_to_cpu(dip->di_magic), dip);
3424
		goto flush_out;
Linus Torvalds's avatar
Linus Torvalds committed
3425
	}
3426
	if (S_ISREG(VFS_I(ip)->i_mode)) {
Linus Torvalds's avatar
Linus Torvalds committed
3427
		if (XFS_TEST_ERROR(
3428 3429
		    ip->i_df.if_format != XFS_DINODE_FMT_EXTENTS &&
		    ip->i_df.if_format != XFS_DINODE_FMT_BTREE,
3430
		    mp, XFS_ERRTAG_IFLUSH_3)) {
3431
			xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
3432
				"%s: Bad regular inode %llu, ptr "PTR_FMT,
3433
				__func__, ip->i_ino, ip);
3434
			goto flush_out;
Linus Torvalds's avatar
Linus Torvalds committed
3435
		}
3436
	} else if (S_ISDIR(VFS_I(ip)->i_mode)) {
Linus Torvalds's avatar
Linus Torvalds committed
3437
		if (XFS_TEST_ERROR(
3438 3439 3440
		    ip->i_df.if_format != XFS_DINODE_FMT_EXTENTS &&
		    ip->i_df.if_format != XFS_DINODE_FMT_BTREE &&
		    ip->i_df.if_format != XFS_DINODE_FMT_LOCAL,
3441
		    mp, XFS_ERRTAG_IFLUSH_4)) {
3442
			xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
3443
				"%s: Bad directory inode %llu, ptr "PTR_FMT,
3444
				__func__, ip->i_ino, ip);
3445
			goto flush_out;
Linus Torvalds's avatar
Linus Torvalds committed
3446 3447
		}
	}
3448
	if (XFS_TEST_ERROR(ip->i_df.if_nextents + xfs_ifork_nextents(&ip->i_af) >
3449
				ip->i_nblocks, mp, XFS_ERRTAG_IFLUSH_5)) {
3450
		xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
3451 3452
			"%s: detected corrupt incore inode %llu, "
			"total extents = %llu nblocks = %lld, ptr "PTR_FMT,
3453
			__func__, ip->i_ino,
3454
			ip->i_df.if_nextents + xfs_ifork_nextents(&ip->i_af),
3455
			ip->i_nblocks, ip);
3456
		goto flush_out;
Linus Torvalds's avatar
Linus Torvalds committed
3457
	}
3458
	if (XFS_TEST_ERROR(ip->i_forkoff > mp->m_sb.sb_inodesize,
3459
				mp, XFS_ERRTAG_IFLUSH_6)) {
3460
		xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
3461
			"%s: bad inode %llu, forkoff 0x%x, ptr "PTR_FMT,
3462
			__func__, ip->i_ino, ip->i_forkoff, ip);
3463
		goto flush_out;
Linus Torvalds's avatar
Linus Torvalds committed
3464
	}
3465

Linus Torvalds's avatar
Linus Torvalds committed
3466
	/*
3467 3468 3469 3470 3471 3472
	 * Inode item log recovery for v2 inodes are dependent on the flushiter
	 * count for correct sequencing.  We bump the flush iteration count so
	 * we can detect flushes which postdate a log record during recovery.
	 * This is redundant as we now log every change and hence this can't
	 * happen but we need to still do it to ensure backwards compatibility
	 * with old kernels that predate logging all inode changes.
Linus Torvalds's avatar
Linus Torvalds committed
3473
	 */
3474
	if (!xfs_has_v3inodes(mp))
3475
		ip->i_flushiter++;
Linus Torvalds's avatar
Linus Torvalds committed
3476

3477 3478 3479 3480
	/*
	 * If there are inline format data / attr forks attached to this inode,
	 * make sure they are not corrupt.
	 */
3481
	if (ip->i_df.if_format == XFS_DINODE_FMT_LOCAL &&
3482 3483
	    xfs_ifork_verify_local_data(ip))
		goto flush_out;
3484
	if (xfs_inode_has_attr_fork(ip) &&
3485
	    ip->i_af.if_format == XFS_DINODE_FMT_LOCAL &&
3486
	    xfs_ifork_verify_local_attr(ip))
3487
		goto flush_out;
3488

Linus Torvalds's avatar
Linus Torvalds committed
3489
	/*
3490 3491 3492
	 * Copy the dirty parts of the inode into the on-disk inode.  We always
	 * copy out the core of the inode, because if the inode is dirty at all
	 * the core must be.
Linus Torvalds's avatar
Linus Torvalds committed
3493
	 */
3494
	xfs_inode_to_disk(ip, dip, iip->ili_item.li_lsn);
Linus Torvalds's avatar
Linus Torvalds committed
3495 3496

	/* Wrap, we never let the log put out DI_MAX_FLUSH */
3497
	if (!xfs_has_v3inodes(mp)) {
3498 3499 3500
		if (ip->i_flushiter == DI_MAX_FLUSH)
			ip->i_flushiter = 0;
	}
Linus Torvalds's avatar
Linus Torvalds committed
3501

3502
	xfs_iflush_fork(ip, dip, iip, XFS_DATA_FORK);
3503
	if (xfs_inode_has_attr_fork(ip))
3504
		xfs_iflush_fork(ip, dip, iip, XFS_ATTR_FORK);
Linus Torvalds's avatar
Linus Torvalds committed
3505 3506

	/*
3507 3508 3509 3510 3511 3512 3513
	 * We've recorded everything logged in the inode, so we'd like to clear
	 * the ili_fields bits so we don't log and flush things unnecessarily.
	 * However, we can't stop logging all this information until the data
	 * we've copied into the disk buffer is written to disk.  If we did we
	 * might overwrite the copy of the inode in the log with all the data
	 * after re-logging only part of it, and in the face of a crash we
	 * wouldn't have all the data we need to recover.
Linus Torvalds's avatar
Linus Torvalds committed
3514
	 *
3515 3516
	 * What we do is move the bits to the ili_last_fields field.  When
	 * logging the inode, these bits are moved back to the ili_fields field.
3517 3518
	 * In the xfs_buf_inode_iodone() routine we clear ili_last_fields, since
	 * we know that the information those bits represent is permanently on
3519 3520
	 * disk.  As long as the flush completes before the inode is logged
	 * again, then both ili_fields and ili_last_fields will be cleared.
Linus Torvalds's avatar
Linus Torvalds committed
3521
	 */
3522 3523
	error = 0;
flush_out:
Dave Chinner's avatar
Dave Chinner committed
3524
	spin_lock(&iip->ili_lock);
3525 3526
	iip->ili_last_fields = iip->ili_fields;
	iip->ili_fields = 0;
3527
	iip->ili_fsync_fields = 0;
Dave Chinner's avatar
Dave Chinner committed
3528
	spin_unlock(&iip->ili_lock);
Linus Torvalds's avatar
Linus Torvalds committed
3529

Dave Chinner's avatar
Dave Chinner committed
3530 3531
	/*
	 * Store the current LSN of the inode so that we can tell whether the
3532
	 * item has moved in the AIL from xfs_buf_inode_iodone().
Dave Chinner's avatar
Dave Chinner committed
3533
	 */
3534 3535
	xfs_trans_ail_copy_lsn(mp->m_ail, &iip->ili_flush_lsn,
				&iip->ili_item.li_lsn);
Linus Torvalds's avatar
Linus Torvalds committed
3536

3537 3538
	/* generate the checksum. */
	xfs_dinode_calc_crc(mp, dip);
3539 3540
	if (error)
		xfs_inode_mark_sick(ip, XFS_SICK_INO_CORE);
3541
	return error;
Linus Torvalds's avatar
Linus Torvalds committed
3542
}
3543

3544 3545 3546 3547 3548 3549 3550
/*
 * Non-blocking flush of dirty inode metadata into the backing buffer.
 *
 * The caller must have a reference to the inode and hold the cluster buffer
 * locked. The function will walk across all the inodes on the cluster buffer it
 * can find and lock without blocking, and flush them to the cluster buffer.
 *
3551 3552 3553 3554 3555
 * On successful flushing of at least one inode, the caller must write out the
 * buffer and release it. If no inodes are flushed, -EAGAIN will be returned and
 * the caller needs to release the buffer. On failure, the filesystem will be
 * shut down, the buffer will have been unlocked and released, and EFSCORRUPTED
 * will be returned.
3556 3557 3558 3559 3560
 */
int
xfs_iflush_cluster(
	struct xfs_buf		*bp)
{
3561 3562 3563 3564
	struct xfs_mount	*mp = bp->b_mount;
	struct xfs_log_item	*lip, *n;
	struct xfs_inode	*ip;
	struct xfs_inode_log_item *iip;
3565
	int			clcount = 0;
3566
	int			error = 0;
3567

3568 3569
	/*
	 * We must use the safe variant here as on shutdown xfs_iflush_abort()
3570
	 * will remove itself from the list.
3571 3572 3573 3574
	 */
	list_for_each_entry_safe(lip, n, &bp->b_li_list, li_bio_list) {
		iip = (struct xfs_inode_log_item *)lip;
		ip = iip->ili_inode;
3575 3576

		/*
3577
		 * Quick and dirty check to avoid locks if possible.
3578
		 */
3579
		if (__xfs_iflags_test(ip, XFS_IRECLAIM | XFS_IFLUSHING))
3580 3581
			continue;
		if (xfs_ipincount(ip))
3582 3583 3584
			continue;

		/*
3585 3586 3587 3588 3589
		 * The inode is still attached to the buffer, which means it is
		 * dirty but reclaim might try to grab it. Check carefully for
		 * that, and grab the ilock while still holding the i_flags_lock
		 * to guarantee reclaim will not be able to reclaim this inode
		 * once we drop the i_flags_lock.
3590
		 */
3591 3592
		spin_lock(&ip->i_flags_lock);
		ASSERT(!__xfs_iflags_test(ip, XFS_ISTALE));
3593
		if (__xfs_iflags_test(ip, XFS_IRECLAIM | XFS_IFLUSHING)) {
3594 3595
			spin_unlock(&ip->i_flags_lock);
			continue;
3596 3597 3598
		}

		/*
3599 3600
		 * ILOCK will pin the inode against reclaim and prevent
		 * concurrent transactions modifying the inode while we are
3601 3602
		 * flushing the inode. If we get the lock, set the flushing
		 * state before we drop the i_flags_lock.
3603
		 */
3604 3605
		if (!xfs_ilock_nowait(ip, XFS_ILOCK_SHARED)) {
			spin_unlock(&ip->i_flags_lock);
3606
			continue;
3607
		}
3608
		__xfs_iflags_set(ip, XFS_IFLUSHING);
3609
		spin_unlock(&ip->i_flags_lock);
3610 3611

		/*
3612 3613 3614 3615 3616
		 * Abort flushing this inode if we are shut down because the
		 * inode may not currently be in the AIL. This can occur when
		 * log I/O failure unpins the inode without inserting into the
		 * AIL, leaving a dirty/unpinned inode attached to the buffer
		 * that otherwise looks like it should be flushed.
3617
		 */
3618
		if (xlog_is_shutdown(mp->m_log)) {
3619 3620 3621 3622
			xfs_iunpin_wait(ip);
			xfs_iflush_abort(ip);
			xfs_iunlock(ip, XFS_ILOCK_SHARED);
			error = -EIO;
3623 3624 3625
			continue;
		}

3626 3627
		/* don't block waiting on a log force to unpin dirty inodes */
		if (xfs_ipincount(ip)) {
3628
			xfs_iflags_clear(ip, XFS_IFLUSHING);
3629 3630
			xfs_iunlock(ip, XFS_ILOCK_SHARED);
			continue;
3631 3632
		}

3633 3634 3635
		if (!xfs_inode_clean(ip))
			error = xfs_iflush(ip, bp);
		else
3636
			xfs_iflags_clear(ip, XFS_IFLUSHING);
3637 3638 3639 3640
		xfs_iunlock(ip, XFS_ILOCK_SHARED);
		if (error)
			break;
		clcount++;
3641 3642 3643
	}

	if (error) {
3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654
		/*
		 * Shutdown first so we kill the log before we release this
		 * buffer. If it is an INODE_ALLOC buffer and pins the tail
		 * of the log, failing it before the _log_ is shut down can
		 * result in the log tail being moved forward in the journal
		 * on disk because log writes can still be taking place. Hence
		 * unpinning the tail will allow the ICREATE intent to be
		 * removed from the log an recovery will fail with uninitialised
		 * inode cluster buffers.
		 */
		xfs_force_shutdown(mp, SHUTDOWN_CORRUPT_INCORE);
3655 3656
		bp->b_flags |= XBF_ASYNC;
		xfs_buf_ioend_fail(bp);
3657
		return error;
3658
	}
3659 3660 3661 3662 3663 3664 3665 3666

	if (!clcount)
		return -EAGAIN;

	XFS_STATS_INC(mp, xs_icluster_flushcnt);
	XFS_STATS_ADD(mp, xs_icluster_flushinode, clcount);
	return 0;

3667 3668
}

3669 3670 3671 3672 3673 3674 3675 3676
/* Release an inode. */
void
xfs_irele(
	struct xfs_inode	*ip)
{
	trace_xfs_irele(ip, _RET_IP_);
	iput(VFS_I(ip));
}
3677 3678 3679 3680 3681 3682 3683 3684

/*
 * Ensure all commited transactions touching the inode are written to the log.
 */
int
xfs_log_force_inode(
	struct xfs_inode	*ip)
{
3685
	xfs_csn_t		seq = 0;
3686 3687 3688

	xfs_ilock(ip, XFS_ILOCK_SHARED);
	if (xfs_ipincount(ip))
3689
		seq = ip->i_itemp->ili_commit_seq;
3690 3691
	xfs_iunlock(ip, XFS_ILOCK_SHARED);

3692
	if (!seq)
3693
		return 0;
3694
	return xfs_log_force_seq(ip->i_mount, seq, XFS_LOG_SYNC, NULL);
3695
}
3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751

/*
 * Grab the exclusive iolock for a data copy from src to dest, making sure to
 * abide vfs locking order (lowest pointer value goes first) and breaking the
 * layout leases before proceeding.  The loop is needed because we cannot call
 * the blocking break_layout() with the iolocks held, and therefore have to
 * back out both locks.
 */
static int
xfs_iolock_two_inodes_and_break_layout(
	struct inode		*src,
	struct inode		*dest)
{
	int			error;

	if (src > dest)
		swap(src, dest);

retry:
	/* Wait to break both inodes' layouts before we start locking. */
	error = break_layout(src, true);
	if (error)
		return error;
	if (src != dest) {
		error = break_layout(dest, true);
		if (error)
			return error;
	}

	/* Lock one inode and make sure nobody got in and leased it. */
	inode_lock(src);
	error = break_layout(src, false);
	if (error) {
		inode_unlock(src);
		if (error == -EWOULDBLOCK)
			goto retry;
		return error;
	}

	if (src == dest)
		return 0;

	/* Lock the other inode and make sure nobody got in and leased it. */
	inode_lock_nested(dest, I_MUTEX_NONDIR2);
	error = break_layout(dest, false);
	if (error) {
		inode_unlock(src);
		inode_unlock(dest);
		if (error == -EWOULDBLOCK)
			goto retry;
		return error;
	}

	return 0;
}

Shiyang Ruan's avatar
Shiyang Ruan committed
3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795
static int
xfs_mmaplock_two_inodes_and_break_dax_layout(
	struct xfs_inode	*ip1,
	struct xfs_inode	*ip2)
{
	int			error;
	bool			retry;
	struct page		*page;

	if (ip1->i_ino > ip2->i_ino)
		swap(ip1, ip2);

again:
	retry = false;
	/* Lock the first inode */
	xfs_ilock(ip1, XFS_MMAPLOCK_EXCL);
	error = xfs_break_dax_layouts(VFS_I(ip1), &retry);
	if (error || retry) {
		xfs_iunlock(ip1, XFS_MMAPLOCK_EXCL);
		if (error == 0 && retry)
			goto again;
		return error;
	}

	if (ip1 == ip2)
		return 0;

	/* Nested lock the second inode */
	xfs_ilock(ip2, xfs_lock_inumorder(XFS_MMAPLOCK_EXCL, 1));
	/*
	 * We cannot use xfs_break_dax_layouts() directly here because it may
	 * need to unlock & lock the XFS_MMAPLOCK_EXCL which is not suitable
	 * for this nested lock case.
	 */
	page = dax_layout_busy_page(VFS_I(ip2)->i_mapping);
	if (page && page_ref_count(page) != 1) {
		xfs_iunlock(ip2, XFS_MMAPLOCK_EXCL);
		xfs_iunlock(ip1, XFS_MMAPLOCK_EXCL);
		goto again;
	}

	return 0;
}

3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809
/*
 * Lock two inodes so that userspace cannot initiate I/O via file syscalls or
 * mmap activity.
 */
int
xfs_ilock2_io_mmap(
	struct xfs_inode	*ip1,
	struct xfs_inode	*ip2)
{
	int			ret;

	ret = xfs_iolock_two_inodes_and_break_layout(VFS_I(ip1), VFS_I(ip2));
	if (ret)
		return ret;
Shiyang Ruan's avatar
Shiyang Ruan committed
3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822

	if (IS_DAX(VFS_I(ip1)) && IS_DAX(VFS_I(ip2))) {
		ret = xfs_mmaplock_two_inodes_and_break_dax_layout(ip1, ip2);
		if (ret) {
			inode_unlock(VFS_I(ip2));
			if (ip1 != ip2)
				inode_unlock(VFS_I(ip1));
			return ret;
		}
	} else
		filemap_invalidate_lock_two(VFS_I(ip1)->i_mapping,
					    VFS_I(ip2)->i_mapping);

3823 3824 3825 3826 3827 3828 3829 3830 3831
	return 0;
}

/* Unlock both inodes to allow IO and mmap activity. */
void
xfs_iunlock2_io_mmap(
	struct xfs_inode	*ip1,
	struct xfs_inode	*ip2)
{
Shiyang Ruan's avatar
Shiyang Ruan committed
3832 3833 3834 3835 3836 3837 3838 3839
	if (IS_DAX(VFS_I(ip1)) && IS_DAX(VFS_I(ip2))) {
		xfs_iunlock(ip2, XFS_MMAPLOCK_EXCL);
		if (ip1 != ip2)
			xfs_iunlock(ip1, XFS_MMAPLOCK_EXCL);
	} else
		filemap_invalidate_unlock_two(VFS_I(ip1)->i_mapping,
					      VFS_I(ip2)->i_mapping);

3840
	inode_unlock(VFS_I(ip2));
3841
	if (ip1 != ip2)
3842 3843
		inode_unlock(VFS_I(ip1));
}
3844

3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861
/* Drop the MMAPLOCK and the IOLOCK after a remap completes. */
void
xfs_iunlock2_remapping(
	struct xfs_inode	*ip1,
	struct xfs_inode	*ip2)
{
	xfs_iflags_clear(ip1, XFS_IREMAPPING);

	if (ip1 != ip2)
		xfs_iunlock(ip1, XFS_MMAPLOCK_SHARED);
	xfs_iunlock(ip2, XFS_MMAPLOCK_EXCL);

	if (ip1 != ip2)
		inode_unlock_shared(VFS_I(ip1));
	inode_unlock(VFS_I(ip2));
}

3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884
/*
 * Reload the incore inode list for this inode.  Caller should ensure that
 * the link count cannot change, either by taking ILOCK_SHARED or otherwise
 * preventing other threads from executing.
 */
int
xfs_inode_reload_unlinked_bucket(
	struct xfs_trans	*tp,
	struct xfs_inode	*ip)
{
	struct xfs_mount	*mp = tp->t_mountp;
	struct xfs_buf		*agibp;
	struct xfs_agi		*agi;
	struct xfs_perag	*pag;
	xfs_agnumber_t		agno = XFS_INO_TO_AGNO(mp, ip->i_ino);
	xfs_agino_t		agino = XFS_INO_TO_AGINO(mp, ip->i_ino);
	xfs_agino_t		prev_agino, next_agino;
	unsigned int		bucket;
	bool			foundit = false;
	int			error;

	/* Grab the first inode in the list */
	pag = xfs_perag_get(mp, agno);
3885
	error = xfs_ialloc_read_agi(pag, tp, 0, &agibp);
3886 3887 3888 3889
	xfs_perag_put(pag);
	if (error)
		return error;

3890 3891 3892 3893 3894 3895 3896 3897 3898 3899
	/*
	 * We've taken ILOCK_SHARED and the AGI buffer lock to stabilize the
	 * incore unlinked list pointers for this inode.  Check once more to
	 * see if we raced with anyone else to reload the unlinked list.
	 */
	if (!xfs_inode_unlinked_incomplete(ip)) {
		foundit = true;
		goto out_agibp;
	}

3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913
	bucket = agino % XFS_AGI_UNLINKED_BUCKETS;
	agi = agibp->b_addr;

	trace_xfs_inode_reload_unlinked_bucket(ip);

	xfs_info_ratelimited(mp,
 "Found unrecovered unlinked inode 0x%x in AG 0x%x.  Initiating list recovery.",
			agino, agno);

	prev_agino = NULLAGINO;
	next_agino = be32_to_cpu(agi->agi_unlinked[bucket]);
	while (next_agino != NULLAGINO) {
		struct xfs_inode	*next_ip = NULL;

3914
		/* Found this caller's inode, set its backlink. */
3915 3916 3917 3918
		if (next_agino == agino) {
			next_ip = ip;
			next_ip->i_prev_unlinked = prev_agino;
			foundit = true;
3919
			goto next_inode;
3920 3921
		}

3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934
		/* Try in-memory lookup first. */
		next_ip = xfs_iunlink_lookup(pag, next_agino);
		if (next_ip)
			goto next_inode;

		/* Inode not in memory, try reloading it. */
		error = xfs_iunlink_reload_next(tp, agibp, prev_agino,
				next_agino);
		if (error)
			break;

		/* Grab the reloaded inode. */
		next_ip = xfs_iunlink_lookup(pag, next_agino);
3935 3936 3937 3938 3939 3940 3941
		if (!next_ip) {
			/* No incore inode at all?  We reloaded it... */
			ASSERT(next_ip != NULL);
			error = -EFSCORRUPTED;
			break;
		}

3942
next_inode:
3943 3944 3945 3946
		prev_agino = next_agino;
		next_agino = next_ip->i_next_unlinked;
	}

3947
out_agibp:
3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974
	xfs_trans_brelse(tp, agibp);
	/* Should have found this inode somewhere in the iunlinked bucket. */
	if (!error && !foundit)
		error = -EFSCORRUPTED;
	return error;
}

/* Decide if this inode is missing its unlinked list and reload it. */
int
xfs_inode_reload_unlinked(
	struct xfs_inode	*ip)
{
	struct xfs_trans	*tp;
	int			error;

	error = xfs_trans_alloc_empty(ip->i_mount, &tp);
	if (error)
		return error;

	xfs_ilock(ip, XFS_ILOCK_SHARED);
	if (xfs_inode_unlinked_incomplete(ip))
		error = xfs_inode_reload_unlinked_bucket(tp, ip);
	xfs_iunlock(ip, XFS_ILOCK_SHARED);
	xfs_trans_cancel(tp);

	return error;
}
3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000

/* Has this inode fork been zapped by repair? */
bool
xfs_ifork_zapped(
	const struct xfs_inode	*ip,
	int			whichfork)
{
	unsigned int		datamask = 0;

	switch (whichfork) {
	case XFS_DATA_FORK:
		switch (ip->i_vnode.i_mode & S_IFMT) {
		case S_IFDIR:
			datamask = XFS_SICK_INO_DIR_ZAPPED;
			break;
		case S_IFLNK:
			datamask = XFS_SICK_INO_SYMLINK_ZAPPED;
			break;
		}
		return ip->i_sick & (XFS_SICK_INO_BMBTD_ZAPPED | datamask);
	case XFS_ATTR_FORK:
		return ip->i_sick & XFS_SICK_INO_BMBTA_ZAPPED;
	default:
		return false;
	}
}
4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016

/* Compute the number of data and realtime blocks used by a file. */
void
xfs_inode_count_blocks(
	struct xfs_trans	*tp,
	struct xfs_inode	*ip,
	xfs_filblks_t		*dblocks,
	xfs_filblks_t		*rblocks)
{
	struct xfs_ifork	*ifp = xfs_ifork_ptr(ip, XFS_DATA_FORK);

	*rblocks = 0;
	if (XFS_IS_REALTIME_INODE(ip))
		xfs_bmap_count_leaves(ifp, rblocks);
	*dblocks = ip->i_nblocks - *rblocks;
}
4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077

static void
xfs_wait_dax_page(
	struct inode		*inode)
{
	struct xfs_inode        *ip = XFS_I(inode);

	xfs_iunlock(ip, XFS_MMAPLOCK_EXCL);
	schedule();
	xfs_ilock(ip, XFS_MMAPLOCK_EXCL);
}

int
xfs_break_dax_layouts(
	struct inode		*inode,
	bool			*retry)
{
	struct page		*page;

	xfs_assert_ilocked(XFS_I(inode), XFS_MMAPLOCK_EXCL);

	page = dax_layout_busy_page(inode->i_mapping);
	if (!page)
		return 0;

	*retry = true;
	return ___wait_var_event(&page->_refcount,
			atomic_read(&page->_refcount) == 1, TASK_INTERRUPTIBLE,
			0, 0, xfs_wait_dax_page(inode));
}

int
xfs_break_layouts(
	struct inode		*inode,
	uint			*iolock,
	enum layout_break_reason reason)
{
	bool			retry;
	int			error;

	xfs_assert_ilocked(XFS_I(inode), XFS_IOLOCK_SHARED | XFS_IOLOCK_EXCL);

	do {
		retry = false;
		switch (reason) {
		case BREAK_UNMAP:
			error = xfs_break_dax_layouts(inode, &retry);
			if (error || retry)
				break;
			fallthrough;
		case BREAK_WRITE:
			error = xfs_break_leased_layouts(inode, iolock, &retry);
			break;
		default:
			WARN_ON_ONCE(1);
			error = -EINVAL;
		}
	} while (error == 0 && retry);

	return error;
}
4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090

/* Returns the size of fundamental allocation unit for a file, in bytes. */
unsigned int
xfs_inode_alloc_unitsize(
	struct xfs_inode	*ip)
{
	unsigned int		blocks = 1;

	if (XFS_IS_REALTIME_INODE(ip))
		blocks = ip->i_mount->m_sb.sb_rextsize;

	return XFS_FSB_TO_B(ip->i_mount, blocks);
}