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