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