1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 *  linux/fs/fat/misc.c
4 *
5 *  Written 1992,1993 by Werner Almesberger
6 *  22/11/2000 - Fixed fat_date_unix2dos for dates earlier than 01/01/1980
7 *		 and date_dos2unix for date==0 by Igor Zhbanov(bsg@uniyar.ac.ru)
8 */
9
10#include "fat.h"
11#include <linux/iversion.h>
12
13/*
14 * fat_fs_error reports a file system problem that might indicate fa data
15 * corruption/inconsistency. Depending on 'errors' mount option the
16 * panic() is called, or error message is printed FAT and nothing is done,
17 * or filesystem is remounted read-only (default behavior).
18 * In case the file system is remounted read-only, it can be made writable
19 * again by remounting it.
20 */
21void __fat_fs_error(struct super_block *sb, int report, const char *fmt, ...)
22{
23	struct fat_mount_options *opts = &MSDOS_SB(sb)->options;
24	va_list args;
25	struct va_format vaf;
26
27	if (report) {
28		va_start(args, fmt);
29		vaf.fmt = fmt;
30		vaf.va = &args;
31		fat_msg(sb, KERN_ERR, "error, %pV", &vaf);
32		va_end(args);
33	}
34
35	if (opts->errors == FAT_ERRORS_PANIC)
36		panic("FAT-fs (%s): fs panic from previous error\n", sb->s_id);
37	else if (opts->errors == FAT_ERRORS_RO && !sb_rdonly(sb)) {
38		sb->s_flags |= SB_RDONLY;
39		fat_msg(sb, KERN_ERR, "Filesystem has been set read-only");
40	}
41}
42EXPORT_SYMBOL_GPL(__fat_fs_error);
43
44/**
45 * _fat_msg() - Print a preformatted FAT message based on a superblock.
46 * @sb: A pointer to a &struct super_block
47 * @level: A Kernel printk level constant
48 * @fmt: The printf-style format string to print.
49 *
50 * Everything that is not fat_fs_error() should be fat_msg().
51 *
52 * fat_msg() wraps _fat_msg() for printk indexing.
53 */
54void _fat_msg(struct super_block *sb, const char *level, const char *fmt, ...)
55{
56	struct va_format vaf;
57	va_list args;
58
59	va_start(args, fmt);
60	vaf.fmt = fmt;
61	vaf.va = &args;
62	_printk(FAT_PRINTK_PREFIX "%pV\n", level, sb->s_id, &vaf);
63	va_end(args);
64}
65
66/* Flushes the number of free clusters on FAT32 */
67/* XXX: Need to write one per FSINFO block.  Currently only writes 1 */
68int fat_clusters_flush(struct super_block *sb)
69{
70	struct msdos_sb_info *sbi = MSDOS_SB(sb);
71	struct buffer_head *bh;
72	struct fat_boot_fsinfo *fsinfo;
73
74	if (!is_fat32(sbi))
75		return 0;
76
77	bh = sb_bread(sb, sbi->fsinfo_sector);
78	if (bh == NULL) {
79		fat_msg(sb, KERN_ERR, "bread failed in fat_clusters_flush");
80		return -EIO;
81	}
82
83	fsinfo = (struct fat_boot_fsinfo *)bh->b_data;
84	/* Sanity check */
85	if (!IS_FSINFO(fsinfo)) {
86		fat_msg(sb, KERN_ERR, "Invalid FSINFO signature: "
87		       "0x%08x, 0x%08x (sector = %lu)",
88		       le32_to_cpu(fsinfo->signature1),
89		       le32_to_cpu(fsinfo->signature2),
90		       sbi->fsinfo_sector);
91	} else {
92		if (sbi->free_clusters != -1)
93			fsinfo->free_clusters = cpu_to_le32(sbi->free_clusters);
94		if (sbi->prev_free != -1)
95			fsinfo->next_cluster = cpu_to_le32(sbi->prev_free);
96		mark_buffer_dirty(bh);
97	}
98	brelse(bh);
99
100	return 0;
101}
102
103/*
104 * fat_chain_add() adds a new cluster to the chain of clusters represented
105 * by inode.
106 */
107int fat_chain_add(struct inode *inode, int new_dclus, int nr_cluster)
108{
109	struct super_block *sb = inode->i_sb;
110	struct msdos_sb_info *sbi = MSDOS_SB(sb);
111	int ret, new_fclus, last;
112
113	/*
114	 * We must locate the last cluster of the file to add this new
115	 * one (new_dclus) to the end of the link list (the FAT).
116	 */
117	last = new_fclus = 0;
118	if (MSDOS_I(inode)->i_start) {
119		int fclus, dclus;
120
121		ret = fat_get_cluster(inode, FAT_ENT_EOF, &fclus, &dclus);
122		if (ret < 0)
123			return ret;
124		new_fclus = fclus + 1;
125		last = dclus;
126	}
127
128	/* add new one to the last of the cluster chain */
129	if (last) {
130		struct fat_entry fatent;
131
132		fatent_init(&fatent);
133		ret = fat_ent_read(inode, &fatent, last);
134		if (ret >= 0) {
135			int wait = inode_needs_sync(inode);
136			ret = fat_ent_write(inode, &fatent, new_dclus, wait);
137			fatent_brelse(&fatent);
138		}
139		if (ret < 0)
140			return ret;
141		/*
142		 * FIXME:Although we can add this cache, fat_cache_add() is
143		 * assuming to be called after linear search with fat_cache_id.
144		 */
145//		fat_cache_add(inode, new_fclus, new_dclus);
146	} else {
147		MSDOS_I(inode)->i_start = new_dclus;
148		MSDOS_I(inode)->i_logstart = new_dclus;
149		/*
150		 * Since generic_write_sync() synchronizes regular files later,
151		 * we sync here only directories.
152		 */
153		if (S_ISDIR(inode->i_mode) && IS_DIRSYNC(inode)) {
154			ret = fat_sync_inode(inode);
155			if (ret)
156				return ret;
157		} else
158			mark_inode_dirty(inode);
159	}
160	if (new_fclus != (inode->i_blocks >> (sbi->cluster_bits - 9))) {
161		fat_fs_error(sb, "clusters badly computed (%d != %llu)",
162			     new_fclus,
163			     (llu)(inode->i_blocks >> (sbi->cluster_bits - 9)));
164		fat_cache_inval_inode(inode);
165	}
166	inode->i_blocks += nr_cluster << (sbi->cluster_bits - 9);
167
168	return 0;
169}
170
171/*
172 * The epoch of FAT timestamp is 1980.
173 *     :  bits :     value
174 * date:  0 -  4: day	(1 -  31)
175 * date:  5 -  8: month	(1 -  12)
176 * date:  9 - 15: year	(0 - 127) from 1980
177 * time:  0 -  4: sec	(0 -  29) 2sec counts
178 * time:  5 - 10: min	(0 -  59)
179 * time: 11 - 15: hour	(0 -  23)
180 */
181#define SECS_PER_MIN	60
182#define SECS_PER_HOUR	(60 * 60)
183#define SECS_PER_DAY	(SECS_PER_HOUR * 24)
184/* days between 1.1.70 and 1.1.80 (2 leap days) */
185#define DAYS_DELTA	(365 * 10 + 2)
186/* 120 (2100 - 1980) isn't leap year */
187#define YEAR_2100	120
188#define IS_LEAP_YEAR(y)	(!((y) & 3) && (y) != YEAR_2100)
189
190/* Linear day numbers of the respective 1sts in non-leap years. */
191static long days_in_year[] = {
192	/* Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec */
193	0,   0,  31,  59,  90, 120, 151, 181, 212, 243, 273, 304, 334, 0, 0, 0,
194};
195
196static inline int fat_tz_offset(const struct msdos_sb_info *sbi)
197{
198	return (sbi->options.tz_set ?
199	       -sbi->options.time_offset :
200	       sys_tz.tz_minuteswest) * SECS_PER_MIN;
201}
202
203/* Convert a FAT time/date pair to a UNIX date (seconds since 1 1 70). */
204void fat_time_fat2unix(struct msdos_sb_info *sbi, struct timespec64 *ts,
205		       __le16 __time, __le16 __date, u8 time_cs)
206{
207	u16 time = le16_to_cpu(__time), date = le16_to_cpu(__date);
208	time64_t second;
209	long day, leap_day, month, year;
210
211	year  = date >> 9;
212	month = max(1, (date >> 5) & 0xf);
213	day   = max(1, date & 0x1f) - 1;
214
215	leap_day = (year + 3) / 4;
216	if (year > YEAR_2100)		/* 2100 isn't leap year */
217		leap_day--;
218	if (IS_LEAP_YEAR(year) && month > 2)
219		leap_day++;
220
221	second =  (time & 0x1f) << 1;
222	second += ((time >> 5) & 0x3f) * SECS_PER_MIN;
223	second += (time >> 11) * SECS_PER_HOUR;
224	second += (time64_t)(year * 365 + leap_day
225		   + days_in_year[month] + day
226		   + DAYS_DELTA) * SECS_PER_DAY;
227
228	second += fat_tz_offset(sbi);
229
230	if (time_cs) {
231		ts->tv_sec = second + (time_cs / 100);
232		ts->tv_nsec = (time_cs % 100) * 10000000;
233	} else {
234		ts->tv_sec = second;
235		ts->tv_nsec = 0;
236	}
237}
238
239/* Export fat_time_fat2unix() for the fat_test KUnit tests. */
240EXPORT_SYMBOL_GPL(fat_time_fat2unix);
241
242/* Convert linear UNIX date to a FAT time/date pair. */
243void fat_time_unix2fat(struct msdos_sb_info *sbi, struct timespec64 *ts,
244		       __le16 *time, __le16 *date, u8 *time_cs)
245{
246	struct tm tm;
247	time64_to_tm(ts->tv_sec, -fat_tz_offset(sbi), &tm);
248
249	/*  FAT can only support year between 1980 to 2107 */
250	if (tm.tm_year < 1980 - 1900) {
251		*time = 0;
252		*date = cpu_to_le16((0 << 9) | (1 << 5) | 1);
253		if (time_cs)
254			*time_cs = 0;
255		return;
256	}
257	if (tm.tm_year > 2107 - 1900) {
258		*time = cpu_to_le16((23 << 11) | (59 << 5) | 29);
259		*date = cpu_to_le16((127 << 9) | (12 << 5) | 31);
260		if (time_cs)
261			*time_cs = 199;
262		return;
263	}
264
265	/* from 1900 -> from 1980 */
266	tm.tm_year -= 80;
267	/* 0~11 -> 1~12 */
268	tm.tm_mon++;
269	/* 0~59 -> 0~29(2sec counts) */
270	tm.tm_sec >>= 1;
271
272	*time = cpu_to_le16(tm.tm_hour << 11 | tm.tm_min << 5 | tm.tm_sec);
273	*date = cpu_to_le16(tm.tm_year << 9 | tm.tm_mon << 5 | tm.tm_mday);
274	if (time_cs)
275		*time_cs = (ts->tv_sec & 1) * 100 + ts->tv_nsec / 10000000;
276}
277EXPORT_SYMBOL_GPL(fat_time_unix2fat);
278
279static inline struct timespec64 fat_timespec64_trunc_2secs(struct timespec64 ts)
280{
281	return (struct timespec64){ ts.tv_sec & ~1ULL, 0 };
282}
283
284/*
285 * truncate atime to 24 hour granularity (00:00:00 in local timezone)
286 */
287struct timespec64 fat_truncate_atime(const struct msdos_sb_info *sbi,
288				     const struct timespec64 *ts)
289{
290	/* to localtime */
291	time64_t seconds = ts->tv_sec - fat_tz_offset(sbi);
292	s32 remainder;
293
294	div_s64_rem(seconds, SECS_PER_DAY, &remainder);
295	/* to day boundary, and back to unix time */
296	seconds = seconds + fat_tz_offset(sbi) - remainder;
297
298	return (struct timespec64){ seconds, 0 };
299}
300
301/*
302 * truncate mtime to 2 second granularity
303 */
304struct timespec64 fat_truncate_mtime(const struct msdos_sb_info *sbi,
305				     const struct timespec64 *ts)
306{
307	return fat_timespec64_trunc_2secs(*ts);
308}
309
310/*
311 * truncate the various times with appropriate granularity:
312 *   all times in root node are always 0
313 */
314int fat_truncate_time(struct inode *inode, struct timespec64 *now, int flags)
315{
316	struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb);
317	struct timespec64 ts;
318
319	if (inode->i_ino == MSDOS_ROOT_INO)
320		return 0;
321
322	if (now == NULL) {
323		now = &ts;
324		ts = current_time(inode);
325	}
326
327	if (flags & S_ATIME)
328		inode_set_atime_to_ts(inode, fat_truncate_atime(sbi, now));
329	/*
330	 * ctime and mtime share the same on-disk field, and should be
331	 * identical in memory. all mtime updates will be applied to ctime,
332	 * but ctime updates are ignored.
333	 */
334	if (flags & S_MTIME)
335		inode_set_mtime_to_ts(inode,
336				      inode_set_ctime_to_ts(inode, fat_truncate_mtime(sbi, now)));
337
338	return 0;
339}
340EXPORT_SYMBOL_GPL(fat_truncate_time);
341
342int fat_update_time(struct inode *inode, int flags)
343{
344	int dirty_flags = 0;
345
346	if (inode->i_ino == MSDOS_ROOT_INO)
347		return 0;
348
349	if (flags & (S_ATIME | S_CTIME | S_MTIME)) {
350		fat_truncate_time(inode, NULL, flags);
351		if (inode->i_sb->s_flags & SB_LAZYTIME)
352			dirty_flags |= I_DIRTY_TIME;
353		else
354			dirty_flags |= I_DIRTY_SYNC;
355	}
356
357	__mark_inode_dirty(inode, dirty_flags);
358	return 0;
359}
360EXPORT_SYMBOL_GPL(fat_update_time);
361
362int fat_sync_bhs(struct buffer_head **bhs, int nr_bhs)
363{
364	int i, err = 0;
365
366	for (i = 0; i < nr_bhs; i++)
367		write_dirty_buffer(bhs[i], 0);
368
369	for (i = 0; i < nr_bhs; i++) {
370		wait_on_buffer(bhs[i]);
371		if (!err && !buffer_uptodate(bhs[i]))
372			err = -EIO;
373	}
374	return err;
375}
376