xref: /linux/fs/ext4/file.c (revision 0a6f584e91f4a65f54d4d4c4876e3e6e12977955)
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_ops, 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_ops);
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 	const struct iomap_ops *iomap_ops;
338 
339 	if (test_opt(inode->i_sb, DELALLOC) && !ext4_nonda_switch(inode->i_sb))
340 		iomap_ops = &ext4_iomap_buffered_da_write_ops;
341 	else
342 		iomap_ops = &ext4_iomap_buffered_write_ops;
343 
344 	return iomap_file_buffered_write(iocb, from, iomap_ops,
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 	inode_lock(inode);
358 
359 	/*
360 	 * Prevent concurrent direct I/O and buffered I/O to the same file
361 	 * range. Wait for in-flight DIO to finish before dirtying pages.
362 	 */
363 	inode_dio_wait(inode);
364 
365 	ret = ext4_write_checks(iocb, from);
366 	if (ret <= 0)
367 		goto out;
368 
369 	if (ext4_inode_buffered_iomap(inode))
370 		ret = ext4_iomap_buffered_write(iocb, from);
371 	else
372 		ret = generic_perform_write(iocb, from);
373 
374 out:
375 	inode_unlock(inode);
376 	if (unlikely(ret <= 0))
377 		return ret;
378 	return generic_write_sync(iocb, ret);
379 }
380 
381 static ssize_t ext4_handle_inode_extension(struct inode *inode, loff_t offset,
382 					   ssize_t written, ssize_t count)
383 {
384 	handle_t *handle;
385 
386 	lockdep_assert_held_write(&inode->i_rwsem);
387 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
388 	if (IS_ERR(handle))
389 		return PTR_ERR(handle);
390 
391 	if (ext4_update_inode_size(inode, offset + written)) {
392 		int ret = ext4_mark_inode_dirty(handle, inode);
393 		if (unlikely(ret)) {
394 			ext4_journal_stop(handle);
395 			return ret;
396 		}
397 	}
398 
399 	if ((written == count) && inode->i_nlink)
400 		ext4_orphan_del(handle, inode);
401 	ext4_journal_stop(handle);
402 
403 	return written;
404 }
405 
406 /*
407  * Clean up the inode after DIO or DAX extending write has completed and the
408  * inode size has been updated using ext4_handle_inode_extension().
409  */
410 static void ext4_inode_extension_cleanup(struct inode *inode, bool need_trunc)
411 {
412 	lockdep_assert_held_write(&inode->i_rwsem);
413 	if (need_trunc) {
414 		ext4_truncate_failed_write(inode);
415 		/*
416 		 * If the truncate operation failed early, then the inode may
417 		 * still be on the orphan list. In that case, we need to try
418 		 * remove the inode from the in-memory linked list.
419 		 */
420 		if (inode->i_nlink)
421 			ext4_orphan_del(NULL, inode);
422 		return;
423 	}
424 	/*
425 	 * If i_disksize got extended either due to writeback of delalloc
426 	 * blocks or extending truncate while the DIO was running we could fail
427 	 * to cleanup the orphan list in ext4_handle_inode_extension(). Do it
428 	 * now.
429 	 */
430 	if (ext4_inode_orphan_tracked(inode) && inode->i_nlink) {
431 		handle_t *handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
432 
433 		if (IS_ERR(handle)) {
434 			/*
435 			 * The write has successfully completed. Not much to
436 			 * do with the error here so just cleanup the orphan
437 			 * list and hope for the best.
438 			 */
439 			ext4_orphan_del(NULL, inode);
440 			return;
441 		}
442 		ext4_orphan_del(handle, inode);
443 		ext4_journal_stop(handle);
444 	}
445 }
446 
447 static int ext4_dio_write_end_io(struct kiocb *iocb, ssize_t size,
448 				 int error, unsigned int flags)
449 {
450 	loff_t pos = iocb->ki_pos;
451 	struct inode *inode = file_inode(iocb->ki_filp);
452 
453 
454 	if (!error && size && (flags & IOMAP_DIO_UNWRITTEN) &&
455 			(iocb->ki_flags & IOCB_ATOMIC))
456 		error = ext4_convert_unwritten_extents_atomic(NULL, inode, pos,
457 							      size);
458 	else if (!error && size && flags & IOMAP_DIO_UNWRITTEN)
459 		error = ext4_convert_unwritten_extents(NULL, inode, pos, size,
460 						       NULL);
461 	if (error)
462 		return error;
463 	/*
464 	 * Note that EXT4_I(inode)->i_disksize can get extended up to
465 	 * inode->i_size while the I/O was running due to writeback of delalloc
466 	 * blocks. But the code in ext4_iomap_alloc() is careful to use
467 	 * zeroed/unwritten extents if this is possible; thus we won't leave
468 	 * uninitialized blocks in a file even if we didn't succeed in writing
469 	 * as much as we intended. Also we can race with truncate or write
470 	 * expanding the file so we have to be a bit careful here.
471 	 */
472 	if (pos + size <= READ_ONCE(EXT4_I(inode)->i_disksize) &&
473 	    pos + size <= i_size_read(inode))
474 		return 0;
475 	error = ext4_handle_inode_extension(inode, pos, size, size);
476 	return error < 0 ? error : 0;
477 }
478 
479 static const struct iomap_dio_ops ext4_dio_write_ops = {
480 	.end_io = ext4_dio_write_end_io,
481 };
482 
483 /*
484  * The intention here is to start with shared lock acquired then see if any
485  * condition requires an exclusive inode lock. If yes, then we restart the
486  * whole operation by releasing the shared lock and acquiring exclusive lock.
487  *
488  * The decision is layered, evaluated in this order:
489  *
490  * 1. If kiocb_modified() needs to update security info (!IS_NOSEC), upgrade
491  *    to the exclusive lock -- the security update itself requires it,
492  *    regardless of whether the write extends the file or is aligned.
493  *
494  * 2. If the write extends i_size or i_disksize, upgrade to the exclusive
495  *    lock to safely update i_disksize and the orphan list, regardless of
496  *    alignment.
497  *
498  * 3. Otherwise, for aligned non-extending writes, shared lock is always
499  *    sufficient regardless of extent state (written, unwritten, or hole).
500  *    truncate/punch_hole cannot run while we hold the shared i_rwsem
501  *    (they need it exclusively); after we release it, inode_dio_begin()
502  *    keeps their inode_dio_wait() blocked until in-flight bios complete.
503  *    i_data_sem serializes concurrent extent tree modifications.
504  *
505  * 4. Otherwise, the write is unaligned and non-extending. Shared lock is
506  *    safe unless the DIO layer needs to perform partial block zeroing --
507  *    i.e. the head or tail partial block sits on a hole or unwritten
508  *    extent. In that case upgrade to the exclusive lock and drain
509  *    in-flight DIO to avoid races with concurrent partial block zeroing.
510  */
511 static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from,
512 				     bool *ilock_shared, bool *extend,
513 				     int *dio_flags)
514 {
515 	struct file *file = iocb->ki_filp;
516 	struct inode *inode = file_inode(file);
517 	loff_t offset;
518 	size_t count;
519 	ssize_t ret;
520 	bool needs_zeroing = false;
521 
522 restart:
523 	ret = ext4_generic_write_checks(iocb, from);
524 	if (ret <= 0)
525 		goto out;
526 
527 	offset = iocb->ki_pos;
528 	count = ret;
529 
530 	*extend = ext4_extending_io(inode, offset, count);
531 
532 	/*
533 	 * For unaligned writes, check whether partial block zeroing will be
534 	 * needed. If so, exclusive lock is required to serialize against
535 	 * concurrent DIO that could race with the zeroing.
536 	 *
537 	 * For aligned writes we skip this check entirely since allocation
538 	 * under shared lock is safe.
539 	 */
540 	if (ext4_unaligned_io(inode, from, offset))
541 		needs_zeroing = ext4_dio_needs_zeroing(inode, offset, count);
542 
543 	/* Determine whether we need to upgrade to an exclusive lock. */
544 	if (*ilock_shared &&
545 	    (!IS_NOSEC(inode) || *extend || needs_zeroing)) {
546 		if (iocb->ki_flags & IOCB_NOWAIT) {
547 			ret = -EAGAIN;
548 			goto out;
549 		}
550 		inode_unlock_shared(inode);
551 		*ilock_shared = false;
552 		inode_lock(inode);
553 		goto restart;
554 	}
555 
556 	/*
557 	 * Now that locking is settled, determine dio flags and exclusivity
558 	 * requirements. We don't use DIO_OVERWRITE_ONLY because we enforce
559 	 * behavior already. When holding the exclusive lock for a write that
560 	 * needs partial block zeroing or is extending the file, we must wait
561 	 * for the I/O to complete synchronously:
562 	 *
563 	 *  - needs_zeroing: drain in-flight DIO whose end_io could race with
564 	 *    our partial block zeroing, and force synchronous completion so we
565 	 *    don't leave in-flight zeroing bios for the next writer to drain.
566 	 *
567 	 *  - extend: the caller must update i_disksize after I/O completion,
568 	 *    which requires the data to be on disk first.
569 	 */
570 	if (!*ilock_shared && (needs_zeroing || *extend)) {
571 		if (iocb->ki_flags & IOCB_NOWAIT) {
572 			ret = -EAGAIN;
573 			goto out;
574 		}
575 		if (needs_zeroing)
576 			inode_dio_wait(inode);
577 		*dio_flags = IOMAP_DIO_FORCE_WAIT;
578 	}
579 
580 	ret = kiocb_modified(iocb);
581 	if (ret < 0)
582 		goto out;
583 
584 	return count;
585 out:
586 	if (*ilock_shared)
587 		inode_unlock_shared(inode);
588 	else
589 		inode_unlock(inode);
590 	return ret;
591 }
592 
593 static ssize_t ext4_dio_write_iter(struct kiocb *iocb, struct iov_iter *from)
594 {
595 	ssize_t ret;
596 	handle_t *handle;
597 	struct inode *inode = file_inode(iocb->ki_filp);
598 	loff_t offset = iocb->ki_pos;
599 	size_t count = iov_iter_count(from);
600 	bool extend = false;
601 	bool ilock_shared = true;
602 	int dio_flags = 0;
603 
604 	/*
605 	 * Quick check here without any i_rwsem lock to see if it is extending
606 	 * IO. A more reliable check is done in ext4_dio_write_checks() with
607 	 * proper locking in place.
608 	 */
609 	if (offset + count > i_size_read(inode))
610 		ilock_shared = false;
611 
612 	if (iocb->ki_flags & IOCB_NOWAIT) {
613 		if (ilock_shared) {
614 			if (!inode_trylock_shared(inode))
615 				return -EAGAIN;
616 		} else {
617 			if (!inode_trylock(inode))
618 				return -EAGAIN;
619 		}
620 	} else {
621 		if (ilock_shared)
622 			inode_lock_shared(inode);
623 		else
624 			inode_lock(inode);
625 	}
626 
627 	/* Fallback to buffered I/O if the inode does not support direct I/O. */
628 	if (!ext4_should_use_dio(iocb, from)) {
629 		if (ilock_shared)
630 			inode_unlock_shared(inode);
631 		else
632 			inode_unlock(inode);
633 		return ext4_buffered_write_iter(iocb, from);
634 	}
635 
636 	/*
637 	 * Prevent inline data from being created since we are going to allocate
638 	 * blocks for DIO. We know the inode does not currently have inline data
639 	 * because ext4_should_use_dio() checked for it, but we have to clear
640 	 * the state flag before the write checks because a lock cycle could
641 	 * introduce races with other writers.
642 	 */
643 	ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
644 
645 	ret = ext4_dio_write_checks(iocb, from, &ilock_shared, &extend,
646 				    &dio_flags);
647 	if (ret <= 0)
648 		return ret;
649 
650 	offset = iocb->ki_pos;
651 	count = ret;
652 
653 	if (extend) {
654 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
655 		if (IS_ERR(handle)) {
656 			ret = PTR_ERR(handle);
657 			goto out;
658 		}
659 
660 		ret = ext4_orphan_add(handle, inode);
661 		ext4_journal_stop(handle);
662 		if (ret)
663 			goto out;
664 	}
665 
666 	ret = iomap_dio_rw(iocb, from, &ext4_iomap_ops, &ext4_dio_write_ops,
667 			   dio_flags, NULL, 0);
668 	if (ret == -ENOTBLK)
669 		ret = 0;
670 	if (extend) {
671 		/*
672 		 * We always perform extending DIO write synchronously so by
673 		 * now the IO is completed and ext4_handle_inode_extension()
674 		 * was called. Cleanup the inode in case of error or race with
675 		 * writeback of delalloc blocks.
676 		 */
677 		WARN_ON_ONCE(ret == -EIOCBQUEUED);
678 		ext4_inode_extension_cleanup(inode, ret < 0);
679 	}
680 
681 out:
682 	if (ilock_shared)
683 		inode_unlock_shared(inode);
684 	else
685 		inode_unlock(inode);
686 
687 	if (ret >= 0 && iov_iter_count(from)) {
688 		ssize_t err;
689 		loff_t endbyte;
690 
691 		/*
692 		 * There is no support for atomic writes on buffered-io yet,
693 		 * we should never fallback to buffered-io for DIO atomic
694 		 * writes.
695 		 */
696 		WARN_ON_ONCE(iocb->ki_flags & IOCB_ATOMIC);
697 
698 		offset = iocb->ki_pos;
699 		err = ext4_buffered_write_iter(iocb, from);
700 		if (err < 0)
701 			return err;
702 
703 		/*
704 		 * We need to ensure that the pages within the page cache for
705 		 * the range covered by this I/O are written to disk and
706 		 * invalidated. This is in attempt to preserve the expected
707 		 * direct I/O semantics in the case we fallback to buffered I/O
708 		 * to complete off the I/O request.
709 		 */
710 		ret += err;
711 		endbyte = offset + err - 1;
712 		err = filemap_write_and_wait_range(iocb->ki_filp->f_mapping,
713 						   offset, endbyte);
714 		if (!err)
715 			invalidate_mapping_pages(iocb->ki_filp->f_mapping,
716 						 offset >> PAGE_SHIFT,
717 						 endbyte >> PAGE_SHIFT);
718 	}
719 
720 	return ret;
721 }
722 
723 #ifdef CONFIG_FS_DAX
724 static ssize_t
725 ext4_dax_write_iter(struct kiocb *iocb, struct iov_iter *from)
726 {
727 	ssize_t ret;
728 	size_t count;
729 	loff_t offset;
730 	handle_t *handle;
731 	bool extend = false;
732 	struct inode *inode = file_inode(iocb->ki_filp);
733 
734 	if (iocb->ki_flags & IOCB_NOWAIT) {
735 		if (!inode_trylock(inode))
736 			return -EAGAIN;
737 	} else {
738 		inode_lock(inode);
739 	}
740 
741 	ret = ext4_write_checks(iocb, from);
742 	if (ret <= 0)
743 		goto out;
744 
745 	offset = iocb->ki_pos;
746 	count = iov_iter_count(from);
747 
748 	if (offset + count > EXT4_I(inode)->i_disksize) {
749 		if (iocb->ki_flags & IOCB_NOWAIT) {
750 			ret = -EAGAIN;
751 			goto out;
752 		}
753 
754 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
755 		if (IS_ERR(handle)) {
756 			ret = PTR_ERR(handle);
757 			goto out;
758 		}
759 
760 		ret = ext4_orphan_add(handle, inode);
761 		if (ret) {
762 			ext4_journal_stop(handle);
763 			goto out;
764 		}
765 
766 		extend = true;
767 		ext4_journal_stop(handle);
768 	}
769 
770 	ret = dax_iomap_rw(iocb, from, &ext4_iomap_ops);
771 
772 	if (extend) {
773 		ret = ext4_handle_inode_extension(inode, offset, ret, count);
774 		ext4_inode_extension_cleanup(inode, ret < (ssize_t)count);
775 	}
776 out:
777 	inode_unlock(inode);
778 	if (ret > 0)
779 		ret = generic_write_sync(iocb, ret);
780 	return ret;
781 }
782 #endif
783 
784 static ssize_t
785 ext4_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
786 {
787 	int ret;
788 	struct inode *inode = file_inode(iocb->ki_filp);
789 
790 	ret = ext4_emergency_state(inode->i_sb);
791 	if (unlikely(ret))
792 		return ret;
793 
794 #ifdef CONFIG_FS_DAX
795 	if (IS_DAX(inode))
796 		return ext4_dax_write_iter(iocb, from);
797 #endif
798 
799 	if (iocb->ki_flags & IOCB_ATOMIC) {
800 		size_t len = iov_iter_count(from);
801 
802 		if (len < EXT4_SB(inode->i_sb)->s_awu_min ||
803 		    len > EXT4_SB(inode->i_sb)->s_awu_max)
804 			return -EINVAL;
805 
806 		ret = generic_atomic_write_valid(iocb, from);
807 		if (ret)
808 			return ret;
809 	}
810 
811 	if (iocb->ki_flags & IOCB_DIRECT)
812 		return ext4_dio_write_iter(iocb, from);
813 	else
814 		return ext4_buffered_write_iter(iocb, from);
815 }
816 
817 #ifdef CONFIG_FS_DAX
818 static vm_fault_t ext4_dax_huge_fault(struct vm_fault *vmf, unsigned int order)
819 {
820 	int error = 0;
821 	vm_fault_t result;
822 	int retries = 0;
823 	handle_t *handle = NULL;
824 	struct inode *inode = file_inode(vmf->vma->vm_file);
825 	struct super_block *sb = inode->i_sb;
826 
827 	/*
828 	 * We have to distinguish real writes from writes which will result in a
829 	 * COW page; COW writes should *not* poke the journal (the file will not
830 	 * be changed). Doing so would cause unintended failures when mounted
831 	 * read-only.
832 	 *
833 	 * We check for VM_SHARED rather than vmf->cow_page since the latter is
834 	 * unset for order != 0 (i.e. only in do_cow_fault); for
835 	 * other sizes, dax_iomap_fault will handle splitting / fallback so that
836 	 * we eventually come back with a COW page.
837 	 */
838 	bool write = (vmf->flags & FAULT_FLAG_WRITE) &&
839 		(vmf->vma->vm_flags & VM_SHARED);
840 	struct address_space *mapping = vmf->vma->vm_file->f_mapping;
841 	unsigned long pfn;
842 
843 	if (write) {
844 		sb_start_pagefault(sb);
845 		file_update_time(vmf->vma->vm_file);
846 		filemap_invalidate_lock_shared(mapping);
847 retry:
848 		handle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE,
849 					       EXT4_DATA_TRANS_BLOCKS(sb));
850 		if (IS_ERR(handle)) {
851 			filemap_invalidate_unlock_shared(mapping);
852 			sb_end_pagefault(sb);
853 			return VM_FAULT_SIGBUS;
854 		}
855 	} else {
856 		filemap_invalidate_lock_shared(mapping);
857 	}
858 	result = dax_iomap_fault(vmf, order, &pfn, &error, &ext4_iomap_ops);
859 	if (write) {
860 		ext4_journal_stop(handle);
861 
862 		if ((result & VM_FAULT_ERROR) && error == -ENOSPC &&
863 		    ext4_should_retry_alloc(sb, &retries))
864 			goto retry;
865 		/* Handling synchronous page fault? */
866 		if (result & VM_FAULT_NEEDDSYNC)
867 			result = dax_finish_sync_fault(vmf, order, pfn);
868 		filemap_invalidate_unlock_shared(mapping);
869 		sb_end_pagefault(sb);
870 	} else {
871 		filemap_invalidate_unlock_shared(mapping);
872 	}
873 
874 	return result;
875 }
876 
877 static vm_fault_t ext4_dax_fault(struct vm_fault *vmf)
878 {
879 	return ext4_dax_huge_fault(vmf, 0);
880 }
881 
882 static const struct vm_operations_struct ext4_dax_vm_ops = {
883 	.fault		= ext4_dax_fault,
884 	.huge_fault	= ext4_dax_huge_fault,
885 	.page_mkwrite	= ext4_dax_fault,
886 	.pfn_mkwrite	= ext4_dax_fault,
887 };
888 #else
889 #define ext4_dax_vm_ops	ext4_file_vm_ops
890 #endif
891 
892 static const struct vm_operations_struct ext4_file_vm_ops = {
893 	.fault		= filemap_fault,
894 	.map_pages	= filemap_map_pages,
895 	.page_mkwrite   = ext4_page_mkwrite,
896 };
897 
898 static int ext4_file_mmap_prepare(struct vm_area_desc *desc)
899 {
900 	int ret;
901 	struct file *file = desc->file;
902 	struct inode *inode = file->f_mapping->host;
903 	struct dax_device *dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
904 
905 	if (file->f_mode & FMODE_WRITE)
906 		ret = ext4_emergency_state(inode->i_sb);
907 	else
908 		ret = ext4_forced_shutdown(inode->i_sb) ? -EIO : 0;
909 	if (unlikely(ret))
910 		return ret;
911 
912 	/*
913 	 * We don't support synchronous mappings for non-DAX files and
914 	 * for DAX files if underneath dax_device is not synchronous.
915 	 */
916 	if (!daxdev_mapping_supported(desc, file_inode(file), dax_dev))
917 		return -EOPNOTSUPP;
918 
919 	file_accessed(file);
920 	if (IS_DAX(file_inode(file))) {
921 		desc->vm_ops = &ext4_dax_vm_ops;
922 		vma_desc_set_flags(desc, VMA_HUGEPAGE_BIT);
923 	} else {
924 		desc->vm_ops = &ext4_file_vm_ops;
925 	}
926 	return 0;
927 }
928 
929 static int ext4_sample_last_mounted(struct super_block *sb,
930 				    struct vfsmount *mnt)
931 {
932 	struct ext4_sb_info *sbi = EXT4_SB(sb);
933 	struct path path;
934 	char buf[64], *cp;
935 	handle_t *handle;
936 	int err;
937 
938 	if (likely(ext4_test_mount_flag(sb, EXT4_MF_MNTDIR_SAMPLED)))
939 		return 0;
940 
941 	if (ext4_emergency_state(sb) || sb_rdonly(sb) ||
942 	    !sb_start_intwrite_trylock(sb))
943 		return 0;
944 
945 	ext4_set_mount_flag(sb, EXT4_MF_MNTDIR_SAMPLED);
946 	/*
947 	 * Sample where the filesystem has been mounted and
948 	 * store it in the superblock for sysadmin convenience
949 	 * when trying to sort through large numbers of block
950 	 * devices or filesystem images.
951 	 */
952 	path.mnt = mnt;
953 	path.dentry = mnt->mnt_root;
954 	cp = d_path(&path, buf, sizeof(buf));
955 	err = 0;
956 	if (IS_ERR(cp))
957 		goto out;
958 
959 	handle = ext4_journal_start_sb(sb, EXT4_HT_MISC, 1);
960 	err = PTR_ERR(handle);
961 	if (IS_ERR(handle))
962 		goto out;
963 	BUFFER_TRACE(sbi->s_sbh, "get_write_access");
964 	err = ext4_journal_get_write_access(handle, sb, sbi->s_sbh,
965 					    EXT4_JTR_NONE);
966 	if (err)
967 		goto out_journal;
968 	lock_buffer(sbi->s_sbh);
969 	strtomem_pad(sbi->s_es->s_last_mounted, cp, 0);
970 	ext4_superblock_csum_set(sb);
971 	unlock_buffer(sbi->s_sbh);
972 	ext4_handle_dirty_metadata(handle, NULL, sbi->s_sbh);
973 out_journal:
974 	ext4_journal_stop(handle);
975 out:
976 	sb_end_intwrite(sb);
977 	return err;
978 }
979 
980 static int ext4_file_open(struct inode *inode, struct file *filp)
981 {
982 	int ret;
983 
984 	if (filp->f_mode & FMODE_WRITE)
985 		ret = ext4_emergency_state(inode->i_sb);
986 	else
987 		ret = ext4_forced_shutdown(inode->i_sb) ? -EIO : 0;
988 	if (unlikely(ret))
989 		return ret;
990 
991 	ret = ext4_sample_last_mounted(inode->i_sb, filp->f_path.mnt);
992 	if (ret)
993 		return ret;
994 
995 	ret = fscrypt_file_open(inode, filp);
996 	if (ret)
997 		return ret;
998 
999 	ret = fsverity_file_open(inode, filp);
1000 	if (ret)
1001 		return ret;
1002 
1003 	/*
1004 	 * Set up the jbd2_inode if we are opening the inode for
1005 	 * writing and the journal is present
1006 	 */
1007 	if (filp->f_mode & FMODE_WRITE) {
1008 		ret = ext4_inode_attach_jinode(inode);
1009 		if (ret < 0)
1010 			return ret;
1011 	}
1012 
1013 	if (ext4_inode_can_atomic_write(inode))
1014 		filp->f_mode |= FMODE_CAN_ATOMIC_WRITE;
1015 
1016 	filp->f_mode |= FMODE_NOWAIT | FMODE_CAN_ODIRECT;
1017 	return dquot_file_open(inode, filp);
1018 }
1019 
1020 /*
1021  * ext4_llseek() handles both block-mapped and extent-mapped maxbytes values
1022  * by calling generic_file_llseek_size() with the appropriate maxbytes
1023  * value for each.
1024  */
1025 loff_t ext4_llseek(struct file *file, loff_t offset, int whence)
1026 {
1027 	struct inode *inode = file->f_mapping->host;
1028 	loff_t maxbytes = ext4_get_maxbytes(inode);
1029 
1030 	switch (whence) {
1031 	default:
1032 		return generic_file_llseek_size(file, offset, whence,
1033 						maxbytes, i_size_read(inode));
1034 	case SEEK_HOLE:
1035 		inode_lock_shared(inode);
1036 		offset = iomap_seek_hole(inode, offset,
1037 					 &ext4_iomap_report_ops);
1038 		inode_unlock_shared(inode);
1039 		break;
1040 	case SEEK_DATA:
1041 		inode_lock_shared(inode);
1042 		offset = iomap_seek_data(inode, offset,
1043 					 &ext4_iomap_report_ops);
1044 		inode_unlock_shared(inode);
1045 		break;
1046 	}
1047 
1048 	if (offset < 0)
1049 		return offset;
1050 	return vfs_setpos(file, offset, maxbytes);
1051 }
1052 
1053 const struct file_operations ext4_file_operations = {
1054 	.llseek		= ext4_llseek,
1055 	.read_iter	= ext4_file_read_iter,
1056 	.write_iter	= ext4_file_write_iter,
1057 	.iopoll		= iocb_bio_iopoll,
1058 	.unlocked_ioctl = ext4_ioctl,
1059 #ifdef CONFIG_COMPAT
1060 	.compat_ioctl	= ext4_compat_ioctl,
1061 #endif
1062 	.mmap_prepare	= ext4_file_mmap_prepare,
1063 	.open		= ext4_file_open,
1064 	.release	= ext4_release_file,
1065 	.fsync		= ext4_sync_file,
1066 	.get_unmapped_area = thp_get_unmapped_area,
1067 	.splice_read	= ext4_file_splice_read,
1068 	.splice_write	= iter_file_splice_write,
1069 	.fallocate	= ext4_fallocate,
1070 	.fop_flags	= FOP_MMAP_SYNC | FOP_BUFFER_RASYNC |
1071 			  FOP_DIO_PARALLEL_WRITE |
1072 			  FOP_DONTCACHE,
1073 	.setlease	= generic_setlease,
1074 };
1075 
1076 const struct inode_operations ext4_file_inode_operations = {
1077 	.setattr	= ext4_setattr,
1078 	.getattr	= ext4_file_getattr,
1079 	.listxattr	= ext4_listxattr,
1080 	.get_inode_acl	= ext4_get_acl,
1081 	.set_acl	= ext4_set_acl,
1082 	.fiemap		= ext4_fiemap,
1083 	.fileattr_get	= ext4_fileattr_get,
1084 	.fileattr_set	= ext4_fileattr_set,
1085 };
1086 
1087