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