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