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