xref: /linux/fs/exfat/file.c (revision bfb921b2a9d5d1123d1d10b196a39db629ddef87)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (C) 2012-2013 Samsung Electronics Co., Ltd.
4  */
5 
6 #include <linux/slab.h>
7 #include <linux/compat.h>
8 #include <linux/cred.h>
9 #include <linux/buffer_head.h>
10 #include <linux/blkdev.h>
11 #include <linux/fsnotify.h>
12 #include <linux/security.h>
13 #include <linux/msdos_fs.h>
14 #include <linux/writeback.h>
15 
16 #include "exfat_raw.h"
17 #include "exfat_fs.h"
18 
19 static int exfat_cont_expand(struct inode *inode, loff_t size)
20 {
21 	int ret;
22 	unsigned int num_clusters, new_num_clusters, last_clu;
23 	struct exfat_inode_info *ei = EXFAT_I(inode);
24 	struct super_block *sb = inode->i_sb;
25 	struct exfat_sb_info *sbi = EXFAT_SB(sb);
26 	struct exfat_chain clu;
27 
28 	ret = inode_newsize_ok(inode, size);
29 	if (ret)
30 		return ret;
31 
32 	num_clusters = EXFAT_B_TO_CLU_ROUND_UP(ei->i_size_ondisk, sbi);
33 	new_num_clusters = EXFAT_B_TO_CLU_ROUND_UP(size, sbi);
34 
35 	if (new_num_clusters == num_clusters)
36 		goto out;
37 
38 	if (num_clusters) {
39 		exfat_chain_set(&clu, ei->start_clu, num_clusters, ei->flags);
40 		ret = exfat_find_last_cluster(sb, &clu, &last_clu);
41 		if (ret)
42 			return ret;
43 
44 		clu.dir = last_clu + 1;
45 	} else {
46 		last_clu = EXFAT_EOF_CLUSTER;
47 		clu.dir = EXFAT_EOF_CLUSTER;
48 	}
49 
50 	clu.size = 0;
51 	clu.flags = ei->flags;
52 
53 	ret = exfat_alloc_cluster(inode, new_num_clusters - num_clusters,
54 			&clu, inode_needs_sync(inode));
55 	if (ret)
56 		return ret;
57 
58 	/* Append new clusters to chain */
59 	if (num_clusters) {
60 		if (clu.flags != ei->flags)
61 			if (exfat_chain_cont_cluster(sb, ei->start_clu, num_clusters))
62 				goto free_clu;
63 
64 		if (clu.flags == ALLOC_FAT_CHAIN)
65 			if (exfat_ent_set(sb, last_clu, clu.dir))
66 				goto free_clu;
67 	} else
68 		ei->start_clu = clu.dir;
69 
70 	ei->flags = clu.flags;
71 
72 out:
73 	inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
74 	/* Expanded range not zeroed, do not update valid_size */
75 	i_size_write(inode, size);
76 
77 	ei->i_size_aligned = round_up(size, sb->s_blocksize);
78 	ei->i_size_ondisk = ei->i_size_aligned;
79 	inode->i_blocks = round_up(size, sbi->cluster_size) >> 9;
80 	mark_inode_dirty(inode);
81 
82 	if (IS_SYNC(inode))
83 		return write_inode_now(inode, 1);
84 
85 	return 0;
86 
87 free_clu:
88 	exfat_free_cluster(inode, &clu);
89 	return -EIO;
90 }
91 
92 static bool exfat_allow_set_time(struct exfat_sb_info *sbi, struct inode *inode)
93 {
94 	mode_t allow_utime = sbi->options.allow_utime;
95 
96 	if (!uid_eq(current_fsuid(), inode->i_uid)) {
97 		if (in_group_p(inode->i_gid))
98 			allow_utime >>= 3;
99 		if (allow_utime & MAY_WRITE)
100 			return true;
101 	}
102 
103 	/* use a default check */
104 	return false;
105 }
106 
107 static int exfat_sanitize_mode(const struct exfat_sb_info *sbi,
108 		struct inode *inode, umode_t *mode_ptr)
109 {
110 	mode_t i_mode, mask, perm;
111 
112 	i_mode = inode->i_mode;
113 
114 	mask = (S_ISREG(i_mode) || S_ISLNK(i_mode)) ?
115 		sbi->options.fs_fmask : sbi->options.fs_dmask;
116 	perm = *mode_ptr & ~(S_IFMT | mask);
117 
118 	/* Of the r and x bits, all (subject to umask) must be present.*/
119 	if ((perm & 0555) != (i_mode & 0555))
120 		return -EPERM;
121 
122 	if (exfat_mode_can_hold_ro(inode)) {
123 		/*
124 		 * Of the w bits, either all (subject to umask) or none must
125 		 * be present.
126 		 */
127 		if ((perm & 0222) && ((perm & 0222) != (0222 & ~mask)))
128 			return -EPERM;
129 	} else {
130 		/*
131 		 * If exfat_mode_can_hold_ro(inode) is false, can't change
132 		 * w bits.
133 		 */
134 		if ((perm & 0222) != (0222 & ~mask))
135 			return -EPERM;
136 	}
137 
138 	*mode_ptr &= S_IFMT | perm;
139 
140 	return 0;
141 }
142 
143 /* resize the file length */
144 int __exfat_truncate(struct inode *inode)
145 {
146 	unsigned int num_clusters_new, num_clusters_phys;
147 	unsigned int last_clu = EXFAT_FREE_CLUSTER;
148 	struct exfat_chain clu;
149 	struct super_block *sb = inode->i_sb;
150 	struct exfat_sb_info *sbi = EXFAT_SB(sb);
151 	struct exfat_inode_info *ei = EXFAT_I(inode);
152 
153 	/* check if the given file ID is opened */
154 	if (ei->type != TYPE_FILE && ei->type != TYPE_DIR)
155 		return -EPERM;
156 
157 	exfat_set_volume_dirty(sb);
158 
159 	num_clusters_new = EXFAT_B_TO_CLU_ROUND_UP(i_size_read(inode), sbi);
160 	num_clusters_phys = EXFAT_B_TO_CLU_ROUND_UP(ei->i_size_ondisk, sbi);
161 
162 	exfat_chain_set(&clu, ei->start_clu, num_clusters_phys, ei->flags);
163 
164 	if (i_size_read(inode) > 0) {
165 		/*
166 		 * Truncate FAT chain num_clusters after the first cluster
167 		 * num_clusters = min(new, phys);
168 		 */
169 		unsigned int num_clusters =
170 			min(num_clusters_new, num_clusters_phys);
171 
172 		/*
173 		 * Follow FAT chain
174 		 * (defensive coding - works fine even with corrupted FAT table
175 		 */
176 		if (clu.flags == ALLOC_NO_FAT_CHAIN) {
177 			clu.dir += num_clusters;
178 			clu.size -= num_clusters;
179 		} else {
180 			while (num_clusters > 0) {
181 				last_clu = clu.dir;
182 				if (exfat_get_next_cluster(sb, &(clu.dir)))
183 					return -EIO;
184 
185 				num_clusters--;
186 				clu.size--;
187 			}
188 		}
189 	} else {
190 		ei->flags = ALLOC_NO_FAT_CHAIN;
191 		ei->start_clu = EXFAT_EOF_CLUSTER;
192 	}
193 
194 	if (i_size_read(inode) < ei->valid_size)
195 		ei->valid_size = i_size_read(inode);
196 
197 	if (ei->type == TYPE_FILE)
198 		ei->attr |= EXFAT_ATTR_ARCHIVE;
199 
200 	/*
201 	 * update the directory entry
202 	 *
203 	 * If the directory entry is updated by mark_inode_dirty(), the
204 	 * directory entry will be written after a writeback cycle of
205 	 * updating the bitmap/FAT, which may result in clusters being
206 	 * freed but referenced by the directory entry in the event of a
207 	 * sudden power failure.
208 	 * __exfat_write_inode() is called for directory entry, bitmap
209 	 * and FAT to be written in a same writeback.
210 	 */
211 	if (__exfat_write_inode(inode, inode_needs_sync(inode)))
212 		return -EIO;
213 
214 	/* cut off from the FAT chain */
215 	if (ei->flags == ALLOC_FAT_CHAIN && last_clu != EXFAT_FREE_CLUSTER &&
216 			last_clu != EXFAT_EOF_CLUSTER) {
217 		if (exfat_ent_set(sb, last_clu, EXFAT_EOF_CLUSTER))
218 			return -EIO;
219 	}
220 
221 	/* invalidate cache and free the clusters */
222 	/* clear exfat cache */
223 	exfat_cache_inval_inode(inode);
224 
225 	/* hint information */
226 	ei->hint_bmap.off = EXFAT_EOF_CLUSTER;
227 	ei->hint_bmap.clu = EXFAT_EOF_CLUSTER;
228 
229 	/* hint_stat will be used if this is directory. */
230 	ei->hint_stat.eidx = 0;
231 	ei->hint_stat.clu = ei->start_clu;
232 	ei->hint_femp.eidx = EXFAT_HINT_NONE;
233 
234 	/* free the clusters */
235 	if (exfat_free_cluster(inode, &clu))
236 		return -EIO;
237 
238 	return 0;
239 }
240 
241 void exfat_truncate(struct inode *inode)
242 {
243 	struct super_block *sb = inode->i_sb;
244 	struct exfat_sb_info *sbi = EXFAT_SB(sb);
245 	struct exfat_inode_info *ei = EXFAT_I(inode);
246 	unsigned int blocksize = i_blocksize(inode);
247 	loff_t aligned_size;
248 	int err;
249 
250 	mutex_lock(&sbi->s_lock);
251 	if (ei->start_clu == 0) {
252 		/*
253 		 * Empty start_clu != ~0 (not allocated)
254 		 */
255 		exfat_fs_error(sb, "tried to truncate zeroed cluster.");
256 		goto write_size;
257 	}
258 
259 	err = __exfat_truncate(inode);
260 	if (err)
261 		goto write_size;
262 
263 	inode->i_blocks = round_up(i_size_read(inode), sbi->cluster_size) >> 9;
264 write_size:
265 	aligned_size = i_size_read(inode);
266 	if (aligned_size & (blocksize - 1)) {
267 		aligned_size |= (blocksize - 1);
268 		aligned_size++;
269 	}
270 
271 	if (ei->i_size_ondisk > i_size_read(inode))
272 		ei->i_size_ondisk = aligned_size;
273 
274 	if (ei->i_size_aligned > i_size_read(inode))
275 		ei->i_size_aligned = aligned_size;
276 	mutex_unlock(&sbi->s_lock);
277 }
278 
279 int exfat_getattr(struct mnt_idmap *idmap, const struct path *path,
280 		  struct kstat *stat, unsigned int request_mask,
281 		  unsigned int query_flags)
282 {
283 	struct inode *inode = d_backing_inode(path->dentry);
284 	struct exfat_inode_info *ei = EXFAT_I(inode);
285 
286 	generic_fillattr(&nop_mnt_idmap, request_mask, inode, stat);
287 	exfat_truncate_atime(&stat->atime);
288 	stat->result_mask |= STATX_BTIME;
289 	stat->btime.tv_sec = ei->i_crtime.tv_sec;
290 	stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
291 	stat->blksize = EXFAT_SB(inode->i_sb)->cluster_size;
292 	return 0;
293 }
294 
295 int exfat_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
296 		  struct iattr *attr)
297 {
298 	struct exfat_sb_info *sbi = EXFAT_SB(dentry->d_sb);
299 	struct inode *inode = dentry->d_inode;
300 	unsigned int ia_valid;
301 	int error;
302 
303 	if ((attr->ia_valid & ATTR_SIZE) &&
304 	    attr->ia_size > i_size_read(inode)) {
305 		error = exfat_cont_expand(inode, attr->ia_size);
306 		if (error || attr->ia_valid == ATTR_SIZE)
307 			return error;
308 		attr->ia_valid &= ~ATTR_SIZE;
309 	}
310 
311 	/* Check for setting the inode time. */
312 	ia_valid = attr->ia_valid;
313 	if ((ia_valid & (ATTR_MTIME_SET | ATTR_ATIME_SET | ATTR_TIMES_SET)) &&
314 	    exfat_allow_set_time(sbi, inode)) {
315 		attr->ia_valid &= ~(ATTR_MTIME_SET | ATTR_ATIME_SET |
316 				ATTR_TIMES_SET);
317 	}
318 
319 	error = setattr_prepare(&nop_mnt_idmap, dentry, attr);
320 	attr->ia_valid = ia_valid;
321 	if (error)
322 		goto out;
323 
324 	if (((attr->ia_valid & ATTR_UID) &&
325 	     !uid_eq(attr->ia_uid, sbi->options.fs_uid)) ||
326 	    ((attr->ia_valid & ATTR_GID) &&
327 	     !gid_eq(attr->ia_gid, sbi->options.fs_gid)) ||
328 	    ((attr->ia_valid & ATTR_MODE) &&
329 	     (attr->ia_mode & ~(S_IFREG | S_IFLNK | S_IFDIR | 0777)))) {
330 		error = -EPERM;
331 		goto out;
332 	}
333 
334 	/*
335 	 * We don't return -EPERM here. Yes, strange, but this is too
336 	 * old behavior.
337 	 */
338 	if (attr->ia_valid & ATTR_MODE) {
339 		if (exfat_sanitize_mode(sbi, inode, &attr->ia_mode) < 0)
340 			attr->ia_valid &= ~ATTR_MODE;
341 	}
342 
343 	if (attr->ia_valid & ATTR_SIZE)
344 		inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
345 
346 	setattr_copy(&nop_mnt_idmap, inode, attr);
347 	exfat_truncate_inode_atime(inode);
348 
349 	if (attr->ia_valid & ATTR_SIZE) {
350 		error = exfat_block_truncate_page(inode, attr->ia_size);
351 		if (error)
352 			goto out;
353 
354 		down_write(&EXFAT_I(inode)->truncate_lock);
355 		truncate_setsize(inode, attr->ia_size);
356 
357 		/*
358 		 * __exfat_write_inode() is called from exfat_truncate(), inode
359 		 * is already written by it, so mark_inode_dirty() is unneeded.
360 		 */
361 		exfat_truncate(inode);
362 		up_write(&EXFAT_I(inode)->truncate_lock);
363 	} else
364 		mark_inode_dirty(inode);
365 
366 out:
367 	return error;
368 }
369 
370 /*
371  * modified ioctls from fat/file.c by Welmer Almesberger
372  */
373 static int exfat_ioctl_get_attributes(struct inode *inode, u32 __user *user_attr)
374 {
375 	u32 attr;
376 
377 	inode_lock_shared(inode);
378 	attr = exfat_make_attr(inode);
379 	inode_unlock_shared(inode);
380 
381 	return put_user(attr, user_attr);
382 }
383 
384 static int exfat_ioctl_set_attributes(struct file *file, u32 __user *user_attr)
385 {
386 	struct inode *inode = file_inode(file);
387 	struct exfat_sb_info *sbi = EXFAT_SB(inode->i_sb);
388 	int is_dir = S_ISDIR(inode->i_mode);
389 	u32 attr, oldattr;
390 	struct iattr ia;
391 	int err;
392 
393 	err = get_user(attr, user_attr);
394 	if (err)
395 		goto out;
396 
397 	err = mnt_want_write_file(file);
398 	if (err)
399 		goto out;
400 	inode_lock(inode);
401 
402 	oldattr = exfat_make_attr(inode);
403 
404 	/*
405 	 * Mask attributes so we don't set reserved fields.
406 	 */
407 	attr &= (EXFAT_ATTR_READONLY | EXFAT_ATTR_HIDDEN | EXFAT_ATTR_SYSTEM |
408 		 EXFAT_ATTR_ARCHIVE);
409 	attr |= (is_dir ? EXFAT_ATTR_SUBDIR : 0);
410 
411 	/* Equivalent to a chmod() */
412 	ia.ia_valid = ATTR_MODE | ATTR_CTIME;
413 	ia.ia_ctime = current_time(inode);
414 	if (is_dir)
415 		ia.ia_mode = exfat_make_mode(sbi, attr, 0777);
416 	else
417 		ia.ia_mode = exfat_make_mode(sbi, attr, 0666 | (inode->i_mode & 0111));
418 
419 	/* The root directory has no attributes */
420 	if (inode->i_ino == EXFAT_ROOT_INO && attr != EXFAT_ATTR_SUBDIR) {
421 		err = -EINVAL;
422 		goto out_unlock_inode;
423 	}
424 
425 	if (((attr | oldattr) & EXFAT_ATTR_SYSTEM) &&
426 	    !capable(CAP_LINUX_IMMUTABLE)) {
427 		err = -EPERM;
428 		goto out_unlock_inode;
429 	}
430 
431 	/*
432 	 * The security check is questionable...  We single
433 	 * out the RO attribute for checking by the security
434 	 * module, just because it maps to a file mode.
435 	 */
436 	err = security_inode_setattr(file_mnt_idmap(file),
437 				     file->f_path.dentry, &ia);
438 	if (err)
439 		goto out_unlock_inode;
440 
441 	/* This MUST be done before doing anything irreversible... */
442 	err = exfat_setattr(file_mnt_idmap(file), file->f_path.dentry, &ia);
443 	if (err)
444 		goto out_unlock_inode;
445 
446 	fsnotify_change(file->f_path.dentry, ia.ia_valid);
447 
448 	exfat_save_attr(inode, attr);
449 	mark_inode_dirty(inode);
450 out_unlock_inode:
451 	inode_unlock(inode);
452 	mnt_drop_write_file(file);
453 out:
454 	return err;
455 }
456 
457 static int exfat_ioctl_fitrim(struct inode *inode, unsigned long arg)
458 {
459 	struct fstrim_range range;
460 	int ret = 0;
461 
462 	if (!capable(CAP_SYS_ADMIN))
463 		return -EPERM;
464 
465 	if (!bdev_max_discard_sectors(inode->i_sb->s_bdev))
466 		return -EOPNOTSUPP;
467 
468 	if (copy_from_user(&range, (struct fstrim_range __user *)arg, sizeof(range)))
469 		return -EFAULT;
470 
471 	range.minlen = max_t(unsigned int, range.minlen,
472 				bdev_discard_granularity(inode->i_sb->s_bdev));
473 
474 	ret = exfat_trim_fs(inode, &range);
475 	if (ret < 0)
476 		return ret;
477 
478 	if (copy_to_user((struct fstrim_range __user *)arg, &range, sizeof(range)))
479 		return -EFAULT;
480 
481 	return 0;
482 }
483 
484 long exfat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
485 {
486 	struct inode *inode = file_inode(filp);
487 	u32 __user *user_attr = (u32 __user *)arg;
488 
489 	switch (cmd) {
490 	case FAT_IOCTL_GET_ATTRIBUTES:
491 		return exfat_ioctl_get_attributes(inode, user_attr);
492 	case FAT_IOCTL_SET_ATTRIBUTES:
493 		return exfat_ioctl_set_attributes(filp, user_attr);
494 	case FITRIM:
495 		return exfat_ioctl_fitrim(inode, arg);
496 	default:
497 		return -ENOTTY;
498 	}
499 }
500 
501 #ifdef CONFIG_COMPAT
502 long exfat_compat_ioctl(struct file *filp, unsigned int cmd,
503 				unsigned long arg)
504 {
505 	return exfat_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
506 }
507 #endif
508 
509 int exfat_file_fsync(struct file *filp, loff_t start, loff_t end, int datasync)
510 {
511 	struct inode *inode = filp->f_mapping->host;
512 	int err;
513 
514 	err = __generic_file_fsync(filp, start, end, datasync);
515 	if (err)
516 		return err;
517 
518 	err = sync_blockdev(inode->i_sb->s_bdev);
519 	if (err)
520 		return err;
521 
522 	return blkdev_issue_flush(inode->i_sb->s_bdev);
523 }
524 
525 static int exfat_file_zeroed_range(struct file *file, loff_t start, loff_t end)
526 {
527 	int err;
528 	struct inode *inode = file_inode(file);
529 	struct address_space *mapping = inode->i_mapping;
530 	const struct address_space_operations *ops = mapping->a_ops;
531 
532 	while (start < end) {
533 		u32 zerofrom, len;
534 		struct page *page = NULL;
535 
536 		zerofrom = start & (PAGE_SIZE - 1);
537 		len = PAGE_SIZE - zerofrom;
538 		if (start + len > end)
539 			len = end - start;
540 
541 		err = ops->write_begin(file, mapping, start, len, &page, NULL);
542 		if (err)
543 			goto out;
544 
545 		zero_user_segment(page, zerofrom, zerofrom + len);
546 
547 		err = ops->write_end(file, mapping, start, len, len, page, NULL);
548 		if (err < 0)
549 			goto out;
550 		start += len;
551 
552 		balance_dirty_pages_ratelimited(mapping);
553 		cond_resched();
554 	}
555 
556 out:
557 	return err;
558 }
559 
560 static ssize_t exfat_file_write_iter(struct kiocb *iocb, struct iov_iter *iter)
561 {
562 	ssize_t ret;
563 	struct file *file = iocb->ki_filp;
564 	struct inode *inode = file_inode(file);
565 	struct exfat_inode_info *ei = EXFAT_I(inode);
566 	loff_t pos = iocb->ki_pos;
567 	loff_t valid_size;
568 
569 	inode_lock(inode);
570 
571 	valid_size = ei->valid_size;
572 
573 	ret = generic_write_checks(iocb, iter);
574 	if (ret < 0)
575 		goto unlock;
576 
577 	if (pos > valid_size) {
578 		ret = exfat_file_zeroed_range(file, valid_size, pos);
579 		if (ret < 0 && ret != -ENOSPC) {
580 			exfat_err(inode->i_sb,
581 				"write: fail to zero from %llu to %llu(%zd)",
582 				valid_size, pos, ret);
583 		}
584 		if (ret < 0)
585 			goto unlock;
586 	}
587 
588 	ret = __generic_file_write_iter(iocb, iter);
589 	if (ret < 0)
590 		goto unlock;
591 
592 	inode_unlock(inode);
593 
594 	if (pos > valid_size)
595 		pos = valid_size;
596 
597 	if (iocb_is_dsync(iocb) && iocb->ki_pos > pos) {
598 		ssize_t err = vfs_fsync_range(file, pos, iocb->ki_pos - 1,
599 				iocb->ki_flags & IOCB_SYNC);
600 		if (err < 0)
601 			return err;
602 	}
603 
604 	return ret;
605 
606 unlock:
607 	inode_unlock(inode);
608 
609 	return ret;
610 }
611 
612 static int exfat_file_mmap(struct file *file, struct vm_area_struct *vma)
613 {
614 	int ret;
615 	struct inode *inode = file_inode(file);
616 	struct exfat_inode_info *ei = EXFAT_I(inode);
617 	loff_t start = ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
618 	loff_t end = min_t(loff_t, i_size_read(inode),
619 			start + vma->vm_end - vma->vm_start);
620 
621 	if ((vma->vm_flags & VM_WRITE) && ei->valid_size < end) {
622 		ret = exfat_file_zeroed_range(file, ei->valid_size, end);
623 		if (ret < 0) {
624 			exfat_err(inode->i_sb,
625 				  "mmap: fail to zero from %llu to %llu(%d)",
626 				  start, end, ret);
627 			return ret;
628 		}
629 	}
630 
631 	return generic_file_mmap(file, vma);
632 }
633 
634 const struct file_operations exfat_file_operations = {
635 	.llseek		= generic_file_llseek,
636 	.read_iter	= generic_file_read_iter,
637 	.write_iter	= exfat_file_write_iter,
638 	.unlocked_ioctl = exfat_ioctl,
639 #ifdef CONFIG_COMPAT
640 	.compat_ioctl = exfat_compat_ioctl,
641 #endif
642 	.mmap		= exfat_file_mmap,
643 	.fsync		= exfat_file_fsync,
644 	.splice_read	= filemap_splice_read,
645 	.splice_write	= iter_file_splice_write,
646 };
647 
648 const struct inode_operations exfat_file_inode_operations = {
649 	.setattr     = exfat_setattr,
650 	.getattr     = exfat_getattr,
651 };
652