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