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