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