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_dir.h"
28 #include "xfs_dir2.h"
29 #include "xfs_da_btree.h"
30 #include "xfs_bmap_btree.h"
31 #include "xfs_alloc_btree.h"
32 #include "xfs_ialloc_btree.h"
33 #include "xfs_dir_sf.h"
34 #include "xfs_dir2_sf.h"
35 #include "xfs_attr_sf.h"
36 #include "xfs_dinode.h"
37 #include "xfs_inode.h"
38 #include "xfs_btree.h"
39 #include "xfs_dmapi.h"
40 #include "xfs_mount.h"
41 #include "xfs_ialloc.h"
42 #include "xfs_itable.h"
43 #include "xfs_inode_item.h"
44 #include "xfs_extfree_item.h"
45 #include "xfs_alloc.h"
46 #include "xfs_bmap.h"
47 #include "xfs_rtalloc.h"
48 #include "xfs_error.h"
49 #include "xfs_dir_leaf.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 #if 0
190 /*
191  * Check that the extents list for the inode ip is in the right order.
192  */
193 STATIC void
194 xfs_bmap_check_extents(
195 	xfs_inode_t		*ip,		/* incore inode pointer */
196 	int			whichfork);	/* data or attr fork */
197 #endif
198 #endif
199 
200 /*
201  * Called by xfs_bmapi to update file extent records and the btree
202  * after removing space (or undoing a delayed allocation).
203  */
204 STATIC int				/* error */
205 xfs_bmap_del_extent(
206 	xfs_inode_t		*ip,	/* incore inode pointer */
207 	xfs_trans_t		*tp,	/* current trans pointer */
208 	xfs_extnum_t		idx,	/* extent number to update/insert */
209 	xfs_bmap_free_t		*flist,	/* list of extents to be freed */
210 	xfs_btree_cur_t		*cur,	/* if null, not a btree */
211 	xfs_bmbt_irec_t		*new,	/* new data to add to file extents */
212 	int			*logflagsp,/* inode logging flags */
213 	xfs_extdelta_t		*delta, /* Change made to incore extents */
214 	int			whichfork, /* data or attr fork */
215 	int			rsvd);	 /* OK to allocate reserved blocks */
216 
217 /*
218  * Remove the entry "free" from the free item list.  Prev points to the
219  * previous entry, unless "free" is the head of the list.
220  */
221 STATIC void
222 xfs_bmap_del_free(
223 	xfs_bmap_free_t		*flist,	/* free item list header */
224 	xfs_bmap_free_item_t	*prev,	/* previous item on list, if any */
225 	xfs_bmap_free_item_t	*free);	/* list item to be freed */
226 
227 /*
228  * Convert an extents-format file into a btree-format file.
229  * The new file will have a root block (in the inode) and a single child block.
230  */
231 STATIC int					/* error */
232 xfs_bmap_extents_to_btree(
233 	xfs_trans_t		*tp,		/* transaction pointer */
234 	xfs_inode_t		*ip,		/* incore inode pointer */
235 	xfs_fsblock_t		*firstblock,	/* first-block-allocated */
236 	xfs_bmap_free_t		*flist,		/* blocks freed in xaction */
237 	xfs_btree_cur_t		**curp,		/* cursor returned to caller */
238 	int			wasdel,		/* converting a delayed alloc */
239 	int			*logflagsp,	/* inode logging flags */
240 	int			whichfork);	/* data or attr fork */
241 
242 /*
243  * Convert a local file to an extents file.
244  * This code is sort of bogus, since the file data needs to get
245  * logged so it won't be lost.  The bmap-level manipulations are ok, though.
246  */
247 STATIC int				/* error */
248 xfs_bmap_local_to_extents(
249 	xfs_trans_t	*tp,		/* transaction pointer */
250 	xfs_inode_t	*ip,		/* incore inode pointer */
251 	xfs_fsblock_t	*firstblock,	/* first block allocated in xaction */
252 	xfs_extlen_t	total,		/* total blocks needed by transaction */
253 	int		*logflagsp,	/* inode logging flags */
254 	int		whichfork);	/* data or attr fork */
255 
256 /*
257  * Search the extents list for the inode, for the extent containing bno.
258  * If bno lies in a hole, point to the next entry.  If bno lies past eof,
259  * *eofp will be set, and *prevp will contain the last entry (null if none).
260  * Else, *lastxp will be set to the index of the found
261  * entry; *gotp will contain the entry.
262  */
263 STATIC xfs_bmbt_rec_t *			/* pointer to found extent entry */
264 xfs_bmap_search_extents(
265 	xfs_inode_t	*ip,		/* incore inode pointer */
266 	xfs_fileoff_t	bno,		/* block number searched for */
267 	int		whichfork,	/* data or attr fork */
268 	int		*eofp,		/* out: end of file found */
269 	xfs_extnum_t	*lastxp,	/* out: last extent index */
270 	xfs_bmbt_irec_t	*gotp,		/* out: extent entry found */
271 	xfs_bmbt_irec_t	*prevp);	/* out: previous extent entry found */
272 
273 /*
274  * Check the last inode extent to determine whether this allocation will result
275  * in blocks being allocated at the end of the file. When we allocate new data
276  * blocks at the end of the file which do not start at the previous data block,
277  * we will try to align the new blocks at stripe unit boundaries.
278  */
279 STATIC int				/* error */
280 xfs_bmap_isaeof(
281 	xfs_inode_t	*ip,		/* incore inode pointer */
282 	xfs_fileoff_t   off,		/* file offset in fsblocks */
283 	int             whichfork,	/* data or attribute fork */
284 	char		*aeof);		/* return value */
285 
286 #ifdef XFS_BMAP_TRACE
287 /*
288  * Add a bmap trace buffer entry.  Base routine for the others.
289  */
290 STATIC void
291 xfs_bmap_trace_addentry(
292 	int		opcode,		/* operation */
293 	char		*fname,		/* function name */
294 	char		*desc,		/* operation description */
295 	xfs_inode_t	*ip,		/* incore inode pointer */
296 	xfs_extnum_t	idx,		/* index of entry(ies) */
297 	xfs_extnum_t	cnt,		/* count of entries, 1 or 2 */
298 	xfs_bmbt_rec_t	*r1,		/* first record */
299 	xfs_bmbt_rec_t	*r2,		/* second record or null */
300 	int		whichfork);	/* data or attr fork */
301 
302 /*
303  * Add bmap trace entry prior to a call to xfs_iext_remove.
304  */
305 STATIC void
306 xfs_bmap_trace_delete(
307 	char		*fname,		/* function name */
308 	char		*desc,		/* operation description */
309 	xfs_inode_t	*ip,		/* incore inode pointer */
310 	xfs_extnum_t	idx,		/* index of entry(entries) deleted */
311 	xfs_extnum_t	cnt,		/* count of entries deleted, 1 or 2 */
312 	int		whichfork);	/* data or attr fork */
313 
314 /*
315  * Add bmap trace entry prior to a call to xfs_iext_insert, or
316  * reading in the extents list from the disk (in the btree).
317  */
318 STATIC void
319 xfs_bmap_trace_insert(
320 	char		*fname,		/* function name */
321 	char		*desc,		/* operation description */
322 	xfs_inode_t	*ip,		/* incore inode pointer */
323 	xfs_extnum_t	idx,		/* index of entry(entries) inserted */
324 	xfs_extnum_t	cnt,		/* count of entries inserted, 1 or 2 */
325 	xfs_bmbt_irec_t	*r1,		/* inserted record 1 */
326 	xfs_bmbt_irec_t	*r2,		/* inserted record 2 or null */
327 	int		whichfork);	/* data or attr fork */
328 
329 /*
330  * Add bmap trace entry after updating an extent record in place.
331  */
332 STATIC void
333 xfs_bmap_trace_post_update(
334 	char		*fname,		/* function name */
335 	char		*desc,		/* operation description */
336 	xfs_inode_t	*ip,		/* incore inode pointer */
337 	xfs_extnum_t	idx,		/* index of entry updated */
338 	int		whichfork);	/* data or attr fork */
339 
340 /*
341  * Add bmap trace entry prior to updating an extent record in place.
342  */
343 STATIC void
344 xfs_bmap_trace_pre_update(
345 	char		*fname,		/* function name */
346 	char		*desc,		/* operation description */
347 	xfs_inode_t	*ip,		/* incore inode pointer */
348 	xfs_extnum_t	idx,		/* index of entry to be updated */
349 	int		whichfork);	/* data or attr fork */
350 
351 #else
352 #define	xfs_bmap_trace_delete(f,d,ip,i,c,w)
353 #define	xfs_bmap_trace_insert(f,d,ip,i,c,r1,r2,w)
354 #define	xfs_bmap_trace_post_update(f,d,ip,i,w)
355 #define	xfs_bmap_trace_pre_update(f,d,ip,i,w)
356 #endif	/* XFS_BMAP_TRACE */
357 
358 /*
359  * Compute the worst-case number of indirect blocks that will be used
360  * for ip's delayed extent of length "len".
361  */
362 STATIC xfs_filblks_t
363 xfs_bmap_worst_indlen(
364 	xfs_inode_t		*ip,	/* incore inode pointer */
365 	xfs_filblks_t		len);	/* delayed extent length */
366 
367 #ifdef DEBUG
368 /*
369  * Perform various validation checks on the values being returned
370  * from xfs_bmapi().
371  */
372 STATIC void
373 xfs_bmap_validate_ret(
374 	xfs_fileoff_t		bno,
375 	xfs_filblks_t		len,
376 	int			flags,
377 	xfs_bmbt_irec_t		*mval,
378 	int			nmap,
379 	int			ret_nmap);
380 #else
381 #define	xfs_bmap_validate_ret(bno,len,flags,mval,onmap,nmap)
382 #endif /* DEBUG */
383 
384 #if defined(XFS_RW_TRACE)
385 STATIC void
386 xfs_bunmap_trace(
387 	xfs_inode_t		*ip,
388 	xfs_fileoff_t		bno,
389 	xfs_filblks_t		len,
390 	int			flags,
391 	inst_t			*ra);
392 #else
393 #define	xfs_bunmap_trace(ip, bno, len, flags, ra)
394 #endif	/* XFS_RW_TRACE */
395 
396 STATIC int
397 xfs_bmap_count_tree(
398 	xfs_mount_t     *mp,
399 	xfs_trans_t     *tp,
400 	xfs_ifork_t	*ifp,
401 	xfs_fsblock_t   blockno,
402 	int             levelin,
403 	int		*count);
404 
405 STATIC int
406 xfs_bmap_count_leaves(
407 	xfs_ifork_t		*ifp,
408 	xfs_extnum_t		idx,
409 	int			numrecs,
410 	int			*count);
411 
412 STATIC int
413 xfs_bmap_disk_count_leaves(
414 	xfs_ifork_t		*ifp,
415 	xfs_mount_t		*mp,
416 	xfs_extnum_t		idx,
417 	xfs_bmbt_block_t	*block,
418 	int			numrecs,
419 	int			*count);
420 
421 /*
422  * Bmap internal routines.
423  */
424 
425 /*
426  * Called from xfs_bmap_add_attrfork to handle btree format files.
427  */
428 STATIC int					/* error */
xfs_bmap_add_attrfork_btree(xfs_trans_t * tp,xfs_inode_t * ip,xfs_fsblock_t * firstblock,xfs_bmap_free_t * flist,int * flags)429 xfs_bmap_add_attrfork_btree(
430 	xfs_trans_t		*tp,		/* transaction pointer */
431 	xfs_inode_t		*ip,		/* incore inode pointer */
432 	xfs_fsblock_t		*firstblock,	/* first block allocated */
433 	xfs_bmap_free_t		*flist,		/* blocks to free at commit */
434 	int			*flags)		/* inode logging flags */
435 {
436 	xfs_btree_cur_t		*cur;		/* btree cursor */
437 	int			error;		/* error return value */
438 	xfs_mount_t		*mp;		/* file system mount struct */
439 	int			stat;		/* newroot status */
440 
441 	mp = ip->i_mount;
442 	if (ip->i_df.if_broot_bytes <= XFS_IFORK_DSIZE(ip))
443 		*flags |= XFS_ILOG_DBROOT;
444 	else {
445 		cur = xfs_btree_init_cursor(mp, tp, NULL, 0, XFS_BTNUM_BMAP, ip,
446 			XFS_DATA_FORK);
447 		cur->bc_private.b.flist = flist;
448 		cur->bc_private.b.firstblock = *firstblock;
449 		if ((error = xfs_bmbt_lookup_ge(cur, 0, 0, 0, &stat)))
450 			goto error0;
451 		ASSERT(stat == 1);	/* must be at least one entry */
452 		if ((error = xfs_bmbt_newroot(cur, flags, &stat)))
453 			goto error0;
454 		if (stat == 0) {
455 			xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
456 			return XFS_ERROR(ENOSPC);
457 		}
458 		*firstblock = cur->bc_private.b.firstblock;
459 		cur->bc_private.b.allocated = 0;
460 		xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
461 	}
462 	return 0;
463 error0:
464 	xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
465 	return error;
466 }
467 
468 /*
469  * Called from xfs_bmap_add_attrfork to handle extents format files.
470  */
471 STATIC int					/* error */
xfs_bmap_add_attrfork_extents(xfs_trans_t * tp,xfs_inode_t * ip,xfs_fsblock_t * firstblock,xfs_bmap_free_t * flist,int * flags)472 xfs_bmap_add_attrfork_extents(
473 	xfs_trans_t		*tp,		/* transaction pointer */
474 	xfs_inode_t		*ip,		/* incore inode pointer */
475 	xfs_fsblock_t		*firstblock,	/* first block allocated */
476 	xfs_bmap_free_t		*flist,		/* blocks to free at commit */
477 	int			*flags)		/* inode logging flags */
478 {
479 	xfs_btree_cur_t		*cur;		/* bmap btree cursor */
480 	int			error;		/* error return value */
481 
482 	if (ip->i_d.di_nextents * sizeof(xfs_bmbt_rec_t) <= XFS_IFORK_DSIZE(ip))
483 		return 0;
484 	cur = NULL;
485 	error = xfs_bmap_extents_to_btree(tp, ip, firstblock, flist, &cur, 0,
486 		flags, XFS_DATA_FORK);
487 	if (cur) {
488 		cur->bc_private.b.allocated = 0;
489 		xfs_btree_del_cursor(cur,
490 			error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
491 	}
492 	return error;
493 }
494 
495 /*
496  * Called from xfs_bmap_add_attrfork to handle local format files.
497  */
498 STATIC int					/* error */
xfs_bmap_add_attrfork_local(xfs_trans_t * tp,xfs_inode_t * ip,xfs_fsblock_t * firstblock,xfs_bmap_free_t * flist,int * flags)499 xfs_bmap_add_attrfork_local(
500 	xfs_trans_t		*tp,		/* transaction pointer */
501 	xfs_inode_t		*ip,		/* incore inode pointer */
502 	xfs_fsblock_t		*firstblock,	/* first block allocated */
503 	xfs_bmap_free_t		*flist,		/* blocks to free at commit */
504 	int			*flags)		/* inode logging flags */
505 {
506 	xfs_da_args_t		dargs;		/* args for dir/attr code */
507 	int			error;		/* error return value */
508 	xfs_mount_t		*mp;		/* mount structure pointer */
509 
510 	if (ip->i_df.if_bytes <= XFS_IFORK_DSIZE(ip))
511 		return 0;
512 	if ((ip->i_d.di_mode & S_IFMT) == S_IFDIR) {
513 		mp = ip->i_mount;
514 		memset(&dargs, 0, sizeof(dargs));
515 		dargs.dp = ip;
516 		dargs.firstblock = firstblock;
517 		dargs.flist = flist;
518 		dargs.total = mp->m_dirblkfsbs;
519 		dargs.whichfork = XFS_DATA_FORK;
520 		dargs.trans = tp;
521 		error = XFS_DIR_SHORTFORM_TO_SINGLE(mp, &dargs);
522 	} else
523 		error = xfs_bmap_local_to_extents(tp, ip, firstblock, 1, flags,
524 			XFS_DATA_FORK);
525 	return error;
526 }
527 
528 /*
529  * Called by xfs_bmapi to update file extent records and the btree
530  * after allocating space (or doing a delayed allocation).
531  */
532 STATIC int				/* error */
xfs_bmap_add_extent(xfs_inode_t * ip,xfs_extnum_t idx,xfs_btree_cur_t ** curp,xfs_bmbt_irec_t * new,xfs_fsblock_t * first,xfs_bmap_free_t * flist,int * logflagsp,xfs_extdelta_t * delta,int whichfork,int rsvd)533 xfs_bmap_add_extent(
534 	xfs_inode_t		*ip,	/* incore inode pointer */
535 	xfs_extnum_t		idx,	/* extent number to update/insert */
536 	xfs_btree_cur_t		**curp,	/* if *curp is null, not a btree */
537 	xfs_bmbt_irec_t		*new,	/* new data to add to file extents */
538 	xfs_fsblock_t		*first,	/* pointer to firstblock variable */
539 	xfs_bmap_free_t		*flist,	/* list of extents to be freed */
540 	int			*logflagsp, /* inode logging flags */
541 	xfs_extdelta_t		*delta, /* Change made to incore extents */
542 	int			whichfork, /* data or attr fork */
543 	int			rsvd)	/* OK to use reserved data blocks */
544 {
545 	xfs_btree_cur_t		*cur;	/* btree cursor or null */
546 	xfs_filblks_t		da_new; /* new count del alloc blocks used */
547 	xfs_filblks_t		da_old; /* old count del alloc blocks used */
548 	int			error;	/* error return value */
549 #ifdef XFS_BMAP_TRACE
550 	static char		fname[] = "xfs_bmap_add_extent";
551 #endif
552 	xfs_ifork_t		*ifp;	/* inode fork ptr */
553 	int			logflags; /* returned value */
554 	xfs_extnum_t		nextents; /* number of extents in file now */
555 
556 	XFS_STATS_INC(xs_add_exlist);
557 	cur = *curp;
558 	ifp = XFS_IFORK_PTR(ip, whichfork);
559 	nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
560 	ASSERT(idx <= nextents);
561 	da_old = da_new = 0;
562 	error = 0;
563 	/*
564 	 * This is the first extent added to a new/empty file.
565 	 * Special case this one, so other routines get to assume there are
566 	 * already extents in the list.
567 	 */
568 	if (nextents == 0) {
569 		xfs_bmap_trace_insert(fname, "insert empty", ip, 0, 1, new,
570 			NULL, whichfork);
571 		xfs_iext_insert(ifp, 0, 1, new);
572 		ASSERT(cur == NULL);
573 		ifp->if_lastex = 0;
574 		if (!ISNULLSTARTBLOCK(new->br_startblock)) {
575 			XFS_IFORK_NEXT_SET(ip, whichfork, 1);
576 			logflags = XFS_ILOG_CORE | XFS_ILOG_FEXT(whichfork);
577 		} else
578 			logflags = 0;
579 		/* DELTA: single new extent */
580 		if (delta) {
581 			if (delta->xed_startoff > new->br_startoff)
582 				delta->xed_startoff = new->br_startoff;
583 			if (delta->xed_blockcount <
584 					new->br_startoff + new->br_blockcount)
585 				delta->xed_blockcount = new->br_startoff +
586 						new->br_blockcount;
587 		}
588 	}
589 	/*
590 	 * Any kind of new delayed allocation goes here.
591 	 */
592 	else if (ISNULLSTARTBLOCK(new->br_startblock)) {
593 		if (cur)
594 			ASSERT((cur->bc_private.b.flags &
595 				XFS_BTCUR_BPRV_WASDEL) == 0);
596 		if ((error = xfs_bmap_add_extent_hole_delay(ip, idx, cur, new,
597 				&logflags, delta, rsvd)))
598 			goto done;
599 	}
600 	/*
601 	 * Real allocation off the end of the file.
602 	 */
603 	else if (idx == nextents) {
604 		if (cur)
605 			ASSERT((cur->bc_private.b.flags &
606 				XFS_BTCUR_BPRV_WASDEL) == 0);
607 		if ((error = xfs_bmap_add_extent_hole_real(ip, idx, cur, new,
608 				&logflags, delta, whichfork)))
609 			goto done;
610 	} else {
611 		xfs_bmbt_irec_t	prev;	/* old extent at offset idx */
612 
613 		/*
614 		 * Get the record referred to by idx.
615 		 */
616 		xfs_bmbt_get_all(xfs_iext_get_ext(ifp, idx), &prev);
617 		/*
618 		 * If it's a real allocation record, and the new allocation ends
619 		 * after the start of the referred to record, then we're filling
620 		 * in a delayed or unwritten allocation with a real one, or
621 		 * converting real back to unwritten.
622 		 */
623 		if (!ISNULLSTARTBLOCK(new->br_startblock) &&
624 		    new->br_startoff + new->br_blockcount > prev.br_startoff) {
625 			if (prev.br_state != XFS_EXT_UNWRITTEN &&
626 			    ISNULLSTARTBLOCK(prev.br_startblock)) {
627 				da_old = STARTBLOCKVAL(prev.br_startblock);
628 				if (cur)
629 					ASSERT(cur->bc_private.b.flags &
630 						XFS_BTCUR_BPRV_WASDEL);
631 				if ((error = xfs_bmap_add_extent_delay_real(ip,
632 					idx, &cur, new, &da_new, first, flist,
633 					&logflags, delta, rsvd)))
634 					goto done;
635 			} else if (new->br_state == XFS_EXT_NORM) {
636 				ASSERT(new->br_state == XFS_EXT_NORM);
637 				if ((error = xfs_bmap_add_extent_unwritten_real(
638 					ip, idx, &cur, new, &logflags, delta)))
639 					goto done;
640 			} else {
641 				ASSERT(new->br_state == XFS_EXT_UNWRITTEN);
642 				if ((error = xfs_bmap_add_extent_unwritten_real(
643 					ip, idx, &cur, new, &logflags, delta)))
644 					goto done;
645 			}
646 			ASSERT(*curp == cur || *curp == NULL);
647 		}
648 		/*
649 		 * Otherwise we're filling in a hole with an allocation.
650 		 */
651 		else {
652 			if (cur)
653 				ASSERT((cur->bc_private.b.flags &
654 					XFS_BTCUR_BPRV_WASDEL) == 0);
655 			if ((error = xfs_bmap_add_extent_hole_real(ip, idx, cur,
656 					new, &logflags, delta, whichfork)))
657 				goto done;
658 		}
659 	}
660 
661 	ASSERT(*curp == cur || *curp == NULL);
662 	/*
663 	 * Convert to a btree if necessary.
664 	 */
665 	if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS &&
666 	    XFS_IFORK_NEXTENTS(ip, whichfork) > ifp->if_ext_max) {
667 		int	tmp_logflags;	/* partial log flag return val */
668 
669 		ASSERT(cur == NULL);
670 		error = xfs_bmap_extents_to_btree(ip->i_transp, ip, first,
671 			flist, &cur, da_old > 0, &tmp_logflags, whichfork);
672 		logflags |= tmp_logflags;
673 		if (error)
674 			goto done;
675 	}
676 	/*
677 	 * Adjust for changes in reserved delayed indirect blocks.
678 	 * Nothing to do for disk quotas here.
679 	 */
680 	if (da_old || da_new) {
681 		xfs_filblks_t	nblks;
682 
683 		nblks = da_new;
684 		if (cur)
685 			nblks += cur->bc_private.b.allocated;
686 		ASSERT(nblks <= da_old);
687 		if (nblks < da_old)
688 			xfs_mod_incore_sb(ip->i_mount, XFS_SBS_FDBLOCKS,
689 				(int)(da_old - nblks), rsvd);
690 	}
691 	/*
692 	 * Clear out the allocated field, done with it now in any case.
693 	 */
694 	if (cur) {
695 		cur->bc_private.b.allocated = 0;
696 		*curp = cur;
697 	}
698 done:
699 #ifdef DEBUG
700 	if (!error)
701 		xfs_bmap_check_leaf_extents(*curp, ip, whichfork);
702 #endif
703 	*logflagsp = logflags;
704 	return error;
705 }
706 
707 /*
708  * Called by xfs_bmap_add_extent to handle cases converting a delayed
709  * allocation to a real allocation.
710  */
711 STATIC int				/* error */
xfs_bmap_add_extent_delay_real(xfs_inode_t * ip,xfs_extnum_t idx,xfs_btree_cur_t ** curp,xfs_bmbt_irec_t * new,xfs_filblks_t * dnew,xfs_fsblock_t * first,xfs_bmap_free_t * flist,int * logflagsp,xfs_extdelta_t * delta,int rsvd)712 xfs_bmap_add_extent_delay_real(
713 	xfs_inode_t		*ip,	/* incore inode pointer */
714 	xfs_extnum_t		idx,	/* extent number to update/insert */
715 	xfs_btree_cur_t		**curp,	/* if *curp is null, not a btree */
716 	xfs_bmbt_irec_t		*new,	/* new data to add to file extents */
717 	xfs_filblks_t		*dnew,	/* new delayed-alloc indirect blocks */
718 	xfs_fsblock_t		*first,	/* pointer to firstblock variable */
719 	xfs_bmap_free_t		*flist,	/* list of extents to be freed */
720 	int			*logflagsp, /* inode logging flags */
721 	xfs_extdelta_t		*delta, /* Change made to incore extents */
722 	int			rsvd)	/* OK to use reserved data block allocation */
723 {
724 	xfs_btree_cur_t		*cur;	/* btree cursor */
725 	int			diff;	/* temp value */
726 	xfs_bmbt_rec_t		*ep;	/* extent entry for idx */
727 	int			error;	/* error return value */
728 #ifdef XFS_BMAP_TRACE
729 	static char		fname[] = "xfs_bmap_add_extent_delay_real";
730 #endif
731 	int			i;	/* temp state */
732 	xfs_ifork_t		*ifp;	/* inode fork pointer */
733 	xfs_fileoff_t		new_endoff;	/* end offset of new entry */
734 	xfs_bmbt_irec_t		r[3];	/* neighbor extent entries */
735 					/* left is 0, right is 1, prev is 2 */
736 	int			rval=0;	/* return value (logging flags) */
737 	int			state = 0;/* state bits, accessed thru macros */
738 	xfs_filblks_t		temp=0;	/* value for dnew calculations */
739 	xfs_filblks_t		temp2=0;/* value for dnew calculations */
740 	int			tmp_rval;	/* partial logging flags */
741 	enum {				/* bit number definitions for state */
742 		LEFT_CONTIG,	RIGHT_CONTIG,
743 		LEFT_FILLING,	RIGHT_FILLING,
744 		LEFT_DELAY,	RIGHT_DELAY,
745 		LEFT_VALID,	RIGHT_VALID
746 	};
747 
748 #define	LEFT		r[0]
749 #define	RIGHT		r[1]
750 #define	PREV		r[2]
751 #define	MASK(b)		(1 << (b))
752 #define	MASK2(a,b)	(MASK(a) | MASK(b))
753 #define	MASK3(a,b,c)	(MASK2(a,b) | MASK(c))
754 #define	MASK4(a,b,c,d)	(MASK3(a,b,c) | MASK(d))
755 #define	STATE_SET(b,v)	((v) ? (state |= MASK(b)) : (state &= ~MASK(b)))
756 #define	STATE_TEST(b)	(state & MASK(b))
757 #define	STATE_SET_TEST(b,v)	((v) ? ((state |= MASK(b)), 1) : \
758 				       ((state &= ~MASK(b)), 0))
759 #define	SWITCH_STATE		\
760 	(state & MASK4(LEFT_FILLING, RIGHT_FILLING, LEFT_CONTIG, RIGHT_CONTIG))
761 
762 	/*
763 	 * Set up a bunch of variables to make the tests simpler.
764 	 */
765 	cur = *curp;
766 	ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
767 	ep = xfs_iext_get_ext(ifp, idx);
768 	xfs_bmbt_get_all(ep, &PREV);
769 	new_endoff = new->br_startoff + new->br_blockcount;
770 	ASSERT(PREV.br_startoff <= new->br_startoff);
771 	ASSERT(PREV.br_startoff + PREV.br_blockcount >= new_endoff);
772 	/*
773 	 * Set flags determining what part of the previous delayed allocation
774 	 * extent is being replaced by a real allocation.
775 	 */
776 	STATE_SET(LEFT_FILLING, PREV.br_startoff == new->br_startoff);
777 	STATE_SET(RIGHT_FILLING,
778 		PREV.br_startoff + PREV.br_blockcount == new_endoff);
779 	/*
780 	 * Check and set flags if this segment has a left neighbor.
781 	 * Don't set contiguous if the combined extent would be too large.
782 	 */
783 	if (STATE_SET_TEST(LEFT_VALID, idx > 0)) {
784 		xfs_bmbt_get_all(xfs_iext_get_ext(ifp, idx - 1), &LEFT);
785 		STATE_SET(LEFT_DELAY, ISNULLSTARTBLOCK(LEFT.br_startblock));
786 	}
787 	STATE_SET(LEFT_CONTIG,
788 		STATE_TEST(LEFT_VALID) && !STATE_TEST(LEFT_DELAY) &&
789 		LEFT.br_startoff + LEFT.br_blockcount == new->br_startoff &&
790 		LEFT.br_startblock + LEFT.br_blockcount == new->br_startblock &&
791 		LEFT.br_state == new->br_state &&
792 		LEFT.br_blockcount + new->br_blockcount <= MAXEXTLEN);
793 	/*
794 	 * Check and set flags if this segment has a right neighbor.
795 	 * Don't set contiguous if the combined extent would be too large.
796 	 * Also check for all-three-contiguous being too large.
797 	 */
798 	if (STATE_SET_TEST(RIGHT_VALID,
799 			idx <
800 			ip->i_df.if_bytes / (uint)sizeof(xfs_bmbt_rec_t) - 1)) {
801 		xfs_bmbt_get_all(xfs_iext_get_ext(ifp, idx + 1), &RIGHT);
802 		STATE_SET(RIGHT_DELAY, ISNULLSTARTBLOCK(RIGHT.br_startblock));
803 	}
804 	STATE_SET(RIGHT_CONTIG,
805 		STATE_TEST(RIGHT_VALID) && !STATE_TEST(RIGHT_DELAY) &&
806 		new_endoff == RIGHT.br_startoff &&
807 		new->br_startblock + new->br_blockcount ==
808 		    RIGHT.br_startblock &&
809 		new->br_state == RIGHT.br_state &&
810 		new->br_blockcount + RIGHT.br_blockcount <= MAXEXTLEN &&
811 		((state & MASK3(LEFT_CONTIG, LEFT_FILLING, RIGHT_FILLING)) !=
812 		  MASK3(LEFT_CONTIG, LEFT_FILLING, RIGHT_FILLING) ||
813 		 LEFT.br_blockcount + new->br_blockcount + RIGHT.br_blockcount
814 		     <= MAXEXTLEN));
815 	error = 0;
816 	/*
817 	 * Switch out based on the FILLING and CONTIG state bits.
818 	 */
819 	switch (SWITCH_STATE) {
820 
821 	case MASK4(LEFT_FILLING, RIGHT_FILLING, LEFT_CONTIG, RIGHT_CONTIG):
822 		/*
823 		 * Filling in all of a previously delayed allocation extent.
824 		 * The left and right neighbors are both contiguous with new.
825 		 */
826 		xfs_bmap_trace_pre_update(fname, "LF|RF|LC|RC", ip, idx - 1,
827 			XFS_DATA_FORK);
828 		xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, idx - 1),
829 			LEFT.br_blockcount + PREV.br_blockcount +
830 			RIGHT.br_blockcount);
831 		xfs_bmap_trace_post_update(fname, "LF|RF|LC|RC", ip, idx - 1,
832 			XFS_DATA_FORK);
833 		xfs_bmap_trace_delete(fname, "LF|RF|LC|RC", ip, idx, 2,
834 			XFS_DATA_FORK);
835 		xfs_iext_remove(ifp, idx, 2);
836 		ip->i_df.if_lastex = idx - 1;
837 		ip->i_d.di_nextents--;
838 		if (cur == NULL)
839 			rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
840 		else {
841 			rval = XFS_ILOG_CORE;
842 			if ((error = xfs_bmbt_lookup_eq(cur, RIGHT.br_startoff,
843 					RIGHT.br_startblock,
844 					RIGHT.br_blockcount, &i)))
845 				goto done;
846 			ASSERT(i == 1);
847 			if ((error = xfs_bmbt_delete(cur, &i)))
848 				goto done;
849 			ASSERT(i == 1);
850 			if ((error = xfs_bmbt_decrement(cur, 0, &i)))
851 				goto done;
852 			ASSERT(i == 1);
853 			if ((error = xfs_bmbt_update(cur, LEFT.br_startoff,
854 					LEFT.br_startblock,
855 					LEFT.br_blockcount +
856 					PREV.br_blockcount +
857 					RIGHT.br_blockcount, LEFT.br_state)))
858 				goto done;
859 		}
860 		*dnew = 0;
861 		/* DELTA: Three in-core extents are replaced by one. */
862 		temp = LEFT.br_startoff;
863 		temp2 = LEFT.br_blockcount +
864 			PREV.br_blockcount +
865 			RIGHT.br_blockcount;
866 		break;
867 
868 	case MASK3(LEFT_FILLING, RIGHT_FILLING, LEFT_CONTIG):
869 		/*
870 		 * Filling in all of a previously delayed allocation extent.
871 		 * The left neighbor is contiguous, the right is not.
872 		 */
873 		xfs_bmap_trace_pre_update(fname, "LF|RF|LC", ip, idx - 1,
874 			XFS_DATA_FORK);
875 		xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, idx - 1),
876 			LEFT.br_blockcount + PREV.br_blockcount);
877 		xfs_bmap_trace_post_update(fname, "LF|RF|LC", ip, idx - 1,
878 			XFS_DATA_FORK);
879 		ip->i_df.if_lastex = idx - 1;
880 		xfs_bmap_trace_delete(fname, "LF|RF|LC", ip, idx, 1,
881 			XFS_DATA_FORK);
882 		xfs_iext_remove(ifp, idx, 1);
883 		if (cur == NULL)
884 			rval = XFS_ILOG_DEXT;
885 		else {
886 			rval = 0;
887 			if ((error = xfs_bmbt_lookup_eq(cur, LEFT.br_startoff,
888 					LEFT.br_startblock, LEFT.br_blockcount,
889 					&i)))
890 				goto done;
891 			ASSERT(i == 1);
892 			if ((error = xfs_bmbt_update(cur, LEFT.br_startoff,
893 					LEFT.br_startblock,
894 					LEFT.br_blockcount +
895 					PREV.br_blockcount, LEFT.br_state)))
896 				goto done;
897 		}
898 		*dnew = 0;
899 		/* DELTA: Two in-core extents are replaced by one. */
900 		temp = LEFT.br_startoff;
901 		temp2 = LEFT.br_blockcount +
902 			PREV.br_blockcount;
903 		break;
904 
905 	case MASK3(LEFT_FILLING, RIGHT_FILLING, RIGHT_CONTIG):
906 		/*
907 		 * Filling in all of a previously delayed allocation extent.
908 		 * The right neighbor is contiguous, the left is not.
909 		 */
910 		xfs_bmap_trace_pre_update(fname, "LF|RF|RC", ip, idx,
911 			XFS_DATA_FORK);
912 		xfs_bmbt_set_startblock(ep, new->br_startblock);
913 		xfs_bmbt_set_blockcount(ep,
914 			PREV.br_blockcount + RIGHT.br_blockcount);
915 		xfs_bmap_trace_post_update(fname, "LF|RF|RC", ip, idx,
916 			XFS_DATA_FORK);
917 		ip->i_df.if_lastex = idx;
918 		xfs_bmap_trace_delete(fname, "LF|RF|RC", ip, idx + 1, 1,
919 			XFS_DATA_FORK);
920 		xfs_iext_remove(ifp, idx + 1, 1);
921 		if (cur == NULL)
922 			rval = XFS_ILOG_DEXT;
923 		else {
924 			rval = 0;
925 			if ((error = xfs_bmbt_lookup_eq(cur, RIGHT.br_startoff,
926 					RIGHT.br_startblock,
927 					RIGHT.br_blockcount, &i)))
928 				goto done;
929 			ASSERT(i == 1);
930 			if ((error = xfs_bmbt_update(cur, PREV.br_startoff,
931 					new->br_startblock,
932 					PREV.br_blockcount +
933 					RIGHT.br_blockcount, PREV.br_state)))
934 				goto done;
935 		}
936 		*dnew = 0;
937 		/* DELTA: Two in-core extents are replaced by one. */
938 		temp = PREV.br_startoff;
939 		temp2 = PREV.br_blockcount +
940 			RIGHT.br_blockcount;
941 		break;
942 
943 	case MASK2(LEFT_FILLING, RIGHT_FILLING):
944 		/*
945 		 * Filling in all of a previously delayed allocation extent.
946 		 * Neither the left nor right neighbors are contiguous with
947 		 * the new one.
948 		 */
949 		xfs_bmap_trace_pre_update(fname, "LF|RF", ip, idx,
950 			XFS_DATA_FORK);
951 		xfs_bmbt_set_startblock(ep, new->br_startblock);
952 		xfs_bmap_trace_post_update(fname, "LF|RF", ip, idx,
953 			XFS_DATA_FORK);
954 		ip->i_df.if_lastex = idx;
955 		ip->i_d.di_nextents++;
956 		if (cur == NULL)
957 			rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
958 		else {
959 			rval = XFS_ILOG_CORE;
960 			if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff,
961 					new->br_startblock, new->br_blockcount,
962 					&i)))
963 				goto done;
964 			ASSERT(i == 0);
965 			cur->bc_rec.b.br_state = XFS_EXT_NORM;
966 			if ((error = xfs_bmbt_insert(cur, &i)))
967 				goto done;
968 			ASSERT(i == 1);
969 		}
970 		*dnew = 0;
971 		/* DELTA: The in-core extent described by new changed type. */
972 		temp = new->br_startoff;
973 		temp2 = new->br_blockcount;
974 		break;
975 
976 	case MASK2(LEFT_FILLING, LEFT_CONTIG):
977 		/*
978 		 * Filling in the first part of a previous delayed allocation.
979 		 * The left neighbor is contiguous.
980 		 */
981 		xfs_bmap_trace_pre_update(fname, "LF|LC", ip, idx - 1,
982 			XFS_DATA_FORK);
983 		xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, idx - 1),
984 			LEFT.br_blockcount + new->br_blockcount);
985 		xfs_bmbt_set_startoff(ep,
986 			PREV.br_startoff + new->br_blockcount);
987 		xfs_bmap_trace_post_update(fname, "LF|LC", ip, idx - 1,
988 			XFS_DATA_FORK);
989 		temp = PREV.br_blockcount - new->br_blockcount;
990 		xfs_bmap_trace_pre_update(fname, "LF|LC", ip, idx,
991 			XFS_DATA_FORK);
992 		xfs_bmbt_set_blockcount(ep, temp);
993 		ip->i_df.if_lastex = idx - 1;
994 		if (cur == NULL)
995 			rval = XFS_ILOG_DEXT;
996 		else {
997 			rval = 0;
998 			if ((error = xfs_bmbt_lookup_eq(cur, LEFT.br_startoff,
999 					LEFT.br_startblock, LEFT.br_blockcount,
1000 					&i)))
1001 				goto done;
1002 			ASSERT(i == 1);
1003 			if ((error = xfs_bmbt_update(cur, LEFT.br_startoff,
1004 					LEFT.br_startblock,
1005 					LEFT.br_blockcount +
1006 					new->br_blockcount,
1007 					LEFT.br_state)))
1008 				goto done;
1009 		}
1010 		temp = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
1011 			STARTBLOCKVAL(PREV.br_startblock));
1012 		xfs_bmbt_set_startblock(ep, NULLSTARTBLOCK((int)temp));
1013 		xfs_bmap_trace_post_update(fname, "LF|LC", ip, idx,
1014 			XFS_DATA_FORK);
1015 		*dnew = temp;
1016 		/* DELTA: The boundary between two in-core extents moved. */
1017 		temp = LEFT.br_startoff;
1018 		temp2 = LEFT.br_blockcount +
1019 			PREV.br_blockcount;
1020 		break;
1021 
1022 	case MASK(LEFT_FILLING):
1023 		/*
1024 		 * Filling in the first part of a previous delayed allocation.
1025 		 * The left neighbor is not contiguous.
1026 		 */
1027 		xfs_bmap_trace_pre_update(fname, "LF", ip, idx, XFS_DATA_FORK);
1028 		xfs_bmbt_set_startoff(ep, new_endoff);
1029 		temp = PREV.br_blockcount - new->br_blockcount;
1030 		xfs_bmbt_set_blockcount(ep, temp);
1031 		xfs_bmap_trace_insert(fname, "LF", ip, idx, 1, new, NULL,
1032 			XFS_DATA_FORK);
1033 		xfs_iext_insert(ifp, idx, 1, new);
1034 		ip->i_df.if_lastex = idx;
1035 		ip->i_d.di_nextents++;
1036 		if (cur == NULL)
1037 			rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
1038 		else {
1039 			rval = XFS_ILOG_CORE;
1040 			if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff,
1041 					new->br_startblock, new->br_blockcount,
1042 					&i)))
1043 				goto done;
1044 			ASSERT(i == 0);
1045 			cur->bc_rec.b.br_state = XFS_EXT_NORM;
1046 			if ((error = xfs_bmbt_insert(cur, &i)))
1047 				goto done;
1048 			ASSERT(i == 1);
1049 		}
1050 		if (ip->i_d.di_format == XFS_DINODE_FMT_EXTENTS &&
1051 		    ip->i_d.di_nextents > ip->i_df.if_ext_max) {
1052 			error = xfs_bmap_extents_to_btree(ip->i_transp, ip,
1053 					first, flist, &cur, 1, &tmp_rval,
1054 					XFS_DATA_FORK);
1055 			rval |= tmp_rval;
1056 			if (error)
1057 				goto done;
1058 		}
1059 		temp = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
1060 			STARTBLOCKVAL(PREV.br_startblock) -
1061 			(cur ? cur->bc_private.b.allocated : 0));
1062 		ep = xfs_iext_get_ext(ifp, idx + 1);
1063 		xfs_bmbt_set_startblock(ep, NULLSTARTBLOCK((int)temp));
1064 		xfs_bmap_trace_post_update(fname, "LF", ip, idx + 1,
1065 			XFS_DATA_FORK);
1066 		*dnew = temp;
1067 		/* DELTA: One in-core extent is split in two. */
1068 		temp = PREV.br_startoff;
1069 		temp2 = PREV.br_blockcount;
1070 		break;
1071 
1072 	case MASK2(RIGHT_FILLING, RIGHT_CONTIG):
1073 		/*
1074 		 * Filling in the last part of a previous delayed allocation.
1075 		 * The right neighbor is contiguous with the new allocation.
1076 		 */
1077 		temp = PREV.br_blockcount - new->br_blockcount;
1078 		xfs_bmap_trace_pre_update(fname, "RF|RC", ip, idx,
1079 			XFS_DATA_FORK);
1080 		xfs_bmap_trace_pre_update(fname, "RF|RC", ip, idx + 1,
1081 			XFS_DATA_FORK);
1082 		xfs_bmbt_set_blockcount(ep, temp);
1083 		xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, idx + 1),
1084 			new->br_startoff, new->br_startblock,
1085 			new->br_blockcount + RIGHT.br_blockcount,
1086 			RIGHT.br_state);
1087 		xfs_bmap_trace_post_update(fname, "RF|RC", ip, idx + 1,
1088 			XFS_DATA_FORK);
1089 		ip->i_df.if_lastex = idx + 1;
1090 		if (cur == NULL)
1091 			rval = XFS_ILOG_DEXT;
1092 		else {
1093 			rval = 0;
1094 			if ((error = xfs_bmbt_lookup_eq(cur, RIGHT.br_startoff,
1095 					RIGHT.br_startblock,
1096 					RIGHT.br_blockcount, &i)))
1097 				goto done;
1098 			ASSERT(i == 1);
1099 			if ((error = xfs_bmbt_update(cur, new->br_startoff,
1100 					new->br_startblock,
1101 					new->br_blockcount +
1102 					RIGHT.br_blockcount,
1103 					RIGHT.br_state)))
1104 				goto done;
1105 		}
1106 		temp = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
1107 			STARTBLOCKVAL(PREV.br_startblock));
1108 		xfs_bmbt_set_startblock(ep, NULLSTARTBLOCK((int)temp));
1109 		xfs_bmap_trace_post_update(fname, "RF|RC", ip, idx,
1110 			XFS_DATA_FORK);
1111 		*dnew = temp;
1112 		/* DELTA: The boundary between two in-core extents moved. */
1113 		temp = PREV.br_startoff;
1114 		temp2 = PREV.br_blockcount +
1115 			RIGHT.br_blockcount;
1116 		break;
1117 
1118 	case MASK(RIGHT_FILLING):
1119 		/*
1120 		 * Filling in the last part of a previous delayed allocation.
1121 		 * The right neighbor is not contiguous.
1122 		 */
1123 		temp = PREV.br_blockcount - new->br_blockcount;
1124 		xfs_bmap_trace_pre_update(fname, "RF", ip, idx, XFS_DATA_FORK);
1125 		xfs_bmbt_set_blockcount(ep, temp);
1126 		xfs_bmap_trace_insert(fname, "RF", ip, idx + 1, 1,
1127 			new, NULL, XFS_DATA_FORK);
1128 		xfs_iext_insert(ifp, idx + 1, 1, new);
1129 		ip->i_df.if_lastex = idx + 1;
1130 		ip->i_d.di_nextents++;
1131 		if (cur == NULL)
1132 			rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
1133 		else {
1134 			rval = XFS_ILOG_CORE;
1135 			if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff,
1136 					new->br_startblock, new->br_blockcount,
1137 					&i)))
1138 				goto done;
1139 			ASSERT(i == 0);
1140 			cur->bc_rec.b.br_state = XFS_EXT_NORM;
1141 			if ((error = xfs_bmbt_insert(cur, &i)))
1142 				goto done;
1143 			ASSERT(i == 1);
1144 		}
1145 		if (ip->i_d.di_format == XFS_DINODE_FMT_EXTENTS &&
1146 		    ip->i_d.di_nextents > ip->i_df.if_ext_max) {
1147 			error = xfs_bmap_extents_to_btree(ip->i_transp, ip,
1148 				first, flist, &cur, 1, &tmp_rval,
1149 				XFS_DATA_FORK);
1150 			rval |= tmp_rval;
1151 			if (error)
1152 				goto done;
1153 		}
1154 		temp = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
1155 			STARTBLOCKVAL(PREV.br_startblock) -
1156 			(cur ? cur->bc_private.b.allocated : 0));
1157 		ep = xfs_iext_get_ext(ifp, idx);
1158 		xfs_bmbt_set_startblock(ep, NULLSTARTBLOCK((int)temp));
1159 		xfs_bmap_trace_post_update(fname, "RF", ip, idx, XFS_DATA_FORK);
1160 		*dnew = temp;
1161 		/* DELTA: One in-core extent is split in two. */
1162 		temp = PREV.br_startoff;
1163 		temp2 = PREV.br_blockcount;
1164 		break;
1165 
1166 	case 0:
1167 		/*
1168 		 * Filling in the middle part of a previous delayed allocation.
1169 		 * Contiguity is impossible here.
1170 		 * This case is avoided almost all the time.
1171 		 */
1172 		temp = new->br_startoff - PREV.br_startoff;
1173 		xfs_bmap_trace_pre_update(fname, "0", ip, idx, XFS_DATA_FORK);
1174 		xfs_bmbt_set_blockcount(ep, temp);
1175 		r[0] = *new;
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 */
xfs_bmap_add_extent_unwritten_real(xfs_inode_t * ip,xfs_extnum_t idx,xfs_btree_cur_t ** curp,xfs_bmbt_irec_t * new,int * logflagsp,xfs_extdelta_t * delta)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 */
xfs_bmap_add_extent_hole_delay(xfs_inode_t * ip,xfs_extnum_t idx,xfs_btree_cur_t * cur,xfs_bmbt_irec_t * new,int * logflagsp,xfs_extdelta_t * delta,int rsvd)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 */
xfs_bmap_add_extent_hole_real(xfs_inode_t * ip,xfs_extnum_t idx,xfs_btree_cur_t * cur,xfs_bmbt_irec_t * new,int * logflagsp,xfs_extdelta_t * delta,int whichfork)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
xfs_bmap_extsize_align(xfs_mount_t * mp,xfs_bmbt_irec_t * gotp,xfs_bmbt_irec_t * prevp,xfs_extlen_t extsz,int rt,int eof,int delay,int convert,xfs_fileoff_t * offp,xfs_extlen_t * lenp)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
xfs_bmap_adjacent(xfs_bmalloca_t * ap)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
xfs_bmap_rtalloc(xfs_bmalloca_t * ap)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
xfs_bmap_btalloc(xfs_bmalloca_t * ap)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 	blen = 0;
2768 	if (nullfb) {
2769 		args.type = XFS_ALLOCTYPE_START_BNO;
2770 		args.total = ap->total;
2771 		/*
2772 		 * Find the longest available space.
2773 		 * We're going to try for the whole allocation at once.
2774 		 */
2775 		startag = ag = XFS_FSB_TO_AGNO(mp, args.fsbno);
2776 		notinit = 0;
2777 		down_read(&mp->m_peraglock);
2778 		while (blen < ap->alen) {
2779 			pag = &mp->m_perag[ag];
2780 			if (!pag->pagf_init &&
2781 			    (error = xfs_alloc_pagf_init(mp, args.tp,
2782 				    ag, XFS_ALLOC_FLAG_TRYLOCK))) {
2783 				up_read(&mp->m_peraglock);
2784 				return error;
2785 			}
2786 			/*
2787 			 * See xfs_alloc_fix_freelist...
2788 			 */
2789 			if (pag->pagf_init) {
2790 				need = XFS_MIN_FREELIST_PAG(pag, mp);
2791 				delta = need > pag->pagf_flcount ?
2792 					need - pag->pagf_flcount : 0;
2793 				longest = (pag->pagf_longest > delta) ?
2794 					(pag->pagf_longest - delta) :
2795 					(pag->pagf_flcount > 0 ||
2796 					 pag->pagf_longest > 0);
2797 				if (blen < longest)
2798 					blen = longest;
2799 			} else
2800 				notinit = 1;
2801 			if (++ag == mp->m_sb.sb_agcount)
2802 				ag = 0;
2803 			if (ag == startag)
2804 				break;
2805 		}
2806 		up_read(&mp->m_peraglock);
2807 		/*
2808 		 * Since the above loop did a BUF_TRYLOCK, it is
2809 		 * possible that there is space for this request.
2810 		 */
2811 		if (notinit || blen < ap->minlen)
2812 			args.minlen = ap->minlen;
2813 		/*
2814 		 * If the best seen length is less than the request
2815 		 * length, use the best as the minimum.
2816 		 */
2817 		else if (blen < ap->alen)
2818 			args.minlen = blen;
2819 		/*
2820 		 * Otherwise we've seen an extent as big as alen,
2821 		 * use that as the minimum.
2822 		 */
2823 		else
2824 			args.minlen = ap->alen;
2825 	} else if (ap->low) {
2826 		args.type = XFS_ALLOCTYPE_FIRST_AG;
2827 		args.total = args.minlen = ap->minlen;
2828 	} else {
2829 		args.type = XFS_ALLOCTYPE_NEAR_BNO;
2830 		args.total = ap->total;
2831 		args.minlen = ap->minlen;
2832 	}
2833 	if (unlikely(ap->userdata && ap->ip->i_d.di_extsize &&
2834 		    (ap->ip->i_d.di_flags & XFS_DIFLAG_EXTSIZE))) {
2835 		args.prod = ap->ip->i_d.di_extsize;
2836 		if ((args.mod = (xfs_extlen_t)do_mod(ap->off, args.prod)))
2837 			args.mod = (xfs_extlen_t)(args.prod - args.mod);
2838 	} else if (unlikely(mp->m_sb.sb_blocksize >= NBPP)) {
2839 		args.prod = 1;
2840 		args.mod = 0;
2841 	} else {
2842 		args.prod = NBPP >> mp->m_sb.sb_blocklog;
2843 		if ((args.mod = (xfs_extlen_t)(do_mod(ap->off, args.prod))))
2844 			args.mod = (xfs_extlen_t)(args.prod - args.mod);
2845 	}
2846 	/*
2847 	 * If we are not low on available data blocks, and the
2848 	 * underlying logical volume manager is a stripe, and
2849 	 * the file offset is zero then try to allocate data
2850 	 * blocks on stripe unit boundary.
2851 	 * NOTE: ap->aeof is only set if the allocation length
2852 	 * is >= the stripe unit and the allocation offset is
2853 	 * at the end of file.
2854 	 */
2855 	if (!ap->low && ap->aeof) {
2856 		if (!ap->off) {
2857 			args.alignment = mp->m_dalign;
2858 			atype = args.type;
2859 			isaligned = 1;
2860 			/*
2861 			 * Adjust for alignment
2862 			 */
2863 			if (blen > args.alignment && blen <= ap->alen)
2864 				args.minlen = blen - args.alignment;
2865 			args.minalignslop = 0;
2866 		} else {
2867 			/*
2868 			 * First try an exact bno allocation.
2869 			 * If it fails then do a near or start bno
2870 			 * allocation with alignment turned on.
2871 			 */
2872 			atype = args.type;
2873 			tryagain = 1;
2874 			args.type = XFS_ALLOCTYPE_THIS_BNO;
2875 			args.alignment = 1;
2876 			/*
2877 			 * Compute the minlen+alignment for the
2878 			 * next case.  Set slop so that the value
2879 			 * of minlen+alignment+slop doesn't go up
2880 			 * between the calls.
2881 			 */
2882 			if (blen > mp->m_dalign && blen <= ap->alen)
2883 				nextminlen = blen - mp->m_dalign;
2884 			else
2885 				nextminlen = args.minlen;
2886 			if (nextminlen + mp->m_dalign > args.minlen + 1)
2887 				args.minalignslop =
2888 					nextminlen + mp->m_dalign -
2889 					args.minlen - 1;
2890 			else
2891 				args.minalignslop = 0;
2892 		}
2893 	} else {
2894 		args.alignment = 1;
2895 		args.minalignslop = 0;
2896 	}
2897 	args.minleft = ap->minleft;
2898 	args.wasdel = ap->wasdel;
2899 	args.isfl = 0;
2900 	args.userdata = ap->userdata;
2901 	if ((error = xfs_alloc_vextent(&args)))
2902 		return error;
2903 	if (tryagain && args.fsbno == NULLFSBLOCK) {
2904 		/*
2905 		 * Exact allocation failed. Now try with alignment
2906 		 * turned on.
2907 		 */
2908 		args.type = atype;
2909 		args.fsbno = ap->rval;
2910 		args.alignment = mp->m_dalign;
2911 		args.minlen = nextminlen;
2912 		args.minalignslop = 0;
2913 		isaligned = 1;
2914 		if ((error = xfs_alloc_vextent(&args)))
2915 			return error;
2916 	}
2917 	if (isaligned && args.fsbno == NULLFSBLOCK) {
2918 		/*
2919 		 * allocation failed, so turn off alignment and
2920 		 * try again.
2921 		 */
2922 		args.type = atype;
2923 		args.fsbno = ap->rval;
2924 		args.alignment = 0;
2925 		if ((error = xfs_alloc_vextent(&args)))
2926 			return error;
2927 	}
2928 	if (args.fsbno == NULLFSBLOCK && nullfb &&
2929 	    args.minlen > ap->minlen) {
2930 		args.minlen = ap->minlen;
2931 		args.type = XFS_ALLOCTYPE_START_BNO;
2932 		args.fsbno = ap->rval;
2933 		if ((error = xfs_alloc_vextent(&args)))
2934 			return error;
2935 	}
2936 	if (args.fsbno == NULLFSBLOCK && nullfb) {
2937 		args.fsbno = 0;
2938 		args.type = XFS_ALLOCTYPE_FIRST_AG;
2939 		args.total = ap->minlen;
2940 		args.minleft = 0;
2941 		if ((error = xfs_alloc_vextent(&args)))
2942 			return error;
2943 		ap->low = 1;
2944 	}
2945 	if (args.fsbno != NULLFSBLOCK) {
2946 		ap->firstblock = ap->rval = args.fsbno;
2947 		ASSERT(nullfb || fb_agno == args.agno ||
2948 		       (ap->low && fb_agno < args.agno));
2949 		ap->alen = args.len;
2950 		ap->ip->i_d.di_nblocks += args.len;
2951 		xfs_trans_log_inode(ap->tp, ap->ip, XFS_ILOG_CORE);
2952 		if (ap->wasdel)
2953 			ap->ip->i_delayed_blks -= args.len;
2954 		/*
2955 		 * Adjust the disk quota also. This was reserved
2956 		 * earlier.
2957 		 */
2958 		XFS_TRANS_MOD_DQUOT_BYINO(mp, ap->tp, ap->ip,
2959 			ap->wasdel ? XFS_TRANS_DQ_DELBCOUNT :
2960 					XFS_TRANS_DQ_BCOUNT,
2961 			(long) args.len);
2962 	} else {
2963 		ap->rval = NULLFSBLOCK;
2964 		ap->alen = 0;
2965 	}
2966 	return 0;
2967 }
2968 
2969 /*
2970  * xfs_bmap_alloc is called by xfs_bmapi to allocate an extent for a file.
2971  * It figures out where to ask the underlying allocator to put the new extent.
2972  */
2973 STATIC int
xfs_bmap_alloc(xfs_bmalloca_t * ap)2974 xfs_bmap_alloc(
2975 	xfs_bmalloca_t	*ap)		/* bmap alloc argument struct */
2976 {
2977 	if ((ap->ip->i_d.di_flags & XFS_DIFLAG_REALTIME) && ap->userdata)
2978 		return xfs_bmap_rtalloc(ap);
2979 	return xfs_bmap_btalloc(ap);
2980 }
2981 
2982 /*
2983  * Transform a btree format file with only one leaf node, where the
2984  * extents list will fit in the inode, into an extents format file.
2985  * Since the file extents are already in-core, all we have to do is
2986  * give up the space for the btree root and pitch the leaf block.
2987  */
2988 STATIC int				/* error */
xfs_bmap_btree_to_extents(xfs_trans_t * tp,xfs_inode_t * ip,xfs_btree_cur_t * cur,int * logflagsp,int whichfork)2989 xfs_bmap_btree_to_extents(
2990 	xfs_trans_t		*tp,	/* transaction pointer */
2991 	xfs_inode_t		*ip,	/* incore inode pointer */
2992 	xfs_btree_cur_t		*cur,	/* btree cursor */
2993 	int			*logflagsp, /* inode logging flags */
2994 	int			whichfork)  /* data or attr fork */
2995 {
2996 	/* REFERENCED */
2997 	xfs_bmbt_block_t	*cblock;/* child btree block */
2998 	xfs_fsblock_t		cbno;	/* child block number */
2999 	xfs_buf_t		*cbp;	/* child block's buffer */
3000 	int			error;	/* error return value */
3001 	xfs_ifork_t		*ifp;	/* inode fork data */
3002 	xfs_mount_t		*mp;	/* mount point structure */
3003 	xfs_bmbt_ptr_t		*pp;	/* ptr to block address */
3004 	xfs_bmbt_block_t	*rblock;/* root btree block */
3005 
3006 	ifp = XFS_IFORK_PTR(ip, whichfork);
3007 	ASSERT(ifp->if_flags & XFS_IFEXTENTS);
3008 	ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE);
3009 	rblock = ifp->if_broot;
3010 	ASSERT(be16_to_cpu(rblock->bb_level) == 1);
3011 	ASSERT(be16_to_cpu(rblock->bb_numrecs) == 1);
3012 	ASSERT(XFS_BMAP_BROOT_MAXRECS(ifp->if_broot_bytes) == 1);
3013 	mp = ip->i_mount;
3014 	pp = XFS_BMAP_BROOT_PTR_ADDR(rblock, 1, ifp->if_broot_bytes);
3015 	*logflagsp = 0;
3016 #ifdef DEBUG
3017 	if ((error = xfs_btree_check_lptr(cur, INT_GET(*pp, ARCH_CONVERT), 1)))
3018 		return error;
3019 #endif
3020 	cbno = INT_GET(*pp, ARCH_CONVERT);
3021 	if ((error = xfs_btree_read_bufl(mp, tp, cbno, 0, &cbp,
3022 			XFS_BMAP_BTREE_REF)))
3023 		return error;
3024 	cblock = XFS_BUF_TO_BMBT_BLOCK(cbp);
3025 	if ((error = xfs_btree_check_lblock(cur, cblock, 0, cbp)))
3026 		return error;
3027 	xfs_bmap_add_free(cbno, 1, cur->bc_private.b.flist, mp);
3028 	ip->i_d.di_nblocks--;
3029 	XFS_TRANS_MOD_DQUOT_BYINO(mp, tp, ip, XFS_TRANS_DQ_BCOUNT, -1L);
3030 	xfs_trans_binval(tp, cbp);
3031 	if (cur->bc_bufs[0] == cbp)
3032 		cur->bc_bufs[0] = NULL;
3033 	xfs_iroot_realloc(ip, -1, whichfork);
3034 	ASSERT(ifp->if_broot == NULL);
3035 	ASSERT((ifp->if_flags & XFS_IFBROOT) == 0);
3036 	XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_EXTENTS);
3037 	*logflagsp = XFS_ILOG_CORE | XFS_ILOG_FEXT(whichfork);
3038 	return 0;
3039 }
3040 
3041 /*
3042  * Called by xfs_bmapi to update file extent records and the btree
3043  * after removing space (or undoing a delayed allocation).
3044  */
3045 STATIC int				/* error */
xfs_bmap_del_extent(xfs_inode_t * ip,xfs_trans_t * tp,xfs_extnum_t idx,xfs_bmap_free_t * flist,xfs_btree_cur_t * cur,xfs_bmbt_irec_t * del,int * logflagsp,xfs_extdelta_t * delta,int whichfork,int rsvd)3046 xfs_bmap_del_extent(
3047 	xfs_inode_t		*ip,	/* incore inode pointer */
3048 	xfs_trans_t		*tp,	/* current transaction pointer */
3049 	xfs_extnum_t		idx,	/* extent number to update/delete */
3050 	xfs_bmap_free_t		*flist,	/* list of extents to be freed */
3051 	xfs_btree_cur_t		*cur,	/* if null, not a btree */
3052 	xfs_bmbt_irec_t		*del,	/* data to remove from extents */
3053 	int			*logflagsp, /* inode logging flags */
3054 	xfs_extdelta_t		*delta, /* Change made to incore extents */
3055 	int			whichfork, /* data or attr fork */
3056 	int			rsvd)	/* OK to allocate reserved blocks */
3057 {
3058 	xfs_filblks_t		da_new;	/* new delay-alloc indirect blocks */
3059 	xfs_filblks_t		da_old;	/* old delay-alloc indirect blocks */
3060 	xfs_fsblock_t		del_endblock=0;	/* first block past del */
3061 	xfs_fileoff_t		del_endoff;	/* first offset past del */
3062 	int			delay;	/* current block is delayed allocated */
3063 	int			do_fx;	/* free extent at end of routine */
3064 	xfs_bmbt_rec_t		*ep;	/* current extent entry pointer */
3065 	int			error;	/* error return value */
3066 	int			flags;	/* inode logging flags */
3067 #ifdef XFS_BMAP_TRACE
3068 	static char		fname[] = "xfs_bmap_del_extent";
3069 #endif
3070 	xfs_bmbt_irec_t		got;	/* current extent entry */
3071 	xfs_fileoff_t		got_endoff;	/* first offset past got */
3072 	int			i;	/* temp state */
3073 	xfs_ifork_t		*ifp;	/* inode fork pointer */
3074 	xfs_mount_t		*mp;	/* mount structure */
3075 	xfs_filblks_t		nblks;	/* quota/sb block count */
3076 	xfs_bmbt_irec_t		new;	/* new record to be inserted */
3077 	/* REFERENCED */
3078 	uint			qfield;	/* quota field to update */
3079 	xfs_filblks_t		temp;	/* for indirect length calculations */
3080 	xfs_filblks_t		temp2;	/* for indirect length calculations */
3081 
3082 	XFS_STATS_INC(xs_del_exlist);
3083 	mp = ip->i_mount;
3084 	ifp = XFS_IFORK_PTR(ip, whichfork);
3085 	ASSERT((idx >= 0) && (idx < ifp->if_bytes /
3086 		(uint)sizeof(xfs_bmbt_rec_t)));
3087 	ASSERT(del->br_blockcount > 0);
3088 	ep = xfs_iext_get_ext(ifp, idx);
3089 	xfs_bmbt_get_all(ep, &got);
3090 	ASSERT(got.br_startoff <= del->br_startoff);
3091 	del_endoff = del->br_startoff + del->br_blockcount;
3092 	got_endoff = got.br_startoff + got.br_blockcount;
3093 	ASSERT(got_endoff >= del_endoff);
3094 	delay = ISNULLSTARTBLOCK(got.br_startblock);
3095 	ASSERT(ISNULLSTARTBLOCK(del->br_startblock) == delay);
3096 	flags = 0;
3097 	qfield = 0;
3098 	error = 0;
3099 	/*
3100 	 * If deleting a real allocation, must free up the disk space.
3101 	 */
3102 	if (!delay) {
3103 		flags = XFS_ILOG_CORE;
3104 		/*
3105 		 * Realtime allocation.  Free it and record di_nblocks update.
3106 		 */
3107 		if (whichfork == XFS_DATA_FORK &&
3108 		    (ip->i_d.di_flags & XFS_DIFLAG_REALTIME)) {
3109 			xfs_fsblock_t	bno;
3110 			xfs_filblks_t	len;
3111 
3112 			ASSERT(do_mod(del->br_blockcount,
3113 				      mp->m_sb.sb_rextsize) == 0);
3114 			ASSERT(do_mod(del->br_startblock,
3115 				      mp->m_sb.sb_rextsize) == 0);
3116 			bno = del->br_startblock;
3117 			len = del->br_blockcount;
3118 			do_div(bno, mp->m_sb.sb_rextsize);
3119 			do_div(len, mp->m_sb.sb_rextsize);
3120 			if ((error = xfs_rtfree_extent(ip->i_transp, bno,
3121 					(xfs_extlen_t)len)))
3122 				goto done;
3123 			do_fx = 0;
3124 			nblks = len * mp->m_sb.sb_rextsize;
3125 			qfield = XFS_TRANS_DQ_RTBCOUNT;
3126 		}
3127 		/*
3128 		 * Ordinary allocation.
3129 		 */
3130 		else {
3131 			do_fx = 1;
3132 			nblks = del->br_blockcount;
3133 			qfield = XFS_TRANS_DQ_BCOUNT;
3134 		}
3135 		/*
3136 		 * Set up del_endblock and cur for later.
3137 		 */
3138 		del_endblock = del->br_startblock + del->br_blockcount;
3139 		if (cur) {
3140 			if ((error = xfs_bmbt_lookup_eq(cur, got.br_startoff,
3141 					got.br_startblock, got.br_blockcount,
3142 					&i)))
3143 				goto done;
3144 			ASSERT(i == 1);
3145 		}
3146 		da_old = da_new = 0;
3147 	} else {
3148 		da_old = STARTBLOCKVAL(got.br_startblock);
3149 		da_new = 0;
3150 		nblks = 0;
3151 		do_fx = 0;
3152 	}
3153 	/*
3154 	 * Set flag value to use in switch statement.
3155 	 * Left-contig is 2, right-contig is 1.
3156 	 */
3157 	switch (((got.br_startoff == del->br_startoff) << 1) |
3158 		(got_endoff == del_endoff)) {
3159 	case 3:
3160 		/*
3161 		 * Matches the whole extent.  Delete the entry.
3162 		 */
3163 		xfs_bmap_trace_delete(fname, "3", ip, idx, 1, whichfork);
3164 		xfs_iext_remove(ifp, idx, 1);
3165 		ifp->if_lastex = idx;
3166 		if (delay)
3167 			break;
3168 		XFS_IFORK_NEXT_SET(ip, whichfork,
3169 			XFS_IFORK_NEXTENTS(ip, whichfork) - 1);
3170 		flags |= XFS_ILOG_CORE;
3171 		if (!cur) {
3172 			flags |= XFS_ILOG_FEXT(whichfork);
3173 			break;
3174 		}
3175 		if ((error = xfs_bmbt_delete(cur, &i)))
3176 			goto done;
3177 		ASSERT(i == 1);
3178 		break;
3179 
3180 	case 2:
3181 		/*
3182 		 * Deleting the first part of the extent.
3183 		 */
3184 		xfs_bmap_trace_pre_update(fname, "2", ip, idx, whichfork);
3185 		xfs_bmbt_set_startoff(ep, del_endoff);
3186 		temp = got.br_blockcount - del->br_blockcount;
3187 		xfs_bmbt_set_blockcount(ep, temp);
3188 		ifp->if_lastex = idx;
3189 		if (delay) {
3190 			temp = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
3191 				da_old);
3192 			xfs_bmbt_set_startblock(ep, NULLSTARTBLOCK((int)temp));
3193 			xfs_bmap_trace_post_update(fname, "2", ip, idx,
3194 				whichfork);
3195 			da_new = temp;
3196 			break;
3197 		}
3198 		xfs_bmbt_set_startblock(ep, del_endblock);
3199 		xfs_bmap_trace_post_update(fname, "2", ip, idx, whichfork);
3200 		if (!cur) {
3201 			flags |= XFS_ILOG_FEXT(whichfork);
3202 			break;
3203 		}
3204 		if ((error = xfs_bmbt_update(cur, del_endoff, del_endblock,
3205 				got.br_blockcount - del->br_blockcount,
3206 				got.br_state)))
3207 			goto done;
3208 		break;
3209 
3210 	case 1:
3211 		/*
3212 		 * Deleting the last part of the extent.
3213 		 */
3214 		temp = got.br_blockcount - del->br_blockcount;
3215 		xfs_bmap_trace_pre_update(fname, "1", ip, idx, whichfork);
3216 		xfs_bmbt_set_blockcount(ep, temp);
3217 		ifp->if_lastex = idx;
3218 		if (delay) {
3219 			temp = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
3220 				da_old);
3221 			xfs_bmbt_set_startblock(ep, NULLSTARTBLOCK((int)temp));
3222 			xfs_bmap_trace_post_update(fname, "1", ip, idx,
3223 				whichfork);
3224 			da_new = temp;
3225 			break;
3226 		}
3227 		xfs_bmap_trace_post_update(fname, "1", ip, idx, whichfork);
3228 		if (!cur) {
3229 			flags |= XFS_ILOG_FEXT(whichfork);
3230 			break;
3231 		}
3232 		if ((error = xfs_bmbt_update(cur, got.br_startoff,
3233 				got.br_startblock,
3234 				got.br_blockcount - del->br_blockcount,
3235 				got.br_state)))
3236 			goto done;
3237 		break;
3238 
3239 	case 0:
3240 		/*
3241 		 * Deleting the middle of the extent.
3242 		 */
3243 		temp = del->br_startoff - got.br_startoff;
3244 		xfs_bmap_trace_pre_update(fname, "0", ip, idx, whichfork);
3245 		xfs_bmbt_set_blockcount(ep, temp);
3246 		new.br_startoff = del_endoff;
3247 		temp2 = got_endoff - del_endoff;
3248 		new.br_blockcount = temp2;
3249 		new.br_state = got.br_state;
3250 		if (!delay) {
3251 			new.br_startblock = del_endblock;
3252 			flags |= XFS_ILOG_CORE;
3253 			if (cur) {
3254 				if ((error = xfs_bmbt_update(cur,
3255 						got.br_startoff,
3256 						got.br_startblock, temp,
3257 						got.br_state)))
3258 					goto done;
3259 				if ((error = xfs_bmbt_increment(cur, 0, &i)))
3260 					goto done;
3261 				cur->bc_rec.b = new;
3262 				error = xfs_bmbt_insert(cur, &i);
3263 				if (error && error != ENOSPC)
3264 					goto done;
3265 				/*
3266 				 * If get no-space back from btree insert,
3267 				 * it tried a split, and we have a zero
3268 				 * block reservation.
3269 				 * Fix up our state and return the error.
3270 				 */
3271 				if (error == ENOSPC) {
3272 					/*
3273 					 * Reset the cursor, don't trust
3274 					 * it after any insert operation.
3275 					 */
3276 					if ((error = xfs_bmbt_lookup_eq(cur,
3277 							got.br_startoff,
3278 							got.br_startblock,
3279 							temp, &i)))
3280 						goto done;
3281 					ASSERT(i == 1);
3282 					/*
3283 					 * Update the btree record back
3284 					 * to the original value.
3285 					 */
3286 					if ((error = xfs_bmbt_update(cur,
3287 							got.br_startoff,
3288 							got.br_startblock,
3289 							got.br_blockcount,
3290 							got.br_state)))
3291 						goto done;
3292 					/*
3293 					 * Reset the extent record back
3294 					 * to the original value.
3295 					 */
3296 					xfs_bmbt_set_blockcount(ep,
3297 						got.br_blockcount);
3298 					flags = 0;
3299 					error = XFS_ERROR(ENOSPC);
3300 					goto done;
3301 				}
3302 				ASSERT(i == 1);
3303 			} else
3304 				flags |= XFS_ILOG_FEXT(whichfork);
3305 			XFS_IFORK_NEXT_SET(ip, whichfork,
3306 				XFS_IFORK_NEXTENTS(ip, whichfork) + 1);
3307 		} else {
3308 			ASSERT(whichfork == XFS_DATA_FORK);
3309 			temp = xfs_bmap_worst_indlen(ip, temp);
3310 			xfs_bmbt_set_startblock(ep, NULLSTARTBLOCK((int)temp));
3311 			temp2 = xfs_bmap_worst_indlen(ip, temp2);
3312 			new.br_startblock = NULLSTARTBLOCK((int)temp2);
3313 			da_new = temp + temp2;
3314 			while (da_new > da_old) {
3315 				if (temp) {
3316 					temp--;
3317 					da_new--;
3318 					xfs_bmbt_set_startblock(ep,
3319 						NULLSTARTBLOCK((int)temp));
3320 				}
3321 				if (da_new == da_old)
3322 					break;
3323 				if (temp2) {
3324 					temp2--;
3325 					da_new--;
3326 					new.br_startblock =
3327 						NULLSTARTBLOCK((int)temp2);
3328 				}
3329 			}
3330 		}
3331 		xfs_bmap_trace_post_update(fname, "0", ip, idx, whichfork);
3332 		xfs_bmap_trace_insert(fname, "0", ip, idx + 1, 1, &new, NULL,
3333 			whichfork);
3334 		xfs_iext_insert(ifp, idx + 1, 1, &new);
3335 		ifp->if_lastex = idx + 1;
3336 		break;
3337 	}
3338 	/*
3339 	 * If we need to, add to list of extents to delete.
3340 	 */
3341 	if (do_fx)
3342 		xfs_bmap_add_free(del->br_startblock, del->br_blockcount, flist,
3343 			mp);
3344 	/*
3345 	 * Adjust inode # blocks in the file.
3346 	 */
3347 	if (nblks)
3348 		ip->i_d.di_nblocks -= nblks;
3349 	/*
3350 	 * Adjust quota data.
3351 	 */
3352 	if (qfield)
3353 		XFS_TRANS_MOD_DQUOT_BYINO(mp, tp, ip, qfield, (long)-nblks);
3354 
3355 	/*
3356 	 * Account for change in delayed indirect blocks.
3357 	 * Nothing to do for disk quota accounting here.
3358 	 */
3359 	ASSERT(da_old >= da_new);
3360 	if (da_old > da_new)
3361 		xfs_mod_incore_sb(mp, XFS_SBS_FDBLOCKS, (int)(da_old - da_new),
3362 			rsvd);
3363 	if (delta) {
3364 		/* DELTA: report the original extent. */
3365 		if (delta->xed_startoff > got.br_startoff)
3366 			delta->xed_startoff = got.br_startoff;
3367 		if (delta->xed_blockcount < got.br_startoff+got.br_blockcount)
3368 			delta->xed_blockcount = got.br_startoff +
3369 							got.br_blockcount;
3370 	}
3371 done:
3372 	*logflagsp = flags;
3373 	return error;
3374 }
3375 
3376 /*
3377  * Remove the entry "free" from the free item list.  Prev points to the
3378  * previous entry, unless "free" is the head of the list.
3379  */
3380 STATIC void
xfs_bmap_del_free(xfs_bmap_free_t * flist,xfs_bmap_free_item_t * prev,xfs_bmap_free_item_t * free)3381 xfs_bmap_del_free(
3382 	xfs_bmap_free_t		*flist,	/* free item list header */
3383 	xfs_bmap_free_item_t	*prev,	/* previous item on list, if any */
3384 	xfs_bmap_free_item_t	*free)	/* list item to be freed */
3385 {
3386 	if (prev)
3387 		prev->xbfi_next = free->xbfi_next;
3388 	else
3389 		flist->xbf_first = free->xbfi_next;
3390 	flist->xbf_count--;
3391 	kmem_zone_free(xfs_bmap_free_item_zone, free);
3392 }
3393 
3394 /*
3395  * Convert an extents-format file into a btree-format file.
3396  * The new file will have a root block (in the inode) and a single child block.
3397  */
3398 STATIC int					/* error */
xfs_bmap_extents_to_btree(xfs_trans_t * tp,xfs_inode_t * ip,xfs_fsblock_t * firstblock,xfs_bmap_free_t * flist,xfs_btree_cur_t ** curp,int wasdel,int * logflagsp,int whichfork)3399 xfs_bmap_extents_to_btree(
3400 	xfs_trans_t		*tp,		/* transaction pointer */
3401 	xfs_inode_t		*ip,		/* incore inode pointer */
3402 	xfs_fsblock_t		*firstblock,	/* first-block-allocated */
3403 	xfs_bmap_free_t		*flist,		/* blocks freed in xaction */
3404 	xfs_btree_cur_t		**curp,		/* cursor returned to caller */
3405 	int			wasdel,		/* converting a delayed alloc */
3406 	int			*logflagsp,	/* inode logging flags */
3407 	int			whichfork)	/* data or attr fork */
3408 {
3409 	xfs_bmbt_block_t	*ablock;	/* allocated (child) bt block */
3410 	xfs_buf_t		*abp;		/* buffer for ablock */
3411 	xfs_alloc_arg_t		args;		/* allocation arguments */
3412 	xfs_bmbt_rec_t		*arp;		/* child record pointer */
3413 	xfs_bmbt_block_t	*block;		/* btree root block */
3414 	xfs_btree_cur_t		*cur;		/* bmap btree cursor */
3415 	xfs_bmbt_rec_t		*ep;		/* extent record pointer */
3416 	int			error;		/* error return value */
3417 	xfs_extnum_t		i, cnt;		/* extent record index */
3418 	xfs_ifork_t		*ifp;		/* inode fork pointer */
3419 	xfs_bmbt_key_t		*kp;		/* root block key pointer */
3420 	xfs_mount_t		*mp;		/* mount structure */
3421 	xfs_extnum_t		nextents;	/* number of file extents */
3422 	xfs_bmbt_ptr_t		*pp;		/* root block address pointer */
3423 
3424 	ifp = XFS_IFORK_PTR(ip, whichfork);
3425 	ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS);
3426 	ASSERT(ifp->if_ext_max ==
3427 	       XFS_IFORK_SIZE(ip, whichfork) / (uint)sizeof(xfs_bmbt_rec_t));
3428 	/*
3429 	 * Make space in the inode incore.
3430 	 */
3431 	xfs_iroot_realloc(ip, 1, whichfork);
3432 	ifp->if_flags |= XFS_IFBROOT;
3433 	/*
3434 	 * Fill in the root.
3435 	 */
3436 	block = ifp->if_broot;
3437 	block->bb_magic = cpu_to_be32(XFS_BMAP_MAGIC);
3438 	block->bb_level = cpu_to_be16(1);
3439 	block->bb_numrecs = cpu_to_be16(1);
3440 	block->bb_leftsib = cpu_to_be64(NULLDFSBNO);
3441 	block->bb_rightsib = cpu_to_be64(NULLDFSBNO);
3442 	/*
3443 	 * Need a cursor.  Can't allocate until bb_level is filled in.
3444 	 */
3445 	mp = ip->i_mount;
3446 	cur = xfs_btree_init_cursor(mp, tp, NULL, 0, XFS_BTNUM_BMAP, ip,
3447 		whichfork);
3448 	cur->bc_private.b.firstblock = *firstblock;
3449 	cur->bc_private.b.flist = flist;
3450 	cur->bc_private.b.flags = wasdel ? XFS_BTCUR_BPRV_WASDEL : 0;
3451 	/*
3452 	 * Convert to a btree with two levels, one record in root.
3453 	 */
3454 	XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_BTREE);
3455 	args.tp = tp;
3456 	args.mp = mp;
3457 	if (*firstblock == NULLFSBLOCK) {
3458 		args.type = XFS_ALLOCTYPE_START_BNO;
3459 		args.fsbno = XFS_INO_TO_FSB(mp, ip->i_ino);
3460 	} else if (flist->xbf_low) {
3461 		args.type = XFS_ALLOCTYPE_START_BNO;
3462 		args.fsbno = *firstblock;
3463 	} else {
3464 		args.type = XFS_ALLOCTYPE_NEAR_BNO;
3465 		args.fsbno = *firstblock;
3466 	}
3467 	args.minlen = args.maxlen = args.prod = 1;
3468 	args.total = args.minleft = args.alignment = args.mod = args.isfl =
3469 		args.minalignslop = 0;
3470 	args.wasdel = wasdel;
3471 	*logflagsp = 0;
3472 	if ((error = xfs_alloc_vextent(&args))) {
3473 		xfs_iroot_realloc(ip, -1, whichfork);
3474 		xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
3475 		return error;
3476 	}
3477 	/*
3478 	 * Allocation can't fail, the space was reserved.
3479 	 */
3480 	ASSERT(args.fsbno != NULLFSBLOCK);
3481 	ASSERT(*firstblock == NULLFSBLOCK ||
3482 	       args.agno == XFS_FSB_TO_AGNO(mp, *firstblock) ||
3483 	       (flist->xbf_low &&
3484 		args.agno > XFS_FSB_TO_AGNO(mp, *firstblock)));
3485 	*firstblock = cur->bc_private.b.firstblock = args.fsbno;
3486 	cur->bc_private.b.allocated++;
3487 	ip->i_d.di_nblocks++;
3488 	XFS_TRANS_MOD_DQUOT_BYINO(mp, tp, ip, XFS_TRANS_DQ_BCOUNT, 1L);
3489 	abp = xfs_btree_get_bufl(mp, tp, args.fsbno, 0);
3490 	/*
3491 	 * Fill in the child block.
3492 	 */
3493 	ablock = XFS_BUF_TO_BMBT_BLOCK(abp);
3494 	ablock->bb_magic = cpu_to_be32(XFS_BMAP_MAGIC);
3495 	ablock->bb_level = 0;
3496 	ablock->bb_leftsib = cpu_to_be64(NULLDFSBNO);
3497 	ablock->bb_rightsib = cpu_to_be64(NULLDFSBNO);
3498 	arp = XFS_BMAP_REC_IADDR(ablock, 1, cur);
3499 	nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
3500 	for (cnt = i = 0; i < nextents; i++) {
3501 		ep = xfs_iext_get_ext(ifp, i);
3502 		if (!ISNULLSTARTBLOCK(xfs_bmbt_get_startblock(ep))) {
3503 			arp->l0 = INT_GET(ep->l0, ARCH_CONVERT);
3504 			arp->l1 = INT_GET(ep->l1, ARCH_CONVERT);
3505 			arp++; cnt++;
3506 		}
3507 	}
3508 	ASSERT(cnt == XFS_IFORK_NEXTENTS(ip, whichfork));
3509 	ablock->bb_numrecs = cpu_to_be16(cnt);
3510 	/*
3511 	 * Fill in the root key and pointer.
3512 	 */
3513 	kp = XFS_BMAP_KEY_IADDR(block, 1, cur);
3514 	arp = XFS_BMAP_REC_IADDR(ablock, 1, cur);
3515 	INT_SET(kp->br_startoff, ARCH_CONVERT, xfs_bmbt_disk_get_startoff(arp));
3516 	pp = XFS_BMAP_PTR_IADDR(block, 1, cur);
3517 	INT_SET(*pp, ARCH_CONVERT, args.fsbno);
3518 	/*
3519 	 * Do all this logging at the end so that
3520 	 * the root is at the right level.
3521 	 */
3522 	xfs_bmbt_log_block(cur, abp, XFS_BB_ALL_BITS);
3523 	xfs_bmbt_log_recs(cur, abp, 1, be16_to_cpu(ablock->bb_numrecs));
3524 	ASSERT(*curp == NULL);
3525 	*curp = cur;
3526 	*logflagsp = XFS_ILOG_CORE | XFS_ILOG_FBROOT(whichfork);
3527 	return 0;
3528 }
3529 
3530 /*
3531  * Helper routine to reset inode di_forkoff field when switching
3532  * attribute fork from local to extent format - we reset it where
3533  * possible to make space available for inline data fork extents.
3534  */
3535 STATIC void
xfs_bmap_forkoff_reset(xfs_mount_t * mp,xfs_inode_t * ip,int whichfork)3536 xfs_bmap_forkoff_reset(
3537 	xfs_mount_t	*mp,
3538 	xfs_inode_t	*ip,
3539 	int		whichfork)
3540 {
3541 	if (whichfork == XFS_ATTR_FORK &&
3542 	    (ip->i_d.di_format != XFS_DINODE_FMT_DEV) &&
3543 	    (ip->i_d.di_format != XFS_DINODE_FMT_UUID) &&
3544 	    ((mp->m_attroffset >> 3) > ip->i_d.di_forkoff)) {
3545 		ip->i_d.di_forkoff = mp->m_attroffset >> 3;
3546 		ip->i_df.if_ext_max = XFS_IFORK_DSIZE(ip) /
3547 					(uint)sizeof(xfs_bmbt_rec_t);
3548 		ip->i_afp->if_ext_max = XFS_IFORK_ASIZE(ip) /
3549 					(uint)sizeof(xfs_bmbt_rec_t);
3550 	}
3551 }
3552 
3553 /*
3554  * Convert a local file to an extents file.
3555  * This code is out of bounds for data forks of regular files,
3556  * since the file data needs to get logged so things will stay consistent.
3557  * (The bmap-level manipulations are ok, though).
3558  */
3559 STATIC int				/* error */
xfs_bmap_local_to_extents(xfs_trans_t * tp,xfs_inode_t * ip,xfs_fsblock_t * firstblock,xfs_extlen_t total,int * logflagsp,int whichfork)3560 xfs_bmap_local_to_extents(
3561 	xfs_trans_t	*tp,		/* transaction pointer */
3562 	xfs_inode_t	*ip,		/* incore inode pointer */
3563 	xfs_fsblock_t	*firstblock,	/* first block allocated in xaction */
3564 	xfs_extlen_t	total,		/* total blocks needed by transaction */
3565 	int		*logflagsp,	/* inode logging flags */
3566 	int		whichfork)	/* data or attr fork */
3567 {
3568 	int		error;		/* error return value */
3569 	int		flags;		/* logging flags returned */
3570 #ifdef XFS_BMAP_TRACE
3571 	static char	fname[] = "xfs_bmap_local_to_extents";
3572 #endif
3573 	xfs_ifork_t	*ifp;		/* inode fork pointer */
3574 
3575 	/*
3576 	 * We don't want to deal with the case of keeping inode data inline yet.
3577 	 * So sending the data fork of a regular inode is invalid.
3578 	 */
3579 	ASSERT(!((ip->i_d.di_mode & S_IFMT) == S_IFREG &&
3580 		 whichfork == XFS_DATA_FORK));
3581 	ifp = XFS_IFORK_PTR(ip, whichfork);
3582 	ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL);
3583 	flags = 0;
3584 	error = 0;
3585 	if (ifp->if_bytes) {
3586 		xfs_alloc_arg_t	args;	/* allocation arguments */
3587 		xfs_buf_t	*bp;	/* buffer for extent block */
3588 		xfs_bmbt_rec_t	*ep;	/* extent record pointer */
3589 
3590 		args.tp = tp;
3591 		args.mp = ip->i_mount;
3592 		ASSERT((ifp->if_flags &
3593 			(XFS_IFINLINE|XFS_IFEXTENTS|XFS_IFEXTIREC)) == XFS_IFINLINE);
3594 		/*
3595 		 * Allocate a block.  We know we need only one, since the
3596 		 * file currently fits in an inode.
3597 		 */
3598 		if (*firstblock == NULLFSBLOCK) {
3599 			args.fsbno = XFS_INO_TO_FSB(args.mp, ip->i_ino);
3600 			args.type = XFS_ALLOCTYPE_START_BNO;
3601 		} else {
3602 			args.fsbno = *firstblock;
3603 			args.type = XFS_ALLOCTYPE_NEAR_BNO;
3604 		}
3605 		args.total = total;
3606 		args.mod = args.minleft = args.alignment = args.wasdel =
3607 			args.isfl = args.minalignslop = 0;
3608 		args.minlen = args.maxlen = args.prod = 1;
3609 		if ((error = xfs_alloc_vextent(&args)))
3610 			goto done;
3611 		/*
3612 		 * Can't fail, the space was reserved.
3613 		 */
3614 		ASSERT(args.fsbno != NULLFSBLOCK);
3615 		ASSERT(args.len == 1);
3616 		*firstblock = args.fsbno;
3617 		bp = xfs_btree_get_bufl(args.mp, tp, args.fsbno, 0);
3618 		memcpy((char *)XFS_BUF_PTR(bp), ifp->if_u1.if_data,
3619 			ifp->if_bytes);
3620 		xfs_trans_log_buf(tp, bp, 0, ifp->if_bytes - 1);
3621 		xfs_bmap_forkoff_reset(args.mp, ip, whichfork);
3622 		xfs_idata_realloc(ip, -ifp->if_bytes, whichfork);
3623 		xfs_iext_add(ifp, 0, 1);
3624 		ep = xfs_iext_get_ext(ifp, 0);
3625 		xfs_bmbt_set_allf(ep, 0, args.fsbno, 1, XFS_EXT_NORM);
3626 		xfs_bmap_trace_post_update(fname, "new", ip, 0, whichfork);
3627 		XFS_IFORK_NEXT_SET(ip, whichfork, 1);
3628 		ip->i_d.di_nblocks = 1;
3629 		XFS_TRANS_MOD_DQUOT_BYINO(args.mp, tp, ip,
3630 			XFS_TRANS_DQ_BCOUNT, 1L);
3631 		flags |= XFS_ILOG_FEXT(whichfork);
3632 	} else {
3633 		ASSERT(XFS_IFORK_NEXTENTS(ip, whichfork) == 0);
3634 		xfs_bmap_forkoff_reset(ip->i_mount, ip, whichfork);
3635 	}
3636 	ifp->if_flags &= ~XFS_IFINLINE;
3637 	ifp->if_flags |= XFS_IFEXTENTS;
3638 	XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_EXTENTS);
3639 	flags |= XFS_ILOG_CORE;
3640 done:
3641 	*logflagsp = flags;
3642 	return error;
3643 }
3644 
3645 /*
3646  * Search the extent records for the entry containing block bno.
3647  * If bno lies in a hole, point to the next entry.  If bno lies
3648  * past eof, *eofp will be set, and *prevp will contain the last
3649  * entry (null if none).  Else, *lastxp will be set to the index
3650  * of the found entry; *gotp will contain the entry.
3651  */
3652 xfs_bmbt_rec_t *			/* pointer to found extent entry */
xfs_bmap_search_multi_extents(xfs_ifork_t * ifp,xfs_fileoff_t bno,int * eofp,xfs_extnum_t * lastxp,xfs_bmbt_irec_t * gotp,xfs_bmbt_irec_t * prevp)3653 xfs_bmap_search_multi_extents(
3654 	xfs_ifork_t	*ifp,		/* inode fork pointer */
3655 	xfs_fileoff_t	bno,		/* block number searched for */
3656 	int		*eofp,		/* out: end of file found */
3657 	xfs_extnum_t	*lastxp,	/* out: last extent index */
3658 	xfs_bmbt_irec_t	*gotp,		/* out: extent entry found */
3659 	xfs_bmbt_irec_t	*prevp)		/* out: previous extent entry found */
3660 {
3661 	xfs_bmbt_rec_t	*ep;		/* extent record pointer */
3662 	xfs_extnum_t	lastx;		/* last extent index */
3663 
3664 	/*
3665 	 * Initialize the extent entry structure to catch access to
3666 	 * uninitialized br_startblock field.
3667 	 */
3668 	gotp->br_startoff = 0xffa5a5a5a5a5a5a5LL;
3669 	gotp->br_blockcount = 0xa55a5a5a5a5a5a5aLL;
3670 	gotp->br_state = XFS_EXT_INVALID;
3671 #if XFS_BIG_BLKNOS
3672 	gotp->br_startblock = 0xffffa5a5a5a5a5a5LL;
3673 #else
3674 	gotp->br_startblock = 0xffffa5a5;
3675 #endif
3676 	prevp->br_startoff = NULLFILEOFF;
3677 
3678 	ep = xfs_iext_bno_to_ext(ifp, bno, &lastx);
3679 	if (lastx > 0) {
3680 		xfs_bmbt_get_all(xfs_iext_get_ext(ifp, lastx - 1), prevp);
3681 	}
3682 	if (lastx < (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t))) {
3683 		xfs_bmbt_get_all(ep, gotp);
3684 		*eofp = 0;
3685 	} else {
3686 		if (lastx > 0) {
3687 			*gotp = *prevp;
3688 		}
3689 		*eofp = 1;
3690 		ep = NULL;
3691 	}
3692 	*lastxp = lastx;
3693 	return ep;
3694 }
3695 
3696 /*
3697  * Search the extents list for the inode, for the extent containing bno.
3698  * If bno lies in a hole, point to the next entry.  If bno lies past eof,
3699  * *eofp will be set, and *prevp will contain the last entry (null if none).
3700  * Else, *lastxp will be set to the index of the found
3701  * entry; *gotp will contain the entry.
3702  */
3703 STATIC xfs_bmbt_rec_t *                 /* pointer to found extent entry */
xfs_bmap_search_extents(xfs_inode_t * ip,xfs_fileoff_t bno,int whichfork,int * eofp,xfs_extnum_t * lastxp,xfs_bmbt_irec_t * gotp,xfs_bmbt_irec_t * prevp)3704 xfs_bmap_search_extents(
3705 	xfs_inode_t     *ip,            /* incore inode pointer */
3706 	xfs_fileoff_t   bno,            /* block number searched for */
3707 	int             whichfork,      /* data or attr fork */
3708 	int             *eofp,          /* out: end of file found */
3709 	xfs_extnum_t    *lastxp,        /* out: last extent index */
3710 	xfs_bmbt_irec_t *gotp,          /* out: extent entry found */
3711 	xfs_bmbt_irec_t *prevp)         /* out: previous extent entry found */
3712 {
3713 	xfs_ifork_t	*ifp;		/* inode fork pointer */
3714 	xfs_bmbt_rec_t  *ep;            /* extent record pointer */
3715 	int		rt;		/* realtime flag    */
3716 
3717 	XFS_STATS_INC(xs_look_exlist);
3718 	ifp = XFS_IFORK_PTR(ip, whichfork);
3719 
3720 	ep = xfs_bmap_search_multi_extents(ifp, bno, eofp, lastxp, gotp, prevp);
3721 
3722 	rt = (whichfork == XFS_DATA_FORK) && XFS_IS_REALTIME_INODE(ip);
3723 	if (unlikely(!rt && !gotp->br_startblock && (*lastxp != NULLEXTNUM))) {
3724                 cmn_err(CE_PANIC,"Access to block zero: fs: <%s> inode: %lld "
3725 			"start_block : %llx start_off : %llx blkcnt : %llx "
3726 			"extent-state : %x \n",
3727 			(ip->i_mount)->m_fsname, (long long)ip->i_ino,
3728 			(unsigned long long)gotp->br_startblock,
3729 			(unsigned long long)gotp->br_startoff,
3730 			(unsigned long long)gotp->br_blockcount,
3731 			gotp->br_state);
3732         }
3733         return ep;
3734 }
3735 
3736 
3737 #ifdef XFS_BMAP_TRACE
3738 ktrace_t	*xfs_bmap_trace_buf;
3739 
3740 /*
3741  * Add a bmap trace buffer entry.  Base routine for the others.
3742  */
3743 STATIC void
xfs_bmap_trace_addentry(int opcode,char * fname,char * desc,xfs_inode_t * ip,xfs_extnum_t idx,xfs_extnum_t cnt,xfs_bmbt_rec_t * r1,xfs_bmbt_rec_t * r2,int whichfork)3744 xfs_bmap_trace_addentry(
3745 	int		opcode,		/* operation */
3746 	char		*fname,		/* function name */
3747 	char		*desc,		/* operation description */
3748 	xfs_inode_t	*ip,		/* incore inode pointer */
3749 	xfs_extnum_t	idx,		/* index of entry(ies) */
3750 	xfs_extnum_t	cnt,		/* count of entries, 1 or 2 */
3751 	xfs_bmbt_rec_t	*r1,		/* first record */
3752 	xfs_bmbt_rec_t	*r2,		/* second record or null */
3753 	int		whichfork)	/* data or attr fork */
3754 {
3755 	xfs_bmbt_rec_t	tr2;
3756 
3757 	ASSERT(cnt == 1 || cnt == 2);
3758 	ASSERT(r1 != NULL);
3759 	if (cnt == 1) {
3760 		ASSERT(r2 == NULL);
3761 		r2 = &tr2;
3762 		memset(&tr2, 0, sizeof(tr2));
3763 	} else
3764 		ASSERT(r2 != NULL);
3765 	ktrace_enter(xfs_bmap_trace_buf,
3766 		(void *)(__psint_t)(opcode | (whichfork << 16)),
3767 		(void *)fname, (void *)desc, (void *)ip,
3768 		(void *)(__psint_t)idx,
3769 		(void *)(__psint_t)cnt,
3770 		(void *)(__psunsigned_t)(ip->i_ino >> 32),
3771 		(void *)(__psunsigned_t)(unsigned)ip->i_ino,
3772 		(void *)(__psunsigned_t)(r1->l0 >> 32),
3773 		(void *)(__psunsigned_t)(unsigned)(r1->l0),
3774 		(void *)(__psunsigned_t)(r1->l1 >> 32),
3775 		(void *)(__psunsigned_t)(unsigned)(r1->l1),
3776 		(void *)(__psunsigned_t)(r2->l0 >> 32),
3777 		(void *)(__psunsigned_t)(unsigned)(r2->l0),
3778 		(void *)(__psunsigned_t)(r2->l1 >> 32),
3779 		(void *)(__psunsigned_t)(unsigned)(r2->l1)
3780 		);
3781 	ASSERT(ip->i_xtrace);
3782 	ktrace_enter(ip->i_xtrace,
3783 		(void *)(__psint_t)(opcode | (whichfork << 16)),
3784 		(void *)fname, (void *)desc, (void *)ip,
3785 		(void *)(__psint_t)idx,
3786 		(void *)(__psint_t)cnt,
3787 		(void *)(__psunsigned_t)(ip->i_ino >> 32),
3788 		(void *)(__psunsigned_t)(unsigned)ip->i_ino,
3789 		(void *)(__psunsigned_t)(r1->l0 >> 32),
3790 		(void *)(__psunsigned_t)(unsigned)(r1->l0),
3791 		(void *)(__psunsigned_t)(r1->l1 >> 32),
3792 		(void *)(__psunsigned_t)(unsigned)(r1->l1),
3793 		(void *)(__psunsigned_t)(r2->l0 >> 32),
3794 		(void *)(__psunsigned_t)(unsigned)(r2->l0),
3795 		(void *)(__psunsigned_t)(r2->l1 >> 32),
3796 		(void *)(__psunsigned_t)(unsigned)(r2->l1)
3797 		);
3798 }
3799 
3800 /*
3801  * Add bmap trace entry prior to a call to xfs_iext_remove.
3802  */
3803 STATIC void
xfs_bmap_trace_delete(char * fname,char * desc,xfs_inode_t * ip,xfs_extnum_t idx,xfs_extnum_t cnt,int whichfork)3804 xfs_bmap_trace_delete(
3805 	char		*fname,		/* function name */
3806 	char		*desc,		/* operation description */
3807 	xfs_inode_t	*ip,		/* incore inode pointer */
3808 	xfs_extnum_t	idx,		/* index of entry(entries) deleted */
3809 	xfs_extnum_t	cnt,		/* count of entries deleted, 1 or 2 */
3810 	int		whichfork)	/* data or attr fork */
3811 {
3812 	xfs_ifork_t	*ifp;		/* inode fork pointer */
3813 
3814 	ifp = XFS_IFORK_PTR(ip, whichfork);
3815 	xfs_bmap_trace_addentry(XFS_BMAP_KTRACE_DELETE, fname, desc, ip, idx,
3816 		cnt, xfs_iext_get_ext(ifp, idx),
3817 		cnt == 2 ? xfs_iext_get_ext(ifp, idx + 1) : NULL,
3818 		whichfork);
3819 }
3820 
3821 /*
3822  * Add bmap trace entry prior to a call to xfs_iext_insert, or
3823  * reading in the extents list from the disk (in the btree).
3824  */
3825 STATIC void
xfs_bmap_trace_insert(char * fname,char * desc,xfs_inode_t * ip,xfs_extnum_t idx,xfs_extnum_t cnt,xfs_bmbt_irec_t * r1,xfs_bmbt_irec_t * r2,int whichfork)3826 xfs_bmap_trace_insert(
3827 	char		*fname,		/* function name */
3828 	char		*desc,		/* operation description */
3829 	xfs_inode_t	*ip,		/* incore inode pointer */
3830 	xfs_extnum_t	idx,		/* index of entry(entries) inserted */
3831 	xfs_extnum_t	cnt,		/* count of entries inserted, 1 or 2 */
3832 	xfs_bmbt_irec_t	*r1,		/* inserted record 1 */
3833 	xfs_bmbt_irec_t	*r2,		/* inserted record 2 or null */
3834 	int		whichfork)	/* data or attr fork */
3835 {
3836 	xfs_bmbt_rec_t	tr1;		/* compressed record 1 */
3837 	xfs_bmbt_rec_t	tr2;		/* compressed record 2 if needed */
3838 
3839 	xfs_bmbt_set_all(&tr1, r1);
3840 	if (cnt == 2) {
3841 		ASSERT(r2 != NULL);
3842 		xfs_bmbt_set_all(&tr2, r2);
3843 	} else {
3844 		ASSERT(cnt == 1);
3845 		ASSERT(r2 == NULL);
3846 	}
3847 	xfs_bmap_trace_addentry(XFS_BMAP_KTRACE_INSERT, fname, desc, ip, idx,
3848 		cnt, &tr1, cnt == 2 ? &tr2 : NULL, whichfork);
3849 }
3850 
3851 /*
3852  * Add bmap trace entry after updating an extent record in place.
3853  */
3854 STATIC void
xfs_bmap_trace_post_update(char * fname,char * desc,xfs_inode_t * ip,xfs_extnum_t idx,int whichfork)3855 xfs_bmap_trace_post_update(
3856 	char		*fname,		/* function name */
3857 	char		*desc,		/* operation description */
3858 	xfs_inode_t	*ip,		/* incore inode pointer */
3859 	xfs_extnum_t	idx,		/* index of entry updated */
3860 	int		whichfork)	/* data or attr fork */
3861 {
3862 	xfs_ifork_t	*ifp;		/* inode fork pointer */
3863 
3864 	ifp = XFS_IFORK_PTR(ip, whichfork);
3865 	xfs_bmap_trace_addentry(XFS_BMAP_KTRACE_POST_UP, fname, desc, ip, idx,
3866 		1, xfs_iext_get_ext(ifp, idx), NULL, whichfork);
3867 }
3868 
3869 /*
3870  * Add bmap trace entry prior to updating an extent record in place.
3871  */
3872 STATIC void
xfs_bmap_trace_pre_update(char * fname,char * desc,xfs_inode_t * ip,xfs_extnum_t idx,int whichfork)3873 xfs_bmap_trace_pre_update(
3874 	char		*fname,		/* function name */
3875 	char		*desc,		/* operation description */
3876 	xfs_inode_t	*ip,		/* incore inode pointer */
3877 	xfs_extnum_t	idx,		/* index of entry to be updated */
3878 	int		whichfork)	/* data or attr fork */
3879 {
3880 	xfs_ifork_t	*ifp;		/* inode fork pointer */
3881 
3882 	ifp = XFS_IFORK_PTR(ip, whichfork);
3883 	xfs_bmap_trace_addentry(XFS_BMAP_KTRACE_PRE_UP, fname, desc, ip, idx, 1,
3884 		xfs_iext_get_ext(ifp, idx), NULL, whichfork);
3885 }
3886 #endif	/* XFS_BMAP_TRACE */
3887 
3888 /*
3889  * Compute the worst-case number of indirect blocks that will be used
3890  * for ip's delayed extent of length "len".
3891  */
3892 STATIC xfs_filblks_t
xfs_bmap_worst_indlen(xfs_inode_t * ip,xfs_filblks_t len)3893 xfs_bmap_worst_indlen(
3894 	xfs_inode_t	*ip,		/* incore inode pointer */
3895 	xfs_filblks_t	len)		/* delayed extent length */
3896 {
3897 	int		level;		/* btree level number */
3898 	int		maxrecs;	/* maximum record count at this level */
3899 	xfs_mount_t	*mp;		/* mount structure */
3900 	xfs_filblks_t	rval;		/* return value */
3901 
3902 	mp = ip->i_mount;
3903 	maxrecs = mp->m_bmap_dmxr[0];
3904 	for (level = 0, rval = 0;
3905 	     level < XFS_BM_MAXLEVELS(mp, XFS_DATA_FORK);
3906 	     level++) {
3907 		len += maxrecs - 1;
3908 		do_div(len, maxrecs);
3909 		rval += len;
3910 		if (len == 1)
3911 			return rval + XFS_BM_MAXLEVELS(mp, XFS_DATA_FORK) -
3912 				level - 1;
3913 		if (level == 0)
3914 			maxrecs = mp->m_bmap_dmxr[1];
3915 	}
3916 	return rval;
3917 }
3918 
3919 #if defined(XFS_RW_TRACE)
3920 STATIC void
xfs_bunmap_trace(xfs_inode_t * ip,xfs_fileoff_t bno,xfs_filblks_t len,int flags,inst_t * ra)3921 xfs_bunmap_trace(
3922 	xfs_inode_t		*ip,
3923 	xfs_fileoff_t		bno,
3924 	xfs_filblks_t		len,
3925 	int			flags,
3926 	inst_t			*ra)
3927 {
3928 	if (ip->i_rwtrace == NULL)
3929 		return;
3930 	ktrace_enter(ip->i_rwtrace,
3931 		(void *)(__psint_t)XFS_BUNMAP,
3932 		(void *)ip,
3933 		(void *)(__psint_t)((ip->i_d.di_size >> 32) & 0xffffffff),
3934 		(void *)(__psint_t)(ip->i_d.di_size & 0xffffffff),
3935 		(void *)(__psint_t)(((xfs_dfiloff_t)bno >> 32) & 0xffffffff),
3936 		(void *)(__psint_t)((xfs_dfiloff_t)bno & 0xffffffff),
3937 		(void *)(__psint_t)len,
3938 		(void *)(__psint_t)flags,
3939 		(void *)current_cpu(),
3940 		(void *)ra,
3941 		(void *)0,
3942 		(void *)0,
3943 		(void *)0,
3944 		(void *)0,
3945 		(void *)0,
3946 		(void *)0);
3947 }
3948 #endif
3949 
3950 /*
3951  * Convert inode from non-attributed to attributed.
3952  * Must not be in a transaction, ip must not be locked.
3953  */
3954 int						/* error code */
xfs_bmap_add_attrfork(xfs_inode_t * ip,int size,int rsvd)3955 xfs_bmap_add_attrfork(
3956 	xfs_inode_t		*ip,		/* incore inode pointer */
3957 	int			size,		/* space new attribute needs */
3958 	int			rsvd)		/* xact may use reserved blks */
3959 {
3960 	xfs_fsblock_t		firstblock;	/* 1st block/ag allocated */
3961 	xfs_bmap_free_t		flist;		/* freed extent records */
3962 	xfs_mount_t		*mp;		/* mount structure */
3963 	xfs_trans_t		*tp;		/* transaction pointer */
3964 	unsigned long		s;		/* spinlock spl value */
3965 	int			blks;		/* space reservation */
3966 	int			version = 1;	/* superblock attr version */
3967 	int			committed;	/* xaction was committed */
3968 	int			logflags;	/* logging flags */
3969 	int			error;		/* error return value */
3970 
3971 	ASSERT(XFS_IFORK_Q(ip) == 0);
3972 	ASSERT(ip->i_df.if_ext_max ==
3973 	       XFS_IFORK_DSIZE(ip) / (uint)sizeof(xfs_bmbt_rec_t));
3974 
3975 	mp = ip->i_mount;
3976 	ASSERT(!XFS_NOT_DQATTACHED(mp, ip));
3977 	tp = xfs_trans_alloc(mp, XFS_TRANS_ADDAFORK);
3978 	blks = XFS_ADDAFORK_SPACE_RES(mp);
3979 	if (rsvd)
3980 		tp->t_flags |= XFS_TRANS_RESERVE;
3981 	if ((error = xfs_trans_reserve(tp, blks, XFS_ADDAFORK_LOG_RES(mp), 0,
3982 			XFS_TRANS_PERM_LOG_RES, XFS_ADDAFORK_LOG_COUNT)))
3983 		goto error0;
3984 	xfs_ilock(ip, XFS_ILOCK_EXCL);
3985 	error = XFS_TRANS_RESERVE_QUOTA_NBLKS(mp, tp, ip, blks, 0, rsvd ?
3986 			XFS_QMOPT_RES_REGBLKS | XFS_QMOPT_FORCE_RES :
3987 			XFS_QMOPT_RES_REGBLKS);
3988 	if (error) {
3989 		xfs_iunlock(ip, XFS_ILOCK_EXCL);
3990 		xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES);
3991 		return error;
3992 	}
3993 	if (XFS_IFORK_Q(ip))
3994 		goto error1;
3995 	if (ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS) {
3996 		/*
3997 		 * For inodes coming from pre-6.2 filesystems.
3998 		 */
3999 		ASSERT(ip->i_d.di_aformat == 0);
4000 		ip->i_d.di_aformat = XFS_DINODE_FMT_EXTENTS;
4001 	}
4002 	ASSERT(ip->i_d.di_anextents == 0);
4003 	VN_HOLD(XFS_ITOV(ip));
4004 	xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
4005 	xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
4006 	switch (ip->i_d.di_format) {
4007 	case XFS_DINODE_FMT_DEV:
4008 		ip->i_d.di_forkoff = roundup(sizeof(xfs_dev_t), 8) >> 3;
4009 		break;
4010 	case XFS_DINODE_FMT_UUID:
4011 		ip->i_d.di_forkoff = roundup(sizeof(uuid_t), 8) >> 3;
4012 		break;
4013 	case XFS_DINODE_FMT_LOCAL:
4014 	case XFS_DINODE_FMT_EXTENTS:
4015 	case XFS_DINODE_FMT_BTREE:
4016 		ip->i_d.di_forkoff = xfs_attr_shortform_bytesfit(ip, size);
4017 		if (!ip->i_d.di_forkoff)
4018 			ip->i_d.di_forkoff = mp->m_attroffset >> 3;
4019 		else if (mp->m_flags & XFS_MOUNT_ATTR2)
4020 			version = 2;
4021 		break;
4022 	default:
4023 		ASSERT(0);
4024 		error = XFS_ERROR(EINVAL);
4025 		goto error1;
4026 	}
4027 	ip->i_df.if_ext_max =
4028 		XFS_IFORK_DSIZE(ip) / (uint)sizeof(xfs_bmbt_rec_t);
4029 	ASSERT(ip->i_afp == NULL);
4030 	ip->i_afp = kmem_zone_zalloc(xfs_ifork_zone, KM_SLEEP);
4031 	ip->i_afp->if_ext_max =
4032 		XFS_IFORK_ASIZE(ip) / (uint)sizeof(xfs_bmbt_rec_t);
4033 	ip->i_afp->if_flags = XFS_IFEXTENTS;
4034 	logflags = 0;
4035 	XFS_BMAP_INIT(&flist, &firstblock);
4036 	switch (ip->i_d.di_format) {
4037 	case XFS_DINODE_FMT_LOCAL:
4038 		error = xfs_bmap_add_attrfork_local(tp, ip, &firstblock, &flist,
4039 			&logflags);
4040 		break;
4041 	case XFS_DINODE_FMT_EXTENTS:
4042 		error = xfs_bmap_add_attrfork_extents(tp, ip, &firstblock,
4043 			&flist, &logflags);
4044 		break;
4045 	case XFS_DINODE_FMT_BTREE:
4046 		error = xfs_bmap_add_attrfork_btree(tp, ip, &firstblock, &flist,
4047 			&logflags);
4048 		break;
4049 	default:
4050 		error = 0;
4051 		break;
4052 	}
4053 	if (logflags)
4054 		xfs_trans_log_inode(tp, ip, logflags);
4055 	if (error)
4056 		goto error2;
4057 	if (!XFS_SB_VERSION_HASATTR(&mp->m_sb) ||
4058 	   (!XFS_SB_VERSION_HASATTR2(&mp->m_sb) && version == 2)) {
4059 		__int64_t sbfields = 0;
4060 
4061 		s = XFS_SB_LOCK(mp);
4062 		if (!XFS_SB_VERSION_HASATTR(&mp->m_sb)) {
4063 			XFS_SB_VERSION_ADDATTR(&mp->m_sb);
4064 			sbfields |= XFS_SB_VERSIONNUM;
4065 		}
4066 		if (!XFS_SB_VERSION_HASATTR2(&mp->m_sb) && version == 2) {
4067 			XFS_SB_VERSION_ADDATTR2(&mp->m_sb);
4068 			sbfields |= (XFS_SB_VERSIONNUM | XFS_SB_FEATURES2);
4069 		}
4070 		if (sbfields) {
4071 			XFS_SB_UNLOCK(mp, s);
4072 			xfs_mod_sb(tp, sbfields);
4073 		} else
4074 			XFS_SB_UNLOCK(mp, s);
4075 	}
4076 	if ((error = xfs_bmap_finish(&tp, &flist, firstblock, &committed)))
4077 		goto error2;
4078 	error = xfs_trans_commit(tp, XFS_TRANS_PERM_LOG_RES, NULL);
4079 	ASSERT(ip->i_df.if_ext_max ==
4080 	       XFS_IFORK_DSIZE(ip) / (uint)sizeof(xfs_bmbt_rec_t));
4081 	return error;
4082 error2:
4083 	xfs_bmap_cancel(&flist);
4084 error1:
4085 	ASSERT(ismrlocked(&ip->i_lock,MR_UPDATE));
4086 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
4087 error0:
4088 	xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES|XFS_TRANS_ABORT);
4089 	ASSERT(ip->i_df.if_ext_max ==
4090 	       XFS_IFORK_DSIZE(ip) / (uint)sizeof(xfs_bmbt_rec_t));
4091 	return error;
4092 }
4093 
4094 /*
4095  * Add the extent to the list of extents to be free at transaction end.
4096  * The list is maintained sorted (by block number).
4097  */
4098 /* ARGSUSED */
4099 void
xfs_bmap_add_free(xfs_fsblock_t bno,xfs_filblks_t len,xfs_bmap_free_t * flist,xfs_mount_t * mp)4100 xfs_bmap_add_free(
4101 	xfs_fsblock_t		bno,		/* fs block number of extent */
4102 	xfs_filblks_t		len,		/* length of extent */
4103 	xfs_bmap_free_t		*flist,		/* list of extents */
4104 	xfs_mount_t		*mp)		/* mount point structure */
4105 {
4106 	xfs_bmap_free_item_t	*cur;		/* current (next) element */
4107 	xfs_bmap_free_item_t	*new;		/* new element */
4108 	xfs_bmap_free_item_t	*prev;		/* previous element */
4109 #ifdef DEBUG
4110 	xfs_agnumber_t		agno;
4111 	xfs_agblock_t		agbno;
4112 
4113 	ASSERT(bno != NULLFSBLOCK);
4114 	ASSERT(len > 0);
4115 	ASSERT(len <= MAXEXTLEN);
4116 	ASSERT(!ISNULLSTARTBLOCK(bno));
4117 	agno = XFS_FSB_TO_AGNO(mp, bno);
4118 	agbno = XFS_FSB_TO_AGBNO(mp, bno);
4119 	ASSERT(agno < mp->m_sb.sb_agcount);
4120 	ASSERT(agbno < mp->m_sb.sb_agblocks);
4121 	ASSERT(len < mp->m_sb.sb_agblocks);
4122 	ASSERT(agbno + len <= mp->m_sb.sb_agblocks);
4123 #endif
4124 	ASSERT(xfs_bmap_free_item_zone != NULL);
4125 	new = kmem_zone_alloc(xfs_bmap_free_item_zone, KM_SLEEP);
4126 	new->xbfi_startblock = bno;
4127 	new->xbfi_blockcount = (xfs_extlen_t)len;
4128 	for (prev = NULL, cur = flist->xbf_first;
4129 	     cur != NULL;
4130 	     prev = cur, cur = cur->xbfi_next) {
4131 		if (cur->xbfi_startblock >= bno)
4132 			break;
4133 	}
4134 	if (prev)
4135 		prev->xbfi_next = new;
4136 	else
4137 		flist->xbf_first = new;
4138 	new->xbfi_next = cur;
4139 	flist->xbf_count++;
4140 }
4141 
4142 /*
4143  * Compute and fill in the value of the maximum depth of a bmap btree
4144  * in this filesystem.  Done once, during mount.
4145  */
4146 void
xfs_bmap_compute_maxlevels(xfs_mount_t * mp,int whichfork)4147 xfs_bmap_compute_maxlevels(
4148 	xfs_mount_t	*mp,		/* file system mount structure */
4149 	int		whichfork)	/* data or attr fork */
4150 {
4151 	int		level;		/* btree level */
4152 	uint		maxblocks;	/* max blocks at this level */
4153 	uint		maxleafents;	/* max leaf entries possible */
4154 	int		maxrootrecs;	/* max records in root block */
4155 	int		minleafrecs;	/* min records in leaf block */
4156 	int		minnoderecs;	/* min records in node block */
4157 	int		sz;		/* root block size */
4158 
4159 	/*
4160 	 * The maximum number of extents in a file, hence the maximum
4161 	 * number of leaf entries, is controlled by the type of di_nextents
4162 	 * (a signed 32-bit number, xfs_extnum_t), or by di_anextents
4163 	 * (a signed 16-bit number, xfs_aextnum_t).
4164 	 */
4165 	if (whichfork == XFS_DATA_FORK) {
4166 		maxleafents = MAXEXTNUM;
4167 		sz = (mp->m_flags & XFS_MOUNT_ATTR2) ?
4168 			XFS_BMDR_SPACE_CALC(MINDBTPTRS) : mp->m_attroffset;
4169 	} else {
4170 		maxleafents = MAXAEXTNUM;
4171 		sz = (mp->m_flags & XFS_MOUNT_ATTR2) ?
4172 			XFS_BMDR_SPACE_CALC(MINABTPTRS) :
4173 			mp->m_sb.sb_inodesize - mp->m_attroffset;
4174 	}
4175 	maxrootrecs = (int)XFS_BTREE_BLOCK_MAXRECS(sz, xfs_bmdr, 0);
4176 	minleafrecs = mp->m_bmap_dmnr[0];
4177 	minnoderecs = mp->m_bmap_dmnr[1];
4178 	maxblocks = (maxleafents + minleafrecs - 1) / minleafrecs;
4179 	for (level = 1; maxblocks > 1; level++) {
4180 		if (maxblocks <= maxrootrecs)
4181 			maxblocks = 1;
4182 		else
4183 			maxblocks = (maxblocks + minnoderecs - 1) / minnoderecs;
4184 	}
4185 	mp->m_bm_maxlevels[whichfork] = level;
4186 }
4187 
4188 /*
4189  * Routine to be called at transaction's end by xfs_bmapi, xfs_bunmapi
4190  * caller.  Frees all the extents that need freeing, which must be done
4191  * last due to locking considerations.  We never free any extents in
4192  * the first transaction.  This is to allow the caller to make the first
4193  * transaction a synchronous one so that the pointers to the data being
4194  * broken in this transaction will be permanent before the data is actually
4195  * freed.  This is necessary to prevent blocks from being reallocated
4196  * and written to before the free and reallocation are actually permanent.
4197  * We do not just make the first transaction synchronous here, because
4198  * there are more efficient ways to gain the same protection in some cases
4199  * (see the file truncation code).
4200  *
4201  * Return 1 if the given transaction was committed and a new one
4202  * started, and 0 otherwise in the committed parameter.
4203  */
4204 /*ARGSUSED*/
4205 int						/* error */
xfs_bmap_finish(xfs_trans_t ** tp,xfs_bmap_free_t * flist,xfs_fsblock_t firstblock,int * committed)4206 xfs_bmap_finish(
4207 	xfs_trans_t		**tp,		/* transaction pointer addr */
4208 	xfs_bmap_free_t		*flist,		/* i/o: list extents to free */
4209 	xfs_fsblock_t		firstblock,	/* controlled ag for allocs */
4210 	int			*committed)	/* xact committed or not */
4211 {
4212 	xfs_efd_log_item_t	*efd;		/* extent free data */
4213 	xfs_efi_log_item_t	*efi;		/* extent free intention */
4214 	int			error;		/* error return value */
4215 	xfs_bmap_free_item_t	*free;		/* free extent item */
4216 	unsigned int		logres;		/* new log reservation */
4217 	unsigned int		logcount;	/* new log count */
4218 	xfs_mount_t		*mp;		/* filesystem mount structure */
4219 	xfs_bmap_free_item_t	*next;		/* next item on free list */
4220 	xfs_trans_t		*ntp;		/* new transaction pointer */
4221 
4222 	ASSERT((*tp)->t_flags & XFS_TRANS_PERM_LOG_RES);
4223 	if (flist->xbf_count == 0) {
4224 		*committed = 0;
4225 		return 0;
4226 	}
4227 	ntp = *tp;
4228 	efi = xfs_trans_get_efi(ntp, flist->xbf_count);
4229 	for (free = flist->xbf_first; free; free = free->xbfi_next)
4230 		xfs_trans_log_efi_extent(ntp, efi, free->xbfi_startblock,
4231 			free->xbfi_blockcount);
4232 	logres = ntp->t_log_res;
4233 	logcount = ntp->t_log_count;
4234 	ntp = xfs_trans_dup(*tp);
4235 	error = xfs_trans_commit(*tp, 0, NULL);
4236 	*tp = ntp;
4237 	*committed = 1;
4238 	/*
4239 	 * We have a new transaction, so we should return committed=1,
4240 	 * even though we're returning an error.
4241 	 */
4242 	if (error) {
4243 		return error;
4244 	}
4245 	if ((error = xfs_trans_reserve(ntp, 0, logres, 0, XFS_TRANS_PERM_LOG_RES,
4246 			logcount)))
4247 		return error;
4248 	efd = xfs_trans_get_efd(ntp, efi, flist->xbf_count);
4249 	for (free = flist->xbf_first; free != NULL; free = next) {
4250 		next = free->xbfi_next;
4251 		if ((error = xfs_free_extent(ntp, free->xbfi_startblock,
4252 				free->xbfi_blockcount))) {
4253 			/*
4254 			 * The bmap free list will be cleaned up at a
4255 			 * higher level.  The EFI will be canceled when
4256 			 * this transaction is aborted.
4257 			 * Need to force shutdown here to make sure it
4258 			 * happens, since this transaction may not be
4259 			 * dirty yet.
4260 			 */
4261 			mp = ntp->t_mountp;
4262 			if (!XFS_FORCED_SHUTDOWN(mp))
4263 				xfs_force_shutdown(mp,
4264 						   (error == EFSCORRUPTED) ?
4265 						   XFS_CORRUPT_INCORE :
4266 						   XFS_METADATA_IO_ERROR);
4267 			return error;
4268 		}
4269 		xfs_trans_log_efd_extent(ntp, efd, free->xbfi_startblock,
4270 			free->xbfi_blockcount);
4271 		xfs_bmap_del_free(flist, NULL, free);
4272 	}
4273 	return 0;
4274 }
4275 
4276 /*
4277  * Free up any items left in the list.
4278  */
4279 void
xfs_bmap_cancel(xfs_bmap_free_t * flist)4280 xfs_bmap_cancel(
4281 	xfs_bmap_free_t		*flist)	/* list of bmap_free_items */
4282 {
4283 	xfs_bmap_free_item_t	*free;	/* free list item */
4284 	xfs_bmap_free_item_t	*next;
4285 
4286 	if (flist->xbf_count == 0)
4287 		return;
4288 	ASSERT(flist->xbf_first != NULL);
4289 	for (free = flist->xbf_first; free; free = next) {
4290 		next = free->xbfi_next;
4291 		xfs_bmap_del_free(flist, NULL, free);
4292 	}
4293 	ASSERT(flist->xbf_count == 0);
4294 }
4295 
4296 /*
4297  * Returns the file-relative block number of the first unused block(s)
4298  * in the file with at least "len" logically contiguous blocks free.
4299  * This is the lowest-address hole if the file has holes, else the first block
4300  * past the end of file.
4301  * Return 0 if the file is currently local (in-inode).
4302  */
4303 int						/* error */
xfs_bmap_first_unused(xfs_trans_t * tp,xfs_inode_t * ip,xfs_extlen_t len,xfs_fileoff_t * first_unused,int whichfork)4304 xfs_bmap_first_unused(
4305 	xfs_trans_t	*tp,			/* transaction pointer */
4306 	xfs_inode_t	*ip,			/* incore inode */
4307 	xfs_extlen_t	len,			/* size of hole to find */
4308 	xfs_fileoff_t	*first_unused,		/* unused block */
4309 	int		whichfork)		/* data or attr fork */
4310 {
4311 	xfs_bmbt_rec_t	*ep;			/* pointer to an extent entry */
4312 	int		error;			/* error return value */
4313 	int		idx;			/* extent record index */
4314 	xfs_ifork_t	*ifp;			/* inode fork pointer */
4315 	xfs_fileoff_t	lastaddr;		/* last block number seen */
4316 	xfs_fileoff_t	lowest;			/* lowest useful block */
4317 	xfs_fileoff_t	max;			/* starting useful block */
4318 	xfs_fileoff_t	off;			/* offset for this block */
4319 	xfs_extnum_t	nextents;		/* number of extent entries */
4320 
4321 	ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE ||
4322 	       XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS ||
4323 	       XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL);
4324 	if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) {
4325 		*first_unused = 0;
4326 		return 0;
4327 	}
4328 	ifp = XFS_IFORK_PTR(ip, whichfork);
4329 	if (!(ifp->if_flags & XFS_IFEXTENTS) &&
4330 	    (error = xfs_iread_extents(tp, ip, whichfork)))
4331 		return error;
4332 	lowest = *first_unused;
4333 	nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
4334 	for (idx = 0, lastaddr = 0, max = lowest; idx < nextents; idx++) {
4335 		ep = xfs_iext_get_ext(ifp, idx);
4336 		off = xfs_bmbt_get_startoff(ep);
4337 		/*
4338 		 * See if the hole before this extent will work.
4339 		 */
4340 		if (off >= lowest + len && off - max >= len) {
4341 			*first_unused = max;
4342 			return 0;
4343 		}
4344 		lastaddr = off + xfs_bmbt_get_blockcount(ep);
4345 		max = XFS_FILEOFF_MAX(lastaddr, lowest);
4346 	}
4347 	*first_unused = max;
4348 	return 0;
4349 }
4350 
4351 /*
4352  * Returns the file-relative block number of the last block + 1 before
4353  * last_block (input value) in the file.
4354  * This is not based on i_size, it is based on the extent records.
4355  * Returns 0 for local files, as they do not have extent records.
4356  */
4357 int						/* error */
xfs_bmap_last_before(xfs_trans_t * tp,xfs_inode_t * ip,xfs_fileoff_t * last_block,int whichfork)4358 xfs_bmap_last_before(
4359 	xfs_trans_t	*tp,			/* transaction pointer */
4360 	xfs_inode_t	*ip,			/* incore inode */
4361 	xfs_fileoff_t	*last_block,		/* last block */
4362 	int		whichfork)		/* data or attr fork */
4363 {
4364 	xfs_fileoff_t	bno;			/* input file offset */
4365 	int		eof;			/* hit end of file */
4366 	xfs_bmbt_rec_t	*ep;			/* pointer to last extent */
4367 	int		error;			/* error return value */
4368 	xfs_bmbt_irec_t	got;			/* current extent value */
4369 	xfs_ifork_t	*ifp;			/* inode fork pointer */
4370 	xfs_extnum_t	lastx;			/* last extent used */
4371 	xfs_bmbt_irec_t	prev;			/* previous extent value */
4372 
4373 	if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE &&
4374 	    XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
4375 	    XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_LOCAL)
4376 	       return XFS_ERROR(EIO);
4377 	if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) {
4378 		*last_block = 0;
4379 		return 0;
4380 	}
4381 	ifp = XFS_IFORK_PTR(ip, whichfork);
4382 	if (!(ifp->if_flags & XFS_IFEXTENTS) &&
4383 	    (error = xfs_iread_extents(tp, ip, whichfork)))
4384 		return error;
4385 	bno = *last_block - 1;
4386 	ep = xfs_bmap_search_extents(ip, bno, whichfork, &eof, &lastx, &got,
4387 		&prev);
4388 	if (eof || xfs_bmbt_get_startoff(ep) > bno) {
4389 		if (prev.br_startoff == NULLFILEOFF)
4390 			*last_block = 0;
4391 		else
4392 			*last_block = prev.br_startoff + prev.br_blockcount;
4393 	}
4394 	/*
4395 	 * Otherwise *last_block is already the right answer.
4396 	 */
4397 	return 0;
4398 }
4399 
4400 /*
4401  * Returns the file-relative block number of the first block past eof in
4402  * the file.  This is not based on i_size, it is based on the extent records.
4403  * Returns 0 for local files, as they do not have extent records.
4404  */
4405 int						/* error */
xfs_bmap_last_offset(xfs_trans_t * tp,xfs_inode_t * ip,xfs_fileoff_t * last_block,int whichfork)4406 xfs_bmap_last_offset(
4407 	xfs_trans_t	*tp,			/* transaction pointer */
4408 	xfs_inode_t	*ip,			/* incore inode */
4409 	xfs_fileoff_t	*last_block,		/* last block */
4410 	int		whichfork)		/* data or attr fork */
4411 {
4412 	xfs_bmbt_rec_t	*ep;			/* pointer to last extent */
4413 	int		error;			/* error return value */
4414 	xfs_ifork_t	*ifp;			/* inode fork pointer */
4415 	xfs_extnum_t	nextents;		/* number of extent entries */
4416 
4417 	if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE &&
4418 	    XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
4419 	    XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_LOCAL)
4420 	       return XFS_ERROR(EIO);
4421 	if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) {
4422 		*last_block = 0;
4423 		return 0;
4424 	}
4425 	ifp = XFS_IFORK_PTR(ip, whichfork);
4426 	if (!(ifp->if_flags & XFS_IFEXTENTS) &&
4427 	    (error = xfs_iread_extents(tp, ip, whichfork)))
4428 		return error;
4429 	nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
4430 	if (!nextents) {
4431 		*last_block = 0;
4432 		return 0;
4433 	}
4434 	ep = xfs_iext_get_ext(ifp, nextents - 1);
4435 	*last_block = xfs_bmbt_get_startoff(ep) + xfs_bmbt_get_blockcount(ep);
4436 	return 0;
4437 }
4438 
4439 /*
4440  * Returns whether the selected fork of the inode has exactly one
4441  * block or not.  For the data fork we check this matches di_size,
4442  * implying the file's range is 0..bsize-1.
4443  */
4444 int					/* 1=>1 block, 0=>otherwise */
xfs_bmap_one_block(xfs_inode_t * ip,int whichfork)4445 xfs_bmap_one_block(
4446 	xfs_inode_t	*ip,		/* incore inode */
4447 	int		whichfork)	/* data or attr fork */
4448 {
4449 	xfs_bmbt_rec_t	*ep;		/* ptr to fork's extent */
4450 	xfs_ifork_t	*ifp;		/* inode fork pointer */
4451 	int		rval;		/* return value */
4452 	xfs_bmbt_irec_t	s;		/* internal version of extent */
4453 
4454 #ifndef DEBUG
4455 	if (whichfork == XFS_DATA_FORK)
4456 		return ip->i_d.di_size == ip->i_mount->m_sb.sb_blocksize;
4457 #endif	/* !DEBUG */
4458 	if (XFS_IFORK_NEXTENTS(ip, whichfork) != 1)
4459 		return 0;
4460 	if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
4461 		return 0;
4462 	ifp = XFS_IFORK_PTR(ip, whichfork);
4463 	ASSERT(ifp->if_flags & XFS_IFEXTENTS);
4464 	ep = xfs_iext_get_ext(ifp, 0);
4465 	xfs_bmbt_get_all(ep, &s);
4466 	rval = s.br_startoff == 0 && s.br_blockcount == 1;
4467 	if (rval && whichfork == XFS_DATA_FORK)
4468 		ASSERT(ip->i_d.di_size == ip->i_mount->m_sb.sb_blocksize);
4469 	return rval;
4470 }
4471 
4472 /*
4473  * Read in the extents to if_extents.
4474  * All inode fields are set up by caller, we just traverse the btree
4475  * and copy the records in. If the file system cannot contain unwritten
4476  * extents, the records are checked for no "state" flags.
4477  */
4478 int					/* error */
xfs_bmap_read_extents(xfs_trans_t * tp,xfs_inode_t * ip,int whichfork)4479 xfs_bmap_read_extents(
4480 	xfs_trans_t		*tp,	/* transaction pointer */
4481 	xfs_inode_t		*ip,	/* incore inode */
4482 	int			whichfork) /* data or attr fork */
4483 {
4484 	xfs_bmbt_block_t	*block;	/* current btree block */
4485 	xfs_fsblock_t		bno;	/* block # of "block" */
4486 	xfs_buf_t		*bp;	/* buffer for "block" */
4487 	int			error;	/* error return value */
4488 	xfs_exntfmt_t		exntf;	/* XFS_EXTFMT_NOSTATE, if checking */
4489 #ifdef XFS_BMAP_TRACE
4490 	static char		fname[] = "xfs_bmap_read_extents";
4491 #endif
4492 	xfs_extnum_t		i, j;	/* index into the extents list */
4493 	xfs_ifork_t		*ifp;	/* fork structure */
4494 	int			level;	/* btree level, for checking */
4495 	xfs_mount_t		*mp;	/* file system mount structure */
4496 	xfs_bmbt_ptr_t		*pp;	/* pointer to block address */
4497 	/* REFERENCED */
4498 	xfs_extnum_t		room;	/* number of entries there's room for */
4499 
4500 	bno = NULLFSBLOCK;
4501 	mp = ip->i_mount;
4502 	ifp = XFS_IFORK_PTR(ip, whichfork);
4503 	exntf = (whichfork != XFS_DATA_FORK) ? XFS_EXTFMT_NOSTATE :
4504 					XFS_EXTFMT_INODE(ip);
4505 	block = ifp->if_broot;
4506 	/*
4507 	 * Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out.
4508 	 */
4509 	level = be16_to_cpu(block->bb_level);
4510 	ASSERT(level > 0);
4511 	pp = XFS_BMAP_BROOT_PTR_ADDR(block, 1, ifp->if_broot_bytes);
4512 	ASSERT(INT_GET(*pp, ARCH_CONVERT) != NULLDFSBNO);
4513 	ASSERT(XFS_FSB_TO_AGNO(mp, INT_GET(*pp, ARCH_CONVERT)) < mp->m_sb.sb_agcount);
4514 	ASSERT(XFS_FSB_TO_AGBNO(mp, INT_GET(*pp, ARCH_CONVERT)) < mp->m_sb.sb_agblocks);
4515 	bno = INT_GET(*pp, ARCH_CONVERT);
4516 	/*
4517 	 * Go down the tree until leaf level is reached, following the first
4518 	 * pointer (leftmost) at each level.
4519 	 */
4520 	while (level-- > 0) {
4521 		if ((error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp,
4522 				XFS_BMAP_BTREE_REF)))
4523 			return error;
4524 		block = XFS_BUF_TO_BMBT_BLOCK(bp);
4525 		XFS_WANT_CORRUPTED_GOTO(
4526 			XFS_BMAP_SANITY_CHECK(mp, block, level),
4527 			error0);
4528 		if (level == 0)
4529 			break;
4530 		pp = XFS_BTREE_PTR_ADDR(mp->m_sb.sb_blocksize, xfs_bmbt, block,
4531 			1, mp->m_bmap_dmxr[1]);
4532 		XFS_WANT_CORRUPTED_GOTO(
4533 			XFS_FSB_SANITY_CHECK(mp, INT_GET(*pp, ARCH_CONVERT)),
4534 			error0);
4535 		bno = INT_GET(*pp, ARCH_CONVERT);
4536 		xfs_trans_brelse(tp, bp);
4537 	}
4538 	/*
4539 	 * Here with bp and block set to the leftmost leaf node in the tree.
4540 	 */
4541 	room = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
4542 	i = 0;
4543 	/*
4544 	 * Loop over all leaf nodes.  Copy information to the extent records.
4545 	 */
4546 	for (;;) {
4547 		xfs_bmbt_rec_t	*frp, *trp;
4548 		xfs_fsblock_t	nextbno;
4549 		xfs_extnum_t	num_recs;
4550 		xfs_extnum_t	start;
4551 
4552 
4553 		num_recs = be16_to_cpu(block->bb_numrecs);
4554 		if (unlikely(i + num_recs > room)) {
4555 			ASSERT(i + num_recs <= room);
4556 			xfs_fs_repair_cmn_err(CE_WARN, ip->i_mount,
4557 				"corrupt dinode %Lu, (btree extents).",
4558 				(unsigned long long) ip->i_ino);
4559 			XFS_ERROR_REPORT("xfs_bmap_read_extents(1)",
4560 					 XFS_ERRLEVEL_LOW,
4561 					ip->i_mount);
4562 			goto error0;
4563 		}
4564 		XFS_WANT_CORRUPTED_GOTO(
4565 			XFS_BMAP_SANITY_CHECK(mp, block, 0),
4566 			error0);
4567 		/*
4568 		 * Read-ahead the next leaf block, if any.
4569 		 */
4570 		nextbno = be64_to_cpu(block->bb_rightsib);
4571 		if (nextbno != NULLFSBLOCK)
4572 			xfs_btree_reada_bufl(mp, nextbno, 1);
4573 		/*
4574 		 * Copy records into the extent records.
4575 		 */
4576 		frp = XFS_BTREE_REC_ADDR(mp->m_sb.sb_blocksize, xfs_bmbt,
4577 			block, 1, mp->m_bmap_dmxr[0]);
4578 		start = i;
4579 		for (j = 0; j < num_recs; j++, i++, frp++) {
4580 			trp = xfs_iext_get_ext(ifp, i);
4581 			trp->l0 = INT_GET(frp->l0, ARCH_CONVERT);
4582 			trp->l1 = INT_GET(frp->l1, ARCH_CONVERT);
4583 		}
4584 		if (exntf == XFS_EXTFMT_NOSTATE) {
4585 			/*
4586 			 * Check all attribute bmap btree records and
4587 			 * any "older" data bmap btree records for a
4588 			 * set bit in the "extent flag" position.
4589 			 */
4590 			if (unlikely(xfs_check_nostate_extents(ifp,
4591 					start, num_recs))) {
4592 				XFS_ERROR_REPORT("xfs_bmap_read_extents(2)",
4593 						 XFS_ERRLEVEL_LOW,
4594 						 ip->i_mount);
4595 				goto error0;
4596 			}
4597 		}
4598 		xfs_trans_brelse(tp, bp);
4599 		bno = nextbno;
4600 		/*
4601 		 * If we've reached the end, stop.
4602 		 */
4603 		if (bno == NULLFSBLOCK)
4604 			break;
4605 		if ((error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp,
4606 				XFS_BMAP_BTREE_REF)))
4607 			return error;
4608 		block = XFS_BUF_TO_BMBT_BLOCK(bp);
4609 	}
4610 	ASSERT(i == (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t)));
4611 	ASSERT(i == XFS_IFORK_NEXTENTS(ip, whichfork));
4612 	xfs_bmap_trace_exlist(fname, ip, i, whichfork);
4613 	return 0;
4614 error0:
4615 	xfs_trans_brelse(tp, bp);
4616 	return XFS_ERROR(EFSCORRUPTED);
4617 }
4618 
4619 #ifdef XFS_BMAP_TRACE
4620 /*
4621  * Add bmap trace insert entries for all the contents of the extent records.
4622  */
4623 void
xfs_bmap_trace_exlist(char * fname,xfs_inode_t * ip,xfs_extnum_t cnt,int whichfork)4624 xfs_bmap_trace_exlist(
4625 	char		*fname,		/* function name */
4626 	xfs_inode_t	*ip,		/* incore inode pointer */
4627 	xfs_extnum_t	cnt,		/* count of entries in the list */
4628 	int		whichfork)	/* data or attr fork */
4629 {
4630 	xfs_bmbt_rec_t	*ep;		/* current extent record */
4631 	xfs_extnum_t	idx;		/* extent record index */
4632 	xfs_ifork_t	*ifp;		/* inode fork pointer */
4633 	xfs_bmbt_irec_t	s;		/* file extent record */
4634 
4635 	ifp = XFS_IFORK_PTR(ip, whichfork);
4636 	ASSERT(cnt == (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t)));
4637 	for (idx = 0; idx < cnt; idx++) {
4638 		ep = xfs_iext_get_ext(ifp, idx);
4639 		xfs_bmbt_get_all(ep, &s);
4640 		xfs_bmap_trace_insert(fname, "exlist", ip, idx, 1, &s, NULL,
4641 			whichfork);
4642 	}
4643 }
4644 #endif
4645 
4646 #ifdef DEBUG
4647 /*
4648  * Validate that the bmbt_irecs being returned from bmapi are valid
4649  * given the callers original parameters.  Specifically check the
4650  * ranges of the returned irecs to ensure that they only extent beyond
4651  * the given parameters if the XFS_BMAPI_ENTIRE flag was set.
4652  */
4653 STATIC void
xfs_bmap_validate_ret(xfs_fileoff_t bno,xfs_filblks_t len,int flags,xfs_bmbt_irec_t * mval,int nmap,int ret_nmap)4654 xfs_bmap_validate_ret(
4655 	xfs_fileoff_t		bno,
4656 	xfs_filblks_t		len,
4657 	int			flags,
4658 	xfs_bmbt_irec_t		*mval,
4659 	int			nmap,
4660 	int			ret_nmap)
4661 {
4662 	int			i;		/* index to map values */
4663 
4664 	ASSERT(ret_nmap <= nmap);
4665 
4666 	for (i = 0; i < ret_nmap; i++) {
4667 		ASSERT(mval[i].br_blockcount > 0);
4668 		if (!(flags & XFS_BMAPI_ENTIRE)) {
4669 			ASSERT(mval[i].br_startoff >= bno);
4670 			ASSERT(mval[i].br_blockcount <= len);
4671 			ASSERT(mval[i].br_startoff + mval[i].br_blockcount <=
4672 			       bno + len);
4673 		} else {
4674 			ASSERT(mval[i].br_startoff < bno + len);
4675 			ASSERT(mval[i].br_startoff + mval[i].br_blockcount >
4676 			       bno);
4677 		}
4678 		ASSERT(i == 0 ||
4679 		       mval[i - 1].br_startoff + mval[i - 1].br_blockcount ==
4680 		       mval[i].br_startoff);
4681 		if ((flags & XFS_BMAPI_WRITE) && !(flags & XFS_BMAPI_DELAY))
4682 			ASSERT(mval[i].br_startblock != DELAYSTARTBLOCK &&
4683 			       mval[i].br_startblock != HOLESTARTBLOCK);
4684 		ASSERT(mval[i].br_state == XFS_EXT_NORM ||
4685 		       mval[i].br_state == XFS_EXT_UNWRITTEN);
4686 	}
4687 }
4688 #endif /* DEBUG */
4689 
4690 
4691 /*
4692  * Map file blocks to filesystem blocks.
4693  * File range is given by the bno/len pair.
4694  * Adds blocks to file if a write ("flags & XFS_BMAPI_WRITE" set)
4695  * into a hole or past eof.
4696  * Only allocates blocks from a single allocation group,
4697  * to avoid locking problems.
4698  * The returned value in "firstblock" from the first call in a transaction
4699  * must be remembered and presented to subsequent calls in "firstblock".
4700  * An upper bound for the number of blocks to be allocated is supplied to
4701  * the first call in "total"; if no allocation group has that many free
4702  * blocks then the call will fail (return NULLFSBLOCK in "firstblock").
4703  */
4704 int					/* error */
xfs_bmapi(xfs_trans_t * tp,xfs_inode_t * ip,xfs_fileoff_t bno,xfs_filblks_t len,int flags,xfs_fsblock_t * firstblock,xfs_extlen_t total,xfs_bmbt_irec_t * mval,int * nmap,xfs_bmap_free_t * flist,xfs_extdelta_t * delta)4705 xfs_bmapi(
4706 	xfs_trans_t	*tp,		/* transaction pointer */
4707 	xfs_inode_t	*ip,		/* incore inode */
4708 	xfs_fileoff_t	bno,		/* starting file offs. mapped */
4709 	xfs_filblks_t	len,		/* length to map in file */
4710 	int		flags,		/* XFS_BMAPI_... */
4711 	xfs_fsblock_t	*firstblock,	/* first allocated block
4712 					   controls a.g. for allocs */
4713 	xfs_extlen_t	total,		/* total blocks needed */
4714 	xfs_bmbt_irec_t	*mval,		/* output: map values */
4715 	int		*nmap,		/* i/o: mval size/count */
4716 	xfs_bmap_free_t	*flist,		/* i/o: list extents to free */
4717 	xfs_extdelta_t	*delta)		/* o: change made to incore extents */
4718 {
4719 	xfs_fsblock_t	abno;		/* allocated block number */
4720 	xfs_extlen_t	alen;		/* allocated extent length */
4721 	xfs_fileoff_t	aoff;		/* allocated file offset */
4722 	xfs_bmalloca_t	bma;		/* args for xfs_bmap_alloc */
4723 	xfs_btree_cur_t	*cur;		/* bmap btree cursor */
4724 	xfs_fileoff_t	end;		/* end of mapped file region */
4725 	int		eof;		/* we've hit the end of extents */
4726 	xfs_bmbt_rec_t	*ep;		/* extent record pointer */
4727 	int		error;		/* error return */
4728 	xfs_bmbt_irec_t	got;		/* current file extent record */
4729 	xfs_ifork_t	*ifp;		/* inode fork pointer */
4730 	xfs_extlen_t	indlen;		/* indirect blocks length */
4731 	xfs_extnum_t	lastx;		/* last useful extent number */
4732 	int		logflags;	/* flags for transaction logging */
4733 	xfs_extlen_t	minleft;	/* min blocks left after allocation */
4734 	xfs_extlen_t	minlen;		/* min allocation size */
4735 	xfs_mount_t	*mp;		/* xfs mount structure */
4736 	int		n;		/* current extent index */
4737 	int		nallocs;	/* number of extents alloc\'d */
4738 	xfs_extnum_t	nextents;	/* number of extents in file */
4739 	xfs_fileoff_t	obno;		/* old block number (offset) */
4740 	xfs_bmbt_irec_t	prev;		/* previous file extent record */
4741 	int		tmp_logflags;	/* temp flags holder */
4742 	int		whichfork;	/* data or attr fork */
4743 	char		inhole;		/* current location is hole in file */
4744 	char		wasdelay;	/* old extent was delayed */
4745 	char		wr;		/* this is a write request */
4746 	char		rt;		/* this is a realtime file */
4747 #ifdef DEBUG
4748 	xfs_fileoff_t	orig_bno;	/* original block number value */
4749 	int		orig_flags;	/* original flags arg value */
4750 	xfs_filblks_t	orig_len;	/* original value of len arg */
4751 	xfs_bmbt_irec_t	*orig_mval;	/* original value of mval */
4752 	int		orig_nmap;	/* original value of *nmap */
4753 
4754 	orig_bno = bno;
4755 	orig_len = len;
4756 	orig_flags = flags;
4757 	orig_mval = mval;
4758 	orig_nmap = *nmap;
4759 #endif
4760 	ASSERT(*nmap >= 1);
4761 	ASSERT(*nmap <= XFS_BMAP_MAX_NMAP || !(flags & XFS_BMAPI_WRITE));
4762 	whichfork = (flags & XFS_BMAPI_ATTRFORK) ?
4763 		XFS_ATTR_FORK : XFS_DATA_FORK;
4764 	mp = ip->i_mount;
4765 	if (unlikely(XFS_TEST_ERROR(
4766 	    (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
4767 	     XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE &&
4768 	     XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_LOCAL),
4769 	     mp, XFS_ERRTAG_BMAPIFORMAT, XFS_RANDOM_BMAPIFORMAT))) {
4770 		XFS_ERROR_REPORT("xfs_bmapi", XFS_ERRLEVEL_LOW, mp);
4771 		return XFS_ERROR(EFSCORRUPTED);
4772 	}
4773 	if (XFS_FORCED_SHUTDOWN(mp))
4774 		return XFS_ERROR(EIO);
4775 	rt = (whichfork == XFS_DATA_FORK) && XFS_IS_REALTIME_INODE(ip);
4776 	ifp = XFS_IFORK_PTR(ip, whichfork);
4777 	ASSERT(ifp->if_ext_max ==
4778 	       XFS_IFORK_SIZE(ip, whichfork) / (uint)sizeof(xfs_bmbt_rec_t));
4779 	if ((wr = (flags & XFS_BMAPI_WRITE)) != 0)
4780 		XFS_STATS_INC(xs_blk_mapw);
4781 	else
4782 		XFS_STATS_INC(xs_blk_mapr);
4783 	/*
4784 	 * IGSTATE flag is used to combine extents which
4785 	 * differ only due to the state of the extents.
4786 	 * This technique is used from xfs_getbmap()
4787 	 * when the caller does not wish to see the
4788 	 * separation (which is the default).
4789 	 *
4790 	 * This technique is also used when writing a
4791 	 * buffer which has been partially written,
4792 	 * (usually by being flushed during a chunkread),
4793 	 * to ensure one write takes place. This also
4794 	 * prevents a change in the xfs inode extents at
4795 	 * this time, intentionally. This change occurs
4796 	 * on completion of the write operation, in
4797 	 * xfs_strat_comp(), where the xfs_bmapi() call
4798 	 * is transactioned, and the extents combined.
4799 	 */
4800 	if ((flags & XFS_BMAPI_IGSTATE) && wr)	/* if writing unwritten space */
4801 		wr = 0;				/* no allocations are allowed */
4802 	ASSERT(wr || !(flags & XFS_BMAPI_DELAY));
4803 	logflags = 0;
4804 	nallocs = 0;
4805 	cur = NULL;
4806 	if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) {
4807 		ASSERT(wr && tp);
4808 		if ((error = xfs_bmap_local_to_extents(tp, ip,
4809 				firstblock, total, &logflags, whichfork)))
4810 			goto error0;
4811 	}
4812 	if (wr && *firstblock == NULLFSBLOCK) {
4813 		if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE)
4814 			minleft = be16_to_cpu(ifp->if_broot->bb_level) + 1;
4815 		else
4816 			minleft = 1;
4817 	} else
4818 		minleft = 0;
4819 	if (!(ifp->if_flags & XFS_IFEXTENTS) &&
4820 	    (error = xfs_iread_extents(tp, ip, whichfork)))
4821 		goto error0;
4822 	ep = xfs_bmap_search_extents(ip, bno, whichfork, &eof, &lastx, &got,
4823 		&prev);
4824 	nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
4825 	n = 0;
4826 	end = bno + len;
4827 	obno = bno;
4828 	bma.ip = NULL;
4829 	if (delta) {
4830 		delta->xed_startoff = NULLFILEOFF;
4831 		delta->xed_blockcount = 0;
4832 	}
4833 	while (bno < end && n < *nmap) {
4834 		/*
4835 		 * Reading past eof, act as though there's a hole
4836 		 * up to end.
4837 		 */
4838 		if (eof && !wr)
4839 			got.br_startoff = end;
4840 		inhole = eof || got.br_startoff > bno;
4841 		wasdelay = wr && !inhole && !(flags & XFS_BMAPI_DELAY) &&
4842 			ISNULLSTARTBLOCK(got.br_startblock);
4843 		/*
4844 		 * First, deal with the hole before the allocated space
4845 		 * that we found, if any.
4846 		 */
4847 		if (wr && (inhole || wasdelay)) {
4848 			/*
4849 			 * For the wasdelay case, we could also just
4850 			 * allocate the stuff asked for in this bmap call
4851 			 * but that wouldn't be as good.
4852 			 */
4853 			if (wasdelay && !(flags & XFS_BMAPI_EXACT)) {
4854 				alen = (xfs_extlen_t)got.br_blockcount;
4855 				aoff = got.br_startoff;
4856 				if (lastx != NULLEXTNUM && lastx) {
4857 					ep = xfs_iext_get_ext(ifp, lastx - 1);
4858 					xfs_bmbt_get_all(ep, &prev);
4859 				}
4860 			} else if (wasdelay) {
4861 				alen = (xfs_extlen_t)
4862 					XFS_FILBLKS_MIN(len,
4863 						(got.br_startoff +
4864 						 got.br_blockcount) - bno);
4865 				aoff = bno;
4866 			} else {
4867 				alen = (xfs_extlen_t)
4868 					XFS_FILBLKS_MIN(len, MAXEXTLEN);
4869 				if (!eof)
4870 					alen = (xfs_extlen_t)
4871 						XFS_FILBLKS_MIN(alen,
4872 							got.br_startoff - bno);
4873 				aoff = bno;
4874 			}
4875 			minlen = (flags & XFS_BMAPI_CONTIG) ? alen : 1;
4876 			if (flags & XFS_BMAPI_DELAY) {
4877 				xfs_extlen_t	extsz;
4878 
4879 				/* Figure out the extent size, adjust alen */
4880 				if (rt) {
4881 					if (!(extsz = ip->i_d.di_extsize))
4882 						extsz = mp->m_sb.sb_rextsize;
4883 				} else {
4884 					extsz = ip->i_d.di_extsize;
4885 				}
4886 				if (extsz) {
4887 					error = xfs_bmap_extsize_align(mp,
4888 							&got, &prev, extsz,
4889 							rt, eof,
4890 							flags&XFS_BMAPI_DELAY,
4891 							flags&XFS_BMAPI_CONVERT,
4892 							&aoff, &alen);
4893 					ASSERT(!error);
4894 				}
4895 
4896 				if (rt)
4897 					extsz = alen / mp->m_sb.sb_rextsize;
4898 
4899 				/*
4900 				 * Make a transaction-less quota reservation for
4901 				 * delayed allocation blocks. This number gets
4902 				 * adjusted later.  We return if we haven't
4903 				 * allocated blocks already inside this loop.
4904 				 */
4905 				if ((error = XFS_TRANS_RESERVE_QUOTA_NBLKS(
4906 						mp, NULL, ip, (long)alen, 0,
4907 						rt ? XFS_QMOPT_RES_RTBLKS :
4908 						     XFS_QMOPT_RES_REGBLKS))) {
4909 					if (n == 0) {
4910 						*nmap = 0;
4911 						ASSERT(cur == NULL);
4912 						return error;
4913 					}
4914 					break;
4915 				}
4916 
4917 				/*
4918 				 * Split changing sb for alen and indlen since
4919 				 * they could be coming from different places.
4920 				 */
4921 				indlen = (xfs_extlen_t)
4922 					xfs_bmap_worst_indlen(ip, alen);
4923 				ASSERT(indlen > 0);
4924 
4925 				if (rt) {
4926 					error = xfs_mod_incore_sb(mp,
4927 							XFS_SBS_FREXTENTS,
4928 							-(extsz), (flags &
4929 							XFS_BMAPI_RSVBLOCKS));
4930 				} else {
4931 					error = xfs_mod_incore_sb(mp,
4932 							XFS_SBS_FDBLOCKS,
4933 							-(alen), (flags &
4934 							XFS_BMAPI_RSVBLOCKS));
4935 				}
4936 				if (!error) {
4937 					error = xfs_mod_incore_sb(mp,
4938 							XFS_SBS_FDBLOCKS,
4939 							-(indlen), (flags &
4940 							XFS_BMAPI_RSVBLOCKS));
4941 					if (error && rt)
4942 						xfs_mod_incore_sb(mp,
4943 							XFS_SBS_FREXTENTS,
4944 							extsz, (flags &
4945 							XFS_BMAPI_RSVBLOCKS));
4946 					else if (error)
4947 						xfs_mod_incore_sb(mp,
4948 							XFS_SBS_FDBLOCKS,
4949 							alen, (flags &
4950 							XFS_BMAPI_RSVBLOCKS));
4951 				}
4952 
4953 				if (error) {
4954 					if (XFS_IS_QUOTA_ON(mp))
4955 						/* unreserve the blocks now */
4956 						(void)
4957 						XFS_TRANS_UNRESERVE_QUOTA_NBLKS(
4958 							mp, NULL, ip,
4959 							(long)alen, 0, rt ?
4960 							XFS_QMOPT_RES_RTBLKS :
4961 							XFS_QMOPT_RES_REGBLKS);
4962 					break;
4963 				}
4964 
4965 				ip->i_delayed_blks += alen;
4966 				abno = NULLSTARTBLOCK(indlen);
4967 			} else {
4968 				/*
4969 				 * If first time, allocate and fill in
4970 				 * once-only bma fields.
4971 				 */
4972 				if (bma.ip == NULL) {
4973 					bma.tp = tp;
4974 					bma.ip = ip;
4975 					bma.prevp = &prev;
4976 					bma.gotp = &got;
4977 					bma.total = total;
4978 					bma.userdata = 0;
4979 				}
4980 				/* Indicate if this is the first user data
4981 				 * in the file, or just any user data.
4982 				 */
4983 				if (!(flags & XFS_BMAPI_METADATA)) {
4984 					bma.userdata = (aoff == 0) ?
4985 						XFS_ALLOC_INITIAL_USER_DATA :
4986 						XFS_ALLOC_USERDATA;
4987 				}
4988 				/*
4989 				 * Fill in changeable bma fields.
4990 				 */
4991 				bma.eof = eof;
4992 				bma.firstblock = *firstblock;
4993 				bma.alen = alen;
4994 				bma.off = aoff;
4995 				bma.conv = (flags & XFS_BMAPI_CONVERT) != 0;
4996 				bma.wasdel = wasdelay;
4997 				bma.minlen = minlen;
4998 				bma.low = flist->xbf_low;
4999 				bma.minleft = minleft;
5000 				/*
5001 				 * Only want to do the alignment at the
5002 				 * eof if it is userdata and allocation length
5003 				 * is larger than a stripe unit.
5004 				 */
5005 				if (mp->m_dalign && alen >= mp->m_dalign &&
5006 				    (!(flags & XFS_BMAPI_METADATA)) &&
5007 				    (whichfork == XFS_DATA_FORK)) {
5008 					if ((error = xfs_bmap_isaeof(ip, aoff,
5009 							whichfork, &bma.aeof)))
5010 						goto error0;
5011 				} else
5012 					bma.aeof = 0;
5013 				/*
5014 				 * Call allocator.
5015 				 */
5016 				if ((error = xfs_bmap_alloc(&bma)))
5017 					goto error0;
5018 				/*
5019 				 * Copy out result fields.
5020 				 */
5021 				abno = bma.rval;
5022 				if ((flist->xbf_low = bma.low))
5023 					minleft = 0;
5024 				alen = bma.alen;
5025 				aoff = bma.off;
5026 				ASSERT(*firstblock == NULLFSBLOCK ||
5027 				       XFS_FSB_TO_AGNO(mp, *firstblock) ==
5028 				       XFS_FSB_TO_AGNO(mp, bma.firstblock) ||
5029 				       (flist->xbf_low &&
5030 					XFS_FSB_TO_AGNO(mp, *firstblock) <
5031 					XFS_FSB_TO_AGNO(mp, bma.firstblock)));
5032 				*firstblock = bma.firstblock;
5033 				if (cur)
5034 					cur->bc_private.b.firstblock =
5035 						*firstblock;
5036 				if (abno == NULLFSBLOCK)
5037 					break;
5038 				if ((ifp->if_flags & XFS_IFBROOT) && !cur) {
5039 					cur = xfs_btree_init_cursor(mp,
5040 						tp, NULL, 0, XFS_BTNUM_BMAP,
5041 						ip, whichfork);
5042 					cur->bc_private.b.firstblock =
5043 						*firstblock;
5044 					cur->bc_private.b.flist = flist;
5045 				}
5046 				/*
5047 				 * Bump the number of extents we've allocated
5048 				 * in this call.
5049 				 */
5050 				nallocs++;
5051 			}
5052 			if (cur)
5053 				cur->bc_private.b.flags =
5054 					wasdelay ? XFS_BTCUR_BPRV_WASDEL : 0;
5055 			got.br_startoff = aoff;
5056 			got.br_startblock = abno;
5057 			got.br_blockcount = alen;
5058 			got.br_state = XFS_EXT_NORM;	/* assume normal */
5059 			/*
5060 			 * Determine state of extent, and the filesystem.
5061 			 * A wasdelay extent has been initialized, so
5062 			 * shouldn't be flagged as unwritten.
5063 			 */
5064 			if (wr && XFS_SB_VERSION_HASEXTFLGBIT(&mp->m_sb)) {
5065 				if (!wasdelay && (flags & XFS_BMAPI_PREALLOC))
5066 					got.br_state = XFS_EXT_UNWRITTEN;
5067 			}
5068 			error = xfs_bmap_add_extent(ip, lastx, &cur, &got,
5069 				firstblock, flist, &tmp_logflags, delta,
5070 				whichfork, (flags & XFS_BMAPI_RSVBLOCKS));
5071 			logflags |= tmp_logflags;
5072 			if (error)
5073 				goto error0;
5074 			lastx = ifp->if_lastex;
5075 			ep = xfs_iext_get_ext(ifp, lastx);
5076 			nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
5077 			xfs_bmbt_get_all(ep, &got);
5078 			ASSERT(got.br_startoff <= aoff);
5079 			ASSERT(got.br_startoff + got.br_blockcount >=
5080 				aoff + alen);
5081 #ifdef DEBUG
5082 			if (flags & XFS_BMAPI_DELAY) {
5083 				ASSERT(ISNULLSTARTBLOCK(got.br_startblock));
5084 				ASSERT(STARTBLOCKVAL(got.br_startblock) > 0);
5085 			}
5086 			ASSERT(got.br_state == XFS_EXT_NORM ||
5087 			       got.br_state == XFS_EXT_UNWRITTEN);
5088 #endif
5089 			/*
5090 			 * Fall down into the found allocated space case.
5091 			 */
5092 		} else if (inhole) {
5093 			/*
5094 			 * Reading in a hole.
5095 			 */
5096 			mval->br_startoff = bno;
5097 			mval->br_startblock = HOLESTARTBLOCK;
5098 			mval->br_blockcount =
5099 				XFS_FILBLKS_MIN(len, got.br_startoff - bno);
5100 			mval->br_state = XFS_EXT_NORM;
5101 			bno += mval->br_blockcount;
5102 			len -= mval->br_blockcount;
5103 			mval++;
5104 			n++;
5105 			continue;
5106 		}
5107 		/*
5108 		 * Then deal with the allocated space we found.
5109 		 */
5110 		ASSERT(ep != NULL);
5111 		if (!(flags & XFS_BMAPI_ENTIRE) &&
5112 		    (got.br_startoff + got.br_blockcount > obno)) {
5113 			if (obno > bno)
5114 				bno = obno;
5115 			ASSERT((bno >= obno) || (n == 0));
5116 			ASSERT(bno < end);
5117 			mval->br_startoff = bno;
5118 			if (ISNULLSTARTBLOCK(got.br_startblock)) {
5119 				ASSERT(!wr || (flags & XFS_BMAPI_DELAY));
5120 				mval->br_startblock = DELAYSTARTBLOCK;
5121 			} else
5122 				mval->br_startblock =
5123 					got.br_startblock +
5124 					(bno - got.br_startoff);
5125 			/*
5126 			 * Return the minimum of what we got and what we
5127 			 * asked for for the length.  We can use the len
5128 			 * variable here because it is modified below
5129 			 * and we could have been there before coming
5130 			 * here if the first part of the allocation
5131 			 * didn't overlap what was asked for.
5132 			 */
5133 			mval->br_blockcount =
5134 				XFS_FILBLKS_MIN(end - bno, got.br_blockcount -
5135 					(bno - got.br_startoff));
5136 			mval->br_state = got.br_state;
5137 			ASSERT(mval->br_blockcount <= len);
5138 		} else {
5139 			*mval = got;
5140 			if (ISNULLSTARTBLOCK(mval->br_startblock)) {
5141 				ASSERT(!wr || (flags & XFS_BMAPI_DELAY));
5142 				mval->br_startblock = DELAYSTARTBLOCK;
5143 			}
5144 		}
5145 
5146 		/*
5147 		 * Check if writing previously allocated but
5148 		 * unwritten extents.
5149 		 */
5150 		if (wr && mval->br_state == XFS_EXT_UNWRITTEN &&
5151 		    ((flags & (XFS_BMAPI_PREALLOC|XFS_BMAPI_DELAY)) == 0)) {
5152 			/*
5153 			 * Modify (by adding) the state flag, if writing.
5154 			 */
5155 			ASSERT(mval->br_blockcount <= len);
5156 			if ((ifp->if_flags & XFS_IFBROOT) && !cur) {
5157 				cur = xfs_btree_init_cursor(mp,
5158 					tp, NULL, 0, XFS_BTNUM_BMAP,
5159 					ip, whichfork);
5160 				cur->bc_private.b.firstblock =
5161 					*firstblock;
5162 				cur->bc_private.b.flist = flist;
5163 			}
5164 			mval->br_state = XFS_EXT_NORM;
5165 			error = xfs_bmap_add_extent(ip, lastx, &cur, mval,
5166 				firstblock, flist, &tmp_logflags, delta,
5167 				whichfork, (flags & XFS_BMAPI_RSVBLOCKS));
5168 			logflags |= tmp_logflags;
5169 			if (error)
5170 				goto error0;
5171 			lastx = ifp->if_lastex;
5172 			ep = xfs_iext_get_ext(ifp, lastx);
5173 			nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
5174 			xfs_bmbt_get_all(ep, &got);
5175 			/*
5176 			 * We may have combined previously unwritten
5177 			 * space with written space, so generate
5178 			 * another request.
5179 			 */
5180 			if (mval->br_blockcount < len)
5181 				continue;
5182 		}
5183 
5184 		ASSERT((flags & XFS_BMAPI_ENTIRE) ||
5185 		       ((mval->br_startoff + mval->br_blockcount) <= end));
5186 		ASSERT((flags & XFS_BMAPI_ENTIRE) ||
5187 		       (mval->br_blockcount <= len) ||
5188 		       (mval->br_startoff < obno));
5189 		bno = mval->br_startoff + mval->br_blockcount;
5190 		len = end - bno;
5191 		if (n > 0 && mval->br_startoff == mval[-1].br_startoff) {
5192 			ASSERT(mval->br_startblock == mval[-1].br_startblock);
5193 			ASSERT(mval->br_blockcount > mval[-1].br_blockcount);
5194 			ASSERT(mval->br_state == mval[-1].br_state);
5195 			mval[-1].br_blockcount = mval->br_blockcount;
5196 			mval[-1].br_state = mval->br_state;
5197 		} else if (n > 0 && mval->br_startblock != DELAYSTARTBLOCK &&
5198 			   mval[-1].br_startblock != DELAYSTARTBLOCK &&
5199 			   mval[-1].br_startblock != HOLESTARTBLOCK &&
5200 			   mval->br_startblock ==
5201 			   mval[-1].br_startblock + mval[-1].br_blockcount &&
5202 			   ((flags & XFS_BMAPI_IGSTATE) ||
5203 				mval[-1].br_state == mval->br_state)) {
5204 			ASSERT(mval->br_startoff ==
5205 			       mval[-1].br_startoff + mval[-1].br_blockcount);
5206 			mval[-1].br_blockcount += mval->br_blockcount;
5207 		} else if (n > 0 &&
5208 			   mval->br_startblock == DELAYSTARTBLOCK &&
5209 			   mval[-1].br_startblock == DELAYSTARTBLOCK &&
5210 			   mval->br_startoff ==
5211 			   mval[-1].br_startoff + mval[-1].br_blockcount) {
5212 			mval[-1].br_blockcount += mval->br_blockcount;
5213 			mval[-1].br_state = mval->br_state;
5214 		} else if (!((n == 0) &&
5215 			     ((mval->br_startoff + mval->br_blockcount) <=
5216 			      obno))) {
5217 			mval++;
5218 			n++;
5219 		}
5220 		/*
5221 		 * If we're done, stop now.  Stop when we've allocated
5222 		 * XFS_BMAP_MAX_NMAP extents no matter what.  Otherwise
5223 		 * the transaction may get too big.
5224 		 */
5225 		if (bno >= end || n >= *nmap || nallocs >= *nmap)
5226 			break;
5227 		/*
5228 		 * Else go on to the next record.
5229 		 */
5230 		ep = xfs_iext_get_ext(ifp, ++lastx);
5231 		if (lastx >= nextents) {
5232 			eof = 1;
5233 			prev = got;
5234 		} else
5235 			xfs_bmbt_get_all(ep, &got);
5236 	}
5237 	ifp->if_lastex = lastx;
5238 	*nmap = n;
5239 	/*
5240 	 * Transform from btree to extents, give it cur.
5241 	 */
5242 	if (tp && XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE &&
5243 	    XFS_IFORK_NEXTENTS(ip, whichfork) <= ifp->if_ext_max) {
5244 		ASSERT(wr && cur);
5245 		error = xfs_bmap_btree_to_extents(tp, ip, cur,
5246 			&tmp_logflags, whichfork);
5247 		logflags |= tmp_logflags;
5248 		if (error)
5249 			goto error0;
5250 	}
5251 	ASSERT(ifp->if_ext_max ==
5252 	       XFS_IFORK_SIZE(ip, whichfork) / (uint)sizeof(xfs_bmbt_rec_t));
5253 	ASSERT(XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE ||
5254 	       XFS_IFORK_NEXTENTS(ip, whichfork) > ifp->if_ext_max);
5255 	error = 0;
5256 	if (delta && delta->xed_startoff != NULLFILEOFF) {
5257 		/* A change was actually made.
5258 		 * Note that delta->xed_blockount is an offset at this
5259 		 * point and needs to be converted to a block count.
5260 		 */
5261 		ASSERT(delta->xed_blockcount > delta->xed_startoff);
5262 		delta->xed_blockcount -= delta->xed_startoff;
5263 	}
5264 error0:
5265 	/*
5266 	 * Log everything.  Do this after conversion, there's no point in
5267 	 * logging the extent records if we've converted to btree format.
5268 	 */
5269 	if ((logflags & XFS_ILOG_FEXT(whichfork)) &&
5270 	    XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
5271 		logflags &= ~XFS_ILOG_FEXT(whichfork);
5272 	else if ((logflags & XFS_ILOG_FBROOT(whichfork)) &&
5273 		 XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE)
5274 		logflags &= ~XFS_ILOG_FBROOT(whichfork);
5275 	/*
5276 	 * Log whatever the flags say, even if error.  Otherwise we might miss
5277 	 * detecting a case where the data is changed, there's an error,
5278 	 * and it's not logged so we don't shutdown when we should.
5279 	 */
5280 	if (logflags) {
5281 		ASSERT(tp && wr);
5282 		xfs_trans_log_inode(tp, ip, logflags);
5283 	}
5284 	if (cur) {
5285 		if (!error) {
5286 			ASSERT(*firstblock == NULLFSBLOCK ||
5287 			       XFS_FSB_TO_AGNO(mp, *firstblock) ==
5288 			       XFS_FSB_TO_AGNO(mp,
5289 				       cur->bc_private.b.firstblock) ||
5290 			       (flist->xbf_low &&
5291 				XFS_FSB_TO_AGNO(mp, *firstblock) <
5292 				XFS_FSB_TO_AGNO(mp,
5293 					cur->bc_private.b.firstblock)));
5294 			*firstblock = cur->bc_private.b.firstblock;
5295 		}
5296 		xfs_btree_del_cursor(cur,
5297 			error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
5298 	}
5299 	if (!error)
5300 		xfs_bmap_validate_ret(orig_bno, orig_len, orig_flags, orig_mval,
5301 			orig_nmap, *nmap);
5302 	return error;
5303 }
5304 
5305 /*
5306  * Map file blocks to filesystem blocks, simple version.
5307  * One block (extent) only, read-only.
5308  * For flags, only the XFS_BMAPI_ATTRFORK flag is examined.
5309  * For the other flag values, the effect is as if XFS_BMAPI_METADATA
5310  * was set and all the others were clear.
5311  */
5312 int						/* error */
xfs_bmapi_single(xfs_trans_t * tp,xfs_inode_t * ip,int whichfork,xfs_fsblock_t * fsb,xfs_fileoff_t bno)5313 xfs_bmapi_single(
5314 	xfs_trans_t	*tp,		/* transaction pointer */
5315 	xfs_inode_t	*ip,		/* incore inode */
5316 	int		whichfork,	/* data or attr fork */
5317 	xfs_fsblock_t	*fsb,		/* output: mapped block */
5318 	xfs_fileoff_t	bno)		/* starting file offs. mapped */
5319 {
5320 	int		eof;		/* we've hit the end of extents */
5321 	int		error;		/* error return */
5322 	xfs_bmbt_irec_t	got;		/* current file extent record */
5323 	xfs_ifork_t	*ifp;		/* inode fork pointer */
5324 	xfs_extnum_t	lastx;		/* last useful extent number */
5325 	xfs_bmbt_irec_t	prev;		/* previous file extent record */
5326 
5327 	ifp = XFS_IFORK_PTR(ip, whichfork);
5328 	if (unlikely(
5329 	    XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE &&
5330 	    XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)) {
5331 	       XFS_ERROR_REPORT("xfs_bmapi_single", XFS_ERRLEVEL_LOW,
5332 				ip->i_mount);
5333 	       return XFS_ERROR(EFSCORRUPTED);
5334 	}
5335 	if (XFS_FORCED_SHUTDOWN(ip->i_mount))
5336 		return XFS_ERROR(EIO);
5337 	XFS_STATS_INC(xs_blk_mapr);
5338 	if (!(ifp->if_flags & XFS_IFEXTENTS) &&
5339 	    (error = xfs_iread_extents(tp, ip, whichfork)))
5340 		return error;
5341 	(void)xfs_bmap_search_extents(ip, bno, whichfork, &eof, &lastx, &got,
5342 		&prev);
5343 	/*
5344 	 * Reading past eof, act as though there's a hole
5345 	 * up to end.
5346 	 */
5347 	if (eof || got.br_startoff > bno) {
5348 		*fsb = NULLFSBLOCK;
5349 		return 0;
5350 	}
5351 	ASSERT(!ISNULLSTARTBLOCK(got.br_startblock));
5352 	ASSERT(bno < got.br_startoff + got.br_blockcount);
5353 	*fsb = got.br_startblock + (bno - got.br_startoff);
5354 	ifp->if_lastex = lastx;
5355 	return 0;
5356 }
5357 
5358 /*
5359  * Unmap (remove) blocks from a file.
5360  * If nexts is nonzero then the number of extents to remove is limited to
5361  * that value.  If not all extents in the block range can be removed then
5362  * *done is set.
5363  */
5364 int						/* error */
xfs_bunmapi(xfs_trans_t * tp,struct xfs_inode * ip,xfs_fileoff_t bno,xfs_filblks_t len,int flags,xfs_extnum_t nexts,xfs_fsblock_t * firstblock,xfs_bmap_free_t * flist,xfs_extdelta_t * delta,int * done)5365 xfs_bunmapi(
5366 	xfs_trans_t		*tp,		/* transaction pointer */
5367 	struct xfs_inode	*ip,		/* incore inode */
5368 	xfs_fileoff_t		bno,		/* starting offset to unmap */
5369 	xfs_filblks_t		len,		/* length to unmap in file */
5370 	int			flags,		/* misc flags */
5371 	xfs_extnum_t		nexts,		/* number of extents max */
5372 	xfs_fsblock_t		*firstblock,	/* first allocated block
5373 						   controls a.g. for allocs */
5374 	xfs_bmap_free_t		*flist,		/* i/o: list extents to free */
5375 	xfs_extdelta_t		*delta,		/* o: change made to incore
5376 						   extents */
5377 	int			*done)		/* set if not done yet */
5378 {
5379 	xfs_btree_cur_t		*cur;		/* bmap btree cursor */
5380 	xfs_bmbt_irec_t		del;		/* extent being deleted */
5381 	int			eof;		/* is deleting at eof */
5382 	xfs_bmbt_rec_t		*ep;		/* extent record pointer */
5383 	int			error;		/* error return value */
5384 	xfs_extnum_t		extno;		/* extent number in list */
5385 	xfs_bmbt_irec_t		got;		/* current extent record */
5386 	xfs_ifork_t		*ifp;		/* inode fork pointer */
5387 	int			isrt;		/* freeing in rt area */
5388 	xfs_extnum_t		lastx;		/* last extent index used */
5389 	int			logflags;	/* transaction logging flags */
5390 	xfs_extlen_t		mod;		/* rt extent offset */
5391 	xfs_mount_t		*mp;		/* mount structure */
5392 	xfs_extnum_t		nextents;	/* number of file extents */
5393 	xfs_bmbt_irec_t		prev;		/* previous extent record */
5394 	xfs_fileoff_t		start;		/* first file offset deleted */
5395 	int			tmp_logflags;	/* partial logging flags */
5396 	int			wasdel;		/* was a delayed alloc extent */
5397 	int			whichfork;	/* data or attribute fork */
5398 	int			rsvd;		/* OK to allocate reserved blocks */
5399 	xfs_fsblock_t		sum;
5400 
5401 	xfs_bunmap_trace(ip, bno, len, flags, (inst_t *)__return_address);
5402 	whichfork = (flags & XFS_BMAPI_ATTRFORK) ?
5403 		XFS_ATTR_FORK : XFS_DATA_FORK;
5404 	ifp = XFS_IFORK_PTR(ip, whichfork);
5405 	if (unlikely(
5406 	    XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
5407 	    XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE)) {
5408 		XFS_ERROR_REPORT("xfs_bunmapi", XFS_ERRLEVEL_LOW,
5409 				 ip->i_mount);
5410 		return XFS_ERROR(EFSCORRUPTED);
5411 	}
5412 	mp = ip->i_mount;
5413 	if (XFS_FORCED_SHUTDOWN(mp))
5414 		return XFS_ERROR(EIO);
5415 	rsvd = (flags & XFS_BMAPI_RSVBLOCKS) != 0;
5416 	ASSERT(len > 0);
5417 	ASSERT(nexts >= 0);
5418 	ASSERT(ifp->if_ext_max ==
5419 	       XFS_IFORK_SIZE(ip, whichfork) / (uint)sizeof(xfs_bmbt_rec_t));
5420 	if (!(ifp->if_flags & XFS_IFEXTENTS) &&
5421 	    (error = xfs_iread_extents(tp, ip, whichfork)))
5422 		return error;
5423 	nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
5424 	if (nextents == 0) {
5425 		*done = 1;
5426 		return 0;
5427 	}
5428 	XFS_STATS_INC(xs_blk_unmap);
5429 	isrt = (whichfork == XFS_DATA_FORK) && XFS_IS_REALTIME_INODE(ip);
5430 	start = bno;
5431 	bno = start + len - 1;
5432 	ep = xfs_bmap_search_extents(ip, bno, whichfork, &eof, &lastx, &got,
5433 		&prev);
5434 	if (delta) {
5435 		delta->xed_startoff = NULLFILEOFF;
5436 		delta->xed_blockcount = 0;
5437 	}
5438 	/*
5439 	 * Check to see if the given block number is past the end of the
5440 	 * file, back up to the last block if so...
5441 	 */
5442 	if (eof) {
5443 		ep = xfs_iext_get_ext(ifp, --lastx);
5444 		xfs_bmbt_get_all(ep, &got);
5445 		bno = got.br_startoff + got.br_blockcount - 1;
5446 	}
5447 	logflags = 0;
5448 	if (ifp->if_flags & XFS_IFBROOT) {
5449 		ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE);
5450 		cur = xfs_btree_init_cursor(mp, tp, NULL, 0, XFS_BTNUM_BMAP, ip,
5451 			whichfork);
5452 		cur->bc_private.b.firstblock = *firstblock;
5453 		cur->bc_private.b.flist = flist;
5454 		cur->bc_private.b.flags = 0;
5455 	} else
5456 		cur = NULL;
5457 	extno = 0;
5458 	while (bno != (xfs_fileoff_t)-1 && bno >= start && lastx >= 0 &&
5459 	       (nexts == 0 || extno < nexts)) {
5460 		/*
5461 		 * Is the found extent after a hole in which bno lives?
5462 		 * Just back up to the previous extent, if so.
5463 		 */
5464 		if (got.br_startoff > bno) {
5465 			if (--lastx < 0)
5466 				break;
5467 			ep = xfs_iext_get_ext(ifp, lastx);
5468 			xfs_bmbt_get_all(ep, &got);
5469 		}
5470 		/*
5471 		 * Is the last block of this extent before the range
5472 		 * we're supposed to delete?  If so, we're done.
5473 		 */
5474 		bno = XFS_FILEOFF_MIN(bno,
5475 			got.br_startoff + got.br_blockcount - 1);
5476 		if (bno < start)
5477 			break;
5478 		/*
5479 		 * Then deal with the (possibly delayed) allocated space
5480 		 * we found.
5481 		 */
5482 		ASSERT(ep != NULL);
5483 		del = got;
5484 		wasdel = ISNULLSTARTBLOCK(del.br_startblock);
5485 		if (got.br_startoff < start) {
5486 			del.br_startoff = start;
5487 			del.br_blockcount -= start - got.br_startoff;
5488 			if (!wasdel)
5489 				del.br_startblock += start - got.br_startoff;
5490 		}
5491 		if (del.br_startoff + del.br_blockcount > bno + 1)
5492 			del.br_blockcount = bno + 1 - del.br_startoff;
5493 		sum = del.br_startblock + del.br_blockcount;
5494 		if (isrt &&
5495 		    (mod = do_mod(sum, mp->m_sb.sb_rextsize))) {
5496 			/*
5497 			 * Realtime extent not lined up at the end.
5498 			 * The extent could have been split into written
5499 			 * and unwritten pieces, or we could just be
5500 			 * unmapping part of it.  But we can't really
5501 			 * get rid of part of a realtime extent.
5502 			 */
5503 			if (del.br_state == XFS_EXT_UNWRITTEN ||
5504 			    !XFS_SB_VERSION_HASEXTFLGBIT(&mp->m_sb)) {
5505 				/*
5506 				 * This piece is unwritten, or we're not
5507 				 * using unwritten extents.  Skip over it.
5508 				 */
5509 				ASSERT(bno >= mod);
5510 				bno -= mod > del.br_blockcount ?
5511 					del.br_blockcount : mod;
5512 				if (bno < got.br_startoff) {
5513 					if (--lastx >= 0)
5514 						xfs_bmbt_get_all(xfs_iext_get_ext(
5515 							ifp, lastx), &got);
5516 				}
5517 				continue;
5518 			}
5519 			/*
5520 			 * It's written, turn it unwritten.
5521 			 * This is better than zeroing it.
5522 			 */
5523 			ASSERT(del.br_state == XFS_EXT_NORM);
5524 			ASSERT(xfs_trans_get_block_res(tp) > 0);
5525 			/*
5526 			 * If this spans a realtime extent boundary,
5527 			 * chop it back to the start of the one we end at.
5528 			 */
5529 			if (del.br_blockcount > mod) {
5530 				del.br_startoff += del.br_blockcount - mod;
5531 				del.br_startblock += del.br_blockcount - mod;
5532 				del.br_blockcount = mod;
5533 			}
5534 			del.br_state = XFS_EXT_UNWRITTEN;
5535 			error = xfs_bmap_add_extent(ip, lastx, &cur, &del,
5536 				firstblock, flist, &logflags, delta,
5537 				XFS_DATA_FORK, 0);
5538 			if (error)
5539 				goto error0;
5540 			goto nodelete;
5541 		}
5542 		if (isrt && (mod = do_mod(del.br_startblock, mp->m_sb.sb_rextsize))) {
5543 			/*
5544 			 * Realtime extent is lined up at the end but not
5545 			 * at the front.  We'll get rid of full extents if
5546 			 * we can.
5547 			 */
5548 			mod = mp->m_sb.sb_rextsize - mod;
5549 			if (del.br_blockcount > mod) {
5550 				del.br_blockcount -= mod;
5551 				del.br_startoff += mod;
5552 				del.br_startblock += mod;
5553 			} else if ((del.br_startoff == start &&
5554 				    (del.br_state == XFS_EXT_UNWRITTEN ||
5555 				     xfs_trans_get_block_res(tp) == 0)) ||
5556 				   !XFS_SB_VERSION_HASEXTFLGBIT(&mp->m_sb)) {
5557 				/*
5558 				 * Can't make it unwritten.  There isn't
5559 				 * a full extent here so just skip it.
5560 				 */
5561 				ASSERT(bno >= del.br_blockcount);
5562 				bno -= del.br_blockcount;
5563 				if (bno < got.br_startoff) {
5564 					if (--lastx >= 0)
5565 						xfs_bmbt_get_all(--ep, &got);
5566 				}
5567 				continue;
5568 			} else if (del.br_state == XFS_EXT_UNWRITTEN) {
5569 				/*
5570 				 * This one is already unwritten.
5571 				 * It must have a written left neighbor.
5572 				 * Unwrite the killed part of that one and
5573 				 * try again.
5574 				 */
5575 				ASSERT(lastx > 0);
5576 				xfs_bmbt_get_all(xfs_iext_get_ext(ifp,
5577 						lastx - 1), &prev);
5578 				ASSERT(prev.br_state == XFS_EXT_NORM);
5579 				ASSERT(!ISNULLSTARTBLOCK(prev.br_startblock));
5580 				ASSERT(del.br_startblock ==
5581 				       prev.br_startblock + prev.br_blockcount);
5582 				if (prev.br_startoff < start) {
5583 					mod = start - prev.br_startoff;
5584 					prev.br_blockcount -= mod;
5585 					prev.br_startblock += mod;
5586 					prev.br_startoff = start;
5587 				}
5588 				prev.br_state = XFS_EXT_UNWRITTEN;
5589 				error = xfs_bmap_add_extent(ip, lastx - 1, &cur,
5590 					&prev, firstblock, flist, &logflags,
5591 					delta, XFS_DATA_FORK, 0);
5592 				if (error)
5593 					goto error0;
5594 				goto nodelete;
5595 			} else {
5596 				ASSERT(del.br_state == XFS_EXT_NORM);
5597 				del.br_state = XFS_EXT_UNWRITTEN;
5598 				error = xfs_bmap_add_extent(ip, lastx, &cur,
5599 					&del, firstblock, flist, &logflags,
5600 					delta, XFS_DATA_FORK, 0);
5601 				if (error)
5602 					goto error0;
5603 				goto nodelete;
5604 			}
5605 		}
5606 		if (wasdel) {
5607 			ASSERT(STARTBLOCKVAL(del.br_startblock) > 0);
5608 			/* Update realtime/data freespace, unreserve quota */
5609 			if (isrt) {
5610 				xfs_filblks_t rtexts;
5611 
5612 				rtexts = XFS_FSB_TO_B(mp, del.br_blockcount);
5613 				do_div(rtexts, mp->m_sb.sb_rextsize);
5614 				xfs_mod_incore_sb(mp, XFS_SBS_FREXTENTS,
5615 						(int)rtexts, rsvd);
5616 				(void)XFS_TRANS_RESERVE_QUOTA_NBLKS(mp,
5617 					NULL, ip, -((long)del.br_blockcount), 0,
5618 					XFS_QMOPT_RES_RTBLKS);
5619 			} else {
5620 				xfs_mod_incore_sb(mp, XFS_SBS_FDBLOCKS,
5621 						(int)del.br_blockcount, rsvd);
5622 				(void)XFS_TRANS_RESERVE_QUOTA_NBLKS(mp,
5623 					NULL, ip, -((long)del.br_blockcount), 0,
5624 					XFS_QMOPT_RES_REGBLKS);
5625 			}
5626 			ip->i_delayed_blks -= del.br_blockcount;
5627 			if (cur)
5628 				cur->bc_private.b.flags |=
5629 					XFS_BTCUR_BPRV_WASDEL;
5630 		} else if (cur)
5631 			cur->bc_private.b.flags &= ~XFS_BTCUR_BPRV_WASDEL;
5632 		/*
5633 		 * If it's the case where the directory code is running
5634 		 * with no block reservation, and the deleted block is in
5635 		 * the middle of its extent, and the resulting insert
5636 		 * of an extent would cause transformation to btree format,
5637 		 * then reject it.  The calling code will then swap
5638 		 * blocks around instead.
5639 		 * We have to do this now, rather than waiting for the
5640 		 * conversion to btree format, since the transaction
5641 		 * will be dirty.
5642 		 */
5643 		if (!wasdel && xfs_trans_get_block_res(tp) == 0 &&
5644 		    XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS &&
5645 		    XFS_IFORK_NEXTENTS(ip, whichfork) >= ifp->if_ext_max &&
5646 		    del.br_startoff > got.br_startoff &&
5647 		    del.br_startoff + del.br_blockcount <
5648 		    got.br_startoff + got.br_blockcount) {
5649 			error = XFS_ERROR(ENOSPC);
5650 			goto error0;
5651 		}
5652 		error = xfs_bmap_del_extent(ip, tp, lastx, flist, cur, &del,
5653 				&tmp_logflags, delta, whichfork, rsvd);
5654 		logflags |= tmp_logflags;
5655 		if (error)
5656 			goto error0;
5657 		bno = del.br_startoff - 1;
5658 nodelete:
5659 		lastx = ifp->if_lastex;
5660 		/*
5661 		 * If not done go on to the next (previous) record.
5662 		 * Reset ep in case the extents array was re-alloced.
5663 		 */
5664 		ep = xfs_iext_get_ext(ifp, lastx);
5665 		if (bno != (xfs_fileoff_t)-1 && bno >= start) {
5666 			if (lastx >= XFS_IFORK_NEXTENTS(ip, whichfork) ||
5667 			    xfs_bmbt_get_startoff(ep) > bno) {
5668 				if (--lastx >= 0)
5669 					ep = xfs_iext_get_ext(ifp, lastx);
5670 			}
5671 			if (lastx >= 0)
5672 				xfs_bmbt_get_all(ep, &got);
5673 			extno++;
5674 		}
5675 	}
5676 	ifp->if_lastex = lastx;
5677 	*done = bno == (xfs_fileoff_t)-1 || bno < start || lastx < 0;
5678 	ASSERT(ifp->if_ext_max ==
5679 	       XFS_IFORK_SIZE(ip, whichfork) / (uint)sizeof(xfs_bmbt_rec_t));
5680 	/*
5681 	 * Convert to a btree if necessary.
5682 	 */
5683 	if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS &&
5684 	    XFS_IFORK_NEXTENTS(ip, whichfork) > ifp->if_ext_max) {
5685 		ASSERT(cur == NULL);
5686 		error = xfs_bmap_extents_to_btree(tp, ip, firstblock, flist,
5687 			&cur, 0, &tmp_logflags, whichfork);
5688 		logflags |= tmp_logflags;
5689 		if (error)
5690 			goto error0;
5691 	}
5692 	/*
5693 	 * transform from btree to extents, give it cur
5694 	 */
5695 	else if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE &&
5696 		 XFS_IFORK_NEXTENTS(ip, whichfork) <= ifp->if_ext_max) {
5697 		ASSERT(cur != NULL);
5698 		error = xfs_bmap_btree_to_extents(tp, ip, cur, &tmp_logflags,
5699 			whichfork);
5700 		logflags |= tmp_logflags;
5701 		if (error)
5702 			goto error0;
5703 	}
5704 	/*
5705 	 * transform from extents to local?
5706 	 */
5707 	ASSERT(ifp->if_ext_max ==
5708 	       XFS_IFORK_SIZE(ip, whichfork) / (uint)sizeof(xfs_bmbt_rec_t));
5709 	error = 0;
5710 	if (delta && delta->xed_startoff != NULLFILEOFF) {
5711 		/* A change was actually made.
5712 		 * Note that delta->xed_blockount is an offset at this
5713 		 * point and needs to be converted to a block count.
5714 		 */
5715 		ASSERT(delta->xed_blockcount > delta->xed_startoff);
5716 		delta->xed_blockcount -= delta->xed_startoff;
5717 	}
5718 error0:
5719 	/*
5720 	 * Log everything.  Do this after conversion, there's no point in
5721 	 * logging the extent records if we've converted to btree format.
5722 	 */
5723 	if ((logflags & XFS_ILOG_FEXT(whichfork)) &&
5724 	    XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
5725 		logflags &= ~XFS_ILOG_FEXT(whichfork);
5726 	else if ((logflags & XFS_ILOG_FBROOT(whichfork)) &&
5727 		 XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE)
5728 		logflags &= ~XFS_ILOG_FBROOT(whichfork);
5729 	/*
5730 	 * Log inode even in the error case, if the transaction
5731 	 * is dirty we'll need to shut down the filesystem.
5732 	 */
5733 	if (logflags)
5734 		xfs_trans_log_inode(tp, ip, logflags);
5735 	if (cur) {
5736 		if (!error) {
5737 			*firstblock = cur->bc_private.b.firstblock;
5738 			cur->bc_private.b.allocated = 0;
5739 		}
5740 		xfs_btree_del_cursor(cur,
5741 			error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
5742 	}
5743 	return error;
5744 }
5745 
5746 #undef copy_to_user
5747 static __inline__ int
copy_to_user(void * dst,void * src,int len)5748 copy_to_user(void *dst, void *src, int len) {
5749 	memcpy(dst,src,len);
5750 	return 0;
5751 }
5752 #undef copy_from_user
5753 static __inline__ int
copy_from_user(void * dst,void * src,int len)5754 copy_from_user(void *dst, void *src, int len) {
5755 	memcpy(dst,src,len);
5756 	return 0;
5757 }
5758 /*
5759  * Fcntl interface to xfs_bmapi.
5760  */
5761 int						/* error code */
xfs_getbmap(bhv_desc_t * bdp,struct getbmap * bmv,void __user * ap,int interface)5762 xfs_getbmap(
5763 	bhv_desc_t		*bdp,		/* XFS behavior descriptor*/
5764 	struct getbmap		*bmv,		/* user bmap structure */
5765 	void			__user *ap,	/* pointer to user's array */
5766 	int			interface)	/* interface flags */
5767 {
5768 	__int64_t		bmvend;		/* last block requested */
5769 	int			error;		/* return value */
5770 	__int64_t		fixlen;		/* length for -1 case */
5771 	int			i;		/* extent number */
5772 	xfs_inode_t		*ip;		/* xfs incore inode pointer */
5773 	xfs_vnode_t		*vp;		/* corresponding vnode */
5774 	int			lock;		/* lock state */
5775 	xfs_bmbt_irec_t		*map;		/* buffer for user's data */
5776 	xfs_mount_t		*mp;		/* file system mount point */
5777 	int			nex;		/* # of user extents can do */
5778 	int			nexleft;	/* # of user extents left */
5779 	int			subnex;		/* # of bmapi's can do */
5780 	int			nmap;		/* number of map entries */
5781 	struct getbmap		out;		/* output structure */
5782 	int			whichfork;	/* data or attr fork */
5783 	int			prealloced;	/* this is a file with
5784 						 * preallocated data space */
5785 	int			sh_unwritten;	/* true, if unwritten */
5786 						/* extents listed separately */
5787 	int			bmapi_flags;	/* flags for xfs_bmapi */
5788 	__int32_t		oflags;		/* getbmapx bmv_oflags field */
5789 
5790 	vp = BHV_TO_VNODE(bdp);
5791 	ip = XFS_BHVTOI(bdp);
5792 	mp = ip->i_mount;
5793 
5794 	whichfork = interface & BMV_IF_ATTRFORK ? XFS_ATTR_FORK : XFS_DATA_FORK;
5795 	sh_unwritten = (interface & BMV_IF_PREALLOC) != 0;
5796 
5797 	/*	If the BMV_IF_NO_DMAPI_READ interface bit specified, do not
5798 	 *	generate a DMAPI read event.  Otherwise, if the DM_EVENT_READ
5799 	 *	bit is set for the file, generate a read event in order
5800 	 *	that the DMAPI application may do its thing before we return
5801 	 *	the extents.  Usually this means restoring user file data to
5802 	 *	regions of the file that look like holes.
5803 	 *
5804 	 *	The "old behavior" (from XFS_IOC_GETBMAP) is to not specify
5805 	 *	BMV_IF_NO_DMAPI_READ so that read events are generated.
5806 	 *	If this were not true, callers of ioctl( XFS_IOC_GETBMAP )
5807 	 *	could misinterpret holes in a DMAPI file as true holes,
5808 	 *	when in fact they may represent offline user data.
5809 	 */
5810 	if (   (interface & BMV_IF_NO_DMAPI_READ) == 0
5811 	    && DM_EVENT_ENABLED(vp->v_vfsp, ip, DM_EVENT_READ)
5812 	    && whichfork == XFS_DATA_FORK) {
5813 
5814 		error = XFS_SEND_DATA(mp, DM_EVENT_READ, vp, 0, 0, 0, NULL);
5815 		if (error)
5816 			return XFS_ERROR(error);
5817 	}
5818 
5819 	if (whichfork == XFS_ATTR_FORK) {
5820 		if (XFS_IFORK_Q(ip)) {
5821 			if (ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS &&
5822 			    ip->i_d.di_aformat != XFS_DINODE_FMT_BTREE &&
5823 			    ip->i_d.di_aformat != XFS_DINODE_FMT_LOCAL)
5824 				return XFS_ERROR(EINVAL);
5825 		} else if (unlikely(
5826 			   ip->i_d.di_aformat != 0 &&
5827 			   ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS)) {
5828 			XFS_ERROR_REPORT("xfs_getbmap", XFS_ERRLEVEL_LOW,
5829 					 ip->i_mount);
5830 			return XFS_ERROR(EFSCORRUPTED);
5831 		}
5832 	} else if (ip->i_d.di_format != XFS_DINODE_FMT_EXTENTS &&
5833 		   ip->i_d.di_format != XFS_DINODE_FMT_BTREE &&
5834 		   ip->i_d.di_format != XFS_DINODE_FMT_LOCAL)
5835 		return XFS_ERROR(EINVAL);
5836 	if (whichfork == XFS_DATA_FORK) {
5837 		if ((ip->i_d.di_extsize && (ip->i_d.di_flags &
5838 				(XFS_DIFLAG_REALTIME|XFS_DIFLAG_EXTSIZE))) ||
5839 		    ip->i_d.di_flags & (XFS_DIFLAG_PREALLOC|XFS_DIFLAG_APPEND)){
5840 			prealloced = 1;
5841 			fixlen = XFS_MAXIOFFSET(mp);
5842 		} else {
5843 			prealloced = 0;
5844 			fixlen = ip->i_d.di_size;
5845 		}
5846 	} else {
5847 		prealloced = 0;
5848 		fixlen = 1LL << 32;
5849 	}
5850 
5851 	if (bmv->bmv_length == -1) {
5852 		fixlen = XFS_FSB_TO_BB(mp, XFS_B_TO_FSB(mp, fixlen));
5853 		bmv->bmv_length = MAX( (__int64_t)(fixlen - bmv->bmv_offset),
5854 					(__int64_t)0);
5855 	} else if (bmv->bmv_length < 0)
5856 		return XFS_ERROR(EINVAL);
5857 	if (bmv->bmv_length == 0) {
5858 		bmv->bmv_entries = 0;
5859 		return 0;
5860 	}
5861 	nex = bmv->bmv_count - 1;
5862 	if (nex <= 0)
5863 		return XFS_ERROR(EINVAL);
5864 	bmvend = bmv->bmv_offset + bmv->bmv_length;
5865 
5866 	xfs_ilock(ip, XFS_IOLOCK_SHARED);
5867 
5868 	if (whichfork == XFS_DATA_FORK && ip->i_delayed_blks) {
5869 		/* xfs_fsize_t last_byte = xfs_file_last_byte(ip); */
5870 		XVOP_FLUSH_PAGES(vp, (xfs_off_t)0, -1, 0, FI_REMAPF, error);
5871 	}
5872 
5873 	ASSERT(whichfork == XFS_ATTR_FORK || ip->i_delayed_blks == 0);
5874 
5875 	lock = xfs_ilock_map_shared(ip);
5876 
5877 	/*
5878 	 * Don't let nex be bigger than the number of extents
5879 	 * we can have assuming alternating holes and real extents.
5880 	 */
5881 	if (nex > XFS_IFORK_NEXTENTS(ip, whichfork) * 2 + 1)
5882 		nex = XFS_IFORK_NEXTENTS(ip, whichfork) * 2 + 1;
5883 
5884 	bmapi_flags = XFS_BMAPI_AFLAG(whichfork) |
5885 			((sh_unwritten) ? 0 : XFS_BMAPI_IGSTATE);
5886 
5887 	/*
5888 	 * Allocate enough space to handle "subnex" maps at a time.
5889 	 */
5890 	subnex = 16;
5891 	map = kmem_alloc(subnex * sizeof(*map), KM_SLEEP);
5892 
5893 	bmv->bmv_entries = 0;
5894 
5895 	if (XFS_IFORK_NEXTENTS(ip, whichfork) == 0) {
5896 		error = 0;
5897 		goto unlock_and_return;
5898 	}
5899 
5900 	nexleft = nex;
5901 
5902 	do {
5903 		nmap = (nexleft > subnex) ? subnex : nexleft;
5904 		error = xfs_bmapi(NULL, ip, XFS_BB_TO_FSBT(mp, bmv->bmv_offset),
5905 				  XFS_BB_TO_FSB(mp, bmv->bmv_length),
5906 				  bmapi_flags, NULL, 0, map, &nmap,
5907 				  NULL, NULL);
5908 		if (error)
5909 			goto unlock_and_return;
5910 		ASSERT(nmap <= subnex);
5911 
5912 		for (i = 0; i < nmap && nexleft && bmv->bmv_length; i++) {
5913 			nexleft--;
5914 			oflags = (map[i].br_state == XFS_EXT_UNWRITTEN) ?
5915 					BMV_OF_PREALLOC : 0;
5916 			out.bmv_offset = XFS_FSB_TO_BB(mp, map[i].br_startoff);
5917 			out.bmv_length = XFS_FSB_TO_BB(mp, map[i].br_blockcount);
5918 			ASSERT(map[i].br_startblock != DELAYSTARTBLOCK);
5919                         if (map[i].br_startblock == HOLESTARTBLOCK &&
5920                            ((prealloced && out.bmv_offset + out.bmv_length == bmvend) ||
5921                              whichfork == XFS_ATTR_FORK )) {
5922                                 /*
5923                                  * came to hole at end of file or the end of
5924                                    attribute fork
5925                                  */
5926 				goto unlock_and_return;
5927 			} else {
5928 				out.bmv_block =
5929 				    (map[i].br_startblock == HOLESTARTBLOCK) ?
5930 					-1 :
5931 					XFS_FSB_TO_DB(ip, map[i].br_startblock);
5932 
5933 				/* return either getbmap/getbmapx structure. */
5934 				if (interface & BMV_IF_EXTENDED) {
5935 					struct	getbmapx	outx;
5936 
5937 					GETBMAP_CONVERT(out,outx);
5938 					outx.bmv_oflags = oflags;
5939 					outx.bmv_unused1 = outx.bmv_unused2 = 0;
5940 					if (copy_to_user(ap, &outx,
5941 							sizeof(outx))) {
5942 						error = XFS_ERROR(EFAULT);
5943 						goto unlock_and_return;
5944 					}
5945 				} else {
5946 					if (copy_to_user(ap, &out,
5947 							sizeof(out))) {
5948 						error = XFS_ERROR(EFAULT);
5949 						goto unlock_and_return;
5950 					}
5951 				}
5952 				bmv->bmv_offset =
5953 					out.bmv_offset + out.bmv_length;
5954 				bmv->bmv_length = MAX((__int64_t)0,
5955 					(__int64_t)(bmvend - bmv->bmv_offset));
5956 				bmv->bmv_entries++;
5957 				ap = (interface & BMV_IF_EXTENDED) ?
5958 						(void __user *)
5959 					((struct getbmapx __user *)ap + 1) :
5960 						(void __user *)
5961 					((struct getbmap __user *)ap + 1);
5962 			}
5963 		}
5964 	} while (nmap && nexleft && bmv->bmv_length);
5965 
5966 unlock_and_return:
5967 	xfs_iunlock_map_shared(ip, lock);
5968 	xfs_iunlock(ip, XFS_IOLOCK_SHARED);
5969 
5970 	kmem_free(map, subnex * sizeof(*map));
5971 
5972 	return error;
5973 }
5974 
5975 /*
5976  * Check the last inode extent to determine whether this allocation will result
5977  * in blocks being allocated at the end of the file. When we allocate new data
5978  * blocks at the end of the file which do not start at the previous data block,
5979  * we will try to align the new blocks at stripe unit boundaries.
5980  */
5981 STATIC int				/* error */
xfs_bmap_isaeof(xfs_inode_t * ip,xfs_fileoff_t off,int whichfork,char * aeof)5982 xfs_bmap_isaeof(
5983 	xfs_inode_t	*ip,		/* incore inode pointer */
5984 	xfs_fileoff_t   off,		/* file offset in fsblocks */
5985 	int             whichfork,	/* data or attribute fork */
5986 	char		*aeof)		/* return value */
5987 {
5988 	int		error;		/* error return value */
5989 	xfs_ifork_t	*ifp;		/* inode fork pointer */
5990 	xfs_bmbt_rec_t	*lastrec;	/* extent record pointer */
5991 	xfs_extnum_t	nextents;	/* number of file extents */
5992 	xfs_bmbt_irec_t	s;		/* expanded extent record */
5993 
5994 	ASSERT(whichfork == XFS_DATA_FORK);
5995 	ifp = XFS_IFORK_PTR(ip, whichfork);
5996 	if (!(ifp->if_flags & XFS_IFEXTENTS) &&
5997 	    (error = xfs_iread_extents(NULL, ip, whichfork)))
5998 		return error;
5999 	nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
6000 	if (nextents == 0) {
6001 		*aeof = 1;
6002 		return 0;
6003 	}
6004 	/*
6005 	 * Go to the last extent
6006 	 */
6007 	lastrec = xfs_iext_get_ext(ifp, nextents - 1);
6008 	xfs_bmbt_get_all(lastrec, &s);
6009 	/*
6010 	 * Check we are allocating in the last extent (for delayed allocations)
6011 	 * or past the last extent for non-delayed allocations.
6012 	 */
6013 	*aeof = (off >= s.br_startoff &&
6014 		 off < s.br_startoff + s.br_blockcount &&
6015 		 ISNULLSTARTBLOCK(s.br_startblock)) ||
6016 		off >= s.br_startoff + s.br_blockcount;
6017 	return 0;
6018 }
6019 
6020 /*
6021  * Check if the endoff is outside the last extent. If so the caller will grow
6022  * the allocation to a stripe unit boundary.
6023  */
6024 int					/* error */
xfs_bmap_eof(xfs_inode_t * ip,xfs_fileoff_t endoff,int whichfork,int * eof)6025 xfs_bmap_eof(
6026 	xfs_inode_t	*ip,		/* incore inode pointer */
6027 	xfs_fileoff_t	endoff,		/* file offset in fsblocks */
6028 	int		whichfork,	/* data or attribute fork */
6029 	int		*eof)		/* result value */
6030 {
6031 	xfs_fsblock_t	blockcount;	/* extent block count */
6032 	int		error;		/* error return value */
6033 	xfs_ifork_t	*ifp;		/* inode fork pointer */
6034 	xfs_bmbt_rec_t	*lastrec;	/* extent record pointer */
6035 	xfs_extnum_t	nextents;	/* number of file extents */
6036 	xfs_fileoff_t	startoff;	/* extent starting file offset */
6037 
6038 	ASSERT(whichfork == XFS_DATA_FORK);
6039 	ifp = XFS_IFORK_PTR(ip, whichfork);
6040 	if (!(ifp->if_flags & XFS_IFEXTENTS) &&
6041 	    (error = xfs_iread_extents(NULL, ip, whichfork)))
6042 		return error;
6043 	nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
6044 	if (nextents == 0) {
6045 		*eof = 1;
6046 		return 0;
6047 	}
6048 	/*
6049 	 * Go to the last extent
6050 	 */
6051 	lastrec = xfs_iext_get_ext(ifp, nextents - 1);
6052 	startoff = xfs_bmbt_get_startoff(lastrec);
6053 	blockcount = xfs_bmbt_get_blockcount(lastrec);
6054 	*eof = endoff >= startoff + blockcount;
6055 	return 0;
6056 }
6057 
6058 #ifdef DEBUG
6059 #if 0
6060 /*
6061  * Check that the extents list for the inode ip is in the right order.
6062  */
6063 STATIC void
6064 xfs_bmap_check_extents(
6065 	xfs_inode_t		*ip,		/* incore inode pointer */
6066 	int			whichfork)	/* data or attr fork */
6067 {
6068 	xfs_bmbt_rec_t		*ep;		/* current extent entry */
6069 	xfs_extnum_t		idx;		/* extent record index */
6070 	xfs_ifork_t		*ifp;		/* inode fork pointer */
6071 	xfs_extnum_t		nextents;	/* number of extents in list */
6072 	xfs_bmbt_rec_t		*nextp;		/* next extent entry */
6073 
6074 	ifp = XFS_IFORK_PTR(ip, whichfork);
6075 	ASSERT(ifp->if_flags & XFS_IFEXTENTS);
6076 	nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
6077 	ep = xfs_iext_get_ext(ifp, 0);
6078 	for (idx = 0; idx < nextents - 1; idx++) {
6079 		nextp = xfs_iext_get_ext(ifp, idx + 1);
6080 		xfs_btree_check_rec(XFS_BTNUM_BMAP, (void *)ep,
6081 			(void *)(nextp));
6082 		ep = nextp;
6083 	}
6084 }
6085 #endif
6086 
6087 STATIC
6088 xfs_buf_t *
xfs_bmap_get_bp(xfs_btree_cur_t * cur,xfs_fsblock_t bno)6089 xfs_bmap_get_bp(
6090 	xfs_btree_cur_t         *cur,
6091 	xfs_fsblock_t		bno)
6092 {
6093 	int i;
6094 	xfs_buf_t *bp;
6095 
6096 	if (!cur)
6097 		return(NULL);
6098 
6099 	bp = NULL;
6100 	for(i = 0; i < XFS_BTREE_MAXLEVELS; i++) {
6101 		bp = cur->bc_bufs[i];
6102 		if (!bp) break;
6103 		if (XFS_BUF_ADDR(bp) == bno)
6104 			break;	/* Found it */
6105 	}
6106 	if (i == XFS_BTREE_MAXLEVELS)
6107 		bp = NULL;
6108 
6109 	if (!bp) { /* Chase down all the log items to see if the bp is there */
6110 		xfs_log_item_chunk_t    *licp;
6111 		xfs_trans_t		*tp;
6112 
6113 		tp = cur->bc_tp;
6114 		licp = &tp->t_items;
6115 		while (!bp && licp != NULL) {
6116 			if (XFS_LIC_ARE_ALL_FREE(licp)) {
6117 				licp = licp->lic_next;
6118 				continue;
6119 			}
6120 			for (i = 0; i < licp->lic_unused; i++) {
6121 				xfs_log_item_desc_t	*lidp;
6122 				xfs_log_item_t		*lip;
6123 				xfs_buf_log_item_t	*bip;
6124 				xfs_buf_t		*lbp;
6125 
6126 				if (XFS_LIC_ISFREE(licp, i)) {
6127 					continue;
6128 				}
6129 
6130 				lidp = XFS_LIC_SLOT(licp, i);
6131 				lip = lidp->lid_item;
6132 				if (lip->li_type != XFS_LI_BUF)
6133 					continue;
6134 
6135 				bip = (xfs_buf_log_item_t *)lip;
6136 				lbp = bip->bli_buf;
6137 
6138 				if (XFS_BUF_ADDR(lbp) == bno) {
6139 					bp = lbp;
6140 					break; /* Found it */
6141 				}
6142 			}
6143 			licp = licp->lic_next;
6144 		}
6145 	}
6146 	return(bp);
6147 }
6148 
6149 STATIC void
xfs_check_block(xfs_bmbt_block_t * block,xfs_mount_t * mp,int root,short sz)6150 xfs_check_block(
6151 	xfs_bmbt_block_t        *block,
6152 	xfs_mount_t		*mp,
6153 	int			root,
6154 	short			sz)
6155 {
6156 	int			i, j, dmxr;
6157 	xfs_bmbt_ptr_t		*pp, *thispa;	/* pointer to block address */
6158 	xfs_bmbt_key_t		*prevp, *keyp;
6159 
6160 	ASSERT(be16_to_cpu(block->bb_level) > 0);
6161 
6162 	prevp = NULL;
6163 	for( i = 1; i <= be16_to_cpu(block->bb_numrecs); i++) {
6164 		dmxr = mp->m_bmap_dmxr[0];
6165 
6166 		if (root) {
6167 			keyp = XFS_BMAP_BROOT_KEY_ADDR(block, i, sz);
6168 		} else {
6169 			keyp = XFS_BTREE_KEY_ADDR(mp->m_sb.sb_blocksize,
6170 				xfs_bmbt, block, i, dmxr);
6171 		}
6172 
6173 		if (prevp) {
6174 			xfs_btree_check_key(XFS_BTNUM_BMAP, prevp, keyp);
6175 		}
6176 		prevp = keyp;
6177 
6178 		/*
6179 		 * Compare the block numbers to see if there are dups.
6180 		 */
6181 
6182 		if (root) {
6183 			pp = XFS_BMAP_BROOT_PTR_ADDR(block, i, sz);
6184 		} else {
6185 			pp = XFS_BTREE_PTR_ADDR(mp->m_sb.sb_blocksize,
6186 				xfs_bmbt, block, i, dmxr);
6187 		}
6188 		for (j = i+1; j <= be16_to_cpu(block->bb_numrecs); j++) {
6189 			if (root) {
6190 				thispa = XFS_BMAP_BROOT_PTR_ADDR(block, j, sz);
6191 			} else {
6192 				thispa = XFS_BTREE_PTR_ADDR(mp->m_sb.sb_blocksize,
6193 					xfs_bmbt, block, j, dmxr);
6194 			}
6195 			if (INT_GET(*thispa, ARCH_CONVERT) ==
6196 			    INT_GET(*pp, ARCH_CONVERT)) {
6197 				cmn_err(CE_WARN, "%s: thispa(%d) == pp(%d) %Ld",
6198 					__FUNCTION__, j, i,
6199 					INT_GET(*thispa, ARCH_CONVERT));
6200 				panic("%s: ptrs are equal in node\n",
6201 					__FUNCTION__);
6202 			}
6203 		}
6204 	}
6205 }
6206 
6207 /*
6208  * Check that the extents for the inode ip are in the right order in all
6209  * btree leaves.
6210  */
6211 
6212 STATIC void
xfs_bmap_check_leaf_extents(xfs_btree_cur_t * cur,xfs_inode_t * ip,int whichfork)6213 xfs_bmap_check_leaf_extents(
6214 	xfs_btree_cur_t		*cur,	/* btree cursor or null */
6215 	xfs_inode_t		*ip,		/* incore inode pointer */
6216 	int			whichfork)	/* data or attr fork */
6217 {
6218 	xfs_bmbt_block_t	*block;	/* current btree block */
6219 	xfs_fsblock_t		bno;	/* block # of "block" */
6220 	xfs_buf_t		*bp;	/* buffer for "block" */
6221 	int			error;	/* error return value */
6222 	xfs_extnum_t		i=0, j;	/* index into the extents list */
6223 	xfs_ifork_t		*ifp;	/* fork structure */
6224 	int			level;	/* btree level, for checking */
6225 	xfs_mount_t		*mp;	/* file system mount structure */
6226 	xfs_bmbt_ptr_t		*pp;	/* pointer to block address */
6227 	xfs_bmbt_rec_t		*ep;	/* pointer to current extent */
6228 	xfs_bmbt_rec_t		*lastp; /* pointer to previous extent */
6229 	xfs_bmbt_rec_t		*nextp;	/* pointer to next extent */
6230 	int			bp_release = 0;
6231 
6232 	if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE) {
6233 		return;
6234 	}
6235 
6236 	bno = NULLFSBLOCK;
6237 	mp = ip->i_mount;
6238 	ifp = XFS_IFORK_PTR(ip, whichfork);
6239 	block = ifp->if_broot;
6240 	/*
6241 	 * Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out.
6242 	 */
6243 	level = be16_to_cpu(block->bb_level);
6244 	ASSERT(level > 0);
6245 	xfs_check_block(block, mp, 1, ifp->if_broot_bytes);
6246 	pp = XFS_BMAP_BROOT_PTR_ADDR(block, 1, ifp->if_broot_bytes);
6247 	ASSERT(INT_GET(*pp, ARCH_CONVERT) != NULLDFSBNO);
6248 	ASSERT(XFS_FSB_TO_AGNO(mp, INT_GET(*pp, ARCH_CONVERT)) < mp->m_sb.sb_agcount);
6249 	ASSERT(XFS_FSB_TO_AGBNO(mp, INT_GET(*pp, ARCH_CONVERT)) < mp->m_sb.sb_agblocks);
6250 	bno = INT_GET(*pp, ARCH_CONVERT);
6251 	/*
6252 	 * Go down the tree until leaf level is reached, following the first
6253 	 * pointer (leftmost) at each level.
6254 	 */
6255 	while (level-- > 0) {
6256 		/* See if buf is in cur first */
6257 		bp = xfs_bmap_get_bp(cur, XFS_FSB_TO_DADDR(mp, bno));
6258 		if (bp) {
6259 			bp_release = 0;
6260 		} else {
6261 			bp_release = 1;
6262 		}
6263 		if (!bp && (error = xfs_btree_read_bufl(mp, NULL, bno, 0, &bp,
6264 				XFS_BMAP_BTREE_REF)))
6265 			goto error_norelse;
6266 		block = XFS_BUF_TO_BMBT_BLOCK(bp);
6267 		XFS_WANT_CORRUPTED_GOTO(
6268 			XFS_BMAP_SANITY_CHECK(mp, block, level),
6269 			error0);
6270 		if (level == 0)
6271 			break;
6272 
6273 		/*
6274 		 * Check this block for basic sanity (increasing keys and
6275 		 * no duplicate blocks).
6276 		 */
6277 
6278 		xfs_check_block(block, mp, 0, 0);
6279 		pp = XFS_BTREE_PTR_ADDR(mp->m_sb.sb_blocksize, xfs_bmbt, block,
6280 			1, mp->m_bmap_dmxr[1]);
6281 		XFS_WANT_CORRUPTED_GOTO(XFS_FSB_SANITY_CHECK(mp, INT_GET(*pp, ARCH_CONVERT)), error0);
6282 		bno = INT_GET(*pp, ARCH_CONVERT);
6283 		if (bp_release) {
6284 			bp_release = 0;
6285 			xfs_trans_brelse(NULL, bp);
6286 		}
6287 	}
6288 
6289 	/*
6290 	 * Here with bp and block set to the leftmost leaf node in the tree.
6291 	 */
6292 	i = 0;
6293 
6294 	/*
6295 	 * Loop over all leaf nodes checking that all extents are in the right order.
6296 	 */
6297 	lastp = NULL;
6298 	for (;;) {
6299 		xfs_fsblock_t	nextbno;
6300 		xfs_extnum_t	num_recs;
6301 
6302 
6303 		num_recs = be16_to_cpu(block->bb_numrecs);
6304 
6305 		/*
6306 		 * Read-ahead the next leaf block, if any.
6307 		 */
6308 
6309 		nextbno = be64_to_cpu(block->bb_rightsib);
6310 
6311 		/*
6312 		 * Check all the extents to make sure they are OK.
6313 		 * If we had a previous block, the last entry should
6314 		 * conform with the first entry in this one.
6315 		 */
6316 
6317 		ep = XFS_BTREE_REC_ADDR(mp->m_sb.sb_blocksize, xfs_bmbt,
6318 			block, 1, mp->m_bmap_dmxr[0]);
6319 		for (j = 1; j < num_recs; j++) {
6320 			nextp = XFS_BTREE_REC_ADDR(mp->m_sb.sb_blocksize, xfs_bmbt,
6321 				block, j + 1, mp->m_bmap_dmxr[0]);
6322 			if (lastp) {
6323 				xfs_btree_check_rec(XFS_BTNUM_BMAP,
6324 					(void *)lastp, (void *)ep);
6325 			}
6326 			xfs_btree_check_rec(XFS_BTNUM_BMAP, (void *)ep,
6327 				(void *)(nextp));
6328 			lastp = ep;
6329 			ep = nextp;
6330 		}
6331 
6332 		i += num_recs;
6333 		if (bp_release) {
6334 			bp_release = 0;
6335 			xfs_trans_brelse(NULL, bp);
6336 		}
6337 		bno = nextbno;
6338 		/*
6339 		 * If we've reached the end, stop.
6340 		 */
6341 		if (bno == NULLFSBLOCK)
6342 			break;
6343 
6344 		bp = xfs_bmap_get_bp(cur, XFS_FSB_TO_DADDR(mp, bno));
6345 		if (bp) {
6346 			bp_release = 0;
6347 		} else {
6348 			bp_release = 1;
6349 		}
6350 		if (!bp && (error = xfs_btree_read_bufl(mp, NULL, bno, 0, &bp,
6351 				XFS_BMAP_BTREE_REF)))
6352 			goto error_norelse;
6353 		block = XFS_BUF_TO_BMBT_BLOCK(bp);
6354 	}
6355 	if (bp_release) {
6356 		bp_release = 0;
6357 		xfs_trans_brelse(NULL, bp);
6358 	}
6359 	return;
6360 
6361 error0:
6362 	cmn_err(CE_WARN, "%s: at error0", __FUNCTION__);
6363 	if (bp_release)
6364 		xfs_trans_brelse(NULL, bp);
6365 error_norelse:
6366 	cmn_err(CE_WARN, "%s: BAD after btree leaves for %d extents",
6367 		__FUNCTION__, i);
6368 	panic("%s: CORRUPTED BTREE OR SOMETHING", __FUNCTION__);
6369 	return;
6370 }
6371 #endif
6372 
6373 /*
6374  * Count fsblocks of the given fork.
6375  */
6376 int						/* error */
xfs_bmap_count_blocks(xfs_trans_t * tp,xfs_inode_t * ip,int whichfork,int * count)6377 xfs_bmap_count_blocks(
6378 	xfs_trans_t		*tp,		/* transaction pointer */
6379 	xfs_inode_t		*ip,		/* incore inode */
6380 	int			whichfork,	/* data or attr fork */
6381 	int			*count)		/* out: count of blocks */
6382 {
6383 	xfs_bmbt_block_t	*block;	/* current btree block */
6384 	xfs_fsblock_t		bno;	/* block # of "block" */
6385 	xfs_ifork_t		*ifp;	/* fork structure */
6386 	int			level;	/* btree level, for checking */
6387 	xfs_mount_t		*mp;	/* file system mount structure */
6388 	xfs_bmbt_ptr_t		*pp;	/* pointer to block address */
6389 
6390 	bno = NULLFSBLOCK;
6391 	mp = ip->i_mount;
6392 	ifp = XFS_IFORK_PTR(ip, whichfork);
6393 	if ( XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS ) {
6394 		if (unlikely(xfs_bmap_count_leaves(ifp, 0,
6395 			ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t),
6396 			count) < 0)) {
6397 			XFS_ERROR_REPORT("xfs_bmap_count_blocks(1)",
6398 					 XFS_ERRLEVEL_LOW, mp);
6399 			return XFS_ERROR(EFSCORRUPTED);
6400 		}
6401 		return 0;
6402 	}
6403 
6404 	/*
6405 	 * Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out.
6406 	 */
6407 	block = ifp->if_broot;
6408 	level = be16_to_cpu(block->bb_level);
6409 	ASSERT(level > 0);
6410 	pp = XFS_BMAP_BROOT_PTR_ADDR(block, 1, ifp->if_broot_bytes);
6411 	ASSERT(INT_GET(*pp, ARCH_CONVERT) != NULLDFSBNO);
6412 	ASSERT(XFS_FSB_TO_AGNO(mp, INT_GET(*pp, ARCH_CONVERT)) < mp->m_sb.sb_agcount);
6413 	ASSERT(XFS_FSB_TO_AGBNO(mp, INT_GET(*pp, ARCH_CONVERT)) < mp->m_sb.sb_agblocks);
6414 	bno = INT_GET(*pp, ARCH_CONVERT);
6415 
6416 	if (unlikely(xfs_bmap_count_tree(mp, tp, ifp, bno, level, count) < 0)) {
6417 		XFS_ERROR_REPORT("xfs_bmap_count_blocks(2)", XFS_ERRLEVEL_LOW,
6418 				 mp);
6419 		return XFS_ERROR(EFSCORRUPTED);
6420 	}
6421 
6422 	return 0;
6423 }
6424 
6425 /*
6426  * Recursively walks each level of a btree
6427  * to count total fsblocks is use.
6428  */
6429 int                                     /* error */
xfs_bmap_count_tree(xfs_mount_t * mp,xfs_trans_t * tp,xfs_ifork_t * ifp,xfs_fsblock_t blockno,int levelin,int * count)6430 xfs_bmap_count_tree(
6431 	xfs_mount_t     *mp,            /* file system mount point */
6432 	xfs_trans_t     *tp,            /* transaction pointer */
6433 	xfs_ifork_t	*ifp,		/* inode fork pointer */
6434 	xfs_fsblock_t   blockno,	/* file system block number */
6435 	int             levelin,	/* level in btree */
6436 	int		*count)		/* Count of blocks */
6437 {
6438 	int			error;
6439 	xfs_buf_t		*bp, *nbp;
6440 	int			level = levelin;
6441 	xfs_bmbt_ptr_t          *pp;
6442 	xfs_fsblock_t           bno = blockno;
6443 	xfs_fsblock_t		nextbno;
6444 	xfs_bmbt_block_t        *block, *nextblock;
6445 	int			numrecs;
6446 
6447 	if ((error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp, XFS_BMAP_BTREE_REF)))
6448 		return error;
6449 	*count += 1;
6450 	block = XFS_BUF_TO_BMBT_BLOCK(bp);
6451 
6452 	if (--level) {
6453 		/* Not at node above leafs, count this level of nodes */
6454 		nextbno = be64_to_cpu(block->bb_rightsib);
6455 		while (nextbno != NULLFSBLOCK) {
6456 			if ((error = xfs_btree_read_bufl(mp, tp, nextbno,
6457 				0, &nbp, XFS_BMAP_BTREE_REF)))
6458 				return error;
6459 			*count += 1;
6460 			nextblock = XFS_BUF_TO_BMBT_BLOCK(nbp);
6461 			nextbno = be64_to_cpu(nextblock->bb_rightsib);
6462 			xfs_trans_brelse(tp, nbp);
6463 		}
6464 
6465 		/* Dive to the next level */
6466 		pp = XFS_BTREE_PTR_ADDR(mp->m_sb.sb_blocksize,
6467 			xfs_bmbt, block, 1, mp->m_bmap_dmxr[1]);
6468 		bno = INT_GET(*pp, ARCH_CONVERT);
6469 		if (unlikely((error =
6470 		     xfs_bmap_count_tree(mp, tp, ifp, bno, level, count)) < 0)) {
6471 			xfs_trans_brelse(tp, bp);
6472 			XFS_ERROR_REPORT("xfs_bmap_count_tree(1)",
6473 					 XFS_ERRLEVEL_LOW, mp);
6474 			return XFS_ERROR(EFSCORRUPTED);
6475 		}
6476 		xfs_trans_brelse(tp, bp);
6477 	} else {
6478 		/* count all level 1 nodes and their leaves */
6479 		for (;;) {
6480 			nextbno = be64_to_cpu(block->bb_rightsib);
6481 			numrecs = be16_to_cpu(block->bb_numrecs);
6482 			if (unlikely(xfs_bmap_disk_count_leaves(ifp, mp,
6483 					0, block, numrecs, count) < 0)) {
6484 				xfs_trans_brelse(tp, bp);
6485 				XFS_ERROR_REPORT("xfs_bmap_count_tree(2)",
6486 						 XFS_ERRLEVEL_LOW, mp);
6487 				return XFS_ERROR(EFSCORRUPTED);
6488 			}
6489 			xfs_trans_brelse(tp, bp);
6490 			if (nextbno == NULLFSBLOCK)
6491 				break;
6492 			bno = nextbno;
6493 			if ((error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp,
6494 				XFS_BMAP_BTREE_REF)))
6495 				return error;
6496 			*count += 1;
6497 			block = XFS_BUF_TO_BMBT_BLOCK(bp);
6498 		}
6499 	}
6500 	return 0;
6501 }
6502 
6503 /*
6504  * Count leaf blocks given a range of extent records.
6505  */
6506 int
xfs_bmap_count_leaves(xfs_ifork_t * ifp,xfs_extnum_t idx,int numrecs,int * count)6507 xfs_bmap_count_leaves(
6508 	xfs_ifork_t		*ifp,
6509 	xfs_extnum_t		idx,
6510 	int			numrecs,
6511 	int			*count)
6512 {
6513 	int		b;
6514 	xfs_bmbt_rec_t	*frp;
6515 
6516 	for (b = 0; b < numrecs; b++) {
6517 		frp = xfs_iext_get_ext(ifp, idx + b);
6518 		*count += xfs_bmbt_get_blockcount(frp);
6519 	}
6520 	return 0;
6521 }
6522 
6523 /*
6524  * Count leaf blocks given a range of extent records originally
6525  * in btree format.
6526  */
6527 int
xfs_bmap_disk_count_leaves(xfs_ifork_t * ifp,xfs_mount_t * mp,xfs_extnum_t idx,xfs_bmbt_block_t * block,int numrecs,int * count)6528 xfs_bmap_disk_count_leaves(
6529 	xfs_ifork_t		*ifp,
6530 	xfs_mount_t		*mp,
6531 	xfs_extnum_t		idx,
6532 	xfs_bmbt_block_t	*block,
6533 	int			numrecs,
6534 	int			*count)
6535 {
6536 	int		b;
6537 	xfs_bmbt_rec_t	*frp;
6538 
6539 	for (b = 1; b <= numrecs; b++) {
6540 		frp = XFS_BTREE_REC_ADDR(mp->m_sb.sb_blocksize,
6541 			xfs_bmbt, block, idx + b, mp->m_bmap_dmxr[0]);
6542 		*count += xfs_bmbt_disk_get_blockcount(frp);
6543 	}
6544 	return 0;
6545 }
6546 
6547 
6548