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