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