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