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