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