xfs: fix multi-AG deadlock in xfs_bunmapi
[sfrench/cifs-2.6.git] / fs / xfs / libxfs / xfs_bmap.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_shared.h"
21 #include "xfs_format.h"
22 #include "xfs_log_format.h"
23 #include "xfs_trans_resv.h"
24 #include "xfs_bit.h"
25 #include "xfs_sb.h"
26 #include "xfs_mount.h"
27 #include "xfs_defer.h"
28 #include "xfs_da_format.h"
29 #include "xfs_da_btree.h"
30 #include "xfs_dir2.h"
31 #include "xfs_inode.h"
32 #include "xfs_btree.h"
33 #include "xfs_trans.h"
34 #include "xfs_inode_item.h"
35 #include "xfs_extfree_item.h"
36 #include "xfs_alloc.h"
37 #include "xfs_bmap.h"
38 #include "xfs_bmap_util.h"
39 #include "xfs_bmap_btree.h"
40 #include "xfs_rtalloc.h"
41 #include "xfs_error.h"
42 #include "xfs_quota.h"
43 #include "xfs_trans_space.h"
44 #include "xfs_buf_item.h"
45 #include "xfs_trace.h"
46 #include "xfs_symlink.h"
47 #include "xfs_attr_leaf.h"
48 #include "xfs_filestream.h"
49 #include "xfs_rmap.h"
50 #include "xfs_ag_resv.h"
51 #include "xfs_refcount.h"
52 #include "xfs_rmap_btree.h"
53 #include "xfs_icache.h"
54
55
56 kmem_zone_t             *xfs_bmap_free_item_zone;
57
58 /*
59  * Miscellaneous helper functions
60  */
61
62 /*
63  * Compute and fill in the value of the maximum depth of a bmap btree
64  * in this filesystem.  Done once, during mount.
65  */
66 void
67 xfs_bmap_compute_maxlevels(
68         xfs_mount_t     *mp,            /* file system mount structure */
69         int             whichfork)      /* data or attr fork */
70 {
71         int             level;          /* btree level */
72         uint            maxblocks;      /* max blocks at this level */
73         uint            maxleafents;    /* max leaf entries possible */
74         int             maxrootrecs;    /* max records in root block */
75         int             minleafrecs;    /* min records in leaf block */
76         int             minnoderecs;    /* min records in node block */
77         int             sz;             /* root block size */
78
79         /*
80          * The maximum number of extents in a file, hence the maximum
81          * number of leaf entries, is controlled by the type of di_nextents
82          * (a signed 32-bit number, xfs_extnum_t), or by di_anextents
83          * (a signed 16-bit number, xfs_aextnum_t).
84          *
85          * Note that we can no longer assume that if we are in ATTR1 that
86          * the fork offset of all the inodes will be
87          * (xfs_default_attroffset(ip) >> 3) because we could have mounted
88          * with ATTR2 and then mounted back with ATTR1, keeping the
89          * di_forkoff's fixed but probably at various positions. Therefore,
90          * for both ATTR1 and ATTR2 we have to assume the worst case scenario
91          * of a minimum size available.
92          */
93         if (whichfork == XFS_DATA_FORK) {
94                 maxleafents = MAXEXTNUM;
95                 sz = XFS_BMDR_SPACE_CALC(MINDBTPTRS);
96         } else {
97                 maxleafents = MAXAEXTNUM;
98                 sz = XFS_BMDR_SPACE_CALC(MINABTPTRS);
99         }
100         maxrootrecs = xfs_bmdr_maxrecs(sz, 0);
101         minleafrecs = mp->m_bmap_dmnr[0];
102         minnoderecs = mp->m_bmap_dmnr[1];
103         maxblocks = (maxleafents + minleafrecs - 1) / minleafrecs;
104         for (level = 1; maxblocks > 1; level++) {
105                 if (maxblocks <= maxrootrecs)
106                         maxblocks = 1;
107                 else
108                         maxblocks = (maxblocks + minnoderecs - 1) / minnoderecs;
109         }
110         mp->m_bm_maxlevels[whichfork] = level;
111 }
112
113 STATIC int                              /* error */
114 xfs_bmbt_lookup_eq(
115         struct xfs_btree_cur    *cur,
116         xfs_fileoff_t           off,
117         xfs_fsblock_t           bno,
118         xfs_filblks_t           len,
119         int                     *stat)  /* success/failure */
120 {
121         cur->bc_rec.b.br_startoff = off;
122         cur->bc_rec.b.br_startblock = bno;
123         cur->bc_rec.b.br_blockcount = len;
124         return xfs_btree_lookup(cur, XFS_LOOKUP_EQ, stat);
125 }
126
127 STATIC int                              /* error */
128 xfs_bmbt_lookup_ge(
129         struct xfs_btree_cur    *cur,
130         xfs_fileoff_t           off,
131         xfs_fsblock_t           bno,
132         xfs_filblks_t           len,
133         int                     *stat)  /* success/failure */
134 {
135         cur->bc_rec.b.br_startoff = off;
136         cur->bc_rec.b.br_startblock = bno;
137         cur->bc_rec.b.br_blockcount = len;
138         return xfs_btree_lookup(cur, XFS_LOOKUP_GE, stat);
139 }
140
141 /*
142  * Check if the inode needs to be converted to btree format.
143  */
144 static inline bool xfs_bmap_needs_btree(struct xfs_inode *ip, int whichfork)
145 {
146         return whichfork != XFS_COW_FORK &&
147                 XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS &&
148                 XFS_IFORK_NEXTENTS(ip, whichfork) >
149                         XFS_IFORK_MAXEXT(ip, whichfork);
150 }
151
152 /*
153  * Check if the inode should be converted to extent format.
154  */
155 static inline bool xfs_bmap_wants_extents(struct xfs_inode *ip, int whichfork)
156 {
157         return whichfork != XFS_COW_FORK &&
158                 XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE &&
159                 XFS_IFORK_NEXTENTS(ip, whichfork) <=
160                         XFS_IFORK_MAXEXT(ip, whichfork);
161 }
162
163 /*
164  * Update the record referred to by cur to the value given
165  * by [off, bno, len, state].
166  * This either works (return 0) or gets an EFSCORRUPTED error.
167  */
168 STATIC int
169 xfs_bmbt_update(
170         struct xfs_btree_cur    *cur,
171         xfs_fileoff_t           off,
172         xfs_fsblock_t           bno,
173         xfs_filblks_t           len,
174         xfs_exntst_t            state)
175 {
176         union xfs_btree_rec     rec;
177
178         xfs_bmbt_disk_set_allf(&rec.bmbt, off, bno, len, state);
179         return xfs_btree_update(cur, &rec);
180 }
181
182 /*
183  * Compute the worst-case number of indirect blocks that will be used
184  * for ip's delayed extent of length "len".
185  */
186 STATIC xfs_filblks_t
187 xfs_bmap_worst_indlen(
188         xfs_inode_t     *ip,            /* incore inode pointer */
189         xfs_filblks_t   len)            /* delayed extent length */
190 {
191         int             level;          /* btree level number */
192         int             maxrecs;        /* maximum record count at this level */
193         xfs_mount_t     *mp;            /* mount structure */
194         xfs_filblks_t   rval;           /* return value */
195         xfs_filblks_t   orig_len;
196
197         mp = ip->i_mount;
198
199         /* Calculate the worst-case size of the bmbt. */
200         orig_len = len;
201         maxrecs = mp->m_bmap_dmxr[0];
202         for (level = 0, rval = 0;
203              level < XFS_BM_MAXLEVELS(mp, XFS_DATA_FORK);
204              level++) {
205                 len += maxrecs - 1;
206                 do_div(len, maxrecs);
207                 rval += len;
208                 if (len == 1) {
209                         rval += XFS_BM_MAXLEVELS(mp, XFS_DATA_FORK) -
210                                 level - 1;
211                         break;
212                 }
213                 if (level == 0)
214                         maxrecs = mp->m_bmap_dmxr[1];
215         }
216
217         /* Calculate the worst-case size of the rmapbt. */
218         if (xfs_sb_version_hasrmapbt(&mp->m_sb))
219                 rval += 1 + xfs_rmapbt_calc_size(mp, orig_len) +
220                                 mp->m_rmap_maxlevels;
221
222         return rval;
223 }
224
225 /*
226  * Calculate the default attribute fork offset for newly created inodes.
227  */
228 uint
229 xfs_default_attroffset(
230         struct xfs_inode        *ip)
231 {
232         struct xfs_mount        *mp = ip->i_mount;
233         uint                    offset;
234
235         if (mp->m_sb.sb_inodesize == 256) {
236                 offset = XFS_LITINO(mp, ip->i_d.di_version) -
237                                 XFS_BMDR_SPACE_CALC(MINABTPTRS);
238         } else {
239                 offset = XFS_BMDR_SPACE_CALC(6 * MINABTPTRS);
240         }
241
242         ASSERT(offset < XFS_LITINO(mp, ip->i_d.di_version));
243         return offset;
244 }
245
246 /*
247  * Helper routine to reset inode di_forkoff field when switching
248  * attribute fork from local to extent format - we reset it where
249  * possible to make space available for inline data fork extents.
250  */
251 STATIC void
252 xfs_bmap_forkoff_reset(
253         xfs_inode_t     *ip,
254         int             whichfork)
255 {
256         if (whichfork == XFS_ATTR_FORK &&
257             ip->i_d.di_format != XFS_DINODE_FMT_DEV &&
258             ip->i_d.di_format != XFS_DINODE_FMT_UUID &&
259             ip->i_d.di_format != XFS_DINODE_FMT_BTREE) {
260                 uint    dfl_forkoff = xfs_default_attroffset(ip) >> 3;
261
262                 if (dfl_forkoff > ip->i_d.di_forkoff)
263                         ip->i_d.di_forkoff = dfl_forkoff;
264         }
265 }
266
267 #ifdef DEBUG
268 STATIC struct xfs_buf *
269 xfs_bmap_get_bp(
270         struct xfs_btree_cur    *cur,
271         xfs_fsblock_t           bno)
272 {
273         struct xfs_log_item_desc *lidp;
274         int                     i;
275
276         if (!cur)
277                 return NULL;
278
279         for (i = 0; i < XFS_BTREE_MAXLEVELS; i++) {
280                 if (!cur->bc_bufs[i])
281                         break;
282                 if (XFS_BUF_ADDR(cur->bc_bufs[i]) == bno)
283                         return cur->bc_bufs[i];
284         }
285
286         /* Chase down all the log items to see if the bp is there */
287         list_for_each_entry(lidp, &cur->bc_tp->t_items, lid_trans) {
288                 struct xfs_buf_log_item *bip;
289                 bip = (struct xfs_buf_log_item *)lidp->lid_item;
290                 if (bip->bli_item.li_type == XFS_LI_BUF &&
291                     XFS_BUF_ADDR(bip->bli_buf) == bno)
292                         return bip->bli_buf;
293         }
294
295         return NULL;
296 }
297
298 STATIC void
299 xfs_check_block(
300         struct xfs_btree_block  *block,
301         xfs_mount_t             *mp,
302         int                     root,
303         short                   sz)
304 {
305         int                     i, j, dmxr;
306         __be64                  *pp, *thispa;   /* pointer to block address */
307         xfs_bmbt_key_t          *prevp, *keyp;
308
309         ASSERT(be16_to_cpu(block->bb_level) > 0);
310
311         prevp = NULL;
312         for( i = 1; i <= xfs_btree_get_numrecs(block); i++) {
313                 dmxr = mp->m_bmap_dmxr[0];
314                 keyp = XFS_BMBT_KEY_ADDR(mp, block, i);
315
316                 if (prevp) {
317                         ASSERT(be64_to_cpu(prevp->br_startoff) <
318                                be64_to_cpu(keyp->br_startoff));
319                 }
320                 prevp = keyp;
321
322                 /*
323                  * Compare the block numbers to see if there are dups.
324                  */
325                 if (root)
326                         pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, i, sz);
327                 else
328                         pp = XFS_BMBT_PTR_ADDR(mp, block, i, dmxr);
329
330                 for (j = i+1; j <= be16_to_cpu(block->bb_numrecs); j++) {
331                         if (root)
332                                 thispa = XFS_BMAP_BROOT_PTR_ADDR(mp, block, j, sz);
333                         else
334                                 thispa = XFS_BMBT_PTR_ADDR(mp, block, j, dmxr);
335                         if (*thispa == *pp) {
336                                 xfs_warn(mp, "%s: thispa(%d) == pp(%d) %Ld",
337                                         __func__, j, i,
338                                         (unsigned long long)be64_to_cpu(*thispa));
339                                 panic("%s: ptrs are equal in node\n",
340                                         __func__);
341                         }
342                 }
343         }
344 }
345
346 /*
347  * Check that the extents for the inode ip are in the right order in all
348  * btree leaves. THis becomes prohibitively expensive for large extent count
349  * files, so don't bother with inodes that have more than 10,000 extents in
350  * them. The btree record ordering checks will still be done, so for such large
351  * bmapbt constructs that is going to catch most corruptions.
352  */
353 STATIC void
354 xfs_bmap_check_leaf_extents(
355         xfs_btree_cur_t         *cur,   /* btree cursor or null */
356         xfs_inode_t             *ip,            /* incore inode pointer */
357         int                     whichfork)      /* data or attr fork */
358 {
359         struct xfs_btree_block  *block; /* current btree block */
360         xfs_fsblock_t           bno;    /* block # of "block" */
361         xfs_buf_t               *bp;    /* buffer for "block" */
362         int                     error;  /* error return value */
363         xfs_extnum_t            i=0, j; /* index into the extents list */
364         xfs_ifork_t             *ifp;   /* fork structure */
365         int                     level;  /* btree level, for checking */
366         xfs_mount_t             *mp;    /* file system mount structure */
367         __be64                  *pp;    /* pointer to block address */
368         xfs_bmbt_rec_t          *ep;    /* pointer to current extent */
369         xfs_bmbt_rec_t          last = {0, 0}; /* last extent in prev block */
370         xfs_bmbt_rec_t          *nextp; /* pointer to next extent */
371         int                     bp_release = 0;
372
373         if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE) {
374                 return;
375         }
376
377         /* skip large extent count inodes */
378         if (ip->i_d.di_nextents > 10000)
379                 return;
380
381         bno = NULLFSBLOCK;
382         mp = ip->i_mount;
383         ifp = XFS_IFORK_PTR(ip, whichfork);
384         block = ifp->if_broot;
385         /*
386          * Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out.
387          */
388         level = be16_to_cpu(block->bb_level);
389         ASSERT(level > 0);
390         xfs_check_block(block, mp, 1, ifp->if_broot_bytes);
391         pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, 1, ifp->if_broot_bytes);
392         bno = be64_to_cpu(*pp);
393
394         ASSERT(bno != NULLFSBLOCK);
395         ASSERT(XFS_FSB_TO_AGNO(mp, bno) < mp->m_sb.sb_agcount);
396         ASSERT(XFS_FSB_TO_AGBNO(mp, bno) < mp->m_sb.sb_agblocks);
397
398         /*
399          * Go down the tree until leaf level is reached, following the first
400          * pointer (leftmost) at each level.
401          */
402         while (level-- > 0) {
403                 /* See if buf is in cur first */
404                 bp_release = 0;
405                 bp = xfs_bmap_get_bp(cur, XFS_FSB_TO_DADDR(mp, bno));
406                 if (!bp) {
407                         bp_release = 1;
408                         error = xfs_btree_read_bufl(mp, NULL, bno, 0, &bp,
409                                                 XFS_BMAP_BTREE_REF,
410                                                 &xfs_bmbt_buf_ops);
411                         if (error)
412                                 goto error_norelse;
413                 }
414                 block = XFS_BUF_TO_BLOCK(bp);
415                 if (level == 0)
416                         break;
417
418                 /*
419                  * Check this block for basic sanity (increasing keys and
420                  * no duplicate blocks).
421                  */
422
423                 xfs_check_block(block, mp, 0, 0);
424                 pp = XFS_BMBT_PTR_ADDR(mp, block, 1, mp->m_bmap_dmxr[1]);
425                 bno = be64_to_cpu(*pp);
426                 XFS_WANT_CORRUPTED_GOTO(mp,
427                                         XFS_FSB_SANITY_CHECK(mp, bno), error0);
428                 if (bp_release) {
429                         bp_release = 0;
430                         xfs_trans_brelse(NULL, bp);
431                 }
432         }
433
434         /*
435          * Here with bp and block set to the leftmost leaf node in the tree.
436          */
437         i = 0;
438
439         /*
440          * Loop over all leaf nodes checking that all extents are in the right order.
441          */
442         for (;;) {
443                 xfs_fsblock_t   nextbno;
444                 xfs_extnum_t    num_recs;
445
446
447                 num_recs = xfs_btree_get_numrecs(block);
448
449                 /*
450                  * Read-ahead the next leaf block, if any.
451                  */
452
453                 nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib);
454
455                 /*
456                  * Check all the extents to make sure they are OK.
457                  * If we had a previous block, the last entry should
458                  * conform with the first entry in this one.
459                  */
460
461                 ep = XFS_BMBT_REC_ADDR(mp, block, 1);
462                 if (i) {
463                         ASSERT(xfs_bmbt_disk_get_startoff(&last) +
464                                xfs_bmbt_disk_get_blockcount(&last) <=
465                                xfs_bmbt_disk_get_startoff(ep));
466                 }
467                 for (j = 1; j < num_recs; j++) {
468                         nextp = XFS_BMBT_REC_ADDR(mp, block, j + 1);
469                         ASSERT(xfs_bmbt_disk_get_startoff(ep) +
470                                xfs_bmbt_disk_get_blockcount(ep) <=
471                                xfs_bmbt_disk_get_startoff(nextp));
472                         ep = nextp;
473                 }
474
475                 last = *ep;
476                 i += num_recs;
477                 if (bp_release) {
478                         bp_release = 0;
479                         xfs_trans_brelse(NULL, bp);
480                 }
481                 bno = nextbno;
482                 /*
483                  * If we've reached the end, stop.
484                  */
485                 if (bno == NULLFSBLOCK)
486                         break;
487
488                 bp_release = 0;
489                 bp = xfs_bmap_get_bp(cur, XFS_FSB_TO_DADDR(mp, bno));
490                 if (!bp) {
491                         bp_release = 1;
492                         error = xfs_btree_read_bufl(mp, NULL, bno, 0, &bp,
493                                                 XFS_BMAP_BTREE_REF,
494                                                 &xfs_bmbt_buf_ops);
495                         if (error)
496                                 goto error_norelse;
497                 }
498                 block = XFS_BUF_TO_BLOCK(bp);
499         }
500
501         return;
502
503 error0:
504         xfs_warn(mp, "%s: at error0", __func__);
505         if (bp_release)
506                 xfs_trans_brelse(NULL, bp);
507 error_norelse:
508         xfs_warn(mp, "%s: BAD after btree leaves for %d extents",
509                 __func__, i);
510         panic("%s: CORRUPTED BTREE OR SOMETHING", __func__);
511         return;
512 }
513
514 /*
515  * Add bmap trace insert entries for all the contents of the extent records.
516  */
517 void
518 xfs_bmap_trace_exlist(
519         xfs_inode_t     *ip,            /* incore inode pointer */
520         xfs_extnum_t    cnt,            /* count of entries in the list */
521         int             whichfork,      /* data or attr or cow fork */
522         unsigned long   caller_ip)
523 {
524         xfs_extnum_t    idx;            /* extent record index */
525         xfs_ifork_t     *ifp;           /* inode fork pointer */
526         int             state = 0;
527
528         if (whichfork == XFS_ATTR_FORK)
529                 state |= BMAP_ATTRFORK;
530         else if (whichfork == XFS_COW_FORK)
531                 state |= BMAP_COWFORK;
532
533         ifp = XFS_IFORK_PTR(ip, whichfork);
534         ASSERT(cnt == xfs_iext_count(ifp));
535         for (idx = 0; idx < cnt; idx++)
536                 trace_xfs_extlist(ip, idx, state, caller_ip);
537 }
538
539 /*
540  * Validate that the bmbt_irecs being returned from bmapi are valid
541  * given the caller's original parameters.  Specifically check the
542  * ranges of the returned irecs to ensure that they only extend beyond
543  * the given parameters if the XFS_BMAPI_ENTIRE flag was set.
544  */
545 STATIC void
546 xfs_bmap_validate_ret(
547         xfs_fileoff_t           bno,
548         xfs_filblks_t           len,
549         int                     flags,
550         xfs_bmbt_irec_t         *mval,
551         int                     nmap,
552         int                     ret_nmap)
553 {
554         int                     i;              /* index to map values */
555
556         ASSERT(ret_nmap <= nmap);
557
558         for (i = 0; i < ret_nmap; i++) {
559                 ASSERT(mval[i].br_blockcount > 0);
560                 if (!(flags & XFS_BMAPI_ENTIRE)) {
561                         ASSERT(mval[i].br_startoff >= bno);
562                         ASSERT(mval[i].br_blockcount <= len);
563                         ASSERT(mval[i].br_startoff + mval[i].br_blockcount <=
564                                bno + len);
565                 } else {
566                         ASSERT(mval[i].br_startoff < bno + len);
567                         ASSERT(mval[i].br_startoff + mval[i].br_blockcount >
568                                bno);
569                 }
570                 ASSERT(i == 0 ||
571                        mval[i - 1].br_startoff + mval[i - 1].br_blockcount ==
572                        mval[i].br_startoff);
573                 ASSERT(mval[i].br_startblock != DELAYSTARTBLOCK &&
574                        mval[i].br_startblock != HOLESTARTBLOCK);
575                 ASSERT(mval[i].br_state == XFS_EXT_NORM ||
576                        mval[i].br_state == XFS_EXT_UNWRITTEN);
577         }
578 }
579
580 #else
581 #define xfs_bmap_check_leaf_extents(cur, ip, whichfork)         do { } while (0)
582 #define xfs_bmap_validate_ret(bno,len,flags,mval,onmap,nmap)
583 #endif /* DEBUG */
584
585 /*
586  * bmap free list manipulation functions
587  */
588
589 /*
590  * Add the extent to the list of extents to be free at transaction end.
591  * The list is maintained sorted (by block number).
592  */
593 void
594 xfs_bmap_add_free(
595         struct xfs_mount                *mp,
596         struct xfs_defer_ops            *dfops,
597         xfs_fsblock_t                   bno,
598         xfs_filblks_t                   len,
599         struct xfs_owner_info           *oinfo)
600 {
601         struct xfs_extent_free_item     *new;           /* new element */
602 #ifdef DEBUG
603         xfs_agnumber_t          agno;
604         xfs_agblock_t           agbno;
605
606         ASSERT(bno != NULLFSBLOCK);
607         ASSERT(len > 0);
608         ASSERT(len <= MAXEXTLEN);
609         ASSERT(!isnullstartblock(bno));
610         agno = XFS_FSB_TO_AGNO(mp, bno);
611         agbno = XFS_FSB_TO_AGBNO(mp, bno);
612         ASSERT(agno < mp->m_sb.sb_agcount);
613         ASSERT(agbno < mp->m_sb.sb_agblocks);
614         ASSERT(len < mp->m_sb.sb_agblocks);
615         ASSERT(agbno + len <= mp->m_sb.sb_agblocks);
616 #endif
617         ASSERT(xfs_bmap_free_item_zone != NULL);
618
619         new = kmem_zone_alloc(xfs_bmap_free_item_zone, KM_SLEEP);
620         new->xefi_startblock = bno;
621         new->xefi_blockcount = (xfs_extlen_t)len;
622         if (oinfo)
623                 new->xefi_oinfo = *oinfo;
624         else
625                 xfs_rmap_skip_owner_update(&new->xefi_oinfo);
626         trace_xfs_bmap_free_defer(mp, XFS_FSB_TO_AGNO(mp, bno), 0,
627                         XFS_FSB_TO_AGBNO(mp, bno), len);
628         xfs_defer_add(dfops, XFS_DEFER_OPS_TYPE_FREE, &new->xefi_list);
629 }
630
631 /*
632  * Inode fork format manipulation functions
633  */
634
635 /*
636  * Transform a btree format file with only one leaf node, where the
637  * extents list will fit in the inode, into an extents format file.
638  * Since the file extents are already in-core, all we have to do is
639  * give up the space for the btree root and pitch the leaf block.
640  */
641 STATIC int                              /* error */
642 xfs_bmap_btree_to_extents(
643         xfs_trans_t             *tp,    /* transaction pointer */
644         xfs_inode_t             *ip,    /* incore inode pointer */
645         xfs_btree_cur_t         *cur,   /* btree cursor */
646         int                     *logflagsp, /* inode logging flags */
647         int                     whichfork)  /* data or attr fork */
648 {
649         /* REFERENCED */
650         struct xfs_btree_block  *cblock;/* child btree block */
651         xfs_fsblock_t           cbno;   /* child block number */
652         xfs_buf_t               *cbp;   /* child block's buffer */
653         int                     error;  /* error return value */
654         xfs_ifork_t             *ifp;   /* inode fork data */
655         xfs_mount_t             *mp;    /* mount point structure */
656         __be64                  *pp;    /* ptr to block address */
657         struct xfs_btree_block  *rblock;/* root btree block */
658         struct xfs_owner_info   oinfo;
659
660         mp = ip->i_mount;
661         ifp = XFS_IFORK_PTR(ip, whichfork);
662         ASSERT(whichfork != XFS_COW_FORK);
663         ASSERT(ifp->if_flags & XFS_IFEXTENTS);
664         ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE);
665         rblock = ifp->if_broot;
666         ASSERT(be16_to_cpu(rblock->bb_level) == 1);
667         ASSERT(be16_to_cpu(rblock->bb_numrecs) == 1);
668         ASSERT(xfs_bmbt_maxrecs(mp, ifp->if_broot_bytes, 0) == 1);
669         pp = XFS_BMAP_BROOT_PTR_ADDR(mp, rblock, 1, ifp->if_broot_bytes);
670         cbno = be64_to_cpu(*pp);
671         *logflagsp = 0;
672 #ifdef DEBUG
673         if ((error = xfs_btree_check_lptr(cur, cbno, 1)))
674                 return error;
675 #endif
676         error = xfs_btree_read_bufl(mp, tp, cbno, 0, &cbp, XFS_BMAP_BTREE_REF,
677                                 &xfs_bmbt_buf_ops);
678         if (error)
679                 return error;
680         cblock = XFS_BUF_TO_BLOCK(cbp);
681         if ((error = xfs_btree_check_block(cur, cblock, 0, cbp)))
682                 return error;
683         xfs_rmap_ino_bmbt_owner(&oinfo, ip->i_ino, whichfork);
684         xfs_bmap_add_free(mp, cur->bc_private.b.dfops, cbno, 1, &oinfo);
685         ip->i_d.di_nblocks--;
686         xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_BCOUNT, -1L);
687         xfs_trans_binval(tp, cbp);
688         if (cur->bc_bufs[0] == cbp)
689                 cur->bc_bufs[0] = NULL;
690         xfs_iroot_realloc(ip, -1, whichfork);
691         ASSERT(ifp->if_broot == NULL);
692         ASSERT((ifp->if_flags & XFS_IFBROOT) == 0);
693         XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_EXTENTS);
694         *logflagsp = XFS_ILOG_CORE | xfs_ilog_fext(whichfork);
695         return 0;
696 }
697
698 /*
699  * Convert an extents-format file into a btree-format file.
700  * The new file will have a root block (in the inode) and a single child block.
701  */
702 STATIC int                                      /* error */
703 xfs_bmap_extents_to_btree(
704         xfs_trans_t             *tp,            /* transaction pointer */
705         xfs_inode_t             *ip,            /* incore inode pointer */
706         xfs_fsblock_t           *firstblock,    /* first-block-allocated */
707         struct xfs_defer_ops    *dfops,         /* blocks freed in xaction */
708         xfs_btree_cur_t         **curp,         /* cursor returned to caller */
709         int                     wasdel,         /* converting a delayed alloc */
710         int                     *logflagsp,     /* inode logging flags */
711         int                     whichfork)      /* data or attr fork */
712 {
713         struct xfs_btree_block  *ablock;        /* allocated (child) bt block */
714         xfs_buf_t               *abp;           /* buffer for ablock */
715         xfs_alloc_arg_t         args;           /* allocation arguments */
716         xfs_bmbt_rec_t          *arp;           /* child record pointer */
717         struct xfs_btree_block  *block;         /* btree root block */
718         xfs_btree_cur_t         *cur;           /* bmap btree cursor */
719         xfs_bmbt_rec_host_t     *ep;            /* extent record pointer */
720         int                     error;          /* error return value */
721         xfs_extnum_t            i, cnt;         /* extent record index */
722         xfs_ifork_t             *ifp;           /* inode fork pointer */
723         xfs_bmbt_key_t          *kp;            /* root block key pointer */
724         xfs_mount_t             *mp;            /* mount structure */
725         xfs_extnum_t            nextents;       /* number of file extents */
726         xfs_bmbt_ptr_t          *pp;            /* root block address pointer */
727
728         mp = ip->i_mount;
729         ASSERT(whichfork != XFS_COW_FORK);
730         ifp = XFS_IFORK_PTR(ip, whichfork);
731         ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS);
732
733         /*
734          * Make space in the inode incore.
735          */
736         xfs_iroot_realloc(ip, 1, whichfork);
737         ifp->if_flags |= XFS_IFBROOT;
738
739         /*
740          * Fill in the root.
741          */
742         block = ifp->if_broot;
743         xfs_btree_init_block_int(mp, block, XFS_BUF_DADDR_NULL,
744                                  XFS_BTNUM_BMAP, 1, 1, ip->i_ino,
745                                  XFS_BTREE_LONG_PTRS);
746         /*
747          * Need a cursor.  Can't allocate until bb_level is filled in.
748          */
749         cur = xfs_bmbt_init_cursor(mp, tp, ip, whichfork);
750         cur->bc_private.b.firstblock = *firstblock;
751         cur->bc_private.b.dfops = dfops;
752         cur->bc_private.b.flags = wasdel ? XFS_BTCUR_BPRV_WASDEL : 0;
753         /*
754          * Convert to a btree with two levels, one record in root.
755          */
756         XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_BTREE);
757         memset(&args, 0, sizeof(args));
758         args.tp = tp;
759         args.mp = mp;
760         xfs_rmap_ino_bmbt_owner(&args.oinfo, ip->i_ino, whichfork);
761         args.firstblock = *firstblock;
762         if (*firstblock == NULLFSBLOCK) {
763                 args.type = XFS_ALLOCTYPE_START_BNO;
764                 args.fsbno = XFS_INO_TO_FSB(mp, ip->i_ino);
765         } else if (dfops->dop_low) {
766                 args.type = XFS_ALLOCTYPE_START_BNO;
767                 args.fsbno = *firstblock;
768         } else {
769                 args.type = XFS_ALLOCTYPE_NEAR_BNO;
770                 args.fsbno = *firstblock;
771         }
772         args.minlen = args.maxlen = args.prod = 1;
773         args.wasdel = wasdel;
774         *logflagsp = 0;
775         if ((error = xfs_alloc_vextent(&args))) {
776                 xfs_iroot_realloc(ip, -1, whichfork);
777                 xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
778                 return error;
779         }
780
781         if (WARN_ON_ONCE(args.fsbno == NULLFSBLOCK)) {
782                 xfs_iroot_realloc(ip, -1, whichfork);
783                 xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
784                 return -ENOSPC;
785         }
786         /*
787          * Allocation can't fail, the space was reserved.
788          */
789         ASSERT(*firstblock == NULLFSBLOCK ||
790                args.agno >= XFS_FSB_TO_AGNO(mp, *firstblock));
791         *firstblock = cur->bc_private.b.firstblock = args.fsbno;
792         cur->bc_private.b.allocated++;
793         ip->i_d.di_nblocks++;
794         xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_BCOUNT, 1L);
795         abp = xfs_btree_get_bufl(mp, tp, args.fsbno, 0);
796         /*
797          * Fill in the child block.
798          */
799         abp->b_ops = &xfs_bmbt_buf_ops;
800         ablock = XFS_BUF_TO_BLOCK(abp);
801         xfs_btree_init_block_int(mp, ablock, abp->b_bn,
802                                 XFS_BTNUM_BMAP, 0, 0, ip->i_ino,
803                                 XFS_BTREE_LONG_PTRS);
804
805         arp = XFS_BMBT_REC_ADDR(mp, ablock, 1);
806         nextents =  xfs_iext_count(ifp);
807         for (cnt = i = 0; i < nextents; i++) {
808                 ep = xfs_iext_get_ext(ifp, i);
809                 if (!isnullstartblock(xfs_bmbt_get_startblock(ep))) {
810                         arp->l0 = cpu_to_be64(ep->l0);
811                         arp->l1 = cpu_to_be64(ep->l1);
812                         arp++; cnt++;
813                 }
814         }
815         ASSERT(cnt == XFS_IFORK_NEXTENTS(ip, whichfork));
816         xfs_btree_set_numrecs(ablock, cnt);
817
818         /*
819          * Fill in the root key and pointer.
820          */
821         kp = XFS_BMBT_KEY_ADDR(mp, block, 1);
822         arp = XFS_BMBT_REC_ADDR(mp, ablock, 1);
823         kp->br_startoff = cpu_to_be64(xfs_bmbt_disk_get_startoff(arp));
824         pp = XFS_BMBT_PTR_ADDR(mp, block, 1, xfs_bmbt_get_maxrecs(cur,
825                                                 be16_to_cpu(block->bb_level)));
826         *pp = cpu_to_be64(args.fsbno);
827
828         /*
829          * Do all this logging at the end so that
830          * the root is at the right level.
831          */
832         xfs_btree_log_block(cur, abp, XFS_BB_ALL_BITS);
833         xfs_btree_log_recs(cur, abp, 1, be16_to_cpu(ablock->bb_numrecs));
834         ASSERT(*curp == NULL);
835         *curp = cur;
836         *logflagsp = XFS_ILOG_CORE | xfs_ilog_fbroot(whichfork);
837         return 0;
838 }
839
840 /*
841  * Convert a local file to an extents file.
842  * This code is out of bounds for data forks of regular files,
843  * since the file data needs to get logged so things will stay consistent.
844  * (The bmap-level manipulations are ok, though).
845  */
846 void
847 xfs_bmap_local_to_extents_empty(
848         struct xfs_inode        *ip,
849         int                     whichfork)
850 {
851         struct xfs_ifork        *ifp = XFS_IFORK_PTR(ip, whichfork);
852
853         ASSERT(whichfork != XFS_COW_FORK);
854         ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL);
855         ASSERT(ifp->if_bytes == 0);
856         ASSERT(XFS_IFORK_NEXTENTS(ip, whichfork) == 0);
857
858         xfs_bmap_forkoff_reset(ip, whichfork);
859         ifp->if_flags &= ~XFS_IFINLINE;
860         ifp->if_flags |= XFS_IFEXTENTS;
861         XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_EXTENTS);
862 }
863
864
865 STATIC int                              /* error */
866 xfs_bmap_local_to_extents(
867         xfs_trans_t     *tp,            /* transaction pointer */
868         xfs_inode_t     *ip,            /* incore inode pointer */
869         xfs_fsblock_t   *firstblock,    /* first block allocated in xaction */
870         xfs_extlen_t    total,          /* total blocks needed by transaction */
871         int             *logflagsp,     /* inode logging flags */
872         int             whichfork,
873         void            (*init_fn)(struct xfs_trans *tp,
874                                    struct xfs_buf *bp,
875                                    struct xfs_inode *ip,
876                                    struct xfs_ifork *ifp))
877 {
878         int             error = 0;
879         int             flags;          /* logging flags returned */
880         xfs_ifork_t     *ifp;           /* inode fork pointer */
881         xfs_alloc_arg_t args;           /* allocation arguments */
882         xfs_buf_t       *bp;            /* buffer for extent block */
883         xfs_bmbt_rec_host_t *ep;        /* extent record pointer */
884
885         /*
886          * We don't want to deal with the case of keeping inode data inline yet.
887          * So sending the data fork of a regular inode is invalid.
888          */
889         ASSERT(!(S_ISREG(VFS_I(ip)->i_mode) && whichfork == XFS_DATA_FORK));
890         ifp = XFS_IFORK_PTR(ip, whichfork);
891         ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL);
892
893         if (!ifp->if_bytes) {
894                 xfs_bmap_local_to_extents_empty(ip, whichfork);
895                 flags = XFS_ILOG_CORE;
896                 goto done;
897         }
898
899         flags = 0;
900         error = 0;
901         ASSERT((ifp->if_flags & (XFS_IFINLINE|XFS_IFEXTENTS|XFS_IFEXTIREC)) ==
902                                                                 XFS_IFINLINE);
903         memset(&args, 0, sizeof(args));
904         args.tp = tp;
905         args.mp = ip->i_mount;
906         xfs_rmap_ino_owner(&args.oinfo, ip->i_ino, whichfork, 0);
907         args.firstblock = *firstblock;
908         /*
909          * Allocate a block.  We know we need only one, since the
910          * file currently fits in an inode.
911          */
912         if (*firstblock == NULLFSBLOCK) {
913                 args.fsbno = XFS_INO_TO_FSB(args.mp, ip->i_ino);
914                 args.type = XFS_ALLOCTYPE_START_BNO;
915         } else {
916                 args.fsbno = *firstblock;
917                 args.type = XFS_ALLOCTYPE_NEAR_BNO;
918         }
919         args.total = total;
920         args.minlen = args.maxlen = args.prod = 1;
921         error = xfs_alloc_vextent(&args);
922         if (error)
923                 goto done;
924
925         /* Can't fail, the space was reserved. */
926         ASSERT(args.fsbno != NULLFSBLOCK);
927         ASSERT(args.len == 1);
928         *firstblock = args.fsbno;
929         bp = xfs_btree_get_bufl(args.mp, tp, args.fsbno, 0);
930
931         /*
932          * Initialize the block, copy the data and log the remote buffer.
933          *
934          * The callout is responsible for logging because the remote format
935          * might differ from the local format and thus we don't know how much to
936          * log here. Note that init_fn must also set the buffer log item type
937          * correctly.
938          */
939         init_fn(tp, bp, ip, ifp);
940
941         /* account for the change in fork size */
942         xfs_idata_realloc(ip, -ifp->if_bytes, whichfork);
943         xfs_bmap_local_to_extents_empty(ip, whichfork);
944         flags |= XFS_ILOG_CORE;
945
946         xfs_iext_add(ifp, 0, 1);
947         ep = xfs_iext_get_ext(ifp, 0);
948         xfs_bmbt_set_allf(ep, 0, args.fsbno, 1, XFS_EXT_NORM);
949         trace_xfs_bmap_post_update(ip, 0,
950                         whichfork == XFS_ATTR_FORK ? BMAP_ATTRFORK : 0,
951                         _THIS_IP_);
952         XFS_IFORK_NEXT_SET(ip, whichfork, 1);
953         ip->i_d.di_nblocks = 1;
954         xfs_trans_mod_dquot_byino(tp, ip,
955                 XFS_TRANS_DQ_BCOUNT, 1L);
956         flags |= xfs_ilog_fext(whichfork);
957
958 done:
959         *logflagsp = flags;
960         return error;
961 }
962
963 /*
964  * Called from xfs_bmap_add_attrfork to handle btree format files.
965  */
966 STATIC int                                      /* error */
967 xfs_bmap_add_attrfork_btree(
968         xfs_trans_t             *tp,            /* transaction pointer */
969         xfs_inode_t             *ip,            /* incore inode pointer */
970         xfs_fsblock_t           *firstblock,    /* first block allocated */
971         struct xfs_defer_ops    *dfops,         /* blocks to free at commit */
972         int                     *flags)         /* inode logging flags */
973 {
974         xfs_btree_cur_t         *cur;           /* btree cursor */
975         int                     error;          /* error return value */
976         xfs_mount_t             *mp;            /* file system mount struct */
977         int                     stat;           /* newroot status */
978
979         mp = ip->i_mount;
980         if (ip->i_df.if_broot_bytes <= XFS_IFORK_DSIZE(ip))
981                 *flags |= XFS_ILOG_DBROOT;
982         else {
983                 cur = xfs_bmbt_init_cursor(mp, tp, ip, XFS_DATA_FORK);
984                 cur->bc_private.b.dfops = dfops;
985                 cur->bc_private.b.firstblock = *firstblock;
986                 if ((error = xfs_bmbt_lookup_ge(cur, 0, 0, 0, &stat)))
987                         goto error0;
988                 /* must be at least one entry */
989                 XFS_WANT_CORRUPTED_GOTO(mp, stat == 1, error0);
990                 if ((error = xfs_btree_new_iroot(cur, flags, &stat)))
991                         goto error0;
992                 if (stat == 0) {
993                         xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
994                         return -ENOSPC;
995                 }
996                 *firstblock = cur->bc_private.b.firstblock;
997                 cur->bc_private.b.allocated = 0;
998                 xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
999         }
1000         return 0;
1001 error0:
1002         xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
1003         return error;
1004 }
1005
1006 /*
1007  * Called from xfs_bmap_add_attrfork to handle extents format files.
1008  */
1009 STATIC int                                      /* error */
1010 xfs_bmap_add_attrfork_extents(
1011         xfs_trans_t             *tp,            /* transaction pointer */
1012         xfs_inode_t             *ip,            /* incore inode pointer */
1013         xfs_fsblock_t           *firstblock,    /* first block allocated */
1014         struct xfs_defer_ops    *dfops,         /* blocks to free at commit */
1015         int                     *flags)         /* inode logging flags */
1016 {
1017         xfs_btree_cur_t         *cur;           /* bmap btree cursor */
1018         int                     error;          /* error return value */
1019
1020         if (ip->i_d.di_nextents * sizeof(xfs_bmbt_rec_t) <= XFS_IFORK_DSIZE(ip))
1021                 return 0;
1022         cur = NULL;
1023         error = xfs_bmap_extents_to_btree(tp, ip, firstblock, dfops, &cur, 0,
1024                 flags, XFS_DATA_FORK);
1025         if (cur) {
1026                 cur->bc_private.b.allocated = 0;
1027                 xfs_btree_del_cursor(cur,
1028                         error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
1029         }
1030         return error;
1031 }
1032
1033 /*
1034  * Called from xfs_bmap_add_attrfork to handle local format files. Each
1035  * different data fork content type needs a different callout to do the
1036  * conversion. Some are basic and only require special block initialisation
1037  * callouts for the data formating, others (directories) are so specialised they
1038  * handle everything themselves.
1039  *
1040  * XXX (dgc): investigate whether directory conversion can use the generic
1041  * formatting callout. It should be possible - it's just a very complex
1042  * formatter.
1043  */
1044 STATIC int                                      /* error */
1045 xfs_bmap_add_attrfork_local(
1046         xfs_trans_t             *tp,            /* transaction pointer */
1047         xfs_inode_t             *ip,            /* incore inode pointer */
1048         xfs_fsblock_t           *firstblock,    /* first block allocated */
1049         struct xfs_defer_ops    *dfops,         /* blocks to free at commit */
1050         int                     *flags)         /* inode logging flags */
1051 {
1052         xfs_da_args_t           dargs;          /* args for dir/attr code */
1053
1054         if (ip->i_df.if_bytes <= XFS_IFORK_DSIZE(ip))
1055                 return 0;
1056
1057         if (S_ISDIR(VFS_I(ip)->i_mode)) {
1058                 memset(&dargs, 0, sizeof(dargs));
1059                 dargs.geo = ip->i_mount->m_dir_geo;
1060                 dargs.dp = ip;
1061                 dargs.firstblock = firstblock;
1062                 dargs.dfops = dfops;
1063                 dargs.total = dargs.geo->fsbcount;
1064                 dargs.whichfork = XFS_DATA_FORK;
1065                 dargs.trans = tp;
1066                 return xfs_dir2_sf_to_block(&dargs);
1067         }
1068
1069         if (S_ISLNK(VFS_I(ip)->i_mode))
1070                 return xfs_bmap_local_to_extents(tp, ip, firstblock, 1,
1071                                                  flags, XFS_DATA_FORK,
1072                                                  xfs_symlink_local_to_remote);
1073
1074         /* should only be called for types that support local format data */
1075         ASSERT(0);
1076         return -EFSCORRUPTED;
1077 }
1078
1079 /*
1080  * Convert inode from non-attributed to attributed.
1081  * Must not be in a transaction, ip must not be locked.
1082  */
1083 int                                             /* error code */
1084 xfs_bmap_add_attrfork(
1085         xfs_inode_t             *ip,            /* incore inode pointer */
1086         int                     size,           /* space new attribute needs */
1087         int                     rsvd)           /* xact may use reserved blks */
1088 {
1089         xfs_fsblock_t           firstblock;     /* 1st block/ag allocated */
1090         struct xfs_defer_ops    dfops;          /* freed extent records */
1091         xfs_mount_t             *mp;            /* mount structure */
1092         xfs_trans_t             *tp;            /* transaction pointer */
1093         int                     blks;           /* space reservation */
1094         int                     version = 1;    /* superblock attr version */
1095         int                     logflags;       /* logging flags */
1096         int                     error;          /* error return value */
1097
1098         ASSERT(XFS_IFORK_Q(ip) == 0);
1099
1100         mp = ip->i_mount;
1101         ASSERT(!XFS_NOT_DQATTACHED(mp, ip));
1102
1103         blks = XFS_ADDAFORK_SPACE_RES(mp);
1104
1105         error = xfs_trans_alloc(mp, &M_RES(mp)->tr_addafork, blks, 0,
1106                         rsvd ? XFS_TRANS_RESERVE : 0, &tp);
1107         if (error)
1108                 return error;
1109
1110         xfs_ilock(ip, XFS_ILOCK_EXCL);
1111         error = xfs_trans_reserve_quota_nblks(tp, ip, blks, 0, rsvd ?
1112                         XFS_QMOPT_RES_REGBLKS | XFS_QMOPT_FORCE_RES :
1113                         XFS_QMOPT_RES_REGBLKS);
1114         if (error)
1115                 goto trans_cancel;
1116         if (XFS_IFORK_Q(ip))
1117                 goto trans_cancel;
1118         if (ip->i_d.di_anextents != 0) {
1119                 error = -EFSCORRUPTED;
1120                 goto trans_cancel;
1121         }
1122         if (ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS) {
1123                 /*
1124                  * For inodes coming from pre-6.2 filesystems.
1125                  */
1126                 ASSERT(ip->i_d.di_aformat == 0);
1127                 ip->i_d.di_aformat = XFS_DINODE_FMT_EXTENTS;
1128         }
1129
1130         xfs_trans_ijoin(tp, ip, 0);
1131         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1132
1133         switch (ip->i_d.di_format) {
1134         case XFS_DINODE_FMT_DEV:
1135                 ip->i_d.di_forkoff = roundup(sizeof(xfs_dev_t), 8) >> 3;
1136                 break;
1137         case XFS_DINODE_FMT_UUID:
1138                 ip->i_d.di_forkoff = roundup(sizeof(uuid_t), 8) >> 3;
1139                 break;
1140         case XFS_DINODE_FMT_LOCAL:
1141         case XFS_DINODE_FMT_EXTENTS:
1142         case XFS_DINODE_FMT_BTREE:
1143                 ip->i_d.di_forkoff = xfs_attr_shortform_bytesfit(ip, size);
1144                 if (!ip->i_d.di_forkoff)
1145                         ip->i_d.di_forkoff = xfs_default_attroffset(ip) >> 3;
1146                 else if (mp->m_flags & XFS_MOUNT_ATTR2)
1147                         version = 2;
1148                 break;
1149         default:
1150                 ASSERT(0);
1151                 error = -EINVAL;
1152                 goto trans_cancel;
1153         }
1154
1155         ASSERT(ip->i_afp == NULL);
1156         ip->i_afp = kmem_zone_zalloc(xfs_ifork_zone, KM_SLEEP);
1157         ip->i_afp->if_flags = XFS_IFEXTENTS;
1158         logflags = 0;
1159         xfs_defer_init(&dfops, &firstblock);
1160         switch (ip->i_d.di_format) {
1161         case XFS_DINODE_FMT_LOCAL:
1162                 error = xfs_bmap_add_attrfork_local(tp, ip, &firstblock, &dfops,
1163                         &logflags);
1164                 break;
1165         case XFS_DINODE_FMT_EXTENTS:
1166                 error = xfs_bmap_add_attrfork_extents(tp, ip, &firstblock,
1167                         &dfops, &logflags);
1168                 break;
1169         case XFS_DINODE_FMT_BTREE:
1170                 error = xfs_bmap_add_attrfork_btree(tp, ip, &firstblock, &dfops,
1171                         &logflags);
1172                 break;
1173         default:
1174                 error = 0;
1175                 break;
1176         }
1177         if (logflags)
1178                 xfs_trans_log_inode(tp, ip, logflags);
1179         if (error)
1180                 goto bmap_cancel;
1181         if (!xfs_sb_version_hasattr(&mp->m_sb) ||
1182            (!xfs_sb_version_hasattr2(&mp->m_sb) && version == 2)) {
1183                 bool log_sb = false;
1184
1185                 spin_lock(&mp->m_sb_lock);
1186                 if (!xfs_sb_version_hasattr(&mp->m_sb)) {
1187                         xfs_sb_version_addattr(&mp->m_sb);
1188                         log_sb = true;
1189                 }
1190                 if (!xfs_sb_version_hasattr2(&mp->m_sb) && version == 2) {
1191                         xfs_sb_version_addattr2(&mp->m_sb);
1192                         log_sb = true;
1193                 }
1194                 spin_unlock(&mp->m_sb_lock);
1195                 if (log_sb)
1196                         xfs_log_sb(tp);
1197         }
1198
1199         error = xfs_defer_finish(&tp, &dfops, NULL);
1200         if (error)
1201                 goto bmap_cancel;
1202         error = xfs_trans_commit(tp);
1203         xfs_iunlock(ip, XFS_ILOCK_EXCL);
1204         return error;
1205
1206 bmap_cancel:
1207         xfs_defer_cancel(&dfops);
1208 trans_cancel:
1209         xfs_trans_cancel(tp);
1210         xfs_iunlock(ip, XFS_ILOCK_EXCL);
1211         return error;
1212 }
1213
1214 /*
1215  * Internal and external extent tree search functions.
1216  */
1217
1218 /*
1219  * Read in the extents to if_extents.
1220  * All inode fields are set up by caller, we just traverse the btree
1221  * and copy the records in. If the file system cannot contain unwritten
1222  * extents, the records are checked for no "state" flags.
1223  */
1224 int                                     /* error */
1225 xfs_bmap_read_extents(
1226         xfs_trans_t             *tp,    /* transaction pointer */
1227         xfs_inode_t             *ip,    /* incore inode */
1228         int                     whichfork) /* data or attr fork */
1229 {
1230         struct xfs_btree_block  *block; /* current btree block */
1231         xfs_fsblock_t           bno;    /* block # of "block" */
1232         xfs_buf_t               *bp;    /* buffer for "block" */
1233         int                     error;  /* error return value */
1234         xfs_extnum_t            i, j;   /* index into the extents list */
1235         xfs_ifork_t             *ifp;   /* fork structure */
1236         int                     level;  /* btree level, for checking */
1237         xfs_mount_t             *mp;    /* file system mount structure */
1238         __be64                  *pp;    /* pointer to block address */
1239         /* REFERENCED */
1240         xfs_extnum_t            room;   /* number of entries there's room for */
1241
1242         mp = ip->i_mount;
1243         ifp = XFS_IFORK_PTR(ip, whichfork);
1244         block = ifp->if_broot;
1245         /*
1246          * Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out.
1247          */
1248         level = be16_to_cpu(block->bb_level);
1249         ASSERT(level > 0);
1250         pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, 1, ifp->if_broot_bytes);
1251         bno = be64_to_cpu(*pp);
1252
1253         /*
1254          * Go down the tree until leaf level is reached, following the first
1255          * pointer (leftmost) at each level.
1256          */
1257         while (level-- > 0) {
1258                 error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp,
1259                                 XFS_BMAP_BTREE_REF, &xfs_bmbt_buf_ops);
1260                 if (error)
1261                         return error;
1262                 block = XFS_BUF_TO_BLOCK(bp);
1263                 if (level == 0)
1264                         break;
1265                 pp = XFS_BMBT_PTR_ADDR(mp, block, 1, mp->m_bmap_dmxr[1]);
1266                 bno = be64_to_cpu(*pp);
1267                 XFS_WANT_CORRUPTED_GOTO(mp,
1268                         XFS_FSB_SANITY_CHECK(mp, bno), error0);
1269                 xfs_trans_brelse(tp, bp);
1270         }
1271         /*
1272          * Here with bp and block set to the leftmost leaf node in the tree.
1273          */
1274         room = xfs_iext_count(ifp);
1275         i = 0;
1276         /*
1277          * Loop over all leaf nodes.  Copy information to the extent records.
1278          */
1279         for (;;) {
1280                 xfs_bmbt_rec_t  *frp;
1281                 xfs_fsblock_t   nextbno;
1282                 xfs_extnum_t    num_recs;
1283
1284                 num_recs = xfs_btree_get_numrecs(block);
1285                 if (unlikely(i + num_recs > room)) {
1286                         ASSERT(i + num_recs <= room);
1287                         xfs_warn(ip->i_mount,
1288                                 "corrupt dinode %Lu, (btree extents).",
1289                                 (unsigned long long) ip->i_ino);
1290                         XFS_CORRUPTION_ERROR("xfs_bmap_read_extents(1)",
1291                                 XFS_ERRLEVEL_LOW, ip->i_mount, block);
1292                         goto error0;
1293                 }
1294                 /*
1295                  * Read-ahead the next leaf block, if any.
1296                  */
1297                 nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib);
1298                 if (nextbno != NULLFSBLOCK)
1299                         xfs_btree_reada_bufl(mp, nextbno, 1,
1300                                              &xfs_bmbt_buf_ops);
1301                 /*
1302                  * Copy records into the extent records.
1303                  */
1304                 frp = XFS_BMBT_REC_ADDR(mp, block, 1);
1305                 for (j = 0; j < num_recs; j++, i++, frp++) {
1306                         xfs_bmbt_rec_host_t *trp = xfs_iext_get_ext(ifp, i);
1307                         trp->l0 = be64_to_cpu(frp->l0);
1308                         trp->l1 = be64_to_cpu(frp->l1);
1309                         if (!xfs_bmbt_validate_extent(mp, whichfork, trp)) {
1310                                 XFS_ERROR_REPORT("xfs_bmap_read_extents(2)",
1311                                                  XFS_ERRLEVEL_LOW, mp);
1312                                 goto error0;
1313                         }
1314                 }
1315                 xfs_trans_brelse(tp, bp);
1316                 bno = nextbno;
1317                 /*
1318                  * If we've reached the end, stop.
1319                  */
1320                 if (bno == NULLFSBLOCK)
1321                         break;
1322                 error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp,
1323                                 XFS_BMAP_BTREE_REF, &xfs_bmbt_buf_ops);
1324                 if (error)
1325                         return error;
1326                 block = XFS_BUF_TO_BLOCK(bp);
1327         }
1328         if (i != XFS_IFORK_NEXTENTS(ip, whichfork))
1329                 return -EFSCORRUPTED;
1330         ASSERT(i == xfs_iext_count(ifp));
1331         XFS_BMAP_TRACE_EXLIST(ip, i, whichfork);
1332         return 0;
1333 error0:
1334         xfs_trans_brelse(tp, bp);
1335         return -EFSCORRUPTED;
1336 }
1337
1338 /*
1339  * Returns the file-relative block number of the first unused block(s)
1340  * in the file with at least "len" logically contiguous blocks free.
1341  * This is the lowest-address hole if the file has holes, else the first block
1342  * past the end of file.
1343  * Return 0 if the file is currently local (in-inode).
1344  */
1345 int                                             /* error */
1346 xfs_bmap_first_unused(
1347         xfs_trans_t     *tp,                    /* transaction pointer */
1348         xfs_inode_t     *ip,                    /* incore inode */
1349         xfs_extlen_t    len,                    /* size of hole to find */
1350         xfs_fileoff_t   *first_unused,          /* unused block */
1351         int             whichfork)              /* data or attr fork */
1352 {
1353         int             error;                  /* error return value */
1354         int             idx;                    /* extent record index */
1355         xfs_ifork_t     *ifp;                   /* inode fork pointer */
1356         xfs_fileoff_t   lastaddr;               /* last block number seen */
1357         xfs_fileoff_t   lowest;                 /* lowest useful block */
1358         xfs_fileoff_t   max;                    /* starting useful block */
1359         xfs_fileoff_t   off;                    /* offset for this block */
1360         xfs_extnum_t    nextents;               /* number of extent entries */
1361
1362         ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE ||
1363                XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS ||
1364                XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL);
1365         if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) {
1366                 *first_unused = 0;
1367                 return 0;
1368         }
1369         ifp = XFS_IFORK_PTR(ip, whichfork);
1370         if (!(ifp->if_flags & XFS_IFEXTENTS) &&
1371             (error = xfs_iread_extents(tp, ip, whichfork)))
1372                 return error;
1373         lowest = *first_unused;
1374         nextents = xfs_iext_count(ifp);
1375         for (idx = 0, lastaddr = 0, max = lowest; idx < nextents; idx++) {
1376                 xfs_bmbt_rec_host_t *ep = xfs_iext_get_ext(ifp, idx);
1377                 off = xfs_bmbt_get_startoff(ep);
1378                 /*
1379                  * See if the hole before this extent will work.
1380                  */
1381                 if (off >= lowest + len && off - max >= len) {
1382                         *first_unused = max;
1383                         return 0;
1384                 }
1385                 lastaddr = off + xfs_bmbt_get_blockcount(ep);
1386                 max = XFS_FILEOFF_MAX(lastaddr, lowest);
1387         }
1388         *first_unused = max;
1389         return 0;
1390 }
1391
1392 /*
1393  * Returns the file-relative block number of the last block - 1 before
1394  * last_block (input value) in the file.
1395  * This is not based on i_size, it is based on the extent records.
1396  * Returns 0 for local files, as they do not have extent records.
1397  */
1398 int                                             /* error */
1399 xfs_bmap_last_before(
1400         struct xfs_trans        *tp,            /* transaction pointer */
1401         struct xfs_inode        *ip,            /* incore inode */
1402         xfs_fileoff_t           *last_block,    /* last block */
1403         int                     whichfork)      /* data or attr fork */
1404 {
1405         struct xfs_ifork        *ifp = XFS_IFORK_PTR(ip, whichfork);
1406         struct xfs_bmbt_irec    got;
1407         xfs_extnum_t            idx;
1408         int                     error;
1409
1410         switch (XFS_IFORK_FORMAT(ip, whichfork)) {
1411         case XFS_DINODE_FMT_LOCAL:
1412                 *last_block = 0;
1413                 return 0;
1414         case XFS_DINODE_FMT_BTREE:
1415         case XFS_DINODE_FMT_EXTENTS:
1416                 break;
1417         default:
1418                 return -EIO;
1419         }
1420
1421         if (!(ifp->if_flags & XFS_IFEXTENTS)) {
1422                 error = xfs_iread_extents(tp, ip, whichfork);
1423                 if (error)
1424                         return error;
1425         }
1426
1427         if (xfs_iext_lookup_extent(ip, ifp, *last_block - 1, &idx, &got)) {
1428                 if (got.br_startoff <= *last_block - 1)
1429                         return 0;
1430         }
1431
1432         if (xfs_iext_get_extent(ifp, idx - 1, &got)) {
1433                 *last_block = got.br_startoff + got.br_blockcount;
1434                 return 0;
1435         }
1436
1437         *last_block = 0;
1438         return 0;
1439 }
1440
1441 int
1442 xfs_bmap_last_extent(
1443         struct xfs_trans        *tp,
1444         struct xfs_inode        *ip,
1445         int                     whichfork,
1446         struct xfs_bmbt_irec    *rec,
1447         int                     *is_empty)
1448 {
1449         struct xfs_ifork        *ifp = XFS_IFORK_PTR(ip, whichfork);
1450         int                     error;
1451         int                     nextents;
1452
1453         if (!(ifp->if_flags & XFS_IFEXTENTS)) {
1454                 error = xfs_iread_extents(tp, ip, whichfork);
1455                 if (error)
1456                         return error;
1457         }
1458
1459         nextents = xfs_iext_count(ifp);
1460         if (nextents == 0) {
1461                 *is_empty = 1;
1462                 return 0;
1463         }
1464
1465         xfs_bmbt_get_all(xfs_iext_get_ext(ifp, nextents - 1), rec);
1466         *is_empty = 0;
1467         return 0;
1468 }
1469
1470 /*
1471  * Check the last inode extent to determine whether this allocation will result
1472  * in blocks being allocated at the end of the file. When we allocate new data
1473  * blocks at the end of the file which do not start at the previous data block,
1474  * we will try to align the new blocks at stripe unit boundaries.
1475  *
1476  * Returns 1 in bma->aeof if the file (fork) is empty as any new write will be
1477  * at, or past the EOF.
1478  */
1479 STATIC int
1480 xfs_bmap_isaeof(
1481         struct xfs_bmalloca     *bma,
1482         int                     whichfork)
1483 {
1484         struct xfs_bmbt_irec    rec;
1485         int                     is_empty;
1486         int                     error;
1487
1488         bma->aeof = 0;
1489         error = xfs_bmap_last_extent(NULL, bma->ip, whichfork, &rec,
1490                                      &is_empty);
1491         if (error)
1492                 return error;
1493
1494         if (is_empty) {
1495                 bma->aeof = 1;
1496                 return 0;
1497         }
1498
1499         /*
1500          * Check if we are allocation or past the last extent, or at least into
1501          * the last delayed allocated extent.
1502          */
1503         bma->aeof = bma->offset >= rec.br_startoff + rec.br_blockcount ||
1504                 (bma->offset >= rec.br_startoff &&
1505                  isnullstartblock(rec.br_startblock));
1506         return 0;
1507 }
1508
1509 /*
1510  * Returns the file-relative block number of the first block past eof in
1511  * the file.  This is not based on i_size, it is based on the extent records.
1512  * Returns 0 for local files, as they do not have extent records.
1513  */
1514 int
1515 xfs_bmap_last_offset(
1516         struct xfs_inode        *ip,
1517         xfs_fileoff_t           *last_block,
1518         int                     whichfork)
1519 {
1520         struct xfs_bmbt_irec    rec;
1521         int                     is_empty;
1522         int                     error;
1523
1524         *last_block = 0;
1525
1526         if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL)
1527                 return 0;
1528
1529         if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE &&
1530             XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
1531                return -EIO;
1532
1533         error = xfs_bmap_last_extent(NULL, ip, whichfork, &rec, &is_empty);
1534         if (error || is_empty)
1535                 return error;
1536
1537         *last_block = rec.br_startoff + rec.br_blockcount;
1538         return 0;
1539 }
1540
1541 /*
1542  * Returns whether the selected fork of the inode has exactly one
1543  * block or not.  For the data fork we check this matches di_size,
1544  * implying the file's range is 0..bsize-1.
1545  */
1546 int                                     /* 1=>1 block, 0=>otherwise */
1547 xfs_bmap_one_block(
1548         xfs_inode_t     *ip,            /* incore inode */
1549         int             whichfork)      /* data or attr fork */
1550 {
1551         xfs_bmbt_rec_host_t *ep;        /* ptr to fork's extent */
1552         xfs_ifork_t     *ifp;           /* inode fork pointer */
1553         int             rval;           /* return value */
1554         xfs_bmbt_irec_t s;              /* internal version of extent */
1555
1556 #ifndef DEBUG
1557         if (whichfork == XFS_DATA_FORK)
1558                 return XFS_ISIZE(ip) == ip->i_mount->m_sb.sb_blocksize;
1559 #endif  /* !DEBUG */
1560         if (XFS_IFORK_NEXTENTS(ip, whichfork) != 1)
1561                 return 0;
1562         if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
1563                 return 0;
1564         ifp = XFS_IFORK_PTR(ip, whichfork);
1565         ASSERT(ifp->if_flags & XFS_IFEXTENTS);
1566         ep = xfs_iext_get_ext(ifp, 0);
1567         xfs_bmbt_get_all(ep, &s);
1568         rval = s.br_startoff == 0 && s.br_blockcount == 1;
1569         if (rval && whichfork == XFS_DATA_FORK)
1570                 ASSERT(XFS_ISIZE(ip) == ip->i_mount->m_sb.sb_blocksize);
1571         return rval;
1572 }
1573
1574 /*
1575  * Extent tree manipulation functions used during allocation.
1576  */
1577
1578 /*
1579  * Convert a delayed allocation to a real allocation.
1580  */
1581 STATIC int                              /* error */
1582 xfs_bmap_add_extent_delay_real(
1583         struct xfs_bmalloca     *bma,
1584         int                     whichfork)
1585 {
1586         struct xfs_bmbt_irec    *new = &bma->got;
1587         int                     diff;   /* temp value */
1588         xfs_bmbt_rec_host_t     *ep;    /* extent entry for idx */
1589         int                     error;  /* error return value */
1590         int                     i;      /* temp state */
1591         xfs_ifork_t             *ifp;   /* inode fork pointer */
1592         xfs_fileoff_t           new_endoff;     /* end offset of new entry */
1593         xfs_bmbt_irec_t         r[3];   /* neighbor extent entries */
1594                                         /* left is 0, right is 1, prev is 2 */
1595         int                     rval=0; /* return value (logging flags) */
1596         int                     state = 0;/* state bits, accessed thru macros */
1597         xfs_filblks_t           da_new; /* new count del alloc blocks used */
1598         xfs_filblks_t           da_old; /* old count del alloc blocks used */
1599         xfs_filblks_t           temp=0; /* value for da_new calculations */
1600         xfs_filblks_t           temp2=0;/* value for da_new calculations */
1601         int                     tmp_rval;       /* partial logging flags */
1602         struct xfs_mount        *mp;
1603         xfs_extnum_t            *nextents;
1604
1605         mp = bma->ip->i_mount;
1606         ifp = XFS_IFORK_PTR(bma->ip, whichfork);
1607         ASSERT(whichfork != XFS_ATTR_FORK);
1608         nextents = (whichfork == XFS_COW_FORK ? &bma->ip->i_cnextents :
1609                                                 &bma->ip->i_d.di_nextents);
1610
1611         ASSERT(bma->idx >= 0);
1612         ASSERT(bma->idx <= xfs_iext_count(ifp));
1613         ASSERT(!isnullstartblock(new->br_startblock));
1614         ASSERT(!bma->cur ||
1615                (bma->cur->bc_private.b.flags & XFS_BTCUR_BPRV_WASDEL));
1616
1617         XFS_STATS_INC(mp, xs_add_exlist);
1618
1619 #define LEFT            r[0]
1620 #define RIGHT           r[1]
1621 #define PREV            r[2]
1622
1623         if (whichfork == XFS_COW_FORK)
1624                 state |= BMAP_COWFORK;
1625
1626         /*
1627          * Set up a bunch of variables to make the tests simpler.
1628          */
1629         ep = xfs_iext_get_ext(ifp, bma->idx);
1630         xfs_bmbt_get_all(ep, &PREV);
1631         new_endoff = new->br_startoff + new->br_blockcount;
1632         ASSERT(PREV.br_startoff <= new->br_startoff);
1633         ASSERT(PREV.br_startoff + PREV.br_blockcount >= new_endoff);
1634
1635         da_old = startblockval(PREV.br_startblock);
1636         da_new = 0;
1637
1638         /*
1639          * Set flags determining what part of the previous delayed allocation
1640          * extent is being replaced by a real allocation.
1641          */
1642         if (PREV.br_startoff == new->br_startoff)
1643                 state |= BMAP_LEFT_FILLING;
1644         if (PREV.br_startoff + PREV.br_blockcount == new_endoff)
1645                 state |= BMAP_RIGHT_FILLING;
1646
1647         /*
1648          * Check and set flags if this segment has a left neighbor.
1649          * Don't set contiguous if the combined extent would be too large.
1650          */
1651         if (bma->idx > 0) {
1652                 state |= BMAP_LEFT_VALID;
1653                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx - 1), &LEFT);
1654
1655                 if (isnullstartblock(LEFT.br_startblock))
1656                         state |= BMAP_LEFT_DELAY;
1657         }
1658
1659         if ((state & BMAP_LEFT_VALID) && !(state & BMAP_LEFT_DELAY) &&
1660             LEFT.br_startoff + LEFT.br_blockcount == new->br_startoff &&
1661             LEFT.br_startblock + LEFT.br_blockcount == new->br_startblock &&
1662             LEFT.br_state == new->br_state &&
1663             LEFT.br_blockcount + new->br_blockcount <= MAXEXTLEN)
1664                 state |= BMAP_LEFT_CONTIG;
1665
1666         /*
1667          * Check and set flags if this segment has a right neighbor.
1668          * Don't set contiguous if the combined extent would be too large.
1669          * Also check for all-three-contiguous being too large.
1670          */
1671         if (bma->idx < xfs_iext_count(ifp) - 1) {
1672                 state |= BMAP_RIGHT_VALID;
1673                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx + 1), &RIGHT);
1674
1675                 if (isnullstartblock(RIGHT.br_startblock))
1676                         state |= BMAP_RIGHT_DELAY;
1677         }
1678
1679         if ((state & BMAP_RIGHT_VALID) && !(state & BMAP_RIGHT_DELAY) &&
1680             new_endoff == RIGHT.br_startoff &&
1681             new->br_startblock + new->br_blockcount == RIGHT.br_startblock &&
1682             new->br_state == RIGHT.br_state &&
1683             new->br_blockcount + RIGHT.br_blockcount <= MAXEXTLEN &&
1684             ((state & (BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING |
1685                        BMAP_RIGHT_FILLING)) !=
1686                       (BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING |
1687                        BMAP_RIGHT_FILLING) ||
1688              LEFT.br_blockcount + new->br_blockcount + RIGHT.br_blockcount
1689                         <= MAXEXTLEN))
1690                 state |= BMAP_RIGHT_CONTIG;
1691
1692         error = 0;
1693         /*
1694          * Switch out based on the FILLING and CONTIG state bits.
1695          */
1696         switch (state & (BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG |
1697                          BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG)) {
1698         case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG |
1699              BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
1700                 /*
1701                  * Filling in all of a previously delayed allocation extent.
1702                  * The left and right neighbors are both contiguous with new.
1703                  */
1704                 bma->idx--;
1705                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
1706                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx),
1707                         LEFT.br_blockcount + PREV.br_blockcount +
1708                         RIGHT.br_blockcount);
1709                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
1710
1711                 xfs_iext_remove(bma->ip, bma->idx + 1, 2, state);
1712                 (*nextents)--;
1713                 if (bma->cur == NULL)
1714                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
1715                 else {
1716                         rval = XFS_ILOG_CORE;
1717                         error = xfs_bmbt_lookup_eq(bma->cur, RIGHT.br_startoff,
1718                                         RIGHT.br_startblock,
1719                                         RIGHT.br_blockcount, &i);
1720                         if (error)
1721                                 goto done;
1722                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1723                         error = xfs_btree_delete(bma->cur, &i);
1724                         if (error)
1725                                 goto done;
1726                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1727                         error = xfs_btree_decrement(bma->cur, 0, &i);
1728                         if (error)
1729                                 goto done;
1730                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1731                         error = xfs_bmbt_update(bma->cur, LEFT.br_startoff,
1732                                         LEFT.br_startblock,
1733                                         LEFT.br_blockcount +
1734                                         PREV.br_blockcount +
1735                                         RIGHT.br_blockcount, LEFT.br_state);
1736                         if (error)
1737                                 goto done;
1738                 }
1739                 break;
1740
1741         case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG:
1742                 /*
1743                  * Filling in all of a previously delayed allocation extent.
1744                  * The left neighbor is contiguous, the right is not.
1745                  */
1746                 bma->idx--;
1747
1748                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
1749                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx),
1750                         LEFT.br_blockcount + PREV.br_blockcount);
1751                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
1752
1753                 xfs_iext_remove(bma->ip, bma->idx + 1, 1, state);
1754                 if (bma->cur == NULL)
1755                         rval = XFS_ILOG_DEXT;
1756                 else {
1757                         rval = 0;
1758                         error = xfs_bmbt_lookup_eq(bma->cur, LEFT.br_startoff,
1759                                         LEFT.br_startblock, LEFT.br_blockcount,
1760                                         &i);
1761                         if (error)
1762                                 goto done;
1763                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1764                         error = xfs_bmbt_update(bma->cur, LEFT.br_startoff,
1765                                         LEFT.br_startblock,
1766                                         LEFT.br_blockcount +
1767                                         PREV.br_blockcount, LEFT.br_state);
1768                         if (error)
1769                                 goto done;
1770                 }
1771                 break;
1772
1773         case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
1774                 /*
1775                  * Filling in all of a previously delayed allocation extent.
1776                  * The right neighbor is contiguous, the left is not.
1777                  */
1778                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
1779                 xfs_bmbt_set_startblock(ep, new->br_startblock);
1780                 xfs_bmbt_set_blockcount(ep,
1781                         PREV.br_blockcount + RIGHT.br_blockcount);
1782                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
1783
1784                 xfs_iext_remove(bma->ip, bma->idx + 1, 1, state);
1785                 if (bma->cur == NULL)
1786                         rval = XFS_ILOG_DEXT;
1787                 else {
1788                         rval = 0;
1789                         error = xfs_bmbt_lookup_eq(bma->cur, RIGHT.br_startoff,
1790                                         RIGHT.br_startblock,
1791                                         RIGHT.br_blockcount, &i);
1792                         if (error)
1793                                 goto done;
1794                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1795                         error = xfs_bmbt_update(bma->cur, PREV.br_startoff,
1796                                         new->br_startblock,
1797                                         PREV.br_blockcount +
1798                                         RIGHT.br_blockcount, PREV.br_state);
1799                         if (error)
1800                                 goto done;
1801                 }
1802                 break;
1803
1804         case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING:
1805                 /*
1806                  * Filling in all of a previously delayed allocation extent.
1807                  * Neither the left nor right neighbors are contiguous with
1808                  * the new one.
1809                  */
1810                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
1811                 xfs_bmbt_set_startblock(ep, new->br_startblock);
1812                 xfs_bmbt_set_state(ep, new->br_state);
1813                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
1814
1815                 (*nextents)++;
1816                 if (bma->cur == NULL)
1817                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
1818                 else {
1819                         rval = XFS_ILOG_CORE;
1820                         error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff,
1821                                         new->br_startblock, new->br_blockcount,
1822                                         &i);
1823                         if (error)
1824                                 goto done;
1825                         XFS_WANT_CORRUPTED_GOTO(mp, i == 0, done);
1826                         bma->cur->bc_rec.b.br_state = XFS_EXT_NORM;
1827                         error = xfs_btree_insert(bma->cur, &i);
1828                         if (error)
1829                                 goto done;
1830                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1831                 }
1832                 break;
1833
1834         case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG:
1835                 /*
1836                  * Filling in the first part of a previous delayed allocation.
1837                  * The left neighbor is contiguous.
1838                  */
1839                 trace_xfs_bmap_pre_update(bma->ip, bma->idx - 1, state, _THIS_IP_);
1840                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx - 1),
1841                         LEFT.br_blockcount + new->br_blockcount);
1842                 xfs_bmbt_set_startoff(ep,
1843                         PREV.br_startoff + new->br_blockcount);
1844                 trace_xfs_bmap_post_update(bma->ip, bma->idx - 1, state, _THIS_IP_);
1845
1846                 temp = PREV.br_blockcount - new->br_blockcount;
1847                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
1848                 xfs_bmbt_set_blockcount(ep, temp);
1849                 if (bma->cur == NULL)
1850                         rval = XFS_ILOG_DEXT;
1851                 else {
1852                         rval = 0;
1853                         error = xfs_bmbt_lookup_eq(bma->cur, LEFT.br_startoff,
1854                                         LEFT.br_startblock, LEFT.br_blockcount,
1855                                         &i);
1856                         if (error)
1857                                 goto done;
1858                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1859                         error = xfs_bmbt_update(bma->cur, LEFT.br_startoff,
1860                                         LEFT.br_startblock,
1861                                         LEFT.br_blockcount +
1862                                         new->br_blockcount,
1863                                         LEFT.br_state);
1864                         if (error)
1865                                 goto done;
1866                 }
1867                 da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp),
1868                         startblockval(PREV.br_startblock));
1869                 xfs_bmbt_set_startblock(ep, nullstartblock(da_new));
1870                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
1871
1872                 bma->idx--;
1873                 break;
1874
1875         case BMAP_LEFT_FILLING:
1876                 /*
1877                  * Filling in the first part of a previous delayed allocation.
1878                  * The left neighbor is not contiguous.
1879                  */
1880                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
1881                 xfs_bmbt_set_startoff(ep, new_endoff);
1882                 temp = PREV.br_blockcount - new->br_blockcount;
1883                 xfs_bmbt_set_blockcount(ep, temp);
1884                 xfs_iext_insert(bma->ip, bma->idx, 1, new, state);
1885                 (*nextents)++;
1886                 if (bma->cur == NULL)
1887                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
1888                 else {
1889                         rval = XFS_ILOG_CORE;
1890                         error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff,
1891                                         new->br_startblock, new->br_blockcount,
1892                                         &i);
1893                         if (error)
1894                                 goto done;
1895                         XFS_WANT_CORRUPTED_GOTO(mp, i == 0, done);
1896                         bma->cur->bc_rec.b.br_state = XFS_EXT_NORM;
1897                         error = xfs_btree_insert(bma->cur, &i);
1898                         if (error)
1899                                 goto done;
1900                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1901                 }
1902
1903                 if (xfs_bmap_needs_btree(bma->ip, whichfork)) {
1904                         error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
1905                                         bma->firstblock, bma->dfops,
1906                                         &bma->cur, 1, &tmp_rval, whichfork);
1907                         rval |= tmp_rval;
1908                         if (error)
1909                                 goto done;
1910                 }
1911                 da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp),
1912                         startblockval(PREV.br_startblock) -
1913                         (bma->cur ? bma->cur->bc_private.b.allocated : 0));
1914                 ep = xfs_iext_get_ext(ifp, bma->idx + 1);
1915                 xfs_bmbt_set_startblock(ep, nullstartblock(da_new));
1916                 trace_xfs_bmap_post_update(bma->ip, bma->idx + 1, state, _THIS_IP_);
1917                 break;
1918
1919         case BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
1920                 /*
1921                  * Filling in the last part of a previous delayed allocation.
1922                  * The right neighbor is contiguous with the new allocation.
1923                  */
1924                 temp = PREV.br_blockcount - new->br_blockcount;
1925                 trace_xfs_bmap_pre_update(bma->ip, bma->idx + 1, state, _THIS_IP_);
1926                 xfs_bmbt_set_blockcount(ep, temp);
1927                 xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, bma->idx + 1),
1928                         new->br_startoff, new->br_startblock,
1929                         new->br_blockcount + RIGHT.br_blockcount,
1930                         RIGHT.br_state);
1931                 trace_xfs_bmap_post_update(bma->ip, bma->idx + 1, state, _THIS_IP_);
1932                 if (bma->cur == NULL)
1933                         rval = XFS_ILOG_DEXT;
1934                 else {
1935                         rval = 0;
1936                         error = xfs_bmbt_lookup_eq(bma->cur, RIGHT.br_startoff,
1937                                         RIGHT.br_startblock,
1938                                         RIGHT.br_blockcount, &i);
1939                         if (error)
1940                                 goto done;
1941                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1942                         error = xfs_bmbt_update(bma->cur, new->br_startoff,
1943                                         new->br_startblock,
1944                                         new->br_blockcount +
1945                                         RIGHT.br_blockcount,
1946                                         RIGHT.br_state);
1947                         if (error)
1948                                 goto done;
1949                 }
1950
1951                 da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp),
1952                         startblockval(PREV.br_startblock));
1953                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
1954                 xfs_bmbt_set_startblock(ep, nullstartblock(da_new));
1955                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
1956
1957                 bma->idx++;
1958                 break;
1959
1960         case BMAP_RIGHT_FILLING:
1961                 /*
1962                  * Filling in the last part of a previous delayed allocation.
1963                  * The right neighbor is not contiguous.
1964                  */
1965                 temp = PREV.br_blockcount - new->br_blockcount;
1966                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
1967                 xfs_bmbt_set_blockcount(ep, temp);
1968                 xfs_iext_insert(bma->ip, bma->idx + 1, 1, new, state);
1969                 (*nextents)++;
1970                 if (bma->cur == NULL)
1971                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
1972                 else {
1973                         rval = XFS_ILOG_CORE;
1974                         error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff,
1975                                         new->br_startblock, new->br_blockcount,
1976                                         &i);
1977                         if (error)
1978                                 goto done;
1979                         XFS_WANT_CORRUPTED_GOTO(mp, i == 0, done);
1980                         bma->cur->bc_rec.b.br_state = XFS_EXT_NORM;
1981                         error = xfs_btree_insert(bma->cur, &i);
1982                         if (error)
1983                                 goto done;
1984                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1985                 }
1986
1987                 if (xfs_bmap_needs_btree(bma->ip, whichfork)) {
1988                         error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
1989                                 bma->firstblock, bma->dfops, &bma->cur, 1,
1990                                 &tmp_rval, whichfork);
1991                         rval |= tmp_rval;
1992                         if (error)
1993                                 goto done;
1994                 }
1995                 da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp),
1996                         startblockval(PREV.br_startblock) -
1997                         (bma->cur ? bma->cur->bc_private.b.allocated : 0));
1998                 ep = xfs_iext_get_ext(ifp, bma->idx);
1999                 xfs_bmbt_set_startblock(ep, nullstartblock(da_new));
2000                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
2001
2002                 bma->idx++;
2003                 break;
2004
2005         case 0:
2006                 /*
2007                  * Filling in the middle part of a previous delayed allocation.
2008                  * Contiguity is impossible here.
2009                  * This case is avoided almost all the time.
2010                  *
2011                  * We start with a delayed allocation:
2012                  *
2013                  * +ddddddddddddddddddddddddddddddddddddddddddddddddddddddd+
2014                  *  PREV @ idx
2015                  *
2016                  * and we are allocating:
2017                  *                     +rrrrrrrrrrrrrrrrr+
2018                  *                            new
2019                  *
2020                  * and we set it up for insertion as:
2021                  * +ddddddddddddddddddd+rrrrrrrrrrrrrrrrr+ddddddddddddddddd+
2022                  *                            new
2023                  *  PREV @ idx          LEFT              RIGHT
2024                  *                      inserted at idx + 1
2025                  */
2026                 temp = new->br_startoff - PREV.br_startoff;
2027                 temp2 = PREV.br_startoff + PREV.br_blockcount - new_endoff;
2028                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, 0, _THIS_IP_);
2029                 xfs_bmbt_set_blockcount(ep, temp);      /* truncate PREV */
2030                 LEFT = *new;
2031                 RIGHT.br_state = PREV.br_state;
2032                 RIGHT.br_startblock = nullstartblock(
2033                                 (int)xfs_bmap_worst_indlen(bma->ip, temp2));
2034                 RIGHT.br_startoff = new_endoff;
2035                 RIGHT.br_blockcount = temp2;
2036                 /* insert LEFT (r[0]) and RIGHT (r[1]) at the same time */
2037                 xfs_iext_insert(bma->ip, bma->idx + 1, 2, &LEFT, state);
2038                 (*nextents)++;
2039                 if (bma->cur == NULL)
2040                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
2041                 else {
2042                         rval = XFS_ILOG_CORE;
2043                         error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff,
2044                                         new->br_startblock, new->br_blockcount,
2045                                         &i);
2046                         if (error)
2047                                 goto done;
2048                         XFS_WANT_CORRUPTED_GOTO(mp, i == 0, done);
2049                         bma->cur->bc_rec.b.br_state = XFS_EXT_NORM;
2050                         error = xfs_btree_insert(bma->cur, &i);
2051                         if (error)
2052                                 goto done;
2053                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2054                 }
2055
2056                 if (xfs_bmap_needs_btree(bma->ip, whichfork)) {
2057                         error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
2058                                         bma->firstblock, bma->dfops, &bma->cur,
2059                                         1, &tmp_rval, whichfork);
2060                         rval |= tmp_rval;
2061                         if (error)
2062                                 goto done;
2063                 }
2064                 temp = xfs_bmap_worst_indlen(bma->ip, temp);
2065                 temp2 = xfs_bmap_worst_indlen(bma->ip, temp2);
2066                 diff = (int)(temp + temp2 -
2067                              (startblockval(PREV.br_startblock) -
2068                               (bma->cur ?
2069                                bma->cur->bc_private.b.allocated : 0)));
2070                 if (diff > 0) {
2071                         error = xfs_mod_fdblocks(bma->ip->i_mount,
2072                                                  -((int64_t)diff), false);
2073                         ASSERT(!error);
2074                         if (error)
2075                                 goto done;
2076                 }
2077
2078                 ep = xfs_iext_get_ext(ifp, bma->idx);
2079                 xfs_bmbt_set_startblock(ep, nullstartblock((int)temp));
2080                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
2081                 trace_xfs_bmap_pre_update(bma->ip, bma->idx + 2, state, _THIS_IP_);
2082                 xfs_bmbt_set_startblock(xfs_iext_get_ext(ifp, bma->idx + 2),
2083                         nullstartblock((int)temp2));
2084                 trace_xfs_bmap_post_update(bma->ip, bma->idx + 2, state, _THIS_IP_);
2085
2086                 bma->idx++;
2087                 da_new = temp + temp2;
2088                 break;
2089
2090         case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
2091         case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
2092         case BMAP_LEFT_FILLING | BMAP_RIGHT_CONTIG:
2093         case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG:
2094         case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
2095         case BMAP_LEFT_CONTIG:
2096         case BMAP_RIGHT_CONTIG:
2097                 /*
2098                  * These cases are all impossible.
2099                  */
2100                 ASSERT(0);
2101         }
2102
2103         /* add reverse mapping */
2104         error = xfs_rmap_map_extent(mp, bma->dfops, bma->ip, whichfork, new);
2105         if (error)
2106                 goto done;
2107
2108         /* convert to a btree if necessary */
2109         if (xfs_bmap_needs_btree(bma->ip, whichfork)) {
2110                 int     tmp_logflags;   /* partial log flag return val */
2111
2112                 ASSERT(bma->cur == NULL);
2113                 error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
2114                                 bma->firstblock, bma->dfops, &bma->cur,
2115                                 da_old > 0, &tmp_logflags, whichfork);
2116                 bma->logflags |= tmp_logflags;
2117                 if (error)
2118                         goto done;
2119         }
2120
2121         /* adjust for changes in reserved delayed indirect blocks */
2122         if (da_old || da_new) {
2123                 temp = da_new;
2124                 if (bma->cur)
2125                         temp += bma->cur->bc_private.b.allocated;
2126                 if (temp < da_old)
2127                         xfs_mod_fdblocks(bma->ip->i_mount,
2128                                         (int64_t)(da_old - temp), false);
2129         }
2130
2131         /* clear out the allocated field, done with it now in any case. */
2132         if (bma->cur)
2133                 bma->cur->bc_private.b.allocated = 0;
2134
2135         xfs_bmap_check_leaf_extents(bma->cur, bma->ip, whichfork);
2136 done:
2137         if (whichfork != XFS_COW_FORK)
2138                 bma->logflags |= rval;
2139         return error;
2140 #undef  LEFT
2141 #undef  RIGHT
2142 #undef  PREV
2143 }
2144
2145 /*
2146  * Convert an unwritten allocation to a real allocation or vice versa.
2147  */
2148 STATIC int                              /* error */
2149 xfs_bmap_add_extent_unwritten_real(
2150         struct xfs_trans        *tp,
2151         xfs_inode_t             *ip,    /* incore inode pointer */
2152         int                     whichfork,
2153         xfs_extnum_t            *idx,   /* extent number to update/insert */
2154         xfs_btree_cur_t         **curp, /* if *curp is null, not a btree */
2155         xfs_bmbt_irec_t         *new,   /* new data to add to file extents */
2156         xfs_fsblock_t           *first, /* pointer to firstblock variable */
2157         struct xfs_defer_ops    *dfops, /* list of extents to be freed */
2158         int                     *logflagsp) /* inode logging flags */
2159 {
2160         xfs_btree_cur_t         *cur;   /* btree cursor */
2161         xfs_bmbt_rec_host_t     *ep;    /* extent entry for idx */
2162         int                     error;  /* error return value */
2163         int                     i;      /* temp state */
2164         xfs_ifork_t             *ifp;   /* inode fork pointer */
2165         xfs_fileoff_t           new_endoff;     /* end offset of new entry */
2166         xfs_exntst_t            newext; /* new extent state */
2167         xfs_exntst_t            oldext; /* old extent state */
2168         xfs_bmbt_irec_t         r[3];   /* neighbor extent entries */
2169                                         /* left is 0, right is 1, prev is 2 */
2170         int                     rval=0; /* return value (logging flags) */
2171         int                     state = 0;/* state bits, accessed thru macros */
2172         struct xfs_mount        *mp = ip->i_mount;
2173
2174         *logflagsp = 0;
2175
2176         cur = *curp;
2177         ifp = XFS_IFORK_PTR(ip, whichfork);
2178         if (whichfork == XFS_COW_FORK)
2179                 state |= BMAP_COWFORK;
2180
2181         ASSERT(*idx >= 0);
2182         ASSERT(*idx <= xfs_iext_count(ifp));
2183         ASSERT(!isnullstartblock(new->br_startblock));
2184
2185         XFS_STATS_INC(mp, xs_add_exlist);
2186
2187 #define LEFT            r[0]
2188 #define RIGHT           r[1]
2189 #define PREV            r[2]
2190
2191         /*
2192          * Set up a bunch of variables to make the tests simpler.
2193          */
2194         error = 0;
2195         ep = xfs_iext_get_ext(ifp, *idx);
2196         xfs_bmbt_get_all(ep, &PREV);
2197         newext = new->br_state;
2198         oldext = (newext == XFS_EXT_UNWRITTEN) ?
2199                 XFS_EXT_NORM : XFS_EXT_UNWRITTEN;
2200         ASSERT(PREV.br_state == oldext);
2201         new_endoff = new->br_startoff + new->br_blockcount;
2202         ASSERT(PREV.br_startoff <= new->br_startoff);
2203         ASSERT(PREV.br_startoff + PREV.br_blockcount >= new_endoff);
2204
2205         /*
2206          * Set flags determining what part of the previous oldext allocation
2207          * extent is being replaced by a newext allocation.
2208          */
2209         if (PREV.br_startoff == new->br_startoff)
2210                 state |= BMAP_LEFT_FILLING;
2211         if (PREV.br_startoff + PREV.br_blockcount == new_endoff)
2212                 state |= BMAP_RIGHT_FILLING;
2213
2214         /*
2215          * Check and set flags if this segment has a left neighbor.
2216          * Don't set contiguous if the combined extent would be too large.
2217          */
2218         if (*idx > 0) {
2219                 state |= BMAP_LEFT_VALID;
2220                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx - 1), &LEFT);
2221
2222                 if (isnullstartblock(LEFT.br_startblock))
2223                         state |= BMAP_LEFT_DELAY;
2224         }
2225
2226         if ((state & BMAP_LEFT_VALID) && !(state & BMAP_LEFT_DELAY) &&
2227             LEFT.br_startoff + LEFT.br_blockcount == new->br_startoff &&
2228             LEFT.br_startblock + LEFT.br_blockcount == new->br_startblock &&
2229             LEFT.br_state == newext &&
2230             LEFT.br_blockcount + new->br_blockcount <= MAXEXTLEN)
2231                 state |= BMAP_LEFT_CONTIG;
2232
2233         /*
2234          * Check and set flags if this segment has a right neighbor.
2235          * Don't set contiguous if the combined extent would be too large.
2236          * Also check for all-three-contiguous being too large.
2237          */
2238         if (*idx < xfs_iext_count(ifp) - 1) {
2239                 state |= BMAP_RIGHT_VALID;
2240                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx + 1), &RIGHT);
2241                 if (isnullstartblock(RIGHT.br_startblock))
2242                         state |= BMAP_RIGHT_DELAY;
2243         }
2244
2245         if ((state & BMAP_RIGHT_VALID) && !(state & BMAP_RIGHT_DELAY) &&
2246             new_endoff == RIGHT.br_startoff &&
2247             new->br_startblock + new->br_blockcount == RIGHT.br_startblock &&
2248             newext == RIGHT.br_state &&
2249             new->br_blockcount + RIGHT.br_blockcount <= MAXEXTLEN &&
2250             ((state & (BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING |
2251                        BMAP_RIGHT_FILLING)) !=
2252                       (BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING |
2253                        BMAP_RIGHT_FILLING) ||
2254              LEFT.br_blockcount + new->br_blockcount + RIGHT.br_blockcount
2255                         <= MAXEXTLEN))
2256                 state |= BMAP_RIGHT_CONTIG;
2257
2258         /*
2259          * Switch out based on the FILLING and CONTIG state bits.
2260          */
2261         switch (state & (BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG |
2262                          BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG)) {
2263         case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG |
2264              BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
2265                 /*
2266                  * Setting all of a previous oldext extent to newext.
2267                  * The left and right neighbors are both contiguous with new.
2268                  */
2269                 --*idx;
2270
2271                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2272                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx),
2273                         LEFT.br_blockcount + PREV.br_blockcount +
2274                         RIGHT.br_blockcount);
2275                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2276
2277                 xfs_iext_remove(ip, *idx + 1, 2, state);
2278                 XFS_IFORK_NEXT_SET(ip, whichfork,
2279                                 XFS_IFORK_NEXTENTS(ip, whichfork) - 2);
2280                 if (cur == NULL)
2281                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
2282                 else {
2283                         rval = XFS_ILOG_CORE;
2284                         if ((error = xfs_bmbt_lookup_eq(cur, RIGHT.br_startoff,
2285                                         RIGHT.br_startblock,
2286                                         RIGHT.br_blockcount, &i)))
2287                                 goto done;
2288                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2289                         if ((error = xfs_btree_delete(cur, &i)))
2290                                 goto done;
2291                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2292                         if ((error = xfs_btree_decrement(cur, 0, &i)))
2293                                 goto done;
2294                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2295                         if ((error = xfs_btree_delete(cur, &i)))
2296                                 goto done;
2297                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2298                         if ((error = xfs_btree_decrement(cur, 0, &i)))
2299                                 goto done;
2300                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2301                         if ((error = xfs_bmbt_update(cur, LEFT.br_startoff,
2302                                 LEFT.br_startblock,
2303                                 LEFT.br_blockcount + PREV.br_blockcount +
2304                                 RIGHT.br_blockcount, LEFT.br_state)))
2305                                 goto done;
2306                 }
2307                 break;
2308
2309         case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG:
2310                 /*
2311                  * Setting all of a previous oldext extent to newext.
2312                  * The left neighbor is contiguous, the right is not.
2313                  */
2314                 --*idx;
2315
2316                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2317                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx),
2318                         LEFT.br_blockcount + PREV.br_blockcount);
2319                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2320
2321                 xfs_iext_remove(ip, *idx + 1, 1, state);
2322                 XFS_IFORK_NEXT_SET(ip, whichfork,
2323                                 XFS_IFORK_NEXTENTS(ip, whichfork) - 1);
2324                 if (cur == NULL)
2325                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
2326                 else {
2327                         rval = XFS_ILOG_CORE;
2328                         if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
2329                                         PREV.br_startblock, PREV.br_blockcount,
2330                                         &i)))
2331                                 goto done;
2332                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2333                         if ((error = xfs_btree_delete(cur, &i)))
2334                                 goto done;
2335                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2336                         if ((error = xfs_btree_decrement(cur, 0, &i)))
2337                                 goto done;
2338                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2339                         if ((error = xfs_bmbt_update(cur, LEFT.br_startoff,
2340                                 LEFT.br_startblock,
2341                                 LEFT.br_blockcount + PREV.br_blockcount,
2342                                 LEFT.br_state)))
2343                                 goto done;
2344                 }
2345                 break;
2346
2347         case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
2348                 /*
2349                  * Setting all of a previous oldext extent to newext.
2350                  * The right neighbor is contiguous, the left is not.
2351                  */
2352                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2353                 xfs_bmbt_set_blockcount(ep,
2354                         PREV.br_blockcount + RIGHT.br_blockcount);
2355                 xfs_bmbt_set_state(ep, newext);
2356                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2357                 xfs_iext_remove(ip, *idx + 1, 1, state);
2358                 XFS_IFORK_NEXT_SET(ip, whichfork,
2359                                 XFS_IFORK_NEXTENTS(ip, whichfork) - 1);
2360                 if (cur == NULL)
2361                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
2362                 else {
2363                         rval = XFS_ILOG_CORE;
2364                         if ((error = xfs_bmbt_lookup_eq(cur, RIGHT.br_startoff,
2365                                         RIGHT.br_startblock,
2366                                         RIGHT.br_blockcount, &i)))
2367                                 goto done;
2368                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2369                         if ((error = xfs_btree_delete(cur, &i)))
2370                                 goto done;
2371                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2372                         if ((error = xfs_btree_decrement(cur, 0, &i)))
2373                                 goto done;
2374                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2375                         if ((error = xfs_bmbt_update(cur, new->br_startoff,
2376                                 new->br_startblock,
2377                                 new->br_blockcount + RIGHT.br_blockcount,
2378                                 newext)))
2379                                 goto done;
2380                 }
2381                 break;
2382
2383         case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING:
2384                 /*
2385                  * Setting all of a previous oldext extent to newext.
2386                  * Neither the left nor right neighbors are contiguous with
2387                  * the new one.
2388                  */
2389                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2390                 xfs_bmbt_set_state(ep, newext);
2391                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2392
2393                 if (cur == NULL)
2394                         rval = XFS_ILOG_DEXT;
2395                 else {
2396                         rval = 0;
2397                         if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff,
2398                                         new->br_startblock, new->br_blockcount,
2399                                         &i)))
2400                                 goto done;
2401                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2402                         if ((error = xfs_bmbt_update(cur, new->br_startoff,
2403                                 new->br_startblock, new->br_blockcount,
2404                                 newext)))
2405                                 goto done;
2406                 }
2407                 break;
2408
2409         case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG:
2410                 /*
2411                  * Setting the first part of a previous oldext extent to newext.
2412                  * The left neighbor is contiguous.
2413                  */
2414                 trace_xfs_bmap_pre_update(ip, *idx - 1, state, _THIS_IP_);
2415                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx - 1),
2416                         LEFT.br_blockcount + new->br_blockcount);
2417                 xfs_bmbt_set_startoff(ep,
2418                         PREV.br_startoff + new->br_blockcount);
2419                 trace_xfs_bmap_post_update(ip, *idx - 1, state, _THIS_IP_);
2420
2421                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2422                 xfs_bmbt_set_startblock(ep,
2423                         new->br_startblock + new->br_blockcount);
2424                 xfs_bmbt_set_blockcount(ep,
2425                         PREV.br_blockcount - new->br_blockcount);
2426                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2427
2428                 --*idx;
2429
2430                 if (cur == NULL)
2431                         rval = XFS_ILOG_DEXT;
2432                 else {
2433                         rval = 0;
2434                         if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
2435                                         PREV.br_startblock, PREV.br_blockcount,
2436                                         &i)))
2437                                 goto done;
2438                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2439                         if ((error = xfs_bmbt_update(cur,
2440                                 PREV.br_startoff + new->br_blockcount,
2441                                 PREV.br_startblock + new->br_blockcount,
2442                                 PREV.br_blockcount - new->br_blockcount,
2443                                 oldext)))
2444                                 goto done;
2445                         if ((error = xfs_btree_decrement(cur, 0, &i)))
2446                                 goto done;
2447                         error = xfs_bmbt_update(cur, LEFT.br_startoff,
2448                                 LEFT.br_startblock,
2449                                 LEFT.br_blockcount + new->br_blockcount,
2450                                 LEFT.br_state);
2451                         if (error)
2452                                 goto done;
2453                 }
2454                 break;
2455
2456         case BMAP_LEFT_FILLING:
2457                 /*
2458                  * Setting the first part of a previous oldext extent to newext.
2459                  * The left neighbor is not contiguous.
2460                  */
2461                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2462                 ASSERT(ep && xfs_bmbt_get_state(ep) == oldext);
2463                 xfs_bmbt_set_startoff(ep, new_endoff);
2464                 xfs_bmbt_set_blockcount(ep,
2465                         PREV.br_blockcount - new->br_blockcount);
2466                 xfs_bmbt_set_startblock(ep,
2467                         new->br_startblock + new->br_blockcount);
2468                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2469
2470                 xfs_iext_insert(ip, *idx, 1, new, state);
2471                 XFS_IFORK_NEXT_SET(ip, whichfork,
2472                                 XFS_IFORK_NEXTENTS(ip, whichfork) + 1);
2473                 if (cur == NULL)
2474                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
2475                 else {
2476                         rval = XFS_ILOG_CORE;
2477                         if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
2478                                         PREV.br_startblock, PREV.br_blockcount,
2479                                         &i)))
2480                                 goto done;
2481                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2482                         if ((error = xfs_bmbt_update(cur,
2483                                 PREV.br_startoff + new->br_blockcount,
2484                                 PREV.br_startblock + new->br_blockcount,
2485                                 PREV.br_blockcount - new->br_blockcount,
2486                                 oldext)))
2487                                 goto done;
2488                         cur->bc_rec.b = *new;
2489                         if ((error = xfs_btree_insert(cur, &i)))
2490                                 goto done;
2491                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2492                 }
2493                 break;
2494
2495         case BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
2496                 /*
2497                  * Setting the last part of a previous oldext extent to newext.
2498                  * The right neighbor is contiguous with the new allocation.
2499                  */
2500                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2501                 xfs_bmbt_set_blockcount(ep,
2502                         PREV.br_blockcount - new->br_blockcount);
2503                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2504
2505                 ++*idx;
2506
2507                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2508                 xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, *idx),
2509                         new->br_startoff, new->br_startblock,
2510                         new->br_blockcount + RIGHT.br_blockcount, newext);
2511                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2512
2513                 if (cur == NULL)
2514                         rval = XFS_ILOG_DEXT;
2515                 else {
2516                         rval = 0;
2517                         if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
2518                                         PREV.br_startblock,
2519                                         PREV.br_blockcount, &i)))
2520                                 goto done;
2521                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2522                         if ((error = xfs_bmbt_update(cur, PREV.br_startoff,
2523                                 PREV.br_startblock,
2524                                 PREV.br_blockcount - new->br_blockcount,
2525                                 oldext)))
2526                                 goto done;
2527                         if ((error = xfs_btree_increment(cur, 0, &i)))
2528                                 goto done;
2529                         if ((error = xfs_bmbt_update(cur, new->br_startoff,
2530                                 new->br_startblock,
2531                                 new->br_blockcount + RIGHT.br_blockcount,
2532                                 newext)))
2533                                 goto done;
2534                 }
2535                 break;
2536
2537         case BMAP_RIGHT_FILLING:
2538                 /*
2539                  * Setting the last part of a previous oldext extent to newext.
2540                  * The right neighbor is not contiguous.
2541                  */
2542                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2543                 xfs_bmbt_set_blockcount(ep,
2544                         PREV.br_blockcount - new->br_blockcount);
2545                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2546
2547                 ++*idx;
2548                 xfs_iext_insert(ip, *idx, 1, new, state);
2549
2550                 XFS_IFORK_NEXT_SET(ip, whichfork,
2551                                 XFS_IFORK_NEXTENTS(ip, whichfork) + 1);
2552                 if (cur == NULL)
2553                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
2554                 else {
2555                         rval = XFS_ILOG_CORE;
2556                         if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
2557                                         PREV.br_startblock, PREV.br_blockcount,
2558                                         &i)))
2559                                 goto done;
2560                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2561                         if ((error = xfs_bmbt_update(cur, PREV.br_startoff,
2562                                 PREV.br_startblock,
2563                                 PREV.br_blockcount - new->br_blockcount,
2564                                 oldext)))
2565                                 goto done;
2566                         if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff,
2567                                         new->br_startblock, new->br_blockcount,
2568                                         &i)))
2569                                 goto done;
2570                         XFS_WANT_CORRUPTED_GOTO(mp, i == 0, done);
2571                         cur->bc_rec.b.br_state = XFS_EXT_NORM;
2572                         if ((error = xfs_btree_insert(cur, &i)))
2573                                 goto done;
2574                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2575                 }
2576                 break;
2577
2578         case 0:
2579                 /*
2580                  * Setting the middle part of a previous oldext extent to
2581                  * newext.  Contiguity is impossible here.
2582                  * One extent becomes three extents.
2583                  */
2584                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2585                 xfs_bmbt_set_blockcount(ep,
2586                         new->br_startoff - PREV.br_startoff);
2587                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2588
2589                 r[0] = *new;
2590                 r[1].br_startoff = new_endoff;
2591                 r[1].br_blockcount =
2592                         PREV.br_startoff + PREV.br_blockcount - new_endoff;
2593                 r[1].br_startblock = new->br_startblock + new->br_blockcount;
2594                 r[1].br_state = oldext;
2595
2596                 ++*idx;
2597                 xfs_iext_insert(ip, *idx, 2, &r[0], state);
2598
2599                 XFS_IFORK_NEXT_SET(ip, whichfork,
2600                                 XFS_IFORK_NEXTENTS(ip, whichfork) + 2);
2601                 if (cur == NULL)
2602                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
2603                 else {
2604                         rval = XFS_ILOG_CORE;
2605                         if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
2606                                         PREV.br_startblock, PREV.br_blockcount,
2607                                         &i)))
2608                                 goto done;
2609                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2610                         /* new right extent - oldext */
2611                         if ((error = xfs_bmbt_update(cur, r[1].br_startoff,
2612                                 r[1].br_startblock, r[1].br_blockcount,
2613                                 r[1].br_state)))
2614                                 goto done;
2615                         /* new left extent - oldext */
2616                         cur->bc_rec.b = PREV;
2617                         cur->bc_rec.b.br_blockcount =
2618                                 new->br_startoff - PREV.br_startoff;
2619                         if ((error = xfs_btree_insert(cur, &i)))
2620                                 goto done;
2621                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2622                         /*
2623                          * Reset the cursor to the position of the new extent
2624                          * we are about to insert as we can't trust it after
2625                          * the previous insert.
2626                          */
2627                         if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff,
2628                                         new->br_startblock, new->br_blockcount,
2629                                         &i)))
2630                                 goto done;
2631                         XFS_WANT_CORRUPTED_GOTO(mp, i == 0, done);
2632                         /* new middle extent - newext */
2633                         cur->bc_rec.b.br_state = new->br_state;
2634                         if ((error = xfs_btree_insert(cur, &i)))
2635                                 goto done;
2636                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2637                 }
2638                 break;
2639
2640         case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
2641         case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
2642         case BMAP_LEFT_FILLING | BMAP_RIGHT_CONTIG:
2643         case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG:
2644         case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
2645         case BMAP_LEFT_CONTIG:
2646         case BMAP_RIGHT_CONTIG:
2647                 /*
2648                  * These cases are all impossible.
2649                  */
2650                 ASSERT(0);
2651         }
2652
2653         /* update reverse mappings */
2654         error = xfs_rmap_convert_extent(mp, dfops, ip, whichfork, new);
2655         if (error)
2656                 goto done;
2657
2658         /* convert to a btree if necessary */
2659         if (xfs_bmap_needs_btree(ip, whichfork)) {
2660                 int     tmp_logflags;   /* partial log flag return val */
2661
2662                 ASSERT(cur == NULL);
2663                 error = xfs_bmap_extents_to_btree(tp, ip, first, dfops, &cur,
2664                                 0, &tmp_logflags, whichfork);
2665                 *logflagsp |= tmp_logflags;
2666                 if (error)
2667                         goto done;
2668         }
2669
2670         /* clear out the allocated field, done with it now in any case. */
2671         if (cur) {
2672                 cur->bc_private.b.allocated = 0;
2673                 *curp = cur;
2674         }
2675
2676         xfs_bmap_check_leaf_extents(*curp, ip, whichfork);
2677 done:
2678         *logflagsp |= rval;
2679         return error;
2680 #undef  LEFT
2681 #undef  RIGHT
2682 #undef  PREV
2683 }
2684
2685 /*
2686  * Convert a hole to a delayed allocation.
2687  */
2688 STATIC void
2689 xfs_bmap_add_extent_hole_delay(
2690         xfs_inode_t             *ip,    /* incore inode pointer */
2691         int                     whichfork,
2692         xfs_extnum_t            *idx,   /* extent number to update/insert */
2693         xfs_bmbt_irec_t         *new)   /* new data to add to file extents */
2694 {
2695         xfs_ifork_t             *ifp;   /* inode fork pointer */
2696         xfs_bmbt_irec_t         left;   /* left neighbor extent entry */
2697         xfs_filblks_t           newlen=0;       /* new indirect size */
2698         xfs_filblks_t           oldlen=0;       /* old indirect size */
2699         xfs_bmbt_irec_t         right;  /* right neighbor extent entry */
2700         int                     state;  /* state bits, accessed thru macros */
2701         xfs_filblks_t           temp=0; /* temp for indirect calculations */
2702
2703         ifp = XFS_IFORK_PTR(ip, whichfork);
2704         state = 0;
2705         if (whichfork == XFS_COW_FORK)
2706                 state |= BMAP_COWFORK;
2707         ASSERT(isnullstartblock(new->br_startblock));
2708
2709         /*
2710          * Check and set flags if this segment has a left neighbor
2711          */
2712         if (*idx > 0) {
2713                 state |= BMAP_LEFT_VALID;
2714                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx - 1), &left);
2715
2716                 if (isnullstartblock(left.br_startblock))
2717                         state |= BMAP_LEFT_DELAY;
2718         }
2719
2720         /*
2721          * Check and set flags if the current (right) segment exists.
2722          * If it doesn't exist, we're converting the hole at end-of-file.
2723          */
2724         if (*idx < xfs_iext_count(ifp)) {
2725                 state |= BMAP_RIGHT_VALID;
2726                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx), &right);
2727
2728                 if (isnullstartblock(right.br_startblock))
2729                         state |= BMAP_RIGHT_DELAY;
2730         }
2731
2732         /*
2733          * Set contiguity flags on the left and right neighbors.
2734          * Don't let extents get too large, even if the pieces are contiguous.
2735          */
2736         if ((state & BMAP_LEFT_VALID) && (state & BMAP_LEFT_DELAY) &&
2737             left.br_startoff + left.br_blockcount == new->br_startoff &&
2738             left.br_blockcount + new->br_blockcount <= MAXEXTLEN)
2739                 state |= BMAP_LEFT_CONTIG;
2740
2741         if ((state & BMAP_RIGHT_VALID) && (state & BMAP_RIGHT_DELAY) &&
2742             new->br_startoff + new->br_blockcount == right.br_startoff &&
2743             new->br_blockcount + right.br_blockcount <= MAXEXTLEN &&
2744             (!(state & BMAP_LEFT_CONTIG) ||
2745              (left.br_blockcount + new->br_blockcount +
2746               right.br_blockcount <= MAXEXTLEN)))
2747                 state |= BMAP_RIGHT_CONTIG;
2748
2749         /*
2750          * Switch out based on the contiguity flags.
2751          */
2752         switch (state & (BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG)) {
2753         case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
2754                 /*
2755                  * New allocation is contiguous with delayed allocations
2756                  * on the left and on the right.
2757                  * Merge all three into a single extent record.
2758                  */
2759                 --*idx;
2760                 temp = left.br_blockcount + new->br_blockcount +
2761                         right.br_blockcount;
2762
2763                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2764                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx), temp);
2765                 oldlen = startblockval(left.br_startblock) +
2766                         startblockval(new->br_startblock) +
2767                         startblockval(right.br_startblock);
2768                 newlen = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
2769                                          oldlen);
2770                 xfs_bmbt_set_startblock(xfs_iext_get_ext(ifp, *idx),
2771                         nullstartblock((int)newlen));
2772                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2773
2774                 xfs_iext_remove(ip, *idx + 1, 1, state);
2775                 break;
2776
2777         case BMAP_LEFT_CONTIG:
2778                 /*
2779                  * New allocation is contiguous with a delayed allocation
2780                  * on the left.
2781                  * Merge the new allocation with the left neighbor.
2782                  */
2783                 --*idx;
2784                 temp = left.br_blockcount + new->br_blockcount;
2785
2786                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2787                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx), temp);
2788                 oldlen = startblockval(left.br_startblock) +
2789                         startblockval(new->br_startblock);
2790                 newlen = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
2791                                          oldlen);
2792                 xfs_bmbt_set_startblock(xfs_iext_get_ext(ifp, *idx),
2793                         nullstartblock((int)newlen));
2794                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2795                 break;
2796
2797         case BMAP_RIGHT_CONTIG:
2798                 /*
2799                  * New allocation is contiguous with a delayed allocation
2800                  * on the right.
2801                  * Merge the new allocation with the right neighbor.
2802                  */
2803                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2804                 temp = new->br_blockcount + right.br_blockcount;
2805                 oldlen = startblockval(new->br_startblock) +
2806                         startblockval(right.br_startblock);
2807                 newlen = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
2808                                          oldlen);
2809                 xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, *idx),
2810                         new->br_startoff,
2811                         nullstartblock((int)newlen), temp, right.br_state);
2812                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2813                 break;
2814
2815         case 0:
2816                 /*
2817                  * New allocation is not contiguous with another
2818                  * delayed allocation.
2819                  * Insert a new entry.
2820                  */
2821                 oldlen = newlen = 0;
2822                 xfs_iext_insert(ip, *idx, 1, new, state);
2823                 break;
2824         }
2825         if (oldlen != newlen) {
2826                 ASSERT(oldlen > newlen);
2827                 xfs_mod_fdblocks(ip->i_mount, (int64_t)(oldlen - newlen),
2828                                  false);
2829                 /*
2830                  * Nothing to do for disk quota accounting here.
2831                  */
2832         }
2833 }
2834
2835 /*
2836  * Convert a hole to a real allocation.
2837  */
2838 STATIC int                              /* error */
2839 xfs_bmap_add_extent_hole_real(
2840         struct xfs_trans        *tp,
2841         struct xfs_inode        *ip,
2842         int                     whichfork,
2843         xfs_extnum_t            *idx,
2844         struct xfs_btree_cur    **curp,
2845         struct xfs_bmbt_irec    *new,
2846         xfs_fsblock_t           *first,
2847         struct xfs_defer_ops    *dfops,
2848         int                     *logflagsp)
2849 {
2850         struct xfs_ifork        *ifp = XFS_IFORK_PTR(ip, whichfork);
2851         struct xfs_mount        *mp = ip->i_mount;
2852         struct xfs_btree_cur    *cur = *curp;
2853         int                     error;  /* error return value */
2854         int                     i;      /* temp state */
2855         xfs_bmbt_irec_t         left;   /* left neighbor extent entry */
2856         xfs_bmbt_irec_t         right;  /* right neighbor extent entry */
2857         int                     rval=0; /* return value (logging flags) */
2858         int                     state;  /* state bits, accessed thru macros */
2859
2860         ASSERT(*idx >= 0);
2861         ASSERT(*idx <= xfs_iext_count(ifp));
2862         ASSERT(!isnullstartblock(new->br_startblock));
2863         ASSERT(!cur || !(cur->bc_private.b.flags & XFS_BTCUR_BPRV_WASDEL));
2864
2865         XFS_STATS_INC(mp, xs_add_exlist);
2866
2867         state = 0;
2868         if (whichfork == XFS_ATTR_FORK)
2869                 state |= BMAP_ATTRFORK;
2870         if (whichfork == XFS_COW_FORK)
2871                 state |= BMAP_COWFORK;
2872
2873         /*
2874          * Check and set flags if this segment has a left neighbor.
2875          */
2876         if (*idx > 0) {
2877                 state |= BMAP_LEFT_VALID;
2878                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx - 1), &left);
2879                 if (isnullstartblock(left.br_startblock))
2880                         state |= BMAP_LEFT_DELAY;
2881         }
2882
2883         /*
2884          * Check and set flags if this segment has a current value.
2885          * Not true if we're inserting into the "hole" at eof.
2886          */
2887         if (*idx < xfs_iext_count(ifp)) {
2888                 state |= BMAP_RIGHT_VALID;
2889                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx), &right);
2890                 if (isnullstartblock(right.br_startblock))
2891                         state |= BMAP_RIGHT_DELAY;
2892         }
2893
2894         /*
2895          * We're inserting a real allocation between "left" and "right".
2896          * Set the contiguity flags.  Don't let extents get too large.
2897          */
2898         if ((state & BMAP_LEFT_VALID) && !(state & BMAP_LEFT_DELAY) &&
2899             left.br_startoff + left.br_blockcount == new->br_startoff &&
2900             left.br_startblock + left.br_blockcount == new->br_startblock &&
2901             left.br_state == new->br_state &&
2902             left.br_blockcount + new->br_blockcount <= MAXEXTLEN)
2903                 state |= BMAP_LEFT_CONTIG;
2904
2905         if ((state & BMAP_RIGHT_VALID) && !(state & BMAP_RIGHT_DELAY) &&
2906             new->br_startoff + new->br_blockcount == right.br_startoff &&
2907             new->br_startblock + new->br_blockcount == right.br_startblock &&
2908             new->br_state == right.br_state &&
2909             new->br_blockcount + right.br_blockcount <= MAXEXTLEN &&
2910             (!(state & BMAP_LEFT_CONTIG) ||
2911              left.br_blockcount + new->br_blockcount +
2912              right.br_blockcount <= MAXEXTLEN))
2913                 state |= BMAP_RIGHT_CONTIG;
2914
2915         error = 0;
2916         /*
2917          * Select which case we're in here, and implement it.
2918          */
2919         switch (state & (BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG)) {
2920         case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
2921                 /*
2922                  * New allocation is contiguous with real allocations on the
2923                  * left and on the right.
2924                  * Merge all three into a single extent record.
2925                  */
2926    &nb