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