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