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