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