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