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