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