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