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