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