xfs: rework xfs_bmap_free callers to use xfs_defer_ops
[cascardo/linux.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
50
51 kmem_zone_t             *xfs_bmap_free_item_zone;
52
53 /*
54  * Miscellaneous helper functions
55  */
56
57 /*
58  * Compute and fill in the value of the maximum depth of a bmap btree
59  * in this filesystem.  Done once, during mount.
60  */
61 void
62 xfs_bmap_compute_maxlevels(
63         xfs_mount_t     *mp,            /* file system mount structure */
64         int             whichfork)      /* data or attr fork */
65 {
66         int             level;          /* btree level */
67         uint            maxblocks;      /* max blocks at this level */
68         uint            maxleafents;    /* max leaf entries possible */
69         int             maxrootrecs;    /* max records in root block */
70         int             minleafrecs;    /* min records in leaf block */
71         int             minnoderecs;    /* min records in node block */
72         int             sz;             /* root block size */
73
74         /*
75          * The maximum number of extents in a file, hence the maximum
76          * number of leaf entries, is controlled by the type of di_nextents
77          * (a signed 32-bit number, xfs_extnum_t), or by di_anextents
78          * (a signed 16-bit number, xfs_aextnum_t).
79          *
80          * Note that we can no longer assume that if we are in ATTR1 that
81          * the fork offset of all the inodes will be
82          * (xfs_default_attroffset(ip) >> 3) because we could have mounted
83          * with ATTR2 and then mounted back with ATTR1, keeping the
84          * di_forkoff's fixed but probably at various positions. Therefore,
85          * for both ATTR1 and ATTR2 we have to assume the worst case scenario
86          * of a minimum size available.
87          */
88         if (whichfork == XFS_DATA_FORK) {
89                 maxleafents = MAXEXTNUM;
90                 sz = XFS_BMDR_SPACE_CALC(MINDBTPTRS);
91         } else {
92                 maxleafents = MAXAEXTNUM;
93                 sz = XFS_BMDR_SPACE_CALC(MINABTPTRS);
94         }
95         maxrootrecs = xfs_bmdr_maxrecs(sz, 0);
96         minleafrecs = mp->m_bmap_dmnr[0];
97         minnoderecs = mp->m_bmap_dmnr[1];
98         maxblocks = (maxleafents + minleafrecs - 1) / minleafrecs;
99         for (level = 1; maxblocks > 1; level++) {
100                 if (maxblocks <= maxrootrecs)
101                         maxblocks = 1;
102                 else
103                         maxblocks = (maxblocks + minnoderecs - 1) / minnoderecs;
104         }
105         mp->m_bm_maxlevels[whichfork] = level;
106 }
107
108 STATIC int                              /* error */
109 xfs_bmbt_lookup_eq(
110         struct xfs_btree_cur    *cur,
111         xfs_fileoff_t           off,
112         xfs_fsblock_t           bno,
113         xfs_filblks_t           len,
114         int                     *stat)  /* success/failure */
115 {
116         cur->bc_rec.b.br_startoff = off;
117         cur->bc_rec.b.br_startblock = bno;
118         cur->bc_rec.b.br_blockcount = len;
119         return xfs_btree_lookup(cur, XFS_LOOKUP_EQ, stat);
120 }
121
122 STATIC int                              /* error */
123 xfs_bmbt_lookup_ge(
124         struct xfs_btree_cur    *cur,
125         xfs_fileoff_t           off,
126         xfs_fsblock_t           bno,
127         xfs_filblks_t           len,
128         int                     *stat)  /* success/failure */
129 {
130         cur->bc_rec.b.br_startoff = off;
131         cur->bc_rec.b.br_startblock = bno;
132         cur->bc_rec.b.br_blockcount = len;
133         return xfs_btree_lookup(cur, XFS_LOOKUP_GE, stat);
134 }
135
136 /*
137  * Check if the inode needs to be converted to btree format.
138  */
139 static inline bool xfs_bmap_needs_btree(struct xfs_inode *ip, int whichfork)
140 {
141         return XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS &&
142                 XFS_IFORK_NEXTENTS(ip, whichfork) >
143                         XFS_IFORK_MAXEXT(ip, whichfork);
144 }
145
146 /*
147  * Check if the inode should be converted to extent format.
148  */
149 static inline bool xfs_bmap_wants_extents(struct xfs_inode *ip, int whichfork)
150 {
151         return XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE &&
152                 XFS_IFORK_NEXTENTS(ip, whichfork) <=
153                         XFS_IFORK_MAXEXT(ip, whichfork);
154 }
155
156 /*
157  * Update the record referred to by cur to the value given
158  * by [off, bno, len, state].
159  * This either works (return 0) or gets an EFSCORRUPTED error.
160  */
161 STATIC int
162 xfs_bmbt_update(
163         struct xfs_btree_cur    *cur,
164         xfs_fileoff_t           off,
165         xfs_fsblock_t           bno,
166         xfs_filblks_t           len,
167         xfs_exntst_t            state)
168 {
169         union xfs_btree_rec     rec;
170
171         xfs_bmbt_disk_set_allf(&rec.bmbt, off, bno, len, state);
172         return xfs_btree_update(cur, &rec);
173 }
174
175 /*
176  * Compute the worst-case number of indirect blocks that will be used
177  * for ip's delayed extent of length "len".
178  */
179 STATIC xfs_filblks_t
180 xfs_bmap_worst_indlen(
181         xfs_inode_t     *ip,            /* incore inode pointer */
182         xfs_filblks_t   len)            /* delayed extent length */
183 {
184         int             level;          /* btree level number */
185         int             maxrecs;        /* maximum record count at this level */
186         xfs_mount_t     *mp;            /* mount structure */
187         xfs_filblks_t   rval;           /* return value */
188
189         mp = ip->i_mount;
190         maxrecs = mp->m_bmap_dmxr[0];
191         for (level = 0, rval = 0;
192              level < XFS_BM_MAXLEVELS(mp, XFS_DATA_FORK);
193              level++) {
194                 len += maxrecs - 1;
195                 do_div(len, maxrecs);
196                 rval += len;
197                 if (len == 1)
198                         return rval + XFS_BM_MAXLEVELS(mp, XFS_DATA_FORK) -
199                                 level - 1;
200                 if (level == 0)
201                         maxrecs = mp->m_bmap_dmxr[1];
202         }
203         return rval;
204 }
205
206 /*
207  * Calculate the default attribute fork offset for newly created inodes.
208  */
209 uint
210 xfs_default_attroffset(
211         struct xfs_inode        *ip)
212 {
213         struct xfs_mount        *mp = ip->i_mount;
214         uint                    offset;
215
216         if (mp->m_sb.sb_inodesize == 256) {
217                 offset = XFS_LITINO(mp, ip->i_d.di_version) -
218                                 XFS_BMDR_SPACE_CALC(MINABTPTRS);
219         } else {
220                 offset = XFS_BMDR_SPACE_CALC(6 * MINABTPTRS);
221         }
222
223         ASSERT(offset < XFS_LITINO(mp, ip->i_d.di_version));
224         return offset;
225 }
226
227 /*
228  * Helper routine to reset inode di_forkoff field when switching
229  * attribute fork from local to extent format - we reset it where
230  * possible to make space available for inline data fork extents.
231  */
232 STATIC void
233 xfs_bmap_forkoff_reset(
234         xfs_inode_t     *ip,
235         int             whichfork)
236 {
237         if (whichfork == XFS_ATTR_FORK &&
238             ip->i_d.di_format != XFS_DINODE_FMT_DEV &&
239             ip->i_d.di_format != XFS_DINODE_FMT_UUID &&
240             ip->i_d.di_format != XFS_DINODE_FMT_BTREE) {
241                 uint    dfl_forkoff = xfs_default_attroffset(ip) >> 3;
242
243                 if (dfl_forkoff > ip->i_d.di_forkoff)
244                         ip->i_d.di_forkoff = dfl_forkoff;
245         }
246 }
247
248 #ifdef DEBUG
249 STATIC struct xfs_buf *
250 xfs_bmap_get_bp(
251         struct xfs_btree_cur    *cur,
252         xfs_fsblock_t           bno)
253 {
254         struct xfs_log_item_desc *lidp;
255         int                     i;
256
257         if (!cur)
258                 return NULL;
259
260         for (i = 0; i < XFS_BTREE_MAXLEVELS; i++) {
261                 if (!cur->bc_bufs[i])
262                         break;
263                 if (XFS_BUF_ADDR(cur->bc_bufs[i]) == bno)
264                         return cur->bc_bufs[i];
265         }
266
267         /* Chase down all the log items to see if the bp is there */
268         list_for_each_entry(lidp, &cur->bc_tp->t_items, lid_trans) {
269                 struct xfs_buf_log_item *bip;
270                 bip = (struct xfs_buf_log_item *)lidp->lid_item;
271                 if (bip->bli_item.li_type == XFS_LI_BUF &&
272                     XFS_BUF_ADDR(bip->bli_buf) == bno)
273                         return bip->bli_buf;
274         }
275
276         return NULL;
277 }
278
279 STATIC void
280 xfs_check_block(
281         struct xfs_btree_block  *block,
282         xfs_mount_t             *mp,
283         int                     root,
284         short                   sz)
285 {
286         int                     i, j, dmxr;
287         __be64                  *pp, *thispa;   /* pointer to block address */
288         xfs_bmbt_key_t          *prevp, *keyp;
289
290         ASSERT(be16_to_cpu(block->bb_level) > 0);
291
292         prevp = NULL;
293         for( i = 1; i <= xfs_btree_get_numrecs(block); i++) {
294                 dmxr = mp->m_bmap_dmxr[0];
295                 keyp = XFS_BMBT_KEY_ADDR(mp, block, i);
296
297                 if (prevp) {
298                         ASSERT(be64_to_cpu(prevp->br_startoff) <
299                                be64_to_cpu(keyp->br_startoff));
300                 }
301                 prevp = keyp;
302
303                 /*
304                  * Compare the block numbers to see if there are dups.
305                  */
306                 if (root)
307                         pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, i, sz);
308                 else
309                         pp = XFS_BMBT_PTR_ADDR(mp, block, i, dmxr);
310
311                 for (j = i+1; j <= be16_to_cpu(block->bb_numrecs); j++) {
312                         if (root)
313                                 thispa = XFS_BMAP_BROOT_PTR_ADDR(mp, block, j, sz);
314                         else
315                                 thispa = XFS_BMBT_PTR_ADDR(mp, block, j, dmxr);
316                         if (*thispa == *pp) {
317                                 xfs_warn(mp, "%s: thispa(%d) == pp(%d) %Ld",
318                                         __func__, j, i,
319                                         (unsigned long long)be64_to_cpu(*thispa));
320                                 panic("%s: ptrs are equal in node\n",
321                                         __func__);
322                         }
323                 }
324         }
325 }
326
327 /*
328  * Check that the extents for the inode ip are in the right order in all
329  * btree leaves. THis becomes prohibitively expensive for large extent count
330  * files, so don't bother with inodes that have more than 10,000 extents in
331  * them. The btree record ordering checks will still be done, so for such large
332  * bmapbt constructs that is going to catch most corruptions.
333  */
334 STATIC void
335 xfs_bmap_check_leaf_extents(
336         xfs_btree_cur_t         *cur,   /* btree cursor or null */
337         xfs_inode_t             *ip,            /* incore inode pointer */
338         int                     whichfork)      /* data or attr fork */
339 {
340         struct xfs_btree_block  *block; /* current btree block */
341         xfs_fsblock_t           bno;    /* block # of "block" */
342         xfs_buf_t               *bp;    /* buffer for "block" */
343         int                     error;  /* error return value */
344         xfs_extnum_t            i=0, j; /* index into the extents list */
345         xfs_ifork_t             *ifp;   /* fork structure */
346         int                     level;  /* btree level, for checking */
347         xfs_mount_t             *mp;    /* file system mount structure */
348         __be64                  *pp;    /* pointer to block address */
349         xfs_bmbt_rec_t          *ep;    /* pointer to current extent */
350         xfs_bmbt_rec_t          last = {0, 0}; /* last extent in prev block */
351         xfs_bmbt_rec_t          *nextp; /* pointer to next extent */
352         int                     bp_release = 0;
353
354         if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE) {
355                 return;
356         }
357
358         /* skip large extent count inodes */
359         if (ip->i_d.di_nextents > 10000)
360                 return;
361
362         bno = NULLFSBLOCK;
363         mp = ip->i_mount;
364         ifp = XFS_IFORK_PTR(ip, whichfork);
365         block = ifp->if_broot;
366         /*
367          * Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out.
368          */
369         level = be16_to_cpu(block->bb_level);
370         ASSERT(level > 0);
371         xfs_check_block(block, mp, 1, ifp->if_broot_bytes);
372         pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, 1, ifp->if_broot_bytes);
373         bno = be64_to_cpu(*pp);
374
375         ASSERT(bno != NULLFSBLOCK);
376         ASSERT(XFS_FSB_TO_AGNO(mp, bno) < mp->m_sb.sb_agcount);
377         ASSERT(XFS_FSB_TO_AGBNO(mp, bno) < mp->m_sb.sb_agblocks);
378
379         /*
380          * Go down the tree until leaf level is reached, following the first
381          * pointer (leftmost) at each level.
382          */
383         while (level-- > 0) {
384                 /* See if buf is in cur first */
385                 bp_release = 0;
386                 bp = xfs_bmap_get_bp(cur, XFS_FSB_TO_DADDR(mp, bno));
387                 if (!bp) {
388                         bp_release = 1;
389                         error = xfs_btree_read_bufl(mp, NULL, bno, 0, &bp,
390                                                 XFS_BMAP_BTREE_REF,
391                                                 &xfs_bmbt_buf_ops);
392                         if (error)
393                                 goto error_norelse;
394                 }
395                 block = XFS_BUF_TO_BLOCK(bp);
396                 if (level == 0)
397                         break;
398
399                 /*
400                  * Check this block for basic sanity (increasing keys and
401                  * no duplicate blocks).
402                  */
403
404                 xfs_check_block(block, mp, 0, 0);
405                 pp = XFS_BMBT_PTR_ADDR(mp, block, 1, mp->m_bmap_dmxr[1]);
406                 bno = be64_to_cpu(*pp);
407                 XFS_WANT_CORRUPTED_GOTO(mp,
408                                         XFS_FSB_SANITY_CHECK(mp, bno), error0);
409                 if (bp_release) {
410                         bp_release = 0;
411                         xfs_trans_brelse(NULL, bp);
412                 }
413         }
414
415         /*
416          * Here with bp and block set to the leftmost leaf node in the tree.
417          */
418         i = 0;
419
420         /*
421          * Loop over all leaf nodes checking that all extents are in the right order.
422          */
423         for (;;) {
424                 xfs_fsblock_t   nextbno;
425                 xfs_extnum_t    num_recs;
426
427
428                 num_recs = xfs_btree_get_numrecs(block);
429
430                 /*
431                  * Read-ahead the next leaf block, if any.
432                  */
433
434                 nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib);
435
436                 /*
437                  * Check all the extents to make sure they are OK.
438                  * If we had a previous block, the last entry should
439                  * conform with the first entry in this one.
440                  */
441
442                 ep = XFS_BMBT_REC_ADDR(mp, block, 1);
443                 if (i) {
444                         ASSERT(xfs_bmbt_disk_get_startoff(&last) +
445                                xfs_bmbt_disk_get_blockcount(&last) <=
446                                xfs_bmbt_disk_get_startoff(ep));
447                 }
448                 for (j = 1; j < num_recs; j++) {
449                         nextp = XFS_BMBT_REC_ADDR(mp, block, j + 1);
450                         ASSERT(xfs_bmbt_disk_get_startoff(ep) +
451                                xfs_bmbt_disk_get_blockcount(ep) <=
452                                xfs_bmbt_disk_get_startoff(nextp));
453                         ep = nextp;
454                 }
455
456                 last = *ep;
457                 i += num_recs;
458                 if (bp_release) {
459                         bp_release = 0;
460                         xfs_trans_brelse(NULL, bp);
461                 }
462                 bno = nextbno;
463                 /*
464                  * If we've reached the end, stop.
465                  */
466                 if (bno == NULLFSBLOCK)
467                         break;
468
469                 bp_release = 0;
470                 bp = xfs_bmap_get_bp(cur, XFS_FSB_TO_DADDR(mp, bno));
471                 if (!bp) {
472                         bp_release = 1;
473                         error = xfs_btree_read_bufl(mp, NULL, bno, 0, &bp,
474                                                 XFS_BMAP_BTREE_REF,
475                                                 &xfs_bmbt_buf_ops);
476                         if (error)
477                                 goto error_norelse;
478                 }
479                 block = XFS_BUF_TO_BLOCK(bp);
480         }
481
482         return;
483
484 error0:
485         xfs_warn(mp, "%s: at error0", __func__);
486         if (bp_release)
487                 xfs_trans_brelse(NULL, bp);
488 error_norelse:
489         xfs_warn(mp, "%s: BAD after btree leaves for %d extents",
490                 __func__, i);
491         panic("%s: CORRUPTED BTREE OR SOMETHING", __func__);
492         return;
493 }
494
495 /*
496  * Add bmap trace insert entries for all the contents of the extent records.
497  */
498 void
499 xfs_bmap_trace_exlist(
500         xfs_inode_t     *ip,            /* incore inode pointer */
501         xfs_extnum_t    cnt,            /* count of entries in the list */
502         int             whichfork,      /* data or attr fork */
503         unsigned long   caller_ip)
504 {
505         xfs_extnum_t    idx;            /* extent record index */
506         xfs_ifork_t     *ifp;           /* inode fork pointer */
507         int             state = 0;
508
509         if (whichfork == XFS_ATTR_FORK)
510                 state |= BMAP_ATTRFORK;
511
512         ifp = XFS_IFORK_PTR(ip, whichfork);
513         ASSERT(cnt == (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t)));
514         for (idx = 0; idx < cnt; idx++)
515                 trace_xfs_extlist(ip, idx, whichfork, caller_ip);
516 }
517
518 /*
519  * Validate that the bmbt_irecs being returned from bmapi are valid
520  * given the caller's original parameters.  Specifically check the
521  * ranges of the returned irecs to ensure that they only extend beyond
522  * the given parameters if the XFS_BMAPI_ENTIRE flag was set.
523  */
524 STATIC void
525 xfs_bmap_validate_ret(
526         xfs_fileoff_t           bno,
527         xfs_filblks_t           len,
528         int                     flags,
529         xfs_bmbt_irec_t         *mval,
530         int                     nmap,
531         int                     ret_nmap)
532 {
533         int                     i;              /* index to map values */
534
535         ASSERT(ret_nmap <= nmap);
536
537         for (i = 0; i < ret_nmap; i++) {
538                 ASSERT(mval[i].br_blockcount > 0);
539                 if (!(flags & XFS_BMAPI_ENTIRE)) {
540                         ASSERT(mval[i].br_startoff >= bno);
541                         ASSERT(mval[i].br_blockcount <= len);
542                         ASSERT(mval[i].br_startoff + mval[i].br_blockcount <=
543                                bno + len);
544                 } else {
545                         ASSERT(mval[i].br_startoff < bno + len);
546                         ASSERT(mval[i].br_startoff + mval[i].br_blockcount >
547                                bno);
548                 }
549                 ASSERT(i == 0 ||
550                        mval[i - 1].br_startoff + mval[i - 1].br_blockcount ==
551                        mval[i].br_startoff);
552                 ASSERT(mval[i].br_startblock != DELAYSTARTBLOCK &&
553                        mval[i].br_startblock != HOLESTARTBLOCK);
554                 ASSERT(mval[i].br_state == XFS_EXT_NORM ||
555                        mval[i].br_state == XFS_EXT_UNWRITTEN);
556         }
557 }
558
559 #else
560 #define xfs_bmap_check_leaf_extents(cur, ip, whichfork)         do { } while (0)
561 #define xfs_bmap_validate_ret(bno,len,flags,mval,onmap,nmap)
562 #endif /* DEBUG */
563
564 /*
565  * bmap free list manipulation functions
566  */
567
568 /*
569  * Add the extent to the list of extents to be free at transaction end.
570  * The list is maintained sorted (by block number).
571  */
572 void
573 xfs_bmap_add_free(
574         struct xfs_mount        *mp,            /* mount point structure */
575         struct xfs_bmap_free    *flist,         /* list of extents */
576         xfs_fsblock_t           bno,            /* fs block number of extent */
577         xfs_filblks_t           len)            /* length of extent */
578 {
579         struct xfs_bmap_free_item       *new;           /* new element */
580 #ifdef DEBUG
581         xfs_agnumber_t          agno;
582         xfs_agblock_t           agbno;
583
584         ASSERT(bno != NULLFSBLOCK);
585         ASSERT(len > 0);
586         ASSERT(len <= MAXEXTLEN);
587         ASSERT(!isnullstartblock(bno));
588         agno = XFS_FSB_TO_AGNO(mp, bno);
589         agbno = XFS_FSB_TO_AGBNO(mp, bno);
590         ASSERT(agno < mp->m_sb.sb_agcount);
591         ASSERT(agbno < mp->m_sb.sb_agblocks);
592         ASSERT(len < mp->m_sb.sb_agblocks);
593         ASSERT(agbno + len <= mp->m_sb.sb_agblocks);
594 #endif
595         ASSERT(xfs_bmap_free_item_zone != NULL);
596         new = kmem_zone_alloc(xfs_bmap_free_item_zone, KM_SLEEP);
597         new->xbfi_startblock = bno;
598         new->xbfi_blockcount = (xfs_extlen_t)len;
599         xfs_defer_add(flist, XFS_DEFER_OPS_TYPE_FREE, &new->xbfi_list);
600 }
601
602 /*
603  * Inode fork format manipulation functions
604  */
605
606 /*
607  * Transform a btree format file with only one leaf node, where the
608  * extents list will fit in the inode, into an extents format file.
609  * Since the file extents are already in-core, all we have to do is
610  * give up the space for the btree root and pitch the leaf block.
611  */
612 STATIC int                              /* error */
613 xfs_bmap_btree_to_extents(
614         xfs_trans_t             *tp,    /* transaction pointer */
615         xfs_inode_t             *ip,    /* incore inode pointer */
616         xfs_btree_cur_t         *cur,   /* btree cursor */
617         int                     *logflagsp, /* inode logging flags */
618         int                     whichfork)  /* data or attr fork */
619 {
620         /* REFERENCED */
621         struct xfs_btree_block  *cblock;/* child btree block */
622         xfs_fsblock_t           cbno;   /* child block number */
623         xfs_buf_t               *cbp;   /* child block's buffer */
624         int                     error;  /* error return value */
625         xfs_ifork_t             *ifp;   /* inode fork data */
626         xfs_mount_t             *mp;    /* mount point structure */
627         __be64                  *pp;    /* ptr to block address */
628         struct xfs_btree_block  *rblock;/* root btree block */
629
630         mp = ip->i_mount;
631         ifp = XFS_IFORK_PTR(ip, whichfork);
632         ASSERT(ifp->if_flags & XFS_IFEXTENTS);
633         ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE);
634         rblock = ifp->if_broot;
635         ASSERT(be16_to_cpu(rblock->bb_level) == 1);
636         ASSERT(be16_to_cpu(rblock->bb_numrecs) == 1);
637         ASSERT(xfs_bmbt_maxrecs(mp, ifp->if_broot_bytes, 0) == 1);
638         pp = XFS_BMAP_BROOT_PTR_ADDR(mp, rblock, 1, ifp->if_broot_bytes);
639         cbno = be64_to_cpu(*pp);
640         *logflagsp = 0;
641 #ifdef DEBUG
642         if ((error = xfs_btree_check_lptr(cur, cbno, 1)))
643                 return error;
644 #endif
645         error = xfs_btree_read_bufl(mp, tp, cbno, 0, &cbp, XFS_BMAP_BTREE_REF,
646                                 &xfs_bmbt_buf_ops);
647         if (error)
648                 return error;
649         cblock = XFS_BUF_TO_BLOCK(cbp);
650         if ((error = xfs_btree_check_block(cur, cblock, 0, cbp)))
651                 return error;
652         xfs_bmap_add_free(mp, cur->bc_private.b.flist, cbno, 1);
653         ip->i_d.di_nblocks--;
654         xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_BCOUNT, -1L);
655         xfs_trans_binval(tp, cbp);
656         if (cur->bc_bufs[0] == cbp)
657                 cur->bc_bufs[0] = NULL;
658         xfs_iroot_realloc(ip, -1, whichfork);
659         ASSERT(ifp->if_broot == NULL);
660         ASSERT((ifp->if_flags & XFS_IFBROOT) == 0);
661         XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_EXTENTS);
662         *logflagsp = XFS_ILOG_CORE | xfs_ilog_fext(whichfork);
663         return 0;
664 }
665
666 /*
667  * Convert an extents-format file into a btree-format file.
668  * The new file will have a root block (in the inode) and a single child block.
669  */
670 STATIC int                                      /* error */
671 xfs_bmap_extents_to_btree(
672         xfs_trans_t             *tp,            /* transaction pointer */
673         xfs_inode_t             *ip,            /* incore inode pointer */
674         xfs_fsblock_t           *firstblock,    /* first-block-allocated */
675         xfs_bmap_free_t         *flist,         /* blocks freed in xaction */
676         xfs_btree_cur_t         **curp,         /* cursor returned to caller */
677         int                     wasdel,         /* converting a delayed alloc */
678         int                     *logflagsp,     /* inode logging flags */
679         int                     whichfork)      /* data or attr fork */
680 {
681         struct xfs_btree_block  *ablock;        /* allocated (child) bt block */
682         xfs_buf_t               *abp;           /* buffer for ablock */
683         xfs_alloc_arg_t         args;           /* allocation arguments */
684         xfs_bmbt_rec_t          *arp;           /* child record pointer */
685         struct xfs_btree_block  *block;         /* btree root block */
686         xfs_btree_cur_t         *cur;           /* bmap btree cursor */
687         xfs_bmbt_rec_host_t     *ep;            /* extent record pointer */
688         int                     error;          /* error return value */
689         xfs_extnum_t            i, cnt;         /* extent record index */
690         xfs_ifork_t             *ifp;           /* inode fork pointer */
691         xfs_bmbt_key_t          *kp;            /* root block key pointer */
692         xfs_mount_t             *mp;            /* mount structure */
693         xfs_extnum_t            nextents;       /* number of file extents */
694         xfs_bmbt_ptr_t          *pp;            /* root block address pointer */
695
696         mp = ip->i_mount;
697         ifp = XFS_IFORK_PTR(ip, whichfork);
698         ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS);
699
700         /*
701          * Make space in the inode incore.
702          */
703         xfs_iroot_realloc(ip, 1, whichfork);
704         ifp->if_flags |= XFS_IFBROOT;
705
706         /*
707          * Fill in the root.
708          */
709         block = ifp->if_broot;
710         if (xfs_sb_version_hascrc(&mp->m_sb))
711                 xfs_btree_init_block_int(mp, block, XFS_BUF_DADDR_NULL,
712                                  XFS_BMAP_CRC_MAGIC, 1, 1, ip->i_ino,
713                                  XFS_BTREE_LONG_PTRS | XFS_BTREE_CRC_BLOCKS);
714         else
715                 xfs_btree_init_block_int(mp, block, XFS_BUF_DADDR_NULL,
716                                  XFS_BMAP_MAGIC, 1, 1, ip->i_ino,
717                                  XFS_BTREE_LONG_PTRS);
718
719         /*
720          * Need a cursor.  Can't allocate until bb_level is filled in.
721          */
722         cur = xfs_bmbt_init_cursor(mp, tp, ip, whichfork);
723         cur->bc_private.b.firstblock = *firstblock;
724         cur->bc_private.b.flist = flist;
725         cur->bc_private.b.flags = wasdel ? XFS_BTCUR_BPRV_WASDEL : 0;
726         /*
727          * Convert to a btree with two levels, one record in root.
728          */
729         XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_BTREE);
730         memset(&args, 0, sizeof(args));
731         args.tp = tp;
732         args.mp = mp;
733         args.firstblock = *firstblock;
734         if (*firstblock == NULLFSBLOCK) {
735                 args.type = XFS_ALLOCTYPE_START_BNO;
736                 args.fsbno = XFS_INO_TO_FSB(mp, ip->i_ino);
737         } else if (flist->dop_low) {
738                 args.type = XFS_ALLOCTYPE_START_BNO;
739                 args.fsbno = *firstblock;
740         } else {
741                 args.type = XFS_ALLOCTYPE_NEAR_BNO;
742                 args.fsbno = *firstblock;
743         }
744         args.minlen = args.maxlen = args.prod = 1;
745         args.wasdel = wasdel;
746         *logflagsp = 0;
747         if ((error = xfs_alloc_vextent(&args))) {
748                 xfs_iroot_realloc(ip, -1, whichfork);
749                 xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
750                 return error;
751         }
752         /*
753          * Allocation can't fail, the space was reserved.
754          */
755         ASSERT(args.fsbno != NULLFSBLOCK);
756         ASSERT(*firstblock == NULLFSBLOCK ||
757                args.agno == XFS_FSB_TO_AGNO(mp, *firstblock) ||
758                (flist->dop_low &&
759                 args.agno > XFS_FSB_TO_AGNO(mp, *firstblock)));
760         *firstblock = cur->bc_private.b.firstblock = args.fsbno;
761         cur->bc_private.b.allocated++;
762         ip->i_d.di_nblocks++;
763         xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_BCOUNT, 1L);
764         abp = xfs_btree_get_bufl(mp, tp, args.fsbno, 0);
765         /*
766          * Fill in the child block.
767          */
768         abp->b_ops = &xfs_bmbt_buf_ops;
769         ablock = XFS_BUF_TO_BLOCK(abp);
770         if (xfs_sb_version_hascrc(&mp->m_sb))
771                 xfs_btree_init_block_int(mp, ablock, abp->b_bn,
772                                 XFS_BMAP_CRC_MAGIC, 0, 0, ip->i_ino,
773                                 XFS_BTREE_LONG_PTRS | XFS_BTREE_CRC_BLOCKS);
774         else
775                 xfs_btree_init_block_int(mp, ablock, abp->b_bn,
776                                 XFS_BMAP_MAGIC, 0, 0, ip->i_ino,
777                                 XFS_BTREE_LONG_PTRS);
778
779         arp = XFS_BMBT_REC_ADDR(mp, ablock, 1);
780         nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
781         for (cnt = i = 0; i < nextents; i++) {
782                 ep = xfs_iext_get_ext(ifp, i);
783                 if (!isnullstartblock(xfs_bmbt_get_startblock(ep))) {
784                         arp->l0 = cpu_to_be64(ep->l0);
785                         arp->l1 = cpu_to_be64(ep->l1);
786                         arp++; cnt++;
787                 }
788         }
789         ASSERT(cnt == XFS_IFORK_NEXTENTS(ip, whichfork));
790         xfs_btree_set_numrecs(ablock, cnt);
791
792         /*
793          * Fill in the root key and pointer.
794          */
795         kp = XFS_BMBT_KEY_ADDR(mp, block, 1);
796         arp = XFS_BMBT_REC_ADDR(mp, ablock, 1);
797         kp->br_startoff = cpu_to_be64(xfs_bmbt_disk_get_startoff(arp));
798         pp = XFS_BMBT_PTR_ADDR(mp, block, 1, xfs_bmbt_get_maxrecs(cur,
799                                                 be16_to_cpu(block->bb_level)));
800         *pp = cpu_to_be64(args.fsbno);
801
802         /*
803          * Do all this logging at the end so that
804          * the root is at the right level.
805          */
806         xfs_btree_log_block(cur, abp, XFS_BB_ALL_BITS);
807         xfs_btree_log_recs(cur, abp, 1, be16_to_cpu(ablock->bb_numrecs));
808         ASSERT(*curp == NULL);
809         *curp = cur;
810         *logflagsp = XFS_ILOG_CORE | xfs_ilog_fbroot(whichfork);
811         return 0;
812 }
813
814 /*
815  * Convert a local file to an extents file.
816  * This code is out of bounds for data forks of regular files,
817  * since the file data needs to get logged so things will stay consistent.
818  * (The bmap-level manipulations are ok, though).
819  */
820 void
821 xfs_bmap_local_to_extents_empty(
822         struct xfs_inode        *ip,
823         int                     whichfork)
824 {
825         struct xfs_ifork        *ifp = XFS_IFORK_PTR(ip, whichfork);
826
827         ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL);
828         ASSERT(ifp->if_bytes == 0);
829         ASSERT(XFS_IFORK_NEXTENTS(ip, whichfork) == 0);
830
831         xfs_bmap_forkoff_reset(ip, whichfork);
832         ifp->if_flags &= ~XFS_IFINLINE;
833         ifp->if_flags |= XFS_IFEXTENTS;
834         XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_EXTENTS);
835 }
836
837
838 STATIC int                              /* error */
839 xfs_bmap_local_to_extents(
840         xfs_trans_t     *tp,            /* transaction pointer */
841         xfs_inode_t     *ip,            /* incore inode pointer */
842         xfs_fsblock_t   *firstblock,    /* first block allocated in xaction */
843         xfs_extlen_t    total,          /* total blocks needed by transaction */
844         int             *logflagsp,     /* inode logging flags */
845         int             whichfork,
846         void            (*init_fn)(struct xfs_trans *tp,
847                                    struct xfs_buf *bp,
848                                    struct xfs_inode *ip,
849                                    struct xfs_ifork *ifp))
850 {
851         int             error = 0;
852         int             flags;          /* logging flags returned */
853         xfs_ifork_t     *ifp;           /* inode fork pointer */
854         xfs_alloc_arg_t args;           /* allocation arguments */
855         xfs_buf_t       *bp;            /* buffer for extent block */
856         xfs_bmbt_rec_host_t *ep;        /* extent record pointer */
857
858         /*
859          * We don't want to deal with the case of keeping inode data inline yet.
860          * So sending the data fork of a regular inode is invalid.
861          */
862         ASSERT(!(S_ISREG(VFS_I(ip)->i_mode) && whichfork == XFS_DATA_FORK));
863         ifp = XFS_IFORK_PTR(ip, whichfork);
864         ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL);
865
866         if (!ifp->if_bytes) {
867                 xfs_bmap_local_to_extents_empty(ip, whichfork);
868                 flags = XFS_ILOG_CORE;
869                 goto done;
870         }
871
872         flags = 0;
873         error = 0;
874         ASSERT((ifp->if_flags & (XFS_IFINLINE|XFS_IFEXTENTS|XFS_IFEXTIREC)) ==
875                                                                 XFS_IFINLINE);
876         memset(&args, 0, sizeof(args));
877         args.tp = tp;
878         args.mp = ip->i_mount;
879         args.firstblock = *firstblock;
880         /*
881          * Allocate a block.  We know we need only one, since the
882          * file currently fits in an inode.
883          */
884         if (*firstblock == NULLFSBLOCK) {
885                 args.fsbno = XFS_INO_TO_FSB(args.mp, ip->i_ino);
886                 args.type = XFS_ALLOCTYPE_START_BNO;
887         } else {
888                 args.fsbno = *firstblock;
889                 args.type = XFS_ALLOCTYPE_NEAR_BNO;
890         }
891         args.total = total;
892         args.minlen = args.maxlen = args.prod = 1;
893         error = xfs_alloc_vextent(&args);
894         if (error)
895                 goto done;
896
897         /* Can't fail, the space was reserved. */
898         ASSERT(args.fsbno != NULLFSBLOCK);
899         ASSERT(args.len == 1);
900         *firstblock = args.fsbno;
901         bp = xfs_btree_get_bufl(args.mp, tp, args.fsbno, 0);
902
903         /*
904          * Initialize the block, copy the data and log the remote buffer.
905          *
906          * The callout is responsible for logging because the remote format
907          * might differ from the local format and thus we don't know how much to
908          * log here. Note that init_fn must also set the buffer log item type
909          * correctly.
910          */
911         init_fn(tp, bp, ip, ifp);
912
913         /* account for the change in fork size */
914         xfs_idata_realloc(ip, -ifp->if_bytes, whichfork);
915         xfs_bmap_local_to_extents_empty(ip, whichfork);
916         flags |= XFS_ILOG_CORE;
917
918         xfs_iext_add(ifp, 0, 1);
919         ep = xfs_iext_get_ext(ifp, 0);
920         xfs_bmbt_set_allf(ep, 0, args.fsbno, 1, XFS_EXT_NORM);
921         trace_xfs_bmap_post_update(ip, 0,
922                         whichfork == XFS_ATTR_FORK ? BMAP_ATTRFORK : 0,
923                         _THIS_IP_);
924         XFS_IFORK_NEXT_SET(ip, whichfork, 1);
925         ip->i_d.di_nblocks = 1;
926         xfs_trans_mod_dquot_byino(tp, ip,
927                 XFS_TRANS_DQ_BCOUNT, 1L);
928         flags |= xfs_ilog_fext(whichfork);
929
930 done:
931         *logflagsp = flags;
932         return error;
933 }
934
935 /*
936  * Called from xfs_bmap_add_attrfork to handle btree format files.
937  */
938 STATIC int                                      /* error */
939 xfs_bmap_add_attrfork_btree(
940         xfs_trans_t             *tp,            /* transaction pointer */
941         xfs_inode_t             *ip,            /* incore inode pointer */
942         xfs_fsblock_t           *firstblock,    /* first block allocated */
943         xfs_bmap_free_t         *flist,         /* blocks to free at commit */
944         int                     *flags)         /* inode logging flags */
945 {
946         xfs_btree_cur_t         *cur;           /* btree cursor */
947         int                     error;          /* error return value */
948         xfs_mount_t             *mp;            /* file system mount struct */
949         int                     stat;           /* newroot status */
950
951         mp = ip->i_mount;
952         if (ip->i_df.if_broot_bytes <= XFS_IFORK_DSIZE(ip))
953                 *flags |= XFS_ILOG_DBROOT;
954         else {
955                 cur = xfs_bmbt_init_cursor(mp, tp, ip, XFS_DATA_FORK);
956                 cur->bc_private.b.flist = flist;
957                 cur->bc_private.b.firstblock = *firstblock;
958                 if ((error = xfs_bmbt_lookup_ge(cur, 0, 0, 0, &stat)))
959                         goto error0;
960                 /* must be at least one entry */
961                 XFS_WANT_CORRUPTED_GOTO(mp, stat == 1, error0);
962                 if ((error = xfs_btree_new_iroot(cur, flags, &stat)))
963                         goto error0;
964                 if (stat == 0) {
965                         xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
966                         return -ENOSPC;
967                 }
968                 *firstblock = cur->bc_private.b.firstblock;
969                 cur->bc_private.b.allocated = 0;
970                 xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
971         }
972         return 0;
973 error0:
974         xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
975         return error;
976 }
977
978 /*
979  * Called from xfs_bmap_add_attrfork to handle extents format files.
980  */
981 STATIC int                                      /* error */
982 xfs_bmap_add_attrfork_extents(
983         xfs_trans_t             *tp,            /* transaction pointer */
984         xfs_inode_t             *ip,            /* incore inode pointer */
985         xfs_fsblock_t           *firstblock,    /* first block allocated */
986         xfs_bmap_free_t         *flist,         /* blocks to free at commit */
987         int                     *flags)         /* inode logging flags */
988 {
989         xfs_btree_cur_t         *cur;           /* bmap btree cursor */
990         int                     error;          /* error return value */
991
992         if (ip->i_d.di_nextents * sizeof(xfs_bmbt_rec_t) <= XFS_IFORK_DSIZE(ip))
993                 return 0;
994         cur = NULL;
995         error = xfs_bmap_extents_to_btree(tp, ip, firstblock, flist, &cur, 0,
996                 flags, XFS_DATA_FORK);
997         if (cur) {
998                 cur->bc_private.b.allocated = 0;
999                 xfs_btree_del_cursor(cur,
1000                         error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
1001         }
1002         return error;
1003 }
1004
1005 /*
1006  * Called from xfs_bmap_add_attrfork to handle local format files. Each
1007  * different data fork content type needs a different callout to do the
1008  * conversion. Some are basic and only require special block initialisation
1009  * callouts for the data formating, others (directories) are so specialised they
1010  * handle everything themselves.
1011  *
1012  * XXX (dgc): investigate whether directory conversion can use the generic
1013  * formatting callout. It should be possible - it's just a very complex
1014  * formatter.
1015  */
1016 STATIC int                                      /* error */
1017 xfs_bmap_add_attrfork_local(
1018         xfs_trans_t             *tp,            /* transaction pointer */
1019         xfs_inode_t             *ip,            /* incore inode pointer */
1020         xfs_fsblock_t           *firstblock,    /* first block allocated */
1021         xfs_bmap_free_t         *flist,         /* blocks to free at commit */
1022         int                     *flags)         /* inode logging flags */
1023 {
1024         xfs_da_args_t           dargs;          /* args for dir/attr code */
1025
1026         if (ip->i_df.if_bytes <= XFS_IFORK_DSIZE(ip))
1027                 return 0;
1028
1029         if (S_ISDIR(VFS_I(ip)->i_mode)) {
1030                 memset(&dargs, 0, sizeof(dargs));
1031                 dargs.geo = ip->i_mount->m_dir_geo;
1032                 dargs.dp = ip;
1033                 dargs.firstblock = firstblock;
1034                 dargs.flist = flist;
1035                 dargs.total = dargs.geo->fsbcount;
1036                 dargs.whichfork = XFS_DATA_FORK;
1037                 dargs.trans = tp;
1038                 return xfs_dir2_sf_to_block(&dargs);
1039         }
1040
1041         if (S_ISLNK(VFS_I(ip)->i_mode))
1042                 return xfs_bmap_local_to_extents(tp, ip, firstblock, 1,
1043                                                  flags, XFS_DATA_FORK,
1044                                                  xfs_symlink_local_to_remote);
1045
1046         /* should only be called for types that support local format data */
1047         ASSERT(0);
1048         return -EFSCORRUPTED;
1049 }
1050
1051 /*
1052  * Convert inode from non-attributed to attributed.
1053  * Must not be in a transaction, ip must not be locked.
1054  */
1055 int                                             /* error code */
1056 xfs_bmap_add_attrfork(
1057         xfs_inode_t             *ip,            /* incore inode pointer */
1058         int                     size,           /* space new attribute needs */
1059         int                     rsvd)           /* xact may use reserved blks */
1060 {
1061         xfs_fsblock_t           firstblock;     /* 1st block/ag allocated */
1062         xfs_bmap_free_t         flist;          /* freed extent records */
1063         xfs_mount_t             *mp;            /* mount structure */
1064         xfs_trans_t             *tp;            /* transaction pointer */
1065         int                     blks;           /* space reservation */
1066         int                     version = 1;    /* superblock attr version */
1067         int                     logflags;       /* logging flags */
1068         int                     error;          /* error return value */
1069
1070         ASSERT(XFS_IFORK_Q(ip) == 0);
1071
1072         mp = ip->i_mount;
1073         ASSERT(!XFS_NOT_DQATTACHED(mp, ip));
1074
1075         blks = XFS_ADDAFORK_SPACE_RES(mp);
1076
1077         error = xfs_trans_alloc(mp, &M_RES(mp)->tr_addafork, blks, 0,
1078                         rsvd ? XFS_TRANS_RESERVE : 0, &tp);
1079         if (error)
1080                 return error;
1081
1082         xfs_ilock(ip, XFS_ILOCK_EXCL);
1083         error = xfs_trans_reserve_quota_nblks(tp, ip, blks, 0, rsvd ?
1084                         XFS_QMOPT_RES_REGBLKS | XFS_QMOPT_FORCE_RES :
1085                         XFS_QMOPT_RES_REGBLKS);
1086         if (error)
1087                 goto trans_cancel;
1088         if (XFS_IFORK_Q(ip))
1089                 goto trans_cancel;
1090         if (ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS) {
1091                 /*
1092                  * For inodes coming from pre-6.2 filesystems.
1093                  */
1094                 ASSERT(ip->i_d.di_aformat == 0);
1095                 ip->i_d.di_aformat = XFS_DINODE_FMT_EXTENTS;
1096         }
1097         ASSERT(ip->i_d.di_anextents == 0);
1098
1099         xfs_trans_ijoin(tp, ip, 0);
1100         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1101
1102         switch (ip->i_d.di_format) {
1103         case XFS_DINODE_FMT_DEV:
1104                 ip->i_d.di_forkoff = roundup(sizeof(xfs_dev_t), 8) >> 3;
1105                 break;
1106         case XFS_DINODE_FMT_UUID:
1107                 ip->i_d.di_forkoff = roundup(sizeof(uuid_t), 8) >> 3;
1108                 break;
1109         case XFS_DINODE_FMT_LOCAL:
1110         case XFS_DINODE_FMT_EXTENTS:
1111         case XFS_DINODE_FMT_BTREE:
1112                 ip->i_d.di_forkoff = xfs_attr_shortform_bytesfit(ip, size);
1113                 if (!ip->i_d.di_forkoff)
1114                         ip->i_d.di_forkoff = xfs_default_attroffset(ip) >> 3;
1115                 else if (mp->m_flags & XFS_MOUNT_ATTR2)
1116                         version = 2;
1117                 break;
1118         default:
1119                 ASSERT(0);
1120                 error = -EINVAL;
1121                 goto trans_cancel;
1122         }
1123
1124         ASSERT(ip->i_afp == NULL);
1125         ip->i_afp = kmem_zone_zalloc(xfs_ifork_zone, KM_SLEEP);
1126         ip->i_afp->if_flags = XFS_IFEXTENTS;
1127         logflags = 0;
1128         xfs_bmap_init(&flist, &firstblock);
1129         switch (ip->i_d.di_format) {
1130         case XFS_DINODE_FMT_LOCAL:
1131                 error = xfs_bmap_add_attrfork_local(tp, ip, &firstblock, &flist,
1132                         &logflags);
1133                 break;
1134         case XFS_DINODE_FMT_EXTENTS:
1135                 error = xfs_bmap_add_attrfork_extents(tp, ip, &firstblock,
1136                         &flist, &logflags);
1137                 break;
1138         case XFS_DINODE_FMT_BTREE:
1139                 error = xfs_bmap_add_attrfork_btree(tp, ip, &firstblock, &flist,
1140                         &logflags);
1141                 break;
1142         default:
1143                 error = 0;
1144                 break;
1145         }
1146         if (logflags)
1147                 xfs_trans_log_inode(tp, ip, logflags);
1148         if (error)
1149                 goto bmap_cancel;
1150         if (!xfs_sb_version_hasattr(&mp->m_sb) ||
1151            (!xfs_sb_version_hasattr2(&mp->m_sb) && version == 2)) {
1152                 bool log_sb = false;
1153
1154                 spin_lock(&mp->m_sb_lock);
1155                 if (!xfs_sb_version_hasattr(&mp->m_sb)) {
1156                         xfs_sb_version_addattr(&mp->m_sb);
1157                         log_sb = true;
1158                 }
1159                 if (!xfs_sb_version_hasattr2(&mp->m_sb) && version == 2) {
1160                         xfs_sb_version_addattr2(&mp->m_sb);
1161                         log_sb = true;
1162                 }
1163                 spin_unlock(&mp->m_sb_lock);
1164                 if (log_sb)
1165                         xfs_log_sb(tp);
1166         }
1167
1168         error = xfs_bmap_finish(&tp, &flist, NULL);
1169         if (error)
1170                 goto bmap_cancel;
1171         error = xfs_trans_commit(tp);
1172         xfs_iunlock(ip, XFS_ILOCK_EXCL);
1173         return error;
1174
1175 bmap_cancel:
1176         xfs_bmap_cancel(&flist);
1177 trans_cancel:
1178         xfs_trans_cancel(tp);
1179         xfs_iunlock(ip, XFS_ILOCK_EXCL);
1180         return error;
1181 }
1182
1183 /*
1184  * Internal and external extent tree search functions.
1185  */
1186
1187 /*
1188  * Read in the extents to if_extents.
1189  * All inode fields are set up by caller, we just traverse the btree
1190  * and copy the records in. If the file system cannot contain unwritten
1191  * extents, the records are checked for no "state" flags.
1192  */
1193 int                                     /* error */
1194 xfs_bmap_read_extents(
1195         xfs_trans_t             *tp,    /* transaction pointer */
1196         xfs_inode_t             *ip,    /* incore inode */
1197         int                     whichfork) /* data or attr fork */
1198 {
1199         struct xfs_btree_block  *block; /* current btree block */
1200         xfs_fsblock_t           bno;    /* block # of "block" */
1201         xfs_buf_t               *bp;    /* buffer for "block" */
1202         int                     error;  /* error return value */
1203         xfs_exntfmt_t           exntf;  /* XFS_EXTFMT_NOSTATE, if checking */
1204         xfs_extnum_t            i, j;   /* index into the extents list */
1205         xfs_ifork_t             *ifp;   /* fork structure */
1206         int                     level;  /* btree level, for checking */
1207         xfs_mount_t             *mp;    /* file system mount structure */
1208         __be64                  *pp;    /* pointer to block address */
1209         /* REFERENCED */
1210         xfs_extnum_t            room;   /* number of entries there's room for */
1211
1212         bno = NULLFSBLOCK;
1213         mp = ip->i_mount;
1214         ifp = XFS_IFORK_PTR(ip, whichfork);
1215         exntf = (whichfork != XFS_DATA_FORK) ? XFS_EXTFMT_NOSTATE :
1216                                         XFS_EXTFMT_INODE(ip);
1217         block = ifp->if_broot;
1218         /*
1219          * Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out.
1220          */
1221         level = be16_to_cpu(block->bb_level);
1222         ASSERT(level > 0);
1223         pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, 1, ifp->if_broot_bytes);
1224         bno = be64_to_cpu(*pp);
1225         ASSERT(bno != NULLFSBLOCK);
1226         ASSERT(XFS_FSB_TO_AGNO(mp, bno) < mp->m_sb.sb_agcount);
1227         ASSERT(XFS_FSB_TO_AGBNO(mp, bno) < mp->m_sb.sb_agblocks);
1228         /*
1229          * Go down the tree until leaf level is reached, following the first
1230          * pointer (leftmost) at each level.
1231          */
1232         while (level-- > 0) {
1233                 error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp,
1234                                 XFS_BMAP_BTREE_REF, &xfs_bmbt_buf_ops);
1235                 if (error)
1236                         return error;
1237                 block = XFS_BUF_TO_BLOCK(bp);
1238                 if (level == 0)
1239                         break;
1240                 pp = XFS_BMBT_PTR_ADDR(mp, block, 1, mp->m_bmap_dmxr[1]);
1241                 bno = be64_to_cpu(*pp);
1242                 XFS_WANT_CORRUPTED_GOTO(mp,
1243                         XFS_FSB_SANITY_CHECK(mp, bno), error0);
1244                 xfs_trans_brelse(tp, bp);
1245         }
1246         /*
1247          * Here with bp and block set to the leftmost leaf node in the tree.
1248          */
1249         room = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
1250         i = 0;
1251         /*
1252          * Loop over all leaf nodes.  Copy information to the extent records.
1253          */
1254         for (;;) {
1255                 xfs_bmbt_rec_t  *frp;
1256                 xfs_fsblock_t   nextbno;
1257                 xfs_extnum_t    num_recs;
1258                 xfs_extnum_t    start;
1259
1260                 num_recs = xfs_btree_get_numrecs(block);
1261                 if (unlikely(i + num_recs > room)) {
1262                         ASSERT(i + num_recs <= room);
1263                         xfs_warn(ip->i_mount,
1264                                 "corrupt dinode %Lu, (btree extents).",
1265                                 (unsigned long long) ip->i_ino);
1266                         XFS_CORRUPTION_ERROR("xfs_bmap_read_extents(1)",
1267                                 XFS_ERRLEVEL_LOW, ip->i_mount, block);
1268                         goto error0;
1269                 }
1270                 /*
1271                  * Read-ahead the next leaf block, if any.
1272                  */
1273                 nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib);
1274                 if (nextbno != NULLFSBLOCK)
1275                         xfs_btree_reada_bufl(mp, nextbno, 1,
1276                                              &xfs_bmbt_buf_ops);
1277                 /*
1278                  * Copy records into the extent records.
1279                  */
1280                 frp = XFS_BMBT_REC_ADDR(mp, block, 1);
1281                 start = i;
1282                 for (j = 0; j < num_recs; j++, i++, frp++) {
1283                         xfs_bmbt_rec_host_t *trp = xfs_iext_get_ext(ifp, i);
1284                         trp->l0 = be64_to_cpu(frp->l0);
1285                         trp->l1 = be64_to_cpu(frp->l1);
1286                 }
1287                 if (exntf == XFS_EXTFMT_NOSTATE) {
1288                         /*
1289                          * Check all attribute bmap btree records and
1290                          * any "older" data bmap btree records for a
1291                          * set bit in the "extent flag" position.
1292                          */
1293                         if (unlikely(xfs_check_nostate_extents(ifp,
1294                                         start, num_recs))) {
1295                                 XFS_ERROR_REPORT("xfs_bmap_read_extents(2)",
1296                                                  XFS_ERRLEVEL_LOW,
1297                                                  ip->i_mount);
1298                                 goto error0;
1299                         }
1300                 }
1301                 xfs_trans_brelse(tp, bp);
1302                 bno = nextbno;
1303                 /*
1304                  * If we've reached the end, stop.
1305                  */
1306                 if (bno == NULLFSBLOCK)
1307                         break;
1308                 error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp,
1309                                 XFS_BMAP_BTREE_REF, &xfs_bmbt_buf_ops);
1310                 if (error)
1311                         return error;
1312                 block = XFS_BUF_TO_BLOCK(bp);
1313         }
1314         ASSERT(i == (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t)));
1315         ASSERT(i == XFS_IFORK_NEXTENTS(ip, whichfork));
1316         XFS_BMAP_TRACE_EXLIST(ip, i, whichfork);
1317         return 0;
1318 error0:
1319         xfs_trans_brelse(tp, bp);
1320         return -EFSCORRUPTED;
1321 }
1322
1323
1324 /*
1325  * Search the extent records for the entry containing block bno.
1326  * If bno lies in a hole, point to the next entry.  If bno lies
1327  * past eof, *eofp will be set, and *prevp will contain the last
1328  * entry (null if none).  Else, *lastxp will be set to the index
1329  * of the found entry; *gotp will contain the entry.
1330  */
1331 STATIC xfs_bmbt_rec_host_t *            /* pointer to found extent entry */
1332 xfs_bmap_search_multi_extents(
1333         xfs_ifork_t     *ifp,           /* inode fork pointer */
1334         xfs_fileoff_t   bno,            /* block number searched for */
1335         int             *eofp,          /* out: end of file found */
1336         xfs_extnum_t    *lastxp,        /* out: last extent index */
1337         xfs_bmbt_irec_t *gotp,          /* out: extent entry found */
1338         xfs_bmbt_irec_t *prevp)         /* out: previous extent entry found */
1339 {
1340         xfs_bmbt_rec_host_t *ep;                /* extent record pointer */
1341         xfs_extnum_t    lastx;          /* last extent index */
1342
1343         /*
1344          * Initialize the extent entry structure to catch access to
1345          * uninitialized br_startblock field.
1346          */
1347         gotp->br_startoff = 0xffa5a5a5a5a5a5a5LL;
1348         gotp->br_blockcount = 0xa55a5a5a5a5a5a5aLL;
1349         gotp->br_state = XFS_EXT_INVALID;
1350         gotp->br_startblock = 0xffffa5a5a5a5a5a5LL;
1351         prevp->br_startoff = NULLFILEOFF;
1352
1353         ep = xfs_iext_bno_to_ext(ifp, bno, &lastx);
1354         if (lastx > 0) {
1355                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, lastx - 1), prevp);
1356         }
1357         if (lastx < (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t))) {
1358                 xfs_bmbt_get_all(ep, gotp);
1359                 *eofp = 0;
1360         } else {
1361                 if (lastx > 0) {
1362                         *gotp = *prevp;
1363                 }
1364                 *eofp = 1;
1365                 ep = NULL;
1366         }
1367         *lastxp = lastx;
1368         return ep;
1369 }
1370
1371 /*
1372  * Search the extents list for the inode, for the extent containing bno.
1373  * If bno lies in a hole, point to the next entry.  If bno lies past eof,
1374  * *eofp will be set, and *prevp will contain the last entry (null if none).
1375  * Else, *lastxp will be set to the index of the found
1376  * entry; *gotp will contain the entry.
1377  */
1378 STATIC xfs_bmbt_rec_host_t *                 /* pointer to found extent entry */
1379 xfs_bmap_search_extents(
1380         xfs_inode_t     *ip,            /* incore inode pointer */
1381         xfs_fileoff_t   bno,            /* block number searched for */
1382         int             fork,           /* data or attr fork */
1383         int             *eofp,          /* out: end of file found */
1384         xfs_extnum_t    *lastxp,        /* out: last extent index */
1385         xfs_bmbt_irec_t *gotp,          /* out: extent entry found */
1386         xfs_bmbt_irec_t *prevp)         /* out: previous extent entry found */
1387 {
1388         xfs_ifork_t     *ifp;           /* inode fork pointer */
1389         xfs_bmbt_rec_host_t  *ep;            /* extent record pointer */
1390
1391         XFS_STATS_INC(ip->i_mount, xs_look_exlist);
1392         ifp = XFS_IFORK_PTR(ip, fork);
1393
1394         ep = xfs_bmap_search_multi_extents(ifp, bno, eofp, lastxp, gotp, prevp);
1395
1396         if (unlikely(!(gotp->br_startblock) && (*lastxp != NULLEXTNUM) &&
1397                      !(XFS_IS_REALTIME_INODE(ip) && fork == XFS_DATA_FORK))) {
1398                 xfs_alert_tag(ip->i_mount, XFS_PTAG_FSBLOCK_ZERO,
1399                                 "Access to block zero in inode %llu "
1400                                 "start_block: %llx start_off: %llx "
1401                                 "blkcnt: %llx extent-state: %x lastx: %x",
1402                         (unsigned long long)ip->i_ino,
1403                         (unsigned long long)gotp->br_startblock,
1404                         (unsigned long long)gotp->br_startoff,
1405                         (unsigned long long)gotp->br_blockcount,
1406                         gotp->br_state, *lastxp);
1407                 *lastxp = NULLEXTNUM;
1408                 *eofp = 1;
1409                 return NULL;
1410         }
1411         return ep;
1412 }
1413
1414 /*
1415  * Returns the file-relative block number of the first unused block(s)
1416  * in the file with at least "len" logically contiguous blocks free.
1417  * This is the lowest-address hole if the file has holes, else the first block
1418  * past the end of file.
1419  * Return 0 if the file is currently local (in-inode).
1420  */
1421 int                                             /* error */
1422 xfs_bmap_first_unused(
1423         xfs_trans_t     *tp,                    /* transaction pointer */
1424         xfs_inode_t     *ip,                    /* incore inode */
1425         xfs_extlen_t    len,                    /* size of hole to find */
1426         xfs_fileoff_t   *first_unused,          /* unused block */
1427         int             whichfork)              /* data or attr fork */
1428 {
1429         int             error;                  /* error return value */
1430         int             idx;                    /* extent record index */
1431         xfs_ifork_t     *ifp;                   /* inode fork pointer */
1432         xfs_fileoff_t   lastaddr;               /* last block number seen */
1433         xfs_fileoff_t   lowest;                 /* lowest useful block */
1434         xfs_fileoff_t   max;                    /* starting useful block */
1435         xfs_fileoff_t   off;                    /* offset for this block */
1436         xfs_extnum_t    nextents;               /* number of extent entries */
1437
1438         ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE ||
1439                XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS ||
1440                XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL);
1441         if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) {
1442                 *first_unused = 0;
1443                 return 0;
1444         }
1445         ifp = XFS_IFORK_PTR(ip, whichfork);
1446         if (!(ifp->if_flags & XFS_IFEXTENTS) &&
1447             (error = xfs_iread_extents(tp, ip, whichfork)))
1448                 return error;
1449         lowest = *first_unused;
1450         nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
1451         for (idx = 0, lastaddr = 0, max = lowest; idx < nextents; idx++) {
1452                 xfs_bmbt_rec_host_t *ep = xfs_iext_get_ext(ifp, idx);
1453                 off = xfs_bmbt_get_startoff(ep);
1454                 /*
1455                  * See if the hole before this extent will work.
1456                  */
1457                 if (off >= lowest + len && off - max >= len) {
1458                         *first_unused = max;
1459                         return 0;
1460                 }
1461                 lastaddr = off + xfs_bmbt_get_blockcount(ep);
1462                 max = XFS_FILEOFF_MAX(lastaddr, lowest);
1463         }
1464         *first_unused = max;
1465         return 0;
1466 }
1467
1468 /*
1469  * Returns the file-relative block number of the last block - 1 before
1470  * last_block (input value) in the file.
1471  * This is not based on i_size, it is based on the extent records.
1472  * Returns 0 for local files, as they do not have extent records.
1473  */
1474 int                                             /* error */
1475 xfs_bmap_last_before(
1476         xfs_trans_t     *tp,                    /* transaction pointer */
1477         xfs_inode_t     *ip,                    /* incore inode */
1478         xfs_fileoff_t   *last_block,            /* last block */
1479         int             whichfork)              /* data or attr fork */
1480 {
1481         xfs_fileoff_t   bno;                    /* input file offset */
1482         int             eof;                    /* hit end of file */
1483         xfs_bmbt_rec_host_t *ep;                /* pointer to last extent */
1484         int             error;                  /* error return value */
1485         xfs_bmbt_irec_t got;                    /* current extent value */
1486         xfs_ifork_t     *ifp;                   /* inode fork pointer */
1487         xfs_extnum_t    lastx;                  /* last extent used */
1488         xfs_bmbt_irec_t prev;                   /* previous extent value */
1489
1490         if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE &&
1491             XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
1492             XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_LOCAL)
1493                return -EIO;
1494         if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) {
1495                 *last_block = 0;
1496                 return 0;
1497         }
1498         ifp = XFS_IFORK_PTR(ip, whichfork);
1499         if (!(ifp->if_flags & XFS_IFEXTENTS) &&
1500             (error = xfs_iread_extents(tp, ip, whichfork)))
1501                 return error;
1502         bno = *last_block - 1;
1503         ep = xfs_bmap_search_extents(ip, bno, whichfork, &eof, &lastx, &got,
1504                 &prev);
1505         if (eof || xfs_bmbt_get_startoff(ep) > bno) {
1506                 if (prev.br_startoff == NULLFILEOFF)
1507                         *last_block = 0;
1508                 else
1509                         *last_block = prev.br_startoff + prev.br_blockcount;
1510         }
1511         /*
1512          * Otherwise *last_block is already the right answer.
1513          */
1514         return 0;
1515 }
1516
1517 int
1518 xfs_bmap_last_extent(
1519         struct xfs_trans        *tp,
1520         struct xfs_inode        *ip,
1521         int                     whichfork,
1522         struct xfs_bmbt_irec    *rec,
1523         int                     *is_empty)
1524 {
1525         struct xfs_ifork        *ifp = XFS_IFORK_PTR(ip, whichfork);
1526         int                     error;
1527         int                     nextents;
1528
1529         if (!(ifp->if_flags & XFS_IFEXTENTS)) {
1530                 error = xfs_iread_extents(tp, ip, whichfork);
1531                 if (error)
1532                         return error;
1533         }
1534
1535         nextents = ifp->if_bytes / sizeof(xfs_bmbt_rec_t);
1536         if (nextents == 0) {
1537                 *is_empty = 1;
1538                 return 0;
1539         }
1540
1541         xfs_bmbt_get_all(xfs_iext_get_ext(ifp, nextents - 1), rec);
1542         *is_empty = 0;
1543         return 0;
1544 }
1545
1546 /*
1547  * Check the last inode extent to determine whether this allocation will result
1548  * in blocks being allocated at the end of the file. When we allocate new data
1549  * blocks at the end of the file which do not start at the previous data block,
1550  * we will try to align the new blocks at stripe unit boundaries.
1551  *
1552  * Returns 1 in bma->aeof if the file (fork) is empty as any new write will be
1553  * at, or past the EOF.
1554  */
1555 STATIC int
1556 xfs_bmap_isaeof(
1557         struct xfs_bmalloca     *bma,
1558         int                     whichfork)
1559 {
1560         struct xfs_bmbt_irec    rec;
1561         int                     is_empty;
1562         int                     error;
1563
1564         bma->aeof = 0;
1565         error = xfs_bmap_last_extent(NULL, bma->ip, whichfork, &rec,
1566                                      &is_empty);
1567         if (error)
1568                 return error;
1569
1570         if (is_empty) {
1571                 bma->aeof = 1;
1572                 return 0;
1573         }
1574
1575         /*
1576          * Check if we are allocation or past the last extent, or at least into
1577          * the last delayed allocated extent.
1578          */
1579         bma->aeof = bma->offset >= rec.br_startoff + rec.br_blockcount ||
1580                 (bma->offset >= rec.br_startoff &&
1581                  isnullstartblock(rec.br_startblock));
1582         return 0;
1583 }
1584
1585 /*
1586  * Returns the file-relative block number of the first block past eof in
1587  * the file.  This is not based on i_size, it is based on the extent records.
1588  * Returns 0 for local files, as they do not have extent records.
1589  */
1590 int
1591 xfs_bmap_last_offset(
1592         struct xfs_inode        *ip,
1593         xfs_fileoff_t           *last_block,
1594         int                     whichfork)
1595 {
1596         struct xfs_bmbt_irec    rec;
1597         int                     is_empty;
1598         int                     error;
1599
1600         *last_block = 0;
1601
1602         if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL)
1603                 return 0;
1604
1605         if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE &&
1606             XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
1607                return -EIO;
1608
1609         error = xfs_bmap_last_extent(NULL, ip, whichfork, &rec, &is_empty);
1610         if (error || is_empty)
1611                 return error;
1612
1613         *last_block = rec.br_startoff + rec.br_blockcount;
1614         return 0;
1615 }
1616
1617 /*
1618  * Returns whether the selected fork of the inode has exactly one
1619  * block or not.  For the data fork we check this matches di_size,
1620  * implying the file's range is 0..bsize-1.
1621  */
1622 int                                     /* 1=>1 block, 0=>otherwise */
1623 xfs_bmap_one_block(
1624         xfs_inode_t     *ip,            /* incore inode */
1625         int             whichfork)      /* data or attr fork */
1626 {
1627         xfs_bmbt_rec_host_t *ep;        /* ptr to fork's extent */
1628         xfs_ifork_t     *ifp;           /* inode fork pointer */
1629         int             rval;           /* return value */
1630         xfs_bmbt_irec_t s;              /* internal version of extent */
1631
1632 #ifndef DEBUG
1633         if (whichfork == XFS_DATA_FORK)
1634                 return XFS_ISIZE(ip) == ip->i_mount->m_sb.sb_blocksize;
1635 #endif  /* !DEBUG */
1636         if (XFS_IFORK_NEXTENTS(ip, whichfork) != 1)
1637                 return 0;
1638         if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
1639                 return 0;
1640         ifp = XFS_IFORK_PTR(ip, whichfork);
1641         ASSERT(ifp->if_flags & XFS_IFEXTENTS);
1642         ep = xfs_iext_get_ext(ifp, 0);
1643         xfs_bmbt_get_all(ep, &s);
1644         rval = s.br_startoff == 0 && s.br_blockcount == 1;
1645         if (rval && whichfork == XFS_DATA_FORK)
1646                 ASSERT(XFS_ISIZE(ip) == ip->i_mount->m_sb.sb_blocksize);
1647         return rval;
1648 }
1649
1650 /*
1651  * Extent tree manipulation functions used during allocation.
1652  */
1653
1654 /*
1655  * Convert a delayed allocation to a real allocation.
1656  */
1657 STATIC int                              /* error */
1658 xfs_bmap_add_extent_delay_real(
1659         struct xfs_bmalloca     *bma)
1660 {
1661         struct xfs_bmbt_irec    *new = &bma->got;
1662         int                     diff;   /* temp value */
1663         xfs_bmbt_rec_host_t     *ep;    /* extent entry for idx */
1664         int                     error;  /* error return value */
1665         int                     i;      /* temp state */
1666         xfs_ifork_t             *ifp;   /* inode fork pointer */
1667         xfs_fileoff_t           new_endoff;     /* end offset of new entry */
1668         xfs_bmbt_irec_t         r[3];   /* neighbor extent entries */
1669                                         /* left is 0, right is 1, prev is 2 */
1670         int                     rval=0; /* return value (logging flags) */
1671         int                     state = 0;/* state bits, accessed thru macros */
1672         xfs_filblks_t           da_new; /* new count del alloc blocks used */
1673         xfs_filblks_t           da_old; /* old count del alloc blocks used */
1674         xfs_filblks_t           temp=0; /* value for da_new calculations */
1675         xfs_filblks_t           temp2=0;/* value for da_new calculations */
1676         int                     tmp_rval;       /* partial logging flags */
1677         int                     whichfork = XFS_DATA_FORK;
1678         struct xfs_mount        *mp;
1679
1680         mp = bma->ip->i_mount;
1681         ifp = XFS_IFORK_PTR(bma->ip, whichfork);
1682
1683         ASSERT(bma->idx >= 0);
1684         ASSERT(bma->idx <= ifp->if_bytes / sizeof(struct xfs_bmbt_rec));
1685         ASSERT(!isnullstartblock(new->br_startblock));
1686         ASSERT(!bma->cur ||
1687                (bma->cur->bc_private.b.flags & XFS_BTCUR_BPRV_WASDEL));
1688
1689         XFS_STATS_INC(mp, xs_add_exlist);
1690
1691 #define LEFT            r[0]
1692 #define RIGHT           r[1]
1693 #define PREV            r[2]
1694
1695         /*
1696          * Set up a bunch of variables to make the tests simpler.
1697          */
1698         ep = xfs_iext_get_ext(ifp, bma->idx);
1699         xfs_bmbt_get_all(ep, &PREV);
1700         new_endoff = new->br_startoff + new->br_blockcount;
1701         ASSERT(PREV.br_startoff <= new->br_startoff);
1702         ASSERT(PREV.br_startoff + PREV.br_blockcount >= new_endoff);
1703
1704         da_old = startblockval(PREV.br_startblock);
1705         da_new = 0;
1706
1707         /*
1708          * Set flags determining what part of the previous delayed allocation
1709          * extent is being replaced by a real allocation.
1710          */
1711         if (PREV.br_startoff == new->br_startoff)
1712                 state |= BMAP_LEFT_FILLING;
1713         if (PREV.br_startoff + PREV.br_blockcount == new_endoff)
1714                 state |= BMAP_RIGHT_FILLING;
1715
1716         /*
1717          * Check and set flags if this segment has a left neighbor.
1718          * Don't set contiguous if the combined extent would be too large.
1719          */
1720         if (bma->idx > 0) {
1721                 state |= BMAP_LEFT_VALID;
1722                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx - 1), &LEFT);
1723
1724                 if (isnullstartblock(LEFT.br_startblock))
1725                         state |= BMAP_LEFT_DELAY;
1726         }
1727
1728         if ((state & BMAP_LEFT_VALID) && !(state & BMAP_LEFT_DELAY) &&
1729             LEFT.br_startoff + LEFT.br_blockcount == new->br_startoff &&
1730             LEFT.br_startblock + LEFT.br_blockcount == new->br_startblock &&
1731             LEFT.br_state == new->br_state &&
1732             LEFT.br_blockcount + new->br_blockcount <= MAXEXTLEN)
1733                 state |= BMAP_LEFT_CONTIG;
1734
1735         /*
1736          * Check and set flags if this segment has a right neighbor.
1737          * Don't set contiguous if the combined extent would be too large.
1738          * Also check for all-three-contiguous being too large.
1739          */
1740         if (bma->idx < ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t) - 1) {
1741                 state |= BMAP_RIGHT_VALID;
1742                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx + 1), &RIGHT);
1743
1744                 if (isnullstartblock(RIGHT.br_startblock))
1745                         state |= BMAP_RIGHT_DELAY;
1746         }
1747
1748         if ((state & BMAP_RIGHT_VALID) && !(state & BMAP_RIGHT_DELAY) &&
1749             new_endoff == RIGHT.br_startoff &&
1750             new->br_startblock + new->br_blockcount == RIGHT.br_startblock &&
1751             new->br_state == RIGHT.br_state &&
1752             new->br_blockcount + RIGHT.br_blockcount <= MAXEXTLEN &&
1753             ((state & (BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING |
1754                        BMAP_RIGHT_FILLING)) !=
1755                       (BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING |
1756                        BMAP_RIGHT_FILLING) ||
1757              LEFT.br_blockcount + new->br_blockcount + RIGHT.br_blockcount
1758                         <= MAXEXTLEN))
1759                 state |= BMAP_RIGHT_CONTIG;
1760
1761         error = 0;
1762         /*
1763          * Switch out based on the FILLING and CONTIG state bits.
1764          */
1765         switch (state & (BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG |
1766                          BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG)) {
1767         case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG |
1768              BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
1769                 /*
1770                  * Filling in all of a previously delayed allocation extent.
1771                  * The left and right neighbors are both contiguous with new.
1772                  */
1773                 bma->idx--;
1774                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
1775                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx),
1776                         LEFT.br_blockcount + PREV.br_blockcount +
1777                         RIGHT.br_blockcount);
1778                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
1779
1780                 xfs_iext_remove(bma->ip, bma->idx + 1, 2, state);
1781                 bma->ip->i_d.di_nextents--;
1782                 if (bma->cur == NULL)
1783                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
1784                 else {
1785                         rval = XFS_ILOG_CORE;
1786                         error = xfs_bmbt_lookup_eq(bma->cur, RIGHT.br_startoff,
1787                                         RIGHT.br_startblock,
1788                                         RIGHT.br_blockcount, &i);
1789                         if (error)
1790                                 goto done;
1791                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1792                         error = xfs_btree_delete(bma->cur, &i);
1793                         if (error)
1794                                 goto done;
1795                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1796                         error = xfs_btree_decrement(bma->cur, 0, &i);
1797                         if (error)
1798                                 goto done;
1799                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1800                         error = xfs_bmbt_update(bma->cur, LEFT.br_startoff,
1801                                         LEFT.br_startblock,
1802                                         LEFT.br_blockcount +
1803                                         PREV.br_blockcount +
1804                                         RIGHT.br_blockcount, LEFT.br_state);
1805                         if (error)
1806                                 goto done;
1807                 }
1808                 break;
1809
1810         case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG:
1811                 /*
1812                  * Filling in all of a previously delayed allocation extent.
1813                  * The left neighbor is contiguous, the right is not.
1814                  */
1815                 bma->idx--;
1816
1817                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
1818                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx),
1819                         LEFT.br_blockcount + PREV.br_blockcount);
1820                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
1821
1822                 xfs_iext_remove(bma->ip, bma->idx + 1, 1, state);
1823                 if (bma->cur == NULL)
1824                         rval = XFS_ILOG_DEXT;
1825                 else {
1826                         rval = 0;
1827                         error = xfs_bmbt_lookup_eq(bma->cur, LEFT.br_startoff,
1828                                         LEFT.br_startblock, LEFT.br_blockcount,
1829                                         &i);
1830                         if (error)
1831                                 goto done;
1832                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1833                         error = xfs_bmbt_update(bma->cur, LEFT.br_startoff,
1834                                         LEFT.br_startblock,
1835                                         LEFT.br_blockcount +
1836                                         PREV.br_blockcount, LEFT.br_state);
1837                         if (error)
1838                                 goto done;
1839                 }
1840                 break;
1841
1842         case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
1843                 /*
1844                  * Filling in all of a previously delayed allocation extent.
1845                  * The right neighbor is contiguous, the left is not.
1846                  */
1847                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
1848                 xfs_bmbt_set_startblock(ep, new->br_startblock);
1849                 xfs_bmbt_set_blockcount(ep,
1850                         PREV.br_blockcount + RIGHT.br_blockcount);
1851                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
1852
1853                 xfs_iext_remove(bma->ip, bma->idx + 1, 1, state);
1854                 if (bma->cur == NULL)
1855                         rval = XFS_ILOG_DEXT;
1856                 else {
1857                         rval = 0;
1858                         error = xfs_bmbt_lookup_eq(bma->cur, RIGHT.br_startoff,
1859                                         RIGHT.br_startblock,
1860                                         RIGHT.br_blockcount, &i);
1861                         if (error)
1862                                 goto done;
1863                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1864                         error = xfs_bmbt_update(bma->cur, PREV.br_startoff,
1865                                         new->br_startblock,
1866                                         PREV.br_blockcount +
1867                                         RIGHT.br_blockcount, PREV.br_state);
1868                         if (error)
1869                                 goto done;
1870                 }
1871                 break;
1872
1873         case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING:
1874                 /*
1875                  * Filling in all of a previously delayed allocation extent.
1876                  * Neither the left nor right neighbors are contiguous with
1877                  * the new one.
1878                  */
1879                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
1880                 xfs_bmbt_set_startblock(ep, new->br_startblock);
1881                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
1882
1883                 bma->ip->i_d.di_nextents++;
1884                 if (bma->cur == NULL)
1885                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
1886                 else {
1887                         rval = XFS_ILOG_CORE;
1888                         error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff,
1889                                         new->br_startblock, new->br_blockcount,
1890                                         &i);
1891                         if (error)
1892                                 goto done;
1893                         XFS_WANT_CORRUPTED_GOTO(mp, i == 0, done);
1894                         bma->cur->bc_rec.b.br_state = XFS_EXT_NORM;
1895                         error = xfs_btree_insert(bma->cur, &i);
1896                         if (error)
1897                                 goto done;
1898                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1899                 }
1900                 break;
1901
1902         case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG:
1903                 /*
1904                  * Filling in the first part of a previous delayed allocation.
1905                  * The left neighbor is contiguous.
1906                  */
1907                 trace_xfs_bmap_pre_update(bma->ip, bma->idx - 1, state, _THIS_IP_);
1908                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx - 1),
1909                         LEFT.br_blockcount + new->br_blockcount);
1910                 xfs_bmbt_set_startoff(ep,
1911                         PREV.br_startoff + new->br_blockcount);
1912                 trace_xfs_bmap_post_update(bma->ip, bma->idx - 1, state, _THIS_IP_);
1913
1914                 temp = PREV.br_blockcount - new->br_blockcount;
1915                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
1916                 xfs_bmbt_set_blockcount(ep, temp);
1917                 if (bma->cur == NULL)
1918                         rval = XFS_ILOG_DEXT;
1919                 else {
1920                         rval = 0;
1921                         error = xfs_bmbt_lookup_eq(bma->cur, LEFT.br_startoff,
1922                                         LEFT.br_startblock, LEFT.br_blockcount,
1923                                         &i);
1924                         if (error)
1925                                 goto done;
1926                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1927                         error = xfs_bmbt_update(bma->cur, LEFT.br_startoff,
1928                                         LEFT.br_startblock,
1929                                         LEFT.br_blockcount +
1930                                         new->br_blockcount,
1931                                         LEFT.br_state);
1932                         if (error)
1933                                 goto done;
1934                 }
1935                 da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp),
1936                         startblockval(PREV.br_startblock));
1937                 xfs_bmbt_set_startblock(ep, nullstartblock(da_new));
1938                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
1939
1940                 bma->idx--;
1941                 break;
1942
1943         case BMAP_LEFT_FILLING:
1944                 /*
1945                  * Filling in the first part of a previous delayed allocation.
1946                  * The left neighbor is not contiguous.
1947                  */
1948                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
1949                 xfs_bmbt_set_startoff(ep, new_endoff);
1950                 temp = PREV.br_blockcount - new->br_blockcount;
1951                 xfs_bmbt_set_blockcount(ep, temp);
1952                 xfs_iext_insert(bma->ip, bma->idx, 1, new, state);
1953                 bma->ip->i_d.di_nextents++;
1954                 if (bma->cur == NULL)
1955                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
1956                 else {
1957                         rval = XFS_ILOG_CORE;
1958                         error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff,
1959                                         new->br_startblock, new->br_blockcount,
1960                                         &i);
1961                         if (error)
1962                                 goto done;
1963                         XFS_WANT_CORRUPTED_GOTO(mp, i == 0, done);
1964                         bma->cur->bc_rec.b.br_state = XFS_EXT_NORM;
1965                         error = xfs_btree_insert(bma->cur, &i);
1966                         if (error)
1967                                 goto done;
1968                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
1969                 }
1970
1971                 if (xfs_bmap_needs_btree(bma->ip, whichfork)) {
1972                         error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
1973                                         bma->firstblock, bma->flist,
1974                                         &bma->cur, 1, &tmp_rval, whichfork);
1975                         rval |= tmp_rval;
1976                         if (error)
1977                                 goto done;
1978                 }
1979                 da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp),
1980                         startblockval(PREV.br_startblock) -
1981                         (bma->cur ? bma->cur->bc_private.b.allocated : 0));
1982                 ep = xfs_iext_get_ext(ifp, bma->idx + 1);
1983                 xfs_bmbt_set_startblock(ep, nullstartblock(da_new));
1984                 trace_xfs_bmap_post_update(bma->ip, bma->idx + 1, state, _THIS_IP_);
1985                 break;
1986
1987         case BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
1988                 /*
1989                  * Filling in the last part of a previous delayed allocation.
1990                  * The right neighbor is contiguous with the new allocation.
1991                  */
1992                 temp = PREV.br_blockcount - new->br_blockcount;
1993                 trace_xfs_bmap_pre_update(bma->ip, bma->idx + 1, state, _THIS_IP_);
1994                 xfs_bmbt_set_blockcount(ep, temp);
1995                 xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, bma->idx + 1),
1996                         new->br_startoff, new->br_startblock,
1997                         new->br_blockcount + RIGHT.br_blockcount,
1998                         RIGHT.br_state);
1999                 trace_xfs_bmap_post_update(bma->ip, bma->idx + 1, state, _THIS_IP_);
2000                 if (bma->cur == NULL)
2001                         rval = XFS_ILOG_DEXT;
2002                 else {
2003                         rval = 0;
2004                         error = xfs_bmbt_lookup_eq(bma->cur, RIGHT.br_startoff,
2005                                         RIGHT.br_startblock,
2006                                         RIGHT.br_blockcount, &i);
2007                         if (error)
2008                                 goto done;
2009                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2010                         error = xfs_bmbt_update(bma->cur, new->br_startoff,
2011                                         new->br_startblock,
2012                                         new->br_blockcount +
2013                                         RIGHT.br_blockcount,
2014                                         RIGHT.br_state);
2015                         if (error)
2016                                 goto done;
2017                 }
2018
2019                 da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp),
2020                         startblockval(PREV.br_startblock));
2021                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
2022                 xfs_bmbt_set_startblock(ep, nullstartblock(da_new));
2023                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
2024
2025                 bma->idx++;
2026                 break;
2027
2028         case BMAP_RIGHT_FILLING:
2029                 /*
2030                  * Filling in the last part of a previous delayed allocation.
2031                  * The right neighbor is not contiguous.
2032                  */
2033                 temp = PREV.br_blockcount - new->br_blockcount;
2034                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
2035                 xfs_bmbt_set_blockcount(ep, temp);
2036                 xfs_iext_insert(bma->ip, bma->idx + 1, 1, new, state);
2037                 bma->ip->i_d.di_nextents++;
2038                 if (bma->cur == NULL)
2039                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
2040                 else {
2041                         rval = XFS_ILOG_CORE;
2042                         error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff,
2043                                         new->br_startblock, new->br_blockcount,
2044                                         &i);
2045                         if (error)
2046                                 goto done;
2047                         XFS_WANT_CORRUPTED_GOTO(mp, i == 0, done);
2048                         bma->cur->bc_rec.b.br_state = XFS_EXT_NORM;
2049                         error = xfs_btree_insert(bma->cur, &i);
2050                         if (error)
2051                                 goto done;
2052                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2053                 }
2054
2055                 if (xfs_bmap_needs_btree(bma->ip, whichfork)) {
2056                         error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
2057                                 bma->firstblock, bma->flist, &bma->cur, 1,
2058                                 &tmp_rval, whichfork);
2059                         rval |= tmp_rval;
2060                         if (error)
2061                                 goto done;
2062                 }
2063                 da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp),
2064                         startblockval(PREV.br_startblock) -
2065                         (bma->cur ? bma->cur->bc_private.b.allocated : 0));
2066                 ep = xfs_iext_get_ext(ifp, bma->idx);
2067                 xfs_bmbt_set_startblock(ep, nullstartblock(da_new));
2068                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
2069
2070                 bma->idx++;
2071                 break;
2072
2073         case 0:
2074                 /*
2075                  * Filling in the middle part of a previous delayed allocation.
2076                  * Contiguity is impossible here.
2077                  * This case is avoided almost all the time.
2078                  *
2079                  * We start with a delayed allocation:
2080                  *
2081                  * +ddddddddddddddddddddddddddddddddddddddddddddddddddddddd+
2082                  *  PREV @ idx
2083                  *
2084                  * and we are allocating:
2085                  *                     +rrrrrrrrrrrrrrrrr+
2086                  *                            new
2087                  *
2088                  * and we set it up for insertion as:
2089                  * +ddddddddddddddddddd+rrrrrrrrrrrrrrrrr+ddddddddddddddddd+
2090                  *                            new
2091                  *  PREV @ idx          LEFT              RIGHT
2092                  *                      inserted at idx + 1
2093                  */
2094                 temp = new->br_startoff - PREV.br_startoff;
2095                 temp2 = PREV.br_startoff + PREV.br_blockcount - new_endoff;
2096                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, 0, _THIS_IP_);
2097                 xfs_bmbt_set_blockcount(ep, temp);      /* truncate PREV */
2098                 LEFT = *new;
2099                 RIGHT.br_state = PREV.br_state;
2100                 RIGHT.br_startblock = nullstartblock(
2101                                 (int)xfs_bmap_worst_indlen(bma->ip, temp2));
2102                 RIGHT.br_startoff = new_endoff;
2103                 RIGHT.br_blockcount = temp2;
2104                 /* insert LEFT (r[0]) and RIGHT (r[1]) at the same time */
2105                 xfs_iext_insert(bma->ip, bma->idx + 1, 2, &LEFT, state);
2106                 bma->ip->i_d.di_nextents++;
2107                 if (bma->cur == NULL)
2108                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
2109                 else {
2110                         rval = XFS_ILOG_CORE;
2111                         error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff,
2112                                         new->br_startblock, new->br_blockcount,
2113                                         &i);
2114                         if (error)
2115                                 goto done;
2116                         XFS_WANT_CORRUPTED_GOTO(mp, i == 0, done);
2117                         bma->cur->bc_rec.b.br_state = XFS_EXT_NORM;
2118                         error = xfs_btree_insert(bma->cur, &i);
2119                         if (error)
2120                                 goto done;
2121                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2122                 }
2123
2124                 if (xfs_bmap_needs_btree(bma->ip, whichfork)) {
2125                         error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
2126                                         bma->firstblock, bma->flist, &bma->cur,
2127                                         1, &tmp_rval, whichfork);
2128                         rval |= tmp_rval;
2129                         if (error)
2130                                 goto done;
2131                 }
2132                 temp = xfs_bmap_worst_indlen(bma->ip, temp);
2133                 temp2 = xfs_bmap_worst_indlen(bma->ip, temp2);
2134                 diff = (int)(temp + temp2 - startblockval(PREV.br_startblock) -
2135                         (bma->cur ? bma->cur->bc_private.b.allocated : 0));
2136                 if (diff > 0) {
2137                         error = xfs_mod_fdblocks(bma->ip->i_mount,
2138                                                  -((int64_t)diff), false);
2139                         ASSERT(!error);
2140                         if (error)
2141                                 goto done;
2142                 }
2143
2144                 ep = xfs_iext_get_ext(ifp, bma->idx);
2145                 xfs_bmbt_set_startblock(ep, nullstartblock((int)temp));
2146                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
2147                 trace_xfs_bmap_pre_update(bma->ip, bma->idx + 2, state, _THIS_IP_);
2148                 xfs_bmbt_set_startblock(xfs_iext_get_ext(ifp, bma->idx + 2),
2149                         nullstartblock((int)temp2));
2150                 trace_xfs_bmap_post_update(bma->ip, bma->idx + 2, state, _THIS_IP_);
2151
2152                 bma->idx++;
2153                 da_new = temp + temp2;
2154                 break;
2155
2156         case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
2157         case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
2158         case BMAP_LEFT_FILLING | BMAP_RIGHT_CONTIG:
2159         case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG:
2160         case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
2161         case BMAP_LEFT_CONTIG:
2162         case BMAP_RIGHT_CONTIG:
2163                 /*
2164                  * These cases are all impossible.
2165                  */
2166                 ASSERT(0);
2167         }
2168
2169         /* convert to a btree if necessary */
2170         if (xfs_bmap_needs_btree(bma->ip, whichfork)) {
2171                 int     tmp_logflags;   /* partial log flag return val */
2172
2173                 ASSERT(bma->cur == NULL);
2174                 error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
2175                                 bma->firstblock, bma->flist, &bma->cur,
2176                                 da_old > 0, &tmp_logflags, whichfork);
2177                 bma->logflags |= tmp_logflags;
2178                 if (error)
2179                         goto done;
2180         }
2181
2182         /* adjust for changes in reserved delayed indirect blocks */
2183         if (da_old || da_new) {
2184                 temp = da_new;
2185                 if (bma->cur)
2186                         temp += bma->cur->bc_private.b.allocated;
2187                 ASSERT(temp <= da_old);
2188                 if (temp < da_old)
2189                         xfs_mod_fdblocks(bma->ip->i_mount,
2190                                         (int64_t)(da_old - temp), false);
2191         }
2192
2193         /* clear out the allocated field, done with it now in any case. */
2194         if (bma->cur)
2195                 bma->cur->bc_private.b.allocated = 0;
2196
2197         xfs_bmap_check_leaf_extents(bma->cur, bma->ip, whichfork);
2198 done:
2199         bma->logflags |= rval;
2200         return error;
2201 #undef  LEFT
2202 #undef  RIGHT
2203 #undef  PREV
2204 }
2205
2206 /*
2207  * Convert an unwritten allocation to a real allocation or vice versa.
2208  */
2209 STATIC int                              /* error */
2210 xfs_bmap_add_extent_unwritten_real(
2211         struct xfs_trans        *tp,
2212         xfs_inode_t             *ip,    /* incore inode pointer */
2213         xfs_extnum_t            *idx,   /* extent number to update/insert */
2214         xfs_btree_cur_t         **curp, /* if *curp is null, not a btree */
2215         xfs_bmbt_irec_t         *new,   /* new data to add to file extents */
2216         xfs_fsblock_t           *first, /* pointer to firstblock variable */
2217         xfs_bmap_free_t         *flist, /* list of extents to be freed */
2218         int                     *logflagsp) /* inode logging flags */
2219 {
2220         xfs_btree_cur_t         *cur;   /* btree cursor */
2221         xfs_bmbt_rec_host_t     *ep;    /* extent entry for idx */
2222         int                     error;  /* error return value */
2223         int                     i;      /* temp state */
2224         xfs_ifork_t             *ifp;   /* inode fork pointer */
2225         xfs_fileoff_t           new_endoff;     /* end offset of new entry */
2226         xfs_exntst_t            newext; /* new extent state */
2227         xfs_exntst_t            oldext; /* old extent state */
2228         xfs_bmbt_irec_t         r[3];   /* neighbor extent entries */
2229                                         /* left is 0, right is 1, prev is 2 */
2230         int                     rval=0; /* return value (logging flags) */
2231         int                     state = 0;/* state bits, accessed thru macros */
2232         struct xfs_mount        *mp = tp->t_mountp;
2233
2234         *logflagsp = 0;
2235
2236         cur = *curp;
2237         ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
2238
2239         ASSERT(*idx >= 0);
2240         ASSERT(*idx <= ifp->if_bytes / sizeof(struct xfs_bmbt_rec));
2241         ASSERT(!isnullstartblock(new->br_startblock));
2242
2243         XFS_STATS_INC(mp, xs_add_exlist);
2244
2245 #define LEFT            r[0]
2246 #define RIGHT           r[1]
2247 #define PREV            r[2]
2248
2249         /*
2250          * Set up a bunch of variables to make the tests simpler.
2251          */
2252         error = 0;
2253         ep = xfs_iext_get_ext(ifp, *idx);
2254         xfs_bmbt_get_all(ep, &PREV);
2255         newext = new->br_state;
2256         oldext = (newext == XFS_EXT_UNWRITTEN) ?
2257                 XFS_EXT_NORM : XFS_EXT_UNWRITTEN;
2258         ASSERT(PREV.br_state == oldext);
2259         new_endoff = new->br_startoff + new->br_blockcount;
2260         ASSERT(PREV.br_startoff <= new->br_startoff);
2261         ASSERT(PREV.br_startoff + PREV.br_blockcount >= new_endoff);
2262
2263         /*
2264          * Set flags determining what part of the previous oldext allocation
2265          * extent is being replaced by a newext allocation.
2266          */
2267         if (PREV.br_startoff == new->br_startoff)
2268                 state |= BMAP_LEFT_FILLING;
2269         if (PREV.br_startoff + PREV.br_blockcount == new_endoff)
2270                 state |= BMAP_RIGHT_FILLING;
2271
2272         /*
2273          * Check and set flags if this segment has a left neighbor.
2274          * Don't set contiguous if the combined extent would be too large.
2275          */
2276         if (*idx > 0) {
2277                 state |= BMAP_LEFT_VALID;
2278                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx - 1), &LEFT);
2279
2280                 if (isnullstartblock(LEFT.br_startblock))
2281                         state |= BMAP_LEFT_DELAY;
2282         }
2283
2284         if ((state & BMAP_LEFT_VALID) && !(state & BMAP_LEFT_DELAY) &&
2285             LEFT.br_startoff + LEFT.br_blockcount == new->br_startoff &&
2286             LEFT.br_startblock + LEFT.br_blockcount == new->br_startblock &&
2287             LEFT.br_state == newext &&
2288             LEFT.br_blockcount + new->br_blockcount <= MAXEXTLEN)
2289                 state |= BMAP_LEFT_CONTIG;
2290
2291         /*
2292          * Check and set flags if this segment has a right neighbor.
2293          * Don't set contiguous if the combined extent would be too large.
2294          * Also check for all-three-contiguous being too large.
2295          */
2296         if (*idx < ip->i_df.if_bytes / (uint)sizeof(xfs_bmbt_rec_t) - 1) {
2297                 state |= BMAP_RIGHT_VALID;
2298                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx + 1), &RIGHT);
2299                 if (isnullstartblock(RIGHT.br_startblock))
2300                         state |= BMAP_RIGHT_DELAY;
2301         }
2302
2303         if ((state & BMAP_RIGHT_VALID) && !(state & BMAP_RIGHT_DELAY) &&
2304             new_endoff == RIGHT.br_startoff &&
2305             new->br_startblock + new->br_blockcount == RIGHT.br_startblock &&
2306             newext == RIGHT.br_state &&
2307             new->br_blockcount + RIGHT.br_blockcount <= MAXEXTLEN &&
2308             ((state & (BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING |
2309                        BMAP_RIGHT_FILLING)) !=
2310                       (BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING |
2311                        BMAP_RIGHT_FILLING) ||
2312              LEFT.br_blockcount + new->br_blockcount + RIGHT.br_blockcount
2313                         <= MAXEXTLEN))
2314                 state |= BMAP_RIGHT_CONTIG;
2315
2316         /*
2317          * Switch out based on the FILLING and CONTIG state bits.
2318          */
2319         switch (state & (BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG |
2320                          BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG)) {
2321         case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG |
2322              BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
2323                 /*
2324                  * Setting all of a previous oldext extent to newext.
2325                  * The left and right neighbors are both contiguous with new.
2326                  */
2327                 --*idx;
2328
2329                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2330                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx),
2331                         LEFT.br_blockcount + PREV.br_blockcount +
2332                         RIGHT.br_blockcount);
2333                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2334
2335                 xfs_iext_remove(ip, *idx + 1, 2, state);
2336                 ip->i_d.di_nextents -= 2;
2337                 if (cur == NULL)
2338                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
2339                 else {
2340                         rval = XFS_ILOG_CORE;
2341                         if ((error = xfs_bmbt_lookup_eq(cur, RIGHT.br_startoff,
2342                                         RIGHT.br_startblock,
2343                                         RIGHT.br_blockcount, &i)))
2344                                 goto done;
2345                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2346                         if ((error = xfs_btree_delete(cur, &i)))
2347                                 goto done;
2348                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2349                         if ((error = xfs_btree_decrement(cur, 0, &i)))
2350                                 goto done;
2351                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2352                         if ((error = xfs_btree_delete(cur, &i)))
2353                                 goto done;
2354                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2355                         if ((error = xfs_btree_decrement(cur, 0, &i)))
2356                                 goto done;
2357                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2358                         if ((error = xfs_bmbt_update(cur, LEFT.br_startoff,
2359                                 LEFT.br_startblock,
2360                                 LEFT.br_blockcount + PREV.br_blockcount +
2361                                 RIGHT.br_blockcount, LEFT.br_state)))
2362                                 goto done;
2363                 }
2364                 break;
2365
2366         case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG:
2367                 /*
2368                  * Setting all of a previous oldext extent to newext.
2369                  * The left neighbor is contiguous, the right is not.
2370                  */
2371                 --*idx;
2372
2373                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2374                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx),
2375                         LEFT.br_blockcount + PREV.br_blockcount);
2376                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2377
2378                 xfs_iext_remove(ip, *idx + 1, 1, state);
2379                 ip->i_d.di_nextents--;
2380                 if (cur == NULL)
2381                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
2382                 else {
2383                         rval = XFS_ILOG_CORE;
2384                         if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
2385                                         PREV.br_startblock, PREV.br_blockcount,
2386                                         &i)))
2387                                 goto done;
2388                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2389                         if ((error = xfs_btree_delete(cur, &i)))
2390                                 goto done;
2391                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2392                         if ((error = xfs_btree_decrement(cur, 0, &i)))
2393                                 goto done;
2394                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2395                         if ((error = xfs_bmbt_update(cur, LEFT.br_startoff,
2396                                 LEFT.br_startblock,
2397                                 LEFT.br_blockcount + PREV.br_blockcount,
2398                                 LEFT.br_state)))
2399                                 goto done;
2400                 }
2401                 break;
2402
2403         case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
2404                 /*
2405                  * Setting all of a previous oldext extent to newext.
2406                  * The right neighbor is contiguous, the left is not.
2407                  */
2408                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2409                 xfs_bmbt_set_blockcount(ep,
2410                         PREV.br_blockcount + RIGHT.br_blockcount);
2411                 xfs_bmbt_set_state(ep, newext);
2412                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2413                 xfs_iext_remove(ip, *idx + 1, 1, state);
2414                 ip->i_d.di_nextents--;
2415                 if (cur == NULL)
2416                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
2417                 else {
2418                         rval = XFS_ILOG_CORE;
2419                         if ((error = xfs_bmbt_lookup_eq(cur, RIGHT.br_startoff,
2420                                         RIGHT.br_startblock,
2421                                         RIGHT.br_blockcount, &i)))
2422                                 goto done;
2423                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2424                         if ((error = xfs_btree_delete(cur, &i)))
2425                                 goto done;
2426                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2427                         if ((error = xfs_btree_decrement(cur, 0, &i)))
2428                                 goto done;
2429                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2430                         if ((error = xfs_bmbt_update(cur, new->br_startoff,
2431                                 new->br_startblock,
2432                                 new->br_blockcount + RIGHT.br_blockcount,
2433                                 newext)))
2434                                 goto done;
2435                 }
2436                 break;
2437
2438         case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING:
2439                 /*
2440                  * Setting all of a previous oldext extent to newext.
2441                  * Neither the left nor right neighbors are contiguous with
2442                  * the new one.
2443                  */
2444                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2445                 xfs_bmbt_set_state(ep, newext);
2446                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2447
2448                 if (cur == NULL)
2449                         rval = XFS_ILOG_DEXT;
2450                 else {
2451                         rval = 0;
2452                         if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff,
2453                                         new->br_startblock, new->br_blockcount,
2454                                         &i)))
2455                                 goto done;
2456                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2457                         if ((error = xfs_bmbt_update(cur, new->br_startoff,
2458                                 new->br_startblock, new->br_blockcount,
2459                                 newext)))
2460                                 goto done;
2461                 }
2462                 break;
2463
2464         case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG:
2465                 /*
2466                  * Setting the first part of a previous oldext extent to newext.
2467                  * The left neighbor is contiguous.
2468                  */
2469                 trace_xfs_bmap_pre_update(ip, *idx - 1, state, _THIS_IP_);
2470                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx - 1),
2471                         LEFT.br_blockcount + new->br_blockcount);
2472                 xfs_bmbt_set_startoff(ep,
2473                         PREV.br_startoff + new->br_blockcount);
2474                 trace_xfs_bmap_post_update(ip, *idx - 1, state, _THIS_IP_);
2475
2476                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2477                 xfs_bmbt_set_startblock(ep,
2478                         new->br_startblock + new->br_blockcount);
2479                 xfs_bmbt_set_blockcount(ep,
2480                         PREV.br_blockcount - new->br_blockcount);
2481                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2482
2483                 --*idx;
2484
2485                 if (cur == NULL)
2486                         rval = XFS_ILOG_DEXT;
2487                 else {
2488                         rval = 0;
2489                         if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
2490                                         PREV.br_startblock, PREV.br_blockcount,
2491                                         &i)))
2492                                 goto done;
2493                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2494                         if ((error = xfs_bmbt_update(cur,
2495                                 PREV.br_startoff + new->br_blockcount,
2496                                 PREV.br_startblock + new->br_blockcount,
2497                                 PREV.br_blockcount - new->br_blockcount,
2498                                 oldext)))
2499                                 goto done;
2500                         if ((error = xfs_btree_decrement(cur, 0, &i)))
2501                                 goto done;
2502                         error = xfs_bmbt_update(cur, LEFT.br_startoff,
2503                                 LEFT.br_startblock,
2504                                 LEFT.br_blockcount + new->br_blockcount,
2505                                 LEFT.br_state);
2506                         if (error)
2507                                 goto done;
2508                 }
2509                 break;
2510
2511         case BMAP_LEFT_FILLING:
2512                 /*
2513                  * Setting the first part of a previous oldext extent to newext.
2514                  * The left neighbor is not contiguous.
2515                  */
2516                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2517                 ASSERT(ep && xfs_bmbt_get_state(ep) == oldext);
2518                 xfs_bmbt_set_startoff(ep, new_endoff);
2519                 xfs_bmbt_set_blockcount(ep,
2520                         PREV.br_blockcount - new->br_blockcount);
2521                 xfs_bmbt_set_startblock(ep,
2522                         new->br_startblock + new->br_blockcount);
2523                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2524
2525                 xfs_iext_insert(ip, *idx, 1, new, state);
2526                 ip->i_d.di_nextents++;
2527                 if (cur == NULL)
2528                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
2529                 else {
2530                         rval = XFS_ILOG_CORE;
2531                         if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
2532                                         PREV.br_startblock, PREV.br_blockcount,
2533                                         &i)))
2534                                 goto done;
2535                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2536                         if ((error = xfs_bmbt_update(cur,
2537                                 PREV.br_startoff + new->br_blockcount,
2538                                 PREV.br_startblock + new->br_blockcount,
2539                                 PREV.br_blockcount - new->br_blockcount,
2540                                 oldext)))
2541                                 goto done;
2542                         cur->bc_rec.b = *new;
2543                         if ((error = xfs_btree_insert(cur, &i)))
2544                                 goto done;
2545                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2546                 }
2547                 break;
2548
2549         case BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
2550                 /*
2551                  * Setting the last part of a previous oldext extent to newext.
2552                  * The right neighbor is contiguous with the new allocation.
2553                  */
2554                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2555                 xfs_bmbt_set_blockcount(ep,
2556                         PREV.br_blockcount - new->br_blockcount);
2557                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2558
2559                 ++*idx;
2560
2561                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2562                 xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, *idx),
2563                         new->br_startoff, new->br_startblock,
2564                         new->br_blockcount + RIGHT.br_blockcount, newext);
2565                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2566
2567                 if (cur == NULL)
2568                         rval = XFS_ILOG_DEXT;
2569                 else {
2570                         rval = 0;
2571                         if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
2572                                         PREV.br_startblock,
2573                                         PREV.br_blockcount, &i)))
2574                                 goto done;
2575                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2576                         if ((error = xfs_bmbt_update(cur, PREV.br_startoff,
2577                                 PREV.br_startblock,
2578                                 PREV.br_blockcount - new->br_blockcount,
2579                                 oldext)))
2580                                 goto done;
2581                         if ((error = xfs_btree_increment(cur, 0, &i)))
2582                                 goto done;
2583                         if ((error = xfs_bmbt_update(cur, new->br_startoff,
2584                                 new->br_startblock,
2585                                 new->br_blockcount + RIGHT.br_blockcount,
2586                                 newext)))
2587                                 goto done;
2588                 }
2589                 break;
2590
2591         case BMAP_RIGHT_FILLING:
2592                 /*
2593                  * Setting the last part of a previous oldext extent to newext.
2594                  * The right neighbor is not contiguous.
2595                  */
2596                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2597                 xfs_bmbt_set_blockcount(ep,
2598                         PREV.br_blockcount - new->br_blockcount);
2599                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2600
2601                 ++*idx;
2602                 xfs_iext_insert(ip, *idx, 1, new, state);
2603
2604                 ip->i_d.di_nextents++;
2605                 if (cur == NULL)
2606                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
2607                 else {
2608                         rval = XFS_ILOG_CORE;
2609                         if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
2610                                         PREV.br_startblock, PREV.br_blockcount,
2611                                         &i)))
2612                                 goto done;
2613                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2614                         if ((error = xfs_bmbt_update(cur, PREV.br_startoff,
2615                                 PREV.br_startblock,
2616                                 PREV.br_blockcount - new->br_blockcount,
2617                                 oldext)))
2618                                 goto done;
2619                         if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff,
2620                                         new->br_startblock, new->br_blockcount,
2621                                         &i)))
2622                                 goto done;
2623                         XFS_WANT_CORRUPTED_GOTO(mp, i == 0, done);
2624                         cur->bc_rec.b.br_state = XFS_EXT_NORM;
2625                         if ((error = xfs_btree_insert(cur, &i)))
2626                                 goto done;
2627                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2628                 }
2629                 break;
2630
2631         case 0:
2632                 /*
2633                  * Setting the middle part of a previous oldext extent to
2634                  * newext.  Contiguity is impossible here.
2635                  * One extent becomes three extents.
2636                  */
2637                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2638                 xfs_bmbt_set_blockcount(ep,
2639                         new->br_startoff - PREV.br_startoff);
2640                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2641
2642                 r[0] = *new;
2643                 r[1].br_startoff = new_endoff;
2644                 r[1].br_blockcount =
2645                         PREV.br_startoff + PREV.br_blockcount - new_endoff;
2646                 r[1].br_startblock = new->br_startblock + new->br_blockcount;
2647                 r[1].br_state = oldext;
2648
2649                 ++*idx;
2650                 xfs_iext_insert(ip, *idx, 2, &r[0], state);
2651
2652                 ip->i_d.di_nextents += 2;
2653                 if (cur == NULL)
2654                         rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
2655                 else {
2656                         rval = XFS_ILOG_CORE;
2657                         if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
2658                                         PREV.br_startblock, PREV.br_blockcount,
2659                                         &i)))
2660                                 goto done;
2661                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2662                         /* new right extent - oldext */
2663                         if ((error = xfs_bmbt_update(cur, r[1].br_startoff,
2664                                 r[1].br_startblock, r[1].br_blockcount,
2665                                 r[1].br_state)))
2666                                 goto done;
2667                         /* new left extent - oldext */
2668                         cur->bc_rec.b = PREV;
2669                         cur->bc_rec.b.br_blockcount =
2670                                 new->br_startoff - PREV.br_startoff;
2671                         if ((error = xfs_btree_insert(cur, &i)))
2672                                 goto done;
2673                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2674                         /*
2675                          * Reset the cursor to the position of the new extent
2676                          * we are about to insert as we can't trust it after
2677                          * the previous insert.
2678                          */
2679                         if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff,
2680                                         new->br_startblock, new->br_blockcount,
2681                                         &i)))
2682                                 goto done;
2683                         XFS_WANT_CORRUPTED_GOTO(mp, i == 0, done);
2684                         /* new middle extent - newext */
2685                         cur->bc_rec.b.br_state = new->br_state;
2686                         if ((error = xfs_btree_insert(cur, &i)))
2687                                 goto done;
2688                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2689                 }
2690                 break;
2691
2692         case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
2693         case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
2694         case BMAP_LEFT_FILLING | BMAP_RIGHT_CONTIG:
2695         case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG:
2696         case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
2697         case BMAP_LEFT_CONTIG:
2698         case BMAP_RIGHT_CONTIG:
2699                 /*
2700                  * These cases are all impossible.
2701                  */
2702                 ASSERT(0);
2703         }
2704
2705         /* convert to a btree if necessary */
2706         if (xfs_bmap_needs_btree(ip, XFS_DATA_FORK)) {
2707                 int     tmp_logflags;   /* partial log flag return val */
2708
2709                 ASSERT(cur == NULL);
2710                 error = xfs_bmap_extents_to_btree(tp, ip, first, flist, &cur,
2711                                 0, &tmp_logflags, XFS_DATA_FORK);
2712                 *logflagsp |= tmp_logflags;
2713                 if (error)
2714                         goto done;
2715         }
2716
2717         /* clear out the allocated field, done with it now in any case. */
2718         if (cur) {
2719                 cur->bc_private.b.allocated = 0;
2720                 *curp = cur;
2721         }
2722
2723         xfs_bmap_check_leaf_extents(*curp, ip, XFS_DATA_FORK);
2724 done:
2725         *logflagsp |= rval;
2726         return error;
2727 #undef  LEFT
2728 #undef  RIGHT
2729 #undef  PREV
2730 }
2731
2732 /*
2733  * Convert a hole to a delayed allocation.
2734  */
2735 STATIC void
2736 xfs_bmap_add_extent_hole_delay(
2737         xfs_inode_t             *ip,    /* incore inode pointer */
2738         xfs_extnum_t            *idx,   /* extent number to update/insert */
2739         xfs_bmbt_irec_t         *new)   /* new data to add to file extents */
2740 {
2741         xfs_ifork_t             *ifp;   /* inode fork pointer */
2742         xfs_bmbt_irec_t         left;   /* left neighbor extent entry */
2743         xfs_filblks_t           newlen=0;       /* new indirect size */
2744         xfs_filblks_t           oldlen=0;       /* old indirect size */
2745         xfs_bmbt_irec_t         right;  /* right neighbor extent entry */
2746         int                     state;  /* state bits, accessed thru macros */
2747         xfs_filblks_t           temp=0; /* temp for indirect calculations */
2748
2749         ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
2750         state = 0;
2751         ASSERT(isnullstartblock(new->br_startblock));
2752
2753         /*
2754          * Check and set flags if this segment has a left neighbor
2755          */
2756         if (*idx > 0) {
2757                 state |= BMAP_LEFT_VALID;
2758                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx - 1), &left);
2759
2760                 if (isnullstartblock(left.br_startblock))
2761                         state |= BMAP_LEFT_DELAY;
2762         }
2763
2764         /*
2765          * Check and set flags if the current (right) segment exists.
2766          * If it doesn't exist, we're converting the hole at end-of-file.
2767          */
2768         if (*idx < ip->i_df.if_bytes / (uint)sizeof(xfs_bmbt_rec_t)) {
2769                 state |= BMAP_RIGHT_VALID;
2770                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx), &right);
2771
2772                 if (isnullstartblock(right.br_startblock))
2773                         state |= BMAP_RIGHT_DELAY;
2774         }
2775
2776         /*
2777          * Set contiguity flags on the left and right neighbors.
2778          * Don't let extents get too large, even if the pieces are contiguous.
2779          */
2780         if ((state & BMAP_LEFT_VALID) && (state & BMAP_LEFT_DELAY) &&
2781             left.br_startoff + left.br_blockcount == new->br_startoff &&
2782             left.br_blockcount + new->br_blockcount <= MAXEXTLEN)
2783                 state |= BMAP_LEFT_CONTIG;
2784
2785         if ((state & BMAP_RIGHT_VALID) && (state & BMAP_RIGHT_DELAY) &&
2786             new->br_startoff + new->br_blockcount == right.br_startoff &&
2787             new->br_blockcount + right.br_blockcount <= MAXEXTLEN &&
2788             (!(state & BMAP_LEFT_CONTIG) ||
2789              (left.br_blockcount + new->br_blockcount +
2790               right.br_blockcount <= MAXEXTLEN)))
2791                 state |= BMAP_RIGHT_CONTIG;
2792
2793         /*
2794          * Switch out based on the contiguity flags.
2795          */
2796         switch (state & (BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG)) {
2797         case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
2798                 /*
2799                  * New allocation is contiguous with delayed allocations
2800                  * on the left and on the right.
2801                  * Merge all three into a single extent record.
2802                  */
2803                 --*idx;
2804                 temp = left.br_blockcount + new->br_blockcount +
2805                         right.br_blockcount;
2806
2807                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2808                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx), temp);
2809                 oldlen = startblockval(left.br_startblock) +
2810                         startblockval(new->br_startblock) +
2811                         startblockval(right.br_startblock);
2812                 newlen = xfs_bmap_worst_indlen(ip, temp);
2813                 xfs_bmbt_set_startblock(xfs_iext_get_ext(ifp, *idx),
2814                         nullstartblock((int)newlen));
2815                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2816
2817                 xfs_iext_remove(ip, *idx + 1, 1, state);
2818                 break;
2819
2820         case BMAP_LEFT_CONTIG:
2821                 /*
2822                  * New allocation is contiguous with a delayed allocation
2823                  * on the left.
2824                  * Merge the new allocation with the left neighbor.
2825                  */
2826                 --*idx;
2827                 temp = left.br_blockcount + new->br_blockcount;
2828
2829                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2830                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx), temp);
2831                 oldlen = startblockval(left.br_startblock) +
2832                         startblockval(new->br_startblock);
2833                 newlen = xfs_bmap_worst_indlen(ip, temp);
2834                 xfs_bmbt_set_startblock(xfs_iext_get_ext(ifp, *idx),
2835                         nullstartblock((int)newlen));
2836                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2837                 break;
2838
2839         case BMAP_RIGHT_CONTIG:
2840                 /*
2841                  * New allocation is contiguous with a delayed allocation
2842                  * on the right.
2843                  * Merge the new allocation with the right neighbor.
2844                  */
2845                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
2846                 temp = new->br_blockcount + right.br_blockcount;
2847                 oldlen = startblockval(new->br_startblock) +
2848                         startblockval(right.br_startblock);
2849                 newlen = xfs_bmap_worst_indlen(ip, temp);
2850                 xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, *idx),
2851                         new->br_startoff,
2852                         nullstartblock((int)newlen), temp, right.br_state);
2853                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
2854                 break;
2855
2856         case 0:
2857                 /*
2858                  * New allocation is not contiguous with another
2859                  * delayed allocation.
2860                  * Insert a new entry.
2861                  */
2862                 oldlen = newlen = 0;
2863                 xfs_iext_insert(ip, *idx, 1, new, state);
2864                 break;
2865         }
2866         if (oldlen != newlen) {
2867                 ASSERT(oldlen > newlen);
2868                 xfs_mod_fdblocks(ip->i_mount, (int64_t)(oldlen - newlen),
2869                                  false);
2870                 /*
2871                  * Nothing to do for disk quota accounting here.
2872                  */
2873         }
2874 }
2875
2876 /*
2877  * Convert a hole to a real allocation.
2878  */
2879 STATIC int                              /* error */
2880 xfs_bmap_add_extent_hole_real(
2881         struct xfs_bmalloca     *bma,
2882         int                     whichfork)
2883 {
2884         struct xfs_bmbt_irec    *new = &bma->got;
2885         int                     error;  /* error return value */
2886         int                     i;      /* temp state */
2887         xfs_ifork_t             *ifp;   /* inode fork pointer */
2888         xfs_bmbt_irec_t         left;   /* left neighbor extent entry */
2889         xfs_bmbt_irec_t         right;  /* right neighbor extent entry */
2890         int                     rval=0; /* return value (logging flags) */
2891         int                     state;  /* state bits, accessed thru macros */
2892         struct xfs_mount        *mp;
2893
2894         mp = bma->ip->i_mount;
2895         ifp = XFS_IFORK_PTR(bma->ip, whichfork);
2896
2897         ASSERT(bma->idx >= 0);
2898         ASSERT(bma->idx <= ifp->if_bytes / sizeof(struct xfs_bmbt_rec));
2899         ASSERT(!isnullstartblock(new->br_startblock));
2900         ASSERT(!bma->cur ||
2901                !(bma->cur->bc_private.b.flags & XFS_BTCUR_BPRV_WASDEL));
2902
2903         XFS_STATS_INC(mp, xs_add_exlist);
2904
2905         state = 0;
2906         if (whichfork == XFS_ATTR_FORK)
2907                 state |= BMAP_ATTRFORK;
2908
2909         /*
2910          * Check and set flags if this segment has a left neighbor.
2911          */
2912         if (bma->idx > 0) {
2913                 state |= BMAP_LEFT_VALID;
2914                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx - 1), &left);
2915                 if (isnullstartblock(left.br_startblock))
2916                         state |= BMAP_LEFT_DELAY;
2917         }
2918
2919         /*
2920          * Check and set flags if this segment has a current value.
2921          * Not true if we're inserting into the "hole" at eof.
2922          */
2923         if (bma->idx < ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t)) {
2924                 state |= BMAP_RIGHT_VALID;
2925                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx), &right);
2926                 if (isnullstartblock(right.br_startblock))
2927                         state |= BMAP_RIGHT_DELAY;
2928         }
2929
2930         /*
2931          * We're inserting a real allocation between "left" and "right".
2932          * Set the contiguity flags.  Don't let extents get too large.
2933          */
2934         if ((state & BMAP_LEFT_VALID) && !(state & BMAP_LEFT_DELAY) &&
2935             left.br_startoff + left.br_blockcount == new->br_startoff &&
2936             left.br_startblock + left.br_blockcount == new->br_startblock &&
2937             left.br_state == new->br_state &&
2938             left.br_blockcount + new->br_blockcount <= MAXEXTLEN)
2939                 state |= BMAP_LEFT_CONTIG;
2940
2941         if ((state & BMAP_RIGHT_VALID) && !(state & BMAP_RIGHT_DELAY) &&
2942             new->br_startoff + new->br_blockcount == right.br_startoff &&
2943             new->br_startblock + new->br_blockcount == right.br_startblock &&
2944             new->br_state == right.br_state &&
2945             new->br_blockcount + right.br_blockcount <= MAXEXTLEN &&
2946             (!(state & BMAP_LEFT_CONTIG) ||
2947              left.br_blockcount + new->br_blockcount +
2948              right.br_blockcount <= MAXEXTLEN))
2949                 state |= BMAP_RIGHT_CONTIG;
2950
2951         error = 0;
2952         /*
2953          * Select which case we're in here, and implement it.
2954          */
2955         switch (state & (BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG)) {
2956         case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
2957                 /*
2958                  * New allocation is contiguous with real allocations on the
2959                  * left and on the right.
2960                  * Merge all three into a single extent record.
2961                  */
2962                 --bma->idx;
2963                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
2964                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx),
2965                         left.br_blockcount + new->br_blockcount +
2966                         right.br_blockcount);
2967                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
2968
2969                 xfs_iext_remove(bma->ip, bma->idx + 1, 1, state);
2970
2971                 XFS_IFORK_NEXT_SET(bma->ip, whichfork,
2972                         XFS_IFORK_NEXTENTS(bma->ip, whichfork) - 1);
2973                 if (bma->cur == NULL) {
2974                         rval = XFS_ILOG_CORE | xfs_ilog_fext(whichfork);
2975                 } else {
2976                         rval = XFS_ILOG_CORE;
2977                         error = xfs_bmbt_lookup_eq(bma->cur, right.br_startoff,
2978                                         right.br_startblock, right.br_blockcount,
2979                                         &i);
2980                         if (error)
2981                                 goto done;
2982                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2983                         error = xfs_btree_delete(bma->cur, &i);
2984                         if (error)
2985                                 goto done;
2986                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2987                         error = xfs_btree_decrement(bma->cur, 0, &i);
2988                         if (error)
2989                                 goto done;
2990                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
2991                         error = xfs_bmbt_update(bma->cur, left.br_startoff,
2992                                         left.br_startblock,
2993                                         left.br_blockcount +
2994                                                 new->br_blockcount +
2995                                                 right.br_blockcount,
2996                                         left.br_state);
2997                         if (error)
2998                                 goto done;
2999                 }
3000                 break;
3001
3002         case BMAP_LEFT_CONTIG:
3003                 /*
3004                  * New allocation is contiguous with a real allocation
3005                  * on the left.
3006                  * Merge the new allocation with the left neighbor.
3007                  */
3008                 --bma->idx;
3009                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
3010                 xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx),
3011                         left.br_blockcount + new->br_blockcount);
3012                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
3013
3014                 if (bma->cur == NULL) {
3015                         rval = xfs_ilog_fext(whichfork);
3016                 } else {
3017                         rval = 0;
3018                         error = xfs_bmbt_lookup_eq(bma->cur, left.br_startoff,
3019                                         left.br_startblock, left.br_blockcount,
3020                                         &i);
3021                         if (error)
3022                                 goto done;
3023                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
3024                         error = xfs_bmbt_update(bma->cur, left.br_startoff,
3025                                         left.br_startblock,
3026                                         left.br_blockcount +
3027                                                 new->br_blockcount,
3028                                         left.br_state);
3029                         if (error)
3030                                 goto done;
3031                 }
3032                 break;
3033
3034         case BMAP_RIGHT_CONTIG:
3035                 /*
3036                  * New allocation is contiguous with a real allocation
3037                  * on the right.
3038                  * Merge the new allocation with the right neighbor.
3039                  */
3040                 trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
3041                 xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, bma->idx),
3042                         new->br_startoff, new->br_startblock,
3043                         new->br_blockcount + right.br_blockcount,
3044                         right.br_state);
3045                 trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
3046
3047                 if (bma->cur == NULL) {
3048                         rval = xfs_ilog_fext(whichfork);
3049                 } else {
3050                         rval = 0;
3051                         error = xfs_bmbt_lookup_eq(bma->cur,
3052                                         right.br_startoff,
3053                                         right.br_startblock,
3054                                         right.br_blockcount, &i);
3055                         if (error)
3056                                 goto done;
3057                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
3058                         error = xfs_bmbt_update(bma->cur, new->br_startoff,
3059                                         new->br_startblock,
3060                                         new->br_blockcount +
3061                                                 right.br_blockcount,
3062                                         right.br_state);
3063                         if (error)
3064                                 goto done;
3065                 }
3066                 break;
3067
3068         case 0:
3069                 /*
3070                  * New allocation is not contiguous with another
3071                  * real allocation.
3072                  * Insert a new entry.
3073                  */
3074                 xfs_iext_insert(bma->ip, bma->idx, 1, new, state);
3075                 XFS_IFORK_NEXT_SET(bma->ip, whichfork,
3076                         XFS_IFORK_NEXTENTS(bma->ip, whichfork) + 1);
3077                 if (bma->cur == NULL) {
3078                         rval = XFS_ILOG_CORE | xfs_ilog_fext(whichfork);
3079                 } else {
3080                         rval = XFS_ILOG_CORE;
3081                         error = xfs_bmbt_lookup_eq(bma->cur,
3082                                         new->br_startoff,
3083                                         new->br_startblock,
3084                                         new->br_blockcount, &i);
3085                         if (error)
3086                                 goto done;
3087                         XFS_WANT_CORRUPTED_GOTO(mp, i == 0, done);
3088                         bma->cur->bc_rec.b.br_state = new->br_state;
3089                         error = xfs_btree_insert(bma->cur, &i);
3090                         if (error)
3091                                 goto done;
3092                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
3093                 }
3094                 break;
3095         }
3096
3097         /* convert to a btree if necessary */
3098         if (xfs_bmap_needs_btree(bma->ip, whichfork)) {
3099                 int     tmp_logflags;   /* partial log flag return val */
3100
3101                 ASSERT(bma->cur == NULL);
3102                 error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
3103                                 bma->firstblock, bma->flist, &bma->cur,
3104                                 0, &tmp_logflags, whichfork);
3105                 bma->logflags |= tmp_logflags;
3106                 if (error)
3107                         goto done;
3108         }
3109
3110         /* clear out the allocated field, done with it now in any case. */
3111         if (bma->cur)
3112                 bma->cur->bc_private.b.allocated = 0;
3113
3114         xfs_bmap_check_leaf_extents(bma->cur, bma->ip, whichfork);
3115 done:
3116         bma->logflags |= rval;
3117         return error;
3118 }
3119
3120 /*
3121  * Functions used in the extent read, allocate and remove paths
3122  */
3123
3124 /*
3125  * Adjust the size of the new extent based on di_extsize and rt extsize.
3126  */
3127 int
3128 xfs_bmap_extsize_align(
3129         xfs_mount_t     *mp,
3130         xfs_bmbt_irec_t *gotp,          /* next extent pointer */
3131         xfs_bmbt_irec_t *prevp,         /* previous extent pointer */
3132         xfs_extlen_t    extsz,          /* align to this extent size */
3133         int             rt,             /* is this a realtime inode? */
3134         int             eof,            /* is extent at end-of-file? */
3135         int             delay,          /* creating delalloc extent? */
3136         int             convert,        /* overwriting unwritten extent? */
3137         xfs_fileoff_t   *offp,          /* in/out: aligned offset */
3138         xfs_extlen_t    *lenp)          /* in/out: aligned length */
3139 {
3140         xfs_fileoff_t   orig_off;       /* original offset */
3141         xfs_extlen_t    orig_alen;      /* original length */
3142         xfs_fileoff_t   orig_end;       /* original off+len */
3143         xfs_fileoff_t   nexto;          /* next file offset */
3144         xfs_fileoff_t   prevo;          /* previous file offset */
3145         xfs_fileoff_t   align_off;      /* temp for offset */
3146         xfs_extlen_t    align_alen;     /* temp for length */
3147         xfs_extlen_t    temp;           /* temp for calculations */
3148
3149         if (convert)
3150                 return 0;
3151
3152         orig_off = align_off = *offp;
3153         orig_alen = align_alen = *lenp;
3154         orig_end = orig_off + orig_alen;
3155
3156         /*
3157          * If this request overlaps an existing extent, then don't
3158          * attempt to perform any additional alignment.
3159          */
3160         if (!delay && !eof &&
3161             (orig_off >= gotp->br_startoff) &&
3162             (orig_end <= gotp->br_startoff + gotp->br_blockcount)) {
3163                 return 0;
3164         }
3165
3166         /*
3167          * If the file offset is unaligned vs. the extent size
3168          * we need to align it.  This will be possible unless
3169          * the file was previously written with a kernel that didn't
3170          * perform this alignment, or if a truncate shot us in the
3171          * foot.
3172          */
3173         temp = do_mod(orig_off, extsz);
3174         if (temp) {
3175                 align_alen += temp;
3176                 align_off -= temp;
3177         }
3178
3179         /* Same adjustment for the end of the requested area. */
3180         temp = (align_alen % extsz);
3181         if (temp)
3182                 align_alen += extsz - temp;
3183
3184         /*
3185          * For large extent hint sizes, the aligned extent might be larger than
3186          * MAXEXTLEN. In that case, reduce the size by an extsz so that it pulls
3187          * the length back under MAXEXTLEN. The outer allocation loops handle
3188          * short allocation just fine, so it is safe to do this. We only want to
3189          * do it when we are forced to, though, because it means more allocation
3190          * operations are required.
3191          */
3192         while (align_alen > MAXEXTLEN)
3193                 align_alen -= extsz;
3194         ASSERT(align_alen <= MAXEXTLEN);
3195
3196         /*
3197          * If the previous block overlaps with this proposed allocation
3198          * then move the start forward without adjusting the length.
3199          */
3200         if (prevp->br_startoff != NULLFILEOFF) {
3201                 if (prevp->br_startblock == HOLESTARTBLOCK)
3202                         prevo = prevp->br_startoff;
3203                 else
3204                         prevo = prevp->br_startoff + prevp->br_blockcount;
3205         } else
3206                 prevo = 0;
3207         if (align_off != orig_off && align_off < prevo)
3208                 align_off = prevo;
3209         /*
3210          * If the next block overlaps with this proposed allocation
3211          * then move the start back without adjusting the length,
3212          * but not before offset 0.
3213          * This may of course make the start overlap previous block,
3214          * and if we hit the offset 0 limit then the next block
3215          * can still overlap too.
3216          */
3217         if (!eof && gotp->br_startoff != NULLFILEOFF) {
3218                 if ((delay && gotp->br_startblock == HOLESTARTBLOCK) ||
3219                     (!delay && gotp->br_startblock == DELAYSTARTBLOCK))
3220                         nexto = gotp->br_startoff + gotp->br_blockcount;
3221                 else
3222                         nexto = gotp->br_startoff;
3223         } else
3224                 nexto = NULLFILEOFF;
3225         if (!eof &&
3226             align_off + align_alen != orig_end &&
3227             align_off + align_alen > nexto)
3228                 align_off = nexto > align_alen ? nexto - align_alen : 0;
3229         /*
3230          * If we're now overlapping the next or previous extent that
3231          * means we can't fit an extsz piece in this hole.  Just move
3232          * the start forward to the first valid spot and set
3233          * the length so we hit the end.
3234          */
3235         if (align_off != orig_off && align_off < prevo)
3236                 align_off = prevo;
3237         if (align_off + align_alen != orig_end &&
3238             align_off + align_alen > nexto &&
3239             nexto != NULLFILEOFF) {
3240                 ASSERT(nexto > prevo);
3241                 align_alen = nexto - align_off;
3242         }
3243
3244         /*
3245          * If realtime, and the result isn't a multiple of the realtime
3246          * extent size we need to remove blocks until it is.
3247          */
3248         if (rt && (temp = (align_alen % mp->m_sb.sb_rextsize))) {
3249                 /*
3250                  * We're not covering the original request, or
3251                  * we won't be able to once we fix the length.
3252                  */
3253                 if (orig_off < align_off ||
3254                     orig_end > align_off + align_alen ||
3255                     align_alen - temp < orig_alen)
3256                         return -EINVAL;
3257                 /*
3258                  * Try to fix it by moving the start up.
3259                  */
3260                 if (align_off + temp <= orig_off) {
3261                         align_alen -= temp;
3262                         align_off += temp;
3263                 }
3264                 /*
3265                  * Try to fix it by moving the end in.
3266                  */
3267                 else if (align_off + align_alen - temp >= orig_end)
3268                         align_alen -= temp;
3269                 /*
3270                  * Set the start to the minimum then trim the length.
3271                  */
3272                 else {
3273                         align_alen -= orig_off - align_off;
3274                         align_off = orig_off;
3275                         align_alen -= align_alen % mp->m_sb.sb_rextsize;
3276                 }
3277                 /*
3278                  * Result doesn't cover the request, fail it.
3279                  */
3280                 if (orig_off < align_off || orig_end > align_off + align_alen)
3281                         return -EINVAL;
3282         } else {
3283                 ASSERT(orig_off >= align_off);
3284                 /* see MAXEXTLEN handling above */
3285                 ASSERT(orig_end <= align_off + align_alen ||
3286                        align_alen + extsz > MAXEXTLEN);
3287         }
3288
3289 #ifdef DEBUG
3290         if (!eof && gotp->br_startoff != NULLFILEOFF)
3291                 ASSERT(align_off + align_alen <= gotp->br_startoff);
3292         if (prevp->br_startoff != NULLFILEOFF)
3293                 ASSERT(align_off >= prevp->br_startoff + prevp->br_blockcount);
3294 #endif
3295
3296         *lenp = align_alen;
3297         *offp = align_off;
3298         return 0;
3299 }
3300
3301 #define XFS_ALLOC_GAP_UNITS     4
3302
3303 void
3304 xfs_bmap_adjacent(
3305         struct xfs_bmalloca     *ap)    /* bmap alloc argument struct */
3306 {
3307         xfs_fsblock_t   adjust;         /* adjustment to block numbers */
3308         xfs_agnumber_t  fb_agno;        /* ag number of ap->firstblock */
3309         xfs_mount_t     *mp;            /* mount point structure */
3310         int             nullfb;         /* true if ap->firstblock isn't set */
3311         int             rt;             /* true if inode is realtime */
3312
3313 #define ISVALID(x,y)    \
3314         (rt ? \
3315                 (x) < mp->m_sb.sb_rblocks : \
3316                 XFS_FSB_TO_AGNO(mp, x) == XFS_FSB_TO_AGNO(mp, y) && \
3317                 XFS_FSB_TO_AGNO(mp, x) < mp->m_sb.sb_agcount && \
3318                 XFS_FSB_TO_AGBNO(mp, x) < mp->m_sb.sb_agblocks)
3319
3320         mp = ap->ip->i_mount;
3321         nullfb = *ap->firstblock == NULLFSBLOCK;
3322         rt = XFS_IS_REALTIME_INODE(ap->ip) && ap->userdata;
3323         fb_agno = nullfb ? NULLAGNUMBER : XFS_FSB_TO_AGNO(mp, *ap->firstblock);
3324         /*
3325          * If allocating at eof, and there's a previous real block,
3326          * try to use its last block as our starting point.
3327          */
3328         if (ap->eof && ap->prev.br_startoff != NULLFILEOFF &&
3329             !isnullstartblock(ap->prev.br_startblock) &&
3330             ISVALID(ap->prev.br_startblock + ap->prev.br_blockcount,
3331                     ap->prev.br_startblock)) {
3332                 ap->blkno = ap->prev.br_startblock + ap->prev.br_blockcount;
3333                 /*
3334                  * Adjust for the gap between prevp and us.
3335                  */
3336                 adjust = ap->offset -
3337                         (ap->prev.br_startoff + ap->prev.br_blockcount);
3338                 if (adjust &&
3339                     ISVALID(ap->blkno + adjust, ap->prev.br_startblock))
3340                         ap->blkno += adjust;
3341         }
3342         /*
3343          * If not at eof, then compare the two neighbor blocks.
3344          * Figure out whether either one gives us a good starting point,
3345          * and pick the better one.
3346          */
3347         else if (!ap->eof) {
3348                 xfs_fsblock_t   gotbno;         /* right side block number */
3349                 xfs_fsblock_t   gotdiff=0;      /* right side difference */
3350                 xfs_fsblock_t   prevbno;        /* left side block number */
3351                 xfs_fsblock_t   prevdiff=0;     /* left side difference */
3352
3353                 /*
3354                  * If there's a previous (left) block, select a requested
3355                  * start block based on it.
3356                  */
3357                 if (ap->prev.br_startoff != NULLFILEOFF &&
3358                     !isnullstartblock(ap->prev.br_startblock) &&
3359                     (prevbno = ap->prev.br_startblock +
3360                                ap->prev.br_blockcount) &&
3361                     ISVALID(prevbno, ap->prev.br_startblock)) {
3362                         /*
3363                          * Calculate gap to end of previous block.
3364                          */
3365                         adjust = prevdiff = ap->offset -
3366                                 (ap->prev.br_startoff +
3367                                  ap->prev.br_blockcount);
3368                         /*
3369                          * Figure the startblock based on the previous block's
3370                          * end and the gap size.
3371                          * Heuristic!
3372                          * If the gap is large relative to the piece we're
3373                          * allocating, or using it gives us an invalid block
3374                          * number, then just use the end of the previous block.
3375                          */
3376                         if (prevdiff <= XFS_ALLOC_GAP_UNITS * ap->length &&
3377                             ISVALID(prevbno + prevdiff,
3378                                     ap->prev.br_startblock))
3379                                 prevbno += adjust;
3380                         else
3381                                 prevdiff += adjust;
3382                         /*
3383                          * If the firstblock forbids it, can't use it,
3384                          * must use default.
3385                          */
3386                         if (!rt && !nullfb &&
3387                             XFS_FSB_TO_AGNO(mp, prevbno) != fb_agno)
3388                                 prevbno = NULLFSBLOCK;
3389                 }
3390                 /*
3391                  * No previous block or can't follow it, just default.
3392                  */
3393                 else
3394                         prevbno = NULLFSBLOCK;
3395                 /*
3396                  * If there's a following (right) block, select a requested
3397                  * start block based on it.
3398                  */
3399                 if (!isnullstartblock(ap->got.br_startblock)) {
3400                         /*
3401                          * Calculate gap to start of next block.
3402                          */
3403                         adjust = gotdiff = ap->got.br_startoff - ap->offset;
3404                         /*
3405                          * Figure the startblock based on the next block's
3406                          * start and the gap size.
3407                          */
3408                         gotbno = ap->got.br_startblock;
3409                         /*
3410                          * Heuristic!
3411                          * If the gap is large relative to the piece we're
3412                          * allocating, or using it gives us an invalid block
3413                          * number, then just use the start of the next block
3414                          * offset by our length.
3415                          */
3416                         if (gotdiff <= XFS_ALLOC_GAP_UNITS * ap->length &&
3417                             ISVALID(gotbno - gotdiff, gotbno))
3418                                 gotbno -= adjust;
3419                         else if (ISVALID(gotbno - ap->length, gotbno)) {
3420                                 gotbno -= ap->length;
3421                                 gotdiff += adjust - ap->length;
3422                         } else
3423                                 gotdiff += adjust;
3424                         /*
3425                          * If the firstblock forbids it, can't use it,
3426                          * must use default.
3427                          */
3428                         if (!rt && !nullfb &&
3429                             XFS_FSB_TO_AGNO(mp, gotbno) != fb_agno)
3430                                 gotbno = NULLFSBLOCK;
3431                 }
3432                 /*
3433                  * No next block, just default.
3434                  */
3435                 else
3436                         gotbno = NULLFSBLOCK;
3437                 /*
3438                  * If both valid, pick the better one, else the only good
3439                  * one, else ap->blkno is already set (to 0 or the inode block).
3440                  */
3441                 if (prevbno != NULLFSBLOCK && gotbno != NULLFSBLOCK)
3442                         ap->blkno = prevdiff <= gotdiff ? prevbno : gotbno;
3443                 else if (prevbno != NULLFSBLOCK)
3444                         ap->blkno = prevbno;
3445                 else if (gotbno != NULLFSBLOCK)
3446                         ap->blkno = gotbno;
3447         }
3448 #undef ISVALID
3449 }
3450
3451 static int
3452 xfs_bmap_longest_free_extent(
3453         struct xfs_trans        *tp,
3454         xfs_agnumber_t          ag,
3455         xfs_extlen_t            *blen,
3456         int                     *notinit)
3457 {
3458         struct xfs_mount        *mp = tp->t_mountp;
3459         struct xfs_perag        *pag;
3460         xfs_extlen_t            longest;
3461         int                     error = 0;
3462
3463         pag = xfs_perag_get(mp, ag);
3464         if (!pag->pagf_init) {
3465                 error = xfs_alloc_pagf_init(mp, tp, ag, XFS_ALLOC_FLAG_TRYLOCK);
3466                 if (error)
3467                         goto out;
3468
3469                 if (!pag->pagf_init) {
3470                         *notinit = 1;
3471                         goto out;
3472                 }
3473         }
3474
3475         longest = xfs_alloc_longest_free_extent(mp, pag,
3476                                         xfs_alloc_min_freelist(mp, pag));
3477         if (*blen < longest)
3478                 *blen = longest;
3479
3480 out:
3481         xfs_perag_put(pag);
3482         return error;
3483 }
3484
3485 static void
3486 xfs_bmap_select_minlen(
3487         struct xfs_bmalloca     *ap,
3488         struct xfs_alloc_arg    *args,
3489         xfs_extlen_t            *blen,
3490         int                     notinit)
3491 {
3492         if (notinit || *blen < ap->minlen) {
3493                 /*
3494                  * Since we did a BUF_TRYLOCK above, it is possible that
3495                  * there is space for this request.
3496                  */
3497                 args->minlen = ap->minlen;
3498         } else if (*blen < args->maxlen) {
3499                 /*
3500                  * If the best seen length is less than the request length,
3501                  * use the best as the minimum.
3502                  */
3503                 args->minlen = *blen;
3504         } else {
3505                 /*
3506                  * Otherwise we've seen an extent as big as maxlen, use that
3507                  * as the minimum.
3508                  */
3509                 args->minlen = args->maxlen;
3510         }
3511 }
3512
3513 STATIC int
3514 xfs_bmap_btalloc_nullfb(
3515         struct xfs_bmalloca     *ap,
3516         struct xfs_alloc_arg    *args,
3517         xfs_extlen_t            *blen)
3518 {
3519         struct xfs_mount        *mp = ap->ip->i_mount;
3520         xfs_agnumber_t          ag, startag;
3521         int                     notinit = 0;
3522         int                     error;
3523
3524         args->type = XFS_ALLOCTYPE_START_BNO;
3525         args->total = ap->total;
3526
3527         startag = ag = XFS_FSB_TO_AGNO(mp, args->fsbno);
3528         if (startag == NULLAGNUMBER)
3529                 startag = ag = 0;
3530
3531         while (*blen < args->maxlen) {
3532                 error = xfs_bmap_longest_free_extent(args->tp, ag, blen,
3533                                                      &notinit);
3534                 if (error)
3535                         return error;
3536
3537                 if (++ag == mp->m_sb.sb_agcount)
3538                         ag = 0;
3539                 if (ag == startag)
3540                         break;
3541         }
3542
3543         xfs_bmap_select_minlen(ap, args, blen, notinit);
3544         return 0;
3545 }
3546
3547 STATIC int
3548 xfs_bmap_btalloc_filestreams(
3549         struct xfs_bmalloca     *ap,
3550         struct xfs_alloc_arg    *args,
3551         xfs_extlen_t            *blen)
3552 {
3553         struct xfs_mount        *mp = ap->ip->i_mount;
3554         xfs_agnumber_t          ag;
3555         int                     notinit = 0;
3556         int                     error;
3557
3558         args->type = XFS_ALLOCTYPE_NEAR_BNO;
3559         args->total = ap->total;
3560
3561         ag = XFS_FSB_TO_AGNO(mp, args->fsbno);
3562         if (ag == NULLAGNUMBER)
3563                 ag = 0;
3564
3565         error = xfs_bmap_longest_free_extent(args->tp, ag, blen, &notinit);
3566         if (error)
3567                 return error;
3568
3569         if (*blen < args->maxlen) {
3570                 error = xfs_filestream_new_ag(ap, &ag);
3571                 if (error)
3572                         return error;
3573
3574                 error = xfs_bmap_longest_free_extent(args->tp, ag, blen,
3575                                                      &notinit);
3576                 if (error)
3577                         return error;
3578
3579         }
3580
3581         xfs_bmap_select_minlen(ap, args, blen, notinit);
3582
3583         /*
3584          * Set the failure fallback case to look in the selected AG as stream
3585          * may have moved.
3586          */
3587         ap->blkno = args->fsbno = XFS_AGB_TO_FSB(mp, ag, 0);
3588         return 0;
3589 }
3590
3591 STATIC int
3592 xfs_bmap_btalloc(
3593         struct xfs_bmalloca     *ap)    /* bmap alloc argument struct */
3594 {
3595         xfs_mount_t     *mp;            /* mount point structure */
3596         xfs_alloctype_t atype = 0;      /* type for allocation routines */
3597         xfs_extlen_t    align;          /* minimum allocation alignment */
3598         xfs_agnumber_t  fb_agno;        /* ag number of ap->firstblock */
3599         xfs_agnumber_t  ag;
3600         xfs_alloc_arg_t args;
3601         xfs_extlen_t    blen;
3602         xfs_extlen_t    nextminlen = 0;
3603         int             nullfb;         /* true if ap->firstblock isn't set */
3604         int             isaligned;
3605         int             tryagain;
3606         int             error;
3607         int             stripe_align;
3608
3609         ASSERT(ap->length);
3610
3611         mp = ap->ip->i_mount;
3612
3613         /* stripe alignment for allocation is determined by mount parameters */
3614         stripe_align = 0;
3615         if (mp->m_swidth && (mp->m_flags & XFS_MOUNT_SWALLOC))
3616                 stripe_align = mp->m_swidth;
3617         else if (mp->m_dalign)
3618                 stripe_align = mp->m_dalign;
3619
3620         align = ap->userdata ? xfs_get_extsz_hint(ap->ip) : 0;
3621         if (unlikely(align)) {
3622                 error = xfs_bmap_extsize_align(mp, &ap->got, &ap->prev,
3623                                                 align, 0, ap->eof, 0, ap->conv,
3624                                                 &ap->offset, &ap->length);
3625                 ASSERT(!error);
3626                 ASSERT(ap->length);
3627         }
3628
3629
3630         nullfb = *ap->firstblock == NULLFSBLOCK;
3631         fb_agno = nullfb ? NULLAGNUMBER : XFS_FSB_TO_AGNO(mp, *ap->firstblock);
3632         if (nullfb) {
3633                 if (ap->userdata && xfs_inode_is_filestream(ap->ip)) {
3634                         ag = xfs_filestream_lookup_ag(ap->ip);
3635                         ag = (ag != NULLAGNUMBER) ? ag : 0;
3636                         ap->blkno = XFS_AGB_TO_FSB(mp, ag, 0);
3637                 } else {
3638                         ap->blkno = XFS_INO_TO_FSB(mp, ap->ip->i_ino);
3639                 }
3640         } else
3641                 ap->blkno = *ap->firstblock;
3642
3643         xfs_bmap_adjacent(ap);
3644
3645         /*
3646          * If allowed, use ap->blkno; otherwise must use firstblock since
3647          * it's in the right allocation group.
3648          */
3649         if (nullfb || XFS_FSB_TO_AGNO(mp, ap->blkno) == fb_agno)
3650                 ;
3651         else
3652                 ap->blkno = *ap->firstblock;
3653         /*
3654          * Normal allocation, done through xfs_alloc_vextent.
3655          */
3656         tryagain = isaligned = 0;
3657         memset(&args, 0, sizeof(args));
3658         args.tp = ap->tp;
3659         args.mp = mp;
3660         args.fsbno = ap->blkno;
3661
3662         /* Trim the allocation back to the maximum an AG can fit. */
3663         args.maxlen = MIN(ap->length, XFS_ALLOC_AG_MAX_USABLE(mp));
3664         args.firstblock = *ap->firstblock;
3665         blen = 0;
3666         if (nullfb) {
3667                 /*
3668                  * Search for an allocation group with a single extent large
3669                  * enough for the request.  If one isn't found, then adjust
3670                  * the minimum allocation size to the largest space found.
3671                  */
3672                 if (ap->userdata && xfs_inode_is_filestream(ap->ip))
3673                         error = xfs_bmap_btalloc_filestreams(ap, &args, &blen);
3674                 else
3675                         error = xfs_bmap_btalloc_nullfb(ap, &args, &blen);
3676                 if (error)
3677                         return error;
3678         } else if (ap->flist->dop_low) {
3679                 if (xfs_inode_is_filestream(ap->ip))
3680                         args.type = XFS_ALLOCTYPE_FIRST_AG;
3681                 else
3682                         args.type = XFS_ALLOCTYPE_START_BNO;
3683                 args.total = args.minlen = ap->minlen;
3684         } else {
3685                 args.type = XFS_ALLOCTYPE_NEAR_BNO;
3686                 args.total = ap->total;
3687                 args.minlen = ap->minlen;
3688         }
3689         /* apply extent size hints if obtained earlier */
3690         if (unlikely(align)) {
3691                 args.prod = align;
3692                 if ((args.mod = (xfs_extlen_t)do_mod(ap->offset, args.prod)))
3693                         args.mod = (xfs_extlen_t)(args.prod - args.mod);
3694         } else if (mp->m_sb.sb_blocksize >= PAGE_SIZE) {
3695                 args.prod = 1;
3696                 args.mod = 0;
3697         } else {
3698                 args.prod = PAGE_SIZE >> mp->m_sb.sb_blocklog;
3699                 if ((args.mod = (xfs_extlen_t)(do_mod(ap->offset, args.prod))))
3700                         args.mod = (xfs_extlen_t)(args.prod - args.mod);
3701         }
3702         /*
3703          * If we are not low on available data blocks, and the
3704          * underlying logical volume manager is a stripe, and
3705          * the file offset is zero then try to allocate data
3706          * blocks on stripe unit boundary.
3707          * NOTE: ap->aeof is only set if the allocation length
3708          * is >= the stripe unit and the allocation offset is
3709          * at the end of file.
3710          */
3711         if (!ap->flist->dop_low && ap->aeof) {
3712                 if (!ap->offset) {
3713                         args.alignment = stripe_align;
3714                         atype = args.type;
3715                         isaligned = 1;
3716                         /*
3717                          * Adjust for alignment
3718                          */
3719                         if (blen > args.alignment && blen <= args.maxlen)
3720                                 args.minlen = blen - args.alignment;
3721                         args.minalignslop = 0;
3722                 } else {
3723                         /*
3724                          * First try an exact bno allocation.
3725                          * If it fails then do a near or start bno
3726                          * allocation with alignment turned on.
3727                          */
3728                         atype = args.type;
3729                         tryagain = 1;
3730                         args.type = XFS_ALLOCTYPE_THIS_BNO;
3731                         args.alignment = 1;
3732                         /*
3733                          * Compute the minlen+alignment for the
3734                          * next case.  Set slop so that the value
3735                          * of minlen+alignment+slop doesn't go up
3736                          * between the calls.
3737                          */
3738                         if (blen > stripe_align && blen <= args.maxlen)
3739                                 nextminlen = blen - stripe_align;
3740                         else
3741                                 nextminlen = args.minlen;
3742                         if (nextminlen + stripe_align > args.minlen + 1)
3743                                 args.minalignslop =
3744                                         nextminlen + stripe_align -
3745                                         args.minlen - 1;
3746                         else
3747                                 args.minalignslop = 0;
3748                 }
3749         } else {
3750                 args.alignment = 1;
3751                 args.minalignslop = 0;
3752         }
3753         args.minleft = ap->minleft;
3754         args.wasdel = ap->wasdel;
3755         args.isfl = 0;
3756         args.userdata = ap->userdata;
3757         if (ap->userdata & XFS_ALLOC_USERDATA_ZERO)
3758                 args.ip = ap->ip;
3759
3760         error = xfs_alloc_vextent(&args);
3761         if (error)
3762                 return error;
3763
3764         if (tryagain && args.fsbno == NULLFSBLOCK) {
3765                 /*
3766                  * Exact allocation failed. Now try with alignment
3767                  * turned on.
3768                  */
3769                 args.type = atype;
3770                 args.fsbno = ap->blkno;
3771                 args.alignment = stripe_align;
3772                 args.minlen = nextminlen;
3773                 args.minalignslop = 0;
3774                 isaligned = 1;
3775                 if ((error = xfs_alloc_vextent(&args)))
3776                         return error;
3777         }
3778         if (isaligned && args.fsbno == NULLFSBLOCK) {
3779                 /*
3780                  * allocation failed, so turn off alignment and
3781                  * try again.
3782                  */
3783                 args.type = atype;
3784                 args.fsbno = ap->blkno;
3785                 args.alignment = 0;
3786                 if ((error = xfs_alloc_vextent(&args)))
3787                         return error;
3788         }
3789         if (args.fsbno == NULLFSBLOCK && nullfb &&
3790             args.minlen > ap->minlen) {
3791                 args.minlen = ap->minlen;
3792                 args.type = XFS_ALLOCTYPE_START_BNO;
3793                 args.fsbno = ap->blkno;
3794                 if ((error = xfs_alloc_vextent(&args)))
3795                         return error;
3796         }
3797         if (args.fsbno == NULLFSBLOCK && nullfb) {
3798                 args.fsbno = 0;
3799                 args.type = XFS_ALLOCTYPE_FIRST_AG;
3800                 args.total = ap->minlen;
3801                 args.minleft = 0;
3802                 if ((error = xfs_alloc_vextent(&args)))
3803                         return error;
3804                 ap->flist->dop_low = true;
3805         }
3806         if (args.fsbno != NULLFSBLOCK) {
3807                 /*
3808                  * check the allocation happened at the same or higher AG than
3809                  * the first block that was allocated.
3810                  */
3811                 ASSERT(*ap->firstblock == NULLFSBLOCK ||
3812                        XFS_FSB_TO_AGNO(mp, *ap->firstblock) ==
3813                        XFS_FSB_TO_AGNO(mp, args.fsbno) ||
3814                        (ap->flist->dop_low &&
3815                         XFS_FSB_TO_AGNO(mp, *ap->firstblock) <
3816                         XFS_FSB_TO_AGNO(mp, args.fsbno)));
3817
3818                 ap->blkno = args.fsbno;
3819                 if (*ap->firstblock == NULLFSBLOCK)
3820                         *ap->firstblock = args.fsbno;
3821                 ASSERT(nullfb || fb_agno == args.agno ||
3822                        (ap->flist->dop_low && fb_agno < args.agno));
3823                 ap->length = args.len;
3824                 ap->ip->i_d.di_nblocks += args.len;
3825                 xfs_trans_log_inode(ap->tp, ap->ip, XFS_ILOG_CORE);
3826                 if (ap->wasdel)
3827                         ap->ip->i_delayed_blks -= args.len;
3828                 /*
3829                  * Adjust the disk quota also. This was reserved
3830                  * earlier.
3831                  */
3832                 xfs_trans_mod_dquot_byino(ap->tp, ap->ip,
3833                         ap->wasdel ? XFS_TRANS_DQ_DELBCOUNT :
3834                                         XFS_TRANS_DQ_BCOUNT,
3835                         (long) args.len);
3836         } else {
3837                 ap->blkno = NULLFSBLOCK;
3838                 ap->length = 0;
3839         }
3840         return 0;
3841 }
3842
3843 /*
3844  * xfs_bmap_alloc is called by xfs_bmapi to allocate an extent for a file.
3845  * It figures out where to ask the underlying allocator to put the new extent.
3846  */
3847 STATIC int
3848 xfs_bmap_alloc(
3849         struct xfs_bmalloca     *ap)    /* bmap alloc argument struct */
3850 {
3851         if (XFS_IS_REALTIME_INODE(ap->ip) && ap->userdata)
3852                 return xfs_bmap_rtalloc(ap);
3853         return xfs_bmap_btalloc(ap);
3854 }
3855
3856 /*
3857  * Trim the returned map to the required bounds
3858  */
3859 STATIC void
3860 xfs_bmapi_trim_map(
3861         struct xfs_bmbt_irec    *mval,
3862         struct xfs_bmbt_irec    *got,
3863         xfs_fileoff_t           *bno,
3864         xfs_filblks_t           len,
3865         xfs_fileoff_t           obno,
3866         xfs_fileoff_t           end,
3867         int                     n,
3868         int                     flags)
3869 {
3870         if ((flags & XFS_BMAPI_ENTIRE) ||
3871             got->br_startoff + got->br_blockcount <= obno) {
3872                 *mval = *got;
3873                 if (isnullstartblock(got->br_startblock))
3874                         mval->br_startblock = DELAYSTARTBLOCK;
3875                 return;
3876         }
3877
3878         if (obno > *bno)
3879                 *bno = obno;
3880         ASSERT((*bno >= obno) || (n == 0));
3881         ASSERT(*bno < end);
3882         mval->br_startoff = *bno;
3883         if (isnullstartblock(got->br_startblock))
3884                 mval->br_startblock = DELAYSTARTBLOCK;
3885         else
3886                 mval->br_startblock = got->br_startblock +
3887                                         (*bno - got->br_startoff);
3888         /*
3889          * Return the minimum of what we got and what we asked for for
3890          * the length.  We can use the len variable here because it is
3891          * modified below and we could have been there before coming
3892          * here if the first part of the allocation didn't overlap what
3893          * was asked for.
3894          */
3895         mval->br_blockcount = XFS_FILBLKS_MIN(end - *bno,
3896                         got->br_blockcount - (*bno - got->br_startoff));
3897         mval->br_state = got->br_state;
3898         ASSERT(mval->br_blockcount <= len);
3899         return;
3900 }
3901
3902 /*
3903  * Update and validate the extent map to return
3904  */
3905 STATIC void
3906 xfs_bmapi_update_map(
3907         struct xfs_bmbt_irec    **map,
3908         xfs_fileoff_t           *bno,
3909         xfs_filblks_t           *len,
3910         xfs_fileoff_t           obno,
3911         xfs_fileoff_t           end,
3912         int                     *n,
3913         int                     flags)
3914 {
3915         xfs_bmbt_irec_t *mval = *map;
3916
3917         ASSERT((flags & XFS_BMAPI_ENTIRE) ||
3918                ((mval->br_startoff + mval->br_blockcount) <= end));
3919         ASSERT((flags & XFS_BMAPI_ENTIRE) || (mval->br_blockcount <= *len) ||
3920                (mval->br_startoff < obno));
3921
3922         *bno = mval->br_startoff + mval->br_blockcount;
3923         *len = end - *bno;
3924         if (*n > 0 && mval->br_startoff == mval[-1].br_startoff) {
3925                 /* update previous map with new information */
3926                 ASSERT(mval->br_startblock == mval[-1].br_startblock);
3927                 ASSERT(mval->br_blockcount > mval[-1].br_blockcount);
3928                 ASSERT(mval->br_state == mval[-1].br_state);
3929                 mval[-1].br_blockcount = mval->br_blockcount;
3930                 mval[-1].br_state = mval->br_state;
3931         } else if (*n > 0 && mval->br_startblock != DELAYSTARTBLOCK &&
3932                    mval[-1].br_startblock != DELAYSTARTBLOCK &&
3933                    mval[-1].br_startblock != HOLESTARTBLOCK &&
3934                    mval->br_startblock == mval[-1].br_startblock +
3935                                           mval[-1].br_blockcount &&
3936                    ((flags & XFS_BMAPI_IGSTATE) ||
3937                         mval[-1].br_state == mval->br_state)) {
3938                 ASSERT(mval->br_startoff ==
3939                        mval[-1].br_startoff + mval[-1].br_blockcount);
3940                 mval[-1].br_blockcount += mval->br_blockcount;
3941         } else if (*n > 0 &&
3942                    mval->br_startblock == DELAYSTARTBLOCK &&
3943                    mval[-1].br_startblock == DELAYSTARTBLOCK &&
3944                    mval->br_startoff ==
3945                    mval[-1].br_startoff + mval[-1].br_blockcount) {
3946                 mval[-1].br_blockcount += mval->br_blockcount;
3947                 mval[-1].br_state = mval->br_state;
3948         } else if (!((*n == 0) &&
3949                      ((mval->br_startoff + mval->br_blockcount) <=
3950                       obno))) {
3951                 mval++;
3952                 (*n)++;
3953         }
3954         *map = mval;
3955 }
3956
3957 /*
3958  * Map file blocks to filesystem blocks without allocation.
3959  */
3960 int
3961 xfs_bmapi_read(
3962         struct xfs_inode        *ip,
3963         xfs_fileoff_t           bno,
3964         xfs_filblks_t           len,
3965         struct xfs_bmbt_irec    *mval,
3966         int                     *nmap,
3967         int                     flags)
3968 {
3969         struct xfs_mount        *mp = ip->i_mount;
3970         struct xfs_ifork        *ifp;
3971         struct xfs_bmbt_irec    got;
3972         struct xfs_bmbt_irec    prev;
3973         xfs_fileoff_t           obno;
3974         xfs_fileoff_t           end;
3975         xfs_extnum_t            lastx;
3976         int                     error;
3977         int                     eof;
3978         int                     n = 0;
3979         int                     whichfork = (flags & XFS_BMAPI_ATTRFORK) ?
3980                                                 XFS_ATTR_FORK : XFS_DATA_FORK;
3981
3982         ASSERT(*nmap >= 1);
3983         ASSERT(!(flags & ~(XFS_BMAPI_ATTRFORK|XFS_BMAPI_ENTIRE|
3984                            XFS_BMAPI_IGSTATE)));
3985         ASSERT(xfs_isilocked(ip, XFS_ILOCK_SHARED|XFS_ILOCK_EXCL));
3986
3987         if (unlikely(XFS_TEST_ERROR(
3988             (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
3989              XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE),
3990              mp, XFS_ERRTAG_BMAPIFORMAT, XFS_RANDOM_BMAPIFORMAT))) {
3991                 XFS_ERROR_REPORT("xfs_bmapi_read", XFS_ERRLEVEL_LOW, mp);
3992                 return -EFSCORRUPTED;
3993         }
3994
3995         if (XFS_FORCED_SHUTDOWN(mp))
3996                 return -EIO;
3997
3998         XFS_STATS_INC(mp, xs_blk_mapr);
3999
4000         ifp = XFS_IFORK_PTR(ip, whichfork);
4001
4002         if (!(ifp->if_flags & XFS_IFEXTENTS)) {
4003                 error = xfs_iread_extents(NULL, ip, whichfork);
4004                 if (error)
4005                         return error;
4006         }
4007
4008         xfs_bmap_search_extents(ip, bno, whichfork, &eof, &lastx, &got, &prev);
4009         end = bno + len;
4010         obno = bno;
4011
4012         while (bno < end && n < *nmap) {
4013                 /* Reading past eof, act as though there's a hole up to end. */
4014                 if (eof)
4015                         got.br_startoff = end;
4016                 if (got.br_startoff > bno) {
4017                         /* Reading in a hole.  */
4018                         mval->br_startoff = bno;
4019                         mval->br_startblock = HOLESTARTBLOCK;
4020                         mval->br_blockcount =
4021                                 XFS_FILBLKS_MIN(len, got.br_startoff - bno);
4022                         mval->br_state = XFS_EXT_NORM;
4023                         bno += mval->br_blockcount;
4024                         len -= mval->br_blockcount;
4025                         mval++;
4026                         n++;
4027                         continue;
4028                 }
4029
4030                 /* set up the extent map to return. */
4031                 xfs_bmapi_trim_map(mval, &got, &bno, len, obno, end, n, flags);
4032                 xfs_bmapi_update_map(&mval, &bno, &len, obno, end, &n, flags);
4033
4034                 /* If we're done, stop now. */
4035                 if (bno >= end || n >= *nmap)
4036                         break;
4037
4038                 /* Else go on to the next record. */
4039                 if (++lastx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t))
4040                         xfs_bmbt_get_all(xfs_iext_get_ext(ifp, lastx), &got);
4041                 else
4042                         eof = 1;
4043         }
4044         *nmap = n;
4045         return 0;
4046 }
4047
4048 STATIC int
4049 xfs_bmapi_reserve_delalloc(
4050         struct xfs_inode        *ip,
4051         xfs_fileoff_t           aoff,
4052         xfs_filblks_t           len,
4053         struct xfs_bmbt_irec    *got,
4054         struct xfs_bmbt_irec    *prev,
4055         xfs_extnum_t            *lastx,
4056         int                     eof)
4057 {
4058         struct xfs_mount        *mp = ip->i_mount;
4059         struct xfs_ifork        *ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
4060         xfs_extlen_t            alen;
4061         xfs_extlen_t            indlen;
4062         char                    rt = XFS_IS_REALTIME_INODE(ip);
4063         xfs_extlen_t            extsz;
4064         int                     error;
4065
4066         alen = XFS_FILBLKS_MIN(len, MAXEXTLEN);
4067         if (!eof)
4068                 alen = XFS_FILBLKS_MIN(alen, got->br_startoff - aoff);
4069
4070         /* Figure out the extent size, adjust alen */
4071         extsz = xfs_get_extsz_hint(ip);
4072         if (extsz) {
4073                 error = xfs_bmap_extsize_align(mp, got, prev, extsz, rt, eof,
4074                                                1, 0, &aoff, &alen);
4075                 ASSERT(!error);
4076         }
4077
4078         if (rt)
4079                 extsz = alen / mp->m_sb.sb_rextsize;
4080
4081         /*
4082          * Make a transaction-less quota reservation for delayed allocation
4083          * blocks.  This number gets adjusted later.  We return if we haven't
4084          * allocated blocks already inside this loop.
4085          */
4086         error = xfs_trans_reserve_quota_nblks(NULL, ip, (long)alen, 0,
4087                         rt ? XFS_QMOPT_RES_RTBLKS : XFS_QMOPT_RES_REGBLKS);
4088         if (error)
4089                 return error;
4090
4091         /*
4092          * Split changing sb for alen and indlen since they could be coming
4093          * from different places.
4094          */
4095         indlen = (xfs_extlen_t)xfs_bmap_worst_indlen(ip, alen);
4096         ASSERT(indlen > 0);
4097
4098         if (rt) {
4099                 error = xfs_mod_frextents(mp, -((int64_t)extsz));
4100         } else {
4101                 error = xfs_mod_fdblocks(mp, -((int64_t)alen), false);
4102         }
4103
4104         if (error)
4105                 goto out_unreserve_quota;
4106
4107         error = xfs_mod_fdblocks(mp, -((int64_t)indlen), false);
4108         if (error)
4109                 goto out_unreserve_blocks;
4110
4111
4112         ip->i_delayed_blks += alen;
4113
4114         got->br_startoff = aoff;
4115         got->br_startblock = nullstartblock(indlen);
4116         got->br_blockcount = alen;
4117         got->br_state = XFS_EXT_NORM;
4118         xfs_bmap_add_extent_hole_delay(ip, lastx, got);
4119
4120         /*
4121          * Update our extent pointer, given that xfs_bmap_add_extent_hole_delay
4122          * might have merged it into one of the neighbouring ones.
4123          */
4124         xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *lastx), got);
4125
4126         ASSERT(got->br_startoff <= aoff);
4127         ASSERT(got->br_startoff + got->br_blockcount >= aoff + alen);
4128         ASSERT(isnullstartblock(got->br_startblock));
4129         ASSERT(got->br_state == XFS_EXT_NORM);
4130         return 0;
4131
4132 out_unreserve_blocks:
4133         if (rt)
4134                 xfs_mod_frextents(mp, extsz);
4135         else
4136                 xfs_mod_fdblocks(mp, alen, false);
4137 out_unreserve_quota:
4138         if (XFS_IS_QUOTA_ON(mp))
4139                 xfs_trans_unreserve_quota_nblks(NULL, ip, (long)alen, 0, rt ?
4140                                 XFS_QMOPT_RES_RTBLKS : XFS_QMOPT_RES_REGBLKS);
4141         return error;
4142 }
4143
4144 /*
4145  * Map file blocks to filesystem blocks, adding delayed allocations as needed.
4146  */
4147 int
4148 xfs_bmapi_delay(
4149         struct xfs_inode        *ip,    /* incore inode */
4150         xfs_fileoff_t           bno,    /* starting file offs. mapped */
4151         xfs_filblks_t           len,    /* length to map in file */
4152         struct xfs_bmbt_irec    *mval,  /* output: map values */
4153         int                     *nmap,  /* i/o: mval size/count */
4154         int                     flags)  /* XFS_BMAPI_... */
4155 {
4156         struct xfs_mount        *mp = ip->i_mount;
4157         struct xfs_ifork        *ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
4158         struct xfs_bmbt_irec    got;    /* current file extent record */
4159         struct xfs_bmbt_irec    prev;   /* previous file extent record */
4160         xfs_fileoff_t           obno;   /* old block number (offset) */
4161         xfs_fileoff_t           end;    /* end of mapped file region */
4162         xfs_extnum_t            lastx;  /* last useful extent number */
4163         int                     eof;    /* we've hit the end of extents */
4164         int                     n = 0;  /* current extent index */
4165         int                     error = 0;
4166
4167         ASSERT(*nmap >= 1);
4168         ASSERT(*nmap <= XFS_BMAP_MAX_NMAP);
4169         ASSERT(!(flags & ~XFS_BMAPI_ENTIRE));
4170         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
4171
4172         if (unlikely(XFS_TEST_ERROR(
4173             (XFS_IFORK_FORMAT(ip, XFS_DATA_FORK) != XFS_DINODE_FMT_EXTENTS &&
4174              XFS_IFORK_FORMAT(ip, XFS_DATA_FORK) != XFS_DINODE_FMT_BTREE),
4175              mp, XFS_ERRTAG_BMAPIFORMAT, XFS_RANDOM_BMAPIFORMAT))) {
4176                 XFS_ERROR_REPORT("xfs_bmapi_delay", XFS_ERRLEVEL_LOW, mp);
4177                 return -EFSCORRUPTED;
4178         }
4179
4180         if (XFS_FORCED_SHUTDOWN(mp))
4181                 return -EIO;
4182
4183         XFS_STATS_INC(mp, xs_blk_mapw);
4184
4185         if (!(ifp->if_flags & XFS_IFEXTENTS)) {
4186                 error = xfs_iread_extents(NULL, ip, XFS_DATA_FORK);
4187                 if (error)
4188                         return error;
4189         }
4190
4191         xfs_bmap_search_extents(ip, bno, XFS_DATA_FORK, &eof, &lastx, &got, &prev);
4192         end = bno + len;
4193         obno = bno;
4194
4195         while (bno < end && n < *nmap) {
4196                 if (eof || got.br_startoff > bno) {
4197                         error = xfs_bmapi_reserve_delalloc(ip, bno, len, &got,
4198                                                            &prev, &lastx, eof);
4199                         if (error) {
4200                                 if (n == 0) {
4201                                         *nmap = 0;
4202                                         return error;
4203                                 }
4204                                 break;
4205                         }
4206                 }
4207
4208                 /* set up the extent map to return. */
4209                 xfs_bmapi_trim_map(mval, &got, &bno, len, obno, end, n, flags);
4210                 xfs_bmapi_update_map(&mval, &bno, &len, obno, end, &n, flags);
4211
4212                 /* If we're done, stop now. */
4213                 if (bno >= end || n >= *nmap)
4214                         break;
4215
4216                 /* Else go on to the next record. */
4217                 prev = got;
4218                 if (++lastx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t))
4219                         xfs_bmbt_get_all(xfs_iext_get_ext(ifp, lastx), &got);
4220                 else
4221                         eof = 1;
4222         }
4223
4224         *nmap = n;
4225         return 0;
4226 }
4227
4228
4229 static int
4230 xfs_bmapi_allocate(
4231         struct xfs_bmalloca     *bma)
4232 {
4233         struct xfs_mount        *mp = bma->ip->i_mount;
4234         int                     whichfork = (bma->flags & XFS_BMAPI_ATTRFORK) ?
4235                                                 XFS_ATTR_FORK : XFS_DATA_FORK;
4236         struct xfs_ifork        *ifp = XFS_IFORK_PTR(bma->ip, whichfork);
4237         int                     tmp_logflags = 0;
4238         int                     error;
4239
4240         ASSERT(bma->length > 0);
4241
4242         /*
4243          * For the wasdelay case, we could also just allocate the stuff asked
4244          * for in this bmap call but that wouldn't be as good.
4245          */
4246         if (bma->wasdel) {
4247                 bma->length = (xfs_extlen_t)bma->got.br_blockcount;
4248                 bma->offset = bma->got.br_startoff;
4249                 if (bma->idx != NULLEXTNUM && bma->idx) {
4250                         xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx - 1),
4251                                          &bma->prev);
4252                 }
4253         } else {
4254                 bma->length = XFS_FILBLKS_MIN(bma->length, MAXEXTLEN);
4255                 if (!bma->eof)
4256                         bma->length = XFS_FILBLKS_MIN(bma->length,
4257                                         bma->got.br_startoff - bma->offset);
4258         }
4259
4260         /*
4261          * Indicate if this is the first user data in the file, or just any
4262          * user data. And if it is userdata, indicate whether it needs to
4263          * be initialised to zero during allocation.
4264          */
4265         if (!(bma->flags & XFS_BMAPI_METADATA)) {
4266                 bma->userdata = (bma->offset == 0) ?
4267                         XFS_ALLOC_INITIAL_USER_DATA : XFS_ALLOC_USERDATA;
4268                 if (bma->flags & XFS_BMAPI_ZERO)
4269                         bma->userdata |= XFS_ALLOC_USERDATA_ZERO;
4270         }
4271
4272         bma->minlen = (bma->flags & XFS_BMAPI_CONTIG) ? bma->length : 1;
4273
4274         /*
4275          * Only want to do the alignment at the eof if it is userdata and
4276          * allocation length is larger than a stripe unit.
4277          */
4278         if (mp->m_dalign && bma->length >= mp->m_dalign &&
4279             !(bma->flags & XFS_BMAPI_METADATA) && whichfork == XFS_DATA_FORK) {
4280                 error = xfs_bmap_isaeof(bma, whichfork);
4281                 if (error)
4282                         return error;
4283         }
4284
4285         error = xfs_bmap_alloc(bma);
4286         if (error)
4287                 return error;
4288
4289         if (bma->flist->dop_low)
4290                 bma->minleft = 0;
4291         if (bma->cur)
4292                 bma->cur->bc_private.b.firstblock = *bma->firstblock;
4293         if (bma->blkno == NULLFSBLOCK)
4294                 return 0;
4295         if ((ifp->if_flags & XFS_IFBROOT) && !bma->cur) {
4296                 bma->cur = xfs_bmbt_init_cursor(mp, bma->tp, bma->ip, whichfork);
4297                 bma->cur->bc_private.b.firstblock = *bma->firstblock;
4298                 bma->cur->bc_private.b.flist = bma->flist;
4299         }
4300         /*
4301          * Bump the number of extents we've allocated
4302          * in this call.
4303          */
4304         bma->nallocs++;
4305
4306         if (bma->cur)
4307                 bma->cur->bc_private.b.flags =
4308                         bma->wasdel ? XFS_BTCUR_BPRV_WASDEL : 0;
4309
4310         bma->got.br_startoff = bma->offset;
4311         bma->got.br_startblock = bma->blkno;
4312         bma->got.br_blockcount = bma->length;
4313         bma->got.br_state = XFS_EXT_NORM;
4314
4315         /*
4316          * A wasdelay extent has been initialized, so shouldn't be flagged
4317          * as unwritten.
4318          */
4319         if (!bma->wasdel && (bma->flags & XFS_BMAPI_PREALLOC) &&
4320             xfs_sb_version_hasextflgbit(&mp->m_sb))
4321                 bma->got.br_state = XFS_EXT_UNWRITTEN;
4322
4323         if (bma->wasdel)
4324                 error = xfs_bmap_add_extent_delay_real(bma);
4325         else
4326                 error = xfs_bmap_add_extent_hole_real(bma, whichfork);
4327
4328         bma->logflags |= tmp_logflags;
4329         if (error)
4330                 return error;
4331
4332         /*
4333          * Update our extent pointer, given that xfs_bmap_add_extent_delay_real
4334          * or xfs_bmap_add_extent_hole_real might have merged it into one of
4335          * the neighbouring ones.
4336          */
4337         xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx), &bma->got);
4338
4339         ASSERT(bma->got.br_startoff <= bma->offset);
4340         ASSERT(bma->got.br_startoff + bma->got.br_blockcount >=
4341                bma->offset + bma->length);
4342         ASSERT(bma->got.br_state == XFS_EXT_NORM ||
4343                bma->got.br_state == XFS_EXT_UNWRITTEN);
4344         return 0;
4345 }
4346
4347 STATIC int
4348 xfs_bmapi_convert_unwritten(
4349         struct xfs_bmalloca     *bma,
4350         struct xfs_bmbt_irec    *mval,
4351         xfs_filblks_t           len,
4352         int                     flags)
4353 {
4354         int                     whichfork = (flags & XFS_BMAPI_ATTRFORK) ?
4355                                                 XFS_ATTR_FORK : XFS_DATA_FORK;
4356         struct xfs_ifork        *ifp = XFS_IFORK_PTR(bma->ip, whichfork);
4357         int                     tmp_logflags = 0;
4358         int                     error;
4359
4360         /* check if we need to do unwritten->real conversion */
4361         if (mval->br_state == XFS_EXT_UNWRITTEN &&
4362             (flags & XFS_BMAPI_PREALLOC))
4363                 return 0;
4364
4365         /* check if we need to do real->unwritten conversion */
4366         if (mval->br_state == XFS_EXT_NORM &&
4367             (flags & (XFS_BMAPI_PREALLOC | XFS_BMAPI_CONVERT)) !=
4368                         (XFS_BMAPI_PREALLOC | XFS_BMAPI_CONVERT))
4369                 return 0;
4370
4371         /*
4372          * Modify (by adding) the state flag, if writing.
4373          */
4374         ASSERT(mval->br_blockcount <= len);
4375         if ((ifp->if_flags & XFS_IFBROOT) && !bma->cur) {
4376                 bma->cur = xfs_bmbt_init_cursor(bma->ip->i_mount, bma->tp,
4377                                         bma->ip, whichfork);
4378                 bma->cur->bc_private.b.firstblock = *bma->firstblock;
4379                 bma->cur->bc_private.b.flist = bma->flist;
4380         }
4381         mval->br_state = (mval->br_state == XFS_EXT_UNWRITTEN)
4382                                 ? XFS_EXT_NORM : XFS_EXT_UNWRITTEN;
4383
4384         /*
4385          * Before insertion into the bmbt, zero the range being converted
4386          * if required.
4387          */
4388         if (flags & XFS_BMAPI_ZERO) {
4389                 error = xfs_zero_extent(bma->ip, mval->br_startblock,
4390                                         mval->br_blockcount);
4391                 if (error)
4392                         return error;
4393         }
4394
4395         error = xfs_bmap_add_extent_unwritten_real(bma->tp, bma->ip, &bma->idx,
4396                         &bma->cur, mval, bma->firstblock, bma->flist,
4397                         &tmp_logflags);
4398         /*
4399          * Log the inode core unconditionally in the unwritten extent conversion
4400          * path because the conversion might not have done so (e.g., if the
4401          * extent count hasn't changed). We need to make sure the inode is dirty
4402          * in the transaction for the sake of fsync(), even if nothing has
4403          * changed, because fsync() will not force the log for this transaction
4404          * unless it sees the inode pinned.
4405          */
4406         bma->logflags |= tmp_logflags | XFS_ILOG_CORE;
4407         if (error)
4408                 return error;
4409
4410         /*
4411          * Update our extent pointer, given that
4412          * xfs_bmap_add_extent_unwritten_real might have merged it into one
4413          * of the neighbouring ones.
4414          */
4415         xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx), &bma->got);
4416
4417         /*
4418          * We may have combined previously unwritten space with written space,
4419          * so generate another request.
4420          */
4421         if (mval->br_blockcount < len)
4422                 return -EAGAIN;
4423         return 0;
4424 }
4425
4426 /*
4427  * Map file blocks to filesystem blocks, and allocate blocks or convert the
4428  * extent state if necessary.  Details behaviour is controlled by the flags
4429  * parameter.  Only allocates blocks from a single allocation group, to avoid
4430  * locking problems.
4431  *
4432  * The returned value in "firstblock" from the first call in a transaction
4433  * must be remembered and presented to subsequent calls in "firstblock".
4434  * An upper bound for the number of blocks to be allocated is supplied to
4435  * the first call in "total"; if no allocation group has that many free
4436  * blocks then the call will fail (return NULLFSBLOCK in "firstblock").
4437  */
4438 int
4439 xfs_bmapi_write(
4440         struct xfs_trans        *tp,            /* transaction pointer */
4441         struct xfs_inode        *ip,            /* incore inode */
4442         xfs_fileoff_t           bno,            /* starting file offs. mapped */
4443         xfs_filblks_t           len,            /* length to map in file */
4444         int                     flags,          /* XFS_BMAPI_... */
4445         xfs_fsblock_t           *firstblock,    /* first allocated block
4446                                                    controls a.g. for allocs */
4447         xfs_extlen_t            total,          /* total blocks needed */
4448         struct xfs_bmbt_irec    *mval,          /* output: map values */
4449         int                     *nmap,          /* i/o: mval size/count */
4450         struct xfs_bmap_free    *flist)         /* i/o: list extents to free */
4451 {
4452         struct xfs_mount        *mp = ip->i_mount;
4453         struct xfs_ifork        *ifp;
4454         struct xfs_bmalloca     bma = { NULL }; /* args for xfs_bmap_alloc */
4455         xfs_fileoff_t           end;            /* end of mapped file region */
4456         int                     eof;            /* after the end of extents */
4457         int                     error;          /* error return */
4458         int                     n;              /* current extent index */
4459         xfs_fileoff_t           obno;           /* old block number (offset) */
4460         int                     whichfork;      /* data or attr fork */
4461         char                    inhole;         /* current location is hole in file */
4462         char                    wasdelay;       /* old extent was delayed */
4463
4464 #ifdef DEBUG
4465         xfs_fileoff_t           orig_bno;       /* original block number value */
4466         int                     orig_flags;     /* original flags arg value */
4467         xfs_filblks_t           orig_len;       /* original value of len arg */
4468         struct xfs_bmbt_irec    *orig_mval;     /* original value of mval */
4469         int                     orig_nmap;      /* original value of *nmap */
4470
4471         orig_bno = bno;
4472         orig_len = len;
4473         orig_flags = flags;
4474         orig_mval = mval;
4475         orig_nmap = *nmap;
4476 #endif
4477         whichfork = (flags & XFS_BMAPI_ATTRFORK) ?
4478                 XFS_ATTR_FORK : XFS_DATA_FORK;
4479
4480         ASSERT(*nmap >= 1);
4481         ASSERT(*nmap <= XFS_BMAP_MAX_NMAP);
4482         ASSERT(!(flags & XFS_BMAPI_IGSTATE));
4483         ASSERT(tp != NULL);
4484         ASSERT(len > 0);
4485         ASSERT(XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_LOCAL);
4486         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
4487
4488         /* zeroing is for currently only for data extents, not metadata */
4489         ASSERT((flags & (XFS_BMAPI_METADATA | XFS_BMAPI_ZERO)) !=
4490                         (XFS_BMAPI_METADATA | XFS_BMAPI_ZERO));
4491         /*
4492          * we can allocate unwritten extents or pre-zero allocated blocks,
4493          * but it makes no sense to do both at once. This would result in
4494          * zeroing the unwritten extent twice, but it still being an
4495          * unwritten extent....
4496          */
4497         ASSERT((flags & (XFS_BMAPI_PREALLOC | XFS_BMAPI_ZERO)) !=
4498                         (XFS_BMAPI_PREALLOC | XFS_BMAPI_ZERO));
4499
4500         if (unlikely(XFS_TEST_ERROR(
4501             (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
4502              XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE),
4503              mp, XFS_ERRTAG_BMAPIFORMAT, XFS_RANDOM_BMAPIFORMAT))) {
4504                 XFS_ERROR_REPORT("xfs_bmapi_write", XFS_ERRLEVEL_LOW, mp);
4505                 return -EFSCORRUPTED;
4506         }
4507
4508         if (XFS_FORCED_SHUTDOWN(mp))
4509                 return -EIO;
4510
4511         ifp = XFS_IFORK_PTR(ip, whichfork);
4512
4513         XFS_STATS_INC(mp, xs_blk_mapw);
4514
4515         if (*firstblock == NULLFSBLOCK) {
4516                 if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE)
4517                         bma.minleft = be16_to_cpu(ifp->if_broot->bb_level) + 1;
4518                 else
4519                         bma.minleft = 1;
4520         } else {
4521                 bma.minleft = 0;
4522         }
4523
4524         if (!(ifp->if_flags & XFS_IFEXTENTS)) {
4525                 error = xfs_iread_extents(tp, ip, whichfork);
4526                 if (error)
4527                         goto error0;
4528         }
4529
4530         xfs_bmap_search_extents(ip, bno, whichfork, &eof, &bma.idx, &bma.got,
4531                                 &bma.prev);
4532         n = 0;
4533         end = bno + len;
4534         obno = bno;
4535
4536         bma.tp = tp;
4537         bma.ip = ip;
4538         bma.total = total;
4539         bma.userdata = 0;
4540         bma.flist = flist;
4541         bma.firstblock = firstblock;
4542
4543         while (bno < end && n < *nmap) {
4544                 inhole = eof || bma.got.br_startoff > bno;
4545                 wasdelay = !inhole && isnullstartblock(bma.got.br_startblock);
4546
4547                 /*
4548                  * First, deal with the hole before the allocated space
4549                  * that we found, if any.
4550                  */
4551                 if (inhole || wasdelay) {
4552                         bma.eof = eof;
4553                         bma.conv = !!(flags & XFS_BMAPI_CONVERT);
4554                         bma.wasdel = wasdelay;
4555                         bma.offset = bno;
4556                         bma.flags = flags;
4557
4558                         /*
4559                          * There's a 32/64 bit type mismatch between the
4560                          * allocation length request (which can be 64 bits in
4561                          * length) and the bma length request, which is
4562                          * xfs_extlen_t and therefore 32 bits. Hence we have to
4563                          * check for 32-bit overflows and handle them here.
4564                          */
4565                         if (len > (xfs_filblks_t)MAXEXTLEN)
4566                                 bma.length = MAXEXTLEN;
4567                         else
4568                                 bma.length = len;
4569
4570                         ASSERT(len > 0);
4571                         ASSERT(bma.length > 0);
4572                         error = xfs_bmapi_allocate(&bma);
4573                         if (error)
4574                                 goto error0;
4575                         if (bma.blkno == NULLFSBLOCK)
4576                                 break;
4577                 }
4578
4579                 /* Deal with the allocated space we found.  */
4580                 xfs_bmapi_trim_map(mval, &bma.got, &bno, len, obno,
4581                                                         end, n, flags);
4582
4583                 /* Execute unwritten extent conversion if necessary */
4584                 error = xfs_bmapi_convert_unwritten(&bma, mval, len, flags);
4585                 if (error == -EAGAIN)
4586                         continue;
4587                 if (error)
4588                         goto error0;
4589
4590                 /* update the extent map to return */
4591                 xfs_bmapi_update_map(&mval, &bno, &len, obno, end, &n, flags);
4592
4593                 /*
4594                  * If we're done, stop now.  Stop when we've allocated
4595                  * XFS_BMAP_MAX_NMAP extents no matter what.  Otherwise
4596                  * the transaction may get too big.
4597                  */
4598                 if (bno >= end || n >= *nmap || bma.nallocs >= *nmap)
4599                         break;
4600
4601                 /* Else go on to the next record. */
4602                 bma.prev = bma.got;
4603                 if (++bma.idx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t)) {
4604                         xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma.idx),
4605                                          &bma.got);
4606                 } else
4607                         eof = 1;
4608         }
4609         *nmap = n;
4610
4611         /*
4612          * Transform from btree to extents, give it cur.
4613          */
4614         if (xfs_bmap_wants_extents(ip, whichfork)) {
4615                 int             tmp_logflags = 0;
4616
4617                 ASSERT(bma.cur);
4618                 error = xfs_bmap_btree_to_extents(tp, ip, bma.cur,
4619                         &tmp_logflags, whichfork);
4620                 bma.logflags |= tmp_logflags;
4621                 if (error)
4622                         goto error0;
4623         }
4624
4625         ASSERT(XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE ||
4626                XFS_IFORK_NEXTENTS(ip, whichfork) >
4627                 XFS_IFORK_MAXEXT(ip, whichfork));
4628         error = 0;
4629 error0:
4630         /*
4631          * Log everything.  Do this after conversion, there's no point in
4632          * logging the extent records if we've converted to btree format.
4633          */
4634         if ((bma.logflags & xfs_ilog_fext(whichfork)) &&
4635             XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
4636                 bma.logflags &= ~xfs_ilog_fext(whichfork);
4637         else if ((bma.logflags & xfs_ilog_fbroot(whichfork)) &&
4638                  XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE)
4639                 bma.logflags &= ~xfs_ilog_fbroot(whichfork);
4640         /*
4641          * Log whatever the flags say, even if error.  Otherwise we might miss
4642          * detecting a case where the data is changed, there's an error,
4643          * and it's not logged so we don't shutdown when we should.
4644          */
4645         if (bma.logflags)
4646                 xfs_trans_log_inode(tp, ip, bma.logflags);
4647
4648         if (bma.cur) {
4649                 if (!error) {
4650                         ASSERT(*firstblock == NULLFSBLOCK ||
4651                                XFS_FSB_TO_AGNO(mp, *firstblock) ==
4652                                XFS_FSB_TO_AGNO(mp,
4653                                        bma.cur->bc_private.b.firstblock) ||
4654                                (flist->dop_low &&
4655                                 XFS_FSB_TO_AGNO(mp, *firstblock) <
4656                                 XFS_FSB_TO_AGNO(mp,
4657                                         bma.cur->bc_private.b.firstblock)));
4658                         *firstblock = bma.cur->bc_private.b.firstblock;
4659                 }
4660                 xfs_btree_del_cursor(bma.cur,
4661                         error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
4662         }
4663         if (!error)
4664                 xfs_bmap_validate_ret(orig_bno, orig_len, orig_flags, orig_mval,
4665                         orig_nmap, *nmap);
4666         return error;
4667 }
4668
4669 /*
4670  * When a delalloc extent is split (e.g., due to a hole punch), the original
4671  * indlen reservation must be shared across the two new extents that are left
4672  * behind.
4673  *
4674  * Given the original reservation and the worst case indlen for the two new
4675  * extents (as calculated by xfs_bmap_worst_indlen()), split the original
4676  * reservation fairly across the two new extents. If necessary, steal available
4677  * blocks from a deleted extent to make up a reservation deficiency (e.g., if
4678  * ores == 1). The number of stolen blocks is returned. The availability and
4679  * subsequent accounting of stolen blocks is the responsibility of the caller.
4680  */
4681 static xfs_filblks_t
4682 xfs_bmap_split_indlen(
4683         xfs_filblks_t                   ores,           /* original res. */
4684         xfs_filblks_t                   *indlen1,       /* ext1 worst indlen */
4685         xfs_filblks_t                   *indlen2,       /* ext2 worst indlen */
4686         xfs_filblks_t                   avail)          /* stealable blocks */
4687 {
4688         xfs_filblks_t                   len1 = *indlen1;
4689         xfs_filblks_t                   len2 = *indlen2;
4690         xfs_filblks_t                   nres = len1 + len2; /* new total res. */
4691         xfs_filblks_t                   stolen = 0;
4692
4693         /*
4694          * Steal as many blocks as we can to try and satisfy the worst case
4695          * indlen for both new extents.
4696          */
4697         while (nres > ores && avail) {
4698                 nres--;
4699                 avail--;
4700                 stolen++;
4701         }
4702
4703         /*
4704          * The only blocks available are those reserved for the original
4705          * extent and what we can steal from the extent being removed.
4706          * If this still isn't enough to satisfy the combined
4707          * requirements for the two new extents, skim blocks off of each
4708          * of the new reservations until they match what is available.
4709          */
4710         while (nres > ores) {
4711                 if (len1) {
4712                         len1--;
4713                         nres--;
4714                 }
4715                 if (nres == ores)
4716                         break;
4717                 if (len2) {
4718                         len2--;
4719                         nres--;
4720                 }
4721         }
4722
4723         *indlen1 = len1;
4724         *indlen2 = len2;
4725
4726         return stolen;
4727 }
4728
4729 /*
4730  * Called by xfs_bmapi to update file extent records and the btree
4731  * after removing space (or undoing a delayed allocation).
4732  */
4733 STATIC int                              /* error */
4734 xfs_bmap_del_extent(
4735         xfs_inode_t             *ip,    /* incore inode pointer */
4736         xfs_trans_t             *tp,    /* current transaction pointer */
4737         xfs_extnum_t            *idx,   /* extent number to update/delete */
4738         xfs_bmap_free_t         *flist, /* list of extents to be freed */
4739         xfs_btree_cur_t         *cur,   /* if null, not a btree */
4740         xfs_bmbt_irec_t         *del,   /* data to remove from extents */
4741         int                     *logflagsp, /* inode logging flags */
4742         int                     whichfork) /* data or attr fork */
4743 {
4744         xfs_filblks_t           da_new; /* new delay-alloc indirect blocks */
4745         xfs_filblks_t           da_old; /* old delay-alloc indirect blocks */
4746         xfs_fsblock_t           del_endblock=0; /* first block past del */
4747         xfs_fileoff_t           del_endoff;     /* first offset past del */
4748         int                     delay;  /* current block is delayed allocated */
4749         int                     do_fx;  /* free extent at end of routine */
4750         xfs_bmbt_rec_host_t     *ep;    /* current extent entry pointer */
4751         int                     error;  /* error return value */
4752         int                     flags;  /* inode logging flags */
4753         xfs_bmbt_irec_t         got;    /* current extent entry */
4754         xfs_fileoff_t           got_endoff;     /* first offset past got */
4755         int                     i;      /* temp state */
4756         xfs_ifork_t             *ifp;   /* inode fork pointer */
4757         xfs_mount_t             *mp;    /* mount structure */
4758         xfs_filblks_t           nblks;  /* quota/sb block count */
4759         xfs_bmbt_irec_t         new;    /* new record to be inserted */
4760         /* REFERENCED */
4761         uint                    qfield; /* quota field to update */
4762         xfs_filblks_t           temp;   /* for indirect length calculations */
4763         xfs_filblks_t           temp2;  /* for indirect length calculations */
4764         int                     state = 0;
4765
4766         mp = ip->i_mount;
4767         XFS_STATS_INC(mp, xs_del_exlist);
4768
4769         if (whichfork == XFS_ATTR_FORK)
4770                 state |= BMAP_ATTRFORK;
4771
4772         ifp = XFS_IFORK_PTR(ip, whichfork);
4773         ASSERT((*idx >= 0) && (*idx < ifp->if_bytes /
4774                 (uint)sizeof(xfs_bmbt_rec_t)));
4775         ASSERT(del->br_blockcount > 0);
4776         ep = xfs_iext_get_ext(ifp, *idx);
4777         xfs_bmbt_get_all(ep, &got);
4778         ASSERT(got.br_startoff <= del->br_startoff);
4779         del_endoff = del->br_startoff + del->br_blockcount;
4780         got_endoff = got.br_startoff + got.br_blockcount;
4781         ASSERT(got_endoff >= del_endoff);
4782         delay = isnullstartblock(got.br_startblock);
4783         ASSERT(isnullstartblock(del->br_startblock) == delay);
4784         flags = 0;
4785         qfield = 0;
4786         error = 0;
4787         /*
4788          * If deleting a real allocation, must free up the disk space.
4789          */
4790         if (!delay) {
4791                 flags = XFS_ILOG_CORE;
4792                 /*
4793                  * Realtime allocation.  Free it and record di_nblocks update.
4794                  */
4795                 if (whichfork == XFS_DATA_FORK && XFS_IS_REALTIME_INODE(ip)) {
4796                         xfs_fsblock_t   bno;
4797                         xfs_filblks_t   len;
4798
4799                         ASSERT(do_mod(del->br_blockcount,
4800                                       mp->m_sb.sb_rextsize) == 0);
4801                         ASSERT(do_mod(del->br_startblock,
4802                                       mp->m_sb.sb_rextsize) == 0);
4803                         bno = del->br_startblock;
4804                         len = del->br_blockcount;
4805                         do_div(bno, mp->m_sb.sb_rextsize);
4806                         do_div(len, mp->m_sb.sb_rextsize);
4807                         error = xfs_rtfree_extent(tp, bno, (xfs_extlen_t)len);
4808                         if (error)
4809                                 goto done;
4810                         do_fx = 0;
4811                         nblks = len * mp->m_sb.sb_rextsize;
4812                         qfield = XFS_TRANS_DQ_RTBCOUNT;
4813                 }
4814                 /*
4815                  * Ordinary allocation.
4816                  */
4817                 else {
4818                         do_fx = 1;
4819                         nblks = del->br_blockcount;
4820                         qfield = XFS_TRANS_DQ_BCOUNT;
4821                 }
4822                 /*
4823                  * Set up del_endblock and cur for later.
4824                  */
4825                 del_endblock = del->br_startblock + del->br_blockcount;
4826                 if (cur) {
4827                         if ((error = xfs_bmbt_lookup_eq(cur, got.br_startoff,
4828                                         got.br_startblock, got.br_blockcount,
4829                                         &i)))
4830                                 goto done;
4831                         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
4832                 }
4833                 da_old = da_new = 0;
4834         } else {
4835                 da_old = startblockval(got.br_startblock);
4836                 da_new = 0;
4837                 nblks = 0;
4838                 do_fx = 0;
4839         }
4840         /*
4841          * Set flag value to use in switch statement.
4842          * Left-contig is 2, right-contig is 1.
4843          */
4844         switch (((got.br_startoff == del->br_startoff) << 1) |
4845                 (got_endoff == del_endoff)) {
4846         case 3:
4847                 /*
4848                  * Matches the whole extent.  Delete the entry.
4849                  */
4850                 xfs_iext_remove(ip, *idx, 1,
4851                                 whichfork == XFS_ATTR_FORK ? BMAP_ATTRFORK : 0);
4852                 --*idx;
4853                 if (delay)
4854                         break;
4855
4856                 XFS_IFORK_NEXT_SET(ip, whichfork,
4857                         XFS_IFORK_NEXTENTS(ip, whichfork) - 1);
4858                 flags |= XFS_ILOG_CORE;
4859                 if (!cur) {
4860                         flags |= xfs_ilog_fext(whichfork);
4861                         break;
4862                 }
4863                 if ((error = xfs_btree_delete(cur, &i)))
4864                         goto done;
4865                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
4866                 break;
4867
4868         case 2:
4869                 /*
4870                  * Deleting the first part of the extent.
4871                  */
4872                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
4873                 xfs_bmbt_set_startoff(ep, del_endoff);
4874                 temp = got.br_blockcount - del->br_blockcount;
4875                 xfs_bmbt_set_blockcount(ep, temp);
4876                 if (delay) {
4877                         temp = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
4878                                 da_old);
4879                         xfs_bmbt_set_startblock(ep, nullstartblock((int)temp));
4880                         trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
4881                         da_new = temp;
4882                         break;
4883                 }
4884                 xfs_bmbt_set_startblock(ep, del_endblock);
4885                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
4886                 if (!cur) {
4887                         flags |= xfs_ilog_fext(whichfork);
4888                         break;
4889                 }
4890                 if ((error = xfs_bmbt_update(cur, del_endoff, del_endblock,
4891                                 got.br_blockcount - del->br_blockcount,
4892                                 got.br_state)))
4893                         goto done;
4894                 break;
4895
4896         case 1:
4897                 /*
4898                  * Deleting the last part of the extent.
4899                  */
4900                 temp = got.br_blockcount - del->br_blockcount;
4901                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
4902                 xfs_bmbt_set_blockcount(ep, temp);
4903                 if (delay) {
4904                         temp = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
4905                                 da_old);
4906                         xfs_bmbt_set_startblock(ep, nullstartblock((int)temp));
4907                         trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
4908                         da_new = temp;
4909                         break;
4910                 }
4911                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
4912                 if (!cur) {
4913                         flags |= xfs_ilog_fext(whichfork);
4914                         break;
4915                 }
4916                 if ((error = xfs_bmbt_update(cur, got.br_startoff,
4917                                 got.br_startblock,
4918                                 got.br_blockcount - del->br_blockcount,
4919                                 got.br_state)))
4920                         goto done;
4921                 break;
4922
4923         case 0:
4924                 /*
4925                  * Deleting the middle of the extent.
4926                  */
4927                 temp = del->br_startoff - got.br_startoff;
4928                 trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
4929                 xfs_bmbt_set_blockcount(ep, temp);
4930                 new.br_startoff = del_endoff;
4931                 temp2 = got_endoff - del_endoff;
4932                 new.br_blockcount = temp2;
4933                 new.br_state = got.br_state;
4934                 if (!delay) {
4935                         new.br_startblock = del_endblock;
4936                         flags |= XFS_ILOG_CORE;
4937                         if (cur) {
4938                                 if ((error = xfs_bmbt_update(cur,
4939                                                 got.br_startoff,
4940                                                 got.br_startblock, temp,
4941                                                 got.br_state)))
4942                                         goto done;
4943                                 if ((error = xfs_btree_increment(cur, 0, &i)))
4944                                         goto done;
4945                                 cur->bc_rec.b = new;
4946                                 error = xfs_btree_insert(cur, &i);
4947                                 if (error && error != -ENOSPC)
4948                                         goto done;
4949                                 /*
4950                                  * If get no-space back from btree insert,
4951                                  * it tried a split, and we have a zero
4952                                  * block reservation.
4953                                  * Fix up our state and return the error.
4954                                  */
4955                                 if (error == -ENOSPC) {
4956                                         /*
4957                                          * Reset the cursor, don't trust
4958                                          * it after any insert operation.
4959                                          */
4960                                         if ((error = xfs_bmbt_lookup_eq(cur,
4961                                                         got.br_startoff,
4962                                                         got.br_startblock,
4963                                                         temp, &i)))
4964                                                 goto done;
4965                                         XFS_WANT_CORRUPTED_GOTO(mp,
4966                                                                 i == 1, done);
4967                                         /*
4968                                          * Update the btree record back
4969                                          * to the original value.
4970                                          */
4971                                         if ((error = xfs_bmbt_update(cur,
4972                                                         got.br_startoff,
4973                                                         got.br_startblock,
4974                                                         got.br_blockcount,
4975                                                         got.br_state)))
4976                                                 goto done;
4977                                         /*
4978                                          * Reset the extent record back
4979                                          * to the original value.
4980                                          */
4981                                         xfs_bmbt_set_blockcount(ep,
4982                                                 got.br_blockcount);
4983                                         flags = 0;
4984                                         error = -ENOSPC;
4985                                         goto done;
4986                                 }
4987                                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, done);
4988                         } else
4989                                 flags |= xfs_ilog_fext(whichfork);
4990                         XFS_IFORK_NEXT_SET(ip, whichfork,
4991                                 XFS_IFORK_NEXTENTS(ip, whichfork) + 1);
4992                 } else {
4993                         xfs_filblks_t   stolen;
4994                         ASSERT(whichfork == XFS_DATA_FORK);
4995
4996                         /*
4997                          * Distribute the original indlen reservation across the
4998                          * two new extents. Steal blocks from the deleted extent
4999                          * if necessary. Stealing blocks simply fudges the
5000                          * fdblocks accounting in xfs_bunmapi().
5001                          */
5002                         temp = xfs_bmap_worst_indlen(ip, got.br_blockcount);
5003                         temp2 = xfs_bmap_worst_indlen(ip, new.br_blockcount);
5004                         stolen = xfs_bmap_split_indlen(da_old, &temp, &temp2,
5005                                                        del->br_blockcount);
5006                         da_new = temp + temp2 - stolen;
5007                         del->br_blockcount -= stolen;
5008
5009                         /*
5010                          * Set the reservation for each extent. Warn if either
5011                          * is zero as this can lead to delalloc problems.
5012                          */
5013                         WARN_ON_ONCE(!temp || !temp2);
5014                         xfs_bmbt_set_startblock(ep, nullstartblock((int)temp));
5015                         new.br_startblock = nullstartblock((int)temp2);
5016                 }
5017                 trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
5018                 xfs_iext_insert(ip, *idx + 1, 1, &new, state);
5019                 ++*idx;
5020                 break;
5021         }
5022         /*
5023          * If we need to, add to list of extents to delete.
5024          */
5025         if (do_fx)
5026                 xfs_bmap_add_free(mp, flist, del->br_startblock,
5027                         del->br_blockcount);
5028         /*
5029          * Adjust inode # blocks in the file.
5030          */
5031         if (nblks)
5032                 ip->i_d.di_nblocks -= nblks;
5033         /*
5034          * Adjust quota data.
5035          */
5036         if (qfield)
5037                 xfs_trans_mod_dquot_byino(tp, ip, qfield, (long)-nblks);
5038
5039         /*
5040          * Account for change in delayed indirect blocks.
5041          * Nothing to do for disk quota accounting here.
5042          */
5043         ASSERT(da_old >= da_new);
5044         if (da_old > da_new)
5045                 xfs_mod_fdblocks(mp, (int64_t)(da_old - da_new), false);
5046 done:
5047         *logflagsp = flags;
5048         return error;
5049 }
5050
5051 /*
5052  * Unmap (remove) blocks from a file.
5053  * If nexts is nonzero then the number of extents to remove is limited to
5054  * that value.  If not all extents in the block range can be removed then
5055  * *done is set.
5056  */
5057 int                                             /* error */
5058 xfs_bunmapi(
5059         xfs_trans_t             *tp,            /* transaction pointer */
5060         struct xfs_inode        *ip,            /* incore inode */
5061         xfs_fileoff_t           bno,            /* starting offset to unmap */
5062         xfs_filblks_t           len,            /* length to unmap in file */
5063         int                     flags,          /* misc flags */
5064         xfs_extnum_t            nexts,          /* number of extents max */
5065         xfs_fsblock_t           *firstblock,    /* first allocated block
5066                                                    controls a.g. for allocs */
5067         xfs_bmap_free_t         *flist,         /* i/o: list extents to free */
5068         int                     *done)          /* set if not done yet */
5069 {
5070         xfs_btree_cur_t         *cur;           /* bmap btree cursor */
5071         xfs_bmbt_irec_t         del;            /* extent being deleted */
5072         int                     eof;            /* is deleting at eof */
5073         xfs_bmbt_rec_host_t     *ep;            /* extent record pointer */
5074         int                     error;          /* error return value */
5075         xfs_extnum_t            extno;          /* extent number in list */
5076         xfs_bmbt_irec_t         got;            /* current extent record */
5077         xfs_ifork_t             *ifp;           /* inode fork pointer */
5078         int                     isrt;           /* freeing in rt area */
5079         xfs_extnum_t            lastx;          /* last extent index used */
5080         int                     logflags;       /* transaction logging flags */
5081         xfs_extlen_t            mod;            /* rt extent offset */
5082         xfs_mount_t             *mp;            /* mount structure */
5083         xfs_extnum_t            nextents;       /* number of file extents */
5084         xfs_bmbt_irec_t         prev;           /* previous extent record */
5085         xfs_fileoff_t           start;          /* first file offset deleted */
5086         int                     tmp_logflags;   /* partial logging flags */
5087         int                     wasdel;         /* was a delayed alloc extent */
5088         int                     whichfork;      /* data or attribute fork */
5089         xfs_fsblock_t           sum;
5090
5091         trace_xfs_bunmap(ip, bno, len, flags, _RET_IP_);
5092
5093         whichfork = (flags & XFS_BMAPI_ATTRFORK) ?
5094                 XFS_ATTR_FORK : XFS_DATA_FORK;
5095         ifp = XFS_IFORK_PTR(ip, whichfork);
5096         if (unlikely(
5097             XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
5098             XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE)) {
5099                 XFS_ERROR_REPORT("xfs_bunmapi", XFS_ERRLEVEL_LOW,
5100                                  ip->i_mount);
5101                 return -EFSCORRUPTED;
5102         }
5103         mp = ip->i_mount;
5104         if (XFS_FORCED_SHUTDOWN(mp))
5105                 return -EIO;
5106
5107         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
5108         ASSERT(len > 0);
5109         ASSERT(nexts >= 0);
5110
5111         if (!(ifp->if_flags & XFS_IFEXTENTS) &&
5112             (error = xfs_iread_extents(tp, ip, whichfork)))
5113                 return error;
5114         nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
5115         if (nextents == 0) {
5116                 *done = 1;
5117                 return 0;
5118         }
5119         XFS_STATS_INC(mp, xs_blk_unmap);
5120         isrt = (whichfork == XFS_DATA_FORK) && XFS_IS_REALTIME_INODE(ip);
5121         start = bno;
5122         bno = start + len - 1;
5123         ep = xfs_bmap_search_extents(ip, bno, whichfork, &eof, &lastx, &got,
5124                 &prev);
5125
5126         /*
5127          * Check to see if the given block number is past the end of the
5128          * file, back up to the last block if so...
5129          */
5130         if (eof) {
5131                 ep = xfs_iext_get_ext(ifp, --lastx);
5132                 xfs_bmbt_get_all(ep, &got);
5133                 bno = got.br_startoff + got.br_blockcount - 1;
5134         }
5135         logflags = 0;
5136         if (ifp->if_flags & XFS_IFBROOT) {
5137                 ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE);
5138                 cur = xfs_bmbt_init_cursor(mp, tp, ip, whichfork);
5139                 cur->bc_private.b.firstblock = *firstblock;
5140                 cur->bc_private.b.flist = flist;
5141                 cur->bc_private.b.flags = 0;
5142         } else
5143                 cur = NULL;
5144
5145         if (isrt) {
5146                 /*
5147                  * Synchronize by locking the bitmap inode.
5148                  */
5149                 xfs_ilock(mp->m_rbmip, XFS_ILOCK_EXCL|XFS_ILOCK_RTBITMAP);
5150                 xfs_trans_ijoin(tp, mp->m_rbmip, XFS_ILOCK_EXCL);
5151                 xfs_ilock(mp->m_rsumip, XFS_ILOCK_EXCL|XFS_ILOCK_RTSUM);
5152                 xfs_trans_ijoin(tp, mp->m_rsumip, XFS_ILOCK_EXCL);
5153         }
5154
5155         extno = 0;
5156         while (bno != (xfs_fileoff_t)-1 && bno >= start && lastx >= 0 &&
5157                (nexts == 0 || extno < nexts)) {
5158                 /*
5159                  * Is the found extent after a hole in which bno lives?
5160                  * Just back up to the previous extent, if so.
5161                  */
5162                 if (got.br_startoff > bno) {
5163                         if (--lastx < 0)
5164                                 break;
5165                         ep = xfs_iext_get_ext(ifp, lastx);
5166                         xfs_bmbt_get_all(ep, &got);
5167                 }
5168                 /*
5169                  * Is the last block of this extent before the range
5170                  * we're supposed to delete?  If so, we're done.
5171                  */
5172                 bno = XFS_FILEOFF_MIN(bno,
5173                         got.br_startoff + got.br_blockcount - 1);
5174                 if (bno < start)
5175                         break;
5176                 /*
5177                  * Then deal with the (possibly delayed) allocated space
5178                  * we found.
5179                  */
5180                 ASSERT(ep != NULL);
5181                 del = got;
5182                 wasdel = isnullstartblock(del.br_startblock);
5183                 if (got.br_startoff < start) {
5184                         del.br_startoff = start;
5185                         del.br_blockcount -= start - got.br_startoff;
5186                         if (!wasdel)
5187                                 del.br_startblock += start - got.br_startoff;
5188                 }
5189                 if (del.br_startoff + del.br_blockcount > bno + 1)
5190                         del.br_blockcount = bno + 1 - del.br_startoff;
5191                 sum = del.br_startblock + del.br_blockcount;
5192                 if (isrt &&
5193                     (mod = do_mod(sum, mp->m_sb.sb_rextsize))) {
5194                         /*
5195                          * Realtime extent not lined up at the end.
5196                          * The extent could have been split into written
5197                          * and unwritten pieces, or we could just be
5198                          * unmapping part of it.  But we can't really
5199                          * get rid of part of a realtime extent.
5200                          */
5201                         if (del.br_state == XFS_EXT_UNWRITTEN ||
5202                             !xfs_sb_version_hasextflgbit(&mp->m_sb)) {
5203                                 /*
5204                                  * This piece is unwritten, or we're not
5205                                  * using unwritten extents.  Skip over it.
5206                                  */
5207                                 ASSERT(bno >= mod);
5208                                 bno -= mod > del.br_blockcount ?
5209                                         del.br_blockcount : mod;
5210                                 if (bno < got.br_startoff) {
5211                                         if (--lastx >= 0)
5212                                                 xfs_bmbt_get_all(xfs_iext_get_ext(
5213                                                         ifp, lastx), &got);
5214                                 }
5215                                 continue;
5216                         }
5217                         /*
5218                          * It's written, turn it unwritten.
5219                          * This is better than zeroing it.
5220                          */
5221                         ASSERT(del.br_state == XFS_EXT_NORM);
5222                         ASSERT(tp->t_blk_res > 0);
5223                         /*
5224                          * If this spans a realtime extent boundary,
5225                          * chop it back to the start of the one we end at.
5226                          */
5227                         if (del.br_blockcount > mod) {
5228                                 del.br_startoff += del.br_blockcount - mod;
5229                                 del.br_startblock += del.br_blockcount - mod;
5230                                 del.br_blockcount = mod;
5231                         }
5232                         del.br_state = XFS_EXT_UNWRITTEN;
5233                         error = xfs_bmap_add_extent_unwritten_real(tp, ip,
5234                                         &lastx, &cur, &del, firstblock, flist,
5235                                         &logflags);
5236                         if (error)
5237                                 goto error0;
5238                         goto nodelete;
5239                 }
5240                 if (isrt && (mod = do_mod(del.br_startblock, mp->m_sb.sb_rextsize))) {
5241                         /*
5242                          * Realtime extent is lined up at the end but not
5243                          * at the front.  We'll get rid of full extents if
5244                          * we can.
5245                          */
5246                         mod = mp->m_sb.sb_rextsize - mod;
5247                         if (del.br_blockcount > mod) {
5248                                 del.br_blockcount -= mod;
5249                                 del.br_startoff += mod;
5250                                 del.br_startblock += mod;
5251                         } else if ((del.br_startoff == start &&
5252                                     (del.br_state == XFS_EXT_UNWRITTEN ||
5253                                      tp->t_blk_res == 0)) ||
5254                                    !xfs_sb_version_hasextflgbit(&mp->m_sb)) {
5255                                 /*
5256                                  * Can't make it unwritten.  There isn't
5257                                  * a full extent here so just skip it.
5258                                  */
5259                                 ASSERT(bno >= del.br_blockcount);
5260                                 bno -= del.br_blockcount;
5261                                 if (got.br_startoff > bno) {
5262                                         if (--lastx >= 0) {
5263                                                 ep = xfs_iext_get_ext(ifp,
5264                                                                       lastx);
5265                                                 xfs_bmbt_get_all(ep, &got);
5266                                         }
5267                                 }
5268                                 continue;
5269                         } else if (del.br_state == XFS_EXT_UNWRITTEN) {
5270                                 /*
5271                                  * This one is already unwritten.
5272                                  * It must have a written left neighbor.
5273                                  * Unwrite the killed part of that one and
5274                                  * try again.
5275                                  */
5276                                 ASSERT(lastx > 0);
5277                                 xfs_bmbt_get_all(xfs_iext_get_ext(ifp,
5278                                                 lastx - 1), &prev);
5279                                 ASSERT(prev.br_state == XFS_EXT_NORM);
5280                                 ASSERT(!isnullstartblock(prev.br_startblock));
5281                                 ASSERT(del.br_startblock ==
5282                                        prev.br_startblock + prev.br_blockcount);
5283                                 if (prev.br_startoff < start) {
5284                                         mod = start - prev.br_startoff;
5285                                         prev.br_blockcount -= mod;
5286                                         prev.br_startblock += mod;
5287                                         prev.br_startoff = start;
5288                                 }
5289                                 prev.br_state = XFS_EXT_UNWRITTEN;
5290                                 lastx--;
5291                                 error = xfs_bmap_add_extent_unwritten_real(tp,
5292                                                 ip, &lastx, &cur, &prev,
5293                                                 firstblock, flist, &logflags);
5294                                 if (error)
5295                                         goto error0;
5296                                 goto nodelete;
5297                         } else {
5298                                 ASSERT(del.br_state == XFS_EXT_NORM);
5299                                 del.br_state = XFS_EXT_UNWRITTEN;
5300                                 error = xfs_bmap_add_extent_unwritten_real(tp,
5301                                                 ip, &lastx, &cur, &del,
5302                                                 firstblock, flist, &logflags);
5303                                 if (error)
5304                                         goto error0;
5305                                 goto nodelete;
5306                         }
5307                 }
5308
5309                 /*
5310                  * If it's the case where the directory code is running
5311                  * with no block reservation, and the deleted block is in
5312                  * the middle of its extent, and the resulting insert
5313                  * of an extent would cause transformation to btree format,
5314                  * then reject it.  The calling code will then swap
5315                  * blocks around instead.
5316                  * We have to do this now, rather than waiting for the
5317                  * conversion to btree format, since the transaction
5318                  * will be dirty.
5319                  */
5320                 if (!wasdel && tp->t_blk_res == 0 &&
5321                     XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS &&
5322                     XFS_IFORK_NEXTENTS(ip, whichfork) >= /* Note the >= */
5323                         XFS_IFORK_MAXEXT(ip, whichfork) &&
5324                     del.br_startoff > got.br_startoff &&
5325                     del.br_startoff + del.br_blockcount <
5326                     got.br_startoff + got.br_blockcount) {
5327                         error = -ENOSPC;
5328                         goto error0;
5329                 }
5330
5331                 /*
5332                  * Unreserve quota and update realtime free space, if
5333                  * appropriate. If delayed allocation, update the inode delalloc
5334                  * counter now and wait to update the sb counters as
5335                  * xfs_bmap_del_extent() might need to borrow some blocks.
5336                  */
5337                 if (wasdel) {
5338                         ASSERT(startblockval(del.br_startblock) > 0);
5339                         if (isrt) {
5340                                 xfs_filblks_t rtexts;
5341
5342                                 rtexts = XFS_FSB_TO_B(mp, del.br_blockcount);
5343                                 do_div(rtexts, mp->m_sb.sb_rextsize);
5344                                 xfs_mod_frextents(mp, (int64_t)rtexts);
5345                                 (void)xfs_trans_reserve_quota_nblks(NULL,
5346                                         ip, -((long)del.br_blockcount), 0,
5347                                         XFS_QMOPT_RES_RTBLKS);
5348                         } else {
5349                                 (void)xfs_trans_reserve_quota_nblks(NULL,
5350                                         ip, -((long)del.br_blockcount), 0,
5351                                         XFS_QMOPT_RES_REGBLKS);
5352                         }
5353                         ip->i_delayed_blks -= del.br_blockcount;
5354                         if (cur)
5355                                 cur->bc_private.b.flags |=
5356                                         XFS_BTCUR_BPRV_WASDEL;
5357                 } else if (cur)
5358                         cur->bc_private.b.flags &= ~XFS_BTCUR_BPRV_WASDEL;
5359
5360                 error = xfs_bmap_del_extent(ip, tp, &lastx, flist, cur, &del,
5361                                 &tmp_logflags, whichfork);
5362                 logflags |= tmp_logflags;
5363                 if (error)
5364                         goto error0;
5365
5366                 if (!isrt && wasdel)
5367                         xfs_mod_fdblocks(mp, (int64_t)del.br_blockcount, false);
5368
5369                 bno = del.br_startoff - 1;
5370 nodelete:
5371                 /*
5372                  * If not done go on to the next (previous) record.
5373                  */
5374                 if (bno != (xfs_fileoff_t)-1 && bno >= start) {
5375                         if (lastx >= 0) {
5376                                 ep = xfs_iext_get_ext(ifp, lastx);
5377                                 if (xfs_bmbt_get_startoff(ep) > bno) {
5378                                         if (--lastx >= 0)
5379                                                 ep = xfs_iext_get_ext(ifp,
5380                                                                       lastx);
5381                                 }
5382                                 xfs_bmbt_get_all(ep, &got);
5383                         }
5384                         extno++;
5385                 }
5386         }
5387         *done = bno == (xfs_fileoff_t)-1 || bno < start || lastx < 0;
5388
5389         /*
5390          * Convert to a btree if necessary.
5391          */
5392         if (xfs_bmap_needs_btree(ip, whichfork)) {
5393                 ASSERT(cur == NULL);
5394                 error = xfs_bmap_extents_to_btree(tp, ip, firstblock, flist,
5395                         &cur, 0, &tmp_logflags, whichfork);
5396                 logflags |= tmp_logflags;
5397                 if (error)
5398                         goto error0;
5399         }
5400         /*
5401          * transform from btree to extents, give it cur
5402          */
5403         else if (xfs_bmap_wants_extents(ip, whichfork)) {
5404                 ASSERT(cur != NULL);
5405                 error = xfs_bmap_btree_to_extents(tp, ip, cur, &tmp_logflags,
5406                         whichfork);
5407                 logflags |= tmp_logflags;
5408                 if (error)
5409                         goto error0;
5410         }
5411         /*
5412          * transform from extents to local?
5413          */
5414         error = 0;
5415 error0:
5416         /*
5417          * Log everything.  Do this after conversion, there's no point in
5418          * logging the extent records if we've converted to btree format.
5419          */
5420         if ((logflags & xfs_ilog_fext(whichfork)) &&
5421             XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
5422                 logflags &= ~xfs_ilog_fext(whichfork);
5423         else if ((logflags & xfs_ilog_fbroot(whichfork)) &&
5424                  XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE)
5425                 logflags &= ~xfs_ilog_fbroot(whichfork);
5426         /*
5427          * Log inode even in the error case, if the transaction
5428          * is dirty we'll need to shut down the filesystem.
5429          */
5430         if (logflags)
5431                 xfs_trans_log_inode(tp, ip, logflags);
5432         if (cur) {
5433                 if (!error) {
5434                         *firstblock = cur->bc_private.b.firstblock;
5435                         cur->bc_private.b.allocated = 0;
5436                 }
5437                 xfs_btree_del_cursor(cur,
5438                         error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
5439         }
5440         return error;
5441 }
5442
5443 /*
5444  * Determine whether an extent shift can be accomplished by a merge with the
5445  * extent that precedes the target hole of the shift.
5446  */
5447 STATIC bool
5448 xfs_bmse_can_merge(
5449         struct xfs_bmbt_irec    *left,  /* preceding extent */
5450         struct xfs_bmbt_irec    *got,   /* current extent to shift */
5451         xfs_fileoff_t           shift)  /* shift fsb */
5452 {
5453         xfs_fileoff_t           startoff;
5454
5455         startoff = got->br_startoff - shift;
5456
5457         /*
5458          * The extent, once shifted, must be adjacent in-file and on-disk with
5459          * the preceding extent.
5460          */
5461         if ((left->br_startoff + left->br_blockcount != startoff) ||
5462             (left->br_startblock + left->br_blockcount != got->br_startblock) ||
5463             (left->br_state != got->br_state) ||
5464             (left->br_blockcount + got->br_blockcount > MAXEXTLEN))
5465                 return false;
5466
5467         return true;
5468 }
5469
5470 /*
5471  * A bmap extent shift adjusts the file offset of an extent to fill a preceding
5472  * hole in the file. If an extent shift would result in the extent being fully
5473  * adjacent to the extent that currently precedes the hole, we can merge with
5474  * the preceding extent rather than do the shift.
5475  *
5476  * This function assumes the caller has verified a shift-by-merge is possible
5477  * with the provided extents via xfs_bmse_can_merge().
5478  */
5479 STATIC int
5480 xfs_bmse_merge(
5481         struct xfs_inode                *ip,
5482         int                             whichfork,
5483         xfs_fileoff_t                   shift,          /* shift fsb */
5484         int                             current_ext,    /* idx of gotp */
5485         struct xfs_bmbt_rec_host        *gotp,          /* extent to shift */
5486         struct xfs_bmbt_rec_host        *leftp,         /* preceding extent */
5487         struct xfs_btree_cur            *cur,
5488         int                             *logflags)      /* output */
5489 {
5490         struct xfs_bmbt_irec            got;
5491         struct xfs_bmbt_irec            left;
5492         xfs_filblks_t                   blockcount;
5493         int                             error, i;
5494         struct xfs_mount                *mp = ip->i_mount;
5495
5496         xfs_bmbt_get_all(gotp, &got);
5497         xfs_bmbt_get_all(leftp, &left);
5498         blockcount = left.br_blockcount + got.br_blockcount;
5499
5500         ASSERT(xfs_isilocked(ip, XFS_IOLOCK_EXCL));
5501         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
5502         ASSERT(xfs_bmse_can_merge(&left, &got, shift));
5503
5504         /*
5505          * Merge the in-core extents. Note that the host record pointers and
5506          * current_ext index are invalid once the extent has been removed via
5507          * xfs_iext_remove().
5508          */
5509         xfs_bmbt_set_blockcount(leftp, blockcount);
5510         xfs_iext_remove(ip, current_ext, 1, 0);
5511
5512         /*
5513          * Update the on-disk extent count, the btree if necessary and log the
5514          * inode.
5515          */
5516         XFS_IFORK_NEXT_SET(ip, whichfork,
5517                            XFS_IFORK_NEXTENTS(ip, whichfork) - 1);
5518         *logflags |= XFS_ILOG_CORE;
5519         if (!cur) {
5520                 *logflags |= XFS_ILOG_DEXT;
5521                 return 0;
5522         }
5523
5524         /* lookup and remove the extent to merge */
5525         error = xfs_bmbt_lookup_eq(cur, got.br_startoff, got.br_startblock,
5526                                    got.br_blockcount, &i);
5527         if (error)
5528                 return error;
5529         XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
5530
5531         error = xfs_btree_delete(cur, &i);
5532         if (error)
5533                 return error;
5534         XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
5535
5536         /* lookup and update size of the previous extent */
5537         error = xfs_bmbt_lookup_eq(cur, left.br_startoff, left.br_startblock,
5538                                    left.br_blockcount, &i);
5539         if (error)
5540                 return error;
5541         XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
5542
5543         left.br_blockcount = blockcount;
5544
5545         return xfs_bmbt_update(cur, left.br_startoff, left.br_startblock,
5546                                left.br_blockcount, left.br_state);
5547 }
5548
5549 /*
5550  * Shift a single extent.
5551  */
5552 STATIC int
5553 xfs_bmse_shift_one(
5554         struct xfs_inode                *ip,
5555         int                             whichfork,
5556         xfs_fileoff_t                   offset_shift_fsb,
5557         int                             *current_ext,
5558         struct xfs_bmbt_rec_host        *gotp,
5559         struct xfs_btree_cur            *cur,
5560         int                             *logflags,
5561         enum shift_direction            direction)
5562 {
5563         struct xfs_ifork                *ifp;
5564         struct xfs_mount                *mp;
5565         xfs_fileoff_t                   startoff;
5566         struct xfs_bmbt_rec_host        *adj_irecp;
5567         struct xfs_bmbt_irec            got;
5568         struct xfs_bmbt_irec            adj_irec;
5569         int                             error;
5570         int                             i;
5571         int                             total_extents;
5572
5573         mp = ip->i_mount;
5574         ifp = XFS_IFORK_PTR(ip, whichfork);
5575         total_extents = ifp->if_bytes / sizeof(xfs_bmbt_rec_t);
5576
5577         xfs_bmbt_get_all(gotp, &got);
5578
5579         /* delalloc extents should be prevented by caller */
5580         XFS_WANT_CORRUPTED_RETURN(mp, !isnullstartblock(got.br_startblock));
5581
5582         if (direction == SHIFT_LEFT) {
5583                 startoff = got.br_startoff - offset_shift_fsb;
5584
5585                 /*
5586                  * Check for merge if we've got an extent to the left,
5587                  * otherwise make sure there's enough room at the start
5588                  * of the file for the shift.
5589                  */
5590                 if (!*current_ext) {
5591                         if (got.br_startoff < offset_shift_fsb)
5592                                 return -EINVAL;
5593                         goto update_current_ext;
5594                 }
5595                 /*
5596                  * grab the left extent and check for a large
5597                  * enough hole.
5598                  */
5599                 adj_irecp = xfs_iext_get_ext(ifp, *current_ext - 1);
5600                 xfs_bmbt_get_all(adj_irecp, &adj_irec);
5601
5602                 if (startoff <
5603                     adj_irec.br_startoff + adj_irec.br_blockcount)
5604                         return -EINVAL;
5605
5606                 /* check whether to merge the extent or shift it down */
5607                 if (xfs_bmse_can_merge(&adj_irec, &got,
5608                                        offset_shift_fsb)) {
5609                         return xfs_bmse_merge(ip, whichfork, offset_shift_fsb,
5610                                               *current_ext, gotp, adj_irecp,
5611                                               cur, logflags);
5612                 }
5613         } else {
5614                 startoff = got.br_startoff + offset_shift_fsb;
5615                 /* nothing to move if this is the last extent */
5616                 if (*current_ext >= (total_extents - 1))
5617                         goto update_current_ext;
5618                 /*
5619                  * If this is not the last extent in the file, make sure there
5620                  * is enough room between current extent and next extent for
5621                  * accommodating the shift.
5622                  */
5623                 adj_irecp = xfs_iext_get_ext(ifp, *current_ext + 1);
5624                 xfs_bmbt_get_all(adj_irecp, &adj_irec);
5625                 if (startoff + got.br_blockcount > adj_irec.br_startoff)
5626                         return -EINVAL;
5627                 /*
5628                  * Unlike a left shift (which involves a hole punch),
5629                  * a right shift does not modify extent neighbors
5630                  * in any way. We should never find mergeable extents
5631                  * in this scenario. Check anyways and warn if we
5632                  * encounter two extents that could be one.
5633                  */
5634                 if (xfs_bmse_can_merge(&got, &adj_irec, offset_shift_fsb))
5635                         WARN_ON_ONCE(1);
5636         }
5637         /*
5638          * Increment the extent index for the next iteration, update the start
5639          * offset of the in-core extent and update the btree if applicable.
5640          */
5641 update_current_ext:
5642         if (direction == SHIFT_LEFT)
5643                 (*current_ext)++;
5644         else
5645                 (*current_ext)--;
5646         xfs_bmbt_set_startoff(gotp, startoff);
5647         *logflags |= XFS_ILOG_CORE;
5648         if (!cur) {
5649                 *logflags |= XFS_ILOG_DEXT;
5650                 return 0;
5651         }
5652
5653         error = xfs_bmbt_lookup_eq(cur, got.br_startoff, got.br_startblock,
5654                                    got.br_blockcount, &i);
5655         if (error)
5656                 return error;
5657         XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
5658
5659         got.br_startoff = startoff;
5660         return xfs_bmbt_update(cur, got.br_startoff, got.br_startblock,
5661                                got.br_blockcount, got.br_state);
5662 }
5663
5664 /*
5665  * Shift extent records to the left/right to cover/create a hole.
5666  *
5667  * The maximum number of extents to be shifted in a single operation is
5668  * @num_exts. @stop_fsb specifies the file offset at which to stop shift and the
5669  * file offset where we've left off is returned in @next_fsb. @offset_shift_fsb
5670  * is the length by which each extent is shifted. If there is no hole to shift
5671  * the extents into, this will be considered invalid operation and we abort
5672  * immediately.
5673  */
5674 int
5675 xfs_bmap_shift_extents(
5676         struct xfs_trans        *tp,
5677         struct xfs_inode        *ip,
5678         xfs_fileoff_t           *next_fsb,
5679         xfs_fileoff_t           offset_shift_fsb,
5680         int                     *done,
5681         xfs_fileoff_t           stop_fsb,
5682         xfs_fsblock_t           *firstblock,
5683         struct xfs_bmap_free    *flist,
5684         enum shift_direction    direction,
5685         int                     num_exts)
5686 {
5687         struct xfs_btree_cur            *cur = NULL;
5688         struct xfs_bmbt_rec_host        *gotp;
5689         struct xfs_bmbt_irec            got;
5690         struct xfs_mount                *mp = ip->i_mount;
5691         struct xfs_ifork                *ifp;
5692         xfs_extnum_t                    nexts = 0;
5693         xfs_extnum_t                    current_ext;
5694         xfs_extnum_t                    total_extents;
5695         xfs_extnum_t                    stop_extent;
5696         int                             error = 0;
5697         int                             whichfork = XFS_DATA_FORK;
5698         int                             logflags = 0;
5699
5700         if (unlikely(XFS_TEST_ERROR(
5701             (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
5702              XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE),
5703              mp, XFS_ERRTAG_BMAPIFORMAT, XFS_RANDOM_BMAPIFORMAT))) {
5704                 XFS_ERROR_REPORT("xfs_bmap_shift_extents",
5705                                  XFS_ERRLEVEL_LOW, mp);
5706                 return -EFSCORRUPTED;
5707         }
5708
5709         if (XFS_FORCED_SHUTDOWN(mp))
5710                 return -EIO;
5711
5712         ASSERT(xfs_isilocked(ip, XFS_IOLOCK_EXCL));
5713         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
5714         ASSERT(direction == SHIFT_LEFT || direction == SHIFT_RIGHT);
5715         ASSERT(*next_fsb != NULLFSBLOCK || direction == SHIFT_RIGHT);
5716
5717         ifp = XFS_IFORK_PTR(ip, whichfork);
5718         if (!(ifp->if_flags & XFS_IFEXTENTS)) {
5719                 /* Read in all the extents */
5720                 error = xfs_iread_extents(tp, ip, whichfork);
5721                 if (error)
5722                         return error;
5723         }
5724
5725         if (ifp->if_flags & XFS_IFBROOT) {
5726                 cur = xfs_bmbt_init_cursor(mp, tp, ip, whichfork);
5727                 cur->bc_private.b.firstblock = *firstblock;
5728                 cur->bc_private.b.flist = flist;
5729                 cur->bc_private.b.flags = 0;
5730         }
5731
5732         /*
5733          * There may be delalloc extents in the data fork before the range we
5734          * are collapsing out, so we cannot use the count of real extents here.
5735          * Instead we have to calculate it from the incore fork.
5736          */
5737         total_extents = ifp->if_bytes / sizeof(xfs_bmbt_rec_t);
5738         if (total_extents == 0) {
5739                 *done = 1;
5740                 goto del_cursor;
5741         }
5742
5743         /*
5744          * In case of first right shift, we need to initialize next_fsb
5745          */
5746         if (*next_fsb == NULLFSBLOCK) {
5747                 gotp = xfs_iext_get_ext(ifp, total_extents - 1);
5748                 xfs_bmbt_get_all(gotp, &got);
5749                 *next_fsb = got.br_startoff;
5750                 if (stop_fsb > *next_fsb) {
5751                         *done = 1;
5752                         goto del_cursor;
5753                 }
5754         }
5755
5756         /* Lookup the extent index at which we have to stop */
5757         if (direction == SHIFT_RIGHT) {
5758                 gotp = xfs_iext_bno_to_ext(ifp, stop_fsb, &stop_extent);
5759                 /* Make stop_extent exclusive of shift range */
5760                 stop_extent--;
5761         } else
5762                 stop_extent = total_extents;
5763
5764         /*
5765          * Look up the extent index for the fsb where we start shifting. We can
5766          * henceforth iterate with current_ext as extent list changes are locked
5767          * out via ilock.
5768          *
5769          * gotp can be null in 2 cases: 1) if there are no extents or 2)
5770          * *next_fsb lies in a hole beyond which there are no extents. Either
5771          * way, we are done.
5772          */
5773         gotp = xfs_iext_bno_to_ext(ifp, *next_fsb, &current_ext);
5774         if (!gotp) {
5775                 *done = 1;
5776                 goto del_cursor;
5777         }
5778
5779         /* some sanity checking before we finally start shifting extents */
5780         if ((direction == SHIFT_LEFT && current_ext >= stop_extent) ||
5781              (direction == SHIFT_RIGHT && current_ext <= stop_extent)) {
5782                 error = -EIO;
5783                 goto del_cursor;
5784         }
5785
5786         while (nexts++ < num_exts) {
5787                 error = xfs_bmse_shift_one(ip, whichfork, offset_shift_fsb,
5788                                            &current_ext, gotp, cur, &logflags,
5789                                            direction);
5790                 if (error)
5791                         goto del_cursor;
5792                 /*
5793                  * If there was an extent merge during the shift, the extent
5794                  * count can change. Update the total and grade the next record.
5795                  */
5796                 if (direction == SHIFT_LEFT) {
5797                         total_extents = ifp->if_bytes / sizeof(xfs_bmbt_rec_t);
5798                         stop_extent = total_extents;
5799                 }
5800
5801                 if (current_ext == stop_extent) {
5802                         *done = 1;
5803                         *next_fsb = NULLFSBLOCK;
5804                         break;
5805                 }
5806                 gotp = xfs_iext_get_ext(ifp, current_ext);
5807         }
5808
5809         if (!*done) {
5810                 xfs_bmbt_get_all(gotp, &got);
5811                 *next_fsb = got.br_startoff;
5812         }
5813
5814 del_cursor:
5815         if (cur)
5816                 xfs_btree_del_cursor(cur,
5817                         error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
5818
5819         if (logflags)
5820                 xfs_trans_log_inode(tp, ip, logflags);
5821
5822         return error;
5823 }
5824
5825 /*
5826  * Splits an extent into two extents at split_fsb block such that it is
5827  * the first block of the current_ext. @current_ext is a target extent
5828  * to be split. @split_fsb is a block where the extents is split.
5829  * If split_fsb lies in a hole or the first block of extents, just return 0.
5830  */
5831 STATIC int
5832 xfs_bmap_split_extent_at(
5833         struct xfs_trans        *tp,
5834         struct xfs_inode        *ip,
5835         xfs_fileoff_t           split_fsb,
5836         xfs_fsblock_t           *firstfsb,
5837         struct xfs_bmap_free    *free_list)
5838 {
5839         int                             whichfork = XFS_DATA_FORK;
5840         struct xfs_btree_cur            *cur = NULL;
5841         struct xfs_bmbt_rec_host        *gotp;
5842         struct xfs_bmbt_irec            got;
5843         struct xfs_bmbt_irec            new; /* split extent */
5844         struct xfs_mount                *mp = ip->i_mount;
5845         struct xfs_ifork                *ifp;
5846         xfs_fsblock_t                   gotblkcnt; /* new block count for got */
5847         xfs_extnum_t                    current_ext;
5848         int                             error = 0;
5849         int                             logflags = 0;
5850         int                             i = 0;
5851
5852         if (unlikely(XFS_TEST_ERROR(
5853             (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
5854              XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE),
5855              mp, XFS_ERRTAG_BMAPIFORMAT, XFS_RANDOM_BMAPIFORMAT))) {
5856                 XFS_ERROR_REPORT("xfs_bmap_split_extent_at",
5857                                  XFS_ERRLEVEL_LOW, mp);
5858                 return -EFSCORRUPTED;
5859         }
5860
5861         if (XFS_FORCED_SHUTDOWN(mp))
5862                 return -EIO;
5863
5864         ifp = XFS_IFORK_PTR(ip, whichfork);
5865         if (!(ifp->if_flags & XFS_IFEXTENTS)) {
5866                 /* Read in all the extents */
5867                 error = xfs_iread_extents(tp, ip, whichfork);
5868                 if (error)
5869                         return error;
5870         }
5871
5872         /*
5873          * gotp can be null in 2 cases: 1) if there are no extents
5874          * or 2) split_fsb lies in a hole beyond which there are
5875          * no extents. Either way, we are done.
5876          */
5877         gotp = xfs_iext_bno_to_ext(ifp, split_fsb, &current_ext);
5878         if (!gotp)
5879                 return 0;
5880
5881         xfs_bmbt_get_all(gotp, &got);
5882
5883         /*
5884          * Check split_fsb lies in a hole or the start boundary offset
5885          * of the extent.
5886          */
5887         if (got.br_startoff >= split_fsb)
5888                 return 0;
5889
5890         gotblkcnt = split_fsb - got.br_startoff;
5891         new.br_startoff = split_fsb;
5892         new.br_startblock = got.br_startblock + gotblkcnt;
5893         new.br_blockcount = got.br_blockcount - gotblkcnt;
5894         new.br_state = got.br_state;
5895
5896         if (ifp->if_flags & XFS_IFBROOT) {
5897                 cur = xfs_bmbt_init_cursor(mp, tp, ip, whichfork);
5898                 cur->bc_private.b.firstblock = *firstfsb;
5899                 cur->bc_private.b.flist = free_list;
5900                 cur->bc_private.b.flags = 0;
5901                 error = xfs_bmbt_lookup_eq(cur, got.br_startoff,
5902                                 got.br_startblock,
5903                                 got.br_blockcount,
5904                                 &i);
5905                 if (error)
5906                         goto del_cursor;
5907                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, del_cursor);
5908         }
5909
5910         xfs_bmbt_set_blockcount(gotp, gotblkcnt);
5911         got.br_blockcount = gotblkcnt;
5912
5913         logflags = XFS_ILOG_CORE;
5914         if (cur) {
5915                 error = xfs_bmbt_update(cur, got.br_startoff,
5916                                 got.br_startblock,
5917                                 got.br_blockcount,
5918                                 got.br_state);
5919                 if (error)
5920                         goto del_cursor;
5921         } else
5922                 logflags |= XFS_ILOG_DEXT;
5923
5924         /* Add new extent */
5925         current_ext++;
5926         xfs_iext_insert(ip, current_ext, 1, &new, 0);
5927         XFS_IFORK_NEXT_SET(ip, whichfork,
5928                            XFS_IFORK_NEXTENTS(ip, whichfork) + 1);
5929
5930         if (cur) {
5931                 error = xfs_bmbt_lookup_eq(cur, new.br_startoff,
5932                                 new.br_startblock, new.br_blockcount,
5933                                 &i);
5934                 if (error)
5935                         goto del_cursor;
5936                 XFS_WANT_CORRUPTED_GOTO(mp, i == 0, del_cursor);
5937                 cur->bc_rec.b.br_state = new.br_state;
5938
5939                 error = xfs_btree_insert(cur, &i);
5940                 if (error)
5941                         goto del_cursor;
5942                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, del_cursor);
5943         }
5944
5945         /*
5946          * Convert to a btree if necessary.
5947          */
5948         if (xfs_bmap_needs_btree(ip, whichfork)) {
5949                 int tmp_logflags; /* partial log flag return val */
5950
5951                 ASSERT(cur == NULL);
5952                 error = xfs_bmap_extents_to_btree(tp, ip, firstfsb, free_list,
5953                                 &cur, 0, &tmp_logflags, whichfork);
5954                 logflags |= tmp_logflags;
5955         }
5956
5957 del_cursor:
5958         if (cur) {
5959                 cur->bc_private.b.allocated = 0;
5960                 xfs_btree_del_cursor(cur,
5961                                 error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
5962         }
5963
5964         if (logflags)
5965                 xfs_trans_log_inode(tp, ip, logflags);
5966         return error;
5967 }
5968
5969 int
5970 xfs_bmap_split_extent(
5971         struct xfs_inode        *ip,
5972         xfs_fileoff_t           split_fsb)
5973 {
5974         struct xfs_mount        *mp = ip->i_mount;
5975         struct xfs_trans        *tp;
5976         struct xfs_bmap_free    free_list;
5977         xfs_fsblock_t           firstfsb;
5978         int                     error;
5979
5980         error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write,
5981                         XFS_DIOSTRAT_SPACE_RES(mp, 0), 0, 0, &tp);
5982         if (error)
5983                 return error;
5984
5985         xfs_ilock(ip, XFS_ILOCK_EXCL);
5986         xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
5987
5988         xfs_bmap_init(&free_list, &firstfsb);
5989
5990         error = xfs_bmap_split_extent_at(tp, ip, split_fsb,
5991                         &firstfsb, &free_list);
5992         if (error)
5993                 goto out;
5994
5995         error = xfs_bmap_finish(&tp, &free_list, NULL);
5996         if (error)
5997                 goto out;
5998
5999         return xfs_trans_commit(tp);
6000
6001 out:
6002         xfs_bmap_cancel(&free_list);
6003         xfs_trans_cancel(tp);
6004         return error;
6005 }