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