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