xref: /linux/fs/ext4/file.c (revision 4dce97c6c265544342e716e62fd24bbb232590c5)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  linux/fs/ext4/file.c
4  *
5  * Copyright (C) 1992, 1993, 1994, 1995
6  * Remy Card (card@masi.ibp.fr)
7  * Laboratoire MASI - Institut Blaise Pascal
8  * Universite Pierre et Marie Curie (Paris VI)
9  *
10  *  from
11  *
12  *  linux/fs/minix/file.c
13  *
14  *  Copyright (C) 1991, 1992  Linus Torvalds
15  *
16  *  ext4 fs regular file handling primitives
17  *
18  *  64-bit file support on 64-bit platforms by Jakub Jelinek
19  *	(jj@sunsite.ms.mff.cuni.cz)
20  */
21 
22 #include <linux/time.h>
23 #include <linux/fs.h>
24 #include <linux/iomap.h>
25 #include <linux/mount.h>
26 #include <linux/path.h>
27 #include <linux/dax.h>
28 #include <linux/filelock.h>
29 #include <linux/quotaops.h>
30 #include <linux/uio.h>
31 #include <linux/mman.h>
32 #include <linux/backing-dev.h>
33 #include "ext4.h"
34 #include "ext4_jbd2.h"
35 #include "xattr.h"
36 #include "acl.h"
37 #include "truncate.h"
38 
39 /*
40  * Returns %true if the given DIO request should be attempted with DIO, or
41  * %false if it should fall back to buffered I/O.
42  *
43  * DIO isn't well specified; when it's unsupported (either due to the request
44  * being misaligned, or due to the file not supporting DIO at all), filesystems
45  * either fall back to buffered I/O or return EINVAL.  For files that don't use
46  * any special features like encryption or verity, ext4 has traditionally
47  * returned EINVAL for misaligned DIO.  iomap_dio_rw() uses this convention too.
48  * In this case, we should attempt the DIO, *not* fall back to buffered I/O.
49  *
50  * In contrast, in cases where DIO is unsupported due to ext4 features, ext4
51  * traditionally falls back to buffered I/O.
52  *
53  * This function implements the traditional ext4 behavior in all these cases.
54  */
55 static bool ext4_should_use_dio(struct kiocb *iocb, struct iov_iter *iter)
56 {
57 	struct inode *inode = file_inode(iocb->ki_filp);
58 	u32 dio_align = ext4_dio_alignment(inode);
59 
60 	if (dio_align == 0)
61 		return false;
62 
63 	if (dio_align == 1)
64 		return true;
65 
66 	return IS_ALIGNED(iocb->ki_pos | iov_iter_alignment(iter), dio_align);
67 }
68 
69 static ssize_t ext4_dio_read_iter(struct kiocb *iocb, struct iov_iter *to)
70 {
71 	ssize_t ret;
72 	struct inode *inode = file_inode(iocb->ki_filp);
73 
74 	if (iocb->ki_flags & IOCB_NOWAIT) {
75 		if (!inode_trylock_shared(inode))
76 			return -EAGAIN;
77 	} else {
78 		inode_lock_shared(inode);
79 	}
80 
81 	if (!ext4_should_use_dio(iocb, to)) {
82 		inode_unlock_shared(inode);
83 		/*
84 		 * Fallback to buffered I/O if the operation being performed on
85 		 * the inode is not supported by direct I/O. The IOCB_DIRECT
86 		 * flag needs to be cleared here in order to ensure that the
87 		 * direct I/O path within generic_file_read_iter() is not
88 		 * taken.
89 		 */
90 		iocb->ki_flags &= ~IOCB_DIRECT;
91 		return generic_file_read_iter(iocb, to);
92 	}
93 
94 	ret = iomap_dio_read_simple(iocb, to, ext4_iomap_begin);
95 	if (ret == -ENOTBLK)
96 		ret = iomap_dio_rw(iocb, to, ext4_iomap_next, NULL, 0, NULL, 0);
97 	inode_unlock_shared(inode);
98 
99 	file_accessed(iocb->ki_filp);
100 	return ret;
101 }
102 
103 #ifdef CONFIG_FS_DAX
104 static ssize_t ext4_dax_read_iter(struct kiocb *iocb, struct iov_iter *to)
105 {
106 	struct inode *inode = file_inode(iocb->ki_filp);
107 	ssize_t ret;
108 
109 	if (iocb->ki_flags & IOCB_NOWAIT) {
110 		if (!inode_trylock_shared(inode))
111 			return -EAGAIN;
112 	} else {
113 		inode_lock_shared(inode);
114 	}
115 	/*
116 	 * Recheck under inode lock - at this point we are sure it cannot
117 	 * change anymore
118 	 */
119 	if (!IS_DAX(inode)) {
120 		inode_unlock_shared(inode);
121 		/* Fallback to buffered IO in case we cannot support DAX */
122 		return generic_file_read_iter(iocb, to);
123 	}
124 	ret = dax_iomap_rw(iocb, to, ext4_iomap_next);
125 	inode_unlock_shared(inode);
126 
127 	file_accessed(iocb->ki_filp);
128 	return ret;
129 }
130 #endif
131 
132 static ssize_t ext4_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
133 {
134 	struct inode *inode = file_inode(iocb->ki_filp);
135 
136 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
137 		return -EIO;
138 
139 	if (!iov_iter_count(to))
140 		return 0; /* skip atime */
141 
142 #ifdef CONFIG_FS_DAX
143 	if (IS_DAX(inode))
144 		return ext4_dax_read_iter(iocb, to);
145 #endif
146 	if (iocb->ki_flags & IOCB_DIRECT)
147 		return ext4_dio_read_iter(iocb, to);
148 
149 	return generic_file_read_iter(iocb, to);
150 }
151 
152 static ssize_t ext4_file_splice_read(struct file *in, loff_t *ppos,
153 				     struct pipe_inode_info *pipe,
154 				     size_t len, unsigned int flags)
155 {
156 	struct inode *inode = file_inode(in);
157 
158 	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
159 		return -EIO;
160 	return filemap_splice_read(in, ppos, pipe, len, flags);
161 }
162 
163 /*
164  * Called when an inode is released. Note that this is different
165  * from ext4_file_open: open gets called at every open, but release
166  * gets called only when /all/ the files are closed.
167  */
168 static int ext4_release_file(struct inode *inode, struct file *filp)
169 {
170 	if (ext4_test_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE)) {
171 		ext4_alloc_da_blocks(inode);
172 		ext4_clear_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
173 	}
174 	/* if we are the last writer on the inode, drop the block reservation */
175 	if ((filp->f_mode & FMODE_WRITE) &&
176 			(atomic_read(&inode->i_writecount) == 1) &&
177 			!EXT4_I(inode)->i_reserved_data_blocks) {
178 		down_write(&EXT4_I(inode)->i_data_sem);
179 		ext4_discard_preallocations(inode);
180 		up_write(&EXT4_I(inode)->i_data_sem);
181 	}
182 	if (is_dx(inode) && filp->private_data)
183 		ext4_htree_free_dir_info(filp->private_data);
184 
185 	return 0;
186 }
187 
188 /*
189  * This tests whether the IO in question is block-aligned or not.
190  * Ext4 utilizes unwritten extents when hole-filling during direct IO, and they
191  * are converted to written only after the IO is complete.  Until they are
192  * mapped, these blocks appear as holes, so dio_zero_block() will assume that
193  * it needs to zero out portions of the start and/or end block.  If 2 AIO
194  * threads are at work on the same unwritten block, they must be synchronized
195  * or one thread will zero the other's data, causing corruption.
196  */
197 static bool
198 ext4_unaligned_io(struct inode *inode, struct iov_iter *from, loff_t pos)
199 {
200 	struct super_block *sb = inode->i_sb;
201 	unsigned long blockmask = sb->s_blocksize - 1;
202 
203 	if ((pos | iov_iter_alignment(from)) & blockmask)
204 		return true;
205 
206 	return false;
207 }
208 
209 static bool
210 ext4_extending_io(struct inode *inode, loff_t offset, size_t len)
211 {
212 	if (offset + len > i_size_read(inode) ||
213 	    offset + len > EXT4_I(inode)->i_disksize)
214 		return true;
215 	return false;
216 }
217 
218 /*
219  * Does an unaligned DIO write require partial block zeroing?
220  *
221  * Partial block zeroing is performed only for the head and tail blocks
222  * when they are partially covered by the write and the underlying extent
223  * is a hole or unwritten. Middle blocks (fully covered by the write)
224  * are written as whole blocks without zeroing.
225  *
226  * When zeroing is required, two concurrent unaligned DIO writes to the
227  * same partial block can race and corrupt each other's data, so the
228  * caller must take the exclusive i_rwsem and drain in-flight DIO. When
229  * zeroing is not required, shared lock is safe -- block allocation and
230  * unwritten conversion for middle blocks are protected by i_data_sem
231  * and inode_dio_begin().
232  */
233 static bool ext4_dio_needs_zeroing(struct inode *inode, loff_t pos, loff_t len)
234 {
235 	struct ext4_map_blocks map;
236 	unsigned int blkbits = inode->i_blkbits;
237 	unsigned long blockmask = inode->i_sb->s_blocksize - 1;
238 	bool head_partial, tail_partial;
239 	ext4_lblk_t head_lblk, tail_lblk;
240 	int err;
241 
242 	if (pos + len > i_size_read(inode))
243 		return true;
244 
245 	head_partial = (pos & blockmask) != 0;
246 	tail_partial = ((pos + len) & blockmask) != 0;
247 	head_lblk = pos >> blkbits;
248 	tail_lblk = (pos + len - 1) >> blkbits;
249 
250 	/* Check the head partial block. */
251 	if (head_partial) {
252 		map.m_lblk = head_lblk;
253 		map.m_len = tail_lblk - head_lblk + 1;
254 		err = ext4_map_blocks(NULL, inode, &map, 0);
255 		if (err <= 0 || !(map.m_flags & EXT4_MAP_MAPPED))
256 			return true;
257 		/* If this mapping already covers the tail block, we're done. */
258 		if (!tail_partial || map.m_lblk + err > tail_lblk)
259 			return false;
260 	}
261 
262 	/* Check the tail partial block. */
263 	if (tail_partial) {
264 		map.m_lblk = tail_lblk;
265 		map.m_len = 1;
266 		err = ext4_map_blocks(NULL, inode, &map, 0);
267 		if (err <= 0 || !(map.m_flags & EXT4_MAP_MAPPED))
268 			return true;
269 	}
270 
271 	return false;
272 }
273 
274 static ssize_t ext4_generic_write_checks(struct kiocb *iocb,
275 					 struct iov_iter *from)
276 {
277 	struct inode *inode = file_inode(iocb->ki_filp);
278 	ssize_t ret;
279 
280 	if (unlikely(IS_IMMUTABLE(inode)))
281 		return -EPERM;
282 
283 	ret = generic_write_checks(iocb, from);
284 	if (ret <= 0)
285 		return ret;
286 
287 	/*
288 	 * If we have encountered a bitmap-format file, the size limit
289 	 * is smaller than s_maxbytes, which is for extent-mapped files.
290 	 */
291 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
292 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
293 
294 		if (iocb->ki_pos >= sbi->s_bitmap_maxbytes)
295 			return -EFBIG;
296 		iov_iter_truncate(from, sbi->s_bitmap_maxbytes - iocb->ki_pos);
297 	}
298 
299 	return iov_iter_count(from);
300 }
301 
302 static ssize_t ext4_write_checks(struct kiocb *iocb, struct iov_iter *from)
303 {
304 	struct inode *inode = file_inode(iocb->ki_filp);
305 	loff_t old_size = i_size_read(inode);
306 	ssize_t ret, count;
307 
308 	count = ext4_generic_write_checks(iocb, from);
309 	if (count <= 0)
310 		return count;
311 
312 	ret = kiocb_modified(iocb);
313 	if (ret)
314 		return ret;
315 
316 	/*
317 	 * If the position is beyond the EOF, it is necessary to zero out the
318 	 * partial block that beyond the existing EOF, as it may contains
319 	 * stale data written through mmap.
320 	 */
321 	if (iocb->ki_pos > old_size && !ext4_verity_in_progress(inode)) {
322 		if (iocb->ki_flags & IOCB_NOWAIT)
323 			return -EAGAIN;
324 
325 		ret = ext4_block_zero_eof(inode, old_size, iocb->ki_pos);
326 		if (ret)
327 			return ret;
328 	}
329 
330 	return count;
331 }
332 
333 static ssize_t ext4_iomap_buffered_write(struct kiocb *iocb,
334 					 struct iov_iter *from)
335 {
336 	struct inode *inode = file_inode(iocb->ki_filp);
337 	iomap_iter_next_fn next;
338 
339 	if (test_opt(inode->i_sb, DELALLOC) && !ext4_nonda_switch(inode->i_sb))
340 		next = ext4_iomap_buffered_da_write_next;
341 	else
342 		next = ext4_iomap_buffered_write_next;
343 
344 	return iomap_file_buffered_write(iocb, from, next,
345 					 &ext4_iomap_write_ops, NULL);
346 }
347 
348 static ssize_t ext4_buffered_write_iter(struct kiocb *iocb,
349 					struct iov_iter *from)
350 {
351 	ssize_t ret;
352 	struct inode *inode = file_inode(iocb->ki_filp);
353 
354 	if (iocb->ki_flags & IOCB_NOWAIT)
355 		return -EOPNOTSUPP;
356 
357 	/*
358 	 * Buffered I/O provides no torn-write protection. The direct I/O path
359 	 * falls back here for inodes that can't do direct I/O at all, so an
360 	 * atomic write must be rejected rather than silently done non-atomically.
361 	 */
362 	if (iocb->ki_flags & IOCB_ATOMIC)
363 		return -EOPNOTSUPP;
364 
365 	inode_lock(inode);
366 
367 	/*
368 	 * Prevent concurrent direct I/O and buffered I/O to the same file
369 	 * range. Wait for in-flight DIO to finish before dirtying pages.
370 	 */
371 	inode_dio_wait(inode);
372 
373 	ret = ext4_write_checks(iocb, from);
374 	if (ret <= 0)
375 		goto out;
376 
377 	if (ext4_inode_buffered_iomap(inode))
378 		ret = ext4_iomap_buffered_write(iocb, from);
379 	else
380 		ret = generic_perform_write(iocb, from);
381 
382 out:
383 	inode_unlock(inode);
384 	if (unlikely(ret <= 0))
385 		return ret;
386 	return generic_write_sync(iocb, ret);
387 }
388 
389 static ssize_t ext4_handle_inode_extension(struct inode *inode, loff_t offset,
390 					   ssize_t written, ssize_t count)
391 {
392 	handle_t *handle;
393 
394 	lockdep_assert_held_write(&inode->i_rwsem);
395 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
396 	if (IS_ERR(handle))
397 		return PTR_ERR(handle);
398 
399 	if (ext4_update_inode_size(inode, offset + written)) {
400 		int ret = ext4_mark_inode_dirty(handle, inode);
401 		if (unlikely(ret)) {
402 			ext4_journal_stop(handle);
403 			return ret;
404 		}
405 	}
406 
407 	if ((written == count) && inode->i_nlink)
408 		ext4_orphan_del(handle, inode);
409 	ext4_journal_stop(handle);
410 
411 	return written;
412 }
413 
414 /*
415  * Clean up the inode after DIO or DAX extending write has completed and the
416  * inode size has been updated using ext4_handle_inode_extension().
417  */
418 static void ext4_inode_extension_cleanup(struct inode *inode, bool need_trunc)
419 {
420 	lockdep_assert_held_write(&inode->i_rwsem);
421 	if (need_trunc) {
422 		ext4_truncate_failed_write(inode);
423 		/*
424 		 * If the truncate operation failed early, then the inode may
425 		 * still be on the orphan list. In that case, we need to try
426 		 * remove the inode from the in-memory linked list.
427 		 */
428 		if (inode->i_nlink)
429 			ext4_orphan_del(NULL, inode);
430 		return;
431 	}
432 	/*
433 	 * If i_disksize got extended either due to writeback of delalloc
434 	 * blocks or extending truncate while the DIO was running we could fail
435 	 * to cleanup the orphan list in ext4_handle_inode_extension(). Do it
436 	 * now.
437 	 */
438 	if (ext4_inode_orphan_tracked(inode) && inode->i_nlink) {
439 		handle_t *handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
440 
441 		if (IS_ERR(handle)) {
442 			/*
443 			 * The write has successfully completed. Not much to
444 			 * do with the error here so just cleanup the orphan
445 			 * list and hope for the best.
446 			 */
447 			ext4_orphan_del(NULL, inode);
448 			return;
449 		}
450 		ext4_orphan_del(handle, inode);
451 		ext4_journal_stop(handle);
452 	}
453 }
454 
455 static int ext4_dio_write_end_io(struct kiocb *iocb, ssize_t size,
456 				 int error, unsigned int flags)
457 {
458 	loff_t pos = iocb->ki_pos;
459 	struct inode *inode = file_inode(iocb->ki_filp);
460 
461 
462 	if (!error && size && (flags & IOMAP_DIO_UNWRITTEN) &&
463 			(iocb->ki_flags & IOCB_ATOMIC))
464 		error = ext4_convert_unwritten_extents_atomic(NULL, inode, pos,
465 							      size);
466 	else if (!error && size && flags & IOMAP_DIO_UNWRITTEN)
467 		error = ext4_convert_unwritten_extents(NULL, inode, pos, size,
468 						       NULL);
469 	if (error)
470 		return error;
471 	/*
472 	 * Note that EXT4_I(inode)->i_disksize can get extended up to
473 	 * inode->i_size while the I/O was running due to writeback of delalloc
474 	 * blocks. But the code in ext4_iomap_alloc() is careful to use
475 	 * zeroed/unwritten extents if this is possible; thus we won't leave
476 	 * uninitialized blocks in a file even if we didn't succeed in writing
477 	 * as much as we intended. Also we can race with truncate or write
478 	 * expanding the file so we have to be a bit careful here.
479 	 */
480 	if (pos + size <= READ_ONCE(EXT4_I(inode)->i_disksize) &&
481 	    pos + size <= i_size_read(inode))
482 		return 0;
483 	error = ext4_handle_inode_extension(inode, pos, size, size);
484 	return error < 0 ? error : 0;
485 }
486 
487 static const struct iomap_dio_ops ext4_dio_write_ops = {
488 	.end_io = ext4_dio_write_end_io,
489 };
490 
491 /*
492  * The intention here is to start with shared lock acquired then see if any
493  * condition requires an exclusive inode lock. If yes, then we restart the
494  * whole operation by releasing the shared lock and acquiring exclusive lock.
495  *
496  * The decision is layered, evaluated in this order:
497  *
498  * 1. If kiocb_modified() needs to update security info (!IS_NOSEC), upgrade
499  *    to the exclusive lock -- the security update itself requires it,
500  *    regardless of whether the write extends the file or is aligned.
501  *
502  * 2. If the write extends i_size or i_disksize, upgrade to the exclusive
503  *    lock to safely update i_disksize and the orphan list, regardless of
504  *    alignment.
505  *
506  * 3. Otherwise, for aligned non-extending writes, shared lock is always
507  *    sufficient regardless of extent state (written, unwritten, or hole).
508  *    truncate/punch_hole cannot run while we hold the shared i_rwsem
509  *    (they need it exclusively); after we release it, inode_dio_begin()
510  *    keeps their inode_dio_wait() blocked until in-flight bios complete.
511  *    i_data_sem serializes concurrent extent tree modifications.
512  *
513  * 4. Otherwise, the write is unaligned and non-extending. Shared lock is
514  *    safe unless the DIO layer needs to perform partial block zeroing --
515  *    i.e. the head or tail partial block sits on a hole or unwritten
516  *    extent. In that case upgrade to the exclusive lock and drain
517  *    in-flight DIO to avoid races with concurrent partial block zeroing.
518  */
519 static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from,
520 				     bool *ilock_shared, bool *extend,
521 				     int *dio_flags)
522 {
523 	struct file *file = iocb->ki_filp;
524 	struct inode *inode = file_inode(file);
525 	loff_t offset;
526 	size_t count;
527 	ssize_t ret;
528 	bool needs_zeroing = false;
529 
530 restart:
531 	ret = ext4_generic_write_checks(iocb, from);
532 	if (ret <= 0)
533 		goto out;
534 
535 	offset = iocb->ki_pos;
536 	count = ret;
537 
538 	*extend = ext4_extending_io(inode, offset, count);
539 
540 	/*
541 	 * For unaligned writes, check whether partial block zeroing will be
542 	 * needed. If so, exclusive lock is required to serialize against
543 	 * concurrent DIO that could race with the zeroing.
544 	 *
545 	 * For aligned writes we skip this check entirely since allocation
546 	 * under shared lock is safe.
547 	 */
548 	if (ext4_unaligned_io(inode, from, offset))
549 		needs_zeroing = ext4_dio_needs_zeroing(inode, offset, count);
550 
551 	/* Determine whether we need to upgrade to an exclusive lock. */
552 	if (*ilock_shared &&
553 	    (!IS_NOSEC(inode) || *extend || needs_zeroing)) {
554 		if (iocb->ki_flags & IOCB_NOWAIT) {
555 			ret = -EAGAIN;
556 			goto out;
557 		}
558 		inode_unlock_shared(inode);
559 		*ilock_shared = false;
560 		inode_lock(inode);
561 		goto restart;
562 	}
563 
564 	/*
565 	 * Now that locking is settled, determine dio flags and exclusivity
566 	 * requirements. We don't use DIO_OVERWRITE_ONLY because we enforce
567 	 * behavior already. When holding the exclusive lock for a write that
568 	 * needs partial block zeroing or is extending the file, we must wait
569 	 * for the I/O to complete synchronously:
570 	 *
571 	 *  - needs_zeroing: drain in-flight DIO whose end_io could race with
572 	 *    our partial block zeroing, and force synchronous completion so we
573 	 *    don't leave in-flight zeroing bios for the next writer to drain.
574 	 *
575 	 *  - extend: the caller must update i_disksize after I/O completion,
576 	 *    which requires the data to be on disk first.
577 	 */
578 	if (!*ilock_shared && (needs_zeroing || *extend)) {
579 		if (iocb->ki_flags & IOCB_NOWAIT) {
580 			ret = -EAGAIN;
581 			goto out;
582 		}
583 		if (needs_zeroing)
584 			inode_dio_wait(inode);
585 		*dio_flags = IOMAP_DIO_FORCE_WAIT;
586 	}
587 
588 	ret = kiocb_modified(iocb);
589 	if (ret < 0)
590 		goto out;
591 
592 	return count;
593 out:
594 	if (*ilock_shared)
595 		inode_unlock_shared(inode);
596 	else
597 		inode_unlock(inode);
598 	return ret;
599 }
600 
601 static ssize_t ext4_dio_write_iter(struct kiocb *iocb, struct iov_iter *from)
602 {
603 	ssize_t ret;
604 	handle_t *handle;
605 	struct inode *inode = file_inode(iocb->ki_filp);
606 	loff_t offset = iocb->ki_pos;
607 	size_t count = iov_iter_count(from);
608 	bool extend = false;
609 	bool ilock_shared = true;
610 	int dio_flags = 0;
611 
612 	/*
613 	 * Quick check here without any i_rwsem lock to see if it is extending
614 	 * IO. A more reliable check is done in ext4_dio_write_checks() with
615 	 * proper locking in place.
616 	 */
617 	if (offset + count > i_size_read(inode))
618 		ilock_shared = false;
619 
620 	if (iocb->ki_flags & IOCB_NOWAIT) {
621 		if (ilock_shared) {
622 			if (!inode_trylock_shared(inode))
623 				return -EAGAIN;
624 		} else {
625 			if (!inode_trylock(inode))
626 				return -EAGAIN;
627 		}
628 	} else {
629 		if (ilock_shared)
630 			inode_lock_shared(inode);
631 		else
632 			inode_lock(inode);
633 	}
634 
635 	/* Fallback to buffered I/O if the inode does not support direct I/O. */
636 	if (!ext4_should_use_dio(iocb, from)) {
637 		if (ilock_shared)
638 			inode_unlock_shared(inode);
639 		else
640 			inode_unlock(inode);
641 		return ext4_buffered_write_iter(iocb, from);
642 	}
643 
644 	/*
645 	 * Prevent inline data from being created since we are going to allocate
646 	 * blocks for DIO. We know the inode does not currently have inline data
647 	 * because ext4_should_use_dio() checked for it, but we have to clear
648 	 * the state flag before the write checks because a lock cycle could
649 	 * introduce races with other writers.
650 	 */
651 	ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
652 
653 	ret = ext4_dio_write_checks(iocb, from, &ilock_shared, &extend,
654 				    &dio_flags);
655 	if (ret <= 0)
656 		return ret;
657 
658 	offset = iocb->ki_pos;
659 	count = ret;
660 
661 	if (extend) {
662 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
663 		if (IS_ERR(handle)) {
664 			ret = PTR_ERR(handle);
665 			goto out;
666 		}
667 
668 		ret = ext4_orphan_add(handle, inode);
669 		ext4_journal_stop(handle);
670 		if (ret)
671 			goto out;
672 	}
673 
674 	ret = iomap_dio_rw(iocb, from, ext4_iomap_next, &ext4_dio_write_ops,
675 			   dio_flags, NULL, 0);
676 	if (ret == -ENOTBLK)
677 		ret = 0;
678 	if (extend) {
679 		/*
680 		 * We always perform extending DIO write synchronously so by
681 		 * now the IO is completed and ext4_handle_inode_extension()
682 		 * was called. Cleanup the inode in case of error or race with
683 		 * writeback of delalloc blocks.
684 		 */
685 		WARN_ON_ONCE(ret == -EIOCBQUEUED);
686 		ext4_inode_extension_cleanup(inode, ret < 0);
687 	}
688 
689 out:
690 	if (ilock_shared)
691 		inode_unlock_shared(inode);
692 	else
693 		inode_unlock(inode);
694 
695 	if (ret >= 0 && iov_iter_count(from)) {
696 		ssize_t err;
697 		loff_t endbyte;
698 
699 		/*
700 		 * Buffered I/O provides no torn-write protection, so never
701 		 * finish an atomic write through the page cache. iomap must
702 		 * not return a short atomic write, so treat one as a bug.
703 		 */
704 		if (WARN_ON_ONCE(iocb->ki_flags & IOCB_ATOMIC))
705 			return -EIO;
706 
707 		offset = iocb->ki_pos;
708 		err = ext4_buffered_write_iter(iocb, from);
709 		if (err < 0)
710 			return err;
711 
712 		/*
713 		 * We need to ensure that the pages within the page cache for
714 		 * the range covered by this I/O are written to disk and
715 		 * invalidated. This is in attempt to preserve the expected
716 		 * direct I/O semantics in the case we fallback to buffered I/O
717 		 * to complete off the I/O request.
718 		 */
719 		ret += err;
720 		endbyte = offset + err - 1;
721 		err = filemap_write_and_wait_range(iocb->ki_filp->f_mapping,
722 						   offset, endbyte);
723 		if (!err)
724 			invalidate_mapping_pages(iocb->ki_filp->f_mapping,
725 						 offset >> PAGE_SHIFT,
726 						 endbyte >> PAGE_SHIFT);
727 	}
728 
729 	return ret;
730 }
731 
732 #ifdef CONFIG_FS_DAX
733 static ssize_t
734 ext4_dax_write_iter(struct kiocb *iocb, struct iov_iter *from)
735 {
736 	ssize_t ret;
737 	size_t count;
738 	loff_t offset;
739 	handle_t *handle;
740 	bool extend = false;
741 	struct inode *inode = file_inode(iocb->ki_filp);
742 
743 	if (iocb->ki_flags & IOCB_NOWAIT) {
744 		if (!inode_trylock(inode))
745 			return -EAGAIN;
746 	} else {
747 		inode_lock(inode);
748 	}
749 
750 	ret = ext4_write_checks(iocb, from);
751 	if (ret <= 0)
752 		goto out;
753 
754 	offset = iocb->ki_pos;
755 	count = iov_iter_count(from);
756 
757 	if (offset + count > EXT4_I(inode)->i_disksize) {
758 		if (iocb->ki_flags & IOCB_NOWAIT) {
759 			ret = -EAGAIN;
760 			goto out;
761 		}
762 
763 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
764 		if (IS_ERR(handle)) {
765 			ret = PTR_ERR(handle);
766 			goto out;
767 		}
768 
769 		ret = ext4_orphan_add(handle, inode);
770 		if (ret) {
771 			ext4_journal_stop(handle);
772 			goto out;
773 		}
774 
775 		extend = true;
776 		ext4_journal_stop(handle);
777 	}
778 
779 	ret = dax_iomap_rw(iocb, from, ext4_iomap_next);
780 
781 	if (extend) {
782 		ret = ext4_handle_inode_extension(inode, offset, ret, count);
783 		ext4_inode_extension_cleanup(inode, ret < (ssize_t)count);
784 	}
785 out:
786 	inode_unlock(inode);
787 	if (ret > 0)
788 		ret = generic_write_sync(iocb, ret);
789 	return ret;
790 }
791 #endif
792 
793 static ssize_t
794 ext4_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
795 {
796 	int ret;
797 	struct inode *inode = file_inode(iocb->ki_filp);
798 
799 	ret = ext4_emergency_state(inode->i_sb);
800 	if (unlikely(ret))
801 		return ret;
802 
803 #ifdef CONFIG_FS_DAX
804 	if (IS_DAX(inode))
805 		return ext4_dax_write_iter(iocb, from);
806 #endif
807 
808 	if (iocb->ki_flags & IOCB_ATOMIC) {
809 		size_t len = iov_iter_count(from);
810 
811 		if (len < EXT4_SB(inode->i_sb)->s_awu_min ||
812 		    len > EXT4_SB(inode->i_sb)->s_awu_max)
813 			return -EINVAL;
814 
815 		ret = generic_atomic_write_valid(iocb, from);
816 		if (ret)
817 			return ret;
818 	}
819 
820 	if (iocb->ki_flags & IOCB_DIRECT)
821 		return ext4_dio_write_iter(iocb, from);
822 	else
823 		return ext4_buffered_write_iter(iocb, from);
824 }
825 
826 #ifdef CONFIG_FS_DAX
827 static vm_fault_t ext4_dax_huge_fault(struct vm_fault *vmf, unsigned int order)
828 {
829 	int error = 0;
830 	vm_fault_t result;
831 	int retries = 0;
832 	handle_t *handle = NULL;
833 	struct inode *inode = file_inode(vmf->vma->vm_file);
834 	struct super_block *sb = inode->i_sb;
835 
836 	/*
837 	 * We have to distinguish real writes from writes which will result in a
838 	 * COW page; COW writes should *not* poke the journal (the file will not
839 	 * be changed). Doing so would cause unintended failures when mounted
840 	 * read-only.
841 	 *
842 	 * We check for VM_SHARED rather than vmf->cow_page since the latter is
843 	 * unset for order != 0 (i.e. only in do_cow_fault); for
844 	 * other sizes, dax_iomap_fault will handle splitting / fallback so that
845 	 * we eventually come back with a COW page.
846 	 */
847 	bool write = (vmf->flags & FAULT_FLAG_WRITE) &&
848 		(vmf->vma->vm_flags & VM_SHARED);
849 	struct address_space *mapping = vmf->vma->vm_file->f_mapping;
850 	unsigned long pfn;
851 
852 	if (write) {
853 		sb_start_pagefault(sb);
854 		file_update_time(vmf->vma->vm_file);
855 		filemap_invalidate_lock_shared(mapping);
856 retry:
857 		handle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE,
858 					       EXT4_DATA_TRANS_BLOCKS(sb));
859 		if (IS_ERR(handle)) {
860 			filemap_invalidate_unlock_shared(mapping);
861 			sb_end_pagefault(sb);
862 			return VM_FAULT_SIGBUS;
863 		}
864 	} else {
865 		filemap_invalidate_lock_shared(mapping);
866 	}
867 	result = dax_iomap_fault(vmf, order, &pfn, &error, ext4_iomap_next);
868 	if (write) {
869 		ext4_journal_stop(handle);
870 
871 		if ((result & VM_FAULT_ERROR) && error == -ENOSPC &&
872 		    ext4_should_retry_alloc(sb, &retries))
873 			goto retry;
874 		/* Handling synchronous page fault? */
875 		if (result & VM_FAULT_NEEDDSYNC)
876 			result = dax_finish_sync_fault(vmf, order, pfn);
877 		filemap_invalidate_unlock_shared(mapping);
878 		sb_end_pagefault(sb);
879 	} else {
880 		filemap_invalidate_unlock_shared(mapping);
881 	}
882 
883 	return result;
884 }
885 
886 static vm_fault_t ext4_dax_fault(struct vm_fault *vmf)
887 {
888 	return ext4_dax_huge_fault(vmf, 0);
889 }
890 
891 static const struct vm_operations_struct ext4_dax_vm_ops = {
892 	.fault		= ext4_dax_fault,
893 	.huge_fault	= ext4_dax_huge_fault,
894 	.page_mkwrite	= ext4_dax_fault,
895 	.pfn_mkwrite	= ext4_dax_fault,
896 };
897 #else
898 #define ext4_dax_vm_ops	ext4_file_vm_ops
899 #endif
900 
901 static const struct vm_operations_struct ext4_file_vm_ops = {
902 	.fault		= filemap_fault,
903 	.map_pages	= filemap_map_pages,
904 	.page_mkwrite   = ext4_page_mkwrite,
905 };
906 
907 static int ext4_file_mmap_prepare(struct vm_area_desc *desc)
908 {
909 	int ret;
910 	struct file *file = desc->file;
911 	struct inode *inode = file->f_mapping->host;
912 	struct dax_device *dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
913 
914 	if (file->f_mode & FMODE_WRITE)
915 		ret = ext4_emergency_state(inode->i_sb);
916 	else
917 		ret = ext4_forced_shutdown(inode->i_sb) ? -EIO : 0;
918 	if (unlikely(ret))
919 		return ret;
920 
921 	/*
922 	 * We don't support synchronous mappings for non-DAX files and
923 	 * for DAX files if underneath dax_device is not synchronous.
924 	 */
925 	if (!daxdev_mapping_supported(desc, file_inode(file), dax_dev))
926 		return -EOPNOTSUPP;
927 
928 	file_accessed(file);
929 	if (IS_DAX(file_inode(file))) {
930 		desc->vm_ops = &ext4_dax_vm_ops;
931 		vma_desc_set_flags(desc, VMA_HUGEPAGE_BIT);
932 	} else {
933 		desc->vm_ops = &ext4_file_vm_ops;
934 	}
935 	return 0;
936 }
937 
938 static int ext4_sample_last_mounted(struct super_block *sb,
939 				    struct vfsmount *mnt)
940 {
941 	struct ext4_sb_info *sbi = EXT4_SB(sb);
942 	struct path path;
943 	char buf[64], *cp;
944 	handle_t *handle;
945 	int err;
946 
947 	if (likely(ext4_test_mount_flag(sb, EXT4_MF_MNTDIR_SAMPLED)))
948 		return 0;
949 
950 	if (ext4_emergency_state(sb) || sb_rdonly(sb) ||
951 	    !sb_start_intwrite_trylock(sb))
952 		return 0;
953 
954 	ext4_set_mount_flag(sb, EXT4_MF_MNTDIR_SAMPLED);
955 	/*
956 	 * Sample where the filesystem has been mounted and
957 	 * store it in the superblock for sysadmin convenience
958 	 * when trying to sort through large numbers of block
959 	 * devices or filesystem images.
960 	 */
961 	path.mnt = mnt;
962 	path.dentry = mnt->mnt_root;
963 	cp = d_path(&path, buf, sizeof(buf));
964 	err = 0;
965 	if (IS_ERR(cp))
966 		goto out;
967 
968 	handle = ext4_journal_start_sb(sb, EXT4_HT_MISC, 1);
969 	err = PTR_ERR(handle);
970 	if (IS_ERR(handle))
971 		goto out;
972 	BUFFER_TRACE(sbi->s_sbh, "get_write_access");
973 	err = ext4_journal_get_write_access(handle, sb, sbi->s_sbh,
974 					    EXT4_JTR_NONE);
975 	if (err)
976 		goto out_journal;
977 	lock_buffer(sbi->s_sbh);
978 	strtomem_pad(sbi->s_es->s_last_mounted, cp, 0);
979 	ext4_superblock_csum_set(sb);
980 	unlock_buffer(sbi->s_sbh);
981 	ext4_handle_dirty_metadata(handle, NULL, sbi->s_sbh);
982 out_journal:
983 	ext4_journal_stop(handle);
984 out:
985 	sb_end_intwrite(sb);
986 	return err;
987 }
988 
989 static int ext4_file_open(struct inode *inode, struct file *filp)
990 {
991 	int ret;
992 
993 	if (filp->f_mode & FMODE_WRITE)
994 		ret = ext4_emergency_state(inode->i_sb);
995 	else
996 		ret = ext4_forced_shutdown(inode->i_sb) ? -EIO : 0;
997 	if (unlikely(ret))
998 		return ret;
999 
1000 	ret = ext4_sample_last_mounted(inode->i_sb, filp->f_path.mnt);
1001 	if (ret)
1002 		return ret;
1003 
1004 	ret = fscrypt_file_open(inode, filp);
1005 	if (ret)
1006 		return ret;
1007 
1008 	ret = fsverity_file_open(inode, filp);
1009 	if (ret)
1010 		return ret;
1011 
1012 	/*
1013 	 * Set up the jbd2_inode if we are opening the inode for
1014 	 * writing and the journal is present
1015 	 */
1016 	if (filp->f_mode & FMODE_WRITE) {
1017 		ret = ext4_inode_attach_jinode(inode);
1018 		if (ret < 0)
1019 			return ret;
1020 	}
1021 
1022 	if (ext4_inode_can_atomic_write(inode))
1023 		filp->f_mode |= FMODE_CAN_ATOMIC_WRITE;
1024 
1025 	filp->f_mode |= FMODE_NOWAIT | FMODE_CAN_ODIRECT;
1026 	return dquot_file_open(inode, filp);
1027 }
1028 
1029 /*
1030  * ext4_llseek() handles both block-mapped and extent-mapped maxbytes values
1031  * by calling generic_file_llseek_size() with the appropriate maxbytes
1032  * value for each.
1033  */
1034 loff_t ext4_llseek(struct file *file, loff_t offset, int whence)
1035 {
1036 	struct inode *inode = file->f_mapping->host;
1037 	loff_t maxbytes = ext4_get_maxbytes(inode);
1038 
1039 	switch (whence) {
1040 	default:
1041 		return generic_file_llseek_size(file, offset, whence,
1042 						maxbytes, i_size_read(inode));
1043 	case SEEK_HOLE:
1044 		inode_lock_shared(inode);
1045 		offset = iomap_seek_hole(inode, offset,
1046 					 ext4_iomap_next_report);
1047 		inode_unlock_shared(inode);
1048 		break;
1049 	case SEEK_DATA:
1050 		inode_lock_shared(inode);
1051 		offset = iomap_seek_data(inode, offset,
1052 					 ext4_iomap_next_report);
1053 		inode_unlock_shared(inode);
1054 		break;
1055 	}
1056 
1057 	if (offset < 0)
1058 		return offset;
1059 	return vfs_setpos(file, offset, maxbytes);
1060 }
1061 
1062 const struct file_operations ext4_file_operations = {
1063 	.llseek		= ext4_llseek,
1064 	.read_iter	= ext4_file_read_iter,
1065 	.write_iter	= ext4_file_write_iter,
1066 	.iopoll		= iocb_bio_iopoll,
1067 	.unlocked_ioctl = ext4_ioctl,
1068 #ifdef CONFIG_COMPAT
1069 	.compat_ioctl	= ext4_compat_ioctl,
1070 #endif
1071 	.mmap_prepare	= ext4_file_mmap_prepare,
1072 	.open		= ext4_file_open,
1073 	.release	= ext4_release_file,
1074 	.fsync		= ext4_sync_file,
1075 	.get_unmapped_area = thp_get_unmapped_area,
1076 	.splice_read	= ext4_file_splice_read,
1077 	.splice_write	= iter_file_splice_write,
1078 	.fallocate	= ext4_fallocate,
1079 	.fop_flags	= FOP_MMAP_SYNC | FOP_BUFFER_RASYNC |
1080 			  FOP_DIO_PARALLEL_WRITE |
1081 			  FOP_DONTCACHE,
1082 	.setlease	= generic_setlease,
1083 };
1084 
1085 const struct inode_operations ext4_file_inode_operations = {
1086 	.setattr	= ext4_setattr,
1087 	.getattr	= ext4_file_getattr,
1088 	.listxattr	= ext4_listxattr,
1089 	.get_inode_acl	= ext4_get_acl,
1090 	.set_acl	= ext4_set_acl,
1091 	.fiemap		= ext4_fiemap,
1092 	.fileattr_get	= ext4_fileattr_get,
1093 	.fileattr_set	= ext4_fileattr_set,
1094 };
1095 
1096