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