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