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