xref: /linux/fs/xfs/xfs_iomap.c (revision a7f25dc23ff6d238ed70e8a3a8a3792cde3bcc68)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2006 Silicon Graphics, Inc.
4  * Copyright (c) 2016-2018 Christoph Hellwig.
5  * All Rights Reserved.
6  */
7 #include "xfs_platform.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_mount.h"
14 #include "xfs_inode.h"
15 #include "xfs_btree.h"
16 #include "xfs_bmap_btree.h"
17 #include "xfs_bmap.h"
18 #include "xfs_bmap_util.h"
19 #include "xfs_errortag.h"
20 #include "xfs_error.h"
21 #include "xfs_trans.h"
22 #include "xfs_trans_space.h"
23 #include "xfs_inode_item.h"
24 #include "xfs_iomap.h"
25 #include "xfs_trace.h"
26 #include "xfs_quota.h"
27 #include "xfs_rtgroup.h"
28 #include "xfs_dquot_item.h"
29 #include "xfs_dquot.h"
30 #include "xfs_reflink.h"
31 #include "xfs_health.h"
32 #include "xfs_rtbitmap.h"
33 #include "xfs_icache.h"
34 #include "xfs_zone_alloc.h"
35 
36 #define XFS_ALLOC_ALIGN(mp, off) \
37 	(((off) >> mp->m_allocsize_log) << mp->m_allocsize_log)
38 
39 static int
xfs_alert_fsblock_zero(xfs_inode_t * ip,xfs_bmbt_irec_t * imap)40 xfs_alert_fsblock_zero(
41 	xfs_inode_t	*ip,
42 	xfs_bmbt_irec_t	*imap)
43 {
44 	xfs_alert_tag(ip->i_mount, XFS_PTAG_FSBLOCK_ZERO,
45 			"Access to block zero in inode %llu "
46 			"start_block: %llx start_off: %llx "
47 			"blkcnt: %llx extent-state: %x",
48 		(unsigned long long)I_INO(ip),
49 		(unsigned long long)imap->br_startblock,
50 		(unsigned long long)imap->br_startoff,
51 		(unsigned long long)imap->br_blockcount,
52 		imap->br_state);
53 	xfs_bmap_mark_sick(ip, XFS_DATA_FORK);
54 	return -EFSCORRUPTED;
55 }
56 
57 u64
xfs_iomap_inode_sequence(struct xfs_inode * ip,u16 iomap_flags)58 xfs_iomap_inode_sequence(
59 	struct xfs_inode	*ip,
60 	u16			iomap_flags)
61 {
62 	u64			cookie = 0;
63 
64 	if (iomap_flags & IOMAP_F_XATTR)
65 		return READ_ONCE(ip->i_af.if_seq);
66 	if ((iomap_flags & IOMAP_F_SHARED) && ip->i_cowfp)
67 		cookie = (u64)READ_ONCE(ip->i_cowfp->if_seq) << 32;
68 	return cookie | READ_ONCE(ip->i_df.if_seq);
69 }
70 
71 /*
72  * Check that the iomap passed to us is still valid for the given offset and
73  * length.
74  */
75 static bool
xfs_iomap_valid(struct inode * inode,const struct iomap * iomap)76 xfs_iomap_valid(
77 	struct inode		*inode,
78 	const struct iomap	*iomap)
79 {
80 	struct xfs_inode	*ip = XFS_I(inode);
81 
82 	if (iomap->type == IOMAP_HOLE)
83 		return true;
84 
85 	if (iomap->validity_cookie !=
86 			xfs_iomap_inode_sequence(ip, iomap->flags)) {
87 		trace_xfs_iomap_invalid(ip, iomap);
88 		return false;
89 	}
90 
91 	XFS_ERRORTAG_DELAY(ip->i_mount, XFS_ERRTAG_WRITE_DELAY_MS);
92 	return true;
93 }
94 
95 const struct iomap_write_ops xfs_iomap_write_ops = {
96 	.iomap_valid		= xfs_iomap_valid,
97 };
98 
99 int
xfs_bmbt_to_iomap(struct xfs_inode * ip,struct iomap * iomap,struct xfs_bmbt_irec * imap,unsigned int mapping_flags,u16 iomap_flags,u64 sequence_cookie)100 xfs_bmbt_to_iomap(
101 	struct xfs_inode	*ip,
102 	struct iomap		*iomap,
103 	struct xfs_bmbt_irec	*imap,
104 	unsigned int		mapping_flags,
105 	u16			iomap_flags,
106 	u64			sequence_cookie)
107 {
108 	struct xfs_mount	*mp = ip->i_mount;
109 	struct xfs_buftarg	*target = xfs_inode_buftarg(ip);
110 
111 	if (unlikely(!xfs_valid_startblock(ip, imap->br_startblock))) {
112 		xfs_bmap_mark_sick(ip, XFS_DATA_FORK);
113 		return xfs_alert_fsblock_zero(ip, imap);
114 	}
115 
116 	iomap->flags = iomap_flags;
117 	if (imap->br_startblock == HOLESTARTBLOCK) {
118 		iomap->addr = IOMAP_NULL_ADDR;
119 		iomap->type = IOMAP_HOLE;
120 	} else if (imap->br_startblock == DELAYSTARTBLOCK ||
121 		   isnullstartblock(imap->br_startblock)) {
122 		iomap->addr = IOMAP_NULL_ADDR;
123 		iomap->type = IOMAP_DELALLOC;
124 	} else {
125 		xfs_daddr_t	daddr = xfs_fsb_to_db(ip, imap->br_startblock);
126 
127 		iomap->addr = BBTOB(daddr);
128 		if (mapping_flags & IOMAP_DAX)
129 			iomap->addr += target->bt_dax_part_off;
130 
131 		if (imap->br_state == XFS_EXT_UNWRITTEN)
132 			iomap->type = IOMAP_UNWRITTEN;
133 		else
134 			iomap->type = IOMAP_MAPPED;
135 
136 		/*
137 		 * Mark iomaps starting at the first sector of a RTG as merge
138 		 * boundary so that each I/O completions is contained to a
139 		 * single RTG.
140 		 */
141 		if (XFS_IS_REALTIME_INODE(ip) && xfs_has_rtgroups(mp) &&
142 		    xfs_rtbno_is_group_start(mp, imap->br_startblock))
143 			iomap->flags |= IOMAP_F_BOUNDARY;
144 	}
145 	iomap->offset = XFS_FSB_TO_B(mp, imap->br_startoff);
146 	iomap->length = XFS_FSB_TO_B(mp, imap->br_blockcount);
147 	if (mapping_flags & IOMAP_DAX) {
148 		iomap->dax_dev = target->bt_daxdev;
149 	} else {
150 		iomap->bdev = target->bt_bdev;
151 		if (bdev_has_integrity_csum(iomap->bdev))
152 			iomap->flags |= IOMAP_F_INTEGRITY;
153 	}
154 
155 	/*
156 	 * If the inode is dirty for datasync purposes, let iomap know so it
157 	 * doesn't elide the IO completion journal flushes on O_DSYNC IO.
158 	 */
159 	if (ip->i_itemp) {
160 		struct xfs_inode_log_item *iip = ip->i_itemp;
161 
162 		spin_lock(&iip->ili_lock);
163 		if (iip->ili_datasync_seq)
164 			iomap->flags |= IOMAP_F_DIRTY;
165 		spin_unlock(&iip->ili_lock);
166 	}
167 
168 	iomap->validity_cookie = sequence_cookie;
169 	return 0;
170 }
171 
172 static void
xfs_hole_to_iomap(struct xfs_inode * ip,struct iomap * iomap,xfs_fileoff_t offset_fsb,xfs_fileoff_t end_fsb)173 xfs_hole_to_iomap(
174 	struct xfs_inode	*ip,
175 	struct iomap		*iomap,
176 	xfs_fileoff_t		offset_fsb,
177 	xfs_fileoff_t		end_fsb)
178 {
179 	struct xfs_buftarg	*target = xfs_inode_buftarg(ip);
180 
181 	iomap->addr = IOMAP_NULL_ADDR;
182 	iomap->type = IOMAP_HOLE;
183 	iomap->offset = XFS_FSB_TO_B(ip->i_mount, offset_fsb);
184 	iomap->length = XFS_FSB_TO_B(ip->i_mount, end_fsb - offset_fsb);
185 	iomap->bdev = target->bt_bdev;
186 	iomap->dax_dev = target->bt_daxdev;
187 }
188 
189 static inline xfs_fileoff_t
xfs_iomap_end_fsb(struct xfs_mount * mp,loff_t offset,loff_t count)190 xfs_iomap_end_fsb(
191 	struct xfs_mount	*mp,
192 	loff_t			offset,
193 	loff_t			count)
194 {
195 	ASSERT(offset <= mp->m_super->s_maxbytes);
196 	return min(XFS_B_TO_FSB(mp, offset + count),
197 		   XFS_B_TO_FSB(mp, mp->m_super->s_maxbytes));
198 }
199 
200 static xfs_extlen_t
xfs_eof_alignment(struct xfs_inode * ip)201 xfs_eof_alignment(
202 	struct xfs_inode	*ip)
203 {
204 	struct xfs_mount	*mp = ip->i_mount;
205 	xfs_extlen_t		align = 0;
206 
207 	if (!XFS_IS_REALTIME_INODE(ip)) {
208 		/*
209 		 * Round up the allocation request to a stripe unit
210 		 * (m_dalign) boundary if the file size is >= stripe unit
211 		 * size, and we are allocating past the allocation eof.
212 		 *
213 		 * If mounted with the "-o swalloc" option the alignment is
214 		 * increased from the strip unit size to the stripe width.
215 		 */
216 		if (mp->m_swidth && xfs_has_swalloc(mp))
217 			align = mp->m_swidth;
218 		else if (mp->m_dalign)
219 			align = mp->m_dalign;
220 
221 		if (align && XFS_ISIZE(ip) < XFS_FSB_TO_B(mp, align))
222 			align = 0;
223 	}
224 
225 	return align;
226 }
227 
228 /*
229  * Check if last_fsb is outside the last extent, and if so grow it to the next
230  * stripe unit boundary.
231  */
232 xfs_fileoff_t
xfs_iomap_eof_align_last_fsb(struct xfs_inode * ip,xfs_fileoff_t end_fsb)233 xfs_iomap_eof_align_last_fsb(
234 	struct xfs_inode	*ip,
235 	xfs_fileoff_t		end_fsb)
236 {
237 	struct xfs_ifork	*ifp = xfs_ifork_ptr(ip, XFS_DATA_FORK);
238 	xfs_extlen_t		extsz = xfs_get_extsz_hint(ip);
239 	xfs_extlen_t		align = xfs_eof_alignment(ip);
240 	struct xfs_bmbt_irec	irec;
241 	struct xfs_iext_cursor	icur;
242 
243 	ASSERT(!xfs_need_iread_extents(ifp));
244 
245 	/*
246 	 * Always round up the allocation request to the extent hint boundary.
247 	 */
248 	if (extsz) {
249 		if (align)
250 			align = roundup_64(align, extsz);
251 		else
252 			align = extsz;
253 	}
254 
255 	if (align) {
256 		xfs_fileoff_t	aligned_end_fsb = roundup_64(end_fsb, align);
257 
258 		xfs_iext_last(ifp, &icur);
259 		if (!xfs_iext_get_extent(ifp, &icur, &irec) ||
260 		    aligned_end_fsb >= irec.br_startoff + irec.br_blockcount)
261 			return aligned_end_fsb;
262 	}
263 
264 	return end_fsb;
265 }
266 
267 int
xfs_iomap_write_direct(struct xfs_inode * ip,xfs_fileoff_t offset_fsb,xfs_fileoff_t count_fsb,unsigned int flags,struct xfs_bmbt_irec * imap,u64 * seq)268 xfs_iomap_write_direct(
269 	struct xfs_inode	*ip,
270 	xfs_fileoff_t		offset_fsb,
271 	xfs_fileoff_t		count_fsb,
272 	unsigned int		flags,
273 	struct xfs_bmbt_irec	*imap,
274 	u64			*seq)
275 {
276 	struct xfs_mount	*mp = ip->i_mount;
277 	struct xfs_trans	*tp;
278 	xfs_filblks_t		resaligned;
279 	int			nimaps;
280 	unsigned int		dblocks, rblocks;
281 	bool			force = false;
282 	int			error;
283 	int			bmapi_flags = XFS_BMAPI_PREALLOC;
284 	int			nr_exts = XFS_IEXT_ADD_NOSPLIT_CNT;
285 
286 	ASSERT(count_fsb > 0);
287 
288 	resaligned = xfs_aligned_fsb_count(offset_fsb, count_fsb,
289 					   xfs_get_extsz_hint(ip));
290 	if (unlikely(XFS_IS_REALTIME_INODE(ip))) {
291 		dblocks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
292 		rblocks = resaligned;
293 	} else {
294 		dblocks = XFS_DIOSTRAT_SPACE_RES(mp, resaligned);
295 		rblocks = 0;
296 	}
297 
298 	error = xfs_qm_dqattach(ip);
299 	if (error)
300 		return error;
301 
302 	/*
303 	 * For DAX, we do not allocate unwritten extents, but instead we zero
304 	 * the block before we commit the transaction.  Ideally we'd like to do
305 	 * this outside the transaction context, but if we commit and then crash
306 	 * we may not have zeroed the blocks and this will be exposed on
307 	 * recovery of the allocation. Hence we must zero before commit.
308 	 *
309 	 * Further, if we are mapping unwritten extents here, we need to zero
310 	 * and convert them to written so that we don't need an unwritten extent
311 	 * callback for DAX. This also means that we need to be able to dip into
312 	 * the reserve block pool for bmbt block allocation if there is no space
313 	 * left but we need to do unwritten extent conversion.
314 	 */
315 	if (flags & IOMAP_DAX) {
316 		bmapi_flags = XFS_BMAPI_CONVERT | XFS_BMAPI_ZERO;
317 		if (imap->br_state == XFS_EXT_UNWRITTEN) {
318 			force = true;
319 			nr_exts = XFS_IEXT_WRITE_UNWRITTEN_CNT;
320 			dblocks = XFS_DIOSTRAT_SPACE_RES(mp, 0) << 1;
321 		}
322 	}
323 
324 	error = xfs_trans_alloc_inode(ip, &M_RES(mp)->tr_write, dblocks,
325 			rblocks, force, &tp);
326 	if (error)
327 		return error;
328 
329 	error = xfs_iext_count_extend(tp, ip, XFS_DATA_FORK, nr_exts);
330 	if (error)
331 		goto out_trans_cancel;
332 
333 	/*
334 	 * From this point onwards we overwrite the imap pointer that the
335 	 * caller gave to us.
336 	 */
337 	nimaps = 1;
338 	error = xfs_bmapi_write(tp, ip, offset_fsb, count_fsb, bmapi_flags, 0,
339 				imap, &nimaps);
340 	if (error)
341 		goto out_trans_cancel;
342 
343 	/*
344 	 * Complete the transaction
345 	 */
346 	error = xfs_trans_commit(tp);
347 	if (error)
348 		goto out_unlock;
349 
350 	if (unlikely(!xfs_valid_startblock(ip, imap->br_startblock))) {
351 		xfs_bmap_mark_sick(ip, XFS_DATA_FORK);
352 		error = xfs_alert_fsblock_zero(ip, imap);
353 	}
354 
355 out_unlock:
356 	*seq = xfs_iomap_inode_sequence(ip, 0);
357 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
358 	return error;
359 
360 out_trans_cancel:
361 	xfs_trans_cancel(tp);
362 	goto out_unlock;
363 }
364 
365 STATIC bool
xfs_quota_need_throttle(struct xfs_inode * ip,xfs_dqtype_t type,xfs_fsblock_t alloc_blocks)366 xfs_quota_need_throttle(
367 	struct xfs_inode	*ip,
368 	xfs_dqtype_t		type,
369 	xfs_fsblock_t		alloc_blocks)
370 {
371 	struct xfs_dquot	*dq = xfs_inode_dquot(ip, type);
372 	struct xfs_dquot_res	*res;
373 	struct xfs_dquot_pre	*pre;
374 
375 	if (!dq || !xfs_this_quota_on(ip->i_mount, type))
376 		return false;
377 
378 	if (XFS_IS_REALTIME_INODE(ip)) {
379 		res = &dq->q_rtb;
380 		pre = &dq->q_rtb_prealloc;
381 	} else {
382 		res = &dq->q_blk;
383 		pre = &dq->q_blk_prealloc;
384 	}
385 
386 	/* no hi watermark, no throttle */
387 	if (!pre->q_prealloc_hi_wmark)
388 		return false;
389 
390 	/* under the lo watermark, no throttle */
391 	if (res->reserved + alloc_blocks < pre->q_prealloc_lo_wmark)
392 		return false;
393 
394 	return true;
395 }
396 
397 STATIC void
xfs_quota_calc_throttle(struct xfs_inode * ip,xfs_dqtype_t type,xfs_fsblock_t * qblocks,int * qshift,int64_t * qfreesp)398 xfs_quota_calc_throttle(
399 	struct xfs_inode	*ip,
400 	xfs_dqtype_t		type,
401 	xfs_fsblock_t		*qblocks,
402 	int			*qshift,
403 	int64_t			*qfreesp)
404 {
405 	struct xfs_dquot	*dq = xfs_inode_dquot(ip, type);
406 	struct xfs_dquot_res	*res;
407 	struct xfs_dquot_pre	*pre;
408 	int64_t			freesp;
409 	int			shift = 0;
410 
411 	if (!dq) {
412 		res = NULL;
413 		pre = NULL;
414 	} else if (XFS_IS_REALTIME_INODE(ip)) {
415 		res = &dq->q_rtb;
416 		pre = &dq->q_rtb_prealloc;
417 	} else {
418 		res = &dq->q_blk;
419 		pre = &dq->q_blk_prealloc;
420 	}
421 
422 	/* no dq, or over hi wmark, squash the prealloc completely */
423 	if (!res || res->reserved >= pre->q_prealloc_hi_wmark) {
424 		*qblocks = 0;
425 		*qfreesp = 0;
426 		return;
427 	}
428 
429 	freesp = pre->q_prealloc_hi_wmark - res->reserved;
430 	if (freesp < pre->q_low_space[XFS_QLOWSP_5_PCNT]) {
431 		shift = 2;
432 		if (freesp < pre->q_low_space[XFS_QLOWSP_3_PCNT])
433 			shift += 2;
434 		if (freesp < pre->q_low_space[XFS_QLOWSP_1_PCNT])
435 			shift += 2;
436 	}
437 
438 	if (freesp < *qfreesp)
439 		*qfreesp = freesp;
440 
441 	/* only overwrite the throttle values if we are more aggressive */
442 	if ((freesp >> shift) < (*qblocks >> *qshift)) {
443 		*qblocks = freesp;
444 		*qshift = shift;
445 	}
446 }
447 
448 static int64_t
xfs_iomap_freesp(struct xfs_mount * mp,unsigned int idx,uint64_t low_space[XFS_LOWSP_MAX],int * shift)449 xfs_iomap_freesp(
450 	struct xfs_mount	*mp,
451 	unsigned int		idx,
452 	uint64_t		low_space[XFS_LOWSP_MAX],
453 	int			*shift)
454 {
455 	int64_t			freesp;
456 
457 	freesp = xfs_estimate_freecounter(mp, idx);
458 	if (freesp < low_space[XFS_LOWSP_5_PCNT]) {
459 		*shift = 2;
460 		if (freesp < low_space[XFS_LOWSP_4_PCNT])
461 			(*shift)++;
462 		if (freesp < low_space[XFS_LOWSP_3_PCNT])
463 			(*shift)++;
464 		if (freesp < low_space[XFS_LOWSP_2_PCNT])
465 			(*shift)++;
466 		if (freesp < low_space[XFS_LOWSP_1_PCNT])
467 			(*shift)++;
468 	}
469 	return freesp;
470 }
471 
472 /*
473  * If we don't have a user specified preallocation size, dynamically increase
474  * the preallocation size as the size of the file grows.  Cap the maximum size
475  * at a single extent or less if the filesystem is near full. The closer the
476  * filesystem is to being full, the smaller the maximum preallocation.
477  */
478 STATIC xfs_fsblock_t
xfs_iomap_prealloc_size(struct xfs_inode * ip,int whichfork,loff_t offset,loff_t count,struct xfs_iext_cursor * icur)479 xfs_iomap_prealloc_size(
480 	struct xfs_inode	*ip,
481 	int			whichfork,
482 	loff_t			offset,
483 	loff_t			count,
484 	struct xfs_iext_cursor	*icur)
485 {
486 	struct xfs_iext_cursor	ncur = *icur;
487 	struct xfs_bmbt_irec	prev, got;
488 	struct xfs_mount	*mp = ip->i_mount;
489 	struct xfs_ifork	*ifp = xfs_ifork_ptr(ip, whichfork);
490 	xfs_fileoff_t		offset_fsb = XFS_B_TO_FSBT(mp, offset);
491 	int64_t			freesp;
492 	xfs_fsblock_t		qblocks;
493 	xfs_fsblock_t		alloc_blocks = 0;
494 	xfs_extlen_t		plen;
495 	int			shift = 0;
496 	int			qshift = 0;
497 
498 	/*
499 	 * As an exception we don't do any preallocation at all if the file is
500 	 * smaller than the minimum preallocation and we are using the default
501 	 * dynamic preallocation scheme, as it is likely this is the only write
502 	 * to the file that is going to be done.
503 	 */
504 	if (XFS_ISIZE(ip) < XFS_FSB_TO_B(mp, mp->m_allocsize_blocks))
505 		return 0;
506 
507 	/*
508 	 * Use the minimum preallocation size for small files or if we are
509 	 * writing right after a hole.
510 	 */
511 	if (XFS_ISIZE(ip) < XFS_FSB_TO_B(mp, mp->m_dalign) ||
512 	    !xfs_iext_prev_extent(ifp, &ncur, &prev) ||
513 	    prev.br_startoff + prev.br_blockcount < offset_fsb)
514 		return mp->m_allocsize_blocks;
515 
516 	/*
517 	 * Take the size of the preceding data extents as the basis for the
518 	 * preallocation size. Note that we don't care if the previous extents
519 	 * are written or not.
520 	 */
521 	plen = prev.br_blockcount;
522 	while (xfs_iext_prev_extent(ifp, &ncur, &got)) {
523 		if (plen > XFS_MAX_BMBT_EXTLEN / 2 ||
524 		    isnullstartblock(got.br_startblock) ||
525 		    got.br_startoff + got.br_blockcount != prev.br_startoff ||
526 		    got.br_startblock + got.br_blockcount != prev.br_startblock)
527 			break;
528 		plen += got.br_blockcount;
529 		prev = got;
530 	}
531 
532 	/*
533 	 * If the size of the extents is greater than half the maximum extent
534 	 * length, then use the current offset as the basis.  This ensures that
535 	 * for large files the preallocation size always extends to
536 	 * XFS_BMBT_MAX_EXTLEN rather than falling short due to things like stripe
537 	 * unit/width alignment of real extents.
538 	 */
539 	alloc_blocks = plen * 2;
540 	if (alloc_blocks > XFS_MAX_BMBT_EXTLEN)
541 		alloc_blocks = XFS_B_TO_FSB(mp, offset);
542 	qblocks = alloc_blocks;
543 
544 	/*
545 	 * XFS_BMBT_MAX_EXTLEN is not a power of two value but we round the prealloc
546 	 * down to the nearest power of two value after throttling. To prevent
547 	 * the round down from unconditionally reducing the maximum supported
548 	 * prealloc size, we round up first, apply appropriate throttling, round
549 	 * down and cap the value to XFS_BMBT_MAX_EXTLEN.
550 	 */
551 	alloc_blocks = XFS_FILEOFF_MIN(roundup_pow_of_two(XFS_MAX_BMBT_EXTLEN),
552 				       alloc_blocks);
553 
554 	if (unlikely(XFS_IS_REALTIME_INODE(ip)))
555 		freesp = xfs_rtbxlen_to_blen(mp,
556 				xfs_iomap_freesp(mp, XC_FREE_RTEXTENTS,
557 					mp->m_low_rtexts, &shift));
558 	else
559 		freesp = xfs_iomap_freesp(mp, XC_FREE_BLOCKS, mp->m_low_space,
560 				&shift);
561 
562 	/*
563 	 * Check each quota to cap the prealloc size, provide a shift value to
564 	 * throttle with and adjust amount of available space.
565 	 */
566 	if (xfs_quota_need_throttle(ip, XFS_DQTYPE_USER, alloc_blocks))
567 		xfs_quota_calc_throttle(ip, XFS_DQTYPE_USER, &qblocks, &qshift,
568 					&freesp);
569 	if (xfs_quota_need_throttle(ip, XFS_DQTYPE_GROUP, alloc_blocks))
570 		xfs_quota_calc_throttle(ip, XFS_DQTYPE_GROUP, &qblocks, &qshift,
571 					&freesp);
572 	if (xfs_quota_need_throttle(ip, XFS_DQTYPE_PROJ, alloc_blocks))
573 		xfs_quota_calc_throttle(ip, XFS_DQTYPE_PROJ, &qblocks, &qshift,
574 					&freesp);
575 
576 	/*
577 	 * The final prealloc size is set to the minimum of free space available
578 	 * in each of the quotas and the overall filesystem.
579 	 *
580 	 * The shift throttle value is set to the maximum value as determined by
581 	 * the global low free space values and per-quota low free space values.
582 	 */
583 	alloc_blocks = min(alloc_blocks, qblocks);
584 	shift = max(shift, qshift);
585 
586 	if (shift)
587 		alloc_blocks >>= shift;
588 	/*
589 	 * rounddown_pow_of_two() returns an undefined result if we pass in
590 	 * alloc_blocks = 0.
591 	 */
592 	if (alloc_blocks)
593 		alloc_blocks = rounddown_pow_of_two(alloc_blocks);
594 	if (alloc_blocks > XFS_MAX_BMBT_EXTLEN)
595 		alloc_blocks = XFS_MAX_BMBT_EXTLEN;
596 
597 	/*
598 	 * If we are still trying to allocate more space than is
599 	 * available, squash the prealloc hard. This can happen if we
600 	 * have a large file on a small filesystem and the above
601 	 * lowspace thresholds are smaller than XFS_BMBT_MAX_EXTLEN.
602 	 */
603 	while (alloc_blocks && alloc_blocks >= freesp)
604 		alloc_blocks >>= 4;
605 	if (alloc_blocks < mp->m_allocsize_blocks)
606 		alloc_blocks = mp->m_allocsize_blocks;
607 	trace_xfs_iomap_prealloc_size(ip, alloc_blocks, shift,
608 				      mp->m_allocsize_blocks);
609 	return alloc_blocks;
610 }
611 
612 int
xfs_iomap_write_unwritten(xfs_inode_t * ip,xfs_off_t offset,xfs_off_t count,bool update_isize)613 xfs_iomap_write_unwritten(
614 	xfs_inode_t	*ip,
615 	xfs_off_t	offset,
616 	xfs_off_t	count,
617 	bool		update_isize)
618 {
619 	xfs_mount_t	*mp = ip->i_mount;
620 	xfs_fileoff_t	offset_fsb;
621 	xfs_filblks_t	count_fsb;
622 	xfs_filblks_t	numblks_fsb;
623 	int		nimaps;
624 	xfs_trans_t	*tp;
625 	xfs_bmbt_irec_t imap;
626 	struct inode	*inode = VFS_I(ip);
627 	xfs_fsize_t	i_size;
628 	uint		resblks;
629 	int		error;
630 
631 	trace_xfs_unwritten_convert(ip, offset, count);
632 
633 	offset_fsb = XFS_B_TO_FSBT(mp, offset);
634 	count_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)offset + count);
635 	count_fsb = (xfs_filblks_t)(count_fsb - offset_fsb);
636 
637 	/*
638 	 * Reserve enough blocks in this transaction for two complete extent
639 	 * btree splits.  We may be converting the middle part of an unwritten
640 	 * extent and in this case we will insert two new extents in the btree
641 	 * each of which could cause a full split.
642 	 *
643 	 * This reservation amount will be used in the first call to
644 	 * xfs_bmbt_split() to select an AG with enough space to satisfy the
645 	 * rest of the operation.
646 	 */
647 	resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0) << 1;
648 
649 	/* Attach dquots so that bmbt splits are accounted correctly. */
650 	error = xfs_qm_dqattach(ip);
651 	if (error)
652 		return error;
653 
654 	do {
655 		/*
656 		 * Set up a transaction to convert the range of extents
657 		 * from unwritten to real. Do allocations in a loop until
658 		 * we have covered the range passed in.
659 		 *
660 		 * Note that we can't risk to recursing back into the filesystem
661 		 * here as we might be asked to write out the same inode that we
662 		 * complete here and might deadlock on the iolock.
663 		 */
664 		error = xfs_trans_alloc_inode(ip, &M_RES(mp)->tr_write, resblks,
665 				0, true, &tp);
666 		if (error)
667 			return error;
668 
669 		error = xfs_iext_count_extend(tp, ip, XFS_DATA_FORK,
670 				XFS_IEXT_WRITE_UNWRITTEN_CNT);
671 		if (error)
672 			goto error_on_bmapi_transaction;
673 
674 		/*
675 		 * Modify the unwritten extent state of the buffer.
676 		 */
677 		nimaps = 1;
678 		error = xfs_bmapi_write(tp, ip, offset_fsb, count_fsb,
679 					XFS_BMAPI_CONVERT, resblks, &imap,
680 					&nimaps);
681 		if (error)
682 			goto error_on_bmapi_transaction;
683 
684 		/*
685 		 * Log the updated inode size as we go.  We have to be careful
686 		 * to only log it up to the actual write offset if it is
687 		 * halfway into a block.
688 		 */
689 		i_size = XFS_FSB_TO_B(mp, offset_fsb + count_fsb);
690 		if (i_size > offset + count)
691 			i_size = offset + count;
692 		if (update_isize && i_size > i_size_read(inode))
693 			i_size_write(inode, i_size);
694 		i_size = xfs_new_eof(ip, i_size);
695 		if (i_size) {
696 			ip->i_disk_size = i_size;
697 			xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
698 		}
699 
700 		error = xfs_trans_commit(tp);
701 		xfs_iunlock(ip, XFS_ILOCK_EXCL);
702 		if (error)
703 			return error;
704 
705 		if (unlikely(!xfs_valid_startblock(ip, imap.br_startblock))) {
706 			xfs_bmap_mark_sick(ip, XFS_DATA_FORK);
707 			return xfs_alert_fsblock_zero(ip, &imap);
708 		}
709 
710 		if ((numblks_fsb = imap.br_blockcount) == 0) {
711 			/*
712 			 * The numblks_fsb value should always get
713 			 * smaller, otherwise the loop is stuck.
714 			 */
715 			ASSERT(imap.br_blockcount);
716 			break;
717 		}
718 		offset_fsb += numblks_fsb;
719 		count_fsb -= numblks_fsb;
720 	} while (count_fsb > 0);
721 
722 	return 0;
723 
724 error_on_bmapi_transaction:
725 	xfs_trans_cancel(tp);
726 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
727 	return error;
728 }
729 
730 static inline bool
imap_needs_alloc(struct inode * inode,unsigned flags,struct xfs_bmbt_irec * imap,int nimaps)731 imap_needs_alloc(
732 	struct inode		*inode,
733 	unsigned		flags,
734 	struct xfs_bmbt_irec	*imap,
735 	int			nimaps)
736 {
737 	/* don't allocate blocks when just zeroing */
738 	if (flags & IOMAP_ZERO)
739 		return false;
740 	if (!nimaps ||
741 	    imap->br_startblock == HOLESTARTBLOCK ||
742 	    imap->br_startblock == DELAYSTARTBLOCK)
743 		return true;
744 	/* we convert unwritten extents before copying the data for DAX */
745 	if ((flags & IOMAP_DAX) && imap->br_state == XFS_EXT_UNWRITTEN)
746 		return true;
747 	return false;
748 }
749 
750 static inline bool
imap_needs_cow(struct xfs_inode * ip,unsigned int flags,struct xfs_bmbt_irec * imap,int nimaps)751 imap_needs_cow(
752 	struct xfs_inode	*ip,
753 	unsigned int		flags,
754 	struct xfs_bmbt_irec	*imap,
755 	int			nimaps)
756 {
757 	if (!xfs_is_cow_inode(ip))
758 		return false;
759 
760 	/* when zeroing we don't have to COW holes or unwritten extents */
761 	if (flags & (IOMAP_UNSHARE | IOMAP_ZERO)) {
762 		if (!nimaps ||
763 		    imap->br_startblock == HOLESTARTBLOCK ||
764 		    imap->br_state == XFS_EXT_UNWRITTEN)
765 			return false;
766 	}
767 
768 	return true;
769 }
770 
771 /*
772  * Extents not yet cached requires exclusive access, don't block for
773  * IOMAP_NOWAIT.
774  *
775  * This is basically an opencoded xfs_ilock_data_map_shared() call, but with
776  * support for IOMAP_NOWAIT.
777  */
778 static int
xfs_ilock_for_iomap(struct xfs_inode * ip,unsigned flags,unsigned * lockmode)779 xfs_ilock_for_iomap(
780 	struct xfs_inode	*ip,
781 	unsigned		flags,
782 	unsigned		*lockmode)
783 {
784 	if (flags & IOMAP_NOWAIT) {
785 		if (xfs_need_iread_extents(&ip->i_df))
786 			return -EAGAIN;
787 		if (!xfs_ilock_nowait(ip, *lockmode))
788 			return -EAGAIN;
789 	} else {
790 		if (xfs_need_iread_extents(&ip->i_df))
791 			*lockmode = XFS_ILOCK_EXCL;
792 		xfs_ilock(ip, *lockmode);
793 	}
794 
795 	return 0;
796 }
797 
798 /*
799  * Check that the imap we are going to return to the caller spans the entire
800  * range that the caller requested for the IO.
801  */
802 static bool
imap_spans_range(struct xfs_bmbt_irec * imap,xfs_fileoff_t offset_fsb,xfs_fileoff_t end_fsb)803 imap_spans_range(
804 	struct xfs_bmbt_irec	*imap,
805 	xfs_fileoff_t		offset_fsb,
806 	xfs_fileoff_t		end_fsb)
807 {
808 	if (imap->br_startoff > offset_fsb)
809 		return false;
810 	if (imap->br_startoff + imap->br_blockcount < end_fsb)
811 		return false;
812 	return true;
813 }
814 
815 static bool
xfs_bmap_hw_atomic_write_possible(struct xfs_inode * ip,struct xfs_bmbt_irec * imap,xfs_fileoff_t offset_fsb,xfs_fileoff_t end_fsb)816 xfs_bmap_hw_atomic_write_possible(
817 	struct xfs_inode	*ip,
818 	struct xfs_bmbt_irec	*imap,
819 	xfs_fileoff_t		offset_fsb,
820 	xfs_fileoff_t		end_fsb)
821 {
822 	struct xfs_mount	*mp = ip->i_mount;
823 	xfs_fsize_t		len = XFS_FSB_TO_B(mp, end_fsb - offset_fsb);
824 
825 	/*
826 	 * atomic writes are required to be naturally aligned for disk blocks,
827 	 * which ensures that we adhere to block layer rules that we won't
828 	 * straddle any boundary or violate write alignment requirement.
829 	 */
830 	if (!IS_ALIGNED(imap->br_startblock, imap->br_blockcount))
831 		return false;
832 
833 	/*
834 	 * Spanning multiple extents would mean that multiple BIOs would be
835 	 * issued, and so would lose atomicity required for REQ_ATOMIC-based
836 	 * atomics.
837 	 */
838 	if (!imap_spans_range(imap, offset_fsb, end_fsb))
839 		return false;
840 
841 	/*
842 	 * The ->iomap_begin caller should ensure this, but check anyway.
843 	 */
844 	return len <= xfs_inode_buftarg(ip)->bt_awu_max;
845 }
846 
847 static int
xfs_direct_write_iomap_begin(struct inode * inode,loff_t offset,loff_t length,unsigned flags,struct iomap * iomap,struct iomap * srcmap)848 xfs_direct_write_iomap_begin(
849 	struct inode		*inode,
850 	loff_t			offset,
851 	loff_t			length,
852 	unsigned		flags,
853 	struct iomap		*iomap,
854 	struct iomap		*srcmap)
855 {
856 	struct xfs_inode	*ip = XFS_I(inode);
857 	struct xfs_mount	*mp = ip->i_mount;
858 	struct xfs_bmbt_irec	imap, cmap;
859 	xfs_fileoff_t		offset_fsb = XFS_B_TO_FSBT(mp, offset);
860 	xfs_fileoff_t		end_fsb = xfs_iomap_end_fsb(mp, offset, length);
861 	xfs_fileoff_t		orig_end_fsb = end_fsb;
862 	int			nimaps = 1, error = 0;
863 	bool			shared = false;
864 	u16			iomap_flags = 0;
865 	bool			needs_alloc;
866 	unsigned int		lockmode;
867 	u64			seq;
868 
869 	ASSERT(flags & (IOMAP_WRITE | IOMAP_ZERO));
870 
871 	if (xfs_is_shutdown(mp))
872 		return -EIO;
873 
874 	/*
875 	 * Writes that span EOF might trigger an IO size update on completion,
876 	 * so consider them to be dirty for the purposes of O_DSYNC even if
877 	 * there is no other metadata changes pending or have been made here.
878 	 */
879 	if (offset + length > i_size_read(inode))
880 		iomap_flags |= IOMAP_F_DIRTY;
881 
882 	/* HW-offload atomics are always used in this path */
883 	if (flags & IOMAP_ATOMIC)
884 		iomap_flags |= IOMAP_F_ATOMIC_BIO;
885 
886 	/*
887 	 * COW writes may allocate delalloc space or convert unwritten COW
888 	 * extents, so we need to make sure to take the lock exclusively here.
889 	 */
890 	if (xfs_is_cow_inode(ip))
891 		lockmode = XFS_ILOCK_EXCL;
892 	else
893 		lockmode = XFS_ILOCK_SHARED;
894 
895 relock:
896 	error = xfs_ilock_for_iomap(ip, flags, &lockmode);
897 	if (error)
898 		return error;
899 
900 	/*
901 	 * The reflink iflag could have changed since the earlier unlocked
902 	 * check, check if it again and relock if needed.
903 	 */
904 	if (xfs_is_cow_inode(ip) && lockmode == XFS_ILOCK_SHARED) {
905 		xfs_iunlock(ip, lockmode);
906 		lockmode = XFS_ILOCK_EXCL;
907 		goto relock;
908 	}
909 
910 	error = xfs_bmapi_read(ip, offset_fsb, end_fsb - offset_fsb, &imap,
911 			       &nimaps, 0);
912 	if (error)
913 		goto out_unlock;
914 
915 	if (imap_needs_cow(ip, flags, &imap, nimaps)) {
916 		error = -EAGAIN;
917 		if (flags & IOMAP_NOWAIT)
918 			goto out_unlock;
919 
920 		/* may drop and re-acquire the ilock */
921 		error = xfs_reflink_allocate_cow(ip, &imap, &cmap, &shared,
922 				&lockmode,
923 				(flags & IOMAP_DIRECT) || IS_DAX(inode));
924 		if (error)
925 			goto out_unlock;
926 		if (shared) {
927 			if ((flags & IOMAP_ATOMIC) &&
928 			    !xfs_bmap_hw_atomic_write_possible(ip, &cmap,
929 					offset_fsb, end_fsb)) {
930 				error = -ENOPROTOOPT;
931 				goto out_unlock;
932 			}
933 			goto out_found_cow;
934 		}
935 		end_fsb = imap.br_startoff + imap.br_blockcount;
936 		length = XFS_FSB_TO_B(mp, end_fsb) - offset;
937 	}
938 
939 	needs_alloc = imap_needs_alloc(inode, flags, &imap, nimaps);
940 
941 	if (flags & IOMAP_ATOMIC) {
942 		error = -ENOPROTOOPT;
943 		/*
944 		 * If we allocate less than what is required for the write
945 		 * then we may end up with multiple extents, which means that
946 		 * REQ_ATOMIC-based cannot be used, so avoid this possibility.
947 		 */
948 		if (needs_alloc && orig_end_fsb - offset_fsb > 1)
949 			goto out_unlock;
950 
951 		if (!xfs_bmap_hw_atomic_write_possible(ip, &imap, offset_fsb,
952 				orig_end_fsb))
953 			goto out_unlock;
954 	}
955 
956 	if (needs_alloc)
957 		goto allocate_blocks;
958 
959 	/*
960 	 * NOWAIT and OVERWRITE I/O needs to span the entire requested I/O with
961 	 * a single map so that we avoid partial IO failures due to the rest of
962 	 * the I/O range not covered by this map triggering an EAGAIN condition
963 	 * when it is subsequently mapped and aborting the I/O.
964 	 */
965 	if (flags & (IOMAP_NOWAIT | IOMAP_OVERWRITE_ONLY)) {
966 		error = -EAGAIN;
967 		if (!imap_spans_range(&imap, offset_fsb, end_fsb))
968 			goto out_unlock;
969 	}
970 
971 	/*
972 	 * For overwrite only I/O, we cannot convert unwritten extents without
973 	 * requiring sub-block zeroing.  This can only be done under an
974 	 * exclusive IOLOCK, hence return -EAGAIN if this is not a written
975 	 * extent to tell the caller to try again.
976 	 */
977 	if (flags & IOMAP_OVERWRITE_ONLY) {
978 		error = -EAGAIN;
979 		if (imap.br_state != XFS_EXT_NORM &&
980 	            ((offset | length) & mp->m_blockmask))
981 			goto out_unlock;
982 	}
983 
984 	seq = xfs_iomap_inode_sequence(ip, iomap_flags);
985 	xfs_iunlock(ip, lockmode);
986 	trace_xfs_iomap_found(ip, offset, length, XFS_DATA_FORK, &imap);
987 	return xfs_bmbt_to_iomap(ip, iomap, &imap, flags, iomap_flags, seq);
988 
989 allocate_blocks:
990 	error = -EAGAIN;
991 	if (flags & (IOMAP_NOWAIT | IOMAP_OVERWRITE_ONLY))
992 		goto out_unlock;
993 
994 	/*
995 	 * We cap the maximum length we map to a sane size  to keep the chunks
996 	 * of work done where somewhat symmetric with the work writeback does.
997 	 * This is a completely arbitrary number pulled out of thin air as a
998 	 * best guess for initial testing.
999 	 *
1000 	 * Note that the values needs to be less than 32-bits wide until the
1001 	 * lower level functions are updated.
1002 	 */
1003 	length = min_t(loff_t, length, 1024 * PAGE_SIZE);
1004 	end_fsb = xfs_iomap_end_fsb(mp, offset, length);
1005 
1006 	if (offset + length > XFS_ISIZE(ip))
1007 		end_fsb = xfs_iomap_eof_align_last_fsb(ip, end_fsb);
1008 	else if (nimaps && imap.br_startblock == HOLESTARTBLOCK)
1009 		end_fsb = min(end_fsb, imap.br_startoff + imap.br_blockcount);
1010 	xfs_iunlock(ip, lockmode);
1011 
1012 	error = xfs_iomap_write_direct(ip, offset_fsb, end_fsb - offset_fsb,
1013 			flags, &imap, &seq);
1014 	if (error)
1015 		return error;
1016 
1017 	trace_xfs_iomap_alloc(ip, offset, length, XFS_DATA_FORK, &imap);
1018 	return xfs_bmbt_to_iomap(ip, iomap, &imap, flags,
1019 				 iomap_flags | IOMAP_F_NEW, seq);
1020 
1021 out_found_cow:
1022 	length = XFS_FSB_TO_B(mp, cmap.br_startoff + cmap.br_blockcount);
1023 	trace_xfs_iomap_found(ip, offset, length - offset, XFS_COW_FORK, &cmap);
1024 	if (imap.br_startblock != HOLESTARTBLOCK) {
1025 		seq = xfs_iomap_inode_sequence(ip, 0);
1026 		error = xfs_bmbt_to_iomap(ip, srcmap, &imap, flags, 0, seq);
1027 		if (error)
1028 			goto out_unlock;
1029 	}
1030 	seq = xfs_iomap_inode_sequence(ip, IOMAP_F_SHARED);
1031 	xfs_iunlock(ip, lockmode);
1032 	return xfs_bmbt_to_iomap(ip, iomap, &cmap, flags, IOMAP_F_SHARED, seq);
1033 
1034 out_unlock:
1035 	if (lockmode)
1036 		xfs_iunlock(ip, lockmode);
1037 	return error;
1038 }
1039 
1040 static DEFINE_IOMAP_ITER_NEXT(xfs_direct_write_iomap_next,
1041 		xfs_direct_write_iomap_begin);
1042 
1043 const struct iomap_ops xfs_direct_write_iomap_ops = {
1044 	.iomap_next		= xfs_direct_write_iomap_next,
1045 };
1046 
1047 #ifdef CONFIG_XFS_RT
1048 /*
1049  * This is really simple.  The space has already been reserved before taking the
1050  * IOLOCK, the actual block allocation is done just before submitting the bio
1051  * and only recorded in the extent map on I/O completion.
1052  */
1053 static int
xfs_zoned_direct_write_iomap_begin(struct inode * inode,loff_t offset,loff_t length,unsigned flags,struct iomap * iomap,struct iomap * srcmap)1054 xfs_zoned_direct_write_iomap_begin(
1055 	struct inode		*inode,
1056 	loff_t			offset,
1057 	loff_t			length,
1058 	unsigned		flags,
1059 	struct iomap		*iomap,
1060 	struct iomap		*srcmap)
1061 {
1062 	struct xfs_inode	*ip = XFS_I(inode);
1063 	int			error;
1064 
1065 	ASSERT(!(flags & IOMAP_OVERWRITE_ONLY));
1066 
1067 	/*
1068 	 * Needs to be pushed down into the allocator so that only writes into
1069 	 * a single zone can be supported.
1070 	 */
1071 	if (flags & IOMAP_NOWAIT)
1072 		return -EAGAIN;
1073 
1074 	/*
1075 	 * Ensure the extent list is in memory in so that we don't have to do
1076 	 * read it from the I/O completion handler.
1077 	 */
1078 	if (xfs_need_iread_extents(&ip->i_df)) {
1079 		xfs_ilock(ip, XFS_ILOCK_EXCL);
1080 		error = xfs_iread_extents(NULL, ip, XFS_DATA_FORK);
1081 		xfs_iunlock(ip, XFS_ILOCK_EXCL);
1082 		if (error)
1083 			return error;
1084 	}
1085 
1086 	xfs_iomap_set_anon_write(ip, iomap, offset, length);
1087 	return 0;
1088 }
1089 
1090 static DEFINE_IOMAP_ITER_NEXT(xfs_zoned_direct_write_iomap_next,
1091 		xfs_zoned_direct_write_iomap_begin);
1092 
1093 const struct iomap_ops xfs_zoned_direct_write_iomap_ops = {
1094 	.iomap_next		= xfs_zoned_direct_write_iomap_next,
1095 };
1096 #endif /* CONFIG_XFS_RT */
1097 
1098 #ifdef DEBUG
1099 static void
xfs_check_atomic_cow_conversion(struct xfs_inode * ip,xfs_fileoff_t offset_fsb,xfs_filblks_t count_fsb,const struct xfs_bmbt_irec * cmap)1100 xfs_check_atomic_cow_conversion(
1101 	struct xfs_inode		*ip,
1102 	xfs_fileoff_t			offset_fsb,
1103 	xfs_filblks_t			count_fsb,
1104 	const struct xfs_bmbt_irec	*cmap)
1105 {
1106 	struct xfs_iext_cursor		icur;
1107 	struct xfs_bmbt_irec		cmap2 = { };
1108 
1109 	if (xfs_iext_lookup_extent(ip, ip->i_cowfp, offset_fsb, &icur, &cmap2))
1110 		xfs_trim_extent(&cmap2, offset_fsb, count_fsb);
1111 
1112 	ASSERT(cmap2.br_startoff == cmap->br_startoff);
1113 	ASSERT(cmap2.br_blockcount == cmap->br_blockcount);
1114 	ASSERT(cmap2.br_startblock == cmap->br_startblock);
1115 	ASSERT(cmap2.br_state == cmap->br_state);
1116 }
1117 #else
1118 # define xfs_check_atomic_cow_conversion(...)	((void)0)
1119 #endif
1120 
1121 static int
xfs_atomic_write_cow_iomap_begin(struct inode * inode,loff_t offset,loff_t length,unsigned flags,struct iomap * iomap,struct iomap * srcmap)1122 xfs_atomic_write_cow_iomap_begin(
1123 	struct inode		*inode,
1124 	loff_t			offset,
1125 	loff_t			length,
1126 	unsigned		flags,
1127 	struct iomap		*iomap,
1128 	struct iomap		*srcmap)
1129 {
1130 	struct xfs_inode	*ip = XFS_I(inode);
1131 	struct xfs_mount	*mp = ip->i_mount;
1132 	const xfs_fileoff_t	offset_fsb = XFS_B_TO_FSBT(mp, offset);
1133 	const xfs_fileoff_t	end_fsb = XFS_B_TO_FSB(mp, offset + length);
1134 	const xfs_filblks_t	count_fsb = end_fsb - offset_fsb;
1135 	xfs_filblks_t		hole_count_fsb;
1136 	int			nmaps = 1;
1137 	xfs_filblks_t		resaligned;
1138 	struct xfs_bmbt_irec	cmap;
1139 	struct xfs_iext_cursor	icur;
1140 	struct xfs_trans	*tp;
1141 	unsigned int		dblocks = 0, rblocks = 0;
1142 	int			error;
1143 	u64			seq;
1144 
1145 	ASSERT(flags & IOMAP_WRITE);
1146 	ASSERT(flags & IOMAP_DIRECT);
1147 
1148 	if (xfs_is_shutdown(mp))
1149 		return -EIO;
1150 
1151 	if (!xfs_can_sw_atomic_write(mp)) {
1152 		ASSERT(xfs_can_sw_atomic_write(mp));
1153 		return -EINVAL;
1154 	}
1155 
1156 	/* blocks are always allocated in this path */
1157 	if (flags & IOMAP_NOWAIT)
1158 		return -EAGAIN;
1159 
1160 	trace_xfs_iomap_atomic_write_cow(ip, offset, length);
1161 retry:
1162 	xfs_ilock(ip, XFS_ILOCK_EXCL);
1163 
1164 	if (!ip->i_cowfp) {
1165 		ASSERT(!xfs_is_reflink_inode(ip));
1166 		xfs_ifork_init_cow(ip);
1167 	}
1168 
1169 	if (!xfs_iext_lookup_extent(ip, ip->i_cowfp, offset_fsb, &icur, &cmap))
1170 		cmap.br_startoff = end_fsb;
1171 	if (cmap.br_startoff <= offset_fsb) {
1172 		if (isnullstartblock(cmap.br_startblock))
1173 			goto convert_delay;
1174 
1175 		/*
1176 		 * cmap could extend outside the write range due to previous
1177 		 * speculative preallocations.  We must trim cmap to the write
1178 		 * range because the cow fork treats written mappings to mean
1179 		 * "write in progress".
1180 		 */
1181 		xfs_trim_extent(&cmap, offset_fsb, count_fsb);
1182 		goto found;
1183 	}
1184 
1185 	hole_count_fsb = cmap.br_startoff - offset_fsb;
1186 
1187 	resaligned = xfs_aligned_fsb_count(offset_fsb, hole_count_fsb,
1188 			xfs_get_cowextsz_hint(ip));
1189 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1190 
1191 	if (XFS_IS_REALTIME_INODE(ip)) {
1192 		dblocks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
1193 		rblocks = resaligned;
1194 	} else {
1195 		dblocks = XFS_DIOSTRAT_SPACE_RES(mp, resaligned);
1196 		rblocks = 0;
1197 	}
1198 
1199 	error = xfs_trans_alloc_inode(ip, &M_RES(mp)->tr_write, dblocks,
1200 			rblocks, false, &tp);
1201 	if (error)
1202 		return error;
1203 
1204 	/* extent layout could have changed since the unlock, so check again */
1205 	if (!xfs_iext_lookup_extent(ip, ip->i_cowfp, offset_fsb, &icur, &cmap))
1206 		cmap.br_startoff = end_fsb;
1207 	if (cmap.br_startoff <= offset_fsb) {
1208 		xfs_trans_cancel(tp);
1209 		if (isnullstartblock(cmap.br_startblock))
1210 			goto convert_delay;
1211 		xfs_trim_extent(&cmap, offset_fsb, count_fsb);
1212 		goto found;
1213 	}
1214 
1215 	/*
1216 	 * Allocate the entire reservation as unwritten blocks.
1217 	 *
1218 	 * Use XFS_BMAPI_EXTSZALIGN to hint at aligning new extents according to
1219 	 * extszhint, such that there will be a greater chance that future
1220 	 * atomic writes to that same range will be aligned (and don't require
1221 	 * this COW-based method).
1222 	 */
1223 	error = xfs_bmapi_write(tp, ip, offset_fsb, hole_count_fsb,
1224 			XFS_BMAPI_COWFORK | XFS_BMAPI_PREALLOC |
1225 			XFS_BMAPI_EXTSZALIGN, 0, &cmap, &nmaps);
1226 	if (error) {
1227 		xfs_trans_cancel(tp);
1228 		goto out_unlock;
1229 	}
1230 
1231 	xfs_inode_set_cowblocks_tag(ip);
1232 	error = xfs_trans_commit(tp);
1233 	if (error)
1234 		goto out_unlock;
1235 
1236 	/*
1237 	 * cmap could map more blocks than the range we passed into bmapi_write
1238 	 * because of EXTSZALIGN or adjacent pre-existing unwritten mappings
1239 	 * that were merged.  Trim cmap to the original write range so that we
1240 	 * don't convert more than we were asked to do for this write.
1241 	 */
1242 	xfs_trim_extent(&cmap, offset_fsb, count_fsb);
1243 
1244 found:
1245 	if (cmap.br_state != XFS_EXT_NORM) {
1246 		error = xfs_reflink_convert_cow_locked(ip, cmap.br_startoff,
1247 				cmap.br_blockcount);
1248 		if (error)
1249 			goto out_unlock;
1250 		cmap.br_state = XFS_EXT_NORM;
1251 		xfs_check_atomic_cow_conversion(ip, offset_fsb, count_fsb,
1252 				&cmap);
1253 	}
1254 
1255 	trace_xfs_iomap_found(ip, offset, length, XFS_COW_FORK, &cmap);
1256 	seq = xfs_iomap_inode_sequence(ip, IOMAP_F_SHARED);
1257 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1258 	return xfs_bmbt_to_iomap(ip, iomap, &cmap, flags, IOMAP_F_SHARED, seq);
1259 
1260 convert_delay:
1261 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1262 	error = xfs_bmapi_convert_delalloc(ip, XFS_COW_FORK, offset, iomap,
1263 			NULL);
1264 	if (error)
1265 		return error;
1266 
1267 	/*
1268 	 * Try the lookup again, because the delalloc conversion might have
1269 	 * turned the COW mapping into unwritten, but we need it to be in
1270 	 * written state.
1271 	 */
1272 	goto retry;
1273 out_unlock:
1274 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
1275 	return error;
1276 }
1277 
1278 static DEFINE_IOMAP_ITER_NEXT(xfs_atomic_write_cow_iomap_next,
1279 		xfs_atomic_write_cow_iomap_begin);
1280 
1281 const struct iomap_ops xfs_atomic_write_cow_iomap_ops = {
1282 	.iomap_next		= xfs_atomic_write_cow_iomap_next,
1283 };
1284 
1285 static int
xfs_dax_write_iomap_end(struct inode * inode,loff_t pos,loff_t length,ssize_t written,unsigned flags,struct iomap * iomap)1286 xfs_dax_write_iomap_end(
1287 	struct inode		*inode,
1288 	loff_t			pos,
1289 	loff_t			length,
1290 	ssize_t			written,
1291 	unsigned		flags,
1292 	struct iomap		*iomap)
1293 {
1294 	struct xfs_inode	*ip = XFS_I(inode);
1295 
1296 	if (!xfs_is_cow_inode(ip))
1297 		return 0;
1298 
1299 	if (!written)
1300 		return xfs_reflink_cancel_cow_range(ip, pos, length, true);
1301 
1302 	return xfs_reflink_end_cow(ip, pos, written);
1303 }
1304 
1305 static DEFINE_IOMAP_ITER_NEXT_END(xfs_dax_write_iomap_next,
1306 		xfs_direct_write_iomap_begin, xfs_dax_write_iomap_end);
1307 
1308 const struct iomap_ops xfs_dax_write_iomap_ops = {
1309 	.iomap_next	= xfs_dax_write_iomap_next,
1310 };
1311 
1312 /*
1313  * Convert a hole to a delayed allocation.
1314  */
1315 static void
xfs_bmap_add_extent_hole_delay(struct xfs_inode * ip,int whichfork,struct xfs_iext_cursor * icur,struct xfs_bmbt_irec * new)1316 xfs_bmap_add_extent_hole_delay(
1317 	struct xfs_inode	*ip,	/* incore inode pointer */
1318 	int			whichfork,
1319 	struct xfs_iext_cursor	*icur,
1320 	struct xfs_bmbt_irec	*new)	/* new data to add to file extents */
1321 {
1322 	struct xfs_ifork	*ifp;	/* inode fork pointer */
1323 	xfs_bmbt_irec_t		left;	/* left neighbor extent entry */
1324 	xfs_filblks_t		newlen=0;	/* new indirect size */
1325 	xfs_filblks_t		oldlen=0;	/* old indirect size */
1326 	xfs_bmbt_irec_t		right;	/* right neighbor extent entry */
1327 	uint32_t		state = xfs_bmap_fork_to_state(whichfork);
1328 	xfs_filblks_t		temp;	 /* temp for indirect calculations */
1329 
1330 	ifp = xfs_ifork_ptr(ip, whichfork);
1331 	ASSERT(isnullstartblock(new->br_startblock));
1332 
1333 	/*
1334 	 * Check and set flags if this segment has a left neighbor
1335 	 */
1336 	if (xfs_iext_peek_prev_extent(ifp, icur, &left)) {
1337 		state |= BMAP_LEFT_VALID;
1338 		if (isnullstartblock(left.br_startblock))
1339 			state |= BMAP_LEFT_DELAY;
1340 	}
1341 
1342 	/*
1343 	 * Check and set flags if the current (right) segment exists.
1344 	 * If it doesn't exist, we're converting the hole at end-of-file.
1345 	 */
1346 	if (xfs_iext_get_extent(ifp, icur, &right)) {
1347 		state |= BMAP_RIGHT_VALID;
1348 		if (isnullstartblock(right.br_startblock))
1349 			state |= BMAP_RIGHT_DELAY;
1350 	}
1351 
1352 	/*
1353 	 * Set contiguity flags on the left and right neighbors.
1354 	 * Don't let extents get too large, even if the pieces are contiguous.
1355 	 */
1356 	if ((state & BMAP_LEFT_VALID) && (state & BMAP_LEFT_DELAY) &&
1357 	    left.br_startoff + left.br_blockcount == new->br_startoff &&
1358 	    left.br_blockcount + new->br_blockcount <= XFS_MAX_BMBT_EXTLEN)
1359 		state |= BMAP_LEFT_CONTIG;
1360 
1361 	if ((state & BMAP_RIGHT_VALID) && (state & BMAP_RIGHT_DELAY) &&
1362 	    new->br_startoff + new->br_blockcount == right.br_startoff &&
1363 	    new->br_blockcount + right.br_blockcount <= XFS_MAX_BMBT_EXTLEN &&
1364 	    (!(state & BMAP_LEFT_CONTIG) ||
1365 	     (left.br_blockcount + new->br_blockcount +
1366 	      right.br_blockcount <= XFS_MAX_BMBT_EXTLEN)))
1367 		state |= BMAP_RIGHT_CONTIG;
1368 
1369 	/*
1370 	 * Switch out based on the contiguity flags.
1371 	 */
1372 	switch (state & (BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG)) {
1373 	case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
1374 		/*
1375 		 * New allocation is contiguous with delayed allocations
1376 		 * on the left and on the right.
1377 		 * Merge all three into a single extent record.
1378 		 */
1379 		temp = left.br_blockcount + new->br_blockcount +
1380 			right.br_blockcount;
1381 
1382 		oldlen = startblockval(left.br_startblock) +
1383 			startblockval(new->br_startblock) +
1384 			startblockval(right.br_startblock);
1385 		newlen = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
1386 					 oldlen);
1387 		left.br_startblock = nullstartblock(newlen);
1388 		left.br_blockcount = temp;
1389 
1390 		xfs_iext_remove(ip, icur, state);
1391 		xfs_iext_prev(ifp, icur);
1392 		xfs_iext_update_extent(ip, state, icur, &left);
1393 		break;
1394 
1395 	case BMAP_LEFT_CONTIG:
1396 		/*
1397 		 * New allocation is contiguous with a delayed allocation
1398 		 * on the left.
1399 		 * Merge the new allocation with the left neighbor.
1400 		 */
1401 		temp = left.br_blockcount + new->br_blockcount;
1402 
1403 		oldlen = startblockval(left.br_startblock) +
1404 			startblockval(new->br_startblock);
1405 		newlen = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
1406 					 oldlen);
1407 		left.br_blockcount = temp;
1408 		left.br_startblock = nullstartblock(newlen);
1409 
1410 		xfs_iext_prev(ifp, icur);
1411 		xfs_iext_update_extent(ip, state, icur, &left);
1412 		break;
1413 
1414 	case BMAP_RIGHT_CONTIG:
1415 		/*
1416 		 * New allocation is contiguous with a delayed allocation
1417 		 * on the right.
1418 		 * Merge the new allocation with the right neighbor.
1419 		 */
1420 		temp = new->br_blockcount + right.br_blockcount;
1421 		oldlen = startblockval(new->br_startblock) +
1422 			startblockval(right.br_startblock);
1423 		newlen = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
1424 					 oldlen);
1425 		right.br_startoff = new->br_startoff;
1426 		right.br_startblock = nullstartblock(newlen);
1427 		right.br_blockcount = temp;
1428 		xfs_iext_update_extent(ip, state, icur, &right);
1429 		break;
1430 
1431 	case 0:
1432 		/*
1433 		 * New allocation is not contiguous with another
1434 		 * delayed allocation.
1435 		 * Insert a new entry.
1436 		 */
1437 		oldlen = newlen = 0;
1438 		xfs_iext_insert(ip, icur, new, state);
1439 		break;
1440 	}
1441 	if (oldlen != newlen) {
1442 		ASSERT(oldlen > newlen);
1443 		xfs_add_fdblocks(ip->i_mount, oldlen - newlen);
1444 
1445 		/*
1446 		 * Nothing to do for disk quota accounting here.
1447 		 */
1448 		xfs_mod_delalloc(ip, 0, (int64_t)newlen - oldlen);
1449 	}
1450 }
1451 
1452 /*
1453  * Add a delayed allocation extent to an inode. Blocks are reserved from the
1454  * global pool and the extent inserted into the inode in-core extent tree.
1455  *
1456  * On entry, got refers to the first extent beyond the offset of the extent to
1457  * allocate or eof is specified if no such extent exists. On return, got refers
1458  * to the extent record that was inserted to the inode fork.
1459  *
1460  * Note that the allocated extent may have been merged with contiguous extents
1461  * during insertion into the inode fork. Thus, got does not reflect the current
1462  * state of the inode fork on return. If necessary, the caller can use lastx to
1463  * look up the updated record in the inode fork.
1464  */
1465 static int
xfs_bmapi_reserve_delalloc(struct xfs_inode * ip,int whichfork,xfs_fileoff_t off,xfs_filblks_t len,xfs_filblks_t prealloc,struct xfs_bmbt_irec * got,struct xfs_iext_cursor * icur,int eof)1466 xfs_bmapi_reserve_delalloc(
1467 	struct xfs_inode	*ip,
1468 	int			whichfork,
1469 	xfs_fileoff_t		off,
1470 	xfs_filblks_t		len,
1471 	xfs_filblks_t		prealloc,
1472 	struct xfs_bmbt_irec	*got,
1473 	struct xfs_iext_cursor	*icur,
1474 	int			eof)
1475 {
1476 	struct xfs_mount	*mp = ip->i_mount;
1477 	struct xfs_ifork	*ifp = xfs_ifork_ptr(ip, whichfork);
1478 	xfs_extlen_t		alen;
1479 	xfs_extlen_t		indlen;
1480 	uint64_t		fdblocks;
1481 	int			error;
1482 	xfs_fileoff_t		aoff;
1483 	bool			use_cowextszhint =
1484 					whichfork == XFS_COW_FORK && !prealloc;
1485 
1486 retry:
1487 	/*
1488 	 * Cap the alloc length. Keep track of prealloc so we know whether to
1489 	 * tag the inode before we return.
1490 	 */
1491 	aoff = off;
1492 	alen = XFS_FILBLKS_MIN(len + prealloc, XFS_MAX_BMBT_EXTLEN);
1493 	if (!eof)
1494 		alen = XFS_FILBLKS_MIN(alen, got->br_startoff - aoff);
1495 	if (prealloc && alen >= len)
1496 		prealloc = alen - len;
1497 
1498 	/*
1499 	 * If we're targetting the COW fork but aren't creating a speculative
1500 	 * posteof preallocation, try to expand the reservation to align with
1501 	 * the COW extent size hint if there's sufficient free space.
1502 	 *
1503 	 * Unlike the data fork, the CoW cancellation functions will free all
1504 	 * the reservations at inactivation, so we don't require that every
1505 	 * delalloc reservation have a dirty pagecache.
1506 	 */
1507 	if (use_cowextszhint) {
1508 		struct xfs_bmbt_irec	prev;
1509 		xfs_extlen_t		extsz = xfs_get_cowextsz_hint(ip);
1510 
1511 		if (!xfs_iext_peek_prev_extent(ifp, icur, &prev))
1512 			prev.br_startoff = NULLFILEOFF;
1513 
1514 		error = xfs_bmap_extsize_align(mp, got, &prev, extsz, 0, eof,
1515 					       1, 0, &aoff, &alen);
1516 		ASSERT(!error);
1517 	}
1518 
1519 	/*
1520 	 * Make a transaction-less quota reservation for delayed allocation
1521 	 * blocks.  This number gets adjusted later.  We return if we haven't
1522 	 * allocated blocks already inside this loop.
1523 	 */
1524 	error = xfs_quota_reserve_blkres(ip, alen);
1525 	if (error)
1526 		goto out;
1527 
1528 	/*
1529 	 * Split changing sb for alen and indlen since they could be coming
1530 	 * from different places.
1531 	 */
1532 	indlen = (xfs_extlen_t)xfs_bmap_worst_indlen(ip, alen);
1533 	ASSERT(indlen > 0);
1534 
1535 	fdblocks = indlen;
1536 	if (XFS_IS_REALTIME_INODE(ip)) {
1537 		ASSERT(!xfs_is_zoned_inode(ip));
1538 		error = xfs_dec_frextents(mp, xfs_blen_to_rtbxlen(mp, alen));
1539 		if (error)
1540 			goto out_unreserve_quota;
1541 	} else {
1542 		fdblocks += alen;
1543 	}
1544 
1545 	error = xfs_dec_fdblocks(mp, fdblocks, false);
1546 	if (error)
1547 		goto out_unreserve_frextents;
1548 
1549 	ip->i_delayed_blks += alen;
1550 	xfs_mod_delalloc(ip, alen, indlen);
1551 
1552 	got->br_startoff = aoff;
1553 	got->br_startblock = nullstartblock(indlen);
1554 	got->br_blockcount = alen;
1555 	got->br_state = XFS_EXT_NORM;
1556 
1557 	xfs_bmap_add_extent_hole_delay(ip, whichfork, icur, got);
1558 
1559 	/*
1560 	 * Tag the inode if blocks were preallocated. Note that COW fork
1561 	 * preallocation can occur at the start or end of the extent, even when
1562 	 * prealloc == 0, so we must also check the aligned offset and length.
1563 	 */
1564 	if (whichfork == XFS_DATA_FORK && prealloc)
1565 		xfs_inode_set_eofblocks_tag(ip);
1566 	if (whichfork == XFS_COW_FORK && (prealloc || aoff < off || alen > len))
1567 		xfs_inode_set_cowblocks_tag(ip);
1568 
1569 	return 0;
1570 
1571 out_unreserve_frextents:
1572 	if (XFS_IS_REALTIME_INODE(ip))
1573 		xfs_add_frextents(mp, xfs_blen_to_rtbxlen(mp, alen));
1574 out_unreserve_quota:
1575 	if (XFS_IS_QUOTA_ON(mp))
1576 		xfs_quota_unreserve_blkres(ip, alen);
1577 out:
1578 	if (error == -ENOSPC || error == -EDQUOT) {
1579 		trace_xfs_delalloc_enospc(ip, off, len);
1580 
1581 		if (prealloc || use_cowextszhint) {
1582 			/* retry without any preallocation */
1583 			use_cowextszhint = false;
1584 			prealloc = 0;
1585 			goto retry;
1586 		}
1587 	}
1588 	return error;
1589 }
1590 
1591 static int
xfs_zoned_buffered_write_iomap_begin(struct inode * inode,loff_t offset,loff_t count,unsigned flags,struct iomap * iomap,struct iomap * srcmap)1592 xfs_zoned_buffered_write_iomap_begin(
1593 	struct inode		*inode,
1594 	loff_t			offset,
1595 	loff_t			count,
1596 	unsigned		flags,
1597 	struct iomap		*iomap,
1598 	struct iomap		*srcmap)
1599 {
1600 	struct iomap_iter	*iter =
1601 		container_of(iomap, struct iomap_iter, iomap);
1602 	struct address_space	*mapping = inode->i_mapping;
1603 	struct xfs_zone_alloc_ctx *ac = iter->private;
1604 	struct xfs_inode	*ip = XFS_I(inode);
1605 	struct xfs_mount	*mp = ip->i_mount;
1606 	xfs_fileoff_t		offset_fsb = XFS_B_TO_FSBT(mp, offset);
1607 	xfs_fileoff_t		end_fsb = xfs_iomap_end_fsb(mp, offset, count);
1608 	u16			iomap_flags = IOMAP_F_SHARED;
1609 	unsigned int		lockmode = XFS_ILOCK_EXCL;
1610 	xfs_filblks_t		count_fsb;
1611 	xfs_extlen_t		indlen;
1612 	struct xfs_bmbt_irec	got;
1613 	struct xfs_iext_cursor	icur;
1614 	int			error = 0;
1615 
1616 	ASSERT(!xfs_get_extsz_hint(ip));
1617 	ASSERT(!(flags & IOMAP_UNSHARE));
1618 	ASSERT(ac);
1619 
1620 	if (xfs_is_shutdown(mp))
1621 		return -EIO;
1622 
1623 	error = xfs_qm_dqattach(ip);
1624 	if (error)
1625 		return error;
1626 
1627 restart:
1628 	error = xfs_ilock_for_iomap(ip, flags, &lockmode);
1629 	if (error)
1630 		return error;
1631 
1632 	if (XFS_IS_CORRUPT(mp, !xfs_ifork_has_extents(&ip->i_df)) ||
1633 	    XFS_TEST_ERROR(mp, XFS_ERRTAG_BMAPIFORMAT)) {
1634 		xfs_bmap_mark_sick(ip, XFS_DATA_FORK);
1635 		error = -EFSCORRUPTED;
1636 		goto out_unlock;
1637 	}
1638 
1639 	XFS_STATS_INC(mp, xs_blk_mapw);
1640 
1641 	error = xfs_iread_extents(NULL, ip, XFS_DATA_FORK);
1642 	if (error)
1643 		goto out_unlock;
1644 
1645 	/*
1646 	 * For zeroing operations check if there is any data to zero first.
1647 	 *
1648 	 * For regular writes we always need to allocate new blocks, but need to
1649 	 * provide the source mapping when the range is unaligned to support
1650 	 * read-modify-write of the whole block in the page cache.
1651 	 *
1652 	 * In either case we need to limit the reported range to the boundaries
1653 	 * of the source map in the data fork.
1654 	 */
1655 	if (!IS_ALIGNED(offset, mp->m_sb.sb_blocksize) ||
1656 	    !IS_ALIGNED(offset + count, mp->m_sb.sb_blocksize) ||
1657 	    (flags & IOMAP_ZERO)) {
1658 		struct xfs_bmbt_irec	smap;
1659 		struct xfs_iext_cursor	scur;
1660 
1661 		if (!xfs_iext_lookup_extent(ip, &ip->i_df, offset_fsb, &scur,
1662 				&smap))
1663 			smap.br_startoff = end_fsb; /* fake hole until EOF */
1664 		if (smap.br_startoff > offset_fsb) {
1665 			end_fsb = min(end_fsb, smap.br_startoff);
1666 		} else {
1667 			end_fsb = min(end_fsb,
1668 				smap.br_startoff + smap.br_blockcount);
1669 			xfs_trim_extent(&smap, offset_fsb,
1670 					end_fsb - offset_fsb);
1671 			error = xfs_bmbt_to_iomap(ip, srcmap, &smap, flags, 0,
1672 					xfs_iomap_inode_sequence(ip, 0));
1673 			if (error)
1674 				goto out_unlock;
1675 		}
1676 	}
1677 
1678 	if (!ip->i_cowfp)
1679 		xfs_ifork_init_cow(ip);
1680 
1681 	if (!xfs_iext_lookup_extent(ip, ip->i_cowfp, offset_fsb, &icur, &got))
1682 		got.br_startoff = end_fsb;
1683 	if (got.br_startoff <= offset_fsb) {
1684 		trace_xfs_reflink_cow_found(ip, &got);
1685 		goto done;
1686 	}
1687 
1688 	/*
1689 	 * Cap the maximum length to keep the chunks of work done here somewhat
1690 	 * symmetric with the work writeback does.
1691 	 */
1692 	end_fsb = min(end_fsb, got.br_startoff);
1693 	count_fsb = min3(end_fsb - offset_fsb, XFS_MAX_BMBT_EXTLEN,
1694 			 XFS_B_TO_FSB(mp, 1024 * PAGE_SIZE));
1695 
1696 	/*
1697 	 * When zeroing, don't allocate blocks for holes as they are already
1698 	 * zeroes, but we need to ensure that no extents exist in both the data
1699 	 * and COW fork to ensure this really is a hole.
1700 	 *
1701 	 * A window exists where we might observe a hole in both forks with
1702 	 * valid data in cache. Writeback removes the COW fork blocks on
1703 	 * submission but doesn't remap into the data fork until completion. If
1704 	 * the data fork was previously a hole, we'll fail to zero. Until we
1705 	 * find a way to avoid this transient state, check for dirty pagecache
1706 	 * and flush to wait on blocks to land in the data fork.
1707 	 */
1708 	if ((flags & IOMAP_ZERO) && srcmap->type == IOMAP_HOLE) {
1709 		if (filemap_range_needs_writeback(mapping, offset,
1710 				offset + count - 1)) {
1711 			xfs_iunlock(ip, lockmode);
1712 			error = filemap_write_and_wait_range(mapping, offset,
1713 					offset + count - 1);
1714 			if (error)
1715 				return error;
1716 			goto restart;
1717 		}
1718 
1719 		xfs_hole_to_iomap(ip, iomap, offset_fsb, end_fsb);
1720 		goto out_unlock;
1721 	}
1722 
1723 	/*
1724 	 * The block reservation is supposed to cover all blocks that the
1725 	 * operation could possible write, but there is a nasty corner case
1726 	 * where blocks could be stolen from underneath us:
1727 	 *
1728 	 *  1) while this thread iterates over a larger buffered write,
1729 	 *  2) another thread is causing a write fault that calls into
1730 	 *     ->page_mkwrite in range this thread writes to, using up the
1731 	 *     delalloc reservation created by a previous call to this function.
1732 	 *  3) another thread does direct I/O on the range that the write fault
1733 	 *     happened on, which causes writeback of the dirty data.
1734 	 *  4) this then set the stale flag, which cuts the current iomap
1735 	 *     iteration short, causing the new call to ->iomap_begin that gets
1736 	 *     us here again, but now without a sufficient reservation.
1737 	 *
1738 	 * This is a very unusual I/O pattern, and nothing but generic/095 is
1739 	 * known to hit it. There's not really much we can do here, so turn this
1740 	 * into a short write.
1741 	 */
1742 	if (count_fsb > ac->reserved_blocks) {
1743 		xfs_warn_ratelimited(mp,
1744 "Short write on ino 0x%llx comm %.20s due to three-way race with write fault and direct I/O",
1745 			I_INO(ip), current->comm);
1746 		count_fsb = ac->reserved_blocks;
1747 		if (!count_fsb) {
1748 			error = -EIO;
1749 			goto out_unlock;
1750 		}
1751 	}
1752 
1753 	error = xfs_quota_reserve_blkres(ip, count_fsb);
1754 	if (error)
1755 		goto out_unlock;
1756 
1757 	indlen = xfs_bmap_worst_indlen(ip, count_fsb);
1758 	error = xfs_dec_fdblocks(mp, indlen, false);
1759 	if (error)
1760 		goto out_unlock;
1761 	ip->i_delayed_blks += count_fsb;
1762 	xfs_mod_delalloc(ip, count_fsb, indlen);
1763 
1764 	got.br_startoff = offset_fsb;
1765 	got.br_startblock = nullstartblock(indlen);
1766 	got.br_blockcount = count_fsb;
1767 	got.br_state = XFS_EXT_NORM;
1768 	xfs_bmap_add_extent_hole_delay(ip, XFS_COW_FORK, &icur, &got);
1769 	ac->reserved_blocks -= count_fsb;
1770 	iomap_flags |= IOMAP_F_NEW;
1771 
1772 	trace_xfs_iomap_alloc(ip, offset, XFS_FSB_TO_B(mp, count_fsb),
1773 			XFS_COW_FORK, &got);
1774 done:
1775 	error = xfs_bmbt_to_iomap(ip, iomap, &got, flags, iomap_flags,
1776 			xfs_iomap_inode_sequence(ip, IOMAP_F_SHARED));
1777 out_unlock:
1778 	xfs_iunlock(ip, lockmode);
1779 	return error;
1780 }
1781 
1782 static int
xfs_buffered_write_iomap_begin(struct inode * inode,loff_t offset,loff_t count,unsigned flags,struct iomap * iomap,struct iomap * srcmap)1783 xfs_buffered_write_iomap_begin(
1784 	struct inode		*inode,
1785 	loff_t			offset,
1786 	loff_t			count,
1787 	unsigned		flags,
1788 	struct iomap		*iomap,
1789 	struct iomap		*srcmap)
1790 {
1791 	struct iomap_iter	*iter = container_of(iomap, struct iomap_iter,
1792 						     iomap);
1793 	struct xfs_inode	*ip = XFS_I(inode);
1794 	struct xfs_mount	*mp = ip->i_mount;
1795 	xfs_fileoff_t		offset_fsb = XFS_B_TO_FSBT(mp, offset);
1796 	xfs_fileoff_t		end_fsb = xfs_iomap_end_fsb(mp, offset, count);
1797 	xfs_fileoff_t		cow_fsb = NULLFILEOFF;
1798 	xfs_fileoff_t		eof_fsb = XFS_B_TO_FSB(mp, XFS_ISIZE(ip));
1799 	struct xfs_bmbt_irec	imap, cmap;
1800 	struct xfs_iext_cursor	icur, ccur;
1801 	xfs_fsblock_t		prealloc_blocks = 0;
1802 	bool			eof = false, cow_eof = false, shared = false;
1803 	int			allocfork = XFS_DATA_FORK;
1804 	int			error = 0;
1805 	unsigned int		lockmode = XFS_ILOCK_EXCL;
1806 	unsigned int		iomap_flags = 0;
1807 	u64			seq;
1808 
1809 	if (xfs_is_shutdown(mp))
1810 		return -EIO;
1811 
1812 	if (xfs_is_zoned_inode(ip))
1813 		return xfs_zoned_buffered_write_iomap_begin(inode, offset,
1814 				count, flags, iomap, srcmap);
1815 
1816 	/* we can't use delayed allocations when using extent size hints */
1817 	if (xfs_get_extsz_hint(ip))
1818 		return xfs_direct_write_iomap_begin(inode, offset, count,
1819 				flags, iomap, srcmap);
1820 
1821 	error = xfs_qm_dqattach(ip);
1822 	if (error)
1823 		return error;
1824 
1825 	error = xfs_ilock_for_iomap(ip, flags, &lockmode);
1826 	if (error)
1827 		return error;
1828 
1829 	if (XFS_IS_CORRUPT(mp, !xfs_ifork_has_extents(&ip->i_df)) ||
1830 	    XFS_TEST_ERROR(mp, XFS_ERRTAG_BMAPIFORMAT)) {
1831 		xfs_bmap_mark_sick(ip, XFS_DATA_FORK);
1832 		error = -EFSCORRUPTED;
1833 		goto out_unlock;
1834 	}
1835 
1836 	XFS_STATS_INC(mp, xs_blk_mapw);
1837 
1838 	error = xfs_iread_extents(NULL, ip, XFS_DATA_FORK);
1839 	if (error)
1840 		goto out_unlock;
1841 
1842 	/*
1843 	 * Search the data fork first to look up our source mapping. We always
1844 	 * need the data fork map, as we have to return it to the iomap code so
1845 	 * that the higher level write code can read data in to perform
1846 	 * read-modify-write cycles for unaligned writes.
1847 	 *
1848 	 * Then search the COW fork extent list even if we did not find a data
1849 	 * fork extent. This serves two purposes: first this implements the
1850 	 * speculative preallocation using cowextsize, so that we also unshare
1851 	 * block adjacent to shared blocks instead of just the shared blocks
1852 	 * themselves. Second the lookup in the extent list is generally faster
1853 	 * than going out to the shared extent tree.
1854 	 */
1855 	eof = !xfs_iext_lookup_extent(ip, &ip->i_df, offset_fsb, &icur, &imap);
1856 	if (eof)
1857 		imap.br_startoff = end_fsb; /* fake hole until the end */
1858 	if (xfs_is_cow_inode(ip)) {
1859 		if (!ip->i_cowfp) {
1860 			ASSERT(!xfs_is_reflink_inode(ip));
1861 			xfs_ifork_init_cow(ip);
1862 		}
1863 		cow_eof = !xfs_iext_lookup_extent(ip, ip->i_cowfp, offset_fsb,
1864 				&ccur, &cmap);
1865 		if (!cow_eof)
1866 			cow_fsb = cmap.br_startoff;
1867 	}
1868 
1869 	/* We never need to allocate blocks for unsharing a hole. */
1870 	if ((flags & IOMAP_UNSHARE) && imap.br_startoff > offset_fsb) {
1871 		xfs_hole_to_iomap(ip, iomap, offset_fsb, imap.br_startoff);
1872 		goto out_unlock;
1873 	}
1874 
1875 	/*
1876 	 * We may need to zero over a hole in the data fork if it's fronted by
1877 	 * COW blocks and dirty pagecache. Scan such file ranges for dirty
1878 	 * cache and fill the iomap batch with folios that need zeroing.
1879 	 */
1880 	if ((flags & IOMAP_ZERO) && imap.br_startoff > offset_fsb) {
1881 		loff_t		start, end;
1882 		unsigned int	fbatch_count;
1883 
1884 		imap.br_blockcount = imap.br_startoff - offset_fsb;
1885 		imap.br_startoff = offset_fsb;
1886 		imap.br_startblock = HOLESTARTBLOCK;
1887 		imap.br_state = XFS_EXT_NORM;
1888 
1889 		if (cow_fsb == NULLFILEOFF)
1890 			goto found_imap;
1891 		if (cow_fsb > offset_fsb) {
1892 			xfs_trim_extent(&imap, offset_fsb,
1893 					cow_fsb - offset_fsb);
1894 			goto found_imap;
1895 		}
1896 
1897 		/* no zeroing beyond eof, so split at the boundary */
1898 		if (offset_fsb >= eof_fsb)
1899 			goto found_imap;
1900 		if (offset_fsb < eof_fsb && end_fsb > eof_fsb)
1901 			xfs_trim_extent(&imap, offset_fsb,
1902 					eof_fsb - offset_fsb);
1903 
1904 		/* COW fork blocks overlap the hole */
1905 		xfs_trim_extent(&imap, offset_fsb,
1906 			    cmap.br_startoff + cmap.br_blockcount - offset_fsb);
1907 		start = XFS_FSB_TO_B(mp, imap.br_startoff);
1908 		end = XFS_FSB_TO_B(mp, imap.br_startoff + imap.br_blockcount);
1909 		fbatch_count = iomap_fill_dirty_folios(iter, &start, end,
1910 						       &iomap_flags);
1911 		xfs_trim_extent(&imap, offset_fsb,
1912 				XFS_B_TO_FSB(mp, start) - offset_fsb);
1913 
1914 		/*
1915 		 * Report the COW mapping if we have folios to zero. Otherwise
1916 		 * ignore the COW blocks as preallocation and report a hole.
1917 		 */
1918 		if (fbatch_count) {
1919 			xfs_trim_extent(&cmap, imap.br_startoff,
1920 					imap.br_blockcount);
1921 			imap.br_startoff = end_fsb;	/* fake hole */
1922 			goto found_cow;
1923 		}
1924 		goto found_imap;
1925 	}
1926 
1927 	/*
1928 	 * For zeroing, trim extents that extend beyond the EOF block. If a
1929 	 * delalloc extent starts beyond the EOF block, convert it to an
1930 	 * unwritten extent.
1931 	 */
1932 	if (flags & IOMAP_ZERO) {
1933 		if (isnullstartblock(imap.br_startblock) &&
1934 		    offset_fsb >= eof_fsb)
1935 			goto convert_delay;
1936 		if (offset_fsb < eof_fsb && end_fsb > eof_fsb)
1937 			end_fsb = eof_fsb;
1938 
1939 		/*
1940 		 * Look up dirty folios for unwritten mappings within EOF.
1941 		 * Providing this bypasses the flush iomap uses to trigger
1942 		 * extent conversion when unwritten mappings have dirty
1943 		 * pagecache in need of zeroing.
1944 		 *
1945 		 * Trim the mapping to the end pos of the lookup, which in turn
1946 		 * was trimmed to the end of the batch if it became full before
1947 		 * the end of the mapping.
1948 		 */
1949 		if (imap.br_state == XFS_EXT_UNWRITTEN &&
1950 		    offset_fsb < eof_fsb) {
1951 			loff_t foffset = offset, fend;
1952 
1953 			fend = offset +
1954 			       min(count, XFS_FSB_TO_B(mp, imap.br_blockcount));
1955 			iomap_fill_dirty_folios(iter, &foffset, fend,
1956 						&iomap_flags);
1957 			end_fsb = min_t(xfs_fileoff_t, end_fsb,
1958 					XFS_B_TO_FSB(mp, foffset));
1959 		}
1960 
1961 		xfs_trim_extent(&imap, offset_fsb, end_fsb - offset_fsb);
1962 	}
1963 
1964 	/*
1965 	 * Now that we've handled any operation specific special cases, at this
1966 	 * point we can report a COW mapping if found.
1967 	 */
1968 	if (xfs_is_cow_inode(ip) &&
1969 	    !cow_eof && cmap.br_startoff <= offset_fsb) {
1970 		trace_xfs_reflink_cow_found(ip, &cmap);
1971 		goto found_cow;
1972 	}
1973 
1974 	if (imap.br_startoff <= offset_fsb) {
1975 		/*
1976 		 * For reflink files we may need a delalloc reservation when
1977 		 * overwriting shared extents.   This includes zeroing of
1978 		 * existing extents that contain data.
1979 		 */
1980 		if (!xfs_is_cow_inode(ip) ||
1981 		    ((flags & IOMAP_ZERO) && imap.br_state != XFS_EXT_NORM)) {
1982 			trace_xfs_iomap_found(ip, offset, count, XFS_DATA_FORK,
1983 					&imap);
1984 			goto found_imap;
1985 		}
1986 
1987 		xfs_trim_extent(&imap, offset_fsb, end_fsb - offset_fsb);
1988 
1989 		/* Trim the mapping to the nearest shared extent boundary. */
1990 		error = xfs_bmap_trim_cow(ip, &imap, &shared);
1991 		if (error)
1992 			goto out_unlock;
1993 
1994 		/* Not shared?  Just report the (potentially capped) extent. */
1995 		if (!shared) {
1996 			trace_xfs_iomap_found(ip, offset, count, XFS_DATA_FORK,
1997 					&imap);
1998 			goto found_imap;
1999 		}
2000 
2001 		/*
2002 		 * Fork all the shared blocks from our write offset until the
2003 		 * end of the extent.
2004 		 */
2005 		allocfork = XFS_COW_FORK;
2006 		end_fsb = imap.br_startoff + imap.br_blockcount;
2007 	} else {
2008 		/*
2009 		 * We cap the maximum length we map here to MAX_WRITEBACK_PAGES
2010 		 * pages to keep the chunks of work done where somewhat
2011 		 * symmetric with the work writeback does.  This is a completely
2012 		 * arbitrary number pulled out of thin air.
2013 		 *
2014 		 * Note that the values needs to be less than 32-bits wide until
2015 		 * the lower level functions are updated.
2016 		 */
2017 		count = min_t(loff_t, count, 1024 * PAGE_SIZE);
2018 		end_fsb = xfs_iomap_end_fsb(mp, offset, count);
2019 
2020 		if (xfs_is_always_cow_inode(ip))
2021 			allocfork = XFS_COW_FORK;
2022 	}
2023 
2024 	if (eof && offset + count > XFS_ISIZE(ip)) {
2025 		/*
2026 		 * Determine the initial size of the preallocation.
2027 		 * We clean up any extra preallocation when the file is closed.
2028 		 */
2029 		if (xfs_has_allocsize(mp))
2030 			prealloc_blocks = mp->m_allocsize_blocks;
2031 		else if (allocfork == XFS_DATA_FORK)
2032 			prealloc_blocks = xfs_iomap_prealloc_size(ip, allocfork,
2033 						offset, count, &icur);
2034 		else
2035 			prealloc_blocks = xfs_iomap_prealloc_size(ip, allocfork,
2036 						offset, count, &ccur);
2037 		if (prealloc_blocks) {
2038 			xfs_extlen_t	align;
2039 			xfs_off_t	end_offset;
2040 			xfs_fileoff_t	p_end_fsb;
2041 
2042 			end_offset = XFS_ALLOC_ALIGN(mp, offset + count - 1);
2043 			p_end_fsb = XFS_B_TO_FSBT(mp, end_offset) +
2044 					prealloc_blocks;
2045 
2046 			align = xfs_eof_alignment(ip);
2047 			if (align)
2048 				p_end_fsb = roundup_64(p_end_fsb, align);
2049 
2050 			p_end_fsb = min(p_end_fsb,
2051 				XFS_B_TO_FSB(mp, mp->m_super->s_maxbytes));
2052 			ASSERT(p_end_fsb > offset_fsb);
2053 			prealloc_blocks = p_end_fsb - end_fsb;
2054 		}
2055 	}
2056 
2057 	/*
2058 	 * Flag newly allocated delalloc blocks with IOMAP_F_NEW so we punch
2059 	 * them out if the write happens to fail.
2060 	 */
2061 	iomap_flags |= IOMAP_F_NEW;
2062 	if (allocfork == XFS_COW_FORK) {
2063 		error = xfs_bmapi_reserve_delalloc(ip, allocfork, offset_fsb,
2064 				end_fsb - offset_fsb, prealloc_blocks, &cmap,
2065 				&ccur, cow_eof);
2066 		if (error)
2067 			goto out_unlock;
2068 
2069 		trace_xfs_iomap_alloc(ip, offset, count, allocfork, &cmap);
2070 		goto found_cow;
2071 	}
2072 
2073 	error = xfs_bmapi_reserve_delalloc(ip, allocfork, offset_fsb,
2074 			end_fsb - offset_fsb, prealloc_blocks, &imap, &icur,
2075 			eof);
2076 	if (error)
2077 		goto out_unlock;
2078 
2079 	trace_xfs_iomap_alloc(ip, offset, count, allocfork, &imap);
2080 found_imap:
2081 	seq = xfs_iomap_inode_sequence(ip, iomap_flags);
2082 	xfs_iunlock(ip, lockmode);
2083 	return xfs_bmbt_to_iomap(ip, iomap, &imap, flags, iomap_flags, seq);
2084 
2085 convert_delay:
2086 	xfs_iunlock(ip, lockmode);
2087 	truncate_pagecache(inode, offset);
2088 	error = xfs_bmapi_convert_delalloc(ip, XFS_DATA_FORK, offset,
2089 					   iomap, NULL);
2090 	if (error)
2091 		return error;
2092 
2093 	trace_xfs_iomap_alloc(ip, offset, count, XFS_DATA_FORK, &imap);
2094 	return 0;
2095 
2096 found_cow:
2097 	if (imap.br_startoff <= offset_fsb) {
2098 		error = xfs_bmbt_to_iomap(ip, srcmap, &imap, flags, 0,
2099 				xfs_iomap_inode_sequence(ip, 0));
2100 		if (error)
2101 			goto out_unlock;
2102 	} else {
2103 		xfs_trim_extent(&cmap, offset_fsb,
2104 				imap.br_startoff - offset_fsb);
2105 	}
2106 
2107 	iomap_flags |= IOMAP_F_SHARED;
2108 	seq = xfs_iomap_inode_sequence(ip, iomap_flags);
2109 	xfs_iunlock(ip, lockmode);
2110 	return xfs_bmbt_to_iomap(ip, iomap, &cmap, flags, iomap_flags, seq);
2111 
2112 out_unlock:
2113 	xfs_iunlock(ip, lockmode);
2114 	return error;
2115 }
2116 
2117 static void
xfs_buffered_write_delalloc_punch(struct inode * inode,loff_t offset,loff_t length,struct iomap * iomap)2118 xfs_buffered_write_delalloc_punch(
2119 	struct inode		*inode,
2120 	loff_t			offset,
2121 	loff_t			length,
2122 	struct iomap		*iomap)
2123 {
2124 	struct iomap_iter	*iter =
2125 		container_of(iomap, struct iomap_iter, iomap);
2126 
2127 	xfs_bmap_punch_delalloc_range(XFS_I(inode),
2128 			(iomap->flags & IOMAP_F_SHARED) ?
2129 				XFS_COW_FORK : XFS_DATA_FORK,
2130 			offset, offset + length, iter->private);
2131 }
2132 
2133 static int
xfs_buffered_write_iomap_end(struct inode * inode,loff_t offset,loff_t length,ssize_t written,unsigned flags,struct iomap * iomap)2134 xfs_buffered_write_iomap_end(
2135 	struct inode		*inode,
2136 	loff_t			offset,
2137 	loff_t			length,
2138 	ssize_t			written,
2139 	unsigned		flags,
2140 	struct iomap		*iomap)
2141 {
2142 	loff_t			start_byte, end_byte;
2143 
2144 	/* If we didn't reserve the blocks, we're not allowed to punch them. */
2145 	if (iomap->type != IOMAP_DELALLOC || !(iomap->flags & IOMAP_F_NEW))
2146 		return 0;
2147 
2148 	/*
2149 	 * iomap_page_mkwrite() will never fail in a way that requires delalloc
2150 	 * extents that it allocated to be revoked.  Hence never try to release
2151 	 * them here.
2152 	 */
2153 	if (flags & IOMAP_FAULT)
2154 		return 0;
2155 
2156 	/* Nothing to do if we've written the entire delalloc extent */
2157 	start_byte = iomap_last_written_block(inode, offset, written);
2158 	end_byte = round_up(offset + length, i_blocksize(inode));
2159 	if (start_byte >= end_byte)
2160 		return 0;
2161 
2162 	/* For zeroing operations the callers already hold invalidate_lock. */
2163 	if (flags & (IOMAP_UNSHARE | IOMAP_ZERO)) {
2164 		rwsem_assert_held_write(&inode->i_mapping->invalidate_lock);
2165 		iomap_write_delalloc_release(inode, start_byte, end_byte, flags,
2166 				iomap, xfs_buffered_write_delalloc_punch);
2167 	} else {
2168 		filemap_invalidate_lock(inode->i_mapping);
2169 		iomap_write_delalloc_release(inode, start_byte, end_byte, flags,
2170 				iomap, xfs_buffered_write_delalloc_punch);
2171 		filemap_invalidate_unlock(inode->i_mapping);
2172 	}
2173 
2174 	return 0;
2175 }
2176 
2177 static DEFINE_IOMAP_ITER_NEXT_END(xfs_buffered_write_iomap_next,
2178 		xfs_buffered_write_iomap_begin, xfs_buffered_write_iomap_end);
2179 
2180 const struct iomap_ops xfs_buffered_write_iomap_ops = {
2181 	.iomap_next		= xfs_buffered_write_iomap_next,
2182 };
2183 
2184 int
xfs_read_iomap_begin(struct inode * inode,loff_t offset,loff_t length,unsigned flags,struct iomap * iomap,struct iomap * srcmap)2185 xfs_read_iomap_begin(
2186 	struct inode		*inode,
2187 	loff_t			offset,
2188 	loff_t			length,
2189 	unsigned		flags,
2190 	struct iomap		*iomap,
2191 	struct iomap		*srcmap)
2192 {
2193 	struct xfs_inode	*ip = XFS_I(inode);
2194 	struct xfs_mount	*mp = ip->i_mount;
2195 	struct xfs_bmbt_irec	imap;
2196 	xfs_fileoff_t		offset_fsb = XFS_B_TO_FSBT(mp, offset);
2197 	xfs_fileoff_t		end_fsb = xfs_iomap_end_fsb(mp, offset, length);
2198 	int			nimaps = 1, error = 0;
2199 	bool			shared = false;
2200 	unsigned int		lockmode = XFS_ILOCK_SHARED;
2201 	u64			seq;
2202 
2203 	ASSERT(!(flags & (IOMAP_WRITE | IOMAP_ZERO)));
2204 
2205 	if (xfs_is_shutdown(mp))
2206 		return -EIO;
2207 
2208 	error = xfs_ilock_for_iomap(ip, flags, &lockmode);
2209 	if (error)
2210 		return error;
2211 	error = xfs_bmapi_read(ip, offset_fsb, end_fsb - offset_fsb, &imap,
2212 			       &nimaps, 0);
2213 	if (!error && ((flags & IOMAP_REPORT) || IS_DAX(inode)))
2214 		error = xfs_reflink_trim_around_shared(ip, &imap, &shared);
2215 	seq = xfs_iomap_inode_sequence(ip, shared ? IOMAP_F_SHARED : 0);
2216 	xfs_iunlock(ip, lockmode);
2217 
2218 	if (error)
2219 		return error;
2220 	trace_xfs_iomap_found(ip, offset, length, XFS_DATA_FORK, &imap);
2221 	return xfs_bmbt_to_iomap(ip, iomap, &imap, flags,
2222 				 shared ? IOMAP_F_SHARED : 0, seq);
2223 }
2224 
2225 static DEFINE_IOMAP_ITER_NEXT(xfs_read_iomap_next, xfs_read_iomap_begin);
2226 
2227 const struct iomap_ops xfs_read_iomap_ops = {
2228 	.iomap_next		= xfs_read_iomap_next,
2229 };
2230 
2231 static int
xfs_seek_iomap_begin(struct inode * inode,loff_t offset,loff_t length,unsigned flags,struct iomap * iomap,struct iomap * srcmap)2232 xfs_seek_iomap_begin(
2233 	struct inode		*inode,
2234 	loff_t			offset,
2235 	loff_t			length,
2236 	unsigned		flags,
2237 	struct iomap		*iomap,
2238 	struct iomap		*srcmap)
2239 {
2240 	struct xfs_inode	*ip = XFS_I(inode);
2241 	struct xfs_mount	*mp = ip->i_mount;
2242 	xfs_fileoff_t		offset_fsb = XFS_B_TO_FSBT(mp, offset);
2243 	xfs_fileoff_t		end_fsb = XFS_B_TO_FSB(mp, offset + length);
2244 	xfs_fileoff_t		cow_fsb = NULLFILEOFF, data_fsb = NULLFILEOFF;
2245 	struct xfs_iext_cursor	icur;
2246 	struct xfs_bmbt_irec	imap, cmap;
2247 	int			error = 0;
2248 	unsigned		lockmode;
2249 	u64			seq;
2250 
2251 	if (xfs_is_shutdown(mp))
2252 		return -EIO;
2253 
2254 	lockmode = xfs_ilock_data_map_shared(ip);
2255 	error = xfs_iread_extents(NULL, ip, XFS_DATA_FORK);
2256 	if (error)
2257 		goto out_unlock;
2258 
2259 	if (xfs_iext_lookup_extent(ip, &ip->i_df, offset_fsb, &icur, &imap)) {
2260 		/*
2261 		 * If we found a data extent we are done.
2262 		 */
2263 		if (imap.br_startoff <= offset_fsb)
2264 			goto done;
2265 		data_fsb = imap.br_startoff;
2266 	} else {
2267 		/*
2268 		 * Fake a hole until the end of the file.
2269 		 */
2270 		data_fsb = xfs_iomap_end_fsb(mp, offset, length);
2271 	}
2272 
2273 	/*
2274 	 * If a COW fork extent covers the hole, report it - capped to the next
2275 	 * data fork extent:
2276 	 */
2277 	if (xfs_inode_has_cow_data(ip) &&
2278 	    xfs_iext_lookup_extent(ip, ip->i_cowfp, offset_fsb, &icur, &cmap))
2279 		cow_fsb = cmap.br_startoff;
2280 	if (cow_fsb != NULLFILEOFF && cow_fsb <= offset_fsb) {
2281 		if (data_fsb < cow_fsb + cmap.br_blockcount)
2282 			end_fsb = min(end_fsb, data_fsb);
2283 		xfs_trim_extent(&cmap, offset_fsb, end_fsb - offset_fsb);
2284 		seq = xfs_iomap_inode_sequence(ip, IOMAP_F_SHARED);
2285 		error = xfs_bmbt_to_iomap(ip, iomap, &cmap, flags,
2286 				IOMAP_F_SHARED, seq);
2287 		/*
2288 		 * This is a COW extent, so we must probe the page cache
2289 		 * because there could be dirty page cache being backed
2290 		 * by this extent.
2291 		 */
2292 		iomap->type = IOMAP_UNWRITTEN;
2293 		goto out_unlock;
2294 	}
2295 
2296 	/*
2297 	 * Else report a hole, capped to the next found data or COW extent.
2298 	 */
2299 	if (cow_fsb != NULLFILEOFF && cow_fsb < data_fsb)
2300 		imap.br_blockcount = cow_fsb - offset_fsb;
2301 	else
2302 		imap.br_blockcount = data_fsb - offset_fsb;
2303 	imap.br_startoff = offset_fsb;
2304 	imap.br_startblock = HOLESTARTBLOCK;
2305 	imap.br_state = XFS_EXT_NORM;
2306 done:
2307 	seq = xfs_iomap_inode_sequence(ip, 0);
2308 	xfs_trim_extent(&imap, offset_fsb, end_fsb - offset_fsb);
2309 	error = xfs_bmbt_to_iomap(ip, iomap, &imap, flags, 0, seq);
2310 out_unlock:
2311 	xfs_iunlock(ip, lockmode);
2312 	return error;
2313 }
2314 
2315 static DEFINE_IOMAP_ITER_NEXT(xfs_seek_iomap_next, xfs_seek_iomap_begin);
2316 
2317 const struct iomap_ops xfs_seek_iomap_ops = {
2318 	.iomap_next		= xfs_seek_iomap_next,
2319 };
2320 
2321 static int
xfs_xattr_iomap_begin(struct inode * inode,loff_t offset,loff_t length,unsigned flags,struct iomap * iomap,struct iomap * srcmap)2322 xfs_xattr_iomap_begin(
2323 	struct inode		*inode,
2324 	loff_t			offset,
2325 	loff_t			length,
2326 	unsigned		flags,
2327 	struct iomap		*iomap,
2328 	struct iomap		*srcmap)
2329 {
2330 	struct xfs_inode	*ip = XFS_I(inode);
2331 	struct xfs_mount	*mp = ip->i_mount;
2332 	xfs_fileoff_t		offset_fsb = XFS_B_TO_FSBT(mp, offset);
2333 	xfs_fileoff_t		end_fsb = XFS_B_TO_FSB(mp, offset + length);
2334 	struct xfs_bmbt_irec	imap;
2335 	int			nimaps = 1, error = 0;
2336 	unsigned		lockmode;
2337 	int			seq;
2338 
2339 	if (xfs_is_shutdown(mp))
2340 		return -EIO;
2341 
2342 	lockmode = xfs_ilock_attr_map_shared(ip);
2343 
2344 	/* if there are no attribute fork or extents, return ENOENT */
2345 	if (!xfs_inode_has_attr_fork(ip) || !ip->i_af.if_nextents) {
2346 		error = -ENOENT;
2347 		goto out_unlock;
2348 	}
2349 
2350 	ASSERT(ip->i_af.if_format != XFS_DINODE_FMT_LOCAL);
2351 	error = xfs_bmapi_read(ip, offset_fsb, end_fsb - offset_fsb, &imap,
2352 			       &nimaps, XFS_BMAPI_ATTRFORK);
2353 out_unlock:
2354 
2355 	seq = xfs_iomap_inode_sequence(ip, IOMAP_F_XATTR);
2356 	xfs_iunlock(ip, lockmode);
2357 
2358 	if (error)
2359 		return error;
2360 	ASSERT(nimaps);
2361 	return xfs_bmbt_to_iomap(ip, iomap, &imap, flags, IOMAP_F_XATTR, seq);
2362 }
2363 
2364 static DEFINE_IOMAP_ITER_NEXT(xfs_xattr_iomap_next, xfs_xattr_iomap_begin);
2365 
2366 const struct iomap_ops xfs_xattr_iomap_ops = {
2367 	.iomap_next		= xfs_xattr_iomap_next,
2368 };
2369 
2370 int
xfs_zero_range(struct xfs_inode * ip,loff_t pos,loff_t len,struct xfs_zone_alloc_ctx * ac,bool * did_zero)2371 xfs_zero_range(
2372 	struct xfs_inode	*ip,
2373 	loff_t			pos,
2374 	loff_t			len,
2375 	struct xfs_zone_alloc_ctx *ac,
2376 	bool			*did_zero)
2377 {
2378 	struct inode		*inode = VFS_I(ip);
2379 
2380 	xfs_assert_ilocked(ip, XFS_IOLOCK_EXCL | XFS_MMAPLOCK_EXCL);
2381 
2382 	if (IS_DAX(inode))
2383 		return dax_zero_range(inode, pos, len, did_zero,
2384 				      &xfs_dax_write_iomap_ops);
2385 	return iomap_zero_range(inode, pos, len, did_zero,
2386 			&xfs_buffered_write_iomap_ops, &xfs_iomap_write_ops,
2387 			ac);
2388 }
2389 
2390 int
xfs_truncate_page(struct xfs_inode * ip,loff_t pos,struct xfs_zone_alloc_ctx * ac,bool * did_zero)2391 xfs_truncate_page(
2392 	struct xfs_inode	*ip,
2393 	loff_t			pos,
2394 	struct xfs_zone_alloc_ctx *ac,
2395 	bool			*did_zero)
2396 {
2397 	struct inode		*inode = VFS_I(ip);
2398 
2399 	if (IS_DAX(inode))
2400 		return dax_truncate_page(inode, pos, did_zero,
2401 					&xfs_dax_write_iomap_ops);
2402 	return iomap_truncate_page(inode, pos, did_zero,
2403 			&xfs_buffered_write_iomap_ops, &xfs_iomap_write_ops,
2404 			ac);
2405 }
2406