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