xref: /linux/fs/fat/namei_vfat.c (revision 136114e0abf03005e182d75761ab694648e6d388)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/fs/vfat/namei.c
4  *
5  *  Written 1992,1993 by Werner Almesberger
6  *
7  *  Windows95/Windows NT compatible extended MSDOS filesystem
8  *    by Gordon Chaffee Copyright (C) 1995.  Send bug reports for the
9  *    VFAT filesystem to <chaffee@cs.berkeley.edu>.  Specify
10  *    what file operation caused you trouble and if you can duplicate
11  *    the problem, send a script that demonstrates it.
12  *
13  *  Short name translation 1999, 2001 by Wolfram Pienkoss <wp@bszh.de>
14  *
15  *  Support Multibyte characters and cleanup by
16  *				OGAWA Hirofumi <hirofumi@mail.parknet.co.jp>
17  */
18 
19 #include <linux/module.h>
20 #include <linux/ctype.h>
21 #include <linux/slab.h>
22 #include <linux/namei.h>
23 #include <linux/hex.h>
24 #include <linux/kernel.h>
25 #include <linux/iversion.h>
26 #include "fat.h"
27 
28 static inline unsigned long vfat_d_version(struct dentry *dentry)
29 {
30 	return (unsigned long) dentry->d_fsdata;
31 }
32 
33 static inline void vfat_d_version_set(struct dentry *dentry,
34 				      unsigned long version)
35 {
36 	dentry->d_fsdata = (void *) version;
37 }
38 
39 /*
40  * If new entry was created in the parent, it could create the 8.3
41  * alias (the shortname of logname).  So, the parent may have the
42  * negative-dentry which matches the created 8.3 alias.
43  *
44  * If it happened, the negative dentry isn't actually negative
45  * anymore.  So, drop it.
46  */
47 static bool vfat_revalidate_shortname(struct dentry *dentry, struct inode *dir)
48 {
49 	return inode_eq_iversion(dir, vfat_d_version(dentry));
50 }
51 
52 static int vfat_revalidate(struct inode *dir, const struct qstr *name,
53 			   struct dentry *dentry, unsigned int flags)
54 {
55 	if (flags & LOOKUP_RCU)
56 		return -ECHILD;
57 
58 	/* This is not negative dentry. Always valid. */
59 	if (d_really_is_positive(dentry))
60 		return 1;
61 	return vfat_revalidate_shortname(dentry, dir);
62 }
63 
64 static int vfat_revalidate_ci(struct inode *dir, const struct qstr *name,
65 			      struct dentry *dentry, unsigned int flags)
66 {
67 	if (flags & LOOKUP_RCU)
68 		return -ECHILD;
69 
70 	/*
71 	 * This is not negative dentry. Always valid.
72 	 *
73 	 * Note, rename() to existing directory entry will have ->d_inode,
74 	 * and will use existing name which isn't specified name by user.
75 	 *
76 	 * We may be able to drop this positive dentry here. But dropping
77 	 * positive dentry isn't good idea. So it's unsupported like
78 	 * rename("filename", "FILENAME") for now.
79 	 */
80 	if (d_really_is_positive(dentry))
81 		return 1;
82 
83 	/*
84 	 * This may be nfsd (or something), anyway, we can't see the
85 	 * intent of this. So, since this can be for creation, drop it.
86 	 */
87 	if (!flags)
88 		return 0;
89 
90 	/*
91 	 * Drop the negative dentry, in order to make sure to use the
92 	 * case sensitive name which is specified by user if this is
93 	 * for creation.
94 	 */
95 	if (flags & (LOOKUP_CREATE | LOOKUP_RENAME_TARGET))
96 		return 0;
97 
98 	return vfat_revalidate_shortname(dentry, dir);
99 }
100 
101 /* returns the length of a struct qstr, ignoring trailing dots */
102 static unsigned int __vfat_striptail_len(unsigned int len, const char *name)
103 {
104 	while (len && name[len - 1] == '.')
105 		len--;
106 	return len;
107 }
108 
109 static unsigned int vfat_striptail_len(const struct qstr *qstr)
110 {
111 	return __vfat_striptail_len(qstr->len, qstr->name);
112 }
113 
114 /*
115  * Compute the hash for the vfat name corresponding to the dentry.
116  * Note: if the name is invalid, we leave the hash code unchanged so
117  * that the existing dentry can be used. The vfat fs routines will
118  * return ENOENT or EINVAL as appropriate.
119  */
120 static int vfat_hash(const struct dentry *dentry, struct qstr *qstr)
121 {
122 	qstr->hash = full_name_hash(dentry, qstr->name, vfat_striptail_len(qstr));
123 	return 0;
124 }
125 
126 /*
127  * Compute the hash for the vfat name corresponding to the dentry.
128  * Note: if the name is invalid, we leave the hash code unchanged so
129  * that the existing dentry can be used. The vfat fs routines will
130  * return ENOENT or EINVAL as appropriate.
131  */
132 static int vfat_hashi(const struct dentry *dentry, struct qstr *qstr)
133 {
134 	struct nls_table *t = MSDOS_SB(dentry->d_sb)->nls_io;
135 	const unsigned char *name;
136 	unsigned int len;
137 	unsigned long hash;
138 
139 	name = qstr->name;
140 	len = vfat_striptail_len(qstr);
141 
142 	hash = init_name_hash(dentry);
143 	while (len--)
144 		hash = partial_name_hash(nls_tolower(t, *name++), hash);
145 	qstr->hash = end_name_hash(hash);
146 
147 	return 0;
148 }
149 
150 /*
151  * Case insensitive compare of two vfat names.
152  */
153 static int vfat_cmpi(const struct dentry *dentry,
154 		unsigned int len, const char *str, const struct qstr *name)
155 {
156 	struct nls_table *t = MSDOS_SB(dentry->d_sb)->nls_io;
157 	unsigned int alen, blen;
158 
159 	/* A filename cannot end in '.' or we treat it like it has none */
160 	alen = vfat_striptail_len(name);
161 	blen = __vfat_striptail_len(len, str);
162 	if (alen == blen) {
163 		if (nls_strnicmp(t, name->name, str, alen) == 0)
164 			return 0;
165 	}
166 	return 1;
167 }
168 
169 /*
170  * Case sensitive compare of two vfat names.
171  */
172 static int vfat_cmp(const struct dentry *dentry,
173 		unsigned int len, const char *str, const struct qstr *name)
174 {
175 	unsigned int alen, blen;
176 
177 	/* A filename cannot end in '.' or we treat it like it has none */
178 	alen = vfat_striptail_len(name);
179 	blen = __vfat_striptail_len(len, str);
180 	if (alen == blen) {
181 		if (strncmp(name->name, str, alen) == 0)
182 			return 0;
183 	}
184 	return 1;
185 }
186 
187 static const struct dentry_operations vfat_ci_dentry_ops = {
188 	.d_revalidate	= vfat_revalidate_ci,
189 	.d_hash		= vfat_hashi,
190 	.d_compare	= vfat_cmpi,
191 };
192 
193 static const struct dentry_operations vfat_dentry_ops = {
194 	.d_revalidate	= vfat_revalidate,
195 	.d_hash		= vfat_hash,
196 	.d_compare	= vfat_cmp,
197 };
198 
199 /* Characters that are undesirable in an MS-DOS file name */
200 
201 static inline bool vfat_bad_char(wchar_t w)
202 {
203 	return (w < 0x0020)
204 	    || (w == '*') || (w == '?') || (w == '<') || (w == '>')
205 	    || (w == '|') || (w == '"') || (w == ':') || (w == '/')
206 	    || (w == '\\');
207 }
208 
209 static inline bool vfat_replace_char(wchar_t w)
210 {
211 	return (w == '[') || (w == ']') || (w == ';') || (w == ',')
212 	    || (w == '+') || (w == '=');
213 }
214 
215 static wchar_t vfat_skip_char(wchar_t w)
216 {
217 	return (w == '.') || (w == ' ');
218 }
219 
220 static inline int vfat_is_used_badchars(const wchar_t *s, int len)
221 {
222 	int i;
223 
224 	for (i = 0; i < len; i++)
225 		if (vfat_bad_char(s[i]))
226 			return -EINVAL;
227 
228 	if (s[i - 1] == ' ') /* last character cannot be space */
229 		return -EINVAL;
230 
231 	return 0;
232 }
233 
234 static int vfat_find_form(struct inode *dir, unsigned char *name)
235 {
236 	struct fat_slot_info sinfo;
237 	int err = fat_scan(dir, name, &sinfo);
238 	if (err)
239 		return -ENOENT;
240 	brelse(sinfo.bh);
241 	return 0;
242 }
243 
244 /*
245  * 1) Valid characters for the 8.3 format alias are any combination of
246  * letters, uppercase alphabets, digits, any of the
247  * following special characters:
248  *     $ % ' ` - @ { } ~ ! # ( ) & _ ^
249  * In this case Longfilename is not stored in disk.
250  *
251  * WinNT's Extension:
252  * File name and extension name is contain uppercase/lowercase
253  * only. And it is expressed by CASE_LOWER_BASE and CASE_LOWER_EXT.
254  *
255  * 2) File name is 8.3 format, but it contain the uppercase and
256  * lowercase char, muliti bytes char, etc. In this case numtail is not
257  * added, but Longfilename is stored.
258  *
259  * 3) When the one except for the above, or the following special
260  * character are contained:
261  *        .   [ ] ; , + =
262  * numtail is added, and Longfilename must be stored in disk .
263  */
264 struct shortname_info {
265 	unsigned char lower:1,
266 		      upper:1,
267 		      valid:1;
268 };
269 #define INIT_SHORTNAME_INFO(x)	do {		\
270 	(x)->lower = 1;				\
271 	(x)->upper = 1;				\
272 	(x)->valid = 1;				\
273 } while (0)
274 
275 static inline int to_shortname_char(struct nls_table *nls,
276 				    unsigned char *buf, int buf_size,
277 				    wchar_t *src, struct shortname_info *info)
278 {
279 	int len;
280 
281 	if (vfat_skip_char(*src)) {
282 		info->valid = 0;
283 		return 0;
284 	}
285 	if (vfat_replace_char(*src)) {
286 		info->valid = 0;
287 		buf[0] = '_';
288 		return 1;
289 	}
290 
291 	len = nls->uni2char(*src, buf, buf_size);
292 	if (len <= 0) {
293 		info->valid = 0;
294 		buf[0] = '_';
295 		len = 1;
296 	} else if (len == 1) {
297 		unsigned char prev = buf[0];
298 
299 		if (buf[0] >= 0x7F) {
300 			info->lower = 0;
301 			info->upper = 0;
302 		}
303 
304 		buf[0] = nls_toupper(nls, buf[0]);
305 		if (isalpha(buf[0])) {
306 			if (buf[0] == prev)
307 				info->lower = 0;
308 			else
309 				info->upper = 0;
310 		}
311 	} else {
312 		info->lower = 0;
313 		info->upper = 0;
314 	}
315 
316 	return len;
317 }
318 
319 /*
320  * Given a valid longname, create a unique shortname.  Make sure the
321  * shortname does not exist
322  * Returns negative number on error, 0 for a normal
323  * return, and 1 for valid shortname
324  */
325 static int vfat_create_shortname(struct inode *dir, struct nls_table *nls,
326 				 wchar_t *uname, int ulen,
327 				 unsigned char *name_res, unsigned char *lcase)
328 {
329 	struct fat_mount_options *opts = &MSDOS_SB(dir->i_sb)->options;
330 	wchar_t *ip, *ext_start, *end, *name_start;
331 	unsigned char base[9], ext[4], buf[5], *p;
332 	unsigned char charbuf[NLS_MAX_CHARSET_SIZE];
333 	int chl, chi;
334 	int sz = 0, extlen, baselen, i, numtail_baselen, numtail2_baselen;
335 	int is_shortname;
336 	struct shortname_info base_info, ext_info;
337 
338 	is_shortname = 1;
339 	INIT_SHORTNAME_INFO(&base_info);
340 	INIT_SHORTNAME_INFO(&ext_info);
341 
342 	/* Now, we need to create a shortname from the long name */
343 	ext_start = end = &uname[ulen];
344 	while (--ext_start >= uname) {
345 		if (*ext_start == 0x002E) {	/* is `.' */
346 			if (ext_start == end - 1) {
347 				sz = ulen;
348 				ext_start = NULL;
349 			}
350 			break;
351 		}
352 	}
353 
354 	if (ext_start == uname - 1) {
355 		sz = ulen;
356 		ext_start = NULL;
357 	} else if (ext_start) {
358 		/*
359 		 * Names which start with a dot could be just
360 		 * an extension eg. "...test".  In this case Win95
361 		 * uses the extension as the name and sets no extension.
362 		 */
363 		name_start = &uname[0];
364 		while (name_start < ext_start) {
365 			if (!vfat_skip_char(*name_start))
366 				break;
367 			name_start++;
368 		}
369 		if (name_start != ext_start) {
370 			sz = ext_start - uname;
371 			ext_start++;
372 		} else {
373 			sz = ulen;
374 			ext_start = NULL;
375 		}
376 	}
377 
378 	numtail_baselen = 6;
379 	numtail2_baselen = 2;
380 	for (baselen = i = 0, p = base, ip = uname; i < sz; i++, ip++) {
381 		chl = to_shortname_char(nls, charbuf, sizeof(charbuf),
382 					ip, &base_info);
383 		if (chl == 0)
384 			continue;
385 
386 		if (baselen < 2 && (baselen + chl) > 2)
387 			numtail2_baselen = baselen;
388 		if (baselen < 6 && (baselen + chl) > 6)
389 			numtail_baselen = baselen;
390 		for (chi = 0; chi < chl; chi++) {
391 			*p++ = charbuf[chi];
392 			baselen++;
393 			if (baselen >= 8)
394 				break;
395 		}
396 		if (baselen >= 8) {
397 			if ((chi < chl - 1) || (ip + 1) - uname < sz)
398 				is_shortname = 0;
399 			break;
400 		}
401 	}
402 	if (baselen == 0) {
403 		return -EINVAL;
404 	}
405 
406 	extlen = 0;
407 	if (ext_start) {
408 		for (p = ext, ip = ext_start; extlen < 3 && ip < end; ip++) {
409 			chl = to_shortname_char(nls, charbuf, sizeof(charbuf),
410 						ip, &ext_info);
411 			if (chl == 0)
412 				continue;
413 
414 			if ((extlen + chl) > 3) {
415 				is_shortname = 0;
416 				break;
417 			}
418 			for (chi = 0; chi < chl; chi++) {
419 				*p++ = charbuf[chi];
420 				extlen++;
421 			}
422 			if (extlen >= 3) {
423 				if (ip + 1 != end)
424 					is_shortname = 0;
425 				break;
426 			}
427 		}
428 	}
429 	ext[extlen] = '\0';
430 	base[baselen] = '\0';
431 
432 	/* Yes, it can happen. ".\xe5" would do it. */
433 	if (base[0] == DELETED_FLAG)
434 		base[0] = 0x05;
435 
436 	/* OK, at this point we know that base is not longer than 8 symbols,
437 	 * ext is not longer than 3, base is nonempty, both don't contain
438 	 * any bad symbols (lowercase transformed to uppercase).
439 	 */
440 
441 	memset(name_res, ' ', MSDOS_NAME);
442 	memcpy(name_res, base, baselen);
443 	memcpy(name_res + 8, ext, extlen);
444 	*lcase = 0;
445 	if (is_shortname && base_info.valid && ext_info.valid) {
446 		if (vfat_find_form(dir, name_res) == 0)
447 			return -EEXIST;
448 
449 		if (opts->shortname & VFAT_SFN_CREATE_WIN95) {
450 			return (base_info.upper && ext_info.upper);
451 		} else if (opts->shortname & VFAT_SFN_CREATE_WINNT) {
452 			if ((base_info.upper || base_info.lower) &&
453 			    (ext_info.upper || ext_info.lower)) {
454 				if (!base_info.upper && base_info.lower)
455 					*lcase |= CASE_LOWER_BASE;
456 				if (!ext_info.upper && ext_info.lower)
457 					*lcase |= CASE_LOWER_EXT;
458 				return 1;
459 			}
460 			return 0;
461 		} else {
462 			BUG();
463 		}
464 	}
465 
466 	if (opts->numtail == 0)
467 		if (vfat_find_form(dir, name_res) < 0)
468 			return 0;
469 
470 	/*
471 	 * Try to find a unique extension.  This used to
472 	 * iterate through all possibilities sequentially,
473 	 * but that gave extremely bad performance.  Windows
474 	 * only tries a few cases before using random
475 	 * values for part of the base.
476 	 */
477 
478 	if (baselen > 6) {
479 		baselen = numtail_baselen;
480 		name_res[7] = ' ';
481 	}
482 	name_res[baselen] = '~';
483 	for (i = 1; i < 10; i++) {
484 		name_res[baselen + 1] = i + '0';
485 		if (vfat_find_form(dir, name_res) < 0)
486 			return 0;
487 	}
488 
489 	i = jiffies;
490 	sz = (jiffies >> 16) & 0x7;
491 	if (baselen > 2) {
492 		baselen = numtail2_baselen;
493 		name_res[7] = ' ';
494 	}
495 	name_res[baselen + 4] = '~';
496 	name_res[baselen + 5] = '1' + sz;
497 	while (1) {
498 		snprintf(buf, sizeof(buf), "%04X", i & 0xffff);
499 		memcpy(&name_res[baselen], buf, 4);
500 		if (vfat_find_form(dir, name_res) < 0)
501 			break;
502 		i -= 11;
503 	}
504 	return 0;
505 }
506 
507 /* Translate a string, including coded sequences into Unicode */
508 static int
509 xlate_to_uni(const unsigned char *name, int len, unsigned char *outname,
510 	     int *longlen, int *outlen, int escape, int utf8,
511 	     struct nls_table *nls)
512 {
513 	const unsigned char *ip;
514 	unsigned char *op;
515 	int i, fill;
516 	int charlen;
517 
518 	if (utf8) {
519 		*outlen = utf8s_to_utf16s(name, len, UTF16_HOST_ENDIAN,
520 				(wchar_t *) outname, FAT_LFN_LEN + 2);
521 		if (*outlen < 0)
522 			return *outlen;
523 		else if (*outlen > FAT_LFN_LEN)
524 			return -ENAMETOOLONG;
525 
526 		op = &outname[*outlen * sizeof(wchar_t)];
527 	} else {
528 		for (i = 0, ip = name, op = outname, *outlen = 0;
529 			 i < len && *outlen < FAT_LFN_LEN;
530 			 *outlen += 1) {
531 			if (escape && (*ip == ':')) {
532 				u8 uc[2];
533 
534 				if (i > len - 5)
535 					return -EINVAL;
536 
537 				if (hex2bin(uc, ip + 1, 2) < 0)
538 					return -EINVAL;
539 
540 				*(wchar_t *)op = uc[0] << 8 | uc[1];
541 
542 				op += 2;
543 				ip += 5;
544 				i += 5;
545 			} else {
546 				charlen = nls->char2uni(ip, len - i,
547 							(wchar_t *)op);
548 				if (charlen < 0)
549 					return -EINVAL;
550 				ip += charlen;
551 				i += charlen;
552 				op += 2;
553 			}
554 		}
555 		if (i < len)
556 			return -ENAMETOOLONG;
557 	}
558 
559 	*longlen = *outlen;
560 	if (*outlen % 13) {
561 		*op++ = 0;
562 		*op++ = 0;
563 		*outlen += 1;
564 		if (*outlen % 13) {
565 			fill = 13 - (*outlen % 13);
566 			for (i = 0; i < fill; i++) {
567 				*op++ = 0xff;
568 				*op++ = 0xff;
569 			}
570 			*outlen += fill;
571 		}
572 	}
573 
574 	return 0;
575 }
576 
577 static int vfat_build_slots(struct inode *dir, const unsigned char *name,
578 			    int len, int is_dir, int cluster,
579 			    struct timespec64 *ts,
580 			    struct msdos_dir_slot *slots, int *nr_slots)
581 {
582 	struct msdos_sb_info *sbi = MSDOS_SB(dir->i_sb);
583 	struct fat_mount_options *opts = &sbi->options;
584 	struct msdos_dir_slot *ps;
585 	struct msdos_dir_entry *de;
586 	unsigned char cksum, lcase;
587 	unsigned char msdos_name[MSDOS_NAME];
588 	wchar_t *uname;
589 	__le16 time, date;
590 	u8 time_cs;
591 	int err, ulen, usize, i;
592 	loff_t offset;
593 
594 	*nr_slots = 0;
595 
596 	uname = __getname();
597 	if (!uname)
598 		return -ENOMEM;
599 
600 	err = xlate_to_uni(name, len, (unsigned char *)uname, &ulen, &usize,
601 			   opts->unicode_xlate, opts->utf8, sbi->nls_io);
602 	if (err)
603 		goto out_free;
604 
605 	err = vfat_is_used_badchars(uname, ulen);
606 	if (err)
607 		goto out_free;
608 
609 	err = vfat_create_shortname(dir, sbi->nls_disk, uname, ulen,
610 				    msdos_name, &lcase);
611 	if (err < 0)
612 		goto out_free;
613 	else if (err == 1) {
614 		de = (struct msdos_dir_entry *)slots;
615 		err = 0;
616 		goto shortname;
617 	}
618 
619 	/* build the entry of long file name */
620 	cksum = fat_checksum(msdos_name);
621 
622 	*nr_slots = usize / 13;
623 	for (ps = slots, i = *nr_slots; i > 0; i--, ps++) {
624 		ps->id = i;
625 		ps->attr = ATTR_EXT;
626 		ps->reserved = 0;
627 		ps->alias_checksum = cksum;
628 		ps->start = 0;
629 		offset = (i - 1) * 13;
630 		fatwchar_to16(ps->name0_4, uname + offset, 5);
631 		fatwchar_to16(ps->name5_10, uname + offset + 5, 6);
632 		fatwchar_to16(ps->name11_12, uname + offset + 11, 2);
633 	}
634 	slots[0].id |= 0x40;
635 	de = (struct msdos_dir_entry *)ps;
636 
637 shortname:
638 	/* build the entry of 8.3 alias name */
639 	(*nr_slots)++;
640 	memcpy(de->name, msdos_name, MSDOS_NAME);
641 	de->attr = is_dir ? ATTR_DIR : ATTR_ARCH;
642 	de->lcase = lcase;
643 	fat_time_unix2fat(sbi, ts, &time, &date, &time_cs);
644 	de->time = de->ctime = time;
645 	de->date = de->cdate = de->adate = date;
646 	de->ctime_cs = time_cs;
647 	fat_set_start(de, cluster);
648 	de->size = 0;
649 out_free:
650 	__putname(uname);
651 	return err;
652 }
653 
654 static int vfat_add_entry(struct inode *dir, const struct qstr *qname,
655 			  int is_dir, int cluster, struct timespec64 *ts,
656 			  struct fat_slot_info *sinfo)
657 {
658 	struct msdos_dir_slot *slots;
659 	unsigned int len;
660 	int err, nr_slots;
661 
662 	len = vfat_striptail_len(qname);
663 	if (len == 0)
664 		return -ENOENT;
665 
666 	slots = kmalloc_array(MSDOS_SLOTS, sizeof(*slots), GFP_NOFS);
667 	if (slots == NULL)
668 		return -ENOMEM;
669 
670 	err = vfat_build_slots(dir, qname->name, len, is_dir, cluster, ts,
671 			       slots, &nr_slots);
672 	if (err)
673 		goto cleanup;
674 
675 	err = fat_add_entries(dir, slots, nr_slots, sinfo);
676 	if (err)
677 		goto cleanup;
678 
679 	/* update timestamp */
680 	fat_truncate_time(dir, ts, FAT_UPDATE_CMTIME);
681 	if (IS_DIRSYNC(dir))
682 		(void)fat_sync_inode(dir);
683 	else
684 		mark_inode_dirty(dir);
685 cleanup:
686 	kfree(slots);
687 	return err;
688 }
689 
690 static int vfat_find(struct inode *dir, const struct qstr *qname,
691 		     struct fat_slot_info *sinfo)
692 {
693 	unsigned int len = vfat_striptail_len(qname);
694 	if (len == 0)
695 		return -ENOENT;
696 	return fat_search_long(dir, qname->name, len, sinfo);
697 }
698 
699 static struct dentry *vfat_lookup(struct inode *dir, struct dentry *dentry,
700 				  unsigned int flags)
701 {
702 	struct super_block *sb = dir->i_sb;
703 	struct fat_slot_info sinfo;
704 	struct inode *inode;
705 	struct dentry *alias;
706 	int err;
707 
708 	mutex_lock(&MSDOS_SB(sb)->s_lock);
709 
710 	err = vfat_find(dir, &dentry->d_name, &sinfo);
711 	if (err) {
712 		if (err == -ENOENT) {
713 			inode = NULL;
714 			goto out;
715 		}
716 		goto error;
717 	}
718 
719 	inode = fat_build_inode(sb, sinfo.de, sinfo.i_pos);
720 	brelse(sinfo.bh);
721 	if (IS_ERR(inode)) {
722 		err = PTR_ERR(inode);
723 		goto error;
724 	}
725 
726 	alias = d_find_alias(inode);
727 	/*
728 	 * Checking "alias->d_parent == dentry->d_parent" to make sure
729 	 * FS is not corrupted (especially double linked dir).
730 	 */
731 	if (alias && alias->d_parent == dentry->d_parent) {
732 		/*
733 		 * This inode has non anonymous-DCACHE_DISCONNECTED
734 		 * dentry. This means, the user did ->lookup() by an
735 		 * another name (longname vs 8.3 alias of it) in past.
736 		 *
737 		 * Switch to new one for reason of locality if possible.
738 		 */
739 		if (!S_ISDIR(inode->i_mode))
740 			d_move(alias, dentry);
741 		iput(inode);
742 		mutex_unlock(&MSDOS_SB(sb)->s_lock);
743 		return alias;
744 	} else
745 		dput(alias);
746 
747 out:
748 	mutex_unlock(&MSDOS_SB(sb)->s_lock);
749 	if (!inode)
750 		vfat_d_version_set(dentry, inode_query_iversion(dir));
751 	return d_splice_alias(inode, dentry);
752 error:
753 	mutex_unlock(&MSDOS_SB(sb)->s_lock);
754 	return ERR_PTR(err);
755 }
756 
757 static int vfat_create(struct mnt_idmap *idmap, struct inode *dir,
758 		       struct dentry *dentry, umode_t mode, bool excl)
759 {
760 	struct super_block *sb = dir->i_sb;
761 	struct inode *inode;
762 	struct fat_slot_info sinfo;
763 	struct timespec64 ts;
764 	int err;
765 
766 	mutex_lock(&MSDOS_SB(sb)->s_lock);
767 
768 	ts = current_time(dir);
769 	err = vfat_add_entry(dir, &dentry->d_name, 0, 0, &ts, &sinfo);
770 	if (err)
771 		goto out;
772 	inode_inc_iversion(dir);
773 
774 	inode = fat_build_inode(sb, sinfo.de, sinfo.i_pos);
775 	brelse(sinfo.bh);
776 	if (IS_ERR(inode)) {
777 		err = PTR_ERR(inode);
778 		goto out;
779 	}
780 	inode_inc_iversion(inode);
781 
782 	d_instantiate(dentry, inode);
783 out:
784 	mutex_unlock(&MSDOS_SB(sb)->s_lock);
785 	return err;
786 }
787 
788 static int vfat_rmdir(struct inode *dir, struct dentry *dentry)
789 {
790 	struct inode *inode = d_inode(dentry);
791 	struct super_block *sb = dir->i_sb;
792 	struct fat_slot_info sinfo;
793 	int err;
794 
795 	mutex_lock(&MSDOS_SB(sb)->s_lock);
796 
797 	err = fat_dir_empty(inode);
798 	if (err)
799 		goto out;
800 	err = vfat_find(dir, &dentry->d_name, &sinfo);
801 	if (err)
802 		goto out;
803 
804 	err = fat_remove_entries(dir, &sinfo);	/* and releases bh */
805 	if (err)
806 		goto out;
807 	if (dir->i_nlink >= 3)
808 		drop_nlink(dir);
809 	else {
810 		fat_fs_error(sb, "parent dir link count too low (%u)",
811 			dir->i_nlink);
812 	}
813 
814 	clear_nlink(inode);
815 	fat_truncate_time(inode, NULL, FAT_UPDATE_ATIME | FAT_UPDATE_CMTIME);
816 	fat_detach(inode);
817 	vfat_d_version_set(dentry, inode_query_iversion(dir));
818 out:
819 	mutex_unlock(&MSDOS_SB(sb)->s_lock);
820 
821 	return err;
822 }
823 
824 static int vfat_unlink(struct inode *dir, struct dentry *dentry)
825 {
826 	struct inode *inode = d_inode(dentry);
827 	struct super_block *sb = dir->i_sb;
828 	struct fat_slot_info sinfo;
829 	int err;
830 
831 	mutex_lock(&MSDOS_SB(sb)->s_lock);
832 
833 	err = vfat_find(dir, &dentry->d_name, &sinfo);
834 	if (err)
835 		goto out;
836 
837 	err = fat_remove_entries(dir, &sinfo);	/* and releases bh */
838 	if (err)
839 		goto out;
840 	clear_nlink(inode);
841 	fat_truncate_time(inode, NULL, FAT_UPDATE_ATIME | FAT_UPDATE_CMTIME);
842 	fat_detach(inode);
843 	vfat_d_version_set(dentry, inode_query_iversion(dir));
844 out:
845 	mutex_unlock(&MSDOS_SB(sb)->s_lock);
846 
847 	return err;
848 }
849 
850 static struct dentry *vfat_mkdir(struct mnt_idmap *idmap, struct inode *dir,
851 				  struct dentry *dentry, umode_t mode)
852 {
853 	struct super_block *sb = dir->i_sb;
854 	struct inode *inode;
855 	struct fat_slot_info sinfo;
856 	struct timespec64 ts;
857 	int err, cluster;
858 
859 	mutex_lock(&MSDOS_SB(sb)->s_lock);
860 
861 	ts = current_time(dir);
862 	cluster = fat_alloc_new_dir(dir, &ts);
863 	if (cluster < 0) {
864 		err = cluster;
865 		goto out;
866 	}
867 	err = vfat_add_entry(dir, &dentry->d_name, 1, cluster, &ts, &sinfo);
868 	if (err)
869 		goto out_free;
870 	inode_inc_iversion(dir);
871 	inc_nlink(dir);
872 
873 	inode = fat_build_inode(sb, sinfo.de, sinfo.i_pos);
874 	brelse(sinfo.bh);
875 	if (IS_ERR(inode)) {
876 		err = PTR_ERR(inode);
877 		/* the directory was completed, just return a error */
878 		goto out;
879 	}
880 	inode_inc_iversion(inode);
881 	set_nlink(inode, 2);
882 
883 	d_instantiate(dentry, inode);
884 
885 	mutex_unlock(&MSDOS_SB(sb)->s_lock);
886 	return NULL;
887 
888 out_free:
889 	fat_free_clusters(dir, cluster);
890 out:
891 	mutex_unlock(&MSDOS_SB(sb)->s_lock);
892 	return ERR_PTR(err);
893 }
894 
895 static int vfat_get_dotdot_de(struct inode *inode, struct buffer_head **bh,
896 			      struct msdos_dir_entry **de)
897 {
898 	if (S_ISDIR(inode->i_mode)) {
899 		if (fat_get_dotdot_entry(inode, bh, de))
900 			return -EIO;
901 	}
902 	return 0;
903 }
904 
905 static int vfat_sync_ipos(struct inode *dir, struct inode *inode)
906 {
907 	if (IS_DIRSYNC(dir))
908 		return fat_sync_inode(inode);
909 	mark_inode_dirty(inode);
910 	return 0;
911 }
912 
913 static int vfat_update_dotdot_de(struct inode *dir, struct inode *inode,
914 				 struct buffer_head *dotdot_bh,
915 				 struct msdos_dir_entry *dotdot_de)
916 {
917 	fat_set_start(dotdot_de, MSDOS_I(dir)->i_logstart);
918 	mark_buffer_dirty_inode(dotdot_bh, inode);
919 	if (IS_DIRSYNC(dir))
920 		return sync_dirty_buffer(dotdot_bh);
921 	return 0;
922 }
923 
924 static void vfat_update_dir_metadata(struct inode *dir, struct timespec64 *ts)
925 {
926 	inode_inc_iversion(dir);
927 	fat_truncate_time(dir, ts, FAT_UPDATE_CMTIME);
928 	if (IS_DIRSYNC(dir))
929 		(void)fat_sync_inode(dir);
930 	else
931 		mark_inode_dirty(dir);
932 }
933 
934 static int vfat_rename(struct inode *old_dir, struct dentry *old_dentry,
935 		       struct inode *new_dir, struct dentry *new_dentry)
936 {
937 	struct buffer_head *dotdot_bh;
938 	struct msdos_dir_entry *dotdot_de = NULL;
939 	struct inode *old_inode, *new_inode;
940 	struct fat_slot_info old_sinfo, sinfo;
941 	struct timespec64 ts;
942 	loff_t new_i_pos;
943 	int err, is_dir, corrupt = 0;
944 	struct super_block *sb = old_dir->i_sb;
945 
946 	old_sinfo.bh = sinfo.bh = dotdot_bh = NULL;
947 	old_inode = d_inode(old_dentry);
948 	new_inode = d_inode(new_dentry);
949 	mutex_lock(&MSDOS_SB(sb)->s_lock);
950 	err = vfat_find(old_dir, &old_dentry->d_name, &old_sinfo);
951 	if (err)
952 		goto out;
953 
954 	if (old_dir != new_dir) {
955 		err = vfat_get_dotdot_de(old_inode, &dotdot_bh, &dotdot_de);
956 		if (err)
957 			goto out;
958 	}
959 
960 	is_dir = S_ISDIR(old_inode->i_mode);
961 	ts = current_time(old_dir);
962 	if (new_inode) {
963 		if (is_dir) {
964 			err = fat_dir_empty(new_inode);
965 			if (err)
966 				goto out;
967 		}
968 		new_i_pos = MSDOS_I(new_inode)->i_pos;
969 		fat_detach(new_inode);
970 	} else {
971 		err = vfat_add_entry(new_dir, &new_dentry->d_name, is_dir, 0,
972 				     &ts, &sinfo);
973 		if (err)
974 			goto out;
975 		new_i_pos = sinfo.i_pos;
976 	}
977 	inode_inc_iversion(new_dir);
978 
979 	fat_detach(old_inode);
980 	fat_attach(old_inode, new_i_pos);
981 	err = vfat_sync_ipos(new_dir, old_inode);
982 	if (err)
983 		goto error_inode;
984 
985 	if (dotdot_de) {
986 		err = vfat_update_dotdot_de(new_dir, old_inode, dotdot_bh,
987 					    dotdot_de);
988 		if (err)
989 			goto error_dotdot;
990 		drop_nlink(old_dir);
991 		if (!new_inode)
992  			inc_nlink(new_dir);
993 	}
994 
995 	err = fat_remove_entries(old_dir, &old_sinfo);	/* and releases bh */
996 	old_sinfo.bh = NULL;
997 	if (err)
998 		goto error_dotdot;
999 	vfat_update_dir_metadata(old_dir, &ts);
1000 
1001 	if (new_inode) {
1002 		drop_nlink(new_inode);
1003 		if (is_dir)
1004 			drop_nlink(new_inode);
1005 	}
1006 out:
1007 	brelse(sinfo.bh);
1008 	brelse(dotdot_bh);
1009 	brelse(old_sinfo.bh);
1010 	mutex_unlock(&MSDOS_SB(sb)->s_lock);
1011 
1012 	return err;
1013 
1014 error_dotdot:
1015 	/* data cluster is shared, serious corruption */
1016 	corrupt = 1;
1017 
1018 	if (dotdot_de) {
1019 		corrupt |= vfat_update_dotdot_de(old_dir, old_inode, dotdot_bh,
1020 						 dotdot_de);
1021 	}
1022 error_inode:
1023 	fat_detach(old_inode);
1024 	fat_attach(old_inode, old_sinfo.i_pos);
1025 	if (new_inode) {
1026 		fat_attach(new_inode, new_i_pos);
1027 		if (corrupt)
1028 			corrupt |= fat_sync_inode(new_inode);
1029 	} else {
1030 		/*
1031 		 * If new entry was not sharing the data cluster, it
1032 		 * shouldn't be serious corruption.
1033 		 */
1034 		int err2 = fat_remove_entries(new_dir, &sinfo);
1035 		if (corrupt)
1036 			corrupt |= err2;
1037 		sinfo.bh = NULL;
1038 	}
1039 	if (corrupt < 0) {
1040 		fat_fs_error(new_dir->i_sb,
1041 			     "%s: Filesystem corrupted (i_pos %lld)",
1042 			     __func__, new_i_pos);
1043 	}
1044 	goto out;
1045 }
1046 
1047 static void vfat_exchange_ipos(struct inode *old_inode, struct inode *new_inode,
1048 			       loff_t old_i_pos, loff_t new_i_pos)
1049 {
1050 	fat_detach(old_inode);
1051 	fat_detach(new_inode);
1052 	fat_attach(old_inode, new_i_pos);
1053 	fat_attach(new_inode, old_i_pos);
1054 }
1055 
1056 static void vfat_move_nlink(struct inode *src, struct inode *dst)
1057 {
1058 	drop_nlink(src);
1059 	inc_nlink(dst);
1060 }
1061 
1062 static int vfat_rename_exchange(struct inode *old_dir, struct dentry *old_dentry,
1063 				struct inode *new_dir, struct dentry *new_dentry)
1064 {
1065 	struct buffer_head *old_dotdot_bh = NULL, *new_dotdot_bh = NULL;
1066 	struct msdos_dir_entry *old_dotdot_de = NULL, *new_dotdot_de = NULL;
1067 	struct inode *old_inode, *new_inode;
1068 	struct timespec64 ts = current_time(old_dir);
1069 	loff_t old_i_pos, new_i_pos;
1070 	int err, corrupt = 0;
1071 	struct super_block *sb = old_dir->i_sb;
1072 
1073 	old_inode = d_inode(old_dentry);
1074 	new_inode = d_inode(new_dentry);
1075 
1076 	/* Acquire super block lock for the operation to be atomic */
1077 	mutex_lock(&MSDOS_SB(sb)->s_lock);
1078 
1079 	/* if directories are not the same, get ".." info to update */
1080 	if (old_dir != new_dir) {
1081 		err = vfat_get_dotdot_de(old_inode, &old_dotdot_bh,
1082 					 &old_dotdot_de);
1083 		if (err)
1084 			goto out;
1085 
1086 		err = vfat_get_dotdot_de(new_inode, &new_dotdot_bh,
1087 					 &new_dotdot_de);
1088 		if (err)
1089 			goto out;
1090 	}
1091 
1092 	old_i_pos = MSDOS_I(old_inode)->i_pos;
1093 	new_i_pos = MSDOS_I(new_inode)->i_pos;
1094 
1095 	vfat_exchange_ipos(old_inode, new_inode, old_i_pos, new_i_pos);
1096 
1097 	err = vfat_sync_ipos(old_dir, new_inode);
1098 	if (err)
1099 		goto error_exchange;
1100 	err = vfat_sync_ipos(new_dir, old_inode);
1101 	if (err)
1102 		goto error_exchange;
1103 
1104 	/* update ".." directory entry info */
1105 	if (old_dotdot_de) {
1106 		err = vfat_update_dotdot_de(new_dir, old_inode, old_dotdot_bh,
1107 					    old_dotdot_de);
1108 		if (err)
1109 			goto error_old_dotdot;
1110 	}
1111 	if (new_dotdot_de) {
1112 		err = vfat_update_dotdot_de(old_dir, new_inode, new_dotdot_bh,
1113 					    new_dotdot_de);
1114 		if (err)
1115 			goto error_new_dotdot;
1116 	}
1117 
1118 	/* if cross directory and only one is a directory, adjust nlink */
1119 	if (!old_dotdot_de != !new_dotdot_de) {
1120 		if (old_dotdot_de)
1121 			vfat_move_nlink(old_dir, new_dir);
1122 		else
1123 			vfat_move_nlink(new_dir, old_dir);
1124 	}
1125 
1126 	vfat_update_dir_metadata(old_dir, &ts);
1127 	/* if directories are not the same, update new_dir as well */
1128 	if (old_dir != new_dir)
1129 		vfat_update_dir_metadata(new_dir, &ts);
1130 
1131 out:
1132 	brelse(old_dotdot_bh);
1133 	brelse(new_dotdot_bh);
1134 	mutex_unlock(&MSDOS_SB(sb)->s_lock);
1135 
1136 	return err;
1137 
1138 error_new_dotdot:
1139 	if (new_dotdot_de) {
1140 		corrupt |= vfat_update_dotdot_de(new_dir, new_inode,
1141 						 new_dotdot_bh, new_dotdot_de);
1142 	}
1143 
1144 error_old_dotdot:
1145 	if (old_dotdot_de) {
1146 		corrupt |= vfat_update_dotdot_de(old_dir, old_inode,
1147 						 old_dotdot_bh, old_dotdot_de);
1148 	}
1149 
1150 error_exchange:
1151 	vfat_exchange_ipos(old_inode, new_inode, new_i_pos, old_i_pos);
1152 	corrupt |= vfat_sync_ipos(new_dir, new_inode);
1153 	corrupt |= vfat_sync_ipos(old_dir, old_inode);
1154 
1155 	if (corrupt < 0) {
1156 		fat_fs_error(new_dir->i_sb,
1157 			     "%s: Filesystem corrupted (i_pos %lld, %lld)",
1158 			     __func__, old_i_pos, new_i_pos);
1159 	}
1160 	goto out;
1161 }
1162 
1163 static int vfat_rename2(struct mnt_idmap *idmap, struct inode *old_dir,
1164 			struct dentry *old_dentry, struct inode *new_dir,
1165 			struct dentry *new_dentry, unsigned int flags)
1166 {
1167 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE))
1168 		return -EINVAL;
1169 
1170 	if (flags & RENAME_EXCHANGE) {
1171 		return vfat_rename_exchange(old_dir, old_dentry,
1172 					    new_dir, new_dentry);
1173 	}
1174 
1175 	/* VFS already handled RENAME_NOREPLACE, handle it as a normal rename */
1176 	return vfat_rename(old_dir, old_dentry, new_dir, new_dentry);
1177 }
1178 
1179 static const struct inode_operations vfat_dir_inode_operations = {
1180 	.create		= vfat_create,
1181 	.lookup		= vfat_lookup,
1182 	.unlink		= vfat_unlink,
1183 	.mkdir		= vfat_mkdir,
1184 	.rmdir		= vfat_rmdir,
1185 	.rename		= vfat_rename2,
1186 	.setattr	= fat_setattr,
1187 	.getattr	= fat_getattr,
1188 	.update_time	= fat_update_time,
1189 };
1190 
1191 static void setup(struct super_block *sb)
1192 {
1193 	MSDOS_SB(sb)->dir_ops = &vfat_dir_inode_operations;
1194 	if (MSDOS_SB(sb)->options.name_check != 's')
1195 		set_default_d_op(sb, &vfat_ci_dentry_ops);
1196 	else
1197 		set_default_d_op(sb, &vfat_dentry_ops);
1198 }
1199 
1200 static int vfat_fill_super(struct super_block *sb, struct fs_context *fc)
1201 {
1202 	return fat_fill_super(sb, fc, setup);
1203 }
1204 
1205 static int vfat_get_tree(struct fs_context *fc)
1206 {
1207 	return get_tree_bdev(fc, vfat_fill_super);
1208 }
1209 
1210 static int vfat_parse_param(struct fs_context *fc, struct fs_parameter *param)
1211 {
1212 	return fat_parse_param(fc, param, true);
1213 }
1214 
1215 static const struct fs_context_operations vfat_context_ops = {
1216 	.parse_param	= vfat_parse_param,
1217 	.get_tree	= vfat_get_tree,
1218 	.reconfigure	= fat_reconfigure,
1219 	.free		= fat_free_fc,
1220 };
1221 
1222 static int vfat_init_fs_context(struct fs_context *fc)
1223 {
1224 	int err;
1225 
1226 	/* Initialize with is_vfat == true */
1227 	err = fat_init_fs_context(fc, true);
1228 	if (err)
1229 		return err;
1230 
1231 	fc->ops = &vfat_context_ops;
1232 	return 0;
1233 }
1234 
1235 static struct file_system_type vfat_fs_type = {
1236 	.owner		= THIS_MODULE,
1237 	.name		= "vfat",
1238 	.kill_sb	= kill_block_super,
1239 	.fs_flags	= FS_REQUIRES_DEV | FS_ALLOW_IDMAP,
1240 	.init_fs_context = vfat_init_fs_context,
1241 	.parameters     = fat_param_spec,
1242 };
1243 MODULE_ALIAS_FS("vfat");
1244 
1245 static int __init init_vfat_fs(void)
1246 {
1247 	return register_filesystem(&vfat_fs_type);
1248 }
1249 
1250 static void __exit exit_vfat_fs(void)
1251 {
1252 	unregister_filesystem(&vfat_fs_type);
1253 }
1254 
1255 MODULE_LICENSE("GPL");
1256 MODULE_DESCRIPTION("VFAT filesystem support");
1257 MODULE_AUTHOR("Gordon Chaffee");
1258 
1259 module_init(init_vfat_fs)
1260 module_exit(exit_vfat_fs)
1261