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