xref: /openbmc/linux/fs/xfs/xfs_bmap_util.c (revision f7d84fa7)
1 /*
2  * Copyright (c) 2000-2006 Silicon Graphics, Inc.
3  * Copyright (c) 2012 Red Hat, Inc.
4  * All Rights Reserved.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it would be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write the Free Software Foundation,
17  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18  */
19 #include "xfs.h"
20 #include "xfs_fs.h"
21 #include "xfs_shared.h"
22 #include "xfs_format.h"
23 #include "xfs_log_format.h"
24 #include "xfs_trans_resv.h"
25 #include "xfs_bit.h"
26 #include "xfs_mount.h"
27 #include "xfs_da_format.h"
28 #include "xfs_defer.h"
29 #include "xfs_inode.h"
30 #include "xfs_btree.h"
31 #include "xfs_trans.h"
32 #include "xfs_extfree_item.h"
33 #include "xfs_alloc.h"
34 #include "xfs_bmap.h"
35 #include "xfs_bmap_util.h"
36 #include "xfs_bmap_btree.h"
37 #include "xfs_rtalloc.h"
38 #include "xfs_error.h"
39 #include "xfs_quota.h"
40 #include "xfs_trans_space.h"
41 #include "xfs_trace.h"
42 #include "xfs_icache.h"
43 #include "xfs_log.h"
44 #include "xfs_rmap_btree.h"
45 #include "xfs_iomap.h"
46 #include "xfs_reflink.h"
47 #include "xfs_refcount.h"
48 
49 /* Kernel only BMAP related definitions and functions */
50 
51 /*
52  * Convert the given file system block to a disk block.  We have to treat it
53  * differently based on whether the file is a real time file or not, because the
54  * bmap code does.
55  */
56 xfs_daddr_t
57 xfs_fsb_to_db(struct xfs_inode *ip, xfs_fsblock_t fsb)
58 {
59 	return (XFS_IS_REALTIME_INODE(ip) ? \
60 		 (xfs_daddr_t)XFS_FSB_TO_BB((ip)->i_mount, (fsb)) : \
61 		 XFS_FSB_TO_DADDR((ip)->i_mount, (fsb)));
62 }
63 
64 /*
65  * Routine to zero an extent on disk allocated to the specific inode.
66  *
67  * The VFS functions take a linearised filesystem block offset, so we have to
68  * convert the sparse xfs fsb to the right format first.
69  * VFS types are real funky, too.
70  */
71 int
72 xfs_zero_extent(
73 	struct xfs_inode *ip,
74 	xfs_fsblock_t	start_fsb,
75 	xfs_off_t	count_fsb)
76 {
77 	struct xfs_mount *mp = ip->i_mount;
78 	xfs_daddr_t	sector = xfs_fsb_to_db(ip, start_fsb);
79 	sector_t	block = XFS_BB_TO_FSBT(mp, sector);
80 
81 	return blkdev_issue_zeroout(xfs_find_bdev_for_inode(VFS_I(ip)),
82 		block << (mp->m_super->s_blocksize_bits - 9),
83 		count_fsb << (mp->m_super->s_blocksize_bits - 9),
84 		GFP_NOFS, 0);
85 }
86 
87 int
88 xfs_bmap_rtalloc(
89 	struct xfs_bmalloca	*ap)	/* bmap alloc argument struct */
90 {
91 	int		error;		/* error return value */
92 	xfs_mount_t	*mp;		/* mount point structure */
93 	xfs_extlen_t	prod = 0;	/* product factor for allocators */
94 	xfs_extlen_t	ralen = 0;	/* realtime allocation length */
95 	xfs_extlen_t	align;		/* minimum allocation alignment */
96 	xfs_rtblock_t	rtb;
97 
98 	mp = ap->ip->i_mount;
99 	align = xfs_get_extsz_hint(ap->ip);
100 	prod = align / mp->m_sb.sb_rextsize;
101 	error = xfs_bmap_extsize_align(mp, &ap->got, &ap->prev,
102 					align, 1, ap->eof, 0,
103 					ap->conv, &ap->offset, &ap->length);
104 	if (error)
105 		return error;
106 	ASSERT(ap->length);
107 	ASSERT(ap->length % mp->m_sb.sb_rextsize == 0);
108 
109 	/*
110 	 * If the offset & length are not perfectly aligned
111 	 * then kill prod, it will just get us in trouble.
112 	 */
113 	if (do_mod(ap->offset, align) || ap->length % align)
114 		prod = 1;
115 	/*
116 	 * Set ralen to be the actual requested length in rtextents.
117 	 */
118 	ralen = ap->length / mp->m_sb.sb_rextsize;
119 	/*
120 	 * If the old value was close enough to MAXEXTLEN that
121 	 * we rounded up to it, cut it back so it's valid again.
122 	 * Note that if it's a really large request (bigger than
123 	 * MAXEXTLEN), we don't hear about that number, and can't
124 	 * adjust the starting point to match it.
125 	 */
126 	if (ralen * mp->m_sb.sb_rextsize >= MAXEXTLEN)
127 		ralen = MAXEXTLEN / mp->m_sb.sb_rextsize;
128 
129 	/*
130 	 * Lock out modifications to both the RT bitmap and summary inodes
131 	 */
132 	xfs_ilock(mp->m_rbmip, XFS_ILOCK_EXCL|XFS_ILOCK_RTBITMAP);
133 	xfs_trans_ijoin(ap->tp, mp->m_rbmip, XFS_ILOCK_EXCL);
134 	xfs_ilock(mp->m_rsumip, XFS_ILOCK_EXCL|XFS_ILOCK_RTSUM);
135 	xfs_trans_ijoin(ap->tp, mp->m_rsumip, XFS_ILOCK_EXCL);
136 
137 	/*
138 	 * If it's an allocation to an empty file at offset 0,
139 	 * pick an extent that will space things out in the rt area.
140 	 */
141 	if (ap->eof && ap->offset == 0) {
142 		xfs_rtblock_t uninitialized_var(rtx); /* realtime extent no */
143 
144 		error = xfs_rtpick_extent(mp, ap->tp, ralen, &rtx);
145 		if (error)
146 			return error;
147 		ap->blkno = rtx * mp->m_sb.sb_rextsize;
148 	} else {
149 		ap->blkno = 0;
150 	}
151 
152 	xfs_bmap_adjacent(ap);
153 
154 	/*
155 	 * Realtime allocation, done through xfs_rtallocate_extent.
156 	 */
157 	do_div(ap->blkno, mp->m_sb.sb_rextsize);
158 	rtb = ap->blkno;
159 	ap->length = ralen;
160 	error = xfs_rtallocate_extent(ap->tp, ap->blkno, 1, ap->length,
161 				&ralen, ap->wasdel, prod, &rtb);
162 	if (error)
163 		return error;
164 
165 	ap->blkno = rtb;
166 	if (ap->blkno != NULLFSBLOCK) {
167 		ap->blkno *= mp->m_sb.sb_rextsize;
168 		ralen *= mp->m_sb.sb_rextsize;
169 		ap->length = ralen;
170 		ap->ip->i_d.di_nblocks += ralen;
171 		xfs_trans_log_inode(ap->tp, ap->ip, XFS_ILOG_CORE);
172 		if (ap->wasdel)
173 			ap->ip->i_delayed_blks -= ralen;
174 		/*
175 		 * Adjust the disk quota also. This was reserved
176 		 * earlier.
177 		 */
178 		xfs_trans_mod_dquot_byino(ap->tp, ap->ip,
179 			ap->wasdel ? XFS_TRANS_DQ_DELRTBCOUNT :
180 					XFS_TRANS_DQ_RTBCOUNT, (long) ralen);
181 
182 		/* Zero the extent if we were asked to do so */
183 		if (ap->datatype & XFS_ALLOC_USERDATA_ZERO) {
184 			error = xfs_zero_extent(ap->ip, ap->blkno, ap->length);
185 			if (error)
186 				return error;
187 		}
188 	} else {
189 		ap->length = 0;
190 	}
191 	return 0;
192 }
193 
194 /*
195  * Check if the endoff is outside the last extent. If so the caller will grow
196  * the allocation to a stripe unit boundary.  All offsets are considered outside
197  * the end of file for an empty fork, so 1 is returned in *eof in that case.
198  */
199 int
200 xfs_bmap_eof(
201 	struct xfs_inode	*ip,
202 	xfs_fileoff_t		endoff,
203 	int			whichfork,
204 	int			*eof)
205 {
206 	struct xfs_bmbt_irec	rec;
207 	int			error;
208 
209 	error = xfs_bmap_last_extent(NULL, ip, whichfork, &rec, eof);
210 	if (error || *eof)
211 		return error;
212 
213 	*eof = endoff >= rec.br_startoff + rec.br_blockcount;
214 	return 0;
215 }
216 
217 /*
218  * Extent tree block counting routines.
219  */
220 
221 /*
222  * Count leaf blocks given a range of extent records.
223  */
224 STATIC void
225 xfs_bmap_count_leaves(
226 	xfs_ifork_t		*ifp,
227 	xfs_extnum_t		idx,
228 	int			numrecs,
229 	int			*count)
230 {
231 	int		b;
232 
233 	for (b = 0; b < numrecs; b++) {
234 		xfs_bmbt_rec_host_t *frp = xfs_iext_get_ext(ifp, idx + b);
235 		*count += xfs_bmbt_get_blockcount(frp);
236 	}
237 }
238 
239 /*
240  * Count leaf blocks given a range of extent records originally
241  * in btree format.
242  */
243 STATIC void
244 xfs_bmap_disk_count_leaves(
245 	struct xfs_mount	*mp,
246 	struct xfs_btree_block	*block,
247 	int			numrecs,
248 	int			*count)
249 {
250 	int		b;
251 	xfs_bmbt_rec_t	*frp;
252 
253 	for (b = 1; b <= numrecs; b++) {
254 		frp = XFS_BMBT_REC_ADDR(mp, block, b);
255 		*count += xfs_bmbt_disk_get_blockcount(frp);
256 	}
257 }
258 
259 /*
260  * Recursively walks each level of a btree
261  * to count total fsblocks in use.
262  */
263 STATIC int                                     /* error */
264 xfs_bmap_count_tree(
265 	xfs_mount_t     *mp,            /* file system mount point */
266 	xfs_trans_t     *tp,            /* transaction pointer */
267 	xfs_ifork_t	*ifp,		/* inode fork pointer */
268 	xfs_fsblock_t   blockno,	/* file system block number */
269 	int             levelin,	/* level in btree */
270 	int		*count)		/* Count of blocks */
271 {
272 	int			error;
273 	xfs_buf_t		*bp, *nbp;
274 	int			level = levelin;
275 	__be64			*pp;
276 	xfs_fsblock_t           bno = blockno;
277 	xfs_fsblock_t		nextbno;
278 	struct xfs_btree_block	*block, *nextblock;
279 	int			numrecs;
280 
281 	error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp, XFS_BMAP_BTREE_REF,
282 						&xfs_bmbt_buf_ops);
283 	if (error)
284 		return error;
285 	*count += 1;
286 	block = XFS_BUF_TO_BLOCK(bp);
287 
288 	if (--level) {
289 		/* Not at node above leaves, count this level of nodes */
290 		nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib);
291 		while (nextbno != NULLFSBLOCK) {
292 			error = xfs_btree_read_bufl(mp, tp, nextbno, 0, &nbp,
293 						XFS_BMAP_BTREE_REF,
294 						&xfs_bmbt_buf_ops);
295 			if (error)
296 				return error;
297 			*count += 1;
298 			nextblock = XFS_BUF_TO_BLOCK(nbp);
299 			nextbno = be64_to_cpu(nextblock->bb_u.l.bb_rightsib);
300 			xfs_trans_brelse(tp, nbp);
301 		}
302 
303 		/* Dive to the next level */
304 		pp = XFS_BMBT_PTR_ADDR(mp, block, 1, mp->m_bmap_dmxr[1]);
305 		bno = be64_to_cpu(*pp);
306 		if (unlikely((error =
307 		     xfs_bmap_count_tree(mp, tp, ifp, bno, level, count)) < 0)) {
308 			xfs_trans_brelse(tp, bp);
309 			XFS_ERROR_REPORT("xfs_bmap_count_tree(1)",
310 					 XFS_ERRLEVEL_LOW, mp);
311 			return -EFSCORRUPTED;
312 		}
313 		xfs_trans_brelse(tp, bp);
314 	} else {
315 		/* count all level 1 nodes and their leaves */
316 		for (;;) {
317 			nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib);
318 			numrecs = be16_to_cpu(block->bb_numrecs);
319 			xfs_bmap_disk_count_leaves(mp, block, numrecs, count);
320 			xfs_trans_brelse(tp, bp);
321 			if (nextbno == NULLFSBLOCK)
322 				break;
323 			bno = nextbno;
324 			error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp,
325 						XFS_BMAP_BTREE_REF,
326 						&xfs_bmbt_buf_ops);
327 			if (error)
328 				return error;
329 			*count += 1;
330 			block = XFS_BUF_TO_BLOCK(bp);
331 		}
332 	}
333 	return 0;
334 }
335 
336 /*
337  * Count fsblocks of the given fork.
338  */
339 static int					/* error */
340 xfs_bmap_count_blocks(
341 	xfs_trans_t		*tp,		/* transaction pointer */
342 	xfs_inode_t		*ip,		/* incore inode */
343 	int			whichfork,	/* data or attr fork */
344 	int			*count)		/* out: count of blocks */
345 {
346 	struct xfs_btree_block	*block;	/* current btree block */
347 	xfs_fsblock_t		bno;	/* block # of "block" */
348 	xfs_ifork_t		*ifp;	/* fork structure */
349 	int			level;	/* btree level, for checking */
350 	xfs_mount_t		*mp;	/* file system mount structure */
351 	__be64			*pp;	/* pointer to block address */
352 
353 	bno = NULLFSBLOCK;
354 	mp = ip->i_mount;
355 	ifp = XFS_IFORK_PTR(ip, whichfork);
356 	if ( XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS ) {
357 		xfs_bmap_count_leaves(ifp, 0, xfs_iext_count(ifp), count);
358 		return 0;
359 	}
360 
361 	/*
362 	 * Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out.
363 	 */
364 	block = ifp->if_broot;
365 	level = be16_to_cpu(block->bb_level);
366 	ASSERT(level > 0);
367 	pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, 1, ifp->if_broot_bytes);
368 	bno = be64_to_cpu(*pp);
369 	ASSERT(bno != NULLFSBLOCK);
370 	ASSERT(XFS_FSB_TO_AGNO(mp, bno) < mp->m_sb.sb_agcount);
371 	ASSERT(XFS_FSB_TO_AGBNO(mp, bno) < mp->m_sb.sb_agblocks);
372 
373 	if (unlikely(xfs_bmap_count_tree(mp, tp, ifp, bno, level, count) < 0)) {
374 		XFS_ERROR_REPORT("xfs_bmap_count_blocks(2)", XFS_ERRLEVEL_LOW,
375 				 mp);
376 		return -EFSCORRUPTED;
377 	}
378 
379 	return 0;
380 }
381 
382 /*
383  * returns 1 for success, 0 if we failed to map the extent.
384  */
385 STATIC int
386 xfs_getbmapx_fix_eof_hole(
387 	xfs_inode_t		*ip,		/* xfs incore inode pointer */
388 	int			whichfork,
389 	struct getbmapx		*out,		/* output structure */
390 	int			prealloced,	/* this is a file with
391 						 * preallocated data space */
392 	__int64_t		end,		/* last block requested */
393 	xfs_fsblock_t		startblock,
394 	bool			moretocome)
395 {
396 	__int64_t		fixlen;
397 	xfs_mount_t		*mp;		/* file system mount point */
398 	xfs_ifork_t		*ifp;		/* inode fork pointer */
399 	xfs_extnum_t		lastx;		/* last extent pointer */
400 	xfs_fileoff_t		fileblock;
401 
402 	if (startblock == HOLESTARTBLOCK) {
403 		mp = ip->i_mount;
404 		out->bmv_block = -1;
405 		fixlen = XFS_FSB_TO_BB(mp, XFS_B_TO_FSB(mp, XFS_ISIZE(ip)));
406 		fixlen -= out->bmv_offset;
407 		if (prealloced && out->bmv_offset + out->bmv_length == end) {
408 			/* Came to hole at EOF. Trim it. */
409 			if (fixlen <= 0)
410 				return 0;
411 			out->bmv_length = fixlen;
412 		}
413 	} else {
414 		if (startblock == DELAYSTARTBLOCK)
415 			out->bmv_block = -2;
416 		else
417 			out->bmv_block = xfs_fsb_to_db(ip, startblock);
418 		fileblock = XFS_BB_TO_FSB(ip->i_mount, out->bmv_offset);
419 		ifp = XFS_IFORK_PTR(ip, whichfork);
420 		if (!moretocome &&
421 		    xfs_iext_bno_to_ext(ifp, fileblock, &lastx) &&
422 		   (lastx == xfs_iext_count(ifp) - 1))
423 			out->bmv_oflags |= BMV_OF_LAST;
424 	}
425 
426 	return 1;
427 }
428 
429 /* Adjust the reported bmap around shared/unshared extent transitions. */
430 STATIC int
431 xfs_getbmap_adjust_shared(
432 	struct xfs_inode		*ip,
433 	int				whichfork,
434 	struct xfs_bmbt_irec		*map,
435 	struct getbmapx			*out,
436 	struct xfs_bmbt_irec		*next_map)
437 {
438 	struct xfs_mount		*mp = ip->i_mount;
439 	xfs_agnumber_t			agno;
440 	xfs_agblock_t			agbno;
441 	xfs_agblock_t			ebno;
442 	xfs_extlen_t			elen;
443 	xfs_extlen_t			nlen;
444 	int				error;
445 
446 	next_map->br_startblock = NULLFSBLOCK;
447 	next_map->br_startoff = NULLFILEOFF;
448 	next_map->br_blockcount = 0;
449 
450 	/* Only written data blocks can be shared. */
451 	if (!xfs_is_reflink_inode(ip) ||
452 	    whichfork != XFS_DATA_FORK ||
453 	    !xfs_bmap_is_real_extent(map))
454 		return 0;
455 
456 	agno = XFS_FSB_TO_AGNO(mp, map->br_startblock);
457 	agbno = XFS_FSB_TO_AGBNO(mp, map->br_startblock);
458 	error = xfs_reflink_find_shared(mp, agno, agbno, map->br_blockcount,
459 			&ebno, &elen, true);
460 	if (error)
461 		return error;
462 
463 	if (ebno == NULLAGBLOCK) {
464 		/* No shared blocks at all. */
465 		return 0;
466 	} else if (agbno == ebno) {
467 		/*
468 		 * Shared extent at (agbno, elen).  Shrink the reported
469 		 * extent length and prepare to move the start of map[i]
470 		 * to agbno+elen, with the aim of (re)formatting the new
471 		 * map[i] the next time through the inner loop.
472 		 */
473 		out->bmv_length = XFS_FSB_TO_BB(mp, elen);
474 		out->bmv_oflags |= BMV_OF_SHARED;
475 		if (elen != map->br_blockcount) {
476 			*next_map = *map;
477 			next_map->br_startblock += elen;
478 			next_map->br_startoff += elen;
479 			next_map->br_blockcount -= elen;
480 		}
481 		map->br_blockcount -= elen;
482 	} else {
483 		/*
484 		 * There's an unshared extent (agbno, ebno - agbno)
485 		 * followed by shared extent at (ebno, elen).  Shrink
486 		 * the reported extent length to cover only the unshared
487 		 * extent and prepare to move up the start of map[i] to
488 		 * ebno, with the aim of (re)formatting the new map[i]
489 		 * the next time through the inner loop.
490 		 */
491 		*next_map = *map;
492 		nlen = ebno - agbno;
493 		out->bmv_length = XFS_FSB_TO_BB(mp, nlen);
494 		next_map->br_startblock += nlen;
495 		next_map->br_startoff += nlen;
496 		next_map->br_blockcount -= nlen;
497 		map->br_blockcount -= nlen;
498 	}
499 
500 	return 0;
501 }
502 
503 /*
504  * Get inode's extents as described in bmv, and format for output.
505  * Calls formatter to fill the user's buffer until all extents
506  * are mapped, until the passed-in bmv->bmv_count slots have
507  * been filled, or until the formatter short-circuits the loop,
508  * if it is tracking filled-in extents on its own.
509  */
510 int						/* error code */
511 xfs_getbmap(
512 	xfs_inode_t		*ip,
513 	struct getbmapx		*bmv,		/* user bmap structure */
514 	xfs_bmap_format_t	formatter,	/* format to user */
515 	void			*arg)		/* formatter arg */
516 {
517 	__int64_t		bmvend;		/* last block requested */
518 	int			error = 0;	/* return value */
519 	__int64_t		fixlen;		/* length for -1 case */
520 	int			i;		/* extent number */
521 	int			lock;		/* lock state */
522 	xfs_bmbt_irec_t		*map;		/* buffer for user's data */
523 	xfs_mount_t		*mp;		/* file system mount point */
524 	int			nex;		/* # of user extents can do */
525 	int			subnex;		/* # of bmapi's can do */
526 	int			nmap;		/* number of map entries */
527 	struct getbmapx		*out;		/* output structure */
528 	int			whichfork;	/* data or attr fork */
529 	int			prealloced;	/* this is a file with
530 						 * preallocated data space */
531 	int			iflags;		/* interface flags */
532 	int			bmapi_flags;	/* flags for xfs_bmapi */
533 	int			cur_ext = 0;
534 	struct xfs_bmbt_irec	inject_map;
535 
536 	mp = ip->i_mount;
537 	iflags = bmv->bmv_iflags;
538 
539 #ifndef DEBUG
540 	/* Only allow CoW fork queries if we're debugging. */
541 	if (iflags & BMV_IF_COWFORK)
542 		return -EINVAL;
543 #endif
544 	if ((iflags & BMV_IF_ATTRFORK) && (iflags & BMV_IF_COWFORK))
545 		return -EINVAL;
546 
547 	if (iflags & BMV_IF_ATTRFORK)
548 		whichfork = XFS_ATTR_FORK;
549 	else if (iflags & BMV_IF_COWFORK)
550 		whichfork = XFS_COW_FORK;
551 	else
552 		whichfork = XFS_DATA_FORK;
553 
554 	switch (whichfork) {
555 	case XFS_ATTR_FORK:
556 		if (XFS_IFORK_Q(ip)) {
557 			if (ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS &&
558 			    ip->i_d.di_aformat != XFS_DINODE_FMT_BTREE &&
559 			    ip->i_d.di_aformat != XFS_DINODE_FMT_LOCAL)
560 				return -EINVAL;
561 		} else if (unlikely(
562 			   ip->i_d.di_aformat != 0 &&
563 			   ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS)) {
564 			XFS_ERROR_REPORT("xfs_getbmap", XFS_ERRLEVEL_LOW,
565 					 ip->i_mount);
566 			return -EFSCORRUPTED;
567 		}
568 
569 		prealloced = 0;
570 		fixlen = 1LL << 32;
571 		break;
572 	case XFS_COW_FORK:
573 		if (ip->i_cformat != XFS_DINODE_FMT_EXTENTS)
574 			return -EINVAL;
575 
576 		if (xfs_get_cowextsz_hint(ip)) {
577 			prealloced = 1;
578 			fixlen = mp->m_super->s_maxbytes;
579 		} else {
580 			prealloced = 0;
581 			fixlen = XFS_ISIZE(ip);
582 		}
583 		break;
584 	default:
585 		/* Local format data forks report no extents. */
586 		if (ip->i_d.di_format == XFS_DINODE_FMT_LOCAL) {
587 			bmv->bmv_entries = 0;
588 			return 0;
589 		}
590 		if (ip->i_d.di_format != XFS_DINODE_FMT_EXTENTS &&
591 		    ip->i_d.di_format != XFS_DINODE_FMT_BTREE)
592 			return -EINVAL;
593 
594 		if (xfs_get_extsz_hint(ip) ||
595 		    ip->i_d.di_flags & (XFS_DIFLAG_PREALLOC|XFS_DIFLAG_APPEND)){
596 			prealloced = 1;
597 			fixlen = mp->m_super->s_maxbytes;
598 		} else {
599 			prealloced = 0;
600 			fixlen = XFS_ISIZE(ip);
601 		}
602 		break;
603 	}
604 
605 	if (bmv->bmv_length == -1) {
606 		fixlen = XFS_FSB_TO_BB(mp, XFS_B_TO_FSB(mp, fixlen));
607 		bmv->bmv_length =
608 			max_t(__int64_t, fixlen - bmv->bmv_offset, 0);
609 	} else if (bmv->bmv_length == 0) {
610 		bmv->bmv_entries = 0;
611 		return 0;
612 	} else if (bmv->bmv_length < 0) {
613 		return -EINVAL;
614 	}
615 
616 	nex = bmv->bmv_count - 1;
617 	if (nex <= 0)
618 		return -EINVAL;
619 	bmvend = bmv->bmv_offset + bmv->bmv_length;
620 
621 
622 	if (bmv->bmv_count > ULONG_MAX / sizeof(struct getbmapx))
623 		return -ENOMEM;
624 	out = kmem_zalloc_large(bmv->bmv_count * sizeof(struct getbmapx), 0);
625 	if (!out)
626 		return -ENOMEM;
627 
628 	xfs_ilock(ip, XFS_IOLOCK_SHARED);
629 	switch (whichfork) {
630 	case XFS_DATA_FORK:
631 		if (!(iflags & BMV_IF_DELALLOC) &&
632 		    (ip->i_delayed_blks || XFS_ISIZE(ip) > ip->i_d.di_size)) {
633 			error = filemap_write_and_wait(VFS_I(ip)->i_mapping);
634 			if (error)
635 				goto out_unlock_iolock;
636 
637 			/*
638 			 * Even after flushing the inode, there can still be
639 			 * delalloc blocks on the inode beyond EOF due to
640 			 * speculative preallocation.  These are not removed
641 			 * until the release function is called or the inode
642 			 * is inactivated.  Hence we cannot assert here that
643 			 * ip->i_delayed_blks == 0.
644 			 */
645 		}
646 
647 		lock = xfs_ilock_data_map_shared(ip);
648 		break;
649 	case XFS_COW_FORK:
650 		lock = XFS_ILOCK_SHARED;
651 		xfs_ilock(ip, lock);
652 		break;
653 	case XFS_ATTR_FORK:
654 		lock = xfs_ilock_attr_map_shared(ip);
655 		break;
656 	}
657 
658 	/*
659 	 * Don't let nex be bigger than the number of extents
660 	 * we can have assuming alternating holes and real extents.
661 	 */
662 	if (nex > XFS_IFORK_NEXTENTS(ip, whichfork) * 2 + 1)
663 		nex = XFS_IFORK_NEXTENTS(ip, whichfork) * 2 + 1;
664 
665 	bmapi_flags = xfs_bmapi_aflag(whichfork);
666 	if (!(iflags & BMV_IF_PREALLOC))
667 		bmapi_flags |= XFS_BMAPI_IGSTATE;
668 
669 	/*
670 	 * Allocate enough space to handle "subnex" maps at a time.
671 	 */
672 	error = -ENOMEM;
673 	subnex = 16;
674 	map = kmem_alloc(subnex * sizeof(*map), KM_MAYFAIL | KM_NOFS);
675 	if (!map)
676 		goto out_unlock_ilock;
677 
678 	bmv->bmv_entries = 0;
679 
680 	if (XFS_IFORK_NEXTENTS(ip, whichfork) == 0 &&
681 	    (whichfork == XFS_ATTR_FORK || !(iflags & BMV_IF_DELALLOC))) {
682 		error = 0;
683 		goto out_free_map;
684 	}
685 
686 	do {
687 		nmap = (nex> subnex) ? subnex : nex;
688 		error = xfs_bmapi_read(ip, XFS_BB_TO_FSBT(mp, bmv->bmv_offset),
689 				       XFS_BB_TO_FSB(mp, bmv->bmv_length),
690 				       map, &nmap, bmapi_flags);
691 		if (error)
692 			goto out_free_map;
693 		ASSERT(nmap <= subnex);
694 
695 		for (i = 0; i < nmap && bmv->bmv_length &&
696 				cur_ext < bmv->bmv_count - 1; i++) {
697 			out[cur_ext].bmv_oflags = 0;
698 			if (map[i].br_state == XFS_EXT_UNWRITTEN)
699 				out[cur_ext].bmv_oflags |= BMV_OF_PREALLOC;
700 			else if (map[i].br_startblock == DELAYSTARTBLOCK)
701 				out[cur_ext].bmv_oflags |= BMV_OF_DELALLOC;
702 			out[cur_ext].bmv_offset =
703 				XFS_FSB_TO_BB(mp, map[i].br_startoff);
704 			out[cur_ext].bmv_length =
705 				XFS_FSB_TO_BB(mp, map[i].br_blockcount);
706 			out[cur_ext].bmv_unused1 = 0;
707 			out[cur_ext].bmv_unused2 = 0;
708 
709 			/*
710 			 * delayed allocation extents that start beyond EOF can
711 			 * occur due to speculative EOF allocation when the
712 			 * delalloc extent is larger than the largest freespace
713 			 * extent at conversion time. These extents cannot be
714 			 * converted by data writeback, so can exist here even
715 			 * if we are not supposed to be finding delalloc
716 			 * extents.
717 			 */
718 			if (map[i].br_startblock == DELAYSTARTBLOCK &&
719 			    map[i].br_startoff < XFS_B_TO_FSB(mp, XFS_ISIZE(ip)))
720 				ASSERT((iflags & BMV_IF_DELALLOC) != 0);
721 
722                         if (map[i].br_startblock == HOLESTARTBLOCK &&
723 			    whichfork == XFS_ATTR_FORK) {
724 				/* came to the end of attribute fork */
725 				out[cur_ext].bmv_oflags |= BMV_OF_LAST;
726 				goto out_free_map;
727 			}
728 
729 			/* Is this a shared block? */
730 			error = xfs_getbmap_adjust_shared(ip, whichfork,
731 					&map[i], &out[cur_ext], &inject_map);
732 			if (error)
733 				goto out_free_map;
734 
735 			if (!xfs_getbmapx_fix_eof_hole(ip, whichfork,
736 					&out[cur_ext], prealloced, bmvend,
737 					map[i].br_startblock,
738 					inject_map.br_startblock != NULLFSBLOCK))
739 				goto out_free_map;
740 
741 			bmv->bmv_offset =
742 				out[cur_ext].bmv_offset +
743 				out[cur_ext].bmv_length;
744 			bmv->bmv_length =
745 				max_t(__int64_t, 0, bmvend - bmv->bmv_offset);
746 
747 			/*
748 			 * In case we don't want to return the hole,
749 			 * don't increase cur_ext so that we can reuse
750 			 * it in the next loop.
751 			 */
752 			if ((iflags & BMV_IF_NO_HOLES) &&
753 			    map[i].br_startblock == HOLESTARTBLOCK) {
754 				memset(&out[cur_ext], 0, sizeof(out[cur_ext]));
755 				continue;
756 			}
757 
758 			/*
759 			 * In order to report shared extents accurately,
760 			 * we report each distinct shared/unshared part
761 			 * of a single bmbt record using multiple bmap
762 			 * extents.  To make that happen, we iterate the
763 			 * same map array item multiple times, each
764 			 * time trimming out the subextent that we just
765 			 * reported.
766 			 *
767 			 * Because of this, we must check the out array
768 			 * index (cur_ext) directly against bmv_count-1
769 			 * to avoid overflows.
770 			 */
771 			if (inject_map.br_startblock != NULLFSBLOCK) {
772 				map[i] = inject_map;
773 				i--;
774 			}
775 			bmv->bmv_entries++;
776 			cur_ext++;
777 		}
778 	} while (nmap && bmv->bmv_length && cur_ext < bmv->bmv_count - 1);
779 
780  out_free_map:
781 	kmem_free(map);
782  out_unlock_ilock:
783 	xfs_iunlock(ip, lock);
784  out_unlock_iolock:
785 	xfs_iunlock(ip, XFS_IOLOCK_SHARED);
786 
787 	for (i = 0; i < cur_ext; i++) {
788 		/* format results & advance arg */
789 		error = formatter(&arg, &out[i]);
790 		if (error)
791 			break;
792 	}
793 
794 	kmem_free(out);
795 	return error;
796 }
797 
798 /*
799  * dead simple method of punching delalyed allocation blocks from a range in
800  * the inode. Walks a block at a time so will be slow, but is only executed in
801  * rare error cases so the overhead is not critical. This will always punch out
802  * both the start and end blocks, even if the ranges only partially overlap
803  * them, so it is up to the caller to ensure that partial blocks are not
804  * passed in.
805  */
806 int
807 xfs_bmap_punch_delalloc_range(
808 	struct xfs_inode	*ip,
809 	xfs_fileoff_t		start_fsb,
810 	xfs_fileoff_t		length)
811 {
812 	xfs_fileoff_t		remaining = length;
813 	int			error = 0;
814 
815 	ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
816 
817 	do {
818 		int		done;
819 		xfs_bmbt_irec_t	imap;
820 		int		nimaps = 1;
821 		xfs_fsblock_t	firstblock;
822 		struct xfs_defer_ops dfops;
823 
824 		/*
825 		 * Map the range first and check that it is a delalloc extent
826 		 * before trying to unmap the range. Otherwise we will be
827 		 * trying to remove a real extent (which requires a
828 		 * transaction) or a hole, which is probably a bad idea...
829 		 */
830 		error = xfs_bmapi_read(ip, start_fsb, 1, &imap, &nimaps,
831 				       XFS_BMAPI_ENTIRE);
832 
833 		if (error) {
834 			/* something screwed, just bail */
835 			if (!XFS_FORCED_SHUTDOWN(ip->i_mount)) {
836 				xfs_alert(ip->i_mount,
837 			"Failed delalloc mapping lookup ino %lld fsb %lld.",
838 						ip->i_ino, start_fsb);
839 			}
840 			break;
841 		}
842 		if (!nimaps) {
843 			/* nothing there */
844 			goto next_block;
845 		}
846 		if (imap.br_startblock != DELAYSTARTBLOCK) {
847 			/* been converted, ignore */
848 			goto next_block;
849 		}
850 		WARN_ON(imap.br_blockcount == 0);
851 
852 		/*
853 		 * Note: while we initialise the firstblock/dfops pair, they
854 		 * should never be used because blocks should never be
855 		 * allocated or freed for a delalloc extent and hence we need
856 		 * don't cancel or finish them after the xfs_bunmapi() call.
857 		 */
858 		xfs_defer_init(&dfops, &firstblock);
859 		error = xfs_bunmapi(NULL, ip, start_fsb, 1, 0, 1, &firstblock,
860 					&dfops, &done);
861 		if (error)
862 			break;
863 
864 		ASSERT(!xfs_defer_has_unfinished_work(&dfops));
865 next_block:
866 		start_fsb++;
867 		remaining--;
868 	} while(remaining > 0);
869 
870 	return error;
871 }
872 
873 /*
874  * Test whether it is appropriate to check an inode for and free post EOF
875  * blocks. The 'force' parameter determines whether we should also consider
876  * regular files that are marked preallocated or append-only.
877  */
878 bool
879 xfs_can_free_eofblocks(struct xfs_inode *ip, bool force)
880 {
881 	/* prealloc/delalloc exists only on regular files */
882 	if (!S_ISREG(VFS_I(ip)->i_mode))
883 		return false;
884 
885 	/*
886 	 * Zero sized files with no cached pages and delalloc blocks will not
887 	 * have speculative prealloc/delalloc blocks to remove.
888 	 */
889 	if (VFS_I(ip)->i_size == 0 &&
890 	    VFS_I(ip)->i_mapping->nrpages == 0 &&
891 	    ip->i_delayed_blks == 0)
892 		return false;
893 
894 	/* If we haven't read in the extent list, then don't do it now. */
895 	if (!(ip->i_df.if_flags & XFS_IFEXTENTS))
896 		return false;
897 
898 	/*
899 	 * Do not free real preallocated or append-only files unless the file
900 	 * has delalloc blocks and we are forced to remove them.
901 	 */
902 	if (ip->i_d.di_flags & (XFS_DIFLAG_PREALLOC | XFS_DIFLAG_APPEND))
903 		if (!force || ip->i_delayed_blks == 0)
904 			return false;
905 
906 	return true;
907 }
908 
909 /*
910  * This is called to free any blocks beyond eof. The caller must hold
911  * IOLOCK_EXCL unless we are in the inode reclaim path and have the only
912  * reference to the inode.
913  */
914 int
915 xfs_free_eofblocks(
916 	struct xfs_inode	*ip)
917 {
918 	struct xfs_trans	*tp;
919 	int			error;
920 	xfs_fileoff_t		end_fsb;
921 	xfs_fileoff_t		last_fsb;
922 	xfs_filblks_t		map_len;
923 	int			nimaps;
924 	struct xfs_bmbt_irec	imap;
925 	struct xfs_mount	*mp = ip->i_mount;
926 
927 	/*
928 	 * Figure out if there are any blocks beyond the end
929 	 * of the file.  If not, then there is nothing to do.
930 	 */
931 	end_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)XFS_ISIZE(ip));
932 	last_fsb = XFS_B_TO_FSB(mp, mp->m_super->s_maxbytes);
933 	if (last_fsb <= end_fsb)
934 		return 0;
935 	map_len = last_fsb - end_fsb;
936 
937 	nimaps = 1;
938 	xfs_ilock(ip, XFS_ILOCK_SHARED);
939 	error = xfs_bmapi_read(ip, end_fsb, map_len, &imap, &nimaps, 0);
940 	xfs_iunlock(ip, XFS_ILOCK_SHARED);
941 
942 	/*
943 	 * If there are blocks after the end of file, truncate the file to its
944 	 * current size to free them up.
945 	 */
946 	if (!error && (nimaps != 0) &&
947 	    (imap.br_startblock != HOLESTARTBLOCK ||
948 	     ip->i_delayed_blks)) {
949 		/*
950 		 * Attach the dquots to the inode up front.
951 		 */
952 		error = xfs_qm_dqattach(ip, 0);
953 		if (error)
954 			return error;
955 
956 		/* wait on dio to ensure i_size has settled */
957 		inode_dio_wait(VFS_I(ip));
958 
959 		error = xfs_trans_alloc(mp, &M_RES(mp)->tr_itruncate, 0, 0, 0,
960 				&tp);
961 		if (error) {
962 			ASSERT(XFS_FORCED_SHUTDOWN(mp));
963 			return error;
964 		}
965 
966 		xfs_ilock(ip, XFS_ILOCK_EXCL);
967 		xfs_trans_ijoin(tp, ip, 0);
968 
969 		/*
970 		 * Do not update the on-disk file size.  If we update the
971 		 * on-disk file size and then the system crashes before the
972 		 * contents of the file are flushed to disk then the files
973 		 * may be full of holes (ie NULL files bug).
974 		 */
975 		error = xfs_itruncate_extents(&tp, ip, XFS_DATA_FORK,
976 					      XFS_ISIZE(ip));
977 		if (error) {
978 			/*
979 			 * If we get an error at this point we simply don't
980 			 * bother truncating the file.
981 			 */
982 			xfs_trans_cancel(tp);
983 		} else {
984 			error = xfs_trans_commit(tp);
985 			if (!error)
986 				xfs_inode_clear_eofblocks_tag(ip);
987 		}
988 
989 		xfs_iunlock(ip, XFS_ILOCK_EXCL);
990 	}
991 	return error;
992 }
993 
994 int
995 xfs_alloc_file_space(
996 	struct xfs_inode	*ip,
997 	xfs_off_t		offset,
998 	xfs_off_t		len,
999 	int			alloc_type)
1000 {
1001 	xfs_mount_t		*mp = ip->i_mount;
1002 	xfs_off_t		count;
1003 	xfs_filblks_t		allocated_fsb;
1004 	xfs_filblks_t		allocatesize_fsb;
1005 	xfs_extlen_t		extsz, temp;
1006 	xfs_fileoff_t		startoffset_fsb;
1007 	xfs_fsblock_t		firstfsb;
1008 	int			nimaps;
1009 	int			quota_flag;
1010 	int			rt;
1011 	xfs_trans_t		*tp;
1012 	xfs_bmbt_irec_t		imaps[1], *imapp;
1013 	struct xfs_defer_ops	dfops;
1014 	uint			qblocks, resblks, resrtextents;
1015 	int			error;
1016 
1017 	trace_xfs_alloc_file_space(ip);
1018 
1019 	if (XFS_FORCED_SHUTDOWN(mp))
1020 		return -EIO;
1021 
1022 	error = xfs_qm_dqattach(ip, 0);
1023 	if (error)
1024 		return error;
1025 
1026 	if (len <= 0)
1027 		return -EINVAL;
1028 
1029 	rt = XFS_IS_REALTIME_INODE(ip);
1030 	extsz = xfs_get_extsz_hint(ip);
1031 
1032 	count = len;
1033 	imapp = &imaps[0];
1034 	nimaps = 1;
1035 	startoffset_fsb	= XFS_B_TO_FSBT(mp, offset);
1036 	allocatesize_fsb = XFS_B_TO_FSB(mp, count);
1037 
1038 	/*
1039 	 * Allocate file space until done or until there is an error
1040 	 */
1041 	while (allocatesize_fsb && !error) {
1042 		xfs_fileoff_t	s, e;
1043 
1044 		/*
1045 		 * Determine space reservations for data/realtime.
1046 		 */
1047 		if (unlikely(extsz)) {
1048 			s = startoffset_fsb;
1049 			do_div(s, extsz);
1050 			s *= extsz;
1051 			e = startoffset_fsb + allocatesize_fsb;
1052 			if ((temp = do_mod(startoffset_fsb, extsz)))
1053 				e += temp;
1054 			if ((temp = do_mod(e, extsz)))
1055 				e += extsz - temp;
1056 		} else {
1057 			s = 0;
1058 			e = allocatesize_fsb;
1059 		}
1060 
1061 		/*
1062 		 * The transaction reservation is limited to a 32-bit block
1063 		 * count, hence we need to limit the number of blocks we are
1064 		 * trying to reserve to avoid an overflow. We can't allocate
1065 		 * more than @nimaps extents, and an extent is limited on disk
1066 		 * to MAXEXTLEN (21 bits), so use that to enforce the limit.
1067 		 */
1068 		resblks = min_t(xfs_fileoff_t, (e - s), (MAXEXTLEN * nimaps));
1069 		if (unlikely(rt)) {
1070 			resrtextents = qblocks = resblks;
1071 			resrtextents /= mp->m_sb.sb_rextsize;
1072 			resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
1073 			quota_flag = XFS_QMOPT_RES_RTBLKS;
1074 		} else {
1075 			resrtextents = 0;
1076 			resblks = qblocks = XFS_DIOSTRAT_SPACE_RES(mp, resblks);
1077 			quota_flag = XFS_QMOPT_RES_REGBLKS;
1078 		}
1079 
1080 		/*
1081 		 * Allocate and setup the transaction.
1082 		 */
1083 		error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, resblks,
1084 				resrtextents, 0, &tp);
1085 
1086 		/*
1087 		 * Check for running out of space
1088 		 */
1089 		if (error) {
1090 			/*
1091 			 * Free the transaction structure.
1092 			 */
1093 			ASSERT(error == -ENOSPC || XFS_FORCED_SHUTDOWN(mp));
1094 			break;
1095 		}
1096 		xfs_ilock(ip, XFS_ILOCK_EXCL);
1097 		error = xfs_trans_reserve_quota_nblks(tp, ip, qblocks,
1098 						      0, quota_flag);
1099 		if (error)
1100 			goto error1;
1101 
1102 		xfs_trans_ijoin(tp, ip, 0);
1103 
1104 		xfs_defer_init(&dfops, &firstfsb);
1105 		error = xfs_bmapi_write(tp, ip, startoffset_fsb,
1106 					allocatesize_fsb, alloc_type, &firstfsb,
1107 					resblks, imapp, &nimaps, &dfops);
1108 		if (error)
1109 			goto error0;
1110 
1111 		/*
1112 		 * Complete the transaction
1113 		 */
1114 		error = xfs_defer_finish(&tp, &dfops, NULL);
1115 		if (error)
1116 			goto error0;
1117 
1118 		error = xfs_trans_commit(tp);
1119 		xfs_iunlock(ip, XFS_ILOCK_EXCL);
1120 		if (error)
1121 			break;
1122 
1123 		allocated_fsb = imapp->br_blockcount;
1124 
1125 		if (nimaps == 0) {
1126 			error = -ENOSPC;
1127 			break;
1128 		}
1129 
1130 		startoffset_fsb += allocated_fsb;
1131 		allocatesize_fsb -= allocated_fsb;
1132 	}
1133 
1134 	return error;
1135 
1136 error0:	/* Cancel bmap, unlock inode, unreserve quota blocks, cancel trans */
1137 	xfs_defer_cancel(&dfops);
1138 	xfs_trans_unreserve_quota_nblks(tp, ip, (long)qblocks, 0, quota_flag);
1139 
1140 error1:	/* Just cancel transaction */
1141 	xfs_trans_cancel(tp);
1142 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1143 	return error;
1144 }
1145 
1146 static int
1147 xfs_unmap_extent(
1148 	struct xfs_inode	*ip,
1149 	xfs_fileoff_t		startoffset_fsb,
1150 	xfs_filblks_t		len_fsb,
1151 	int			*done)
1152 {
1153 	struct xfs_mount	*mp = ip->i_mount;
1154 	struct xfs_trans	*tp;
1155 	struct xfs_defer_ops	dfops;
1156 	xfs_fsblock_t		firstfsb;
1157 	uint			resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
1158 	int			error;
1159 
1160 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, resblks, 0, 0, &tp);
1161 	if (error) {
1162 		ASSERT(error == -ENOSPC || XFS_FORCED_SHUTDOWN(mp));
1163 		return error;
1164 	}
1165 
1166 	xfs_ilock(ip, XFS_ILOCK_EXCL);
1167 	error = xfs_trans_reserve_quota(tp, mp, ip->i_udquot, ip->i_gdquot,
1168 			ip->i_pdquot, resblks, 0, XFS_QMOPT_RES_REGBLKS);
1169 	if (error)
1170 		goto out_trans_cancel;
1171 
1172 	xfs_trans_ijoin(tp, ip, 0);
1173 
1174 	xfs_defer_init(&dfops, &firstfsb);
1175 	error = xfs_bunmapi(tp, ip, startoffset_fsb, len_fsb, 0, 2, &firstfsb,
1176 			&dfops, done);
1177 	if (error)
1178 		goto out_bmap_cancel;
1179 
1180 	error = xfs_defer_finish(&tp, &dfops, ip);
1181 	if (error)
1182 		goto out_bmap_cancel;
1183 
1184 	error = xfs_trans_commit(tp);
1185 out_unlock:
1186 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1187 	return error;
1188 
1189 out_bmap_cancel:
1190 	xfs_defer_cancel(&dfops);
1191 out_trans_cancel:
1192 	xfs_trans_cancel(tp);
1193 	goto out_unlock;
1194 }
1195 
1196 static int
1197 xfs_adjust_extent_unmap_boundaries(
1198 	struct xfs_inode	*ip,
1199 	xfs_fileoff_t		*startoffset_fsb,
1200 	xfs_fileoff_t		*endoffset_fsb)
1201 {
1202 	struct xfs_mount	*mp = ip->i_mount;
1203 	struct xfs_bmbt_irec	imap;
1204 	int			nimap, error;
1205 	xfs_extlen_t		mod = 0;
1206 
1207 	nimap = 1;
1208 	error = xfs_bmapi_read(ip, *startoffset_fsb, 1, &imap, &nimap, 0);
1209 	if (error)
1210 		return error;
1211 
1212 	if (nimap && imap.br_startblock != HOLESTARTBLOCK) {
1213 		ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
1214 		mod = do_mod(imap.br_startblock, mp->m_sb.sb_rextsize);
1215 		if (mod)
1216 			*startoffset_fsb += mp->m_sb.sb_rextsize - mod;
1217 	}
1218 
1219 	nimap = 1;
1220 	error = xfs_bmapi_read(ip, *endoffset_fsb - 1, 1, &imap, &nimap, 0);
1221 	if (error)
1222 		return error;
1223 
1224 	if (nimap && imap.br_startblock != HOLESTARTBLOCK) {
1225 		ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
1226 		mod++;
1227 		if (mod && mod != mp->m_sb.sb_rextsize)
1228 			*endoffset_fsb -= mod;
1229 	}
1230 
1231 	return 0;
1232 }
1233 
1234 static int
1235 xfs_flush_unmap_range(
1236 	struct xfs_inode	*ip,
1237 	xfs_off_t		offset,
1238 	xfs_off_t		len)
1239 {
1240 	struct xfs_mount	*mp = ip->i_mount;
1241 	struct inode		*inode = VFS_I(ip);
1242 	xfs_off_t		rounding, start, end;
1243 	int			error;
1244 
1245 	/* wait for the completion of any pending DIOs */
1246 	inode_dio_wait(inode);
1247 
1248 	rounding = max_t(xfs_off_t, 1 << mp->m_sb.sb_blocklog, PAGE_SIZE);
1249 	start = round_down(offset, rounding);
1250 	end = round_up(offset + len, rounding) - 1;
1251 
1252 	error = filemap_write_and_wait_range(inode->i_mapping, start, end);
1253 	if (error)
1254 		return error;
1255 	truncate_pagecache_range(inode, start, end);
1256 	return 0;
1257 }
1258 
1259 int
1260 xfs_free_file_space(
1261 	struct xfs_inode	*ip,
1262 	xfs_off_t		offset,
1263 	xfs_off_t		len)
1264 {
1265 	struct xfs_mount	*mp = ip->i_mount;
1266 	xfs_fileoff_t		startoffset_fsb;
1267 	xfs_fileoff_t		endoffset_fsb;
1268 	int			done = 0, error;
1269 
1270 	trace_xfs_free_file_space(ip);
1271 
1272 	error = xfs_qm_dqattach(ip, 0);
1273 	if (error)
1274 		return error;
1275 
1276 	if (len <= 0)	/* if nothing being freed */
1277 		return 0;
1278 
1279 	error = xfs_flush_unmap_range(ip, offset, len);
1280 	if (error)
1281 		return error;
1282 
1283 	startoffset_fsb = XFS_B_TO_FSB(mp, offset);
1284 	endoffset_fsb = XFS_B_TO_FSBT(mp, offset + len);
1285 
1286 	/*
1287 	 * Need to zero the stuff we're not freeing, on disk.  If it's a RT file
1288 	 * and we can't use unwritten extents then we actually need to ensure
1289 	 * to zero the whole extent, otherwise we just need to take of block
1290 	 * boundaries, and xfs_bunmapi will handle the rest.
1291 	 */
1292 	if (XFS_IS_REALTIME_INODE(ip) &&
1293 	    !xfs_sb_version_hasextflgbit(&mp->m_sb)) {
1294 		error = xfs_adjust_extent_unmap_boundaries(ip, &startoffset_fsb,
1295 				&endoffset_fsb);
1296 		if (error)
1297 			return error;
1298 	}
1299 
1300 	if (endoffset_fsb > startoffset_fsb) {
1301 		while (!done) {
1302 			error = xfs_unmap_extent(ip, startoffset_fsb,
1303 					endoffset_fsb - startoffset_fsb, &done);
1304 			if (error)
1305 				return error;
1306 		}
1307 	}
1308 
1309 	/*
1310 	 * Now that we've unmap all full blocks we'll have to zero out any
1311 	 * partial block at the beginning and/or end.  xfs_zero_range is
1312 	 * smart enough to skip any holes, including those we just created,
1313 	 * but we must take care not to zero beyond EOF and enlarge i_size.
1314 	 */
1315 
1316 	if (offset >= XFS_ISIZE(ip))
1317 		return 0;
1318 
1319 	if (offset + len > XFS_ISIZE(ip))
1320 		len = XFS_ISIZE(ip) - offset;
1321 
1322 	return xfs_zero_range(ip, offset, len, NULL);
1323 }
1324 
1325 /*
1326  * Preallocate and zero a range of a file. This mechanism has the allocation
1327  * semantics of fallocate and in addition converts data in the range to zeroes.
1328  */
1329 int
1330 xfs_zero_file_space(
1331 	struct xfs_inode	*ip,
1332 	xfs_off_t		offset,
1333 	xfs_off_t		len)
1334 {
1335 	struct xfs_mount	*mp = ip->i_mount;
1336 	uint			blksize;
1337 	int			error;
1338 
1339 	trace_xfs_zero_file_space(ip);
1340 
1341 	blksize = 1 << mp->m_sb.sb_blocklog;
1342 
1343 	/*
1344 	 * Punch a hole and prealloc the range. We use hole punch rather than
1345 	 * unwritten extent conversion for two reasons:
1346 	 *
1347 	 * 1.) Hole punch handles partial block zeroing for us.
1348 	 *
1349 	 * 2.) If prealloc returns ENOSPC, the file range is still zero-valued
1350 	 * by virtue of the hole punch.
1351 	 */
1352 	error = xfs_free_file_space(ip, offset, len);
1353 	if (error)
1354 		goto out;
1355 
1356 	error = xfs_alloc_file_space(ip, round_down(offset, blksize),
1357 				     round_up(offset + len, blksize) -
1358 				     round_down(offset, blksize),
1359 				     XFS_BMAPI_PREALLOC);
1360 out:
1361 	return error;
1362 
1363 }
1364 
1365 /*
1366  * @next_fsb will keep track of the extent currently undergoing shift.
1367  * @stop_fsb will keep track of the extent at which we have to stop.
1368  * If we are shifting left, we will start with block (offset + len) and
1369  * shift each extent till last extent.
1370  * If we are shifting right, we will start with last extent inside file space
1371  * and continue until we reach the block corresponding to offset.
1372  */
1373 static int
1374 xfs_shift_file_space(
1375 	struct xfs_inode        *ip,
1376 	xfs_off_t               offset,
1377 	xfs_off_t               len,
1378 	enum shift_direction	direction)
1379 {
1380 	int			done = 0;
1381 	struct xfs_mount	*mp = ip->i_mount;
1382 	struct xfs_trans	*tp;
1383 	int			error;
1384 	struct xfs_defer_ops	dfops;
1385 	xfs_fsblock_t		first_block;
1386 	xfs_fileoff_t		stop_fsb;
1387 	xfs_fileoff_t		next_fsb;
1388 	xfs_fileoff_t		shift_fsb;
1389 	uint			resblks;
1390 
1391 	ASSERT(direction == SHIFT_LEFT || direction == SHIFT_RIGHT);
1392 
1393 	if (direction == SHIFT_LEFT) {
1394 		/*
1395 		 * Reserve blocks to cover potential extent merges after left
1396 		 * shift operations.
1397 		 */
1398 		resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
1399 		next_fsb = XFS_B_TO_FSB(mp, offset + len);
1400 		stop_fsb = XFS_B_TO_FSB(mp, VFS_I(ip)->i_size);
1401 	} else {
1402 		/*
1403 		 * If right shift, delegate the work of initialization of
1404 		 * next_fsb to xfs_bmap_shift_extent as it has ilock held.
1405 		 */
1406 		resblks = 0;
1407 		next_fsb = NULLFSBLOCK;
1408 		stop_fsb = XFS_B_TO_FSB(mp, offset);
1409 	}
1410 
1411 	shift_fsb = XFS_B_TO_FSB(mp, len);
1412 
1413 	/*
1414 	 * Trim eofblocks to avoid shifting uninitialized post-eof preallocation
1415 	 * into the accessible region of the file.
1416 	 */
1417 	if (xfs_can_free_eofblocks(ip, true)) {
1418 		error = xfs_free_eofblocks(ip);
1419 		if (error)
1420 			return error;
1421 	}
1422 
1423 	/*
1424 	 * Writeback and invalidate cache for the remainder of the file as we're
1425 	 * about to shift down every extent from offset to EOF.
1426 	 */
1427 	error = filemap_write_and_wait_range(VFS_I(ip)->i_mapping,
1428 					     offset, -1);
1429 	if (error)
1430 		return error;
1431 	error = invalidate_inode_pages2_range(VFS_I(ip)->i_mapping,
1432 					offset >> PAGE_SHIFT, -1);
1433 	if (error)
1434 		return error;
1435 
1436 	/*
1437 	 * The extent shiting code works on extent granularity. So, if
1438 	 * stop_fsb is not the starting block of extent, we need to split
1439 	 * the extent at stop_fsb.
1440 	 */
1441 	if (direction == SHIFT_RIGHT) {
1442 		error = xfs_bmap_split_extent(ip, stop_fsb);
1443 		if (error)
1444 			return error;
1445 	}
1446 
1447 	while (!error && !done) {
1448 		error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, resblks, 0, 0,
1449 					&tp);
1450 		if (error)
1451 			break;
1452 
1453 		xfs_ilock(ip, XFS_ILOCK_EXCL);
1454 		error = xfs_trans_reserve_quota(tp, mp, ip->i_udquot,
1455 				ip->i_gdquot, ip->i_pdquot, resblks, 0,
1456 				XFS_QMOPT_RES_REGBLKS);
1457 		if (error)
1458 			goto out_trans_cancel;
1459 
1460 		xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
1461 
1462 		xfs_defer_init(&dfops, &first_block);
1463 
1464 		/*
1465 		 * We are using the write transaction in which max 2 bmbt
1466 		 * updates are allowed
1467 		 */
1468 		error = xfs_bmap_shift_extents(tp, ip, &next_fsb, shift_fsb,
1469 				&done, stop_fsb, &first_block, &dfops,
1470 				direction, XFS_BMAP_MAX_SHIFT_EXTENTS);
1471 		if (error)
1472 			goto out_bmap_cancel;
1473 
1474 		error = xfs_defer_finish(&tp, &dfops, NULL);
1475 		if (error)
1476 			goto out_bmap_cancel;
1477 
1478 		error = xfs_trans_commit(tp);
1479 	}
1480 
1481 	return error;
1482 
1483 out_bmap_cancel:
1484 	xfs_defer_cancel(&dfops);
1485 out_trans_cancel:
1486 	xfs_trans_cancel(tp);
1487 	return error;
1488 }
1489 
1490 /*
1491  * xfs_collapse_file_space()
1492  *	This routine frees disk space and shift extent for the given file.
1493  *	The first thing we do is to free data blocks in the specified range
1494  *	by calling xfs_free_file_space(). It would also sync dirty data
1495  *	and invalidate page cache over the region on which collapse range
1496  *	is working. And Shift extent records to the left to cover a hole.
1497  * RETURNS:
1498  *	0 on success
1499  *	errno on error
1500  *
1501  */
1502 int
1503 xfs_collapse_file_space(
1504 	struct xfs_inode	*ip,
1505 	xfs_off_t		offset,
1506 	xfs_off_t		len)
1507 {
1508 	int error;
1509 
1510 	ASSERT(xfs_isilocked(ip, XFS_IOLOCK_EXCL));
1511 	trace_xfs_collapse_file_space(ip);
1512 
1513 	error = xfs_free_file_space(ip, offset, len);
1514 	if (error)
1515 		return error;
1516 
1517 	return xfs_shift_file_space(ip, offset, len, SHIFT_LEFT);
1518 }
1519 
1520 /*
1521  * xfs_insert_file_space()
1522  *	This routine create hole space by shifting extents for the given file.
1523  *	The first thing we do is to sync dirty data and invalidate page cache
1524  *	over the region on which insert range is working. And split an extent
1525  *	to two extents at given offset by calling xfs_bmap_split_extent.
1526  *	And shift all extent records which are laying between [offset,
1527  *	last allocated extent] to the right to reserve hole range.
1528  * RETURNS:
1529  *	0 on success
1530  *	errno on error
1531  */
1532 int
1533 xfs_insert_file_space(
1534 	struct xfs_inode	*ip,
1535 	loff_t			offset,
1536 	loff_t			len)
1537 {
1538 	ASSERT(xfs_isilocked(ip, XFS_IOLOCK_EXCL));
1539 	trace_xfs_insert_file_space(ip);
1540 
1541 	return xfs_shift_file_space(ip, offset, len, SHIFT_RIGHT);
1542 }
1543 
1544 /*
1545  * We need to check that the format of the data fork in the temporary inode is
1546  * valid for the target inode before doing the swap. This is not a problem with
1547  * attr1 because of the fixed fork offset, but attr2 has a dynamically sized
1548  * data fork depending on the space the attribute fork is taking so we can get
1549  * invalid formats on the target inode.
1550  *
1551  * E.g. target has space for 7 extents in extent format, temp inode only has
1552  * space for 6.  If we defragment down to 7 extents, then the tmp format is a
1553  * btree, but when swapped it needs to be in extent format. Hence we can't just
1554  * blindly swap data forks on attr2 filesystems.
1555  *
1556  * Note that we check the swap in both directions so that we don't end up with
1557  * a corrupt temporary inode, either.
1558  *
1559  * Note that fixing the way xfs_fsr sets up the attribute fork in the source
1560  * inode will prevent this situation from occurring, so all we do here is
1561  * reject and log the attempt. basically we are putting the responsibility on
1562  * userspace to get this right.
1563  */
1564 static int
1565 xfs_swap_extents_check_format(
1566 	struct xfs_inode	*ip,	/* target inode */
1567 	struct xfs_inode	*tip)	/* tmp inode */
1568 {
1569 
1570 	/* Should never get a local format */
1571 	if (ip->i_d.di_format == XFS_DINODE_FMT_LOCAL ||
1572 	    tip->i_d.di_format == XFS_DINODE_FMT_LOCAL)
1573 		return -EINVAL;
1574 
1575 	/*
1576 	 * if the target inode has less extents that then temporary inode then
1577 	 * why did userspace call us?
1578 	 */
1579 	if (ip->i_d.di_nextents < tip->i_d.di_nextents)
1580 		return -EINVAL;
1581 
1582 	/*
1583 	 * If we have to use the (expensive) rmap swap method, we can
1584 	 * handle any number of extents and any format.
1585 	 */
1586 	if (xfs_sb_version_hasrmapbt(&ip->i_mount->m_sb))
1587 		return 0;
1588 
1589 	/*
1590 	 * if the target inode is in extent form and the temp inode is in btree
1591 	 * form then we will end up with the target inode in the wrong format
1592 	 * as we already know there are less extents in the temp inode.
1593 	 */
1594 	if (ip->i_d.di_format == XFS_DINODE_FMT_EXTENTS &&
1595 	    tip->i_d.di_format == XFS_DINODE_FMT_BTREE)
1596 		return -EINVAL;
1597 
1598 	/* Check temp in extent form to max in target */
1599 	if (tip->i_d.di_format == XFS_DINODE_FMT_EXTENTS &&
1600 	    XFS_IFORK_NEXTENTS(tip, XFS_DATA_FORK) >
1601 			XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK))
1602 		return -EINVAL;
1603 
1604 	/* Check target in extent form to max in temp */
1605 	if (ip->i_d.di_format == XFS_DINODE_FMT_EXTENTS &&
1606 	    XFS_IFORK_NEXTENTS(ip, XFS_DATA_FORK) >
1607 			XFS_IFORK_MAXEXT(tip, XFS_DATA_FORK))
1608 		return -EINVAL;
1609 
1610 	/*
1611 	 * If we are in a btree format, check that the temp root block will fit
1612 	 * in the target and that it has enough extents to be in btree format
1613 	 * in the target.
1614 	 *
1615 	 * Note that we have to be careful to allow btree->extent conversions
1616 	 * (a common defrag case) which will occur when the temp inode is in
1617 	 * extent format...
1618 	 */
1619 	if (tip->i_d.di_format == XFS_DINODE_FMT_BTREE) {
1620 		if (XFS_IFORK_BOFF(ip) &&
1621 		    XFS_BMAP_BMDR_SPACE(tip->i_df.if_broot) > XFS_IFORK_BOFF(ip))
1622 			return -EINVAL;
1623 		if (XFS_IFORK_NEXTENTS(tip, XFS_DATA_FORK) <=
1624 		    XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK))
1625 			return -EINVAL;
1626 	}
1627 
1628 	/* Reciprocal target->temp btree format checks */
1629 	if (ip->i_d.di_format == XFS_DINODE_FMT_BTREE) {
1630 		if (XFS_IFORK_BOFF(tip) &&
1631 		    XFS_BMAP_BMDR_SPACE(ip->i_df.if_broot) > XFS_IFORK_BOFF(tip))
1632 			return -EINVAL;
1633 		if (XFS_IFORK_NEXTENTS(ip, XFS_DATA_FORK) <=
1634 		    XFS_IFORK_MAXEXT(tip, XFS_DATA_FORK))
1635 			return -EINVAL;
1636 	}
1637 
1638 	return 0;
1639 }
1640 
1641 static int
1642 xfs_swap_extent_flush(
1643 	struct xfs_inode	*ip)
1644 {
1645 	int	error;
1646 
1647 	error = filemap_write_and_wait(VFS_I(ip)->i_mapping);
1648 	if (error)
1649 		return error;
1650 	truncate_pagecache_range(VFS_I(ip), 0, -1);
1651 
1652 	/* Verify O_DIRECT for ftmp */
1653 	if (VFS_I(ip)->i_mapping->nrpages)
1654 		return -EINVAL;
1655 	return 0;
1656 }
1657 
1658 /*
1659  * Move extents from one file to another, when rmap is enabled.
1660  */
1661 STATIC int
1662 xfs_swap_extent_rmap(
1663 	struct xfs_trans		**tpp,
1664 	struct xfs_inode		*ip,
1665 	struct xfs_inode		*tip)
1666 {
1667 	struct xfs_bmbt_irec		irec;
1668 	struct xfs_bmbt_irec		uirec;
1669 	struct xfs_bmbt_irec		tirec;
1670 	xfs_fileoff_t			offset_fsb;
1671 	xfs_fileoff_t			end_fsb;
1672 	xfs_filblks_t			count_fsb;
1673 	xfs_fsblock_t			firstfsb;
1674 	struct xfs_defer_ops		dfops;
1675 	int				error;
1676 	xfs_filblks_t			ilen;
1677 	xfs_filblks_t			rlen;
1678 	int				nimaps;
1679 	__uint64_t			tip_flags2;
1680 
1681 	/*
1682 	 * If the source file has shared blocks, we must flag the donor
1683 	 * file as having shared blocks so that we get the shared-block
1684 	 * rmap functions when we go to fix up the rmaps.  The flags
1685 	 * will be switch for reals later.
1686 	 */
1687 	tip_flags2 = tip->i_d.di_flags2;
1688 	if (ip->i_d.di_flags2 & XFS_DIFLAG2_REFLINK)
1689 		tip->i_d.di_flags2 |= XFS_DIFLAG2_REFLINK;
1690 
1691 	offset_fsb = 0;
1692 	end_fsb = XFS_B_TO_FSB(ip->i_mount, i_size_read(VFS_I(ip)));
1693 	count_fsb = (xfs_filblks_t)(end_fsb - offset_fsb);
1694 
1695 	while (count_fsb) {
1696 		/* Read extent from the donor file */
1697 		nimaps = 1;
1698 		error = xfs_bmapi_read(tip, offset_fsb, count_fsb, &tirec,
1699 				&nimaps, 0);
1700 		if (error)
1701 			goto out;
1702 		ASSERT(nimaps == 1);
1703 		ASSERT(tirec.br_startblock != DELAYSTARTBLOCK);
1704 
1705 		trace_xfs_swap_extent_rmap_remap(tip, &tirec);
1706 		ilen = tirec.br_blockcount;
1707 
1708 		/* Unmap the old blocks in the source file. */
1709 		while (tirec.br_blockcount) {
1710 			xfs_defer_init(&dfops, &firstfsb);
1711 			trace_xfs_swap_extent_rmap_remap_piece(tip, &tirec);
1712 
1713 			/* Read extent from the source file */
1714 			nimaps = 1;
1715 			error = xfs_bmapi_read(ip, tirec.br_startoff,
1716 					tirec.br_blockcount, &irec,
1717 					&nimaps, 0);
1718 			if (error)
1719 				goto out_defer;
1720 			ASSERT(nimaps == 1);
1721 			ASSERT(tirec.br_startoff == irec.br_startoff);
1722 			trace_xfs_swap_extent_rmap_remap_piece(ip, &irec);
1723 
1724 			/* Trim the extent. */
1725 			uirec = tirec;
1726 			uirec.br_blockcount = rlen = min_t(xfs_filblks_t,
1727 					tirec.br_blockcount,
1728 					irec.br_blockcount);
1729 			trace_xfs_swap_extent_rmap_remap_piece(tip, &uirec);
1730 
1731 			/* Remove the mapping from the donor file. */
1732 			error = xfs_bmap_unmap_extent((*tpp)->t_mountp, &dfops,
1733 					tip, &uirec);
1734 			if (error)
1735 				goto out_defer;
1736 
1737 			/* Remove the mapping from the source file. */
1738 			error = xfs_bmap_unmap_extent((*tpp)->t_mountp, &dfops,
1739 					ip, &irec);
1740 			if (error)
1741 				goto out_defer;
1742 
1743 			/* Map the donor file's blocks into the source file. */
1744 			error = xfs_bmap_map_extent((*tpp)->t_mountp, &dfops,
1745 					ip, &uirec);
1746 			if (error)
1747 				goto out_defer;
1748 
1749 			/* Map the source file's blocks into the donor file. */
1750 			error = xfs_bmap_map_extent((*tpp)->t_mountp, &dfops,
1751 					tip, &irec);
1752 			if (error)
1753 				goto out_defer;
1754 
1755 			error = xfs_defer_finish(tpp, &dfops, ip);
1756 			if (error)
1757 				goto out_defer;
1758 
1759 			tirec.br_startoff += rlen;
1760 			if (tirec.br_startblock != HOLESTARTBLOCK &&
1761 			    tirec.br_startblock != DELAYSTARTBLOCK)
1762 				tirec.br_startblock += rlen;
1763 			tirec.br_blockcount -= rlen;
1764 		}
1765 
1766 		/* Roll on... */
1767 		count_fsb -= ilen;
1768 		offset_fsb += ilen;
1769 	}
1770 
1771 	tip->i_d.di_flags2 = tip_flags2;
1772 	return 0;
1773 
1774 out_defer:
1775 	xfs_defer_cancel(&dfops);
1776 out:
1777 	trace_xfs_swap_extent_rmap_error(ip, error, _RET_IP_);
1778 	tip->i_d.di_flags2 = tip_flags2;
1779 	return error;
1780 }
1781 
1782 /* Swap the extents of two files by swapping data forks. */
1783 STATIC int
1784 xfs_swap_extent_forks(
1785 	struct xfs_trans	*tp,
1786 	struct xfs_inode	*ip,
1787 	struct xfs_inode	*tip,
1788 	int			*src_log_flags,
1789 	int			*target_log_flags)
1790 {
1791 	struct xfs_ifork	tempifp, *ifp, *tifp;
1792 	int			aforkblks = 0;
1793 	int			taforkblks = 0;
1794 	xfs_extnum_t		nextents;
1795 	__uint64_t		tmp;
1796 	int			error;
1797 
1798 	/*
1799 	 * Count the number of extended attribute blocks
1800 	 */
1801 	if ( ((XFS_IFORK_Q(ip) != 0) && (ip->i_d.di_anextents > 0)) &&
1802 	     (ip->i_d.di_aformat != XFS_DINODE_FMT_LOCAL)) {
1803 		error = xfs_bmap_count_blocks(tp, ip, XFS_ATTR_FORK,
1804 				&aforkblks);
1805 		if (error)
1806 			return error;
1807 	}
1808 	if ( ((XFS_IFORK_Q(tip) != 0) && (tip->i_d.di_anextents > 0)) &&
1809 	     (tip->i_d.di_aformat != XFS_DINODE_FMT_LOCAL)) {
1810 		error = xfs_bmap_count_blocks(tp, tip, XFS_ATTR_FORK,
1811 				&taforkblks);
1812 		if (error)
1813 			return error;
1814 	}
1815 
1816 	/*
1817 	 * Before we've swapped the forks, lets set the owners of the forks
1818 	 * appropriately. We have to do this as we are demand paging the btree
1819 	 * buffers, and so the validation done on read will expect the owner
1820 	 * field to be correctly set. Once we change the owners, we can swap the
1821 	 * inode forks.
1822 	 */
1823 	if (ip->i_d.di_version == 3 &&
1824 	    ip->i_d.di_format == XFS_DINODE_FMT_BTREE) {
1825 		(*target_log_flags) |= XFS_ILOG_DOWNER;
1826 		error = xfs_bmbt_change_owner(tp, ip, XFS_DATA_FORK,
1827 					      tip->i_ino, NULL);
1828 		if (error)
1829 			return error;
1830 	}
1831 
1832 	if (tip->i_d.di_version == 3 &&
1833 	    tip->i_d.di_format == XFS_DINODE_FMT_BTREE) {
1834 		(*src_log_flags) |= XFS_ILOG_DOWNER;
1835 		error = xfs_bmbt_change_owner(tp, tip, XFS_DATA_FORK,
1836 					      ip->i_ino, NULL);
1837 		if (error)
1838 			return error;
1839 	}
1840 
1841 	/*
1842 	 * Swap the data forks of the inodes
1843 	 */
1844 	ifp = &ip->i_df;
1845 	tifp = &tip->i_df;
1846 	tempifp = *ifp;		/* struct copy */
1847 	*ifp = *tifp;		/* struct copy */
1848 	*tifp = tempifp;	/* struct copy */
1849 
1850 	/*
1851 	 * Fix the on-disk inode values
1852 	 */
1853 	tmp = (__uint64_t)ip->i_d.di_nblocks;
1854 	ip->i_d.di_nblocks = tip->i_d.di_nblocks - taforkblks + aforkblks;
1855 	tip->i_d.di_nblocks = tmp + taforkblks - aforkblks;
1856 
1857 	tmp = (__uint64_t) ip->i_d.di_nextents;
1858 	ip->i_d.di_nextents = tip->i_d.di_nextents;
1859 	tip->i_d.di_nextents = tmp;
1860 
1861 	tmp = (__uint64_t) ip->i_d.di_format;
1862 	ip->i_d.di_format = tip->i_d.di_format;
1863 	tip->i_d.di_format = tmp;
1864 
1865 	/*
1866 	 * The extents in the source inode could still contain speculative
1867 	 * preallocation beyond EOF (e.g. the file is open but not modified
1868 	 * while defrag is in progress). In that case, we need to copy over the
1869 	 * number of delalloc blocks the data fork in the source inode is
1870 	 * tracking beyond EOF so that when the fork is truncated away when the
1871 	 * temporary inode is unlinked we don't underrun the i_delayed_blks
1872 	 * counter on that inode.
1873 	 */
1874 	ASSERT(tip->i_delayed_blks == 0);
1875 	tip->i_delayed_blks = ip->i_delayed_blks;
1876 	ip->i_delayed_blks = 0;
1877 
1878 	switch (ip->i_d.di_format) {
1879 	case XFS_DINODE_FMT_EXTENTS:
1880 		/*
1881 		 * If the extents fit in the inode, fix the pointer.  Otherwise
1882 		 * it's already NULL or pointing to the extent.
1883 		 */
1884 		nextents = xfs_iext_count(&ip->i_df);
1885 		if (nextents <= XFS_INLINE_EXTS)
1886 			ifp->if_u1.if_extents = ifp->if_u2.if_inline_ext;
1887 		(*src_log_flags) |= XFS_ILOG_DEXT;
1888 		break;
1889 	case XFS_DINODE_FMT_BTREE:
1890 		ASSERT(ip->i_d.di_version < 3 ||
1891 		       (*src_log_flags & XFS_ILOG_DOWNER));
1892 		(*src_log_flags) |= XFS_ILOG_DBROOT;
1893 		break;
1894 	}
1895 
1896 	switch (tip->i_d.di_format) {
1897 	case XFS_DINODE_FMT_EXTENTS:
1898 		/*
1899 		 * If the extents fit in the inode, fix the pointer.  Otherwise
1900 		 * it's already NULL or pointing to the extent.
1901 		 */
1902 		nextents = xfs_iext_count(&tip->i_df);
1903 		if (nextents <= XFS_INLINE_EXTS)
1904 			tifp->if_u1.if_extents = tifp->if_u2.if_inline_ext;
1905 		(*target_log_flags) |= XFS_ILOG_DEXT;
1906 		break;
1907 	case XFS_DINODE_FMT_BTREE:
1908 		(*target_log_flags) |= XFS_ILOG_DBROOT;
1909 		ASSERT(tip->i_d.di_version < 3 ||
1910 		       (*target_log_flags & XFS_ILOG_DOWNER));
1911 		break;
1912 	}
1913 
1914 	return 0;
1915 }
1916 
1917 int
1918 xfs_swap_extents(
1919 	struct xfs_inode	*ip,	/* target inode */
1920 	struct xfs_inode	*tip,	/* tmp inode */
1921 	struct xfs_swapext	*sxp)
1922 {
1923 	struct xfs_mount	*mp = ip->i_mount;
1924 	struct xfs_trans	*tp;
1925 	struct xfs_bstat	*sbp = &sxp->sx_stat;
1926 	int			src_log_flags, target_log_flags;
1927 	int			error = 0;
1928 	int			lock_flags;
1929 	struct xfs_ifork	*cowfp;
1930 	__uint64_t		f;
1931 	int			resblks;
1932 
1933 	/*
1934 	 * Lock the inodes against other IO, page faults and truncate to
1935 	 * begin with.  Then we can ensure the inodes are flushed and have no
1936 	 * page cache safely. Once we have done this we can take the ilocks and
1937 	 * do the rest of the checks.
1938 	 */
1939 	lock_two_nondirectories(VFS_I(ip), VFS_I(tip));
1940 	lock_flags = XFS_MMAPLOCK_EXCL;
1941 	xfs_lock_two_inodes(ip, tip, XFS_MMAPLOCK_EXCL);
1942 
1943 	/* Verify that both files have the same format */
1944 	if ((VFS_I(ip)->i_mode & S_IFMT) != (VFS_I(tip)->i_mode & S_IFMT)) {
1945 		error = -EINVAL;
1946 		goto out_unlock;
1947 	}
1948 
1949 	/* Verify both files are either real-time or non-realtime */
1950 	if (XFS_IS_REALTIME_INODE(ip) != XFS_IS_REALTIME_INODE(tip)) {
1951 		error = -EINVAL;
1952 		goto out_unlock;
1953 	}
1954 
1955 	error = xfs_swap_extent_flush(ip);
1956 	if (error)
1957 		goto out_unlock;
1958 	error = xfs_swap_extent_flush(tip);
1959 	if (error)
1960 		goto out_unlock;
1961 
1962 	/*
1963 	 * Extent "swapping" with rmap requires a permanent reservation and
1964 	 * a block reservation because it's really just a remap operation
1965 	 * performed with log redo items!
1966 	 */
1967 	if (xfs_sb_version_hasrmapbt(&mp->m_sb)) {
1968 		/*
1969 		 * Conceptually this shouldn't affect the shape of either
1970 		 * bmbt, but since we atomically move extents one by one,
1971 		 * we reserve enough space to rebuild both trees.
1972 		 */
1973 		resblks = XFS_SWAP_RMAP_SPACE_RES(mp,
1974 				XFS_IFORK_NEXTENTS(ip, XFS_DATA_FORK),
1975 				XFS_DATA_FORK) +
1976 			  XFS_SWAP_RMAP_SPACE_RES(mp,
1977 				XFS_IFORK_NEXTENTS(tip, XFS_DATA_FORK),
1978 				XFS_DATA_FORK);
1979 		error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, resblks,
1980 				0, 0, &tp);
1981 	} else
1982 		error = xfs_trans_alloc(mp, &M_RES(mp)->tr_ichange, 0,
1983 				0, 0, &tp);
1984 	if (error)
1985 		goto out_unlock;
1986 
1987 	/*
1988 	 * Lock and join the inodes to the tansaction so that transaction commit
1989 	 * or cancel will unlock the inodes from this point onwards.
1990 	 */
1991 	xfs_lock_two_inodes(ip, tip, XFS_ILOCK_EXCL);
1992 	lock_flags |= XFS_ILOCK_EXCL;
1993 	xfs_trans_ijoin(tp, ip, 0);
1994 	xfs_trans_ijoin(tp, tip, 0);
1995 
1996 
1997 	/* Verify all data are being swapped */
1998 	if (sxp->sx_offset != 0 ||
1999 	    sxp->sx_length != ip->i_d.di_size ||
2000 	    sxp->sx_length != tip->i_d.di_size) {
2001 		error = -EFAULT;
2002 		goto out_trans_cancel;
2003 	}
2004 
2005 	trace_xfs_swap_extent_before(ip, 0);
2006 	trace_xfs_swap_extent_before(tip, 1);
2007 
2008 	/* check inode formats now that data is flushed */
2009 	error = xfs_swap_extents_check_format(ip, tip);
2010 	if (error) {
2011 		xfs_notice(mp,
2012 		    "%s: inode 0x%llx format is incompatible for exchanging.",
2013 				__func__, ip->i_ino);
2014 		goto out_trans_cancel;
2015 	}
2016 
2017 	/*
2018 	 * Compare the current change & modify times with that
2019 	 * passed in.  If they differ, we abort this swap.
2020 	 * This is the mechanism used to ensure the calling
2021 	 * process that the file was not changed out from
2022 	 * under it.
2023 	 */
2024 	if ((sbp->bs_ctime.tv_sec != VFS_I(ip)->i_ctime.tv_sec) ||
2025 	    (sbp->bs_ctime.tv_nsec != VFS_I(ip)->i_ctime.tv_nsec) ||
2026 	    (sbp->bs_mtime.tv_sec != VFS_I(ip)->i_mtime.tv_sec) ||
2027 	    (sbp->bs_mtime.tv_nsec != VFS_I(ip)->i_mtime.tv_nsec)) {
2028 		error = -EBUSY;
2029 		goto out_trans_cancel;
2030 	}
2031 
2032 	/*
2033 	 * Note the trickiness in setting the log flags - we set the owner log
2034 	 * flag on the opposite inode (i.e. the inode we are setting the new
2035 	 * owner to be) because once we swap the forks and log that, log
2036 	 * recovery is going to see the fork as owned by the swapped inode,
2037 	 * not the pre-swapped inodes.
2038 	 */
2039 	src_log_flags = XFS_ILOG_CORE;
2040 	target_log_flags = XFS_ILOG_CORE;
2041 
2042 	if (xfs_sb_version_hasrmapbt(&mp->m_sb))
2043 		error = xfs_swap_extent_rmap(&tp, ip, tip);
2044 	else
2045 		error = xfs_swap_extent_forks(tp, ip, tip, &src_log_flags,
2046 				&target_log_flags);
2047 	if (error)
2048 		goto out_trans_cancel;
2049 
2050 	/* Do we have to swap reflink flags? */
2051 	if ((ip->i_d.di_flags2 & XFS_DIFLAG2_REFLINK) ^
2052 	    (tip->i_d.di_flags2 & XFS_DIFLAG2_REFLINK)) {
2053 		f = ip->i_d.di_flags2 & XFS_DIFLAG2_REFLINK;
2054 		ip->i_d.di_flags2 &= ~XFS_DIFLAG2_REFLINK;
2055 		ip->i_d.di_flags2 |= tip->i_d.di_flags2 & XFS_DIFLAG2_REFLINK;
2056 		tip->i_d.di_flags2 &= ~XFS_DIFLAG2_REFLINK;
2057 		tip->i_d.di_flags2 |= f & XFS_DIFLAG2_REFLINK;
2058 		cowfp = ip->i_cowfp;
2059 		ip->i_cowfp = tip->i_cowfp;
2060 		tip->i_cowfp = cowfp;
2061 		xfs_inode_set_cowblocks_tag(ip);
2062 		xfs_inode_set_cowblocks_tag(tip);
2063 	}
2064 
2065 	xfs_trans_log_inode(tp, ip,  src_log_flags);
2066 	xfs_trans_log_inode(tp, tip, target_log_flags);
2067 
2068 	/*
2069 	 * If this is a synchronous mount, make sure that the
2070 	 * transaction goes to disk before returning to the user.
2071 	 */
2072 	if (mp->m_flags & XFS_MOUNT_WSYNC)
2073 		xfs_trans_set_sync(tp);
2074 
2075 	error = xfs_trans_commit(tp);
2076 
2077 	trace_xfs_swap_extent_after(ip, 0);
2078 	trace_xfs_swap_extent_after(tip, 1);
2079 
2080 out_unlock:
2081 	xfs_iunlock(ip, lock_flags);
2082 	xfs_iunlock(tip, lock_flags);
2083 	unlock_two_nondirectories(VFS_I(ip), VFS_I(tip));
2084 	return error;
2085 
2086 out_trans_cancel:
2087 	xfs_trans_cancel(tp);
2088 	goto out_unlock;
2089 }
2090