xref: /linux/fs/ntfs3/file.c (revision 297fef494d78d00fa563ead08396da6b4ba58172)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *
4  * Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
5  *
6  *  Regular file handling primitives for NTFS-based filesystems.
7  *
8  */
9 
10 #include <linux/backing-dev.h>
11 #include <linux/blkdev.h>
12 #include <linux/buffer_head.h>
13 #include <linux/compat.h>
14 #include <linux/falloc.h>
15 #include <linux/fiemap.h>
16 #include <linux/fileattr.h>
17 
18 #include "debug.h"
19 #include "ntfs.h"
20 #include "ntfs_fs.h"
21 
22 static int ntfs_ioctl_fitrim(struct ntfs_sb_info *sbi, unsigned long arg)
23 {
24 	struct fstrim_range __user *user_range;
25 	struct fstrim_range range;
26 	struct block_device *dev;
27 	int err;
28 
29 	if (!capable(CAP_SYS_ADMIN))
30 		return -EPERM;
31 
32 	dev = sbi->sb->s_bdev;
33 	if (!bdev_max_discard_sectors(dev))
34 		return -EOPNOTSUPP;
35 
36 	user_range = (struct fstrim_range __user *)arg;
37 	if (copy_from_user(&range, user_range, sizeof(range)))
38 		return -EFAULT;
39 
40 	range.minlen = max_t(u32, range.minlen, bdev_discard_granularity(dev));
41 
42 	err = ntfs_trim_fs(sbi, &range);
43 	if (err < 0)
44 		return err;
45 
46 	if (copy_to_user(user_range, &range, sizeof(range)))
47 		return -EFAULT;
48 
49 	return 0;
50 }
51 
52 /*
53  * ntfs_fileattr_get - inode_operations::fileattr_get
54  */
55 int ntfs_fileattr_get(struct dentry *dentry, struct fileattr *fa)
56 {
57 	struct inode *inode = d_inode(dentry);
58 	struct ntfs_inode *ni = ntfs_i(inode);
59 	u32 flags = 0;
60 
61 	if (inode->i_flags & S_IMMUTABLE)
62 		flags |= FS_IMMUTABLE_FL;
63 
64 	if (inode->i_flags & S_APPEND)
65 		flags |= FS_APPEND_FL;
66 
67 	if (is_compressed(ni))
68 		flags |= FS_COMPR_FL;
69 
70 	if (is_encrypted(ni))
71 		flags |= FS_ENCRYPT_FL;
72 
73 	fileattr_fill_flags(fa, flags);
74 
75 	return 0;
76 }
77 
78 /*
79  * ntfs_fileattr_set - inode_operations::fileattr_set
80  */
81 int ntfs_fileattr_set(struct mnt_idmap *idmap, struct dentry *dentry,
82 		      struct fileattr *fa)
83 {
84 	struct inode *inode = d_inode(dentry);
85 	u32 flags = fa->flags;
86 	unsigned int new_fl = 0;
87 
88 	if (fileattr_has_fsx(fa))
89 		return -EOPNOTSUPP;
90 
91 	if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL))
92 		return -EOPNOTSUPP;
93 
94 	if (flags & FS_IMMUTABLE_FL)
95 		new_fl |= S_IMMUTABLE;
96 
97 	if (flags & FS_APPEND_FL)
98 		new_fl |= S_APPEND;
99 
100 	inode_set_flags(inode, new_fl, S_IMMUTABLE | S_APPEND);
101 
102 	inode_set_ctime_current(inode);
103 	mark_inode_dirty(inode);
104 
105 	return 0;
106 }
107 
108 /*
109  * ntfs_ioctl - file_operations::unlocked_ioctl
110  */
111 long ntfs_ioctl(struct file *filp, u32 cmd, unsigned long arg)
112 {
113 	struct inode *inode = file_inode(filp);
114 	struct ntfs_sb_info *sbi = inode->i_sb->s_fs_info;
115 
116 	switch (cmd) {
117 	case FITRIM:
118 		return ntfs_ioctl_fitrim(sbi, arg);
119 	}
120 	return -ENOTTY; /* Inappropriate ioctl for device. */
121 }
122 
123 #ifdef CONFIG_COMPAT
124 long ntfs_compat_ioctl(struct file *filp, u32 cmd, unsigned long arg)
125 
126 {
127 	return ntfs_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
128 }
129 #endif
130 
131 /*
132  * ntfs_getattr - inode_operations::getattr
133  */
134 int ntfs_getattr(struct mnt_idmap *idmap, const struct path *path,
135 		 struct kstat *stat, u32 request_mask, u32 flags)
136 {
137 	struct inode *inode = d_inode(path->dentry);
138 	struct ntfs_inode *ni = ntfs_i(inode);
139 
140 	stat->result_mask |= STATX_BTIME;
141 	stat->btime = ni->i_crtime;
142 	stat->blksize = ni->mi.sbi->cluster_size; /* 512, 1K, ..., 2M */
143 
144 	if (inode->i_flags & S_IMMUTABLE)
145 		stat->attributes |= STATX_ATTR_IMMUTABLE;
146 
147 	if (inode->i_flags & S_APPEND)
148 		stat->attributes |= STATX_ATTR_APPEND;
149 
150 	if (is_compressed(ni))
151 		stat->attributes |= STATX_ATTR_COMPRESSED;
152 
153 	if (is_encrypted(ni))
154 		stat->attributes |= STATX_ATTR_ENCRYPTED;
155 
156 	stat->attributes_mask |= STATX_ATTR_COMPRESSED | STATX_ATTR_ENCRYPTED |
157 				 STATX_ATTR_IMMUTABLE | STATX_ATTR_APPEND;
158 
159 	generic_fillattr(idmap, request_mask, inode, stat);
160 
161 	return 0;
162 }
163 
164 static int ntfs_extend_initialized_size(struct file *file,
165 					struct ntfs_inode *ni,
166 					const loff_t valid,
167 					const loff_t new_valid)
168 {
169 	struct inode *inode = &ni->vfs_inode;
170 	struct address_space *mapping = inode->i_mapping;
171 	struct ntfs_sb_info *sbi = inode->i_sb->s_fs_info;
172 	loff_t pos = valid;
173 	int err;
174 
175 	if (is_resident(ni)) {
176 		ni->i_valid = new_valid;
177 		return 0;
178 	}
179 
180 	WARN_ON(is_compressed(ni));
181 	WARN_ON(valid >= new_valid);
182 
183 	for (;;) {
184 		u32 zerofrom, len;
185 		struct page *page;
186 		u8 bits;
187 		CLST vcn, lcn, clen;
188 
189 		if (is_sparsed(ni)) {
190 			bits = sbi->cluster_bits;
191 			vcn = pos >> bits;
192 
193 			err = attr_data_get_block(ni, vcn, 1, &lcn, &clen, NULL,
194 						  false);
195 			if (err)
196 				goto out;
197 
198 			if (lcn == SPARSE_LCN) {
199 				pos = ((loff_t)clen + vcn) << bits;
200 				ni->i_valid = pos;
201 				goto next;
202 			}
203 		}
204 
205 		zerofrom = pos & (PAGE_SIZE - 1);
206 		len = PAGE_SIZE - zerofrom;
207 
208 		if (pos + len > new_valid)
209 			len = new_valid - pos;
210 
211 		err = ntfs_write_begin(file, mapping, pos, len, &page, NULL);
212 		if (err)
213 			goto out;
214 
215 		zero_user_segment(page, zerofrom, PAGE_SIZE);
216 
217 		/* This function in any case puts page. */
218 		err = ntfs_write_end(file, mapping, pos, len, len, page, NULL);
219 		if (err < 0)
220 			goto out;
221 		pos += len;
222 
223 next:
224 		if (pos >= new_valid)
225 			break;
226 
227 		balance_dirty_pages_ratelimited(mapping);
228 		cond_resched();
229 	}
230 
231 	return 0;
232 
233 out:
234 	ni->i_valid = valid;
235 	ntfs_inode_warn(inode, "failed to extend initialized size to %llx.",
236 			new_valid);
237 	return err;
238 }
239 
240 /*
241  * ntfs_zero_range - Helper function for punch_hole.
242  *
243  * It zeroes a range [vbo, vbo_to).
244  */
245 static int ntfs_zero_range(struct inode *inode, u64 vbo, u64 vbo_to)
246 {
247 	int err = 0;
248 	struct address_space *mapping = inode->i_mapping;
249 	u32 blocksize = i_blocksize(inode);
250 	pgoff_t idx = vbo >> PAGE_SHIFT;
251 	u32 from = vbo & (PAGE_SIZE - 1);
252 	pgoff_t idx_end = (vbo_to + PAGE_SIZE - 1) >> PAGE_SHIFT;
253 	loff_t page_off;
254 	struct buffer_head *head, *bh;
255 	u32 bh_next, bh_off, to;
256 	sector_t iblock;
257 	struct folio *folio;
258 	bool dirty = false;
259 
260 	for (; idx < idx_end; idx += 1, from = 0) {
261 		page_off = (loff_t)idx << PAGE_SHIFT;
262 		to = (page_off + PAGE_SIZE) > vbo_to ? (vbo_to - page_off) :
263 						       PAGE_SIZE;
264 		iblock = page_off >> inode->i_blkbits;
265 
266 		folio = __filemap_get_folio(
267 			mapping, idx, FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
268 			mapping_gfp_constraint(mapping, ~__GFP_FS));
269 		if (IS_ERR(folio))
270 			return PTR_ERR(folio);
271 
272 		head = folio_buffers(folio);
273 		if (!head)
274 			head = create_empty_buffers(folio, blocksize, 0);
275 
276 		bh = head;
277 		bh_off = 0;
278 		do {
279 			bh_next = bh_off + blocksize;
280 
281 			if (bh_next <= from || bh_off >= to)
282 				continue;
283 
284 			if (!buffer_mapped(bh)) {
285 				ntfs_get_block(inode, iblock, bh, 0);
286 				/* Unmapped? It's a hole - nothing to do. */
287 				if (!buffer_mapped(bh))
288 					continue;
289 			}
290 
291 			/* Ok, it's mapped. Make sure it's up-to-date. */
292 			if (folio_test_uptodate(folio))
293 				set_buffer_uptodate(bh);
294 			else if (bh_read(bh, 0) < 0) {
295 				err = -EIO;
296 				folio_unlock(folio);
297 				folio_put(folio);
298 				goto out;
299 			}
300 
301 			mark_buffer_dirty(bh);
302 		} while (bh_off = bh_next, iblock += 1,
303 			 head != (bh = bh->b_this_page));
304 
305 		folio_zero_segment(folio, from, to);
306 		dirty = true;
307 
308 		folio_unlock(folio);
309 		folio_put(folio);
310 		cond_resched();
311 	}
312 out:
313 	if (dirty)
314 		mark_inode_dirty(inode);
315 	return err;
316 }
317 
318 /*
319  * ntfs_file_mmap - file_operations::mmap
320  */
321 static int ntfs_file_mmap(struct file *file, struct vm_area_struct *vma)
322 {
323 	struct inode *inode = file_inode(file);
324 	struct ntfs_inode *ni = ntfs_i(inode);
325 	u64 from = ((u64)vma->vm_pgoff << PAGE_SHIFT);
326 	bool rw = vma->vm_flags & VM_WRITE;
327 	int err;
328 
329 	if (unlikely(ntfs3_forced_shutdown(inode->i_sb)))
330 		return -EIO;
331 
332 	if (is_encrypted(ni)) {
333 		ntfs_inode_warn(inode, "mmap encrypted not supported");
334 		return -EOPNOTSUPP;
335 	}
336 
337 	if (is_dedup(ni)) {
338 		ntfs_inode_warn(inode, "mmap deduplicated not supported");
339 		return -EOPNOTSUPP;
340 	}
341 
342 	if (is_compressed(ni) && rw) {
343 		ntfs_inode_warn(inode, "mmap(write) compressed not supported");
344 		return -EOPNOTSUPP;
345 	}
346 
347 	if (rw) {
348 		u64 to = min_t(loff_t, i_size_read(inode),
349 			       from + vma->vm_end - vma->vm_start);
350 
351 		if (is_sparsed(ni)) {
352 			/* Allocate clusters for rw map. */
353 			struct ntfs_sb_info *sbi = inode->i_sb->s_fs_info;
354 			CLST lcn, len;
355 			CLST vcn = from >> sbi->cluster_bits;
356 			CLST end = bytes_to_cluster(sbi, to);
357 			bool new;
358 
359 			for (; vcn < end; vcn += len) {
360 				err = attr_data_get_block(ni, vcn, 1, &lcn,
361 							  &len, &new, true);
362 				if (err)
363 					goto out;
364 			}
365 		}
366 
367 		if (ni->i_valid < to) {
368 			inode_lock(inode);
369 			err = ntfs_extend_initialized_size(file, ni,
370 							   ni->i_valid, to);
371 			inode_unlock(inode);
372 			if (err)
373 				goto out;
374 		}
375 	}
376 
377 	err = generic_file_mmap(file, vma);
378 out:
379 	return err;
380 }
381 
382 static int ntfs_extend(struct inode *inode, loff_t pos, size_t count,
383 		       struct file *file)
384 {
385 	struct ntfs_inode *ni = ntfs_i(inode);
386 	struct address_space *mapping = inode->i_mapping;
387 	loff_t end = pos + count;
388 	bool extend_init = file && pos > ni->i_valid;
389 	int err;
390 
391 	if (end <= inode->i_size && !extend_init)
392 		return 0;
393 
394 	/* Mark rw ntfs as dirty. It will be cleared at umount. */
395 	ntfs_set_state(ni->mi.sbi, NTFS_DIRTY_DIRTY);
396 
397 	if (end > inode->i_size) {
398 		err = ntfs_set_size(inode, end);
399 		if (err)
400 			goto out;
401 	}
402 
403 	if (extend_init && !is_compressed(ni)) {
404 		err = ntfs_extend_initialized_size(file, ni, ni->i_valid, pos);
405 		if (err)
406 			goto out;
407 	} else {
408 		err = 0;
409 	}
410 
411 	inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
412 	mark_inode_dirty(inode);
413 
414 	if (IS_SYNC(inode)) {
415 		int err2;
416 
417 		err = filemap_fdatawrite_range(mapping, pos, end - 1);
418 		err2 = sync_mapping_buffers(mapping);
419 		if (!err)
420 			err = err2;
421 		err2 = write_inode_now(inode, 1);
422 		if (!err)
423 			err = err2;
424 		if (!err)
425 			err = filemap_fdatawait_range(mapping, pos, end - 1);
426 	}
427 
428 out:
429 	return err;
430 }
431 
432 static int ntfs_truncate(struct inode *inode, loff_t new_size)
433 {
434 	struct super_block *sb = inode->i_sb;
435 	struct ntfs_inode *ni = ntfs_i(inode);
436 	int err, dirty = 0;
437 	u64 new_valid;
438 
439 	if (!S_ISREG(inode->i_mode))
440 		return 0;
441 
442 	if (is_compressed(ni)) {
443 		if (ni->i_valid > new_size)
444 			ni->i_valid = new_size;
445 	} else {
446 		err = block_truncate_page(inode->i_mapping, new_size,
447 					  ntfs_get_block);
448 		if (err)
449 			return err;
450 	}
451 
452 	new_valid = ntfs_up_block(sb, min_t(u64, ni->i_valid, new_size));
453 
454 	truncate_setsize(inode, new_size);
455 
456 	ni_lock(ni);
457 
458 	down_write(&ni->file.run_lock);
459 	err = attr_set_size(ni, ATTR_DATA, NULL, 0, &ni->file.run, new_size,
460 			    &new_valid, ni->mi.sbi->options->prealloc, NULL);
461 	up_write(&ni->file.run_lock);
462 
463 	if (new_valid < ni->i_valid)
464 		ni->i_valid = new_valid;
465 
466 	ni_unlock(ni);
467 
468 	ni->std_fa |= FILE_ATTRIBUTE_ARCHIVE;
469 	inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
470 	if (!IS_DIRSYNC(inode)) {
471 		dirty = 1;
472 	} else {
473 		err = ntfs_sync_inode(inode);
474 		if (err)
475 			return err;
476 	}
477 
478 	if (dirty)
479 		mark_inode_dirty(inode);
480 
481 	/*ntfs_flush_inodes(inode->i_sb, inode, NULL);*/
482 
483 	return 0;
484 }
485 
486 /*
487  * ntfs_fallocate
488  *
489  * Preallocate space for a file. This implements ntfs's fallocate file
490  * operation, which gets called from sys_fallocate system call. User
491  * space requests 'len' bytes at 'vbo'. If FALLOC_FL_KEEP_SIZE is set
492  * we just allocate clusters without zeroing them out. Otherwise we
493  * allocate and zero out clusters via an expanding truncate.
494  */
495 static long ntfs_fallocate(struct file *file, int mode, loff_t vbo, loff_t len)
496 {
497 	struct inode *inode = file_inode(file);
498 	struct address_space *mapping = inode->i_mapping;
499 	struct super_block *sb = inode->i_sb;
500 	struct ntfs_sb_info *sbi = sb->s_fs_info;
501 	struct ntfs_inode *ni = ntfs_i(inode);
502 	loff_t end = vbo + len;
503 	loff_t vbo_down = round_down(vbo, max_t(unsigned long,
504 						sbi->cluster_size, PAGE_SIZE));
505 	bool is_supported_holes = is_sparsed(ni) || is_compressed(ni);
506 	loff_t i_size, new_size;
507 	bool map_locked;
508 	int err;
509 
510 	/* No support for dir. */
511 	if (!S_ISREG(inode->i_mode))
512 		return -EOPNOTSUPP;
513 
514 	/*
515 	 * vfs_fallocate checks all possible combinations of mode.
516 	 * Do additional checks here before ntfs_set_state(dirty).
517 	 */
518 	if (mode & FALLOC_FL_PUNCH_HOLE) {
519 		if (!is_supported_holes)
520 			return -EOPNOTSUPP;
521 	} else if (mode & FALLOC_FL_COLLAPSE_RANGE) {
522 	} else if (mode & FALLOC_FL_INSERT_RANGE) {
523 		if (!is_supported_holes)
524 			return -EOPNOTSUPP;
525 	} else if (mode &
526 		   ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
527 		     FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE)) {
528 		ntfs_inode_warn(inode, "fallocate(0x%x) is not supported",
529 				mode);
530 		return -EOPNOTSUPP;
531 	}
532 
533 	ntfs_set_state(sbi, NTFS_DIRTY_DIRTY);
534 
535 	inode_lock(inode);
536 	i_size = inode->i_size;
537 	new_size = max(end, i_size);
538 	map_locked = false;
539 
540 	if (WARN_ON(ni->ni_flags & NI_FLAG_COMPRESSED_MASK)) {
541 		/* Should never be here, see ntfs_file_open. */
542 		err = -EOPNOTSUPP;
543 		goto out;
544 	}
545 
546 	if (mode & (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_COLLAPSE_RANGE |
547 		    FALLOC_FL_INSERT_RANGE)) {
548 		inode_dio_wait(inode);
549 		filemap_invalidate_lock(mapping);
550 		map_locked = true;
551 	}
552 
553 	if (mode & FALLOC_FL_PUNCH_HOLE) {
554 		u32 frame_size;
555 		loff_t mask, vbo_a, end_a, tmp;
556 
557 		err = filemap_write_and_wait_range(mapping, vbo_down,
558 						   LLONG_MAX);
559 		if (err)
560 			goto out;
561 
562 		truncate_pagecache(inode, vbo_down);
563 
564 		ni_lock(ni);
565 		err = attr_punch_hole(ni, vbo, len, &frame_size);
566 		ni_unlock(ni);
567 		if (!err)
568 			goto ok;
569 
570 		if (err != E_NTFS_NOTALIGNED)
571 			goto out;
572 
573 		/* Process not aligned punch. */
574 		err = 0;
575 		mask = frame_size - 1;
576 		vbo_a = (vbo + mask) & ~mask;
577 		end_a = end & ~mask;
578 
579 		tmp = min(vbo_a, end);
580 		if (tmp > vbo) {
581 			err = ntfs_zero_range(inode, vbo, tmp);
582 			if (err)
583 				goto out;
584 		}
585 
586 		if (vbo < end_a && end_a < end) {
587 			err = ntfs_zero_range(inode, end_a, end);
588 			if (err)
589 				goto out;
590 		}
591 
592 		/* Aligned punch_hole */
593 		if (end_a > vbo_a) {
594 			ni_lock(ni);
595 			err = attr_punch_hole(ni, vbo_a, end_a - vbo_a, NULL);
596 			ni_unlock(ni);
597 			if (err)
598 				goto out;
599 		}
600 	} else if (mode & FALLOC_FL_COLLAPSE_RANGE) {
601 		/*
602 		 * Write tail of the last page before removed range since
603 		 * it will get removed from the page cache below.
604 		 */
605 		err = filemap_write_and_wait_range(mapping, vbo_down, vbo);
606 		if (err)
607 			goto out;
608 
609 		/*
610 		 * Write data that will be shifted to preserve them
611 		 * when discarding page cache below.
612 		 */
613 		err = filemap_write_and_wait_range(mapping, end, LLONG_MAX);
614 		if (err)
615 			goto out;
616 
617 		truncate_pagecache(inode, vbo_down);
618 
619 		ni_lock(ni);
620 		err = attr_collapse_range(ni, vbo, len);
621 		ni_unlock(ni);
622 	} else if (mode & FALLOC_FL_INSERT_RANGE) {
623 		/* Check new size. */
624 		err = inode_newsize_ok(inode, new_size);
625 		if (err)
626 			goto out;
627 
628 		/* Write out all dirty pages. */
629 		err = filemap_write_and_wait_range(mapping, vbo_down,
630 						   LLONG_MAX);
631 		if (err)
632 			goto out;
633 		truncate_pagecache(inode, vbo_down);
634 
635 		ni_lock(ni);
636 		err = attr_insert_range(ni, vbo, len);
637 		ni_unlock(ni);
638 		if (err)
639 			goto out;
640 	} else {
641 		/* Check new size. */
642 		u8 cluster_bits = sbi->cluster_bits;
643 
644 		/* Be sure file is non resident. */
645 		if (is_resident(ni)) {
646 			ni_lock(ni);
647 			err = attr_force_nonresident(ni);
648 			ni_unlock(ni);
649 			if (err)
650 				goto out;
651 		}
652 
653 		/* generic/213: expected -ENOSPC instead of -EFBIG. */
654 		if (!is_supported_holes) {
655 			loff_t to_alloc = new_size - inode_get_bytes(inode);
656 
657 			if (to_alloc > 0 &&
658 			    (to_alloc >> cluster_bits) >
659 				    wnd_zeroes(&sbi->used.bitmap)) {
660 				err = -ENOSPC;
661 				goto out;
662 			}
663 		}
664 
665 		err = inode_newsize_ok(inode, new_size);
666 		if (err)
667 			goto out;
668 
669 		if (new_size > i_size) {
670 			/*
671 			 * Allocate clusters, do not change 'valid' size.
672 			 */
673 			err = ntfs_set_size(inode, new_size);
674 			if (err)
675 				goto out;
676 		}
677 
678 		if (is_supported_holes) {
679 			CLST vcn = vbo >> cluster_bits;
680 			CLST cend = bytes_to_cluster(sbi, end);
681 			CLST cend_v = bytes_to_cluster(sbi, ni->i_valid);
682 			CLST lcn, clen;
683 			bool new;
684 
685 			if (cend_v > cend)
686 				cend_v = cend;
687 
688 			/*
689 			 * Allocate and zero new clusters.
690 			 * Zeroing these clusters may be too long.
691 			 */
692 			for (; vcn < cend_v; vcn += clen) {
693 				err = attr_data_get_block(ni, vcn, cend_v - vcn,
694 							  &lcn, &clen, &new,
695 							  true);
696 				if (err)
697 					goto out;
698 			}
699 			/*
700 			 * Allocate but not zero new clusters.
701 			 */
702 			for (; vcn < cend; vcn += clen) {
703 				err = attr_data_get_block(ni, vcn, cend - vcn,
704 							  &lcn, &clen, &new,
705 							  false);
706 				if (err)
707 					goto out;
708 			}
709 		}
710 
711 		if (mode & FALLOC_FL_KEEP_SIZE) {
712 			ni_lock(ni);
713 			/* True - Keep preallocated. */
714 			err = attr_set_size(ni, ATTR_DATA, NULL, 0,
715 					    &ni->file.run, i_size, &ni->i_valid,
716 					    true, NULL);
717 			ni_unlock(ni);
718 			if (err)
719 				goto out;
720 		} else if (new_size > i_size) {
721 			i_size_write(inode, new_size);
722 		}
723 	}
724 
725 ok:
726 	err = file_modified(file);
727 	if (err)
728 		goto out;
729 
730 out:
731 	if (map_locked)
732 		filemap_invalidate_unlock(mapping);
733 
734 	if (!err) {
735 		inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
736 		mark_inode_dirty(inode);
737 	}
738 
739 	inode_unlock(inode);
740 	return err;
741 }
742 
743 /*
744  * ntfs3_setattr - inode_operations::setattr
745  */
746 int ntfs3_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
747 		  struct iattr *attr)
748 {
749 	struct inode *inode = d_inode(dentry);
750 	struct ntfs_inode *ni = ntfs_i(inode);
751 	u32 ia_valid = attr->ia_valid;
752 	umode_t mode = inode->i_mode;
753 	int err;
754 
755 	if (unlikely(ntfs3_forced_shutdown(inode->i_sb)))
756 		return -EIO;
757 
758 	err = setattr_prepare(idmap, dentry, attr);
759 	if (err)
760 		goto out;
761 
762 	if (ia_valid & ATTR_SIZE) {
763 		loff_t newsize, oldsize;
764 
765 		if (WARN_ON(ni->ni_flags & NI_FLAG_COMPRESSED_MASK)) {
766 			/* Should never be here, see ntfs_file_open(). */
767 			err = -EOPNOTSUPP;
768 			goto out;
769 		}
770 		inode_dio_wait(inode);
771 		oldsize = i_size_read(inode);
772 		newsize = attr->ia_size;
773 
774 		if (newsize <= oldsize)
775 			err = ntfs_truncate(inode, newsize);
776 		else
777 			err = ntfs_extend(inode, newsize, 0, NULL);
778 
779 		if (err)
780 			goto out;
781 
782 		ni->ni_flags |= NI_FLAG_UPDATE_PARENT;
783 		i_size_write(inode, newsize);
784 	}
785 
786 	setattr_copy(idmap, inode, attr);
787 
788 	if (mode != inode->i_mode) {
789 		err = ntfs_acl_chmod(idmap, dentry);
790 		if (err)
791 			goto out;
792 
793 		/* Linux 'w' -> Windows 'ro'. */
794 		if (0222 & inode->i_mode)
795 			ni->std_fa &= ~FILE_ATTRIBUTE_READONLY;
796 		else
797 			ni->std_fa |= FILE_ATTRIBUTE_READONLY;
798 	}
799 
800 	if (ia_valid & (ATTR_UID | ATTR_GID | ATTR_MODE))
801 		ntfs_save_wsl_perm(inode, NULL);
802 	mark_inode_dirty(inode);
803 out:
804 	return err;
805 }
806 
807 static ssize_t ntfs_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
808 {
809 	struct file *file = iocb->ki_filp;
810 	struct inode *inode = file_inode(file);
811 	struct ntfs_inode *ni = ntfs_i(inode);
812 
813 	if (unlikely(ntfs3_forced_shutdown(inode->i_sb)))
814 		return -EIO;
815 
816 	if (is_encrypted(ni)) {
817 		ntfs_inode_warn(inode, "encrypted i/o not supported");
818 		return -EOPNOTSUPP;
819 	}
820 
821 	if (is_compressed(ni) && (iocb->ki_flags & IOCB_DIRECT)) {
822 		ntfs_inode_warn(inode, "direct i/o + compressed not supported");
823 		return -EOPNOTSUPP;
824 	}
825 
826 #ifndef CONFIG_NTFS3_LZX_XPRESS
827 	if (ni->ni_flags & NI_FLAG_COMPRESSED_MASK) {
828 		ntfs_inode_warn(
829 			inode,
830 			"activate CONFIG_NTFS3_LZX_XPRESS to read external compressed files");
831 		return -EOPNOTSUPP;
832 	}
833 #endif
834 
835 	if (is_dedup(ni)) {
836 		ntfs_inode_warn(inode, "read deduplicated not supported");
837 		return -EOPNOTSUPP;
838 	}
839 
840 	return generic_file_read_iter(iocb, iter);
841 }
842 
843 static ssize_t ntfs_file_splice_read(struct file *in, loff_t *ppos,
844 				     struct pipe_inode_info *pipe, size_t len,
845 				     unsigned int flags)
846 {
847 	struct inode *inode = file_inode(in);
848 	struct ntfs_inode *ni = ntfs_i(inode);
849 
850 	if (unlikely(ntfs3_forced_shutdown(inode->i_sb)))
851 		return -EIO;
852 
853 	if (is_encrypted(ni)) {
854 		ntfs_inode_warn(inode, "encrypted i/o not supported");
855 		return -EOPNOTSUPP;
856 	}
857 
858 #ifndef CONFIG_NTFS3_LZX_XPRESS
859 	if (ni->ni_flags & NI_FLAG_COMPRESSED_MASK) {
860 		ntfs_inode_warn(
861 			inode,
862 			"activate CONFIG_NTFS3_LZX_XPRESS to read external compressed files");
863 		return -EOPNOTSUPP;
864 	}
865 #endif
866 
867 	if (is_dedup(ni)) {
868 		ntfs_inode_warn(inode, "read deduplicated not supported");
869 		return -EOPNOTSUPP;
870 	}
871 
872 	return filemap_splice_read(in, ppos, pipe, len, flags);
873 }
874 
875 /*
876  * ntfs_get_frame_pages
877  *
878  * Return: Array of locked pages.
879  */
880 static int ntfs_get_frame_pages(struct address_space *mapping, pgoff_t index,
881 				struct page **pages, u32 pages_per_frame,
882 				bool *frame_uptodate)
883 {
884 	gfp_t gfp_mask = mapping_gfp_mask(mapping);
885 	u32 npages;
886 
887 	*frame_uptodate = true;
888 
889 	for (npages = 0; npages < pages_per_frame; npages++, index++) {
890 		struct folio *folio;
891 
892 		folio = __filemap_get_folio(mapping, index,
893 					    FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
894 					    gfp_mask);
895 		if (IS_ERR(folio)) {
896 			while (npages--) {
897 				folio = page_folio(pages[npages]);
898 				folio_unlock(folio);
899 				folio_put(folio);
900 			}
901 
902 			return -ENOMEM;
903 		}
904 
905 		if (!folio_test_uptodate(folio))
906 			*frame_uptodate = false;
907 
908 		pages[npages] = &folio->page;
909 	}
910 
911 	return 0;
912 }
913 
914 /*
915  * ntfs_compress_write - Helper for ntfs_file_write_iter() (compressed files).
916  */
917 static ssize_t ntfs_compress_write(struct kiocb *iocb, struct iov_iter *from)
918 {
919 	int err;
920 	struct file *file = iocb->ki_filp;
921 	size_t count = iov_iter_count(from);
922 	loff_t pos = iocb->ki_pos;
923 	struct inode *inode = file_inode(file);
924 	loff_t i_size = i_size_read(inode);
925 	struct address_space *mapping = inode->i_mapping;
926 	struct ntfs_inode *ni = ntfs_i(inode);
927 	u64 valid = ni->i_valid;
928 	struct ntfs_sb_info *sbi = ni->mi.sbi;
929 	struct page *page, **pages = NULL;
930 	size_t written = 0;
931 	u8 frame_bits = NTFS_LZNT_CUNIT + sbi->cluster_bits;
932 	u32 frame_size = 1u << frame_bits;
933 	u32 pages_per_frame = frame_size >> PAGE_SHIFT;
934 	u32 ip, off;
935 	CLST frame;
936 	u64 frame_vbo;
937 	pgoff_t index;
938 	bool frame_uptodate;
939 
940 	if (frame_size < PAGE_SIZE) {
941 		/*
942 		 * frame_size == 8K if cluster 512
943 		 * frame_size == 64K if cluster 4096
944 		 */
945 		ntfs_inode_warn(inode, "page size is bigger than frame size");
946 		return -EOPNOTSUPP;
947 	}
948 
949 	pages = kmalloc_array(pages_per_frame, sizeof(struct page *), GFP_NOFS);
950 	if (!pages)
951 		return -ENOMEM;
952 
953 	err = file_remove_privs(file);
954 	if (err)
955 		goto out;
956 
957 	err = file_update_time(file);
958 	if (err)
959 		goto out;
960 
961 	/* Zero range [valid : pos). */
962 	while (valid < pos) {
963 		CLST lcn, clen;
964 
965 		frame = valid >> frame_bits;
966 		frame_vbo = valid & ~(frame_size - 1);
967 		off = valid & (frame_size - 1);
968 
969 		err = attr_data_get_block(ni, frame << NTFS_LZNT_CUNIT, 1, &lcn,
970 					  &clen, NULL, false);
971 		if (err)
972 			goto out;
973 
974 		if (lcn == SPARSE_LCN) {
975 			ni->i_valid = valid =
976 				frame_vbo + ((u64)clen << sbi->cluster_bits);
977 			continue;
978 		}
979 
980 		/* Load full frame. */
981 		err = ntfs_get_frame_pages(mapping, frame_vbo >> PAGE_SHIFT,
982 					   pages, pages_per_frame,
983 					   &frame_uptodate);
984 		if (err)
985 			goto out;
986 
987 		if (!frame_uptodate && off) {
988 			err = ni_read_frame(ni, frame_vbo, pages,
989 					    pages_per_frame);
990 			if (err) {
991 				for (ip = 0; ip < pages_per_frame; ip++) {
992 					page = pages[ip];
993 					unlock_page(page);
994 					put_page(page);
995 				}
996 				goto out;
997 			}
998 		}
999 
1000 		ip = off >> PAGE_SHIFT;
1001 		off = offset_in_page(valid);
1002 		for (; ip < pages_per_frame; ip++, off = 0) {
1003 			page = pages[ip];
1004 			zero_user_segment(page, off, PAGE_SIZE);
1005 			flush_dcache_page(page);
1006 			SetPageUptodate(page);
1007 		}
1008 
1009 		ni_lock(ni);
1010 		err = ni_write_frame(ni, pages, pages_per_frame);
1011 		ni_unlock(ni);
1012 
1013 		for (ip = 0; ip < pages_per_frame; ip++) {
1014 			page = pages[ip];
1015 			SetPageUptodate(page);
1016 			unlock_page(page);
1017 			put_page(page);
1018 		}
1019 
1020 		if (err)
1021 			goto out;
1022 
1023 		ni->i_valid = valid = frame_vbo + frame_size;
1024 	}
1025 
1026 	/* Copy user data [pos : pos + count). */
1027 	while (count) {
1028 		size_t copied, bytes;
1029 
1030 		off = pos & (frame_size - 1);
1031 		bytes = frame_size - off;
1032 		if (bytes > count)
1033 			bytes = count;
1034 
1035 		frame_vbo = pos & ~(frame_size - 1);
1036 		index = frame_vbo >> PAGE_SHIFT;
1037 
1038 		if (unlikely(fault_in_iov_iter_readable(from, bytes))) {
1039 			err = -EFAULT;
1040 			goto out;
1041 		}
1042 
1043 		/* Load full frame. */
1044 		err = ntfs_get_frame_pages(mapping, index, pages,
1045 					   pages_per_frame, &frame_uptodate);
1046 		if (err)
1047 			goto out;
1048 
1049 		if (!frame_uptodate) {
1050 			loff_t to = pos + bytes;
1051 
1052 			if (off || (to < i_size && (to & (frame_size - 1)))) {
1053 				err = ni_read_frame(ni, frame_vbo, pages,
1054 						    pages_per_frame);
1055 				if (err) {
1056 					for (ip = 0; ip < pages_per_frame;
1057 					     ip++) {
1058 						page = pages[ip];
1059 						unlock_page(page);
1060 						put_page(page);
1061 					}
1062 					goto out;
1063 				}
1064 			}
1065 		}
1066 
1067 		WARN_ON(!bytes);
1068 		copied = 0;
1069 		ip = off >> PAGE_SHIFT;
1070 		off = offset_in_page(pos);
1071 
1072 		/* Copy user data to pages. */
1073 		for (;;) {
1074 			size_t cp, tail = PAGE_SIZE - off;
1075 
1076 			page = pages[ip];
1077 			cp = copy_page_from_iter_atomic(page, off,
1078 							min(tail, bytes), from);
1079 			flush_dcache_page(page);
1080 
1081 			copied += cp;
1082 			bytes -= cp;
1083 			if (!bytes || !cp)
1084 				break;
1085 
1086 			if (cp < tail) {
1087 				off += cp;
1088 			} else {
1089 				ip++;
1090 				off = 0;
1091 			}
1092 		}
1093 
1094 		ni_lock(ni);
1095 		err = ni_write_frame(ni, pages, pages_per_frame);
1096 		ni_unlock(ni);
1097 
1098 		for (ip = 0; ip < pages_per_frame; ip++) {
1099 			page = pages[ip];
1100 			ClearPageDirty(page);
1101 			SetPageUptodate(page);
1102 			unlock_page(page);
1103 			put_page(page);
1104 		}
1105 
1106 		if (err)
1107 			goto out;
1108 
1109 		/*
1110 		 * We can loop for a long time in here. Be nice and allow
1111 		 * us to schedule out to avoid softlocking if preempt
1112 		 * is disabled.
1113 		 */
1114 		cond_resched();
1115 
1116 		pos += copied;
1117 		written += copied;
1118 
1119 		count = iov_iter_count(from);
1120 	}
1121 
1122 out:
1123 	kfree(pages);
1124 
1125 	if (err < 0)
1126 		return err;
1127 
1128 	iocb->ki_pos += written;
1129 	if (iocb->ki_pos > ni->i_valid)
1130 		ni->i_valid = iocb->ki_pos;
1131 	if (iocb->ki_pos > i_size)
1132 		i_size_write(inode, iocb->ki_pos);
1133 
1134 	return written;
1135 }
1136 
1137 /*
1138  * ntfs_file_write_iter - file_operations::write_iter
1139  */
1140 static ssize_t ntfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
1141 {
1142 	struct file *file = iocb->ki_filp;
1143 	struct inode *inode = file_inode(file);
1144 	ssize_t ret;
1145 	int err;
1146 	struct ntfs_inode *ni = ntfs_i(inode);
1147 
1148 	if (unlikely(ntfs3_forced_shutdown(inode->i_sb)))
1149 		return -EIO;
1150 
1151 	if (is_encrypted(ni)) {
1152 		ntfs_inode_warn(inode, "encrypted i/o not supported");
1153 		return -EOPNOTSUPP;
1154 	}
1155 
1156 	if (is_compressed(ni) && (iocb->ki_flags & IOCB_DIRECT)) {
1157 		ntfs_inode_warn(inode, "direct i/o + compressed not supported");
1158 		return -EOPNOTSUPP;
1159 	}
1160 
1161 	if (is_dedup(ni)) {
1162 		ntfs_inode_warn(inode, "write into deduplicated not supported");
1163 		return -EOPNOTSUPP;
1164 	}
1165 
1166 	if (!inode_trylock(inode)) {
1167 		if (iocb->ki_flags & IOCB_NOWAIT)
1168 			return -EAGAIN;
1169 		inode_lock(inode);
1170 	}
1171 
1172 	ret = generic_write_checks(iocb, from);
1173 	if (ret <= 0)
1174 		goto out;
1175 
1176 	err = file_modified(iocb->ki_filp);
1177 	if (err) {
1178 		ret = err;
1179 		goto out;
1180 	}
1181 
1182 	if (WARN_ON(ni->ni_flags & NI_FLAG_COMPRESSED_MASK)) {
1183 		/* Should never be here, see ntfs_file_open(). */
1184 		ret = -EOPNOTSUPP;
1185 		goto out;
1186 	}
1187 
1188 	ret = ntfs_extend(inode, iocb->ki_pos, ret, file);
1189 	if (ret)
1190 		goto out;
1191 
1192 	ret = is_compressed(ni) ? ntfs_compress_write(iocb, from) :
1193 				  __generic_file_write_iter(iocb, from);
1194 
1195 out:
1196 	inode_unlock(inode);
1197 
1198 	if (ret > 0)
1199 		ret = generic_write_sync(iocb, ret);
1200 
1201 	return ret;
1202 }
1203 
1204 /*
1205  * ntfs_file_open - file_operations::open
1206  */
1207 int ntfs_file_open(struct inode *inode, struct file *file)
1208 {
1209 	struct ntfs_inode *ni = ntfs_i(inode);
1210 
1211 	if (unlikely(ntfs3_forced_shutdown(inode->i_sb)))
1212 		return -EIO;
1213 
1214 	if (unlikely((is_compressed(ni) || is_encrypted(ni)) &&
1215 		     (file->f_flags & O_DIRECT))) {
1216 		return -EOPNOTSUPP;
1217 	}
1218 
1219 	/* Decompress "external compressed" file if opened for rw. */
1220 	if ((ni->ni_flags & NI_FLAG_COMPRESSED_MASK) &&
1221 	    (file->f_flags & (O_WRONLY | O_RDWR | O_TRUNC))) {
1222 #ifdef CONFIG_NTFS3_LZX_XPRESS
1223 		int err = ni_decompress_file(ni);
1224 
1225 		if (err)
1226 			return err;
1227 #else
1228 		ntfs_inode_warn(
1229 			inode,
1230 			"activate CONFIG_NTFS3_LZX_XPRESS to write external compressed files");
1231 		return -EOPNOTSUPP;
1232 #endif
1233 	}
1234 
1235 	return generic_file_open(inode, file);
1236 }
1237 
1238 /*
1239  * ntfs_file_release - file_operations::release
1240  */
1241 static int ntfs_file_release(struct inode *inode, struct file *file)
1242 {
1243 	struct ntfs_inode *ni = ntfs_i(inode);
1244 	struct ntfs_sb_info *sbi = ni->mi.sbi;
1245 	int err = 0;
1246 
1247 	/* If we are last writer on the inode, drop the block reservation. */
1248 	if (sbi->options->prealloc &&
1249 	    ((file->f_mode & FMODE_WRITE) &&
1250 	     atomic_read(&inode->i_writecount) == 1)) {
1251 		ni_lock(ni);
1252 		down_write(&ni->file.run_lock);
1253 
1254 		err = attr_set_size(ni, ATTR_DATA, NULL, 0, &ni->file.run,
1255 				    i_size_read(inode), &ni->i_valid, false,
1256 				    NULL);
1257 
1258 		up_write(&ni->file.run_lock);
1259 		ni_unlock(ni);
1260 	}
1261 	return err;
1262 }
1263 
1264 /*
1265  * ntfs_fiemap - inode_operations::fiemap
1266  */
1267 int ntfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
1268 		__u64 start, __u64 len)
1269 {
1270 	int err;
1271 	struct ntfs_inode *ni = ntfs_i(inode);
1272 
1273 	err = fiemap_prep(inode, fieinfo, start, &len, ~FIEMAP_FLAG_XATTR);
1274 	if (err)
1275 		return err;
1276 
1277 	ni_lock(ni);
1278 
1279 	err = ni_fiemap(ni, fieinfo, start, len);
1280 
1281 	ni_unlock(ni);
1282 
1283 	return err;
1284 }
1285 
1286 // clang-format off
1287 const struct inode_operations ntfs_file_inode_operations = {
1288 	.getattr	= ntfs_getattr,
1289 	.setattr	= ntfs3_setattr,
1290 	.listxattr	= ntfs_listxattr,
1291 	.get_acl	= ntfs_get_acl,
1292 	.set_acl	= ntfs_set_acl,
1293 	.fiemap		= ntfs_fiemap,
1294 	.fileattr_get	= ntfs_fileattr_get,
1295 	.fileattr_set	= ntfs_fileattr_set,
1296 };
1297 
1298 const struct file_operations ntfs_file_operations = {
1299 	.llseek		= generic_file_llseek,
1300 	.read_iter	= ntfs_file_read_iter,
1301 	.write_iter	= ntfs_file_write_iter,
1302 	.unlocked_ioctl = ntfs_ioctl,
1303 #ifdef CONFIG_COMPAT
1304 	.compat_ioctl	= ntfs_compat_ioctl,
1305 #endif
1306 	.splice_read	= ntfs_file_splice_read,
1307 	.mmap		= ntfs_file_mmap,
1308 	.open		= ntfs_file_open,
1309 	.fsync		= generic_file_fsync,
1310 	.splice_write	= iter_file_splice_write,
1311 	.fallocate	= ntfs_fallocate,
1312 	.release	= ntfs_file_release,
1313 };
1314 
1315 #if IS_ENABLED(CONFIG_NTFS_FS)
1316 const struct file_operations ntfs_legacy_file_operations = {
1317 	.llseek		= generic_file_llseek,
1318 	.read_iter	= ntfs_file_read_iter,
1319 	.splice_read	= ntfs_file_splice_read,
1320 	.open		= ntfs_file_open,
1321 	.release	= ntfs_file_release,
1322 };
1323 #endif
1324 // clang-format on
1325