bba8f37525b3867576aea0acaf3adddbadbe7f2b
[firefly-linux-kernel-4.4.55.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_types.h"
23 #include "xfs_log.h"
24 #include "xfs_inum.h"
25 #include "xfs_trans.h"
26 #include "xfs_trans_priv.h"
27 #include "xfs_sb.h"
28 #include "xfs_ag.h"
29 #include "xfs_mount.h"
30 #include "xfs_bmap_btree.h"
31 #include "xfs_alloc_btree.h"
32 #include "xfs_ialloc_btree.h"
33 #include "xfs_attr_sf.h"
34 #include "xfs_dinode.h"
35 #include "xfs_inode.h"
36 #include "xfs_buf_item.h"
37 #include "xfs_inode_item.h"
38 #include "xfs_btree.h"
39 #include "xfs_alloc.h"
40 #include "xfs_ialloc.h"
41 #include "xfs_bmap.h"
42 #include "xfs_error.h"
43 #include "xfs_utils.h"
44 #include "xfs_quota.h"
45 #include "xfs_filestream.h"
46 #include "xfs_vnodeops.h"
47 #include "xfs_trace.h"
48 #include "xfs_icache.h"
49
50 kmem_zone_t *xfs_ifork_zone;
51 kmem_zone_t *xfs_inode_zone;
52
53 /*
54  * Used in xfs_itruncate_extents().  This is the maximum number of extents
55  * freed from a file in a single transaction.
56  */
57 #define XFS_ITRUNC_MAX_EXTENTS  2
58
59 STATIC int xfs_iflush_int(xfs_inode_t *, xfs_buf_t *);
60 STATIC int xfs_iformat_local(xfs_inode_t *, xfs_dinode_t *, int, int);
61 STATIC int xfs_iformat_extents(xfs_inode_t *, xfs_dinode_t *, int);
62 STATIC int xfs_iformat_btree(xfs_inode_t *, xfs_dinode_t *, int);
63
64 /*
65  * helper function to extract extent size hint from inode
66  */
67 xfs_extlen_t
68 xfs_get_extsz_hint(
69         struct xfs_inode        *ip)
70 {
71         if ((ip->i_d.di_flags & XFS_DIFLAG_EXTSIZE) && ip->i_d.di_extsize)
72                 return ip->i_d.di_extsize;
73         if (XFS_IS_REALTIME_INODE(ip))
74                 return ip->i_mount->m_sb.sb_rextsize;
75         return 0;
76 }
77
78 /*
79  * This is a wrapper routine around the xfs_ilock() routine used to centralize
80  * some grungy code.  It is used in places that wish to lock the inode solely
81  * for reading the extents.  The reason these places can't just call
82  * xfs_ilock(SHARED) is that the inode lock also guards to bringing in of the
83  * extents from disk for a file in b-tree format.  If the inode is in b-tree
84  * format, then we need to lock the inode exclusively until the extents are read
85  * in.  Locking it exclusively all the time would limit our parallelism
86  * unnecessarily, though.  What we do instead is check to see if the extents
87  * have been read in yet, and only lock the inode exclusively if they have not.
88  *
89  * The function returns a value which should be given to the corresponding
90  * xfs_iunlock_map_shared().  This value is the mode in which the lock was
91  * actually taken.
92  */
93 uint
94 xfs_ilock_map_shared(
95         xfs_inode_t     *ip)
96 {
97         uint    lock_mode;
98
99         if ((ip->i_d.di_format == XFS_DINODE_FMT_BTREE) &&
100             ((ip->i_df.if_flags & XFS_IFEXTENTS) == 0)) {
101                 lock_mode = XFS_ILOCK_EXCL;
102         } else {
103                 lock_mode = XFS_ILOCK_SHARED;
104         }
105
106         xfs_ilock(ip, lock_mode);
107
108         return lock_mode;
109 }
110
111 /*
112  * This is simply the unlock routine to go with xfs_ilock_map_shared().
113  * All it does is call xfs_iunlock() with the given lock_mode.
114  */
115 void
116 xfs_iunlock_map_shared(
117         xfs_inode_t     *ip,
118         unsigned int    lock_mode)
119 {
120         xfs_iunlock(ip, lock_mode);
121 }
122
123 /*
124  * The xfs inode contains 2 locks: a multi-reader lock called the
125  * i_iolock and a multi-reader lock called the i_lock.  This routine
126  * allows either or both of the locks to be obtained.
127  *
128  * The 2 locks should always be ordered so that the IO lock is
129  * obtained first in order to prevent deadlock.
130  *
131  * ip -- the inode being locked
132  * lock_flags -- this parameter indicates the inode's locks
133  *       to be locked.  It can be:
134  *              XFS_IOLOCK_SHARED,
135  *              XFS_IOLOCK_EXCL,
136  *              XFS_ILOCK_SHARED,
137  *              XFS_ILOCK_EXCL,
138  *              XFS_IOLOCK_SHARED | XFS_ILOCK_SHARED,
139  *              XFS_IOLOCK_SHARED | XFS_ILOCK_EXCL,
140  *              XFS_IOLOCK_EXCL | XFS_ILOCK_SHARED,
141  *              XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL
142  */
143 void
144 xfs_ilock(
145         xfs_inode_t             *ip,
146         uint                    lock_flags)
147 {
148         trace_xfs_ilock(ip, lock_flags, _RET_IP_);
149
150         /*
151          * You can't set both SHARED and EXCL for the same lock,
152          * and only XFS_IOLOCK_SHARED, XFS_IOLOCK_EXCL, XFS_ILOCK_SHARED,
153          * and XFS_ILOCK_EXCL are valid values to set in lock_flags.
154          */
155         ASSERT((lock_flags & (XFS_IOLOCK_SHARED | XFS_IOLOCK_EXCL)) !=
156                (XFS_IOLOCK_SHARED | XFS_IOLOCK_EXCL));
157         ASSERT((lock_flags & (XFS_ILOCK_SHARED | XFS_ILOCK_EXCL)) !=
158                (XFS_ILOCK_SHARED | XFS_ILOCK_EXCL));
159         ASSERT((lock_flags & ~(XFS_LOCK_MASK | XFS_LOCK_DEP_MASK)) == 0);
160
161         if (lock_flags & XFS_IOLOCK_EXCL)
162                 mrupdate_nested(&ip->i_iolock, XFS_IOLOCK_DEP(lock_flags));
163         else if (lock_flags & XFS_IOLOCK_SHARED)
164                 mraccess_nested(&ip->i_iolock, XFS_IOLOCK_DEP(lock_flags));
165
166         if (lock_flags & XFS_ILOCK_EXCL)
167                 mrupdate_nested(&ip->i_lock, XFS_ILOCK_DEP(lock_flags));
168         else if (lock_flags & XFS_ILOCK_SHARED)
169                 mraccess_nested(&ip->i_lock, XFS_ILOCK_DEP(lock_flags));
170 }
171
172 /*
173  * This is just like xfs_ilock(), except that the caller
174  * is guaranteed not to sleep.  It returns 1 if it gets
175  * the requested locks and 0 otherwise.  If the IO lock is
176  * obtained but the inode lock cannot be, then the IO lock
177  * is dropped before returning.
178  *
179  * ip -- the inode being locked
180  * lock_flags -- this parameter indicates the inode's locks to be
181  *       to be locked.  See the comment for xfs_ilock() for a list
182  *       of valid values.
183  */
184 int
185 xfs_ilock_nowait(
186         xfs_inode_t             *ip,
187         uint                    lock_flags)
188 {
189         trace_xfs_ilock_nowait(ip, lock_flags, _RET_IP_);
190
191         /*
192          * You can't set both SHARED and EXCL for the same lock,
193          * and only XFS_IOLOCK_SHARED, XFS_IOLOCK_EXCL, XFS_ILOCK_SHARED,
194          * and XFS_ILOCK_EXCL are valid values to set in lock_flags.
195          */
196         ASSERT((lock_flags & (XFS_IOLOCK_SHARED | XFS_IOLOCK_EXCL)) !=
197                (XFS_IOLOCK_SHARED | XFS_IOLOCK_EXCL));
198         ASSERT((lock_flags & (XFS_ILOCK_SHARED | XFS_ILOCK_EXCL)) !=
199                (XFS_ILOCK_SHARED | XFS_ILOCK_EXCL));
200         ASSERT((lock_flags & ~(XFS_LOCK_MASK | XFS_LOCK_DEP_MASK)) == 0);
201
202         if (lock_flags & XFS_IOLOCK_EXCL) {
203                 if (!mrtryupdate(&ip->i_iolock))
204                         goto out;
205         } else if (lock_flags & XFS_IOLOCK_SHARED) {
206                 if (!mrtryaccess(&ip->i_iolock))
207                         goto out;
208         }
209         if (lock_flags & XFS_ILOCK_EXCL) {
210                 if (!mrtryupdate(&ip->i_lock))
211                         goto out_undo_iolock;
212         } else if (lock_flags & XFS_ILOCK_SHARED) {
213                 if (!mrtryaccess(&ip->i_lock))
214                         goto out_undo_iolock;
215         }
216         return 1;
217
218  out_undo_iolock:
219         if (lock_flags & XFS_IOLOCK_EXCL)
220                 mrunlock_excl(&ip->i_iolock);
221         else if (lock_flags & XFS_IOLOCK_SHARED)
222                 mrunlock_shared(&ip->i_iolock);
223  out:
224         return 0;
225 }
226
227 /*
228  * xfs_iunlock() is used to drop the inode locks acquired with
229  * xfs_ilock() and xfs_ilock_nowait().  The caller must pass
230  * in the flags given to xfs_ilock() or xfs_ilock_nowait() so
231  * that we know which locks to drop.
232  *
233  * ip -- the inode being unlocked
234  * lock_flags -- this parameter indicates the inode's locks to be
235  *       to be unlocked.  See the comment for xfs_ilock() for a list
236  *       of valid values for this parameter.
237  *
238  */
239 void
240 xfs_iunlock(
241         xfs_inode_t             *ip,
242         uint                    lock_flags)
243 {
244         /*
245          * You can't set both SHARED and EXCL for the same lock,
246          * and only XFS_IOLOCK_SHARED, XFS_IOLOCK_EXCL, XFS_ILOCK_SHARED,
247          * and XFS_ILOCK_EXCL are valid values to set in lock_flags.
248          */
249         ASSERT((lock_flags & (XFS_IOLOCK_SHARED | XFS_IOLOCK_EXCL)) !=
250                (XFS_IOLOCK_SHARED | XFS_IOLOCK_EXCL));
251         ASSERT((lock_flags & (XFS_ILOCK_SHARED | XFS_ILOCK_EXCL)) !=
252                (XFS_ILOCK_SHARED | XFS_ILOCK_EXCL));
253         ASSERT((lock_flags & ~(XFS_LOCK_MASK | XFS_LOCK_DEP_MASK)) == 0);
254         ASSERT(lock_flags != 0);
255
256         if (lock_flags & XFS_IOLOCK_EXCL)
257                 mrunlock_excl(&ip->i_iolock);
258         else if (lock_flags & XFS_IOLOCK_SHARED)
259                 mrunlock_shared(&ip->i_iolock);
260
261         if (lock_flags & XFS_ILOCK_EXCL)
262                 mrunlock_excl(&ip->i_lock);
263         else if (lock_flags & XFS_ILOCK_SHARED)
264                 mrunlock_shared(&ip->i_lock);
265
266         trace_xfs_iunlock(ip, lock_flags, _RET_IP_);
267 }
268
269 /*
270  * give up write locks.  the i/o lock cannot be held nested
271  * if it is being demoted.
272  */
273 void
274 xfs_ilock_demote(
275         xfs_inode_t             *ip,
276         uint                    lock_flags)
277 {
278         ASSERT(lock_flags & (XFS_IOLOCK_EXCL|XFS_ILOCK_EXCL));
279         ASSERT((lock_flags & ~(XFS_IOLOCK_EXCL|XFS_ILOCK_EXCL)) == 0);
280
281         if (lock_flags & XFS_ILOCK_EXCL)
282                 mrdemote(&ip->i_lock);
283         if (lock_flags & XFS_IOLOCK_EXCL)
284                 mrdemote(&ip->i_iolock);
285
286         trace_xfs_ilock_demote(ip, lock_flags, _RET_IP_);
287 }
288
289 #ifdef DEBUG
290 int
291 xfs_isilocked(
292         xfs_inode_t             *ip,
293         uint                    lock_flags)
294 {
295         if (lock_flags & (XFS_ILOCK_EXCL|XFS_ILOCK_SHARED)) {
296                 if (!(lock_flags & XFS_ILOCK_SHARED))
297                         return !!ip->i_lock.mr_writer;
298                 return rwsem_is_locked(&ip->i_lock.mr_lock);
299         }
300
301         if (lock_flags & (XFS_IOLOCK_EXCL|XFS_IOLOCK_SHARED)) {
302                 if (!(lock_flags & XFS_IOLOCK_SHARED))
303                         return !!ip->i_iolock.mr_writer;
304                 return rwsem_is_locked(&ip->i_iolock.mr_lock);
305         }
306
307         ASSERT(0);
308         return 0;
309 }
310 #endif
311
312 void
313 __xfs_iflock(
314         struct xfs_inode        *ip)
315 {
316         wait_queue_head_t *wq = bit_waitqueue(&ip->i_flags, __XFS_IFLOCK_BIT);
317         DEFINE_WAIT_BIT(wait, &ip->i_flags, __XFS_IFLOCK_BIT);
318
319         do {
320                 prepare_to_wait_exclusive(wq, &wait.wait, TASK_UNINTERRUPTIBLE);
321                 if (xfs_isiflocked(ip))
322                         io_schedule();
323         } while (!xfs_iflock_nowait(ip));
324
325         finish_wait(wq, &wait.wait);
326 }
327
328 #ifdef DEBUG
329 /*
330  * Make sure that the extents in the given memory buffer
331  * are valid.
332  */
333 STATIC void
334 xfs_validate_extents(
335         xfs_ifork_t             *ifp,
336         int                     nrecs,
337         xfs_exntfmt_t           fmt)
338 {
339         xfs_bmbt_irec_t         irec;
340         xfs_bmbt_rec_host_t     rec;
341         int                     i;
342
343         for (i = 0; i < nrecs; i++) {
344                 xfs_bmbt_rec_host_t *ep = xfs_iext_get_ext(ifp, i);
345                 rec.l0 = get_unaligned(&ep->l0);
346                 rec.l1 = get_unaligned(&ep->l1);
347                 xfs_bmbt_get_all(&rec, &irec);
348                 if (fmt == XFS_EXTFMT_NOSTATE)
349                         ASSERT(irec.br_state == XFS_EXT_NORM);
350         }
351 }
352 #else /* DEBUG */
353 #define xfs_validate_extents(ifp, nrecs, fmt)
354 #endif /* DEBUG */
355
356 /*
357  * Check that none of the inode's in the buffer have a next
358  * unlinked field of 0.
359  */
360 #if defined(DEBUG)
361 void
362 xfs_inobp_check(
363         xfs_mount_t     *mp,
364         xfs_buf_t       *bp)
365 {
366         int             i;
367         int             j;
368         xfs_dinode_t    *dip;
369
370         j = mp->m_inode_cluster_size >> mp->m_sb.sb_inodelog;
371
372         for (i = 0; i < j; i++) {
373                 dip = (xfs_dinode_t *)xfs_buf_offset(bp,
374                                         i * mp->m_sb.sb_inodesize);
375                 if (!dip->di_next_unlinked)  {
376                         xfs_alert(mp,
377         "Detected bogus zero next_unlinked field in incore inode buffer 0x%p.",
378                                 bp);
379                         ASSERT(dip->di_next_unlinked);
380                 }
381         }
382 }
383 #endif
384
385 /*
386  * This routine is called to map an inode to the buffer containing the on-disk
387  * version of the inode.  It returns a pointer to the buffer containing the
388  * on-disk inode in the bpp parameter, and in the dipp parameter it returns a
389  * pointer to the on-disk inode within that buffer.
390  *
391  * If a non-zero error is returned, then the contents of bpp and dipp are
392  * undefined.
393  */
394 int
395 xfs_imap_to_bp(
396         struct xfs_mount        *mp,
397         struct xfs_trans        *tp,
398         struct xfs_imap         *imap,
399         struct xfs_dinode       **dipp,
400         struct xfs_buf          **bpp,
401         uint                    buf_flags,
402         uint                    iget_flags)
403 {
404         struct xfs_buf          *bp;
405         int                     error;
406         int                     i;
407         int                     ni;
408
409         buf_flags |= XBF_UNMAPPED;
410         error = xfs_trans_read_buf(mp, tp, mp->m_ddev_targp, imap->im_blkno,
411                                    (int)imap->im_len, buf_flags, &bp);
412         if (error) {
413                 if (error != EAGAIN) {
414                         xfs_warn(mp,
415                                 "%s: xfs_trans_read_buf() returned error %d.",
416                                 __func__, error);
417                 } else {
418                         ASSERT(buf_flags & XBF_TRYLOCK);
419                 }
420                 return error;
421         }
422
423         /*
424          * Validate the magic number and version of every inode in the buffer
425          * (if DEBUG kernel) or the first inode in the buffer, otherwise.
426          */
427 #ifdef DEBUG
428         ni = BBTOB(imap->im_len) >> mp->m_sb.sb_inodelog;
429 #else   /* usual case */
430         ni = 1;
431 #endif
432
433         for (i = 0; i < ni; i++) {
434                 int             di_ok;
435                 xfs_dinode_t    *dip;
436
437                 dip = (xfs_dinode_t *)xfs_buf_offset(bp,
438                                         (i << mp->m_sb.sb_inodelog));
439                 di_ok = dip->di_magic == cpu_to_be16(XFS_DINODE_MAGIC) &&
440                             XFS_DINODE_GOOD_VERSION(dip->di_version);
441                 if (unlikely(XFS_TEST_ERROR(!di_ok, mp,
442                                                 XFS_ERRTAG_ITOBP_INOTOBP,
443                                                 XFS_RANDOM_ITOBP_INOTOBP))) {
444                         if (iget_flags & XFS_IGET_UNTRUSTED) {
445                                 xfs_trans_brelse(tp, bp);
446                                 return XFS_ERROR(EINVAL);
447                         }
448                         XFS_CORRUPTION_ERROR(__func__, XFS_ERRLEVEL_HIGH,
449                                              mp, dip);
450 #ifdef DEBUG
451                         xfs_emerg(mp,
452                                 "bad inode magic/vsn daddr %lld #%d (magic=%x)",
453                                 (unsigned long long)imap->im_blkno, i,
454                                 be16_to_cpu(dip->di_magic));
455                         ASSERT(0);
456 #endif
457                         xfs_trans_brelse(tp, bp);
458                         return XFS_ERROR(EFSCORRUPTED);
459                 }
460         }
461
462         xfs_inobp_check(mp, bp);
463
464         *bpp = bp;
465         *dipp = (struct xfs_dinode *)xfs_buf_offset(bp, imap->im_boffset);
466         return 0;
467 }
468
469 /*
470  * Move inode type and inode format specific information from the
471  * on-disk inode to the in-core inode.  For fifos, devs, and sockets
472  * this means set if_rdev to the proper value.  For files, directories,
473  * and symlinks this means to bring in the in-line data or extent
474  * pointers.  For a file in B-tree format, only the root is immediately
475  * brought in-core.  The rest will be in-lined in if_extents when it
476  * is first referenced (see xfs_iread_extents()).
477  */
478 STATIC int
479 xfs_iformat(
480         xfs_inode_t             *ip,
481         xfs_dinode_t            *dip)
482 {
483         xfs_attr_shortform_t    *atp;
484         int                     size;
485         int                     error = 0;
486         xfs_fsize_t             di_size;
487
488         if (unlikely(be32_to_cpu(dip->di_nextents) +
489                      be16_to_cpu(dip->di_anextents) >
490                      be64_to_cpu(dip->di_nblocks))) {
491                 xfs_warn(ip->i_mount,
492                         "corrupt dinode %Lu, extent total = %d, nblocks = %Lu.",
493                         (unsigned long long)ip->i_ino,
494                         (int)(be32_to_cpu(dip->di_nextents) +
495                               be16_to_cpu(dip->di_anextents)),
496                         (unsigned long long)
497                                 be64_to_cpu(dip->di_nblocks));
498                 XFS_CORRUPTION_ERROR("xfs_iformat(1)", XFS_ERRLEVEL_LOW,
499                                      ip->i_mount, dip);
500                 return XFS_ERROR(EFSCORRUPTED);
501         }
502
503         if (unlikely(dip->di_forkoff > ip->i_mount->m_sb.sb_inodesize)) {
504                 xfs_warn(ip->i_mount, "corrupt dinode %Lu, forkoff = 0x%x.",
505                         (unsigned long long)ip->i_ino,
506                         dip->di_forkoff);
507                 XFS_CORRUPTION_ERROR("xfs_iformat(2)", XFS_ERRLEVEL_LOW,
508                                      ip->i_mount, dip);
509                 return XFS_ERROR(EFSCORRUPTED);
510         }
511
512         if (unlikely((ip->i_d.di_flags & XFS_DIFLAG_REALTIME) &&
513                      !ip->i_mount->m_rtdev_targp)) {
514                 xfs_warn(ip->i_mount,
515                         "corrupt dinode %Lu, has realtime flag set.",
516                         ip->i_ino);
517                 XFS_CORRUPTION_ERROR("xfs_iformat(realtime)",
518                                      XFS_ERRLEVEL_LOW, ip->i_mount, dip);
519                 return XFS_ERROR(EFSCORRUPTED);
520         }
521
522         switch (ip->i_d.di_mode & S_IFMT) {
523         case S_IFIFO:
524         case S_IFCHR:
525         case S_IFBLK:
526         case S_IFSOCK:
527                 if (unlikely(dip->di_format != XFS_DINODE_FMT_DEV)) {
528                         XFS_CORRUPTION_ERROR("xfs_iformat(3)", XFS_ERRLEVEL_LOW,
529                                               ip->i_mount, dip);
530                         return XFS_ERROR(EFSCORRUPTED);
531                 }
532                 ip->i_d.di_size = 0;
533                 ip->i_df.if_u2.if_rdev = xfs_dinode_get_rdev(dip);
534                 break;
535
536         case S_IFREG:
537         case S_IFLNK:
538         case S_IFDIR:
539                 switch (dip->di_format) {
540                 case XFS_DINODE_FMT_LOCAL:
541                         /*
542                          * no local regular files yet
543                          */
544                         if (unlikely(S_ISREG(be16_to_cpu(dip->di_mode)))) {
545                                 xfs_warn(ip->i_mount,
546                         "corrupt inode %Lu (local format for regular file).",
547                                         (unsigned long long) ip->i_ino);
548                                 XFS_CORRUPTION_ERROR("xfs_iformat(4)",
549                                                      XFS_ERRLEVEL_LOW,
550                                                      ip->i_mount, dip);
551                                 return XFS_ERROR(EFSCORRUPTED);
552                         }
553
554                         di_size = be64_to_cpu(dip->di_size);
555                         if (unlikely(di_size > XFS_DFORK_DSIZE(dip, ip->i_mount))) {
556                                 xfs_warn(ip->i_mount,
557                         "corrupt inode %Lu (bad size %Ld for local inode).",
558                                         (unsigned long long) ip->i_ino,
559                                         (long long) di_size);
560                                 XFS_CORRUPTION_ERROR("xfs_iformat(5)",
561                                                      XFS_ERRLEVEL_LOW,
562                                                      ip->i_mount, dip);
563                                 return XFS_ERROR(EFSCORRUPTED);
564                         }
565
566                         size = (int)di_size;
567                         error = xfs_iformat_local(ip, dip, XFS_DATA_FORK, size);
568                         break;
569                 case XFS_DINODE_FMT_EXTENTS:
570                         error = xfs_iformat_extents(ip, dip, XFS_DATA_FORK);
571                         break;
572                 case XFS_DINODE_FMT_BTREE:
573                         error = xfs_iformat_btree(ip, dip, XFS_DATA_FORK);
574                         break;
575                 default:
576                         XFS_ERROR_REPORT("xfs_iformat(6)", XFS_ERRLEVEL_LOW,
577                                          ip->i_mount);
578                         return XFS_ERROR(EFSCORRUPTED);
579                 }
580                 break;
581
582         default:
583                 XFS_ERROR_REPORT("xfs_iformat(7)", XFS_ERRLEVEL_LOW, ip->i_mount);
584                 return XFS_ERROR(EFSCORRUPTED);
585         }
586         if (error) {
587                 return error;
588         }
589         if (!XFS_DFORK_Q(dip))
590                 return 0;
591
592         ASSERT(ip->i_afp == NULL);
593         ip->i_afp = kmem_zone_zalloc(xfs_ifork_zone, KM_SLEEP | KM_NOFS);
594
595         switch (dip->di_aformat) {
596         case XFS_DINODE_FMT_LOCAL:
597                 atp = (xfs_attr_shortform_t *)XFS_DFORK_APTR(dip);
598                 size = be16_to_cpu(atp->hdr.totsize);
599
600                 if (unlikely(size < sizeof(struct xfs_attr_sf_hdr))) {
601                         xfs_warn(ip->i_mount,
602                                 "corrupt inode %Lu (bad attr fork size %Ld).",
603                                 (unsigned long long) ip->i_ino,
604                                 (long long) size);
605                         XFS_CORRUPTION_ERROR("xfs_iformat(8)",
606                                              XFS_ERRLEVEL_LOW,
607                                              ip->i_mount, dip);
608                         return XFS_ERROR(EFSCORRUPTED);
609                 }
610
611                 error = xfs_iformat_local(ip, dip, XFS_ATTR_FORK, size);
612                 break;
613         case XFS_DINODE_FMT_EXTENTS:
614                 error = xfs_iformat_extents(ip, dip, XFS_ATTR_FORK);
615                 break;
616         case XFS_DINODE_FMT_BTREE:
617                 error = xfs_iformat_btree(ip, dip, XFS_ATTR_FORK);
618                 break;
619         default:
620                 error = XFS_ERROR(EFSCORRUPTED);
621                 break;
622         }
623         if (error) {
624                 kmem_zone_free(xfs_ifork_zone, ip->i_afp);
625                 ip->i_afp = NULL;
626                 xfs_idestroy_fork(ip, XFS_DATA_FORK);
627         }
628         return error;
629 }
630
631 /*
632  * The file is in-lined in the on-disk inode.
633  * If it fits into if_inline_data, then copy
634  * it there, otherwise allocate a buffer for it
635  * and copy the data there.  Either way, set
636  * if_data to point at the data.
637  * If we allocate a buffer for the data, make
638  * sure that its size is a multiple of 4 and
639  * record the real size in i_real_bytes.
640  */
641 STATIC int
642 xfs_iformat_local(
643         xfs_inode_t     *ip,
644         xfs_dinode_t    *dip,
645         int             whichfork,
646         int             size)
647 {
648         xfs_ifork_t     *ifp;
649         int             real_size;
650
651         /*
652          * If the size is unreasonable, then something
653          * is wrong and we just bail out rather than crash in
654          * kmem_alloc() or memcpy() below.
655          */
656         if (unlikely(size > XFS_DFORK_SIZE(dip, ip->i_mount, whichfork))) {
657                 xfs_warn(ip->i_mount,
658         "corrupt inode %Lu (bad size %d for local fork, size = %d).",
659                         (unsigned long long) ip->i_ino, size,
660                         XFS_DFORK_SIZE(dip, ip->i_mount, whichfork));
661                 XFS_CORRUPTION_ERROR("xfs_iformat_local", XFS_ERRLEVEL_LOW,
662                                      ip->i_mount, dip);
663                 return XFS_ERROR(EFSCORRUPTED);
664         }
665         ifp = XFS_IFORK_PTR(ip, whichfork);
666         real_size = 0;
667         if (size == 0)
668                 ifp->if_u1.if_data = NULL;
669         else if (size <= sizeof(ifp->if_u2.if_inline_data))
670                 ifp->if_u1.if_data = ifp->if_u2.if_inline_data;
671         else {
672                 real_size = roundup(size, 4);
673                 ifp->if_u1.if_data = kmem_alloc(real_size, KM_SLEEP | KM_NOFS);
674         }
675         ifp->if_bytes = size;
676         ifp->if_real_bytes = real_size;
677         if (size)
678                 memcpy(ifp->if_u1.if_data, XFS_DFORK_PTR(dip, whichfork), size);
679         ifp->if_flags &= ~XFS_IFEXTENTS;
680         ifp->if_flags |= XFS_IFINLINE;
681         return 0;
682 }
683
684 /*
685  * The file consists of a set of extents all
686  * of which fit into the on-disk inode.
687  * If there are few enough extents to fit into
688  * the if_inline_ext, then copy them there.
689  * Otherwise allocate a buffer for them and copy
690  * them into it.  Either way, set if_extents
691  * to point at the extents.
692  */
693 STATIC int
694 xfs_iformat_extents(
695         xfs_inode_t     *ip,
696         xfs_dinode_t    *dip,
697         int             whichfork)
698 {
699         xfs_bmbt_rec_t  *dp;
700         xfs_ifork_t     *ifp;
701         int             nex;
702         int             size;
703         int             i;
704
705         ifp = XFS_IFORK_PTR(ip, whichfork);
706         nex = XFS_DFORK_NEXTENTS(dip, whichfork);
707         size = nex * (uint)sizeof(xfs_bmbt_rec_t);
708
709         /*
710          * If the number of extents is unreasonable, then something
711          * is wrong and we just bail out rather than crash in
712          * kmem_alloc() or memcpy() below.
713          */
714         if (unlikely(size < 0 || size > XFS_DFORK_SIZE(dip, ip->i_mount, whichfork))) {
715                 xfs_warn(ip->i_mount, "corrupt inode %Lu ((a)extents = %d).",
716                         (unsigned long long) ip->i_ino, nex);
717                 XFS_CORRUPTION_ERROR("xfs_iformat_extents(1)", XFS_ERRLEVEL_LOW,
718                                      ip->i_mount, dip);
719                 return XFS_ERROR(EFSCORRUPTED);
720         }
721
722         ifp->if_real_bytes = 0;
723         if (nex == 0)
724                 ifp->if_u1.if_extents = NULL;
725         else if (nex <= XFS_INLINE_EXTS)
726                 ifp->if_u1.if_extents = ifp->if_u2.if_inline_ext;
727         else
728                 xfs_iext_add(ifp, 0, nex);
729
730         ifp->if_bytes = size;
731         if (size) {
732                 dp = (xfs_bmbt_rec_t *) XFS_DFORK_PTR(dip, whichfork);
733                 xfs_validate_extents(ifp, nex, XFS_EXTFMT_INODE(ip));
734                 for (i = 0; i < nex; i++, dp++) {
735                         xfs_bmbt_rec_host_t *ep = xfs_iext_get_ext(ifp, i);
736                         ep->l0 = get_unaligned_be64(&dp->l0);
737                         ep->l1 = get_unaligned_be64(&dp->l1);
738                 }
739                 XFS_BMAP_TRACE_EXLIST(ip, nex, whichfork);
740                 if (whichfork != XFS_DATA_FORK ||
741                         XFS_EXTFMT_INODE(ip) == XFS_EXTFMT_NOSTATE)
742                                 if (unlikely(xfs_check_nostate_extents(
743                                     ifp, 0, nex))) {
744                                         XFS_ERROR_REPORT("xfs_iformat_extents(2)",
745                                                          XFS_ERRLEVEL_LOW,
746                                                          ip->i_mount);
747                                         return XFS_ERROR(EFSCORRUPTED);
748                                 }
749         }
750         ifp->if_flags |= XFS_IFEXTENTS;
751         return 0;
752 }
753
754 /*
755  * The file has too many extents to fit into
756  * the inode, so they are in B-tree format.
757  * Allocate a buffer for the root of the B-tree
758  * and copy the root into it.  The i_extents
759  * field will remain NULL until all of the
760  * extents are read in (when they are needed).
761  */
762 STATIC int
763 xfs_iformat_btree(
764         xfs_inode_t             *ip,
765         xfs_dinode_t            *dip,
766         int                     whichfork)
767 {
768         xfs_bmdr_block_t        *dfp;
769         xfs_ifork_t             *ifp;
770         /* REFERENCED */
771         int                     nrecs;
772         int                     size;
773
774         ifp = XFS_IFORK_PTR(ip, whichfork);
775         dfp = (xfs_bmdr_block_t *)XFS_DFORK_PTR(dip, whichfork);
776         size = XFS_BMAP_BROOT_SPACE(dfp);
777         nrecs = be16_to_cpu(dfp->bb_numrecs);
778
779         /*
780          * blow out if -- fork has less extents than can fit in
781          * fork (fork shouldn't be a btree format), root btree
782          * block has more records than can fit into the fork,
783          * or the number of extents is greater than the number of
784          * blocks.
785          */
786         if (unlikely(XFS_IFORK_NEXTENTS(ip, whichfork) <=
787                         XFS_IFORK_MAXEXT(ip, whichfork) ||
788                      XFS_BMDR_SPACE_CALC(nrecs) >
789                         XFS_DFORK_SIZE(dip, ip->i_mount, whichfork) ||
790                      XFS_IFORK_NEXTENTS(ip, whichfork) > ip->i_d.di_nblocks)) {
791                 xfs_warn(ip->i_mount, "corrupt inode %Lu (btree).",
792                         (unsigned long long) ip->i_ino);
793                 XFS_CORRUPTION_ERROR("xfs_iformat_btree", XFS_ERRLEVEL_LOW,
794                                  ip->i_mount, dip);
795                 return XFS_ERROR(EFSCORRUPTED);
796         }
797
798         ifp->if_broot_bytes = size;
799         ifp->if_broot = kmem_alloc(size, KM_SLEEP | KM_NOFS);
800         ASSERT(ifp->if_broot != NULL);
801         /*
802          * Copy and convert from the on-disk structure
803          * to the in-memory structure.
804          */
805         xfs_bmdr_to_bmbt(ip->i_mount, dfp,
806                          XFS_DFORK_SIZE(dip, ip->i_mount, whichfork),
807                          ifp->if_broot, size);
808         ifp->if_flags &= ~XFS_IFEXTENTS;
809         ifp->if_flags |= XFS_IFBROOT;
810
811         return 0;
812 }
813
814 STATIC void
815 xfs_dinode_from_disk(
816         xfs_icdinode_t          *to,
817         xfs_dinode_t            *from)
818 {
819         to->di_magic = be16_to_cpu(from->di_magic);
820         to->di_mode = be16_to_cpu(from->di_mode);
821         to->di_version = from ->di_version;
822         to->di_format = from->di_format;
823         to->di_onlink = be16_to_cpu(from->di_onlink);
824         to->di_uid = be32_to_cpu(from->di_uid);
825         to->di_gid = be32_to_cpu(from->di_gid);
826         to->di_nlink = be32_to_cpu(from->di_nlink);
827         to->di_projid_lo = be16_to_cpu(from->di_projid_lo);
828         to->di_projid_hi = be16_to_cpu(from->di_projid_hi);
829         memcpy(to->di_pad, from->di_pad, sizeof(to->di_pad));
830         to->di_flushiter = be16_to_cpu(from->di_flushiter);
831         to->di_atime.t_sec = be32_to_cpu(from->di_atime.t_sec);
832         to->di_atime.t_nsec = be32_to_cpu(from->di_atime.t_nsec);
833         to->di_mtime.t_sec = be32_to_cpu(from->di_mtime.t_sec);
834         to->di_mtime.t_nsec = be32_to_cpu(from->di_mtime.t_nsec);
835         to->di_ctime.t_sec = be32_to_cpu(from->di_ctime.t_sec);
836         to->di_ctime.t_nsec = be32_to_cpu(from->di_ctime.t_nsec);
837         to->di_size = be64_to_cpu(from->di_size);
838         to->di_nblocks = be64_to_cpu(from->di_nblocks);
839         to->di_extsize = be32_to_cpu(from->di_extsize);
840         to->di_nextents = be32_to_cpu(from->di_nextents);
841         to->di_anextents = be16_to_cpu(from->di_anextents);
842         to->di_forkoff = from->di_forkoff;
843         to->di_aformat  = from->di_aformat;
844         to->di_dmevmask = be32_to_cpu(from->di_dmevmask);
845         to->di_dmstate  = be16_to_cpu(from->di_dmstate);
846         to->di_flags    = be16_to_cpu(from->di_flags);
847         to->di_gen      = be32_to_cpu(from->di_gen);
848 }
849
850 void
851 xfs_dinode_to_disk(
852         xfs_dinode_t            *to,
853         xfs_icdinode_t          *from)
854 {
855         to->di_magic = cpu_to_be16(from->di_magic);
856         to->di_mode = cpu_to_be16(from->di_mode);
857         to->di_version = from ->di_version;
858         to->di_format = from->di_format;
859         to->di_onlink = cpu_to_be16(from->di_onlink);
860         to->di_uid = cpu_to_be32(from->di_uid);
861         to->di_gid = cpu_to_be32(from->di_gid);
862         to->di_nlink = cpu_to_be32(from->di_nlink);
863         to->di_projid_lo = cpu_to_be16(from->di_projid_lo);
864         to->di_projid_hi = cpu_to_be16(from->di_projid_hi);
865         memcpy(to->di_pad, from->di_pad, sizeof(to->di_pad));
866         to->di_flushiter = cpu_to_be16(from->di_flushiter);
867         to->di_atime.t_sec = cpu_to_be32(from->di_atime.t_sec);
868         to->di_atime.t_nsec = cpu_to_be32(from->di_atime.t_nsec);
869         to->di_mtime.t_sec = cpu_to_be32(from->di_mtime.t_sec);
870         to->di_mtime.t_nsec = cpu_to_be32(from->di_mtime.t_nsec);
871         to->di_ctime.t_sec = cpu_to_be32(from->di_ctime.t_sec);
872         to->di_ctime.t_nsec = cpu_to_be32(from->di_ctime.t_nsec);
873         to->di_size = cpu_to_be64(from->di_size);
874         to->di_nblocks = cpu_to_be64(from->di_nblocks);
875         to->di_extsize = cpu_to_be32(from->di_extsize);
876         to->di_nextents = cpu_to_be32(from->di_nextents);
877         to->di_anextents = cpu_to_be16(from->di_anextents);
878         to->di_forkoff = from->di_forkoff;
879         to->di_aformat = from->di_aformat;
880         to->di_dmevmask = cpu_to_be32(from->di_dmevmask);
881         to->di_dmstate = cpu_to_be16(from->di_dmstate);
882         to->di_flags = cpu_to_be16(from->di_flags);
883         to->di_gen = cpu_to_be32(from->di_gen);
884 }
885
886 STATIC uint
887 _xfs_dic2xflags(
888         __uint16_t              di_flags)
889 {
890         uint                    flags = 0;
891
892         if (di_flags & XFS_DIFLAG_ANY) {
893                 if (di_flags & XFS_DIFLAG_REALTIME)
894                         flags |= XFS_XFLAG_REALTIME;
895                 if (di_flags & XFS_DIFLAG_PREALLOC)
896                         flags |= XFS_XFLAG_PREALLOC;
897                 if (di_flags & XFS_DIFLAG_IMMUTABLE)
898                         flags |= XFS_XFLAG_IMMUTABLE;
899                 if (di_flags & XFS_DIFLAG_APPEND)
900                         flags |= XFS_XFLAG_APPEND;
901                 if (di_flags & XFS_DIFLAG_SYNC)
902                         flags |= XFS_XFLAG_SYNC;
903                 if (di_flags & XFS_DIFLAG_NOATIME)
904                         flags |= XFS_XFLAG_NOATIME;
905                 if (di_flags & XFS_DIFLAG_NODUMP)
906                         flags |= XFS_XFLAG_NODUMP;
907                 if (di_flags & XFS_DIFLAG_RTINHERIT)
908                         flags |= XFS_XFLAG_RTINHERIT;
909                 if (di_flags & XFS_DIFLAG_PROJINHERIT)
910                         flags |= XFS_XFLAG_PROJINHERIT;
911                 if (di_flags & XFS_DIFLAG_NOSYMLINKS)
912                         flags |= XFS_XFLAG_NOSYMLINKS;
913                 if (di_flags & XFS_DIFLAG_EXTSIZE)
914                         flags |= XFS_XFLAG_EXTSIZE;
915                 if (di_flags & XFS_DIFLAG_EXTSZINHERIT)
916                         flags |= XFS_XFLAG_EXTSZINHERIT;
917                 if (di_flags & XFS_DIFLAG_NODEFRAG)
918                         flags |= XFS_XFLAG_NODEFRAG;
919                 if (di_flags & XFS_DIFLAG_FILESTREAM)
920                         flags |= XFS_XFLAG_FILESTREAM;
921         }
922
923         return flags;
924 }
925
926 uint
927 xfs_ip2xflags(
928         xfs_inode_t             *ip)
929 {
930         xfs_icdinode_t          *dic = &ip->i_d;
931
932         return _xfs_dic2xflags(dic->di_flags) |
933                                 (XFS_IFORK_Q(ip) ? XFS_XFLAG_HASATTR : 0);
934 }
935
936 uint
937 xfs_dic2xflags(
938         xfs_dinode_t            *dip)
939 {
940         return _xfs_dic2xflags(be16_to_cpu(dip->di_flags)) |
941                                 (XFS_DFORK_Q(dip) ? XFS_XFLAG_HASATTR : 0);
942 }
943
944 /*
945  * Read the disk inode attributes into the in-core inode structure.
946  */
947 int
948 xfs_iread(
949         xfs_mount_t     *mp,
950         xfs_trans_t     *tp,
951         xfs_inode_t     *ip,
952         uint            iget_flags)
953 {
954         xfs_buf_t       *bp;
955         xfs_dinode_t    *dip;
956         int             error;
957
958         /*
959          * Fill in the location information in the in-core inode.
960          */
961         error = xfs_imap(mp, tp, ip->i_ino, &ip->i_imap, iget_flags);
962         if (error)
963                 return error;
964
965         /*
966          * Get pointers to the on-disk inode and the buffer containing it.
967          */
968         error = xfs_imap_to_bp(mp, tp, &ip->i_imap, &dip, &bp, 0, iget_flags);
969         if (error)
970                 return error;
971
972         /*
973          * If we got something that isn't an inode it means someone
974          * (nfs or dmi) has a stale handle.
975          */
976         if (dip->di_magic != cpu_to_be16(XFS_DINODE_MAGIC)) {
977 #ifdef DEBUG
978                 xfs_alert(mp,
979                         "%s: dip->di_magic (0x%x) != XFS_DINODE_MAGIC (0x%x)",
980                         __func__, be16_to_cpu(dip->di_magic), XFS_DINODE_MAGIC);
981 #endif /* DEBUG */
982                 error = XFS_ERROR(EINVAL);
983                 goto out_brelse;
984         }
985
986         /*
987          * If the on-disk inode is already linked to a directory
988          * entry, copy all of the inode into the in-core inode.
989          * xfs_iformat() handles copying in the inode format
990          * specific information.
991          * Otherwise, just get the truly permanent information.
992          */
993         if (dip->di_mode) {
994                 xfs_dinode_from_disk(&ip->i_d, dip);
995                 error = xfs_iformat(ip, dip);
996                 if (error)  {
997 #ifdef DEBUG
998                         xfs_alert(mp, "%s: xfs_iformat() returned error %d",
999                                 __func__, error);
1000 #endif /* DEBUG */
1001                         goto out_brelse;
1002                 }
1003         } else {
1004                 ip->i_d.di_magic = be16_to_cpu(dip->di_magic);
1005                 ip->i_d.di_version = dip->di_version;
1006                 ip->i_d.di_gen = be32_to_cpu(dip->di_gen);
1007                 ip->i_d.di_flushiter = be16_to_cpu(dip->di_flushiter);
1008                 /*
1009                  * Make sure to pull in the mode here as well in
1010                  * case the inode is released without being used.
1011                  * This ensures that xfs_inactive() will see that
1012                  * the inode is already free and not try to mess
1013                  * with the uninitialized part of it.
1014                  */
1015                 ip->i_d.di_mode = 0;
1016         }
1017
1018         /*
1019          * The inode format changed when we moved the link count and
1020          * made it 32 bits long.  If this is an old format inode,
1021          * convert it in memory to look like a new one.  If it gets
1022          * flushed to disk we will convert back before flushing or
1023          * logging it.  We zero out the new projid field and the old link
1024          * count field.  We'll handle clearing the pad field (the remains
1025          * of the old uuid field) when we actually convert the inode to
1026          * the new format. We don't change the version number so that we
1027          * can distinguish this from a real new format inode.
1028          */
1029         if (ip->i_d.di_version == 1) {
1030                 ip->i_d.di_nlink = ip->i_d.di_onlink;
1031                 ip->i_d.di_onlink = 0;
1032                 xfs_set_projid(ip, 0);
1033         }
1034
1035         ip->i_delayed_blks = 0;
1036
1037         /*
1038          * Mark the buffer containing the inode as something to keep
1039          * around for a while.  This helps to keep recently accessed
1040          * meta-data in-core longer.
1041          */
1042         xfs_buf_set_ref(bp, XFS_INO_REF);
1043
1044         /*
1045          * Use xfs_trans_brelse() to release the buffer containing the
1046          * on-disk inode, because it was acquired with xfs_trans_read_buf()
1047          * in xfs_imap_to_bp() above.  If tp is NULL, this is just a normal
1048          * brelse().  If we're within a transaction, then xfs_trans_brelse()
1049          * will only release the buffer if it is not dirty within the
1050          * transaction.  It will be OK to release the buffer in this case,
1051          * because inodes on disk are never destroyed and we will be
1052          * locking the new in-core inode before putting it in the hash
1053          * table where other processes can find it.  Thus we don't have
1054          * to worry about the inode being changed just because we released
1055          * the buffer.
1056          */
1057  out_brelse:
1058         xfs_trans_brelse(tp, bp);
1059         return error;
1060 }
1061
1062 /*
1063  * Read in extents from a btree-format inode.
1064  * Allocate and fill in if_extents.  Real work is done in xfs_bmap.c.
1065  */
1066 int
1067 xfs_iread_extents(
1068         xfs_trans_t     *tp,
1069         xfs_inode_t     *ip,
1070         int             whichfork)
1071 {
1072         int             error;
1073         xfs_ifork_t     *ifp;
1074         xfs_extnum_t    nextents;
1075
1076         if (unlikely(XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE)) {
1077                 XFS_ERROR_REPORT("xfs_iread_extents", XFS_ERRLEVEL_LOW,
1078                                  ip->i_mount);
1079                 return XFS_ERROR(EFSCORRUPTED);
1080         }
1081         nextents = XFS_IFORK_NEXTENTS(ip, whichfork);
1082         ifp = XFS_IFORK_PTR(ip, whichfork);
1083
1084         /*
1085          * We know that the size is valid (it's checked in iformat_btree)
1086          */
1087         ifp->if_bytes = ifp->if_real_bytes = 0;
1088         ifp->if_flags |= XFS_IFEXTENTS;
1089         xfs_iext_add(ifp, 0, nextents);
1090         error = xfs_bmap_read_extents(tp, ip, whichfork);
1091         if (error) {
1092                 xfs_iext_destroy(ifp);
1093                 ifp->if_flags &= ~XFS_IFEXTENTS;
1094                 return error;
1095         }
1096         xfs_validate_extents(ifp, nextents, XFS_EXTFMT_INODE(ip));
1097         return 0;
1098 }
1099
1100 /*
1101  * Allocate an inode on disk and return a copy of its in-core version.
1102  * The in-core inode is locked exclusively.  Set mode, nlink, and rdev
1103  * appropriately within the inode.  The uid and gid for the inode are
1104  * set according to the contents of the given cred structure.
1105  *
1106  * Use xfs_dialloc() to allocate the on-disk inode. If xfs_dialloc()
1107  * has a free inode available, call xfs_iget()
1108  * to obtain the in-core version of the allocated inode.  Finally,
1109  * fill in the inode and log its initial contents.  In this case,
1110  * ialloc_context would be set to NULL and call_again set to false.
1111  *
1112  * If xfs_dialloc() does not have an available inode,
1113  * it will replenish its supply by doing an allocation. Since we can
1114  * only do one allocation within a transaction without deadlocks, we
1115  * must commit the current transaction before returning the inode itself.
1116  * In this case, therefore, we will set call_again to true and return.
1117  * The caller should then commit the current transaction, start a new
1118  * transaction, and call xfs_ialloc() again to actually get the inode.
1119  *
1120  * To ensure that some other process does not grab the inode that
1121  * was allocated during the first call to xfs_ialloc(), this routine
1122  * also returns the [locked] bp pointing to the head of the freelist
1123  * as ialloc_context.  The caller should hold this buffer across
1124  * the commit and pass it back into this routine on the second call.
1125  *
1126  * If we are allocating quota inodes, we do not have a parent inode
1127  * to attach to or associate with (i.e. pip == NULL) because they
1128  * are not linked into the directory structure - they are attached
1129  * directly to the superblock - and so have no parent.
1130  */
1131 int
1132 xfs_ialloc(
1133         xfs_trans_t     *tp,
1134         xfs_inode_t     *pip,
1135         umode_t         mode,
1136         xfs_nlink_t     nlink,
1137         xfs_dev_t       rdev,
1138         prid_t          prid,
1139         int             okalloc,
1140         xfs_buf_t       **ialloc_context,
1141         xfs_inode_t     **ipp)
1142 {
1143         xfs_ino_t       ino;
1144         xfs_inode_t     *ip;
1145         uint            flags;
1146         int             error;
1147         timespec_t      tv;
1148         int             filestreams = 0;
1149
1150         /*
1151          * Call the space management code to pick
1152          * the on-disk inode to be allocated.
1153          */
1154         error = xfs_dialloc(tp, pip ? pip->i_ino : 0, mode, okalloc,
1155                             ialloc_context, &ino);
1156         if (error)
1157                 return error;
1158         if (*ialloc_context || ino == NULLFSINO) {
1159                 *ipp = NULL;
1160                 return 0;
1161         }
1162         ASSERT(*ialloc_context == NULL);
1163
1164         /*
1165          * Get the in-core inode with the lock held exclusively.
1166          * This is because we're setting fields here we need
1167          * to prevent others from looking at until we're done.
1168          */
1169         error = xfs_iget(tp->t_mountp, tp, ino, XFS_IGET_CREATE,
1170                          XFS_ILOCK_EXCL, &ip);
1171         if (error)
1172                 return error;
1173         ASSERT(ip != NULL);
1174
1175         ip->i_d.di_mode = mode;
1176         ip->i_d.di_onlink = 0;
1177         ip->i_d.di_nlink = nlink;
1178         ASSERT(ip->i_d.di_nlink == nlink);
1179         ip->i_d.di_uid = current_fsuid();
1180         ip->i_d.di_gid = current_fsgid();
1181         xfs_set_projid(ip, prid);
1182         memset(&(ip->i_d.di_pad[0]), 0, sizeof(ip->i_d.di_pad));
1183
1184         /*
1185          * If the superblock version is up to where we support new format
1186          * inodes and this is currently an old format inode, then change
1187          * the inode version number now.  This way we only do the conversion
1188          * here rather than here and in the flush/logging code.
1189          */
1190         if (xfs_sb_version_hasnlink(&tp->t_mountp->m_sb) &&
1191             ip->i_d.di_version == 1) {
1192                 ip->i_d.di_version = 2;
1193                 /*
1194                  * We've already zeroed the old link count, the projid field,
1195                  * and the pad field.
1196                  */
1197         }
1198
1199         /*
1200          * Project ids won't be stored on disk if we are using a version 1 inode.
1201          */
1202         if ((prid != 0) && (ip->i_d.di_version == 1))
1203                 xfs_bump_ino_vers2(tp, ip);
1204
1205         if (pip && XFS_INHERIT_GID(pip)) {
1206                 ip->i_d.di_gid = pip->i_d.di_gid;
1207                 if ((pip->i_d.di_mode & S_ISGID) && S_ISDIR(mode)) {
1208                         ip->i_d.di_mode |= S_ISGID;
1209                 }
1210         }
1211
1212         /*
1213          * If the group ID of the new file does not match the effective group
1214          * ID or one of the supplementary group IDs, the S_ISGID bit is cleared
1215          * (and only if the irix_sgid_inherit compatibility variable is set).
1216          */
1217         if ((irix_sgid_inherit) &&
1218             (ip->i_d.di_mode & S_ISGID) &&
1219             (!in_group_p((gid_t)ip->i_d.di_gid))) {
1220                 ip->i_d.di_mode &= ~S_ISGID;
1221         }
1222
1223         ip->i_d.di_size = 0;
1224         ip->i_d.di_nextents = 0;
1225         ASSERT(ip->i_d.di_nblocks == 0);
1226
1227         nanotime(&tv);
1228         ip->i_d.di_mtime.t_sec = (__int32_t)tv.tv_sec;
1229         ip->i_d.di_mtime.t_nsec = (__int32_t)tv.tv_nsec;
1230         ip->i_d.di_atime = ip->i_d.di_mtime;
1231         ip->i_d.di_ctime = ip->i_d.di_mtime;
1232
1233         /*
1234          * di_gen will have been taken care of in xfs_iread.
1235          */
1236         ip->i_d.di_extsize = 0;
1237         ip->i_d.di_dmevmask = 0;
1238         ip->i_d.di_dmstate = 0;
1239         ip->i_d.di_flags = 0;
1240         flags = XFS_ILOG_CORE;
1241         switch (mode & S_IFMT) {
1242         case S_IFIFO:
1243         case S_IFCHR:
1244         case S_IFBLK:
1245         case S_IFSOCK:
1246                 ip->i_d.di_format = XFS_DINODE_FMT_DEV;
1247                 ip->i_df.if_u2.if_rdev = rdev;
1248                 ip->i_df.if_flags = 0;
1249                 flags |= XFS_ILOG_DEV;
1250                 break;
1251         case S_IFREG:
1252                 /*
1253                  * we can't set up filestreams until after the VFS inode
1254                  * is set up properly.
1255                  */
1256                 if (pip && xfs_inode_is_filestream(pip))
1257                         filestreams = 1;
1258                 /* fall through */
1259         case S_IFDIR:
1260                 if (pip && (pip->i_d.di_flags & XFS_DIFLAG_ANY)) {
1261                         uint    di_flags = 0;
1262
1263                         if (S_ISDIR(mode)) {
1264                                 if (pip->i_d.di_flags & XFS_DIFLAG_RTINHERIT)
1265                                         di_flags |= XFS_DIFLAG_RTINHERIT;
1266                                 if (pip->i_d.di_flags & XFS_DIFLAG_EXTSZINHERIT) {
1267                                         di_flags |= XFS_DIFLAG_EXTSZINHERIT;
1268                                         ip->i_d.di_extsize = pip->i_d.di_extsize;
1269                                 }
1270                         } else if (S_ISREG(mode)) {
1271                                 if (pip->i_d.di_flags & XFS_DIFLAG_RTINHERIT)
1272                                         di_flags |= XFS_DIFLAG_REALTIME;
1273                                 if (pip->i_d.di_flags & XFS_DIFLAG_EXTSZINHERIT) {
1274                                         di_flags |= XFS_DIFLAG_EXTSIZE;
1275                                         ip->i_d.di_extsize = pip->i_d.di_extsize;
1276                                 }
1277                         }
1278                         if ((pip->i_d.di_flags & XFS_DIFLAG_NOATIME) &&
1279                             xfs_inherit_noatime)
1280                                 di_flags |= XFS_DIFLAG_NOATIME;
1281                         if ((pip->i_d.di_flags & XFS_DIFLAG_NODUMP) &&
1282                             xfs_inherit_nodump)
1283                                 di_flags |= XFS_DIFLAG_NODUMP;
1284                         if ((pip->i_d.di_flags & XFS_DIFLAG_SYNC) &&
1285                             xfs_inherit_sync)
1286                                 di_flags |= XFS_DIFLAG_SYNC;
1287                         if ((pip->i_d.di_flags & XFS_DIFLAG_NOSYMLINKS) &&
1288                             xfs_inherit_nosymlinks)
1289                                 di_flags |= XFS_DIFLAG_NOSYMLINKS;
1290                         if (pip->i_d.di_flags & XFS_DIFLAG_PROJINHERIT)
1291                                 di_flags |= XFS_DIFLAG_PROJINHERIT;
1292                         if ((pip->i_d.di_flags & XFS_DIFLAG_NODEFRAG) &&
1293                             xfs_inherit_nodefrag)
1294                                 di_flags |= XFS_DIFLAG_NODEFRAG;
1295                         if (pip->i_d.di_flags & XFS_DIFLAG_FILESTREAM)
1296                                 di_flags |= XFS_DIFLAG_FILESTREAM;
1297                         ip->i_d.di_flags |= di_flags;
1298                 }
1299                 /* FALLTHROUGH */
1300         case S_IFLNK:
1301                 ip->i_d.di_format = XFS_DINODE_FMT_EXTENTS;
1302                 ip->i_df.if_flags = XFS_IFEXTENTS;
1303                 ip->i_df.if_bytes = ip->i_df.if_real_bytes = 0;
1304                 ip->i_df.if_u1.if_extents = NULL;
1305                 break;
1306         default:
1307                 ASSERT(0);
1308         }
1309         /*
1310          * Attribute fork settings for new inode.
1311          */
1312         ip->i_d.di_aformat = XFS_DINODE_FMT_EXTENTS;
1313         ip->i_d.di_anextents = 0;
1314
1315         /*
1316          * Log the new values stuffed into the inode.
1317          */
1318         xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
1319         xfs_trans_log_inode(tp, ip, flags);
1320
1321         /* now that we have an i_mode we can setup inode ops and unlock */
1322         xfs_setup_inode(ip);
1323
1324         /* now we have set up the vfs inode we can associate the filestream */
1325         if (filestreams) {
1326                 error = xfs_filestream_associate(pip, ip);
1327                 if (error < 0)
1328                         return -error;
1329                 if (!error)
1330                         xfs_iflags_set(ip, XFS_IFILESTREAM);
1331         }
1332
1333         *ipp = ip;
1334         return 0;
1335 }
1336
1337 /*
1338  * Free up the underlying blocks past new_size.  The new size must be smaller
1339  * than the current size.  This routine can be used both for the attribute and
1340  * data fork, and does not modify the inode size, which is left to the caller.
1341  *
1342  * The transaction passed to this routine must have made a permanent log
1343  * reservation of at least XFS_ITRUNCATE_LOG_RES.  This routine may commit the
1344  * given transaction and start new ones, so make sure everything involved in
1345  * the transaction is tidy before calling here.  Some transaction will be
1346  * returned to the caller to be committed.  The incoming transaction must
1347  * already include the inode, and both inode locks must be held exclusively.
1348  * The inode must also be "held" within the transaction.  On return the inode
1349  * will be "held" within the returned transaction.  This routine does NOT
1350  * require any disk space to be reserved for it within the transaction.
1351  *
1352  * If we get an error, we must return with the inode locked and linked into the
1353  * current transaction. This keeps things simple for the higher level code,
1354  * because it always knows that the inode is locked and held in the transaction
1355  * that returns to it whether errors occur or not.  We don't mark the inode
1356  * dirty on error so that transactions can be easily aborted if possible.
1357  */
1358 int
1359 xfs_itruncate_extents(
1360         struct xfs_trans        **tpp,
1361         struct xfs_inode        *ip,
1362         int                     whichfork,
1363         xfs_fsize_t             new_size)
1364 {
1365         struct xfs_mount        *mp = ip->i_mount;
1366         struct xfs_trans        *tp = *tpp;
1367         struct xfs_trans        *ntp;
1368         xfs_bmap_free_t         free_list;
1369         xfs_fsblock_t           first_block;
1370         xfs_fileoff_t           first_unmap_block;
1371         xfs_fileoff_t           last_block;
1372         xfs_filblks_t           unmap_len;
1373         int                     committed;
1374         int                     error = 0;
1375         int                     done = 0;
1376
1377         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
1378         ASSERT(!atomic_read(&VFS_I(ip)->i_count) ||
1379                xfs_isilocked(ip, XFS_IOLOCK_EXCL));
1380         ASSERT(new_size <= XFS_ISIZE(ip));
1381         ASSERT(tp->t_flags & XFS_TRANS_PERM_LOG_RES);
1382         ASSERT(ip->i_itemp != NULL);
1383         ASSERT(ip->i_itemp->ili_lock_flags == 0);
1384         ASSERT(!XFS_NOT_DQATTACHED(mp, ip));
1385
1386         trace_xfs_itruncate_extents_start(ip, new_size);
1387
1388         /*
1389          * Since it is possible for space to become allocated beyond
1390          * the end of the file (in a crash where the space is allocated
1391          * but the inode size is not yet updated), simply remove any
1392          * blocks which show up between the new EOF and the maximum
1393          * possible file size.  If the first block to be removed is
1394          * beyond the maximum file size (ie it is the same as last_block),
1395          * then there is nothing to do.
1396          */
1397         first_unmap_block = XFS_B_TO_FSB(mp, (xfs_ufsize_t)new_size);
1398         last_block = XFS_B_TO_FSB(mp, mp->m_super->s_maxbytes);
1399         if (first_unmap_block == last_block)
1400                 return 0;
1401
1402         ASSERT(first_unmap_block < last_block);
1403         unmap_len = last_block - first_unmap_block + 1;
1404         while (!done) {
1405                 xfs_bmap_init(&free_list, &first_block);
1406                 error = xfs_bunmapi(tp, ip,
1407                                     first_unmap_block, unmap_len,
1408                                     xfs_bmapi_aflag(whichfork),
1409                                     XFS_ITRUNC_MAX_EXTENTS,
1410                                     &first_block, &free_list,
1411                                     &done);
1412                 if (error)
1413                         goto out_bmap_cancel;
1414
1415                 /*
1416                  * Duplicate the transaction that has the permanent
1417                  * reservation and commit the old transaction.
1418                  */
1419                 error = xfs_bmap_finish(&tp, &free_list, &committed);
1420                 if (committed)
1421                         xfs_trans_ijoin(tp, ip, 0);
1422                 if (error)
1423                         goto out_bmap_cancel;
1424
1425                 if (committed) {
1426                         /*
1427                          * Mark the inode dirty so it will be logged and
1428                          * moved forward in the log as part of every commit.
1429                          */
1430                         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1431                 }
1432
1433                 ntp = xfs_trans_dup(tp);
1434                 error = xfs_trans_commit(tp, 0);
1435                 tp = ntp;
1436
1437                 xfs_trans_ijoin(tp, ip, 0);
1438
1439                 if (error)
1440                         goto out;
1441
1442                 /*
1443                  * Transaction commit worked ok so we can drop the extra ticket
1444                  * reference that we gained in xfs_trans_dup()
1445                  */
1446                 xfs_log_ticket_put(tp->t_ticket);
1447                 error = xfs_trans_reserve(tp, 0,
1448                                         XFS_ITRUNCATE_LOG_RES(mp), 0,
1449                                         XFS_TRANS_PERM_LOG_RES,
1450                                         XFS_ITRUNCATE_LOG_COUNT);
1451                 if (error)
1452                         goto out;
1453         }
1454
1455         /*
1456          * Always re-log the inode so that our permanent transaction can keep
1457          * on rolling it forward in the log.
1458          */
1459         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1460
1461         trace_xfs_itruncate_extents_end(ip, new_size);
1462
1463 out:
1464         *tpp = tp;
1465         return error;
1466 out_bmap_cancel:
1467         /*
1468          * If the bunmapi call encounters an error, return to the caller where
1469          * the transaction can be properly aborted.  We just need to make sure
1470          * we're not holding any resources that we were not when we came in.
1471          */
1472         xfs_bmap_cancel(&free_list);
1473         goto out;
1474 }
1475
1476 /*
1477  * This is called when the inode's link count goes to 0.
1478  * We place the on-disk inode on a list in the AGI.  It
1479  * will be pulled from this list when the inode is freed.
1480  */
1481 int
1482 xfs_iunlink(
1483         xfs_trans_t     *tp,
1484         xfs_inode_t     *ip)
1485 {
1486         xfs_mount_t     *mp;
1487         xfs_agi_t       *agi;
1488         xfs_dinode_t    *dip;
1489         xfs_buf_t       *agibp;
1490         xfs_buf_t       *ibp;
1491         xfs_agino_t     agino;
1492         short           bucket_index;
1493         int             offset;
1494         int             error;
1495
1496         ASSERT(ip->i_d.di_nlink == 0);
1497         ASSERT(ip->i_d.di_mode != 0);
1498
1499         mp = tp->t_mountp;
1500
1501         /*
1502          * Get the agi buffer first.  It ensures lock ordering
1503          * on the list.
1504          */
1505         error = xfs_read_agi(mp, tp, XFS_INO_TO_AGNO(mp, ip->i_ino), &agibp);
1506         if (error)
1507                 return error;
1508         agi = XFS_BUF_TO_AGI(agibp);
1509
1510         /*
1511          * Get the index into the agi hash table for the
1512          * list this inode will go on.
1513          */
1514         agino = XFS_INO_TO_AGINO(mp, ip->i_ino);
1515         ASSERT(agino != 0);
1516         bucket_index = agino % XFS_AGI_UNLINKED_BUCKETS;
1517         ASSERT(agi->agi_unlinked[bucket_index]);
1518         ASSERT(be32_to_cpu(agi->agi_unlinked[bucket_index]) != agino);
1519
1520         if (agi->agi_unlinked[bucket_index] != cpu_to_be32(NULLAGINO)) {
1521                 /*
1522                  * There is already another inode in the bucket we need
1523                  * to add ourselves to.  Add us at the front of the list.
1524                  * Here we put the head pointer into our next pointer,
1525                  * and then we fall through to point the head at us.
1526                  */
1527                 error = xfs_imap_to_bp(mp, tp, &ip->i_imap, &dip, &ibp,
1528                                        0, 0);
1529                 if (error)
1530                         return error;
1531
1532                 ASSERT(dip->di_next_unlinked == cpu_to_be32(NULLAGINO));
1533                 dip->di_next_unlinked = agi->agi_unlinked[bucket_index];
1534                 offset = ip->i_imap.im_boffset +
1535                         offsetof(xfs_dinode_t, di_next_unlinked);
1536                 xfs_trans_inode_buf(tp, ibp);
1537                 xfs_trans_log_buf(tp, ibp, offset,
1538                                   (offset + sizeof(xfs_agino_t) - 1));
1539                 xfs_inobp_check(mp, ibp);
1540         }
1541
1542         /*
1543          * Point the bucket head pointer at the inode being inserted.
1544          */
1545         ASSERT(agino != 0);
1546         agi->agi_unlinked[bucket_index] = cpu_to_be32(agino);
1547         offset = offsetof(xfs_agi_t, agi_unlinked) +
1548                 (sizeof(xfs_agino_t) * bucket_index);
1549         xfs_trans_log_buf(tp, agibp, offset,
1550                           (offset + sizeof(xfs_agino_t) - 1));
1551         return 0;
1552 }
1553
1554 /*
1555  * Pull the on-disk inode from the AGI unlinked list.
1556  */
1557 STATIC int
1558 xfs_iunlink_remove(
1559         xfs_trans_t     *tp,
1560         xfs_inode_t     *ip)
1561 {
1562         xfs_ino_t       next_ino;
1563         xfs_mount_t     *mp;
1564         xfs_agi_t       *agi;
1565         xfs_dinode_t    *dip;
1566         xfs_buf_t       *agibp;
1567         xfs_buf_t       *ibp;
1568         xfs_agnumber_t  agno;
1569         xfs_agino_t     agino;
1570         xfs_agino_t     next_agino;
1571         xfs_buf_t       *last_ibp;
1572         xfs_dinode_t    *last_dip = NULL;
1573         short           bucket_index;
1574         int             offset, last_offset = 0;
1575         int             error;
1576
1577         mp = tp->t_mountp;
1578         agno = XFS_INO_TO_AGNO(mp, ip->i_ino);
1579
1580         /*
1581          * Get the agi buffer first.  It ensures lock ordering
1582          * on the list.
1583          */
1584         error = xfs_read_agi(mp, tp, agno, &agibp);
1585         if (error)
1586                 return error;
1587
1588         agi = XFS_BUF_TO_AGI(agibp);
1589
1590         /*
1591          * Get the index into the agi hash table for the
1592          * list this inode will go on.
1593          */
1594         agino = XFS_INO_TO_AGINO(mp, ip->i_ino);
1595         ASSERT(agino != 0);
1596         bucket_index = agino % XFS_AGI_UNLINKED_BUCKETS;
1597         ASSERT(agi->agi_unlinked[bucket_index] != cpu_to_be32(NULLAGINO));
1598         ASSERT(agi->agi_unlinked[bucket_index]);
1599
1600         if (be32_to_cpu(agi->agi_unlinked[bucket_index]) == agino) {
1601                 /*
1602                  * We're at the head of the list.  Get the inode's on-disk
1603                  * buffer to see if there is anyone after us on the list.
1604                  * Only modify our next pointer if it is not already NULLAGINO.
1605                  * This saves us the overhead of dealing with the buffer when
1606                  * there is no need to change it.
1607                  */
1608                 error = xfs_imap_to_bp(mp, tp, &ip->i_imap, &dip, &ibp,
1609                                        0, 0);
1610                 if (error) {
1611                         xfs_warn(mp, "%s: xfs_imap_to_bp returned error %d.",
1612                                 __func__, error);
1613                         return error;
1614                 }
1615                 next_agino = be32_to_cpu(dip->di_next_unlinked);
1616                 ASSERT(next_agino != 0);
1617                 if (next_agino != NULLAGINO) {
1618                         dip->di_next_unlinked = cpu_to_be32(NULLAGINO);
1619                         offset = ip->i_imap.im_boffset +
1620                                 offsetof(xfs_dinode_t, di_next_unlinked);
1621                         xfs_trans_inode_buf(tp, ibp);
1622                         xfs_trans_log_buf(tp, ibp, offset,
1623                                           (offset + sizeof(xfs_agino_t) - 1));
1624                         xfs_inobp_check(mp, ibp);
1625                 } else {
1626                         xfs_trans_brelse(tp, ibp);
1627                 }
1628                 /*
1629                  * Point the bucket head pointer at the next inode.
1630                  */
1631                 ASSERT(next_agino != 0);
1632                 ASSERT(next_agino != agino);
1633                 agi->agi_unlinked[bucket_index] = cpu_to_be32(next_agino);
1634                 offset = offsetof(xfs_agi_t, agi_unlinked) +
1635                         (sizeof(xfs_agino_t) * bucket_index);
1636                 xfs_trans_log_buf(tp, agibp, offset,
1637                                   (offset + sizeof(xfs_agino_t) - 1));
1638         } else {
1639                 /*
1640                  * We need to search the list for the inode being freed.
1641                  */
1642                 next_agino = be32_to_cpu(agi->agi_unlinked[bucket_index]);
1643                 last_ibp = NULL;
1644                 while (next_agino != agino) {
1645                         struct xfs_imap imap;
1646
1647                         if (last_ibp)
1648                                 xfs_trans_brelse(tp, last_ibp);
1649
1650                         imap.im_blkno = 0;
1651                         next_ino = XFS_AGINO_TO_INO(mp, agno, next_agino);
1652
1653                         error = xfs_imap(mp, tp, next_ino, &imap, 0);
1654                         if (error) {
1655                                 xfs_warn(mp,
1656         "%s: xfs_imap returned error %d.",
1657                                          __func__, error);
1658                                 return error;
1659                         }
1660
1661                         error = xfs_imap_to_bp(mp, tp, &imap, &last_dip,
1662                                                &last_ibp, 0, 0);
1663                         if (error) {
1664                                 xfs_warn(mp,
1665         "%s: xfs_imap_to_bp returned error %d.",
1666                                         __func__, error);
1667                                 return error;
1668                         }
1669
1670                         last_offset = imap.im_boffset;
1671                         next_agino = be32_to_cpu(last_dip->di_next_unlinked);
1672                         ASSERT(next_agino != NULLAGINO);
1673                         ASSERT(next_agino != 0);
1674                 }
1675
1676                 /*
1677                  * Now last_ibp points to the buffer previous to us on the
1678                  * unlinked list.  Pull us from the list.
1679                  */
1680                 error = xfs_imap_to_bp(mp, tp, &ip->i_imap, &dip, &ibp,
1681                                        0, 0);
1682                 if (error) {
1683                         xfs_warn(mp, "%s: xfs_imap_to_bp(2) returned error %d.",
1684                                 __func__, error);
1685                         return error;
1686                 }
1687                 next_agino = be32_to_cpu(dip->di_next_unlinked);
1688                 ASSERT(next_agino != 0);
1689                 ASSERT(next_agino != agino);
1690                 if (next_agino != NULLAGINO) {
1691                         dip->di_next_unlinked = cpu_to_be32(NULLAGINO);
1692                         offset = ip->i_imap.im_boffset +
1693                                 offsetof(xfs_dinode_t, di_next_unlinked);
1694                         xfs_trans_inode_buf(tp, ibp);
1695                         xfs_trans_log_buf(tp, ibp, offset,
1696                                           (offset + sizeof(xfs_agino_t) - 1));
1697                         xfs_inobp_check(mp, ibp);
1698                 } else {
1699                         xfs_trans_brelse(tp, ibp);
1700                 }
1701                 /*
1702                  * Point the previous inode on the list to the next inode.
1703                  */
1704                 last_dip->di_next_unlinked = cpu_to_be32(next_agino);
1705                 ASSERT(next_agino != 0);
1706                 offset = last_offset + offsetof(xfs_dinode_t, di_next_unlinked);
1707                 xfs_trans_inode_buf(tp, last_ibp);
1708                 xfs_trans_log_buf(tp, last_ibp, offset,
1709                                   (offset + sizeof(xfs_agino_t) - 1));
1710                 xfs_inobp_check(mp, last_ibp);
1711         }
1712         return 0;
1713 }
1714
1715 /*
1716  * A big issue when freeing the inode cluster is is that we _cannot_ skip any
1717  * inodes that are in memory - they all must be marked stale and attached to
1718  * the cluster buffer.
1719  */
1720 STATIC int
1721 xfs_ifree_cluster(
1722         xfs_inode_t     *free_ip,
1723         xfs_trans_t     *tp,
1724         xfs_ino_t       inum)
1725 {
1726         xfs_mount_t             *mp = free_ip->i_mount;
1727         int                     blks_per_cluster;
1728         int                     nbufs;
1729         int                     ninodes;
1730         int                     i, j;
1731         xfs_daddr_t             blkno;
1732         xfs_buf_t               *bp;
1733         xfs_inode_t             *ip;
1734         xfs_inode_log_item_t    *iip;
1735         xfs_log_item_t          *lip;
1736         struct xfs_perag        *pag;
1737
1738         pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, inum));
1739         if (mp->m_sb.sb_blocksize >= XFS_INODE_CLUSTER_SIZE(mp)) {
1740                 blks_per_cluster = 1;
1741                 ninodes = mp->m_sb.sb_inopblock;
1742                 nbufs = XFS_IALLOC_BLOCKS(mp);
1743         } else {
1744                 blks_per_cluster = XFS_INODE_CLUSTER_SIZE(mp) /
1745                                         mp->m_sb.sb_blocksize;
1746                 ninodes = blks_per_cluster * mp->m_sb.sb_inopblock;
1747                 nbufs = XFS_IALLOC_BLOCKS(mp) / blks_per_cluster;
1748         }
1749
1750         for (j = 0; j < nbufs; j++, inum += ninodes) {
1751                 blkno = XFS_AGB_TO_DADDR(mp, XFS_INO_TO_AGNO(mp, inum),
1752                                          XFS_INO_TO_AGBNO(mp, inum));
1753
1754                 /*
1755                  * We obtain and lock the backing buffer first in the process
1756                  * here, as we have to ensure that any dirty inode that we
1757                  * can't get the flush lock on is attached to the buffer.
1758                  * If we scan the in-memory inodes first, then buffer IO can
1759                  * complete before we get a lock on it, and hence we may fail
1760                  * to mark all the active inodes on the buffer stale.
1761                  */
1762                 bp = xfs_trans_get_buf(tp, mp->m_ddev_targp, blkno,
1763                                         mp->m_bsize * blks_per_cluster, 0);
1764
1765                 if (!bp)
1766                         return ENOMEM;
1767                 /*
1768                  * Walk the inodes already attached to the buffer and mark them
1769                  * stale. These will all have the flush locks held, so an
1770                  * in-memory inode walk can't lock them. By marking them all
1771                  * stale first, we will not attempt to lock them in the loop
1772                  * below as the XFS_ISTALE flag will be set.
1773                  */
1774                 lip = bp->b_fspriv;
1775                 while (lip) {
1776                         if (lip->li_type == XFS_LI_INODE) {
1777                                 iip = (xfs_inode_log_item_t *)lip;
1778                                 ASSERT(iip->ili_logged == 1);
1779                                 lip->li_cb = xfs_istale_done;
1780                                 xfs_trans_ail_copy_lsn(mp->m_ail,
1781                                                         &iip->ili_flush_lsn,
1782                                                         &iip->ili_item.li_lsn);
1783                                 xfs_iflags_set(iip->ili_inode, XFS_ISTALE);
1784                         }
1785                         lip = lip->li_bio_list;
1786                 }
1787
1788
1789                 /*
1790                  * For each inode in memory attempt to add it to the inode
1791                  * buffer and set it up for being staled on buffer IO
1792                  * completion.  This is safe as we've locked out tail pushing
1793                  * and flushing by locking the buffer.
1794                  *
1795                  * We have already marked every inode that was part of a
1796                  * transaction stale above, which means there is no point in
1797                  * even trying to lock them.
1798                  */
1799                 for (i = 0; i < ninodes; i++) {
1800 retry:
1801                         rcu_read_lock();
1802                         ip = radix_tree_lookup(&pag->pag_ici_root,
1803                                         XFS_INO_TO_AGINO(mp, (inum + i)));
1804
1805                         /* Inode not in memory, nothing to do */
1806                         if (!ip) {
1807                                 rcu_read_unlock();
1808                                 continue;
1809                         }
1810
1811                         /*
1812                          * because this is an RCU protected lookup, we could
1813                          * find a recently freed or even reallocated inode
1814                          * during the lookup. We need to check under the
1815                          * i_flags_lock for a valid inode here. Skip it if it
1816                          * is not valid, the wrong inode or stale.
1817                          */
1818                         spin_lock(&ip->i_flags_lock);
1819                         if (ip->i_ino != inum + i ||
1820                             __xfs_iflags_test(ip, XFS_ISTALE)) {
1821                                 spin_unlock(&ip->i_flags_lock);
1822                                 rcu_read_unlock();
1823                                 continue;
1824                         }
1825                         spin_unlock(&ip->i_flags_lock);
1826
1827                         /*
1828                          * Don't try to lock/unlock the current inode, but we
1829                          * _cannot_ skip the other inodes that we did not find
1830                          * in the list attached to the buffer and are not
1831                          * already marked stale. If we can't lock it, back off
1832                          * and retry.
1833                          */
1834                         if (ip != free_ip &&
1835                             !xfs_ilock_nowait(ip, XFS_ILOCK_EXCL)) {
1836                                 rcu_read_unlock();
1837                                 delay(1);
1838                                 goto retry;
1839                         }
1840                         rcu_read_unlock();
1841
1842                         xfs_iflock(ip);
1843                         xfs_iflags_set(ip, XFS_ISTALE);
1844
1845                         /*
1846                          * we don't need to attach clean inodes or those only
1847                          * with unlogged changes (which we throw away, anyway).
1848                          */
1849                         iip = ip->i_itemp;
1850                         if (!iip || xfs_inode_clean(ip)) {
1851                                 ASSERT(ip != free_ip);
1852                                 xfs_ifunlock(ip);
1853                                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1854                                 continue;
1855                         }
1856
1857                         iip->ili_last_fields = iip->ili_fields;
1858                         iip->ili_fields = 0;
1859                         iip->ili_logged = 1;
1860                         xfs_trans_ail_copy_lsn(mp->m_ail, &iip->ili_flush_lsn,
1861                                                 &iip->ili_item.li_lsn);
1862
1863                         xfs_buf_attach_iodone(bp, xfs_istale_done,
1864                                                   &iip->ili_item);
1865
1866                         if (ip != free_ip)
1867                                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1868                 }
1869
1870                 xfs_trans_stale_inode_buf(tp, bp);
1871                 xfs_trans_binval(tp, bp);
1872         }
1873
1874         xfs_perag_put(pag);
1875         return 0;
1876 }
1877
1878 /*
1879  * This is called to return an inode to the inode free list.
1880  * The inode should already be truncated to 0 length and have
1881  * no pages associated with it.  This routine also assumes that
1882  * the inode is already a part of the transaction.
1883  *
1884  * The on-disk copy of the inode will have been added to the list
1885  * of unlinked inodes in the AGI. We need to remove the inode from
1886  * that list atomically with respect to freeing it here.
1887  */
1888 int
1889 xfs_ifree(
1890         xfs_trans_t     *tp,
1891         xfs_inode_t     *ip,
1892         xfs_bmap_free_t *flist)
1893 {
1894         int                     error;
1895         int                     delete;
1896         xfs_ino_t               first_ino;
1897         xfs_dinode_t            *dip;
1898         xfs_buf_t               *ibp;
1899
1900         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
1901         ASSERT(ip->i_d.di_nlink == 0);
1902         ASSERT(ip->i_d.di_nextents == 0);
1903         ASSERT(ip->i_d.di_anextents == 0);
1904         ASSERT(ip->i_d.di_size == 0 || !S_ISREG(ip->i_d.di_mode));
1905         ASSERT(ip->i_d.di_nblocks == 0);
1906
1907         /*
1908          * Pull the on-disk inode from the AGI unlinked list.
1909          */
1910         error = xfs_iunlink_remove(tp, ip);
1911         if (error != 0) {
1912                 return error;
1913         }
1914
1915         error = xfs_difree(tp, ip->i_ino, flist, &delete, &first_ino);
1916         if (error != 0) {
1917                 return error;
1918         }
1919         ip->i_d.di_mode = 0;            /* mark incore inode as free */
1920         ip->i_d.di_flags = 0;
1921         ip->i_d.di_dmevmask = 0;
1922         ip->i_d.di_forkoff = 0;         /* mark the attr fork not in use */
1923         ip->i_d.di_format = XFS_DINODE_FMT_EXTENTS;
1924         ip->i_d.di_aformat = XFS_DINODE_FMT_EXTENTS;
1925         /*
1926          * Bump the generation count so no one will be confused
1927          * by reincarnations of this inode.
1928          */
1929         ip->i_d.di_gen++;
1930
1931         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1932
1933         error = xfs_imap_to_bp(ip->i_mount, tp, &ip->i_imap, &dip, &ibp,
1934                                0, 0);
1935         if (error)
1936                 return error;
1937
1938         /*
1939         * Clear the on-disk di_mode. This is to prevent xfs_bulkstat
1940         * from picking up this inode when it is reclaimed (its incore state
1941         * initialzed but not flushed to disk yet). The in-core di_mode is
1942         * already cleared  and a corresponding transaction logged.
1943         * The hack here just synchronizes the in-core to on-disk
1944         * di_mode value in advance before the actual inode sync to disk.
1945         * This is OK because the inode is already unlinked and would never
1946         * change its di_mode again for this inode generation.
1947         * This is a temporary hack that would require a proper fix
1948         * in the future.
1949         */
1950         dip->di_mode = 0;
1951
1952         if (delete) {
1953                 error = xfs_ifree_cluster(ip, tp, first_ino);
1954         }
1955
1956         return error;
1957 }
1958
1959 /*
1960  * Reallocate the space for if_broot based on the number of records
1961  * being added or deleted as indicated in rec_diff.  Move the records
1962  * and pointers in if_broot to fit the new size.  When shrinking this
1963  * will eliminate holes between the records and pointers created by
1964  * the caller.  When growing this will create holes to be filled in
1965  * by the caller.
1966  *
1967  * The caller must not request to add more records than would fit in
1968  * the on-disk inode root.  If the if_broot is currently NULL, then
1969  * if we adding records one will be allocated.  The caller must also
1970  * not request that the number of records go below zero, although
1971  * it can go to zero.
1972  *
1973  * ip -- the inode whose if_broot area is changing
1974  * ext_diff -- the change in the number of records, positive or negative,
1975  *       requested for the if_broot array.
1976  */
1977 void
1978 xfs_iroot_realloc(
1979         xfs_inode_t             *ip,
1980         int                     rec_diff,
1981         int                     whichfork)
1982 {
1983         struct xfs_mount        *mp = ip->i_mount;
1984         int                     cur_max;
1985         xfs_ifork_t             *ifp;
1986         struct xfs_btree_block  *new_broot;
1987         int                     new_max;
1988         size_t                  new_size;
1989         char                    *np;
1990         char                    *op;
1991
1992         /*
1993          * Handle the degenerate case quietly.
1994          */
1995         if (rec_diff == 0) {
1996                 return;
1997         }
1998
1999         ifp = XFS_IFORK_PTR(ip, whichfork);
2000         if (rec_diff > 0) {
2001                 /*
2002                  * If there wasn't any memory allocated before, just
2003                  * allocate it now and get out.
2004                  */
2005                 if (ifp->if_broot_bytes == 0) {
2006                         new_size = (size_t)XFS_BMAP_BROOT_SPACE_CALC(rec_diff);
2007                         ifp->if_broot = kmem_alloc(new_size, KM_SLEEP | KM_NOFS);
2008                         ifp->if_broot_bytes = (int)new_size;
2009                         return;
2010                 }
2011
2012                 /*
2013                  * If there is already an existing if_broot, then we need
2014                  * to realloc() it and shift the pointers to their new
2015                  * location.  The records don't change location because
2016                  * they are kept butted up against the btree block header.
2017                  */
2018                 cur_max = xfs_bmbt_maxrecs(mp, ifp->if_broot_bytes, 0);
2019                 new_max = cur_max + rec_diff;
2020                 new_size = (size_t)XFS_BMAP_BROOT_SPACE_CALC(new_max);
2021                 ifp->if_broot = kmem_realloc(ifp->if_broot, new_size,
2022                                 (size_t)XFS_BMAP_BROOT_SPACE_CALC(cur_max), /* old size */
2023                                 KM_SLEEP | KM_NOFS);
2024                 op = (char *)XFS_BMAP_BROOT_PTR_ADDR(mp, ifp->if_broot, 1,
2025                                                      ifp->if_broot_bytes);
2026                 np = (char *)XFS_BMAP_BROOT_PTR_ADDR(mp, ifp->if_broot, 1,
2027                                                      (int)new_size);
2028                 ifp->if_broot_bytes = (int)new_size;
2029                 ASSERT(ifp->if_broot_bytes <=
2030                         XFS_IFORK_SIZE(ip, whichfork) + XFS_BROOT_SIZE_ADJ);
2031                 memmove(np, op, cur_max * (uint)sizeof(xfs_dfsbno_t));
2032                 return;
2033         }
2034
2035         /*
2036          * rec_diff is less than 0.  In this case, we are shrinking the
2037          * if_broot buffer.  It must already exist.  If we go to zero
2038          * records, just get rid of the root and clear the status bit.
2039          */
2040         ASSERT((ifp->if_broot != NULL) && (ifp->if_broot_bytes > 0));
2041         cur_max = xfs_bmbt_maxrecs(mp, ifp->if_broot_bytes, 0);
2042         new_max = cur_max + rec_diff;
2043         ASSERT(new_max >= 0);
2044         if (new_max > 0)
2045                 new_size = (size_t)XFS_BMAP_BROOT_SPACE_CALC(new_max);
2046         else
2047                 new_size = 0;
2048         if (new_size > 0) {
2049                 new_broot = kmem_alloc(new_size, KM_SLEEP | KM_NOFS);
2050                 /*
2051                  * First copy over the btree block header.
2052                  */
2053                 memcpy(new_broot, ifp->if_broot, XFS_BTREE_LBLOCK_LEN);
2054         } else {
2055                 new_broot = NULL;
2056                 ifp->if_flags &= ~XFS_IFBROOT;
2057         }
2058
2059         /*
2060          * Only copy the records and pointers if there are any.
2061          */
2062         if (new_max > 0) {
2063                 /*
2064                  * First copy the records.
2065                  */
2066                 op = (char *)XFS_BMBT_REC_ADDR(mp, ifp->if_broot, 1);
2067                 np = (char *)XFS_BMBT_REC_ADDR(mp, new_broot, 1);
2068                 memcpy(np, op, new_max * (uint)sizeof(xfs_bmbt_rec_t));
2069
2070                 /*
2071                  * Then copy the pointers.
2072                  */
2073                 op = (char *)XFS_BMAP_BROOT_PTR_ADDR(mp, ifp->if_broot, 1,
2074                                                      ifp->if_broot_bytes);
2075                 np = (char *)XFS_BMAP_BROOT_PTR_ADDR(mp, new_broot, 1,
2076                                                      (int)new_size);
2077                 memcpy(np, op, new_max * (uint)sizeof(xfs_dfsbno_t));
2078         }
2079         kmem_free(ifp->if_broot);
2080         ifp->if_broot = new_broot;
2081         ifp->if_broot_bytes = (int)new_size;
2082         ASSERT(ifp->if_broot_bytes <=
2083                 XFS_IFORK_SIZE(ip, whichfork) + XFS_BROOT_SIZE_ADJ);
2084         return;
2085 }
2086
2087
2088 /*
2089  * This is called when the amount of space needed for if_data
2090  * is increased or decreased.  The change in size is indicated by
2091  * the number of bytes that need to be added or deleted in the
2092  * byte_diff parameter.
2093  *
2094  * If the amount of space needed has decreased below the size of the
2095  * inline buffer, then switch to using the inline buffer.  Otherwise,
2096  * use kmem_realloc() or kmem_alloc() to adjust the size of the buffer
2097  * to what is needed.
2098  *
2099  * ip -- the inode whose if_data area is changing
2100  * byte_diff -- the change in the number of bytes, positive or negative,
2101  *       requested for the if_data array.
2102  */
2103 void
2104 xfs_idata_realloc(
2105         xfs_inode_t     *ip,
2106         int             byte_diff,
2107         int             whichfork)
2108 {
2109         xfs_ifork_t     *ifp;
2110         int             new_size;
2111         int             real_size;
2112
2113         if (byte_diff == 0) {
2114                 return;
2115         }
2116
2117         ifp = XFS_IFORK_PTR(ip, whichfork);
2118         new_size = (int)ifp->if_bytes + byte_diff;
2119         ASSERT(new_size >= 0);
2120
2121         if (new_size == 0) {
2122                 if (ifp->if_u1.if_data != ifp->if_u2.if_inline_data) {
2123                         kmem_free(ifp->if_u1.if_data);
2124                 }
2125                 ifp->if_u1.if_data = NULL;
2126                 real_size = 0;
2127         } else if (new_size <= sizeof(ifp->if_u2.if_inline_data)) {
2128                 /*
2129                  * If the valid extents/data can fit in if_inline_ext/data,
2130                  * copy them from the malloc'd vector and free it.
2131                  */
2132                 if (ifp->if_u1.if_data == NULL) {
2133                         ifp->if_u1.if_data = ifp->if_u2.if_inline_data;
2134                 } else if (ifp->if_u1.if_data != ifp->if_u2.if_inline_data) {
2135                         ASSERT(ifp->if_real_bytes != 0);
2136                         memcpy(ifp->if_u2.if_inline_data, ifp->if_u1.if_data,
2137                               new_size);
2138                         kmem_free(ifp->if_u1.if_data);
2139                         ifp->if_u1.if_data = ifp->if_u2.if_inline_data;
2140                 }
2141                 real_size = 0;
2142         } else {
2143                 /*
2144                  * Stuck with malloc/realloc.
2145                  * For inline data, the underlying buffer must be
2146                  * a multiple of 4 bytes in size so that it can be
2147                  * logged and stay on word boundaries.  We enforce
2148                  * that here.
2149                  */
2150                 real_size = roundup(new_size, 4);
2151                 if (ifp->if_u1.if_data == NULL) {
2152                         ASSERT(ifp->if_real_bytes == 0);
2153                         ifp->if_u1.if_data = kmem_alloc(real_size,
2154                                                         KM_SLEEP | KM_NOFS);
2155                 } else if (ifp->if_u1.if_data != ifp->if_u2.if_inline_data) {
2156                         /*
2157                          * Only do the realloc if the underlying size
2158                          * is really changing.
2159                          */
2160                         if (ifp->if_real_bytes != real_size) {
2161                                 ifp->if_u1.if_data =
2162                                         kmem_realloc(ifp->if_u1.if_data,
2163                                                         real_size,
2164                                                         ifp->if_real_bytes,
2165                                                         KM_SLEEP | KM_NOFS);
2166                         }
2167                 } else {
2168                         ASSERT(ifp->if_real_bytes == 0);
2169                         ifp->if_u1.if_data = kmem_alloc(real_size,
2170                                                         KM_SLEEP | KM_NOFS);
2171                         memcpy(ifp->if_u1.if_data, ifp->if_u2.if_inline_data,
2172                                 ifp->if_bytes);
2173                 }
2174         }
2175         ifp->if_real_bytes = real_size;
2176         ifp->if_bytes = new_size;
2177         ASSERT(ifp->if_bytes <= XFS_IFORK_SIZE(ip, whichfork));
2178 }
2179
2180 void
2181 xfs_idestroy_fork(
2182         xfs_inode_t     *ip,
2183         int             whichfork)
2184 {
2185         xfs_ifork_t     *ifp;
2186
2187         ifp = XFS_IFORK_PTR(ip, whichfork);
2188         if (ifp->if_broot != NULL) {
2189                 kmem_free(ifp->if_broot);
2190                 ifp->if_broot = NULL;
2191         }
2192
2193         /*
2194          * If the format is local, then we can't have an extents
2195          * array so just look for an inline data array.  If we're
2196          * not local then we may or may not have an extents list,
2197          * so check and free it up if we do.
2198          */
2199         if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) {
2200                 if ((ifp->if_u1.if_data != ifp->if_u2.if_inline_data) &&
2201                     (ifp->if_u1.if_data != NULL)) {
2202                         ASSERT(ifp->if_real_bytes != 0);
2203                         kmem_free(ifp->if_u1.if_data);
2204                         ifp->if_u1.if_data = NULL;
2205                         ifp->if_real_bytes = 0;
2206                 }
2207         } else if ((ifp->if_flags & XFS_IFEXTENTS) &&
2208                    ((ifp->if_flags & XFS_IFEXTIREC) ||
2209                     ((ifp->if_u1.if_extents != NULL) &&
2210                      (ifp->if_u1.if_extents != ifp->if_u2.if_inline_ext)))) {
2211                 ASSERT(ifp->if_real_bytes != 0);
2212                 xfs_iext_destroy(ifp);
2213         }
2214         ASSERT(ifp->if_u1.if_extents == NULL ||
2215                ifp->if_u1.if_extents == ifp->if_u2.if_inline_ext);
2216         ASSERT(ifp->if_real_bytes == 0);
2217         if (whichfork == XFS_ATTR_FORK) {
2218                 kmem_zone_free(xfs_ifork_zone, ip->i_afp);
2219                 ip->i_afp = NULL;
2220         }
2221 }
2222
2223 /*
2224  * This is called to unpin an inode.  The caller must have the inode locked
2225  * in at least shared mode so that the buffer cannot be subsequently pinned
2226  * once someone is waiting for it to be unpinned.
2227  */
2228 static void
2229 xfs_iunpin(
2230         struct xfs_inode        *ip)
2231 {
2232         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL|XFS_ILOCK_SHARED));
2233
2234         trace_xfs_inode_unpin_nowait(ip, _RET_IP_);
2235
2236         /* Give the log a push to start the unpinning I/O */
2237         xfs_log_force_lsn(ip->i_mount, ip->i_itemp->ili_last_lsn, 0);
2238
2239 }
2240
2241 static void
2242 __xfs_iunpin_wait(
2243         struct xfs_inode        *ip)
2244 {
2245         wait_queue_head_t *wq = bit_waitqueue(&ip->i_flags, __XFS_IPINNED_BIT);
2246         DEFINE_WAIT_BIT(wait, &ip->i_flags, __XFS_IPINNED_BIT);
2247
2248         xfs_iunpin(ip);
2249
2250         do {
2251                 prepare_to_wait(wq, &wait.wait, TASK_UNINTERRUPTIBLE);
2252                 if (xfs_ipincount(ip))
2253                         io_schedule();
2254         } while (xfs_ipincount(ip));
2255         finish_wait(wq, &wait.wait);
2256 }
2257
2258 void
2259 xfs_iunpin_wait(
2260         struct xfs_inode        *ip)
2261 {
2262         if (xfs_ipincount(ip))
2263                 __xfs_iunpin_wait(ip);
2264 }
2265
2266 /*
2267  * xfs_iextents_copy()
2268  *
2269  * This is called to copy the REAL extents (as opposed to the delayed
2270  * allocation extents) from the inode into the given buffer.  It
2271  * returns the number of bytes copied into the buffer.
2272  *
2273  * If there are no delayed allocation extents, then we can just
2274  * memcpy() the extents into the buffer.  Otherwise, we need to
2275  * examine each extent in turn and skip those which are delayed.
2276  */
2277 int
2278 xfs_iextents_copy(
2279         xfs_inode_t             *ip,
2280         xfs_bmbt_rec_t          *dp,
2281         int                     whichfork)
2282 {
2283         int                     copied;
2284         int                     i;
2285         xfs_ifork_t             *ifp;
2286         int                     nrecs;
2287         xfs_fsblock_t           start_block;
2288
2289         ifp = XFS_IFORK_PTR(ip, whichfork);
2290         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL|XFS_ILOCK_SHARED));
2291         ASSERT(ifp->if_bytes > 0);
2292
2293         nrecs = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
2294         XFS_BMAP_TRACE_EXLIST(ip, nrecs, whichfork);
2295         ASSERT(nrecs > 0);
2296
2297         /*
2298          * There are some delayed allocation extents in the
2299          * inode, so copy the extents one at a time and skip
2300          * the delayed ones.  There must be at least one
2301          * non-delayed extent.
2302          */
2303         copied = 0;
2304         for (i = 0; i < nrecs; i++) {
2305                 xfs_bmbt_rec_host_t *ep = xfs_iext_get_ext(ifp, i);
2306                 start_block = xfs_bmbt_get_startblock(ep);
2307                 if (isnullstartblock(start_block)) {
2308                         /*
2309                          * It's a delayed allocation extent, so skip it.
2310                          */
2311                         continue;
2312                 }
2313
2314                 /* Translate to on disk format */
2315                 put_unaligned(cpu_to_be64(ep->l0), &dp->l0);
2316                 put_unaligned(cpu_to_be64(ep->l1), &dp->l1);
2317                 dp++;
2318                 copied++;
2319         }
2320         ASSERT(copied != 0);
2321         xfs_validate_extents(ifp, copied, XFS_EXTFMT_INODE(ip));
2322
2323         return (copied * (uint)sizeof(xfs_bmbt_rec_t));
2324 }
2325
2326 /*
2327  * Each of the following cases stores data into the same region
2328  * of the on-disk inode, so only one of them can be valid at
2329  * any given time. While it is possible to have conflicting formats
2330  * and log flags, e.g. having XFS_ILOG_?DATA set when the fork is
2331  * in EXTENTS format, this can only happen when the fork has
2332  * changed formats after being modified but before being flushed.
2333  * In these cases, the format always takes precedence, because the
2334  * format indicates the current state of the fork.
2335  */
2336 /*ARGSUSED*/
2337 STATIC void
2338 xfs_iflush_fork(
2339         xfs_inode_t             *ip,
2340         xfs_dinode_t            *dip,
2341         xfs_inode_log_item_t    *iip,
2342         int                     whichfork,
2343         xfs_buf_t               *bp)
2344 {
2345         char                    *cp;
2346         xfs_ifork_t             *ifp;
2347         xfs_mount_t             *mp;
2348 #ifdef XFS_TRANS_DEBUG
2349         int                     first;
2350 #endif
2351         static const short      brootflag[2] =
2352                 { XFS_ILOG_DBROOT, XFS_ILOG_ABROOT };
2353         static const short      dataflag[2] =
2354                 { XFS_ILOG_DDATA, XFS_ILOG_ADATA };
2355         static const short      extflag[2] =
2356                 { XFS_ILOG_DEXT, XFS_ILOG_AEXT };
2357
2358         if (!iip)
2359                 return;
2360         ifp = XFS_IFORK_PTR(ip, whichfork);
2361         /*
2362          * This can happen if we gave up in iformat in an error path,
2363          * for the attribute fork.
2364          */
2365         if (!ifp) {
2366                 ASSERT(whichfork == XFS_ATTR_FORK);
2367                 return;
2368         }
2369         cp = XFS_DFORK_PTR(dip, whichfork);
2370         mp = ip->i_mount;
2371         switch (XFS_IFORK_FORMAT(ip, whichfork)) {
2372         case XFS_DINODE_FMT_LOCAL:
2373                 if ((iip->ili_fields & dataflag[whichfork]) &&
2374                     (ifp->if_bytes > 0)) {
2375                         ASSERT(ifp->if_u1.if_data != NULL);
2376                         ASSERT(ifp->if_bytes <= XFS_IFORK_SIZE(ip, whichfork));
2377                         memcpy(cp, ifp->if_u1.if_data, ifp->if_bytes);
2378                 }
2379                 break;
2380
2381         case XFS_DINODE_FMT_EXTENTS:
2382                 ASSERT((ifp->if_flags & XFS_IFEXTENTS) ||
2383                        !(iip->ili_fields & extflag[whichfork]));
2384                 if ((iip->ili_fields & extflag[whichfork]) &&
2385                     (ifp->if_bytes > 0)) {
2386                         ASSERT(xfs_iext_get_ext(ifp, 0));
2387                         ASSERT(XFS_IFORK_NEXTENTS(ip, whichfork) > 0);
2388                         (void)xfs_iextents_copy(ip, (xfs_bmbt_rec_t *)cp,
2389                                 whichfork);
2390                 }
2391                 break;
2392
2393         case XFS_DINODE_FMT_BTREE:
2394                 if ((iip->ili_fields & brootflag[whichfork]) &&
2395                     (ifp->if_broot_bytes > 0)) {
2396                         ASSERT(ifp->if_broot != NULL);
2397                         ASSERT(ifp->if_broot_bytes <=
2398                                (XFS_IFORK_SIZE(ip, whichfork) +
2399                                 XFS_BROOT_SIZE_ADJ));
2400                         xfs_bmbt_to_bmdr(mp, ifp->if_broot, ifp->if_broot_bytes,
2401                                 (xfs_bmdr_block_t *)cp,
2402                                 XFS_DFORK_SIZE(dip, mp, whichfork));
2403                 }
2404                 break;
2405
2406         case XFS_DINODE_FMT_DEV:
2407                 if (iip->ili_fields & XFS_ILOG_DEV) {
2408                         ASSERT(whichfork == XFS_DATA_FORK);
2409                         xfs_dinode_put_rdev(dip, ip->i_df.if_u2.if_rdev);
2410                 }
2411                 break;
2412
2413         case XFS_DINODE_FMT_UUID:
2414                 if (iip->ili_fields & XFS_ILOG_UUID) {
2415                         ASSERT(whichfork == XFS_DATA_FORK);
2416                         memcpy(XFS_DFORK_DPTR(dip),
2417                                &ip->i_df.if_u2.if_uuid,
2418                                sizeof(uuid_t));
2419                 }
2420                 break;
2421
2422         default:
2423                 ASSERT(0);
2424                 break;
2425         }
2426 }
2427
2428 STATIC int
2429 xfs_iflush_cluster(
2430         xfs_inode_t     *ip,
2431         xfs_buf_t       *bp)
2432 {
2433         xfs_mount_t             *mp = ip->i_mount;
2434         struct xfs_perag        *pag;
2435         unsigned long           first_index, mask;
2436         unsigned long           inodes_per_cluster;
2437         int                     ilist_size;
2438         xfs_inode_t             **ilist;
2439         xfs_inode_t             *iq;
2440         int                     nr_found;
2441         int                     clcount = 0;
2442         int                     bufwasdelwri;
2443         int                     i;
2444
2445         pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, ip->i_ino));
2446
2447         inodes_per_cluster = XFS_INODE_CLUSTER_SIZE(mp) >> mp->m_sb.sb_inodelog;
2448         ilist_size = inodes_per_cluster * sizeof(xfs_inode_t *);
2449         ilist = kmem_alloc(ilist_size, KM_MAYFAIL|KM_NOFS);
2450         if (!ilist)
2451                 goto out_put;
2452
2453         mask = ~(((XFS_INODE_CLUSTER_SIZE(mp) >> mp->m_sb.sb_inodelog)) - 1);
2454         first_index = XFS_INO_TO_AGINO(mp, ip->i_ino) & mask;
2455         rcu_read_lock();
2456         /* really need a gang lookup range call here */
2457         nr_found = radix_tree_gang_lookup(&pag->pag_ici_root, (void**)ilist,
2458                                         first_index, inodes_per_cluster);
2459         if (nr_found == 0)
2460                 goto out_free;
2461
2462         for (i = 0; i < nr_found; i++) {
2463                 iq = ilist[i];
2464                 if (iq == ip)
2465                         continue;
2466
2467                 /*
2468                  * because this is an RCU protected lookup, we could find a
2469                  * recently freed or even reallocated inode during the lookup.
2470                  * We need to check under the i_flags_lock for a valid inode
2471                  * here. Skip it if it is not valid or the wrong inode.
2472                  */
2473                 spin_lock(&ip->i_flags_lock);
2474                 if (!ip->i_ino ||
2475                     (XFS_INO_TO_AGINO(mp, iq->i_ino) & mask) != first_index) {
2476                         spin_unlock(&ip->i_flags_lock);
2477                         continue;
2478                 }
2479                 spin_unlock(&ip->i_flags_lock);
2480
2481                 /*
2482                  * Do an un-protected check to see if the inode is dirty and
2483                  * is a candidate for flushing.  These checks will be repeated
2484                  * later after the appropriate locks are acquired.
2485                  */
2486                 if (xfs_inode_clean(iq) && xfs_ipincount(iq) == 0)
2487                         continue;
2488
2489                 /*
2490                  * Try to get locks.  If any are unavailable or it is pinned,
2491                  * then this inode cannot be flushed and is skipped.
2492                  */
2493
2494                 if (!xfs_ilock_nowait(iq, XFS_ILOCK_SHARED))
2495                         continue;
2496                 if (!xfs_iflock_nowait(iq)) {
2497                         xfs_iunlock(iq, XFS_ILOCK_SHARED);
2498                         continue;
2499                 }
2500                 if (xfs_ipincount(iq)) {
2501                         xfs_ifunlock(iq);
2502                         xfs_iunlock(iq, XFS_ILOCK_SHARED);
2503                         continue;
2504                 }
2505
2506                 /*
2507                  * arriving here means that this inode can be flushed.  First
2508                  * re-check that it's dirty before flushing.
2509                  */
2510                 if (!xfs_inode_clean(iq)) {
2511                         int     error;
2512                         error = xfs_iflush_int(iq, bp);
2513                         if (error) {
2514                                 xfs_iunlock(iq, XFS_ILOCK_SHARED);
2515                                 goto cluster_corrupt_out;
2516                         }
2517                         clcount++;
2518                 } else {
2519                         xfs_ifunlock(iq);
2520                 }
2521                 xfs_iunlock(iq, XFS_ILOCK_SHARED);
2522         }
2523
2524         if (clcount) {
2525                 XFS_STATS_INC(xs_icluster_flushcnt);
2526                 XFS_STATS_ADD(xs_icluster_flushinode, clcount);
2527         }
2528
2529 out_free:
2530         rcu_read_unlock();
2531         kmem_free(ilist);
2532 out_put:
2533         xfs_perag_put(pag);
2534         return 0;
2535
2536
2537 cluster_corrupt_out:
2538         /*
2539          * Corruption detected in the clustering loop.  Invalidate the
2540          * inode buffer and shut down the filesystem.
2541          */
2542         rcu_read_unlock();
2543         /*
2544          * Clean up the buffer.  If it was delwri, just release it --
2545          * brelse can handle it with no problems.  If not, shut down the
2546          * filesystem before releasing the buffer.
2547          */
2548         bufwasdelwri = (bp->b_flags & _XBF_DELWRI_Q);
2549         if (bufwasdelwri)
2550                 xfs_buf_relse(bp);
2551
2552         xfs_force_shutdown(mp, SHUTDOWN_CORRUPT_INCORE);
2553
2554         if (!bufwasdelwri) {
2555                 /*
2556                  * Just like incore_relse: if we have b_iodone functions,
2557                  * mark the buffer as an error and call them.  Otherwise
2558                  * mark it as stale and brelse.
2559                  */
2560                 if (bp->b_iodone) {
2561                         XFS_BUF_UNDONE(bp);
2562                         xfs_buf_stale(bp);
2563                         xfs_buf_ioerror(bp, EIO);
2564                         xfs_buf_ioend(bp, 0);
2565                 } else {
2566                         xfs_buf_stale(bp);
2567                         xfs_buf_relse(bp);
2568                 }
2569         }
2570
2571         /*
2572          * Unlocks the flush lock
2573          */
2574         xfs_iflush_abort(iq, false);
2575         kmem_free(ilist);
2576         xfs_perag_put(pag);
2577         return XFS_ERROR(EFSCORRUPTED);
2578 }
2579
2580 /*
2581  * Flush dirty inode metadata into the backing buffer.
2582  *
2583  * The caller must have the inode lock and the inode flush lock held.  The
2584  * inode lock will still be held upon return to the caller, and the inode
2585  * flush lock will be released after the inode has reached the disk.
2586  *
2587  * The caller must write out the buffer returned in *bpp and release it.
2588  */
2589 int
2590 xfs_iflush(
2591         struct xfs_inode        *ip,
2592         struct xfs_buf          **bpp)
2593 {
2594         struct xfs_mount        *mp = ip->i_mount;
2595         struct xfs_buf          *bp;
2596         struct xfs_dinode       *dip;
2597         int                     error;
2598
2599         XFS_STATS_INC(xs_iflush_count);
2600
2601         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL|XFS_ILOCK_SHARED));
2602         ASSERT(xfs_isiflocked(ip));
2603         ASSERT(ip->i_d.di_format != XFS_DINODE_FMT_BTREE ||
2604                ip->i_d.di_nextents > XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK));
2605
2606         *bpp = NULL;
2607
2608         xfs_iunpin_wait(ip);
2609
2610         /*
2611          * For stale inodes we cannot rely on the backing buffer remaining
2612          * stale in cache for the remaining life of the stale inode and so
2613          * xfs_imap_to_bp() below may give us a buffer that no longer contains
2614          * inodes below. We have to check this after ensuring the inode is
2615          * unpinned so that it is safe to reclaim the stale inode after the
2616          * flush call.
2617          */
2618         if (xfs_iflags_test(ip, XFS_ISTALE)) {
2619                 xfs_ifunlock(ip);
2620                 return 0;
2621         }
2622
2623         /*
2624          * This may have been unpinned because the filesystem is shutting
2625          * down forcibly. If that's the case we must not write this inode
2626          * to disk, because the log record didn't make it to disk.
2627          *
2628          * We also have to remove the log item from the AIL in this case,
2629          * as we wait for an empty AIL as part of the unmount process.
2630          */
2631         if (XFS_FORCED_SHUTDOWN(mp)) {
2632                 error = XFS_ERROR(EIO);
2633                 goto abort_out;
2634         }
2635
2636         /*
2637          * Get the buffer containing the on-disk inode.
2638          */
2639         error = xfs_imap_to_bp(mp, NULL, &ip->i_imap, &dip, &bp, XBF_TRYLOCK,
2640                                0);
2641         if (error || !bp) {
2642                 xfs_ifunlock(ip);
2643                 return error;
2644         }
2645
2646         /*
2647          * First flush out the inode that xfs_iflush was called with.
2648          */
2649         error = xfs_iflush_int(ip, bp);
2650         if (error)
2651                 goto corrupt_out;
2652
2653         /*
2654          * If the buffer is pinned then push on the log now so we won't
2655          * get stuck waiting in the write for too long.
2656          */
2657         if (xfs_buf_ispinned(bp))
2658                 xfs_log_force(mp, 0);
2659
2660         /*
2661          * inode clustering:
2662          * see if other inodes can be gathered into this write
2663          */
2664         error = xfs_iflush_cluster(ip, bp);
2665         if (error)
2666                 goto cluster_corrupt_out;
2667
2668         *bpp = bp;
2669         return 0;
2670
2671 corrupt_out:
2672         xfs_buf_relse(bp);
2673         xfs_force_shutdown(mp, SHUTDOWN_CORRUPT_INCORE);
2674 cluster_corrupt_out:
2675         error = XFS_ERROR(EFSCORRUPTED);
2676 abort_out:
2677         /*
2678          * Unlocks the flush lock
2679          */
2680         xfs_iflush_abort(ip, false);
2681         return error;
2682 }
2683
2684
2685 STATIC int
2686 xfs_iflush_int(
2687         xfs_inode_t             *ip,
2688         xfs_buf_t               *bp)
2689 {
2690         xfs_inode_log_item_t    *iip;
2691         xfs_dinode_t            *dip;
2692         xfs_mount_t             *mp;
2693 #ifdef XFS_TRANS_DEBUG
2694         int                     first;
2695 #endif
2696
2697         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL|XFS_ILOCK_SHARED));
2698         ASSERT(xfs_isiflocked(ip));
2699         ASSERT(ip->i_d.di_format != XFS_DINODE_FMT_BTREE ||
2700                ip->i_d.di_nextents > XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK));
2701
2702         iip = ip->i_itemp;
2703         mp = ip->i_mount;
2704
2705         /* set *dip = inode's place in the buffer */
2706         dip = (xfs_dinode_t *)xfs_buf_offset(bp, ip->i_imap.im_boffset);
2707
2708         if (XFS_TEST_ERROR(dip->di_magic != cpu_to_be16(XFS_DINODE_MAGIC),
2709                                mp, XFS_ERRTAG_IFLUSH_1, XFS_RANDOM_IFLUSH_1)) {
2710                 xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
2711                         "%s: Bad inode %Lu magic number 0x%x, ptr 0x%p",
2712                         __func__, ip->i_ino, be16_to_cpu(dip->di_magic), dip);
2713                 goto corrupt_out;
2714         }
2715         if (XFS_TEST_ERROR(ip->i_d.di_magic != XFS_DINODE_MAGIC,
2716                                 mp, XFS_ERRTAG_IFLUSH_2, XFS_RANDOM_IFLUSH_2)) {
2717                 xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
2718                         "%s: Bad inode %Lu, ptr 0x%p, magic number 0x%x",
2719                         __func__, ip->i_ino, ip, ip->i_d.di_magic);
2720                 goto corrupt_out;
2721         }
2722         if (S_ISREG(ip->i_d.di_mode)) {
2723                 if (XFS_TEST_ERROR(
2724                     (ip->i_d.di_format != XFS_DINODE_FMT_EXTENTS) &&
2725                     (ip->i_d.di_format != XFS_DINODE_FMT_BTREE),
2726                     mp, XFS_ERRTAG_IFLUSH_3, XFS_RANDOM_IFLUSH_3)) {
2727                         xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
2728                                 "%s: Bad regular inode %Lu, ptr 0x%p",
2729                                 __func__, ip->i_ino, ip);
2730                         goto corrupt_out;
2731                 }
2732         } else if (S_ISDIR(ip->i_d.di_mode)) {
2733                 if (XFS_TEST_ERROR(
2734                     (ip->i_d.di_format != XFS_DINODE_FMT_EXTENTS) &&
2735                     (ip->i_d.di_format != XFS_DINODE_FMT_BTREE) &&
2736                     (ip->i_d.di_format != XFS_DINODE_FMT_LOCAL),
2737                     mp, XFS_ERRTAG_IFLUSH_4, XFS_RANDOM_IFLUSH_4)) {
2738                         xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
2739                                 "%s: Bad directory inode %Lu, ptr 0x%p",
2740                                 __func__, ip->i_ino, ip);
2741                         goto corrupt_out;
2742                 }
2743         }
2744         if (XFS_TEST_ERROR(ip->i_d.di_nextents + ip->i_d.di_anextents >
2745                                 ip->i_d.di_nblocks, mp, XFS_ERRTAG_IFLUSH_5,
2746                                 XFS_RANDOM_IFLUSH_5)) {
2747                 xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
2748                         "%s: detected corrupt incore inode %Lu, "
2749                         "total extents = %d, nblocks = %Ld, ptr 0x%p",
2750                         __func__, ip->i_ino,
2751                         ip->i_d.di_nextents + ip->i_d.di_anextents,
2752                         ip->i_d.di_nblocks, ip);
2753                 goto corrupt_out;
2754         }
2755         if (XFS_TEST_ERROR(ip->i_d.di_forkoff > mp->m_sb.sb_inodesize,
2756                                 mp, XFS_ERRTAG_IFLUSH_6, XFS_RANDOM_IFLUSH_6)) {
2757                 xfs_alert_tag(mp, XFS_PTAG_IFLUSH,
2758                         "%s: bad inode %Lu, forkoff 0x%x, ptr 0x%p",
2759                         __func__, ip->i_ino, ip->i_d.di_forkoff, ip);
2760                 goto corrupt_out;
2761         }
2762         /*
2763          * bump the flush iteration count, used to detect flushes which
2764          * postdate a log record during recovery.
2765          */
2766
2767         ip->i_d.di_flushiter++;
2768
2769         /*
2770          * Copy the dirty parts of the inode into the on-disk
2771          * inode.  We always copy out the core of the inode,
2772          * because if the inode is dirty at all the core must
2773          * be.
2774          */
2775         xfs_dinode_to_disk(dip, &ip->i_d);
2776
2777         /* Wrap, we never let the log put out DI_MAX_FLUSH */
2778         if (ip->i_d.di_flushiter == DI_MAX_FLUSH)
2779                 ip->i_d.di_flushiter = 0;
2780
2781         /*
2782          * If this is really an old format inode and the superblock version
2783          * has not been updated to support only new format inodes, then
2784          * convert back to the old inode format.  If the superblock version
2785          * has been updated, then make the conversion permanent.
2786          */
2787         ASSERT(ip->i_d.di_version == 1 || xfs_sb_version_hasnlink(&mp->m_sb));
2788         if (ip->i_d.di_version == 1) {
2789                 if (!xfs_sb_version_hasnlink(&mp->m_sb)) {
2790                         /*
2791                          * Convert it back.
2792                          */
2793                         ASSERT(ip->i_d.di_nlink <= XFS_MAXLINK_1);
2794                         dip->di_onlink = cpu_to_be16(ip->i_d.di_nlink);
2795                 } else {
2796                         /*
2797                          * The superblock version has already been bumped,
2798                          * so just make the conversion to the new inode
2799                          * format permanent.
2800                          */
2801                         ip->i_d.di_version = 2;
2802                         dip->di_version = 2;
2803                         ip->i_d.di_onlink = 0;
2804                         dip->di_onlink = 0;
2805                         memset(&(ip->i_d.di_pad[0]), 0, sizeof(ip->i_d.di_pad));
2806                         memset(&(dip->di_pad[0]), 0,
2807                               sizeof(dip->di_pad));
2808                         ASSERT(xfs_get_projid(ip) == 0);
2809                 }
2810         }
2811
2812         xfs_iflush_fork(ip, dip, iip, XFS_DATA_FORK, bp);
2813         if (XFS_IFORK_Q(ip))
2814                 xfs_iflush_fork(ip, dip, iip, XFS_ATTR_FORK, bp);
2815         xfs_inobp_check(mp, bp);
2816
2817         /*
2818          * We've recorded everything logged in the inode, so we'd like to clear
2819          * the ili_fields bits so we don't log and flush things unnecessarily.
2820          * However, we can't stop logging all this information until the data
2821          * we've copied into the disk buffer is written to disk.  If we did we
2822          * might overwrite the copy of the inode in the log with all the data
2823          * after re-logging only part of it, and in the face of a crash we
2824          * wouldn't have all the data we need to recover.
2825          *
2826          * What we do is move the bits to the ili_last_fields field.  When
2827          * logging the inode, these bits are moved back to the ili_fields field.
2828          * In the xfs_iflush_done() routine we clear ili_last_fields, since we
2829          * know that the information those bits represent is permanently on
2830          * disk.  As long as the flush completes before the inode is logged
2831          * again, then both ili_fields and ili_last_fields will be cleared.
2832          *
2833          * We can play with the ili_fields bits here, because the inode lock
2834          * must be held exclusively in order to set bits there and the flush
2835          * lock protects the ili_last_fields bits.  Set ili_logged so the flush
2836          * done routine can tell whether or not to look in the AIL.  Also, store
2837          * the current LSN of the inode so that we can tell whether the item has
2838          * moved in the AIL from xfs_iflush_done().  In order to read the lsn we
2839          * need the AIL lock, because it is a 64 bit value that cannot be read
2840          * atomically.
2841          */
2842         if (iip != NULL && iip->ili_fields != 0) {
2843                 iip->ili_last_fields = iip->ili_fields;
2844                 iip->ili_fields = 0;
2845                 iip->ili_logged = 1;
2846
2847                 xfs_trans_ail_copy_lsn(mp->m_ail, &iip->ili_flush_lsn,
2848                                         &iip->ili_item.li_lsn);
2849
2850                 /*
2851                  * Attach the function xfs_iflush_done to the inode's
2852                  * buffer.  This will remove the inode from the AIL
2853                  * and unlock the inode's flush lock when the inode is
2854                  * completely written to disk.
2855                  */
2856                 xfs_buf_attach_iodone(bp, xfs_iflush_done, &iip->ili_item);
2857
2858                 ASSERT(bp->b_fspriv != NULL);
2859                 ASSERT(bp->b_iodone != NULL);
2860         } else {
2861                 /*
2862                  * We're flushing an inode which is not in the AIL and has
2863                  * not been logged.  For this case we can immediately drop
2864                  * the inode flush lock because we can avoid the whole
2865                  * AIL state thing.  It's OK to drop the flush lock now,
2866                  * because we've already locked the buffer and to do anything
2867                  * you really need both.
2868                  */
2869                 if (iip != NULL) {
2870                         ASSERT(iip->ili_logged == 0);
2871                         ASSERT(iip->ili_last_fields == 0);
2872                         ASSERT((iip->ili_item.li_flags & XFS_LI_IN_AIL) == 0);
2873                 }
2874                 xfs_ifunlock(ip);
2875         }
2876
2877         return 0;
2878
2879 corrupt_out:
2880         return XFS_ERROR(EFSCORRUPTED);
2881 }
2882
2883 /*
2884  * Return a pointer to the extent record at file index idx.
2885  */
2886 xfs_bmbt_rec_host_t *
2887 xfs_iext_get_ext(
2888         xfs_ifork_t     *ifp,           /* inode fork pointer */
2889         xfs_extnum_t    idx)            /* index of target extent */
2890 {
2891         ASSERT(idx >= 0);
2892         ASSERT(idx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t));
2893
2894         if ((ifp->if_flags & XFS_IFEXTIREC) && (idx == 0)) {
2895                 return ifp->if_u1.if_ext_irec->er_extbuf;
2896         } else if (ifp->if_flags & XFS_IFEXTIREC) {
2897                 xfs_ext_irec_t  *erp;           /* irec pointer */
2898                 int             erp_idx = 0;    /* irec index */
2899                 xfs_extnum_t    page_idx = idx; /* ext index in target list */
2900
2901                 erp = xfs_iext_idx_to_irec(ifp, &page_idx, &erp_idx, 0);
2902                 return &erp->er_extbuf[page_idx];
2903         } else if (ifp->if_bytes) {
2904                 return &ifp->if_u1.if_extents[idx];
2905         } else {
2906                 return NULL;
2907         }
2908 }
2909
2910 /*
2911  * Insert new item(s) into the extent records for incore inode
2912  * fork 'ifp'.  'count' new items are inserted at index 'idx'.
2913  */
2914 void
2915 xfs_iext_insert(
2916         xfs_inode_t     *ip,            /* incore inode pointer */
2917         xfs_extnum_t    idx,            /* starting index of new items */
2918         xfs_extnum_t    count,          /* number of inserted items */
2919         xfs_bmbt_irec_t *new,           /* items to insert */
2920         int             state)          /* type of extent conversion */
2921 {
2922         xfs_ifork_t     *ifp = (state & BMAP_ATTRFORK) ? ip->i_afp : &ip->i_df;
2923         xfs_extnum_t    i;              /* extent record index */
2924
2925         trace_xfs_iext_insert(ip, idx, new, state, _RET_IP_);
2926
2927         ASSERT(ifp->if_flags & XFS_IFEXTENTS);
2928         xfs_iext_add(ifp, idx, count);
2929         for (i = idx; i < idx + count; i++, new++)
2930                 xfs_bmbt_set_all(xfs_iext_get_ext(ifp, i), new);
2931 }
2932
2933 /*
2934  * This is called when the amount of space required for incore file
2935  * extents needs to be increased. The ext_diff parameter stores the
2936  * number of new extents being added and the idx parameter contains
2937  * the extent index where the new extents will be added. If the new
2938  * extents are being appended, then we just need to (re)allocate and
2939  * initialize the space. Otherwise, if the new extents are being
2940  * inserted into the middle of the existing entries, a bit more work
2941  * is required to make room for the new extents to be inserted. The
2942  * caller is responsible for filling in the new extent entries upon
2943  * return.
2944  */
2945 void
2946 xfs_iext_add(
2947         xfs_ifork_t     *ifp,           /* inode fork pointer */
2948         xfs_extnum_t    idx,            /* index to begin adding exts */
2949         int             ext_diff)       /* number of extents to add */
2950 {
2951         int             byte_diff;      /* new bytes being added */
2952         int             new_size;       /* size of extents after adding */
2953         xfs_extnum_t    nextents;       /* number of extents in file */
2954
2955         nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
2956         ASSERT((idx >= 0) && (idx <= nextents));
2957         byte_diff = ext_diff * sizeof(xfs_bmbt_rec_t);
2958         new_size = ifp->if_bytes + byte_diff;
2959         /*
2960          * If the new number of extents (nextents + ext_diff)
2961          * fits inside the inode, then continue to use the inline
2962          * extent buffer.
2963          */
2964         if (nextents + ext_diff <= XFS_INLINE_EXTS) {
2965                 if (idx < nextents) {
2966                         memmove(&ifp->if_u2.if_inline_ext[idx + ext_diff],
2967                                 &ifp->if_u2.if_inline_ext[idx],
2968                                 (nextents - idx) * sizeof(xfs_bmbt_rec_t));
2969                         memset(&ifp->if_u2.if_inline_ext[idx], 0, byte_diff);
2970                 }
2971                 ifp->if_u1.if_extents = ifp->if_u2.if_inline_ext;
2972                 ifp->if_real_bytes = 0;
2973         }
2974         /*
2975          * Otherwise use a linear (direct) extent list.
2976          * If the extents are currently inside the inode,
2977          * xfs_iext_realloc_direct will switch us from
2978          * inline to direct extent allocation mode.
2979          */
2980         else if (nextents + ext_diff <= XFS_LINEAR_EXTS) {
2981                 xfs_iext_realloc_direct(ifp, new_size);
2982                 if (idx < nextents) {
2983                         memmove(&ifp->if_u1.if_extents[idx + ext_diff],
2984                                 &ifp->if_u1.if_extents[idx],
2985                                 (nextents - idx) * sizeof(xfs_bmbt_rec_t));
2986                         memset(&ifp->if_u1.if_extents[idx], 0, byte_diff);
2987                 }
2988         }
2989         /* Indirection array */
2990         else {
2991                 xfs_ext_irec_t  *erp;
2992                 int             erp_idx = 0;
2993                 int             page_idx = idx;
2994
2995                 ASSERT(nextents + ext_diff > XFS_LINEAR_EXTS);
2996                 if (ifp->if_flags & XFS_IFEXTIREC) {
2997                         erp = xfs_iext_idx_to_irec(ifp, &page_idx, &erp_idx, 1);
2998                 } else {
2999                         xfs_iext_irec_init(ifp);
3000                         ASSERT(ifp->if_flags & XFS_IFEXTIREC);
3001                         erp = ifp->if_u1.if_ext_irec;
3002                 }
3003                 /* Extents fit in target extent page */
3004                 if (erp && erp->er_extcount + ext_diff <= XFS_LINEAR_EXTS) {
3005                         if (page_idx < erp->er_extcount) {
3006                                 memmove(&erp->er_extbuf[page_idx + ext_diff],
3007                                         &erp->er_extbuf[page_idx],
3008                                         (erp->er_extcount - page_idx) *
3009                                         sizeof(xfs_bmbt_rec_t));
3010                                 memset(&erp->er_extbuf[page_idx], 0, byte_diff);
3011                         }
3012                         erp->er_extcount += ext_diff;
3013                         xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, ext_diff);
3014                 }
3015                 /* Insert a new extent page */
3016                 else if (erp) {
3017                         xfs_iext_add_indirect_multi(ifp,
3018                                 erp_idx, page_idx, ext_diff);
3019                 }
3020                 /*
3021                  * If extent(s) are being appended to the last page in
3022                  * the indirection array and the new extent(s) don't fit
3023                  * in the page, then erp is NULL and erp_idx is set to
3024                  * the next index needed in the indirection array.
3025                  */
3026                 else {
3027                         int     count = ext_diff;
3028
3029                         while (count) {
3030                                 erp = xfs_iext_irec_new(ifp, erp_idx);
3031                                 erp->er_extcount = count;
3032                                 count -= MIN(count, (int)XFS_LINEAR_EXTS);
3033                                 if (count) {
3034                                         erp_idx++;
3035                                 }
3036                         }
3037                 }
3038         }
3039         ifp->if_bytes = new_size;
3040 }
3041
3042 /*
3043  * This is called when incore extents are being added to the indirection
3044  * array and the new extents do not fit in the target extent list. The
3045  * erp_idx parameter contains the irec index for the target extent list
3046  * in the indirection array, and the idx parameter contains the extent
3047  * index within the list. The number of extents being added is stored
3048  * in the count parameter.
3049  *
3050  *    |-------|   |-------|
3051  *    |       |   |       |    idx - number of extents before idx
3052  *    |  idx  |   | count |
3053  *    |       |   |       |    count - number of extents being inserted at idx
3054  *    |-------|   |-------|
3055  *    | count |   | nex2  |    nex2 - number of extents after idx + count
3056  *    |-------|   |-------|
3057  */
3058 void
3059 xfs_iext_add_indirect_multi(
3060         xfs_ifork_t     *ifp,                   /* inode fork pointer */
3061         int             erp_idx,                /* target extent irec index */
3062         xfs_extnum_t    idx,                    /* index within target list */
3063         int             count)                  /* new extents being added */
3064 {
3065         int             byte_diff;              /* new bytes being added */
3066         xfs_ext_irec_t  *erp;                   /* pointer to irec entry */
3067         xfs_extnum_t    ext_diff;               /* number of extents to add */
3068         xfs_extnum_t    ext_cnt;                /* new extents still needed */
3069         xfs_extnum_t    nex2;                   /* extents after idx + count */
3070         xfs_bmbt_rec_t  *nex2_ep = NULL;        /* temp list for nex2 extents */
3071         int             nlists;                 /* number of irec's (lists) */
3072
3073         ASSERT(ifp->if_flags & XFS_IFEXTIREC);
3074         erp = &ifp->if_u1.if_ext_irec[erp_idx];
3075         nex2 = erp->er_extcount - idx;
3076         nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
3077
3078         /*
3079          * Save second part of target extent list
3080          * (all extents past */
3081         if (nex2) {
3082                 byte_diff = nex2 * sizeof(xfs_bmbt_rec_t);
3083                 nex2_ep = (xfs_bmbt_rec_t *) kmem_alloc(byte_diff, KM_NOFS);
3084                 memmove(nex2_ep, &erp->er_extbuf[idx], byte_diff);
3085                 erp->er_extcount -= nex2;
3086                 xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, -nex2);
3087                 memset(&erp->er_extbuf[idx], 0, byte_diff);
3088         }
3089
3090         /*
3091          * Add the new extents to the end of the target
3092          * list, then allocate new irec record(s) and
3093          * extent buffer(s) as needed to store the rest
3094          * of the new extents.
3095          */
3096         ext_cnt = count;
3097         ext_diff = MIN(ext_cnt, (int)XFS_LINEAR_EXTS - erp->er_extcount);
3098         if (ext_diff) {
3099                 erp->er_extcount += ext_diff;
3100                 xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, ext_diff);
3101                 ext_cnt -= ext_diff;
3102         }
3103         while (ext_cnt) {
3104                 erp_idx++;
3105                 erp = xfs_iext_irec_new(ifp, erp_idx);
3106                 ext_diff = MIN(ext_cnt, (int)XFS_LINEAR_EXTS);
3107                 erp->er_extcount = ext_diff;
3108                 xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, ext_diff);
3109                 ext_cnt -= ext_diff;
3110         }
3111
3112         /* Add nex2 extents back to indirection array */
3113         if (nex2) {
3114                 xfs_extnum_t    ext_avail;
3115                 int             i;
3116
3117                 byte_diff = nex2 * sizeof(xfs_bmbt_rec_t);
3118                 ext_avail = XFS_LINEAR_EXTS - erp->er_extcount;
3119                 i = 0;
3120                 /*
3121                  * If nex2 extents fit in the current page, append
3122                  * nex2_ep after the new extents.
3123                  */
3124                 if (nex2 <= ext_avail) {
3125                         i = erp->er_extcount;
3126                 }
3127                 /*
3128                  * Otherwise, check if space is available in the
3129                  * next page.
3130                  */
3131                 else if ((erp_idx < nlists - 1) &&
3132                          (nex2 <= (ext_avail = XFS_LINEAR_EXTS -
3133                           ifp->if_u1.if_ext_irec[erp_idx+1].er_extcount))) {
3134                         erp_idx++;
3135                         erp++;
3136                         /* Create a hole for nex2 extents */
3137                         memmove(&erp->er_extbuf[nex2], erp->er_extbuf,
3138                                 erp->er_extcount * sizeof(xfs_bmbt_rec_t));
3139                 }
3140                 /*
3141                  * Final choice, create a new extent page for
3142                  * nex2 extents.
3143                  */
3144                 else {
3145                         erp_idx++;
3146                         erp = xfs_iext_irec_new(ifp, erp_idx);
3147                 }
3148                 memmove(&erp->er_extbuf[i], nex2_ep, byte_diff);
3149                 kmem_free(nex2_ep);
3150                 erp->er_extcount += nex2;
3151                 xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, nex2);
3152         }
3153 }
3154
3155 /*
3156  * This is called when the amount of space required for incore file
3157  * extents needs to be decreased. The ext_diff parameter stores the
3158  * number of extents to be removed and the idx parameter contains
3159  * the extent index where the extents will be removed from.
3160  *
3161  * If the amount of space needed has decreased below the linear
3162  * limit, XFS_IEXT_BUFSZ, then switch to using the contiguous
3163  * extent array.  Otherwise, use kmem_realloc() to adjust the
3164  * size to what is needed.
3165  */
3166 void
3167 xfs_iext_remove(
3168         xfs_inode_t     *ip,            /* incore inode pointer */
3169         xfs_extnum_t    idx,            /* index to begin removing exts */
3170         int             ext_diff,       /* number of extents to remove */
3171         int             state)          /* type of extent conversion */
3172 {
3173         xfs_ifork_t     *ifp = (state & BMAP_ATTRFORK) ? ip->i_afp : &ip->i_df;
3174         xfs_extnum_t    nextents;       /* number of extents in file */
3175         int             new_size;       /* size of extents after removal */
3176
3177         trace_xfs_iext_remove(ip, idx, state, _RET_IP_);
3178
3179         ASSERT(ext_diff > 0);
3180         nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
3181         new_size = (nextents - ext_diff) * sizeof(xfs_bmbt_rec_t);
3182
3183         if (new_size == 0) {
3184                 xfs_iext_destroy(ifp);
3185         } else if (ifp->if_flags & XFS_IFEXTIREC) {
3186                 xfs_iext_remove_indirect(ifp, idx, ext_diff);
3187         } else if (ifp->if_real_bytes) {
3188                 xfs_iext_remove_direct(ifp, idx, ext_diff);
3189         } else {
3190                 xfs_iext_remove_inline(ifp, idx, ext_diff);
3191         }
3192         ifp->if_bytes = new_size;
3193 }
3194
3195 /*
3196  * This removes ext_diff extents from the inline buffer, beginning
3197  * at extent index idx.
3198  */
3199 void
3200 xfs_iext_remove_inline(
3201         xfs_ifork_t     *ifp,           /* inode fork pointer */
3202         xfs_extnum_t    idx,            /* index to begin removing exts */
3203         int             ext_diff)       /* number of extents to remove */
3204 {
3205         int             nextents;       /* number of extents in file */
3206
3207         ASSERT(!(ifp->if_flags & XFS_IFEXTIREC));
3208         ASSERT(idx < XFS_INLINE_EXTS);
3209         nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
3210         ASSERT(((nextents - ext_diff) > 0) &&
3211                 (nextents - ext_diff) < XFS_INLINE_EXTS);
3212
3213         if (idx + ext_diff < nextents) {
3214                 memmove(&ifp->if_u2.if_inline_ext[idx],
3215                         &ifp->if_u2.if_inline_ext[idx + ext_diff],
3216                         (nextents - (idx + ext_diff)) *
3217                          sizeof(xfs_bmbt_rec_t));
3218                 memset(&ifp->if_u2.if_inline_ext[nextents - ext_diff],
3219                         0, ext_diff * sizeof(xfs_bmbt_rec_t));
3220         } else {
3221                 memset(&ifp->if_u2.if_inline_ext[idx], 0,
3222                         ext_diff * sizeof(xfs_bmbt_rec_t));
3223         }
3224 }
3225
3226 /*
3227  * This removes ext_diff extents from a linear (direct) extent list,
3228  * beginning at extent index idx. If the extents are being removed
3229  * from the end of the list (ie. truncate) then we just need to re-
3230  * allocate the list to remove the extra space. Otherwise, if the
3231  * extents are being removed from the middle of the existing extent
3232  * entries, then we first need to move the extent records beginning
3233  * at idx + ext_diff up in the list to overwrite the records being
3234  * removed, then remove the extra space via kmem_realloc.
3235  */
3236 void
3237 xfs_iext_remove_direct(
3238         xfs_ifork_t     *ifp,           /* inode fork pointer */
3239         xfs_extnum_t    idx,            /* index to begin removing exts */
3240         int             ext_diff)       /* number of extents to remove */
3241 {
3242         xfs_extnum_t    nextents;       /* number of extents in file */
3243         int             new_size;       /* size of extents after removal */
3244
3245         ASSERT(!(ifp->if_flags & XFS_IFEXTIREC));
3246         new_size = ifp->if_bytes -
3247                 (ext_diff * sizeof(xfs_bmbt_rec_t));
3248         nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
3249
3250         if (new_size == 0) {
3251                 xfs_iext_destroy(ifp);
3252                 return;
3253         }
3254         /* Move extents up in the list (if needed) */
3255         if (idx + ext_diff < nextents) {
3256                 memmove(&ifp->if_u1.if_extents[idx],
3257                         &ifp->if_u1.if_extents[idx + ext_diff],
3258                         (nextents - (idx + ext_diff)) *
3259                          sizeof(xfs_bmbt_rec_t));
3260         }
3261         memset(&ifp->if_u1.if_extents[nextents - ext_diff],
3262                 0, ext_diff * sizeof(xfs_bmbt_rec_t));
3263         /*
3264          * Reallocate the direct extent list. If the extents
3265          * will fit inside the inode then xfs_iext_realloc_direct
3266          * will switch from direct to inline extent allocation
3267          * mode for us.
3268          */
3269         xfs_iext_realloc_direct(ifp, new_size);
3270         ifp->if_bytes = new_size;
3271 }
3272
3273 /*
3274  * This is called when incore extents are being removed from the
3275  * indirection array and the extents being removed span multiple extent
3276  * buffers. The idx parameter contains the file extent index where we
3277  * want to begin removing extents, and the count parameter contains
3278  * how many extents need to be removed.
3279  *
3280  *    |-------|   |-------|
3281  *    | nex1  |   |       |    nex1 - number of extents before idx
3282  *    |-------|   | count |
3283  *    |       |   |       |    count - number of extents being removed at idx
3284  *    | count |   |-------|
3285  *    |       |   | nex2  |    nex2 - number of extents after idx + count
3286  *    |-------|   |-------|
3287  */
3288 void
3289 xfs_iext_remove_indirect(
3290         xfs_ifork_t     *ifp,           /* inode fork pointer */
3291         xfs_extnum_t    idx,            /* index to begin removing extents */
3292         int             count)          /* number of extents to remove */
3293 {
3294         xfs_ext_irec_t  *erp;           /* indirection array pointer */
3295         int             erp_idx = 0;    /* indirection array index */
3296         xfs_extnum_t    ext_cnt;        /* extents left to remove */
3297         xfs_extnum_t    ext_diff;       /* extents to remove in current list */
3298         xfs_extnum_t    nex1;           /* number of extents before idx */
3299         xfs_extnum_t    nex2;           /* extents after idx + count */
3300         int             page_idx = idx; /* index in target extent list */
3301
3302         ASSERT(ifp->if_flags & XFS_IFEXTIREC);
3303         erp = xfs_iext_idx_to_irec(ifp,  &page_idx, &erp_idx, 0);
3304         ASSERT(erp != NULL);
3305         nex1 = page_idx;
3306         ext_cnt = count;
3307         while (ext_cnt) {
3308                 nex2 = MAX((erp->er_extcount - (nex1 + ext_cnt)), 0);
3309                 ext_diff = MIN(ext_cnt, (erp->er_extcount - nex1));
3310                 /*
3311                  * Check for deletion of entire list;
3312                  * xfs_iext_irec_remove() updates extent offsets.
3313                  */
3314                 if (ext_diff == erp->er_extcount) {
3315                         xfs_iext_irec_remove(ifp, erp_idx);
3316                         ext_cnt -= ext_diff;
3317                         nex1 = 0;
3318                         if (ext_cnt) {
3319                                 ASSERT(erp_idx < ifp->if_real_bytes /
3320                                         XFS_IEXT_BUFSZ);
3321                                 erp = &ifp->if_u1.if_ext_irec[erp_idx];
3322                                 nex1 = 0;
3323                                 continue;
3324                         } else {
3325                                 break;
3326                         }
3327                 }
3328                 /* Move extents up (if needed) */
3329                 if (nex2) {
3330                         memmove(&erp->er_extbuf[nex1],
3331                                 &erp->er_extbuf[nex1 + ext_diff],
3332                                 nex2 * sizeof(xfs_bmbt_rec_t));
3333                 }
3334                 /* Zero out rest of page */
3335                 memset(&erp->er_extbuf[nex1 + nex2], 0, (XFS_IEXT_BUFSZ -
3336                         ((nex1 + nex2) * sizeof(xfs_bmbt_rec_t))));
3337                 /* Update remaining counters */
3338                 erp->er_extcount -= ext_diff;
3339                 xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, -ext_diff);
3340                 ext_cnt -= ext_diff;
3341                 nex1 = 0;
3342                 erp_idx++;
3343                 erp++;
3344         }
3345         ifp->if_bytes -= count * sizeof(xfs_bmbt_rec_t);
3346         xfs_iext_irec_compact(ifp);
3347 }
3348
3349 /*
3350  * Create, destroy, or resize a linear (direct) block of extents.
3351  */
3352 void
3353 xfs_iext_realloc_direct(
3354         xfs_ifork_t     *ifp,           /* inode fork pointer */
3355         int             new_size)       /* new size of extents */
3356 {
3357         int             rnew_size;      /* real new size of extents */
3358
3359         rnew_size = new_size;
3360
3361         ASSERT(!(ifp->if_flags & XFS_IFEXTIREC) ||
3362                 ((new_size >= 0) && (new_size <= XFS_IEXT_BUFSZ) &&
3363                  (new_size != ifp->if_real_bytes)));
3364
3365         /* Free extent records */
3366         if (new_size == 0) {
3367                 xfs_iext_destroy(ifp);
3368         }
3369         /* Resize direct extent list and zero any new bytes */
3370         else if (ifp->if_real_bytes) {
3371                 /* Check if extents will fit inside the inode */
3372                 if (new_size <= XFS_INLINE_EXTS * sizeof(xfs_bmbt_rec_t)) {
3373                         xfs_iext_direct_to_inline(ifp, new_size /
3374                                 (uint)sizeof(xfs_bmbt_rec_t));
3375                         ifp->if_bytes = new_size;
3376                         return;
3377                 }
3378                 if (!is_power_of_2(new_size)){
3379                         rnew_size = roundup_pow_of_two(new_size);
3380                 }
3381                 if (rnew_size != ifp->if_real_bytes) {
3382                         ifp->if_u1.if_extents =
3383                                 kmem_realloc(ifp->if_u1.if_extents,
3384                                                 rnew_size,
3385                                                 ifp->if_real_bytes, KM_NOFS);
3386                 }
3387                 if (rnew_size > ifp->if_real_bytes) {
3388                         memset(&ifp->if_u1.if_extents[ifp->if_bytes /
3389                                 (uint)sizeof(xfs_bmbt_rec_t)], 0,
3390                                 rnew_size - ifp->if_real_bytes);
3391                 }
3392         }
3393         /*
3394          * Switch from the inline extent buffer to a direct
3395          * extent list. Be sure to include the inline extent
3396          * bytes in new_size.
3397          */
3398         else {
3399                 new_size += ifp->if_bytes;
3400                 if (!is_power_of_2(new_size)) {
3401                         rnew_size = roundup_pow_of_two(new_size);
3402                 }
3403                 xfs_iext_inline_to_direct(ifp, rnew_size);
3404         }
3405         ifp->if_real_bytes = rnew_size;
3406         ifp->if_bytes = new_size;
3407 }
3408
3409 /*
3410  * Switch from linear (direct) extent records to inline buffer.
3411  */
3412 void
3413 xfs_iext_direct_to_inline(
3414         xfs_ifork_t     *ifp,           /* inode fork pointer */
3415         xfs_extnum_t    nextents)       /* number of extents in file */
3416 {
3417         ASSERT(ifp->if_flags & XFS_IFEXTENTS);
3418         ASSERT(nextents <= XFS_INLINE_EXTS);
3419         /*
3420          * The inline buffer was zeroed when we switched
3421          * from inline to direct extent allocation mode,
3422          * so we don't need to clear it here.
3423          */
3424         memcpy(ifp->if_u2.if_inline_ext, ifp->if_u1.if_extents,
3425                 nextents * sizeof(xfs_bmbt_rec_t));
3426         kmem_free(ifp->if_u1.if_extents);
3427         ifp->if_u1.if_extents = ifp->if_u2.if_inline_ext;
3428         ifp->if_real_bytes = 0;
3429 }
3430
3431 /*
3432  * Switch from inline buffer to linear (direct) extent records.
3433  * new_size should already be rounded up to the next power of 2
3434  * by the caller (when appropriate), so use new_size as it is.
3435  * However, since new_size may be rounded up, we can't update
3436  * if_bytes here. It is the caller's responsibility to update
3437  * if_bytes upon return.
3438  */
3439 void
3440 xfs_iext_inline_to_direct(
3441         xfs_ifork_t     *ifp,           /* inode fork pointer */
3442         int             new_size)       /* number of extents in file */
3443 {
3444         ifp->if_u1.if_extents = kmem_alloc(new_size, KM_NOFS);
3445         memset(ifp->if_u1.if_extents, 0, new_size);
3446         if (ifp->if_bytes) {
3447                 memcpy(ifp->if_u1.if_extents, ifp->if_u2.if_inline_ext,
3448                         ifp->if_bytes);
3449                 memset(ifp->if_u2.if_inline_ext, 0, XFS_INLINE_EXTS *
3450                         sizeof(xfs_bmbt_rec_t));
3451         }
3452         ifp->if_real_bytes = new_size;
3453 }
3454
3455 /*
3456  * Resize an extent indirection array to new_size bytes.
3457  */
3458 STATIC void
3459 xfs_iext_realloc_indirect(
3460         xfs_ifork_t     *ifp,           /* inode fork pointer */
3461         int             new_size)       /* new indirection array size */
3462 {
3463         int             nlists;         /* number of irec's (ex lists) */
3464         int             size;           /* current indirection array size */
3465
3466         ASSERT(ifp->if_flags & XFS_IFEXTIREC);
3467         nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
3468         size = nlists * sizeof(xfs_ext_irec_t);
3469         ASSERT(ifp->if_real_bytes);
3470         ASSERT((new_size >= 0) && (new_size != size));
3471         if (new_size == 0) {
3472                 xfs_iext_destroy(ifp);
3473         } else {
3474                 ifp->if_u1.if_ext_irec = (xfs_ext_irec_t *)
3475                         kmem_realloc(ifp->if_u1.if_ext_irec,
3476                                 new_size, size, KM_NOFS);
3477         }
3478 }
3479
3480 /*
3481  * Switch from indirection array to linear (direct) extent allocations.
3482  */
3483 STATIC void
3484 xfs_iext_indirect_to_direct(
3485          xfs_ifork_t    *ifp)           /* inode fork pointer */
3486 {
3487         xfs_bmbt_rec_host_t *ep;        /* extent record pointer */
3488         xfs_extnum_t    nextents;       /* number of extents in file */
3489         int             size;           /* size of file extents */
3490
3491         ASSERT(ifp->if_flags & XFS_IFEXTIREC);
3492         nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
3493         ASSERT(nextents <= XFS_LINEAR_EXTS);
3494         size = nextents * sizeof(xfs_bmbt_rec_t);
3495
3496         xfs_iext_irec_compact_pages(ifp);
3497         ASSERT(ifp->if_real_bytes == XFS_IEXT_BUFSZ);
3498
3499         ep = ifp->if_u1.if_ext_irec->er_extbuf;
3500         kmem_free(ifp->if_u1.if_ext_irec);
3501         ifp->if_flags &= ~XFS_IFEXTIREC;
3502         ifp->if_u1.if_extents = ep;
3503         ifp->if_bytes = size;
3504         if (nextents < XFS_LINEAR_EXTS) {
3505                 xfs_iext_realloc_direct(ifp, size);
3506         }
3507 }
3508
3509 /*
3510  * Free incore file extents.
3511  */
3512 void
3513 xfs_iext_destroy(
3514         xfs_ifork_t     *ifp)           /* inode fork pointer */
3515 {
3516         if (ifp->if_flags & XFS_IFEXTIREC) {
3517                 int     erp_idx;
3518                 int     nlists;
3519
3520                 nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
3521                 for (erp_idx = nlists - 1; erp_idx >= 0 ; erp_idx--) {
3522                         xfs_iext_irec_remove(ifp, erp_idx);
3523                 }
3524                 ifp->if_flags &= ~XFS_IFEXTIREC;
3525         } else if (ifp->if_real_bytes) {
3526                 kmem_free(ifp->if_u1.if_extents);
3527         } else if (ifp->if_bytes) {
3528                 memset(ifp->if_u2.if_inline_ext, 0, XFS_INLINE_EXTS *
3529                         sizeof(xfs_bmbt_rec_t));
3530         }
3531         ifp->if_u1.if_extents = NULL;
3532         ifp->if_real_bytes = 0;
3533         ifp->if_bytes = 0;
3534 }
3535
3536 /*
3537  * Return a pointer to the extent record for file system block bno.
3538  */
3539 xfs_bmbt_rec_host_t *                   /* pointer to found extent record */
3540 xfs_iext_bno_to_ext(
3541         xfs_ifork_t     *ifp,           /* inode fork pointer */
3542         xfs_fileoff_t   bno,            /* block number to search for */
3543         xfs_extnum_t    *idxp)          /* index of target extent */
3544 {
3545         xfs_bmbt_rec_host_t *base;      /* pointer to first extent */
3546         xfs_filblks_t   blockcount = 0; /* number of blocks in extent */
3547         xfs_bmbt_rec_host_t *ep = NULL; /* pointer to target extent */
3548         xfs_ext_irec_t  *erp = NULL;    /* indirection array pointer */
3549         int             high;           /* upper boundary in search */
3550         xfs_extnum_t    idx = 0;        /* index of target extent */
3551         int             low;            /* lower boundary in search */
3552         xfs_extnum_t    nextents;       /* number of file extents */
3553         xfs_fileoff_t   startoff = 0;   /* start offset of extent */
3554
3555         nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
3556         if (nextents == 0) {
3557                 *idxp = 0;
3558                 return NULL;
3559         }
3560         low = 0;
3561         if (ifp->if_flags & XFS_IFEXTIREC) {
3562                 /* Find target extent list */
3563                 int     erp_idx = 0;
3564                 erp = xfs_iext_bno_to_irec(ifp, bno, &erp_idx);
3565                 base = erp->er_extbuf;
3566                 high = erp->er_extcount - 1;
3567         } else {
3568                 base = ifp->if_u1.if_extents;
3569                 high = nextents - 1;
3570         }
3571         /* Binary search extent records */
3572         while (low <= high) {
3573                 idx = (low + high) >> 1;
3574                 ep = base + idx;
3575                 startoff = xfs_bmbt_get_startoff(ep);
3576                 blockcount = xfs_bmbt_get_blockcount(ep);
3577                 if (bno < startoff) {
3578                         high = idx - 1;
3579                 } else if (bno >= startoff + blockcount) {
3580                         low = idx + 1;
3581                 } else {
3582                         /* Convert back to file-based extent index */
3583                         if (ifp->if_flags & XFS_IFEXTIREC) {
3584                                 idx += erp->er_extoff;
3585                         }
3586                         *idxp = idx;
3587                         return ep;
3588                 }
3589         }
3590         /* Convert back to file-based extent index */
3591         if (ifp->if_flags & XFS_IFEXTIREC) {
3592                 idx += erp->er_extoff;
3593         }
3594         if (bno >= startoff + blockcount) {
3595                 if (++idx == nextents) {
3596                         ep = NULL;
3597                 } else {
3598                         ep = xfs_iext_get_ext(ifp, idx);
3599                 }
3600         }
3601         *idxp = idx;
3602         return ep;
3603 }
3604
3605 /*
3606  * Return a pointer to the indirection array entry containing the
3607  * extent record for filesystem block bno. Store the index of the
3608  * target irec in *erp_idxp.
3609  */
3610 xfs_ext_irec_t *                        /* pointer to found extent record */
3611 xfs_iext_bno_to_irec(
3612         xfs_ifork_t     *ifp,           /* inode fork pointer */
3613         xfs_fileoff_t   bno,            /* block number to search for */
3614         int             *erp_idxp)      /* irec index of target ext list */
3615 {
3616         xfs_ext_irec_t  *erp = NULL;    /* indirection array pointer */
3617         xfs_ext_irec_t  *erp_next;      /* next indirection array entry */
3618         int             erp_idx;        /* indirection array index */
3619         int             nlists;         /* number of extent irec's (lists) */
3620         int             high;           /* binary search upper limit */
3621         int             low;            /* binary search lower limit */
3622
3623         ASSERT(ifp->if_flags & XFS_IFEXTIREC);
3624         nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
3625         erp_idx = 0;
3626         low = 0;
3627         high = nlists - 1;
3628         while (low <= high) {
3629                 erp_idx = (low + high) >> 1;
3630                 erp = &ifp->if_u1.if_ext_irec[erp_idx];
3631                 erp_next = erp_idx < nlists - 1 ? erp + 1 : NULL;
3632                 if (bno < xfs_bmbt_get_startoff(erp->er_extbuf)) {
3633                         high = erp_idx - 1;
3634                 } else if (erp_next && bno >=
3635                            xfs_bmbt_get_startoff(erp_next->er_extbuf)) {
3636                         low = erp_idx + 1;
3637                 } else {
3638                         break;
3639                 }
3640         }
3641         *erp_idxp = erp_idx;
3642         return erp;
3643 }
3644
3645 /*
3646  * Return a pointer to the indirection array entry containing the
3647  * extent record at file extent index *idxp. Store the index of the
3648  * target irec in *erp_idxp and store the page index of the target
3649  * extent record in *idxp.
3650  */
3651 xfs_ext_irec_t *
3652 xfs_iext_idx_to_irec(
3653         xfs_ifork_t     *ifp,           /* inode fork pointer */
3654         xfs_extnum_t    *idxp,          /* extent index (file -> page) */
3655         int             *erp_idxp,      /* pointer to target irec */
3656         int             realloc)        /* new bytes were just added */
3657 {
3658         xfs_ext_irec_t  *prev;          /* pointer to previous irec */
3659         xfs_ext_irec_t  *erp = NULL;    /* pointer to current irec */
3660         int             erp_idx;        /* indirection array index */
3661         int             nlists;         /* number of irec's (ex lists) */
3662         int             high;           /* binary search upper limit */
3663         int             low;            /* binary search lower limit */
3664         xfs_extnum_t    page_idx = *idxp; /* extent index in target list */
3665
3666         ASSERT(ifp->if_flags & XFS_IFEXTIREC);
3667         ASSERT(page_idx >= 0);
3668         ASSERT(page_idx <= ifp->if_bytes / sizeof(xfs_bmbt_rec_t));
3669         ASSERT(page_idx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t) || realloc);
3670
3671         nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
3672         erp_idx = 0;
3673         low = 0;
3674         high = nlists - 1;
3675
3676         /* Binary search extent irec's */
3677         while (low <= high) {
3678                 erp_idx = (low + high) >> 1;
3679                 erp = &ifp->if_u1.if_ext_irec[erp_idx];
3680                 prev = erp_idx > 0 ? erp - 1 : NULL;
3681                 if (page_idx < erp->er_extoff || (page_idx == erp->er_extoff &&
3682                      realloc && prev && prev->er_extcount < XFS_LINEAR_EXTS)) {
3683                         high = erp_idx - 1;
3684                 } else if (page_idx > erp->er_extoff + erp->er_extcount ||
3685                            (page_idx == erp->er_extoff + erp->er_extcount &&
3686                             !realloc)) {
3687                         low = erp_idx + 1;
3688                 } else if (page_idx == erp->er_extoff + erp->er_extcount &&
3689                            erp->er_extcount == XFS_LINEAR_EXTS) {
3690                         ASSERT(realloc);
3691                         page_idx = 0;
3692                         erp_idx++;
3693                         erp = erp_idx < nlists ? erp + 1 : NULL;
3694                         break;
3695                 } else {
3696                         page_idx -= erp->er_extoff;
3697                         break;
3698                 }
3699         }
3700         *idxp = page_idx;
3701         *erp_idxp = erp_idx;
3702         return(erp);
3703 }
3704
3705 /*
3706  * Allocate and initialize an indirection array once the space needed
3707  * for incore extents increases above XFS_IEXT_BUFSZ.
3708  */
3709 void
3710 xfs_iext_irec_init(
3711         xfs_ifork_t     *ifp)           /* inode fork pointer */
3712 {
3713         xfs_ext_irec_t  *erp;           /* indirection array pointer */
3714         xfs_extnum_t    nextents;       /* number of extents in file */
3715
3716         ASSERT(!(ifp->if_flags & XFS_IFEXTIREC));
3717         nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
3718         ASSERT(nextents <= XFS_LINEAR_EXTS);
3719
3720         erp = kmem_alloc(sizeof(xfs_ext_irec_t), KM_NOFS);
3721
3722         if (nextents == 0) {
3723                 ifp->if_u1.if_extents = kmem_alloc(XFS_IEXT_BUFSZ, KM_NOFS);
3724         } else if (!ifp->if_real_bytes) {
3725                 xfs_iext_inline_to_direct(ifp, XFS_IEXT_BUFSZ);
3726         } else if (ifp->if_real_bytes < XFS_IEXT_BUFSZ) {
3727                 xfs_iext_realloc_direct(ifp, XFS_IEXT_BUFSZ);
3728         }
3729         erp->er_extbuf = ifp->if_u1.if_extents;
3730         erp->er_extcount = nextents;
3731         erp->er_extoff = 0;
3732
3733         ifp->if_flags |= XFS_IFEXTIREC;
3734         ifp->if_real_bytes = XFS_IEXT_BUFSZ;
3735         ifp->if_bytes = nextents * sizeof(xfs_bmbt_rec_t);
3736         ifp->if_u1.if_ext_irec = erp;
3737
3738         return;
3739 }
3740
3741 /*
3742  * Allocate and initialize a new entry in the indirection array.
3743  */
3744 xfs_ext_irec_t *
3745 xfs_iext_irec_new(
3746         xfs_ifork_t     *ifp,           /* inode fork pointer */
3747         int             erp_idx)        /* index for new irec */
3748 {
3749         xfs_ext_irec_t  *erp;           /* indirection array pointer */
3750         int             i;              /* loop counter */
3751         int             nlists;         /* number of irec's (ex lists) */
3752
3753         ASSERT(ifp->if_flags & XFS_IFEXTIREC);
3754         nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
3755
3756         /* Resize indirection array */
3757         xfs_iext_realloc_indirect(ifp, ++nlists *
3758                                   sizeof(xfs_ext_irec_t));
3759         /*
3760          * Move records down in the array so the
3761          * new page can use erp_idx.
3762          */
3763         erp = ifp->if_u1.if_ext_irec;
3764         for (i = nlists - 1; i > erp_idx; i--) {
3765                 memmove(&erp[i], &erp[i-1], sizeof(xfs_ext_irec_t));
3766         }
3767         ASSERT(i == erp_idx);
3768
3769         /* Initialize new extent record */
3770         erp = ifp->if_u1.if_ext_irec;
3771         erp[erp_idx].er_extbuf = kmem_alloc(XFS_IEXT_BUFSZ, KM_NOFS);
3772         ifp->if_real_bytes = nlists * XFS_IEXT_BUFSZ;
3773         memset(erp[erp_idx].er_extbuf, 0, XFS_IEXT_BUFSZ);
3774         erp[erp_idx].er_extcount = 0;
3775         erp[erp_idx].er_extoff = erp_idx > 0 ?
3776                 erp[erp_idx-1].er_extoff + erp[erp_idx-1].er_extcount : 0;
3777         return (&erp[erp_idx]);
3778 }
3779
3780 /*
3781  * Remove a record from the indirection array.
3782  */
3783 void
3784 xfs_iext_irec_remove(
3785         xfs_ifork_t     *ifp,           /* inode fork pointer */
3786         int             erp_idx)        /* irec index to remove */
3787 {
3788         xfs_ext_irec_t  *erp;           /* indirection array pointer */
3789         int             i;              /* loop counter */
3790         int             nlists;         /* number of irec's (ex lists) */
3791
3792         ASSERT(ifp->if_flags & XFS_IFEXTIREC);
3793         nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
3794         erp = &ifp->if_u1.if_ext_irec[erp_idx];
3795         if (erp->er_extbuf) {
3796                 xfs_iext_irec_update_extoffs(ifp, erp_idx + 1,
3797                         -erp->er_extcount);
3798                 kmem_free(erp->er_extbuf);
3799         }
3800         /* Compact extent records */
3801         erp = ifp->if_u1.if_ext_irec;
3802         for (i = erp_idx; i < nlists - 1; i++) {
3803                 memmove(&erp[i], &erp[i+1], sizeof(xfs_ext_irec_t));
3804         }
3805         /*
3806          * Manually free the last extent record from the indirection
3807          * array.  A call to xfs_iext_realloc_indirect() with a size
3808          * of zero would result in a call to xfs_iext_destroy() which
3809          * would in turn call this function again, creating a nasty
3810          * infinite loop.
3811          */
3812         if (--nlists) {
3813                 xfs_iext_realloc_indirect(ifp,
3814                         nlists * sizeof(xfs_ext_irec_t));
3815         } else {
3816                 kmem_free(ifp->if_u1.if_ext_irec);
3817         }
3818         ifp->if_real_bytes = nlists * XFS_IEXT_BUFSZ;
3819 }
3820
3821 /*
3822  * This is called to clean up large amounts of unused memory allocated
3823  * by the indirection array.  Before compacting anything though, verify
3824  * that the indirection array is still needed and switch back to the
3825  * linear extent list (or even the inline buffer) if possible.  The
3826  * compaction policy is as follows:
3827  *
3828  *    Full Compaction: Extents fit into a single page (or inline buffer)
3829  * Partial Compaction: Extents occupy less than 50% of allocated space
3830  *      No Compaction: Extents occupy at least 50% of allocated space
3831  */
3832 void
3833 xfs_iext_irec_compact(
3834         xfs_ifork_t     *ifp)           /* inode fork pointer */
3835 {
3836         xfs_extnum_t    nextents;       /* number of extents in file */
3837         int             nlists;         /* number of irec's (ex lists) */
3838
3839         ASSERT(ifp->if_flags & XFS_IFEXTIREC);
3840         nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
3841         nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
3842
3843         if (nextents == 0) {
3844                 xfs_iext_destroy(ifp);
3845         } else if (nextents <= XFS_INLINE_EXTS) {
3846                 xfs_iext_indirect_to_direct(ifp);
3847                 xfs_iext_direct_to_inline(ifp, nextents);
3848         } else if (nextents <= XFS_LINEAR_EXTS) {
3849                 xfs_iext_indirect_to_direct(ifp);
3850         } else if (nextents < (nlists * XFS_LINEAR_EXTS) >> 1) {
3851                 xfs_iext_irec_compact_pages(ifp);
3852         }
3853 }
3854
3855 /*
3856  * Combine extents from neighboring extent pages.
3857  */
3858 void
3859 xfs_iext_irec_compact_pages(
3860         xfs_ifork_t     *ifp)           /* inode fork pointer */
3861 {
3862         xfs_ext_irec_t  *erp, *erp_next;/* pointers to irec entries */
3863         int             erp_idx = 0;    /* indirection array index */
3864         int             nlists;         /* number of irec's (ex lists) */
3865
3866         ASSERT(ifp->if_flags & XFS_IFEXTIREC);
3867         nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
3868         while (erp_idx < nlists - 1) {
3869                 erp = &ifp->if_u1.if_ext_irec[erp_idx];
3870                 erp_next = erp + 1;
3871                 if (erp_next->er_extcount <=
3872                     (XFS_LINEAR_EXTS - erp->er_extcount)) {
3873                         memcpy(&erp->er_extbuf[erp->er_extcount],
3874                                 erp_next->er_extbuf, erp_next->er_extcount *
3875                                 sizeof(xfs_bmbt_rec_t));
3876                         erp->er_extcount += erp_next->er_extcount;
3877                         /*
3878                          * Free page before removing extent record
3879                          * so er_extoffs don't get modified in
3880                          * xfs_iext_irec_remove.
3881                          */
3882                         kmem_free(erp_next->er_extbuf);
3883                         erp_next->er_extbuf = NULL;
3884                         xfs_iext_irec_remove(ifp, erp_idx + 1);
3885                         nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
3886                 } else {
3887                         erp_idx++;
3888                 }
3889         }
3890 }
3891
3892 /*
3893  * This is called to update the er_extoff field in the indirection
3894  * array when extents have been added or removed from one of the
3895  * extent lists. erp_idx contains the irec index to begin updating
3896  * at and ext_diff contains the number of extents that were added
3897  * or removed.
3898  */
3899 void
3900 xfs_iext_irec_update_extoffs(
3901         xfs_ifork_t     *ifp,           /* inode fork pointer */
3902         int             erp_idx,        /* irec index to update */
3903         int             ext_diff)       /* number of new extents */
3904 {
3905         int             i;              /* loop counter */
3906         int             nlists;         /* number of irec's (ex lists */
3907
3908         ASSERT(ifp->if_flags & XFS_IFEXTIREC);
3909         nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ;
3910         for (i = erp_idx; i < nlists; i++) {
3911                 ifp->if_u1.if_ext_irec[i].er_extoff += ext_diff;
3912         }
3913 }