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