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