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