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