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