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