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