xref: /linux/fs/xfs/xfs_bmap_util.c (revision 66e72a01b60ae6950ddbb3585fdc1424d303e14b)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2006 Silicon Graphics, Inc.
4  * Copyright (c) 2012 Red Hat, Inc.
5  * All Rights Reserved.
6  */
7 #include "xfs.h"
8 #include "xfs_fs.h"
9 #include "xfs_shared.h"
10 #include "xfs_format.h"
11 #include "xfs_log_format.h"
12 #include "xfs_trans_resv.h"
13 #include "xfs_bit.h"
14 #include "xfs_mount.h"
15 #include "xfs_defer.h"
16 #include "xfs_inode.h"
17 #include "xfs_btree.h"
18 #include "xfs_trans.h"
19 #include "xfs_alloc.h"
20 #include "xfs_bmap.h"
21 #include "xfs_bmap_util.h"
22 #include "xfs_bmap_btree.h"
23 #include "xfs_rtalloc.h"
24 #include "xfs_error.h"
25 #include "xfs_quota.h"
26 #include "xfs_trans_space.h"
27 #include "xfs_trace.h"
28 #include "xfs_icache.h"
29 #include "xfs_iomap.h"
30 #include "xfs_reflink.h"
31 #include "xfs_rtbitmap.h"
32 
33 /* Kernel only BMAP related definitions and functions */
34 
35 /*
36  * Convert the given file system block to a disk block.  We have to treat it
37  * differently based on whether the file is a real time file or not, because the
38  * bmap code does.
39  */
40 xfs_daddr_t
41 xfs_fsb_to_db(struct xfs_inode *ip, xfs_fsblock_t fsb)
42 {
43 	if (XFS_IS_REALTIME_INODE(ip))
44 		return XFS_FSB_TO_BB(ip->i_mount, fsb);
45 	return XFS_FSB_TO_DADDR(ip->i_mount, fsb);
46 }
47 
48 /*
49  * Routine to zero an extent on disk allocated to the specific inode.
50  *
51  * The VFS functions take a linearised filesystem block offset, so we have to
52  * convert the sparse xfs fsb to the right format first.
53  * VFS types are real funky, too.
54  */
55 int
56 xfs_zero_extent(
57 	struct xfs_inode	*ip,
58 	xfs_fsblock_t		start_fsb,
59 	xfs_off_t		count_fsb)
60 {
61 	struct xfs_mount	*mp = ip->i_mount;
62 	struct xfs_buftarg	*target = xfs_inode_buftarg(ip);
63 	xfs_daddr_t		sector = xfs_fsb_to_db(ip, start_fsb);
64 	sector_t		block = XFS_BB_TO_FSBT(mp, sector);
65 
66 	return blkdev_issue_zeroout(target->bt_bdev,
67 		block << (mp->m_super->s_blocksize_bits - 9),
68 		count_fsb << (mp->m_super->s_blocksize_bits - 9),
69 		GFP_KERNEL, 0);
70 }
71 
72 /*
73  * Extent tree block counting routines.
74  */
75 
76 /*
77  * Count leaf blocks given a range of extent records.  Delayed allocation
78  * extents are not counted towards the totals.
79  */
80 xfs_extnum_t
81 xfs_bmap_count_leaves(
82 	struct xfs_ifork	*ifp,
83 	xfs_filblks_t		*count)
84 {
85 	struct xfs_iext_cursor	icur;
86 	struct xfs_bmbt_irec	got;
87 	xfs_extnum_t		numrecs = 0;
88 
89 	for_each_xfs_iext(ifp, &icur, &got) {
90 		if (!isnullstartblock(got.br_startblock)) {
91 			*count += got.br_blockcount;
92 			numrecs++;
93 		}
94 	}
95 
96 	return numrecs;
97 }
98 
99 /*
100  * Count fsblocks of the given fork.  Delayed allocation extents are
101  * not counted towards the totals.
102  */
103 int
104 xfs_bmap_count_blocks(
105 	struct xfs_trans	*tp,
106 	struct xfs_inode	*ip,
107 	int			whichfork,
108 	xfs_extnum_t		*nextents,
109 	xfs_filblks_t		*count)
110 {
111 	struct xfs_mount	*mp = ip->i_mount;
112 	struct xfs_ifork	*ifp = xfs_ifork_ptr(ip, whichfork);
113 	struct xfs_btree_cur	*cur;
114 	xfs_extlen_t		btblocks = 0;
115 	int			error;
116 
117 	*nextents = 0;
118 	*count = 0;
119 
120 	if (!ifp)
121 		return 0;
122 
123 	switch (ifp->if_format) {
124 	case XFS_DINODE_FMT_BTREE:
125 		error = xfs_iread_extents(tp, ip, whichfork);
126 		if (error)
127 			return error;
128 
129 		cur = xfs_bmbt_init_cursor(mp, tp, ip, whichfork);
130 		error = xfs_btree_count_blocks(cur, &btblocks);
131 		xfs_btree_del_cursor(cur, error);
132 		if (error)
133 			return error;
134 
135 		/*
136 		 * xfs_btree_count_blocks includes the root block contained in
137 		 * the inode fork in @btblocks, so subtract one because we're
138 		 * only interested in allocated disk blocks.
139 		 */
140 		*count += btblocks - 1;
141 
142 		fallthrough;
143 	case XFS_DINODE_FMT_EXTENTS:
144 		*nextents = xfs_bmap_count_leaves(ifp, count);
145 		break;
146 	}
147 
148 	return 0;
149 }
150 
151 static int
152 xfs_getbmap_report_one(
153 	struct xfs_inode	*ip,
154 	struct getbmapx		*bmv,
155 	struct kgetbmap		*out,
156 	int64_t			bmv_end,
157 	struct xfs_bmbt_irec	*got)
158 {
159 	struct kgetbmap		*p = out + bmv->bmv_entries;
160 	bool			shared = false;
161 	int			error;
162 
163 	error = xfs_reflink_trim_around_shared(ip, got, &shared);
164 	if (error)
165 		return error;
166 
167 	if (isnullstartblock(got->br_startblock) ||
168 	    got->br_startblock == DELAYSTARTBLOCK) {
169 		/*
170 		 * Take the flush completion as being a point-in-time snapshot
171 		 * where there are no delalloc extents, and if any new ones
172 		 * have been created racily, just skip them as being 'after'
173 		 * the flush and so don't get reported.
174 		 */
175 		if (!(bmv->bmv_iflags & BMV_IF_DELALLOC))
176 			return 0;
177 
178 		p->bmv_oflags |= BMV_OF_DELALLOC;
179 		p->bmv_block = -2;
180 	} else {
181 		p->bmv_block = xfs_fsb_to_db(ip, got->br_startblock);
182 	}
183 
184 	if (got->br_state == XFS_EXT_UNWRITTEN &&
185 	    (bmv->bmv_iflags & BMV_IF_PREALLOC))
186 		p->bmv_oflags |= BMV_OF_PREALLOC;
187 
188 	if (shared)
189 		p->bmv_oflags |= BMV_OF_SHARED;
190 
191 	p->bmv_offset = XFS_FSB_TO_BB(ip->i_mount, got->br_startoff);
192 	p->bmv_length = XFS_FSB_TO_BB(ip->i_mount, got->br_blockcount);
193 
194 	bmv->bmv_offset = p->bmv_offset + p->bmv_length;
195 	bmv->bmv_length = max(0LL, bmv_end - bmv->bmv_offset);
196 	bmv->bmv_entries++;
197 	return 0;
198 }
199 
200 static void
201 xfs_getbmap_report_hole(
202 	struct xfs_inode	*ip,
203 	struct getbmapx		*bmv,
204 	struct kgetbmap		*out,
205 	int64_t			bmv_end,
206 	xfs_fileoff_t		bno,
207 	xfs_fileoff_t		end)
208 {
209 	struct kgetbmap		*p = out + bmv->bmv_entries;
210 
211 	if (bmv->bmv_iflags & BMV_IF_NO_HOLES)
212 		return;
213 
214 	p->bmv_block = -1;
215 	p->bmv_offset = XFS_FSB_TO_BB(ip->i_mount, bno);
216 	p->bmv_length = XFS_FSB_TO_BB(ip->i_mount, end - bno);
217 
218 	bmv->bmv_offset = p->bmv_offset + p->bmv_length;
219 	bmv->bmv_length = max(0LL, bmv_end - bmv->bmv_offset);
220 	bmv->bmv_entries++;
221 }
222 
223 static inline bool
224 xfs_getbmap_full(
225 	struct getbmapx		*bmv)
226 {
227 	return bmv->bmv_length == 0 || bmv->bmv_entries >= bmv->bmv_count - 1;
228 }
229 
230 static bool
231 xfs_getbmap_next_rec(
232 	struct xfs_bmbt_irec	*rec,
233 	xfs_fileoff_t		total_end)
234 {
235 	xfs_fileoff_t		end = rec->br_startoff + rec->br_blockcount;
236 
237 	if (end == total_end)
238 		return false;
239 
240 	rec->br_startoff += rec->br_blockcount;
241 	if (!isnullstartblock(rec->br_startblock) &&
242 	    rec->br_startblock != DELAYSTARTBLOCK)
243 		rec->br_startblock += rec->br_blockcount;
244 	rec->br_blockcount = total_end - end;
245 	return true;
246 }
247 
248 /*
249  * Get inode's extents as described in bmv, and format for output.
250  * Calls formatter to fill the user's buffer until all extents
251  * are mapped, until the passed-in bmv->bmv_count slots have
252  * been filled, or until the formatter short-circuits the loop,
253  * if it is tracking filled-in extents on its own.
254  */
255 int						/* error code */
256 xfs_getbmap(
257 	struct xfs_inode	*ip,
258 	struct getbmapx		*bmv,		/* user bmap structure */
259 	struct kgetbmap		*out)
260 {
261 	struct xfs_mount	*mp = ip->i_mount;
262 	int			iflags = bmv->bmv_iflags;
263 	int			whichfork, lock, error = 0;
264 	int64_t			bmv_end, max_len;
265 	xfs_fileoff_t		bno, first_bno;
266 	struct xfs_ifork	*ifp;
267 	struct xfs_bmbt_irec	got, rec;
268 	xfs_filblks_t		len;
269 	struct xfs_iext_cursor	icur;
270 
271 	if (bmv->bmv_iflags & ~BMV_IF_VALID)
272 		return -EINVAL;
273 #ifndef DEBUG
274 	/* Only allow CoW fork queries if we're debugging. */
275 	if (iflags & BMV_IF_COWFORK)
276 		return -EINVAL;
277 #endif
278 	if ((iflags & BMV_IF_ATTRFORK) && (iflags & BMV_IF_COWFORK))
279 		return -EINVAL;
280 
281 	if (bmv->bmv_length < -1)
282 		return -EINVAL;
283 	bmv->bmv_entries = 0;
284 	if (bmv->bmv_length == 0)
285 		return 0;
286 
287 	if (iflags & BMV_IF_ATTRFORK)
288 		whichfork = XFS_ATTR_FORK;
289 	else if (iflags & BMV_IF_COWFORK)
290 		whichfork = XFS_COW_FORK;
291 	else
292 		whichfork = XFS_DATA_FORK;
293 
294 	xfs_ilock(ip, XFS_IOLOCK_SHARED);
295 	switch (whichfork) {
296 	case XFS_ATTR_FORK:
297 		lock = xfs_ilock_attr_map_shared(ip);
298 		if (!xfs_inode_has_attr_fork(ip))
299 			goto out_unlock_ilock;
300 
301 		max_len = 1LL << 32;
302 		break;
303 	case XFS_COW_FORK:
304 		lock = XFS_ILOCK_SHARED;
305 		xfs_ilock(ip, lock);
306 
307 		/* No CoW fork? Just return */
308 		if (!xfs_ifork_ptr(ip, whichfork))
309 			goto out_unlock_ilock;
310 
311 		if (xfs_get_cowextsz_hint(ip))
312 			max_len = mp->m_super->s_maxbytes;
313 		else
314 			max_len = XFS_ISIZE(ip);
315 		break;
316 	case XFS_DATA_FORK:
317 		if (!(iflags & BMV_IF_DELALLOC) &&
318 		    (ip->i_delayed_blks || XFS_ISIZE(ip) > ip->i_disk_size)) {
319 			error = filemap_write_and_wait(VFS_I(ip)->i_mapping);
320 			if (error)
321 				goto out_unlock_iolock;
322 
323 			/*
324 			 * Even after flushing the inode, there can still be
325 			 * delalloc blocks on the inode beyond EOF due to
326 			 * speculative preallocation.  These are not removed
327 			 * until the release function is called or the inode
328 			 * is inactivated.  Hence we cannot assert here that
329 			 * ip->i_delayed_blks == 0.
330 			 */
331 		}
332 
333 		if (xfs_get_extsz_hint(ip) ||
334 		    (ip->i_diflags &
335 		     (XFS_DIFLAG_PREALLOC | XFS_DIFLAG_APPEND)))
336 			max_len = mp->m_super->s_maxbytes;
337 		else
338 			max_len = XFS_ISIZE(ip);
339 
340 		lock = xfs_ilock_data_map_shared(ip);
341 		break;
342 	}
343 
344 	ifp = xfs_ifork_ptr(ip, whichfork);
345 
346 	switch (ifp->if_format) {
347 	case XFS_DINODE_FMT_EXTENTS:
348 	case XFS_DINODE_FMT_BTREE:
349 		break;
350 	case XFS_DINODE_FMT_LOCAL:
351 		/* Local format inode forks report no extents. */
352 		goto out_unlock_ilock;
353 	default:
354 		error = -EINVAL;
355 		goto out_unlock_ilock;
356 	}
357 
358 	if (bmv->bmv_length == -1) {
359 		max_len = XFS_FSB_TO_BB(mp, XFS_B_TO_FSB(mp, max_len));
360 		bmv->bmv_length = max(0LL, max_len - bmv->bmv_offset);
361 	}
362 
363 	bmv_end = bmv->bmv_offset + bmv->bmv_length;
364 
365 	first_bno = bno = XFS_BB_TO_FSBT(mp, bmv->bmv_offset);
366 	len = XFS_BB_TO_FSB(mp, bmv->bmv_length);
367 
368 	error = xfs_iread_extents(NULL, ip, whichfork);
369 	if (error)
370 		goto out_unlock_ilock;
371 
372 	if (!xfs_iext_lookup_extent(ip, ifp, bno, &icur, &got)) {
373 		/*
374 		 * Report a whole-file hole if the delalloc flag is set to
375 		 * stay compatible with the old implementation.
376 		 */
377 		if (iflags & BMV_IF_DELALLOC)
378 			xfs_getbmap_report_hole(ip, bmv, out, bmv_end, bno,
379 					XFS_B_TO_FSB(mp, XFS_ISIZE(ip)));
380 		goto out_unlock_ilock;
381 	}
382 
383 	while (!xfs_getbmap_full(bmv)) {
384 		xfs_trim_extent(&got, first_bno, len);
385 
386 		/*
387 		 * Report an entry for a hole if this extent doesn't directly
388 		 * follow the previous one.
389 		 */
390 		if (got.br_startoff > bno) {
391 			xfs_getbmap_report_hole(ip, bmv, out, bmv_end, bno,
392 					got.br_startoff);
393 			if (xfs_getbmap_full(bmv))
394 				break;
395 		}
396 
397 		/*
398 		 * In order to report shared extents accurately, we report each
399 		 * distinct shared / unshared part of a single bmbt record with
400 		 * an individual getbmapx record.
401 		 */
402 		bno = got.br_startoff + got.br_blockcount;
403 		rec = got;
404 		do {
405 			error = xfs_getbmap_report_one(ip, bmv, out, bmv_end,
406 					&rec);
407 			if (error || xfs_getbmap_full(bmv))
408 				goto out_unlock_ilock;
409 		} while (xfs_getbmap_next_rec(&rec, bno));
410 
411 		if (!xfs_iext_next_extent(ifp, &icur, &got)) {
412 			xfs_fileoff_t	end = XFS_B_TO_FSB(mp, XFS_ISIZE(ip));
413 
414 			if (bmv->bmv_entries > 0)
415 				out[bmv->bmv_entries - 1].bmv_oflags |=
416 								BMV_OF_LAST;
417 
418 			if (whichfork != XFS_ATTR_FORK && bno < end &&
419 			    !xfs_getbmap_full(bmv)) {
420 				xfs_getbmap_report_hole(ip, bmv, out, bmv_end,
421 						bno, end);
422 			}
423 			break;
424 		}
425 
426 		if (bno >= first_bno + len)
427 			break;
428 	}
429 
430 out_unlock_ilock:
431 	xfs_iunlock(ip, lock);
432 out_unlock_iolock:
433 	xfs_iunlock(ip, XFS_IOLOCK_SHARED);
434 	return error;
435 }
436 
437 /*
438  * Dead simple method of punching delalyed allocation blocks from a range in
439  * the inode.  This will always punch out both the start and end blocks, even
440  * if the ranges only partially overlap them, so it is up to the caller to
441  * ensure that partial blocks are not passed in.
442  */
443 void
444 xfs_bmap_punch_delalloc_range(
445 	struct xfs_inode	*ip,
446 	xfs_off_t		start_byte,
447 	xfs_off_t		end_byte)
448 {
449 	struct xfs_mount	*mp = ip->i_mount;
450 	struct xfs_ifork	*ifp = &ip->i_df;
451 	xfs_fileoff_t		start_fsb = XFS_B_TO_FSBT(mp, start_byte);
452 	xfs_fileoff_t		end_fsb = XFS_B_TO_FSB(mp, end_byte);
453 	struct xfs_bmbt_irec	got, del;
454 	struct xfs_iext_cursor	icur;
455 
456 	ASSERT(!xfs_need_iread_extents(ifp));
457 
458 	xfs_ilock(ip, XFS_ILOCK_EXCL);
459 	if (!xfs_iext_lookup_extent_before(ip, ifp, &end_fsb, &icur, &got))
460 		goto out_unlock;
461 
462 	while (got.br_startoff + got.br_blockcount > start_fsb) {
463 		del = got;
464 		xfs_trim_extent(&del, start_fsb, end_fsb - start_fsb);
465 
466 		/*
467 		 * A delete can push the cursor forward. Step back to the
468 		 * previous extent on non-delalloc or extents outside the
469 		 * target range.
470 		 */
471 		if (!del.br_blockcount ||
472 		    !isnullstartblock(del.br_startblock)) {
473 			if (!xfs_iext_prev_extent(ifp, &icur, &got))
474 				break;
475 			continue;
476 		}
477 
478 		xfs_bmap_del_extent_delay(ip, XFS_DATA_FORK, &icur, &got, &del);
479 		if (!xfs_iext_get_extent(ifp, &icur, &got))
480 			break;
481 	}
482 
483 out_unlock:
484 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
485 }
486 
487 /*
488  * Test whether it is appropriate to check an inode for and free post EOF
489  * blocks.
490  */
491 bool
492 xfs_can_free_eofblocks(
493 	struct xfs_inode	*ip)
494 {
495 	struct xfs_bmbt_irec	imap;
496 	struct xfs_mount	*mp = ip->i_mount;
497 	xfs_fileoff_t		end_fsb;
498 	xfs_fileoff_t		last_fsb;
499 	int			nimaps = 1;
500 	int			error;
501 
502 	/*
503 	 * Caller must either hold the exclusive io lock; or be inactivating
504 	 * the inode, which guarantees there are no other users of the inode.
505 	 */
506 	if (!(VFS_I(ip)->i_state & I_FREEING))
507 		xfs_assert_ilocked(ip, XFS_IOLOCK_EXCL);
508 
509 	/* prealloc/delalloc exists only on regular files */
510 	if (!S_ISREG(VFS_I(ip)->i_mode))
511 		return false;
512 
513 	/*
514 	 * Zero sized files with no cached pages and delalloc blocks will not
515 	 * have speculative prealloc/delalloc blocks to remove.
516 	 */
517 	if (VFS_I(ip)->i_size == 0 &&
518 	    VFS_I(ip)->i_mapping->nrpages == 0 &&
519 	    ip->i_delayed_blks == 0)
520 		return false;
521 
522 	/* If we haven't read in the extent list, then don't do it now. */
523 	if (xfs_need_iread_extents(&ip->i_df))
524 		return false;
525 
526 	/*
527 	 * Only free real extents for inodes with persistent preallocations or
528 	 * the append-only flag.
529 	 */
530 	if (ip->i_diflags & (XFS_DIFLAG_PREALLOC | XFS_DIFLAG_APPEND))
531 		if (ip->i_delayed_blks == 0)
532 			return false;
533 
534 	/*
535 	 * Do not try to free post-EOF blocks if EOF is beyond the end of the
536 	 * range supported by the page cache, because the truncation will loop
537 	 * forever.
538 	 */
539 	end_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)XFS_ISIZE(ip));
540 	if (xfs_inode_has_bigrtalloc(ip))
541 		end_fsb = xfs_rtb_roundup_rtx(mp, end_fsb);
542 	last_fsb = XFS_B_TO_FSB(mp, mp->m_super->s_maxbytes);
543 	if (last_fsb <= end_fsb)
544 		return false;
545 
546 	/*
547 	 * Look up the mapping for the first block past EOF.  If we can't find
548 	 * it, there's nothing to free.
549 	 */
550 	xfs_ilock(ip, XFS_ILOCK_SHARED);
551 	error = xfs_bmapi_read(ip, end_fsb, last_fsb - end_fsb, &imap, &nimaps,
552 			0);
553 	xfs_iunlock(ip, XFS_ILOCK_SHARED);
554 	if (error || nimaps == 0)
555 		return false;
556 
557 	/*
558 	 * If there's a real mapping there or there are delayed allocation
559 	 * reservations, then we have post-EOF blocks to try to free.
560 	 */
561 	return imap.br_startblock != HOLESTARTBLOCK || ip->i_delayed_blks;
562 }
563 
564 /*
565  * This is called to free any blocks beyond eof. The caller must hold
566  * IOLOCK_EXCL unless we are in the inode reclaim path and have the only
567  * reference to the inode.
568  */
569 int
570 xfs_free_eofblocks(
571 	struct xfs_inode	*ip)
572 {
573 	struct xfs_trans	*tp;
574 	struct xfs_mount	*mp = ip->i_mount;
575 	int			error;
576 
577 	/* Attach the dquots to the inode up front. */
578 	error = xfs_qm_dqattach(ip);
579 	if (error)
580 		return error;
581 
582 	/* Wait on dio to ensure i_size has settled. */
583 	inode_dio_wait(VFS_I(ip));
584 
585 	/*
586 	 * For preallocated files only free delayed allocations.
587 	 *
588 	 * Note that this means we also leave speculative preallocations in
589 	 * place for preallocated files.
590 	 */
591 	if (ip->i_diflags & (XFS_DIFLAG_PREALLOC | XFS_DIFLAG_APPEND)) {
592 		if (ip->i_delayed_blks) {
593 			xfs_bmap_punch_delalloc_range(ip,
594 				round_up(XFS_ISIZE(ip), mp->m_sb.sb_blocksize),
595 				LLONG_MAX);
596 		}
597 		xfs_inode_clear_eofblocks_tag(ip);
598 		return 0;
599 	}
600 
601 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_itruncate, 0, 0, 0, &tp);
602 	if (error) {
603 		ASSERT(xfs_is_shutdown(mp));
604 		return error;
605 	}
606 
607 	xfs_ilock(ip, XFS_ILOCK_EXCL);
608 	xfs_trans_ijoin(tp, ip, 0);
609 
610 	/*
611 	 * Do not update the on-disk file size.  If we update the on-disk file
612 	 * size and then the system crashes before the contents of the file are
613 	 * flushed to disk then the files may be full of holes (ie NULL files
614 	 * bug).
615 	 */
616 	error = xfs_itruncate_extents_flags(&tp, ip, XFS_DATA_FORK,
617 				XFS_ISIZE(ip), XFS_BMAPI_NODISCARD);
618 	if (error)
619 		goto err_cancel;
620 
621 	error = xfs_trans_commit(tp);
622 	if (error)
623 		goto out_unlock;
624 
625 	xfs_inode_clear_eofblocks_tag(ip);
626 	goto out_unlock;
627 
628 err_cancel:
629 	/*
630 	 * If we get an error at this point we simply don't
631 	 * bother truncating the file.
632 	 */
633 	xfs_trans_cancel(tp);
634 out_unlock:
635 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
636 	return error;
637 }
638 
639 int
640 xfs_alloc_file_space(
641 	struct xfs_inode	*ip,
642 	xfs_off_t		offset,
643 	xfs_off_t		len)
644 {
645 	xfs_mount_t		*mp = ip->i_mount;
646 	xfs_off_t		count;
647 	xfs_filblks_t		allocatesize_fsb;
648 	xfs_extlen_t		extsz, temp;
649 	xfs_fileoff_t		startoffset_fsb;
650 	xfs_fileoff_t		endoffset_fsb;
651 	int			rt;
652 	xfs_trans_t		*tp;
653 	xfs_bmbt_irec_t		imaps[1], *imapp;
654 	int			error;
655 
656 	trace_xfs_alloc_file_space(ip);
657 
658 	if (xfs_is_shutdown(mp))
659 		return -EIO;
660 
661 	error = xfs_qm_dqattach(ip);
662 	if (error)
663 		return error;
664 
665 	if (len <= 0)
666 		return -EINVAL;
667 
668 	rt = XFS_IS_REALTIME_INODE(ip);
669 	extsz = xfs_get_extsz_hint(ip);
670 
671 	count = len;
672 	imapp = &imaps[0];
673 	startoffset_fsb	= XFS_B_TO_FSBT(mp, offset);
674 	endoffset_fsb = XFS_B_TO_FSB(mp, offset + count);
675 	allocatesize_fsb = endoffset_fsb - startoffset_fsb;
676 
677 	/*
678 	 * Allocate file space until done or until there is an error
679 	 */
680 	while (allocatesize_fsb && !error) {
681 		xfs_fileoff_t	s, e;
682 		unsigned int	dblocks, rblocks, resblks;
683 		int		nimaps = 1;
684 
685 		/*
686 		 * Determine space reservations for data/realtime.
687 		 */
688 		if (unlikely(extsz)) {
689 			s = startoffset_fsb;
690 			do_div(s, extsz);
691 			s *= extsz;
692 			e = startoffset_fsb + allocatesize_fsb;
693 			div_u64_rem(startoffset_fsb, extsz, &temp);
694 			if (temp)
695 				e += temp;
696 			div_u64_rem(e, extsz, &temp);
697 			if (temp)
698 				e += extsz - temp;
699 		} else {
700 			s = 0;
701 			e = allocatesize_fsb;
702 		}
703 
704 		/*
705 		 * The transaction reservation is limited to a 32-bit block
706 		 * count, hence we need to limit the number of blocks we are
707 		 * trying to reserve to avoid an overflow. We can't allocate
708 		 * more than @nimaps extents, and an extent is limited on disk
709 		 * to XFS_BMBT_MAX_EXTLEN (21 bits), so use that to enforce the
710 		 * limit.
711 		 */
712 		resblks = min_t(xfs_fileoff_t, (e - s),
713 				(XFS_MAX_BMBT_EXTLEN * nimaps));
714 		if (unlikely(rt)) {
715 			dblocks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
716 			rblocks = resblks;
717 		} else {
718 			dblocks = XFS_DIOSTRAT_SPACE_RES(mp, resblks);
719 			rblocks = 0;
720 		}
721 
722 		error = xfs_trans_alloc_inode(ip, &M_RES(mp)->tr_write,
723 				dblocks, rblocks, false, &tp);
724 		if (error)
725 			break;
726 
727 		error = xfs_iext_count_extend(tp, ip, XFS_DATA_FORK,
728 				XFS_IEXT_ADD_NOSPLIT_CNT);
729 		if (error)
730 			goto error;
731 
732 		/*
733 		 * If the allocator cannot find a single free extent large
734 		 * enough to cover the start block of the requested range,
735 		 * xfs_bmapi_write will return -ENOSR.
736 		 *
737 		 * In that case we simply need to keep looping with the same
738 		 * startoffset_fsb so that one of the following allocations
739 		 * will eventually reach the requested range.
740 		 */
741 		error = xfs_bmapi_write(tp, ip, startoffset_fsb,
742 				allocatesize_fsb, XFS_BMAPI_PREALLOC, 0, imapp,
743 				&nimaps);
744 		if (error) {
745 			if (error != -ENOSR)
746 				goto error;
747 			error = 0;
748 		} else {
749 			startoffset_fsb += imapp->br_blockcount;
750 			allocatesize_fsb -= imapp->br_blockcount;
751 		}
752 
753 		ip->i_diflags |= XFS_DIFLAG_PREALLOC;
754 		xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
755 
756 		error = xfs_trans_commit(tp);
757 		xfs_iunlock(ip, XFS_ILOCK_EXCL);
758 	}
759 
760 	return error;
761 
762 error:
763 	xfs_trans_cancel(tp);
764 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
765 	return error;
766 }
767 
768 static int
769 xfs_unmap_extent(
770 	struct xfs_inode	*ip,
771 	xfs_fileoff_t		startoffset_fsb,
772 	xfs_filblks_t		len_fsb,
773 	int			*done)
774 {
775 	struct xfs_mount	*mp = ip->i_mount;
776 	struct xfs_trans	*tp;
777 	uint			resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
778 	int			error;
779 
780 	error = xfs_trans_alloc_inode(ip, &M_RES(mp)->tr_write, resblks, 0,
781 			false, &tp);
782 	if (error)
783 		return error;
784 
785 	error = xfs_iext_count_extend(tp, ip, XFS_DATA_FORK,
786 			XFS_IEXT_PUNCH_HOLE_CNT);
787 	if (error)
788 		goto out_trans_cancel;
789 
790 	error = xfs_bunmapi(tp, ip, startoffset_fsb, len_fsb, 0, 2, done);
791 	if (error)
792 		goto out_trans_cancel;
793 
794 	error = xfs_trans_commit(tp);
795 out_unlock:
796 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
797 	return error;
798 
799 out_trans_cancel:
800 	xfs_trans_cancel(tp);
801 	goto out_unlock;
802 }
803 
804 /* Caller must first wait for the completion of any pending DIOs if required. */
805 int
806 xfs_flush_unmap_range(
807 	struct xfs_inode	*ip,
808 	xfs_off_t		offset,
809 	xfs_off_t		len)
810 {
811 	struct inode		*inode = VFS_I(ip);
812 	xfs_off_t		rounding, start, end;
813 	int			error;
814 
815 	/*
816 	 * Make sure we extend the flush out to extent alignment
817 	 * boundaries so any extent range overlapping the start/end
818 	 * of the modification we are about to do is clean and idle.
819 	 */
820 	rounding = max_t(xfs_off_t, xfs_inode_alloc_unitsize(ip), PAGE_SIZE);
821 	start = rounddown_64(offset, rounding);
822 	end = roundup_64(offset + len, rounding) - 1;
823 
824 	error = filemap_write_and_wait_range(inode->i_mapping, start, end);
825 	if (error)
826 		return error;
827 	truncate_pagecache_range(inode, start, end);
828 	return 0;
829 }
830 
831 int
832 xfs_free_file_space(
833 	struct xfs_inode	*ip,
834 	xfs_off_t		offset,
835 	xfs_off_t		len)
836 {
837 	struct xfs_mount	*mp = ip->i_mount;
838 	xfs_fileoff_t		startoffset_fsb;
839 	xfs_fileoff_t		endoffset_fsb;
840 	int			done = 0, error;
841 
842 	trace_xfs_free_file_space(ip);
843 
844 	error = xfs_qm_dqattach(ip);
845 	if (error)
846 		return error;
847 
848 	if (len <= 0)	/* if nothing being freed */
849 		return 0;
850 
851 	startoffset_fsb = XFS_B_TO_FSB(mp, offset);
852 	endoffset_fsb = XFS_B_TO_FSBT(mp, offset + len);
853 
854 	/* We can only free complete realtime extents. */
855 	if (xfs_inode_has_bigrtalloc(ip)) {
856 		startoffset_fsb = xfs_rtb_roundup_rtx(mp, startoffset_fsb);
857 		endoffset_fsb = xfs_rtb_rounddown_rtx(mp, endoffset_fsb);
858 	}
859 
860 	/*
861 	 * Need to zero the stuff we're not freeing, on disk.
862 	 */
863 	if (endoffset_fsb > startoffset_fsb) {
864 		while (!done) {
865 			error = xfs_unmap_extent(ip, startoffset_fsb,
866 					endoffset_fsb - startoffset_fsb, &done);
867 			if (error)
868 				return error;
869 		}
870 	}
871 
872 	/*
873 	 * Now that we've unmap all full blocks we'll have to zero out any
874 	 * partial block at the beginning and/or end.  xfs_zero_range is smart
875 	 * enough to skip any holes, including those we just created, but we
876 	 * must take care not to zero beyond EOF and enlarge i_size.
877 	 */
878 	if (offset >= XFS_ISIZE(ip))
879 		return 0;
880 	if (offset + len > XFS_ISIZE(ip))
881 		len = XFS_ISIZE(ip) - offset;
882 	error = xfs_zero_range(ip, offset, len, NULL);
883 	if (error)
884 		return error;
885 
886 	/*
887 	 * If we zeroed right up to EOF and EOF straddles a page boundary we
888 	 * must make sure that the post-EOF area is also zeroed because the
889 	 * page could be mmap'd and xfs_zero_range doesn't do that for us.
890 	 * Writeback of the eof page will do this, albeit clumsily.
891 	 */
892 	if (offset + len >= XFS_ISIZE(ip) && offset_in_page(offset + len) > 0) {
893 		error = filemap_write_and_wait_range(VFS_I(ip)->i_mapping,
894 				round_down(offset + len, PAGE_SIZE), LLONG_MAX);
895 	}
896 
897 	return error;
898 }
899 
900 static int
901 xfs_prepare_shift(
902 	struct xfs_inode	*ip,
903 	loff_t			offset)
904 {
905 	unsigned int		rounding;
906 	int			error;
907 
908 	/*
909 	 * Trim eofblocks to avoid shifting uninitialized post-eof preallocation
910 	 * into the accessible region of the file.
911 	 */
912 	if (xfs_can_free_eofblocks(ip)) {
913 		error = xfs_free_eofblocks(ip);
914 		if (error)
915 			return error;
916 	}
917 
918 	/*
919 	 * Shift operations must stabilize the start block offset boundary along
920 	 * with the full range of the operation. If we don't, a COW writeback
921 	 * completion could race with an insert, front merge with the start
922 	 * extent (after split) during the shift and corrupt the file. Start
923 	 * with the allocation unit just prior to the start to stabilize the
924 	 * boundary.
925 	 */
926 	rounding = xfs_inode_alloc_unitsize(ip);
927 	offset = rounddown_64(offset, rounding);
928 	if (offset)
929 		offset -= rounding;
930 
931 	/*
932 	 * Writeback and invalidate cache for the remainder of the file as we're
933 	 * about to shift down every extent from offset to EOF.
934 	 */
935 	error = xfs_flush_unmap_range(ip, offset, XFS_ISIZE(ip));
936 	if (error)
937 		return error;
938 
939 	/*
940 	 * Clean out anything hanging around in the cow fork now that
941 	 * we've flushed all the dirty data out to disk to avoid having
942 	 * CoW extents at the wrong offsets.
943 	 */
944 	if (xfs_inode_has_cow_data(ip)) {
945 		error = xfs_reflink_cancel_cow_range(ip, offset, NULLFILEOFF,
946 				true);
947 		if (error)
948 			return error;
949 	}
950 
951 	return 0;
952 }
953 
954 /*
955  * xfs_collapse_file_space()
956  *	This routine frees disk space and shift extent for the given file.
957  *	The first thing we do is to free data blocks in the specified range
958  *	by calling xfs_free_file_space(). It would also sync dirty data
959  *	and invalidate page cache over the region on which collapse range
960  *	is working. And Shift extent records to the left to cover a hole.
961  * RETURNS:
962  *	0 on success
963  *	errno on error
964  *
965  */
966 int
967 xfs_collapse_file_space(
968 	struct xfs_inode	*ip,
969 	xfs_off_t		offset,
970 	xfs_off_t		len)
971 {
972 	struct xfs_mount	*mp = ip->i_mount;
973 	struct xfs_trans	*tp;
974 	int			error;
975 	xfs_fileoff_t		next_fsb = XFS_B_TO_FSB(mp, offset + len);
976 	xfs_fileoff_t		shift_fsb = XFS_B_TO_FSB(mp, len);
977 	bool			done = false;
978 
979 	xfs_assert_ilocked(ip, XFS_IOLOCK_EXCL | XFS_MMAPLOCK_EXCL);
980 
981 	trace_xfs_collapse_file_space(ip);
982 
983 	error = xfs_free_file_space(ip, offset, len);
984 	if (error)
985 		return error;
986 
987 	error = xfs_prepare_shift(ip, offset);
988 	if (error)
989 		return error;
990 
991 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, 0, 0, 0, &tp);
992 	if (error)
993 		return error;
994 
995 	xfs_ilock(ip, XFS_ILOCK_EXCL);
996 	xfs_trans_ijoin(tp, ip, 0);
997 
998 	while (!done) {
999 		error = xfs_bmap_collapse_extents(tp, ip, &next_fsb, shift_fsb,
1000 				&done);
1001 		if (error)
1002 			goto out_trans_cancel;
1003 		if (done)
1004 			break;
1005 
1006 		/* finish any deferred frees and roll the transaction */
1007 		error = xfs_defer_finish(&tp);
1008 		if (error)
1009 			goto out_trans_cancel;
1010 	}
1011 
1012 	error = xfs_trans_commit(tp);
1013 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1014 	return error;
1015 
1016 out_trans_cancel:
1017 	xfs_trans_cancel(tp);
1018 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1019 	return error;
1020 }
1021 
1022 /*
1023  * xfs_insert_file_space()
1024  *	This routine create hole space by shifting extents for the given file.
1025  *	The first thing we do is to sync dirty data and invalidate page cache
1026  *	over the region on which insert range is working. And split an extent
1027  *	to two extents at given offset by calling xfs_bmap_split_extent.
1028  *	And shift all extent records which are laying between [offset,
1029  *	last allocated extent] to the right to reserve hole range.
1030  * RETURNS:
1031  *	0 on success
1032  *	errno on error
1033  */
1034 int
1035 xfs_insert_file_space(
1036 	struct xfs_inode	*ip,
1037 	loff_t			offset,
1038 	loff_t			len)
1039 {
1040 	struct xfs_mount	*mp = ip->i_mount;
1041 	struct xfs_trans	*tp;
1042 	int			error;
1043 	xfs_fileoff_t		stop_fsb = XFS_B_TO_FSB(mp, offset);
1044 	xfs_fileoff_t		next_fsb = NULLFSBLOCK;
1045 	xfs_fileoff_t		shift_fsb = XFS_B_TO_FSB(mp, len);
1046 	bool			done = false;
1047 
1048 	xfs_assert_ilocked(ip, XFS_IOLOCK_EXCL | XFS_MMAPLOCK_EXCL);
1049 
1050 	trace_xfs_insert_file_space(ip);
1051 
1052 	error = xfs_bmap_can_insert_extents(ip, stop_fsb, shift_fsb);
1053 	if (error)
1054 		return error;
1055 
1056 	error = xfs_prepare_shift(ip, offset);
1057 	if (error)
1058 		return error;
1059 
1060 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write,
1061 			XFS_DIOSTRAT_SPACE_RES(mp, 0), 0, 0, &tp);
1062 	if (error)
1063 		return error;
1064 
1065 	xfs_ilock(ip, XFS_ILOCK_EXCL);
1066 	xfs_trans_ijoin(tp, ip, 0);
1067 
1068 	error = xfs_iext_count_extend(tp, ip, XFS_DATA_FORK,
1069 			XFS_IEXT_PUNCH_HOLE_CNT);
1070 	if (error)
1071 		goto out_trans_cancel;
1072 
1073 	/*
1074 	 * The extent shifting code works on extent granularity. So, if stop_fsb
1075 	 * is not the starting block of extent, we need to split the extent at
1076 	 * stop_fsb.
1077 	 */
1078 	error = xfs_bmap_split_extent(tp, ip, stop_fsb);
1079 	if (error)
1080 		goto out_trans_cancel;
1081 
1082 	do {
1083 		error = xfs_defer_finish(&tp);
1084 		if (error)
1085 			goto out_trans_cancel;
1086 
1087 		error = xfs_bmap_insert_extents(tp, ip, &next_fsb, shift_fsb,
1088 				&done, stop_fsb);
1089 		if (error)
1090 			goto out_trans_cancel;
1091 	} while (!done);
1092 
1093 	error = xfs_trans_commit(tp);
1094 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1095 	return error;
1096 
1097 out_trans_cancel:
1098 	xfs_trans_cancel(tp);
1099 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1100 	return error;
1101 }
1102 
1103 /*
1104  * We need to check that the format of the data fork in the temporary inode is
1105  * valid for the target inode before doing the swap. This is not a problem with
1106  * attr1 because of the fixed fork offset, but attr2 has a dynamically sized
1107  * data fork depending on the space the attribute fork is taking so we can get
1108  * invalid formats on the target inode.
1109  *
1110  * E.g. target has space for 7 extents in extent format, temp inode only has
1111  * space for 6.  If we defragment down to 7 extents, then the tmp format is a
1112  * btree, but when swapped it needs to be in extent format. Hence we can't just
1113  * blindly swap data forks on attr2 filesystems.
1114  *
1115  * Note that we check the swap in both directions so that we don't end up with
1116  * a corrupt temporary inode, either.
1117  *
1118  * Note that fixing the way xfs_fsr sets up the attribute fork in the source
1119  * inode will prevent this situation from occurring, so all we do here is
1120  * reject and log the attempt. basically we are putting the responsibility on
1121  * userspace to get this right.
1122  */
1123 static int
1124 xfs_swap_extents_check_format(
1125 	struct xfs_inode	*ip,	/* target inode */
1126 	struct xfs_inode	*tip)	/* tmp inode */
1127 {
1128 	struct xfs_ifork	*ifp = &ip->i_df;
1129 	struct xfs_ifork	*tifp = &tip->i_df;
1130 
1131 	/* User/group/project quota ids must match if quotas are enforced. */
1132 	if (XFS_IS_QUOTA_ON(ip->i_mount) &&
1133 	    (!uid_eq(VFS_I(ip)->i_uid, VFS_I(tip)->i_uid) ||
1134 	     !gid_eq(VFS_I(ip)->i_gid, VFS_I(tip)->i_gid) ||
1135 	     ip->i_projid != tip->i_projid))
1136 		return -EINVAL;
1137 
1138 	/* Should never get a local format */
1139 	if (ifp->if_format == XFS_DINODE_FMT_LOCAL ||
1140 	    tifp->if_format == XFS_DINODE_FMT_LOCAL)
1141 		return -EINVAL;
1142 
1143 	/*
1144 	 * if the target inode has less extents that then temporary inode then
1145 	 * why did userspace call us?
1146 	 */
1147 	if (ifp->if_nextents < tifp->if_nextents)
1148 		return -EINVAL;
1149 
1150 	/*
1151 	 * If we have to use the (expensive) rmap swap method, we can
1152 	 * handle any number of extents and any format.
1153 	 */
1154 	if (xfs_has_rmapbt(ip->i_mount))
1155 		return 0;
1156 
1157 	/*
1158 	 * if the target inode is in extent form and the temp inode is in btree
1159 	 * form then we will end up with the target inode in the wrong format
1160 	 * as we already know there are less extents in the temp inode.
1161 	 */
1162 	if (ifp->if_format == XFS_DINODE_FMT_EXTENTS &&
1163 	    tifp->if_format == XFS_DINODE_FMT_BTREE)
1164 		return -EINVAL;
1165 
1166 	/* Check temp in extent form to max in target */
1167 	if (tifp->if_format == XFS_DINODE_FMT_EXTENTS &&
1168 	    tifp->if_nextents > XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK))
1169 		return -EINVAL;
1170 
1171 	/* Check target in extent form to max in temp */
1172 	if (ifp->if_format == XFS_DINODE_FMT_EXTENTS &&
1173 	    ifp->if_nextents > XFS_IFORK_MAXEXT(tip, XFS_DATA_FORK))
1174 		return -EINVAL;
1175 
1176 	/*
1177 	 * If we are in a btree format, check that the temp root block will fit
1178 	 * in the target and that it has enough extents to be in btree format
1179 	 * in the target.
1180 	 *
1181 	 * Note that we have to be careful to allow btree->extent conversions
1182 	 * (a common defrag case) which will occur when the temp inode is in
1183 	 * extent format...
1184 	 */
1185 	if (tifp->if_format == XFS_DINODE_FMT_BTREE) {
1186 		if (xfs_inode_has_attr_fork(ip) &&
1187 		    XFS_BMAP_BMDR_SPACE(tifp->if_broot) > xfs_inode_fork_boff(ip))
1188 			return -EINVAL;
1189 		if (tifp->if_nextents <= XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK))
1190 			return -EINVAL;
1191 	}
1192 
1193 	/* Reciprocal target->temp btree format checks */
1194 	if (ifp->if_format == XFS_DINODE_FMT_BTREE) {
1195 		if (xfs_inode_has_attr_fork(tip) &&
1196 		    XFS_BMAP_BMDR_SPACE(ip->i_df.if_broot) > xfs_inode_fork_boff(tip))
1197 			return -EINVAL;
1198 		if (ifp->if_nextents <= XFS_IFORK_MAXEXT(tip, XFS_DATA_FORK))
1199 			return -EINVAL;
1200 	}
1201 
1202 	return 0;
1203 }
1204 
1205 static int
1206 xfs_swap_extent_flush(
1207 	struct xfs_inode	*ip)
1208 {
1209 	int	error;
1210 
1211 	error = filemap_write_and_wait(VFS_I(ip)->i_mapping);
1212 	if (error)
1213 		return error;
1214 	truncate_pagecache_range(VFS_I(ip), 0, -1);
1215 
1216 	/* Verify O_DIRECT for ftmp */
1217 	if (VFS_I(ip)->i_mapping->nrpages)
1218 		return -EINVAL;
1219 	return 0;
1220 }
1221 
1222 /*
1223  * Move extents from one file to another, when rmap is enabled.
1224  */
1225 STATIC int
1226 xfs_swap_extent_rmap(
1227 	struct xfs_trans		**tpp,
1228 	struct xfs_inode		*ip,
1229 	struct xfs_inode		*tip)
1230 {
1231 	struct xfs_trans		*tp = *tpp;
1232 	struct xfs_bmbt_irec		irec;
1233 	struct xfs_bmbt_irec		uirec;
1234 	struct xfs_bmbt_irec		tirec;
1235 	xfs_fileoff_t			offset_fsb;
1236 	xfs_fileoff_t			end_fsb;
1237 	xfs_filblks_t			count_fsb;
1238 	int				error;
1239 	xfs_filblks_t			ilen;
1240 	xfs_filblks_t			rlen;
1241 	int				nimaps;
1242 	uint64_t			tip_flags2;
1243 
1244 	/*
1245 	 * If the source file has shared blocks, we must flag the donor
1246 	 * file as having shared blocks so that we get the shared-block
1247 	 * rmap functions when we go to fix up the rmaps.  The flags
1248 	 * will be switch for reals later.
1249 	 */
1250 	tip_flags2 = tip->i_diflags2;
1251 	if (ip->i_diflags2 & XFS_DIFLAG2_REFLINK)
1252 		tip->i_diflags2 |= XFS_DIFLAG2_REFLINK;
1253 
1254 	offset_fsb = 0;
1255 	end_fsb = XFS_B_TO_FSB(ip->i_mount, i_size_read(VFS_I(ip)));
1256 	count_fsb = (xfs_filblks_t)(end_fsb - offset_fsb);
1257 
1258 	while (count_fsb) {
1259 		/* Read extent from the donor file */
1260 		nimaps = 1;
1261 		error = xfs_bmapi_read(tip, offset_fsb, count_fsb, &tirec,
1262 				&nimaps, 0);
1263 		if (error)
1264 			goto out;
1265 		ASSERT(nimaps == 1);
1266 		ASSERT(tirec.br_startblock != DELAYSTARTBLOCK);
1267 
1268 		trace_xfs_swap_extent_rmap_remap(tip, &tirec);
1269 		ilen = tirec.br_blockcount;
1270 
1271 		/* Unmap the old blocks in the source file. */
1272 		while (tirec.br_blockcount) {
1273 			ASSERT(tp->t_highest_agno == NULLAGNUMBER);
1274 			trace_xfs_swap_extent_rmap_remap_piece(tip, &tirec);
1275 
1276 			/* Read extent from the source file */
1277 			nimaps = 1;
1278 			error = xfs_bmapi_read(ip, tirec.br_startoff,
1279 					tirec.br_blockcount, &irec,
1280 					&nimaps, 0);
1281 			if (error)
1282 				goto out;
1283 			ASSERT(nimaps == 1);
1284 			ASSERT(tirec.br_startoff == irec.br_startoff);
1285 			trace_xfs_swap_extent_rmap_remap_piece(ip, &irec);
1286 
1287 			/* Trim the extent. */
1288 			uirec = tirec;
1289 			uirec.br_blockcount = rlen = min_t(xfs_filblks_t,
1290 					tirec.br_blockcount,
1291 					irec.br_blockcount);
1292 			trace_xfs_swap_extent_rmap_remap_piece(tip, &uirec);
1293 
1294 			if (xfs_bmap_is_real_extent(&uirec)) {
1295 				error = xfs_iext_count_extend(tp, ip,
1296 						XFS_DATA_FORK,
1297 						XFS_IEXT_SWAP_RMAP_CNT);
1298 				if (error)
1299 					goto out;
1300 			}
1301 
1302 			if (xfs_bmap_is_real_extent(&irec)) {
1303 				error = xfs_iext_count_extend(tp, tip,
1304 						XFS_DATA_FORK,
1305 						XFS_IEXT_SWAP_RMAP_CNT);
1306 				if (error)
1307 					goto out;
1308 			}
1309 
1310 			/* Remove the mapping from the donor file. */
1311 			xfs_bmap_unmap_extent(tp, tip, XFS_DATA_FORK, &uirec);
1312 
1313 			/* Remove the mapping from the source file. */
1314 			xfs_bmap_unmap_extent(tp, ip, XFS_DATA_FORK, &irec);
1315 
1316 			/* Map the donor file's blocks into the source file. */
1317 			xfs_bmap_map_extent(tp, ip, XFS_DATA_FORK, &uirec);
1318 
1319 			/* Map the source file's blocks into the donor file. */
1320 			xfs_bmap_map_extent(tp, tip, XFS_DATA_FORK, &irec);
1321 
1322 			error = xfs_defer_finish(tpp);
1323 			tp = *tpp;
1324 			if (error)
1325 				goto out;
1326 
1327 			tirec.br_startoff += rlen;
1328 			if (tirec.br_startblock != HOLESTARTBLOCK &&
1329 			    tirec.br_startblock != DELAYSTARTBLOCK)
1330 				tirec.br_startblock += rlen;
1331 			tirec.br_blockcount -= rlen;
1332 		}
1333 
1334 		/* Roll on... */
1335 		count_fsb -= ilen;
1336 		offset_fsb += ilen;
1337 	}
1338 
1339 	tip->i_diflags2 = tip_flags2;
1340 	return 0;
1341 
1342 out:
1343 	trace_xfs_swap_extent_rmap_error(ip, error, _RET_IP_);
1344 	tip->i_diflags2 = tip_flags2;
1345 	return error;
1346 }
1347 
1348 /* Swap the extents of two files by swapping data forks. */
1349 STATIC int
1350 xfs_swap_extent_forks(
1351 	struct xfs_trans	*tp,
1352 	struct xfs_inode	*ip,
1353 	struct xfs_inode	*tip,
1354 	int			*src_log_flags,
1355 	int			*target_log_flags)
1356 {
1357 	xfs_filblks_t		aforkblks = 0;
1358 	xfs_filblks_t		taforkblks = 0;
1359 	xfs_extnum_t		junk;
1360 	uint64_t		tmp;
1361 	int			error;
1362 
1363 	/*
1364 	 * Count the number of extended attribute blocks
1365 	 */
1366 	if (xfs_inode_has_attr_fork(ip) && ip->i_af.if_nextents > 0 &&
1367 	    ip->i_af.if_format != XFS_DINODE_FMT_LOCAL) {
1368 		error = xfs_bmap_count_blocks(tp, ip, XFS_ATTR_FORK, &junk,
1369 				&aforkblks);
1370 		if (error)
1371 			return error;
1372 	}
1373 	if (xfs_inode_has_attr_fork(tip) && tip->i_af.if_nextents > 0 &&
1374 	    tip->i_af.if_format != XFS_DINODE_FMT_LOCAL) {
1375 		error = xfs_bmap_count_blocks(tp, tip, XFS_ATTR_FORK, &junk,
1376 				&taforkblks);
1377 		if (error)
1378 			return error;
1379 	}
1380 
1381 	/*
1382 	 * Btree format (v3) inodes have the inode number stamped in the bmbt
1383 	 * block headers. We can't start changing the bmbt blocks until the
1384 	 * inode owner change is logged so recovery does the right thing in the
1385 	 * event of a crash. Set the owner change log flags now and leave the
1386 	 * bmbt scan as the last step.
1387 	 */
1388 	if (xfs_has_v3inodes(ip->i_mount)) {
1389 		if (ip->i_df.if_format == XFS_DINODE_FMT_BTREE)
1390 			(*target_log_flags) |= XFS_ILOG_DOWNER;
1391 		if (tip->i_df.if_format == XFS_DINODE_FMT_BTREE)
1392 			(*src_log_flags) |= XFS_ILOG_DOWNER;
1393 	}
1394 
1395 	/*
1396 	 * Swap the data forks of the inodes
1397 	 */
1398 	swap(ip->i_df, tip->i_df);
1399 
1400 	/*
1401 	 * Fix the on-disk inode values
1402 	 */
1403 	tmp = (uint64_t)ip->i_nblocks;
1404 	ip->i_nblocks = tip->i_nblocks - taforkblks + aforkblks;
1405 	tip->i_nblocks = tmp + taforkblks - aforkblks;
1406 
1407 	/*
1408 	 * The extents in the source inode could still contain speculative
1409 	 * preallocation beyond EOF (e.g. the file is open but not modified
1410 	 * while defrag is in progress). In that case, we need to copy over the
1411 	 * number of delalloc blocks the data fork in the source inode is
1412 	 * tracking beyond EOF so that when the fork is truncated away when the
1413 	 * temporary inode is unlinked we don't underrun the i_delayed_blks
1414 	 * counter on that inode.
1415 	 */
1416 	ASSERT(tip->i_delayed_blks == 0);
1417 	tip->i_delayed_blks = ip->i_delayed_blks;
1418 	ip->i_delayed_blks = 0;
1419 
1420 	switch (ip->i_df.if_format) {
1421 	case XFS_DINODE_FMT_EXTENTS:
1422 		(*src_log_flags) |= XFS_ILOG_DEXT;
1423 		break;
1424 	case XFS_DINODE_FMT_BTREE:
1425 		ASSERT(!xfs_has_v3inodes(ip->i_mount) ||
1426 		       (*src_log_flags & XFS_ILOG_DOWNER));
1427 		(*src_log_flags) |= XFS_ILOG_DBROOT;
1428 		break;
1429 	}
1430 
1431 	switch (tip->i_df.if_format) {
1432 	case XFS_DINODE_FMT_EXTENTS:
1433 		(*target_log_flags) |= XFS_ILOG_DEXT;
1434 		break;
1435 	case XFS_DINODE_FMT_BTREE:
1436 		(*target_log_flags) |= XFS_ILOG_DBROOT;
1437 		ASSERT(!xfs_has_v3inodes(ip->i_mount) ||
1438 		       (*target_log_flags & XFS_ILOG_DOWNER));
1439 		break;
1440 	}
1441 
1442 	return 0;
1443 }
1444 
1445 /*
1446  * Fix up the owners of the bmbt blocks to refer to the current inode. The
1447  * change owner scan attempts to order all modified buffers in the current
1448  * transaction. In the event of ordered buffer failure, the offending buffer is
1449  * physically logged as a fallback and the scan returns -EAGAIN. We must roll
1450  * the transaction in this case to replenish the fallback log reservation and
1451  * restart the scan. This process repeats until the scan completes.
1452  */
1453 static int
1454 xfs_swap_change_owner(
1455 	struct xfs_trans	**tpp,
1456 	struct xfs_inode	*ip,
1457 	struct xfs_inode	*tmpip)
1458 {
1459 	int			error;
1460 	struct xfs_trans	*tp = *tpp;
1461 
1462 	do {
1463 		error = xfs_bmbt_change_owner(tp, ip, XFS_DATA_FORK, ip->i_ino,
1464 					      NULL);
1465 		/* success or fatal error */
1466 		if (error != -EAGAIN)
1467 			break;
1468 
1469 		error = xfs_trans_roll(tpp);
1470 		if (error)
1471 			break;
1472 		tp = *tpp;
1473 
1474 		/*
1475 		 * Redirty both inodes so they can relog and keep the log tail
1476 		 * moving forward.
1477 		 */
1478 		xfs_trans_ijoin(tp, ip, 0);
1479 		xfs_trans_ijoin(tp, tmpip, 0);
1480 		xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1481 		xfs_trans_log_inode(tp, tmpip, XFS_ILOG_CORE);
1482 	} while (true);
1483 
1484 	return error;
1485 }
1486 
1487 int
1488 xfs_swap_extents(
1489 	struct xfs_inode	*ip,	/* target inode */
1490 	struct xfs_inode	*tip,	/* tmp inode */
1491 	struct xfs_swapext	*sxp)
1492 {
1493 	struct xfs_mount	*mp = ip->i_mount;
1494 	struct xfs_trans	*tp;
1495 	struct xfs_bstat	*sbp = &sxp->sx_stat;
1496 	int			src_log_flags, target_log_flags;
1497 	int			error = 0;
1498 	uint64_t		f;
1499 	int			resblks = 0;
1500 	unsigned int		flags = 0;
1501 	struct timespec64	ctime, mtime;
1502 
1503 	/*
1504 	 * Lock the inodes against other IO, page faults and truncate to
1505 	 * begin with.  Then we can ensure the inodes are flushed and have no
1506 	 * page cache safely. Once we have done this we can take the ilocks and
1507 	 * do the rest of the checks.
1508 	 */
1509 	lock_two_nondirectories(VFS_I(ip), VFS_I(tip));
1510 	filemap_invalidate_lock_two(VFS_I(ip)->i_mapping,
1511 				    VFS_I(tip)->i_mapping);
1512 
1513 	/* Verify that both files have the same format */
1514 	if ((VFS_I(ip)->i_mode & S_IFMT) != (VFS_I(tip)->i_mode & S_IFMT)) {
1515 		error = -EINVAL;
1516 		goto out_unlock;
1517 	}
1518 
1519 	/* Verify both files are either real-time or non-realtime */
1520 	if (XFS_IS_REALTIME_INODE(ip) != XFS_IS_REALTIME_INODE(tip)) {
1521 		error = -EINVAL;
1522 		goto out_unlock;
1523 	}
1524 
1525 	error = xfs_qm_dqattach(ip);
1526 	if (error)
1527 		goto out_unlock;
1528 
1529 	error = xfs_qm_dqattach(tip);
1530 	if (error)
1531 		goto out_unlock;
1532 
1533 	error = xfs_swap_extent_flush(ip);
1534 	if (error)
1535 		goto out_unlock;
1536 	error = xfs_swap_extent_flush(tip);
1537 	if (error)
1538 		goto out_unlock;
1539 
1540 	if (xfs_inode_has_cow_data(tip)) {
1541 		error = xfs_reflink_cancel_cow_range(tip, 0, NULLFILEOFF, true);
1542 		if (error)
1543 			goto out_unlock;
1544 	}
1545 
1546 	/*
1547 	 * Extent "swapping" with rmap requires a permanent reservation and
1548 	 * a block reservation because it's really just a remap operation
1549 	 * performed with log redo items!
1550 	 */
1551 	if (xfs_has_rmapbt(mp)) {
1552 		int		w = XFS_DATA_FORK;
1553 		uint32_t	ipnext = ip->i_df.if_nextents;
1554 		uint32_t	tipnext	= tip->i_df.if_nextents;
1555 
1556 		/*
1557 		 * Conceptually this shouldn't affect the shape of either bmbt,
1558 		 * but since we atomically move extents one by one, we reserve
1559 		 * enough space to rebuild both trees.
1560 		 */
1561 		resblks = XFS_SWAP_RMAP_SPACE_RES(mp, ipnext, w);
1562 		resblks +=  XFS_SWAP_RMAP_SPACE_RES(mp, tipnext, w);
1563 
1564 		/*
1565 		 * If either inode straddles a bmapbt block allocation boundary,
1566 		 * the rmapbt algorithm triggers repeated allocs and frees as
1567 		 * extents are remapped. This can exhaust the block reservation
1568 		 * prematurely and cause shutdown. Return freed blocks to the
1569 		 * transaction reservation to counter this behavior.
1570 		 */
1571 		flags |= XFS_TRANS_RES_FDBLKS;
1572 	}
1573 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, resblks, 0, flags,
1574 				&tp);
1575 	if (error)
1576 		goto out_unlock;
1577 
1578 	/*
1579 	 * Lock and join the inodes to the tansaction so that transaction commit
1580 	 * or cancel will unlock the inodes from this point onwards.
1581 	 */
1582 	xfs_lock_two_inodes(ip, XFS_ILOCK_EXCL, tip, XFS_ILOCK_EXCL);
1583 	xfs_trans_ijoin(tp, ip, 0);
1584 	xfs_trans_ijoin(tp, tip, 0);
1585 
1586 
1587 	/* Verify all data are being swapped */
1588 	if (sxp->sx_offset != 0 ||
1589 	    sxp->sx_length != ip->i_disk_size ||
1590 	    sxp->sx_length != tip->i_disk_size) {
1591 		error = -EFAULT;
1592 		goto out_trans_cancel;
1593 	}
1594 
1595 	trace_xfs_swap_extent_before(ip, 0);
1596 	trace_xfs_swap_extent_before(tip, 1);
1597 
1598 	/* check inode formats now that data is flushed */
1599 	error = xfs_swap_extents_check_format(ip, tip);
1600 	if (error) {
1601 		xfs_notice(mp,
1602 		    "%s: inode 0x%llx format is incompatible for exchanging.",
1603 				__func__, ip->i_ino);
1604 		goto out_trans_cancel;
1605 	}
1606 
1607 	/*
1608 	 * Compare the current change & modify times with that
1609 	 * passed in.  If they differ, we abort this swap.
1610 	 * This is the mechanism used to ensure the calling
1611 	 * process that the file was not changed out from
1612 	 * under it.
1613 	 */
1614 	ctime = inode_get_ctime(VFS_I(ip));
1615 	mtime = inode_get_mtime(VFS_I(ip));
1616 	if ((sbp->bs_ctime.tv_sec != ctime.tv_sec) ||
1617 	    (sbp->bs_ctime.tv_nsec != ctime.tv_nsec) ||
1618 	    (sbp->bs_mtime.tv_sec != mtime.tv_sec) ||
1619 	    (sbp->bs_mtime.tv_nsec != mtime.tv_nsec)) {
1620 		error = -EBUSY;
1621 		goto out_trans_cancel;
1622 	}
1623 
1624 	/*
1625 	 * Note the trickiness in setting the log flags - we set the owner log
1626 	 * flag on the opposite inode (i.e. the inode we are setting the new
1627 	 * owner to be) because once we swap the forks and log that, log
1628 	 * recovery is going to see the fork as owned by the swapped inode,
1629 	 * not the pre-swapped inodes.
1630 	 */
1631 	src_log_flags = XFS_ILOG_CORE;
1632 	target_log_flags = XFS_ILOG_CORE;
1633 
1634 	if (xfs_has_rmapbt(mp))
1635 		error = xfs_swap_extent_rmap(&tp, ip, tip);
1636 	else
1637 		error = xfs_swap_extent_forks(tp, ip, tip, &src_log_flags,
1638 				&target_log_flags);
1639 	if (error)
1640 		goto out_trans_cancel;
1641 
1642 	/* Do we have to swap reflink flags? */
1643 	if ((ip->i_diflags2 & XFS_DIFLAG2_REFLINK) ^
1644 	    (tip->i_diflags2 & XFS_DIFLAG2_REFLINK)) {
1645 		f = ip->i_diflags2 & XFS_DIFLAG2_REFLINK;
1646 		ip->i_diflags2 &= ~XFS_DIFLAG2_REFLINK;
1647 		ip->i_diflags2 |= tip->i_diflags2 & XFS_DIFLAG2_REFLINK;
1648 		tip->i_diflags2 &= ~XFS_DIFLAG2_REFLINK;
1649 		tip->i_diflags2 |= f & XFS_DIFLAG2_REFLINK;
1650 	}
1651 
1652 	/* Swap the cow forks. */
1653 	if (xfs_has_reflink(mp)) {
1654 		ASSERT(!ip->i_cowfp ||
1655 		       ip->i_cowfp->if_format == XFS_DINODE_FMT_EXTENTS);
1656 		ASSERT(!tip->i_cowfp ||
1657 		       tip->i_cowfp->if_format == XFS_DINODE_FMT_EXTENTS);
1658 
1659 		swap(ip->i_cowfp, tip->i_cowfp);
1660 
1661 		if (ip->i_cowfp && ip->i_cowfp->if_bytes)
1662 			xfs_inode_set_cowblocks_tag(ip);
1663 		else
1664 			xfs_inode_clear_cowblocks_tag(ip);
1665 		if (tip->i_cowfp && tip->i_cowfp->if_bytes)
1666 			xfs_inode_set_cowblocks_tag(tip);
1667 		else
1668 			xfs_inode_clear_cowblocks_tag(tip);
1669 	}
1670 
1671 	xfs_trans_log_inode(tp, ip,  src_log_flags);
1672 	xfs_trans_log_inode(tp, tip, target_log_flags);
1673 
1674 	/*
1675 	 * The extent forks have been swapped, but crc=1,rmapbt=0 filesystems
1676 	 * have inode number owner values in the bmbt blocks that still refer to
1677 	 * the old inode. Scan each bmbt to fix up the owner values with the
1678 	 * inode number of the current inode.
1679 	 */
1680 	if (src_log_flags & XFS_ILOG_DOWNER) {
1681 		error = xfs_swap_change_owner(&tp, ip, tip);
1682 		if (error)
1683 			goto out_trans_cancel;
1684 	}
1685 	if (target_log_flags & XFS_ILOG_DOWNER) {
1686 		error = xfs_swap_change_owner(&tp, tip, ip);
1687 		if (error)
1688 			goto out_trans_cancel;
1689 	}
1690 
1691 	/*
1692 	 * If this is a synchronous mount, make sure that the
1693 	 * transaction goes to disk before returning to the user.
1694 	 */
1695 	if (xfs_has_wsync(mp))
1696 		xfs_trans_set_sync(tp);
1697 
1698 	error = xfs_trans_commit(tp);
1699 
1700 	trace_xfs_swap_extent_after(ip, 0);
1701 	trace_xfs_swap_extent_after(tip, 1);
1702 
1703 out_unlock_ilock:
1704 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1705 	xfs_iunlock(tip, XFS_ILOCK_EXCL);
1706 out_unlock:
1707 	filemap_invalidate_unlock_two(VFS_I(ip)->i_mapping,
1708 				      VFS_I(tip)->i_mapping);
1709 	unlock_two_nondirectories(VFS_I(ip), VFS_I(tip));
1710 	return error;
1711 
1712 out_trans_cancel:
1713 	xfs_trans_cancel(tp);
1714 	goto out_unlock_ilock;
1715 }
1716