1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 * Copyright (C) 2012-2013 Samsung Electronics Co., Ltd.
4 */
5
6#include <linux/iversion.h>
7#include <linux/namei.h>
8#include <linux/slab.h>
9#include <linux/buffer_head.h>
10#include <linux/nls.h>
11
12#include "exfat_raw.h"
13#include "exfat_fs.h"
14
15static inline unsigned long exfat_d_version(struct dentry *dentry)
16{
17	return (unsigned long) dentry->d_fsdata;
18}
19
20static inline void exfat_d_version_set(struct dentry *dentry,
21		unsigned long version)
22{
23	dentry->d_fsdata = (void *) version;
24}
25
26/*
27 * If new entry was created in the parent, it could create the 8.3 alias (the
28 * shortname of logname).  So, the parent may have the negative-dentry which
29 * matches the created 8.3 alias.
30 *
31 * If it happened, the negative dentry isn't actually negative anymore.  So,
32 * drop it.
33 */
34static int exfat_d_revalidate(struct dentry *dentry, unsigned int flags)
35{
36	int ret;
37
38	if (flags & LOOKUP_RCU)
39		return -ECHILD;
40
41	/*
42	 * This is not negative dentry. Always valid.
43	 *
44	 * Note, rename() to existing directory entry will have ->d_inode, and
45	 * will use existing name which isn't specified name by user.
46	 *
47	 * We may be able to drop this positive dentry here. But dropping
48	 * positive dentry isn't good idea. So it's unsupported like
49	 * rename("filename", "FILENAME") for now.
50	 */
51	if (d_really_is_positive(dentry))
52		return 1;
53
54	/*
55	 * Drop the negative dentry, in order to make sure to use the case
56	 * sensitive name which is specified by user if this is for creation.
57	 */
58	if (flags & (LOOKUP_CREATE | LOOKUP_RENAME_TARGET))
59		return 0;
60
61	spin_lock(&dentry->d_lock);
62	ret = inode_eq_iversion(d_inode(dentry->d_parent),
63			exfat_d_version(dentry));
64	spin_unlock(&dentry->d_lock);
65	return ret;
66}
67
68/* returns the length of a struct qstr, ignoring trailing dots if necessary */
69static unsigned int exfat_striptail_len(unsigned int len, const char *name,
70					bool keep_last_dots)
71{
72	if (!keep_last_dots) {
73		while (len && name[len - 1] == '.')
74			len--;
75	}
76	return len;
77}
78
79/*
80 * Compute the hash for the exfat name corresponding to the dentry.  If the name
81 * is invalid, we leave the hash code unchanged so that the existing dentry can
82 * be used. The exfat fs routines will return ENOENT or EINVAL as appropriate.
83 */
84static int exfat_d_hash(const struct dentry *dentry, struct qstr *qstr)
85{
86	struct super_block *sb = dentry->d_sb;
87	struct nls_table *t = EXFAT_SB(sb)->nls_io;
88	const unsigned char *name = qstr->name;
89	unsigned int len = exfat_striptail_len(qstr->len, qstr->name,
90			   EXFAT_SB(sb)->options.keep_last_dots);
91	unsigned long hash = init_name_hash(dentry);
92	int i, charlen;
93	wchar_t c;
94
95	for (i = 0; i < len; i += charlen) {
96		charlen = t->char2uni(&name[i], len - i, &c);
97		if (charlen < 0)
98			return charlen;
99		hash = partial_name_hash(exfat_toupper(sb, c), hash);
100	}
101
102	qstr->hash = end_name_hash(hash);
103	return 0;
104}
105
106static int exfat_d_cmp(const struct dentry *dentry, unsigned int len,
107		const char *str, const struct qstr *name)
108{
109	struct super_block *sb = dentry->d_sb;
110	struct nls_table *t = EXFAT_SB(sb)->nls_io;
111	unsigned int alen = exfat_striptail_len(name->len, name->name,
112				EXFAT_SB(sb)->options.keep_last_dots);
113	unsigned int blen = exfat_striptail_len(len, str,
114				EXFAT_SB(sb)->options.keep_last_dots);
115	wchar_t c1, c2;
116	int charlen, i;
117
118	if (alen != blen)
119		return 1;
120
121	for (i = 0; i < len; i += charlen) {
122		charlen = t->char2uni(&name->name[i], alen - i, &c1);
123		if (charlen < 0)
124			return 1;
125		if (charlen != t->char2uni(&str[i], blen - i, &c2))
126			return 1;
127
128		if (exfat_toupper(sb, c1) != exfat_toupper(sb, c2))
129			return 1;
130	}
131
132	return 0;
133}
134
135const struct dentry_operations exfat_dentry_ops = {
136	.d_revalidate	= exfat_d_revalidate,
137	.d_hash		= exfat_d_hash,
138	.d_compare	= exfat_d_cmp,
139};
140
141static int exfat_utf8_d_hash(const struct dentry *dentry, struct qstr *qstr)
142{
143	struct super_block *sb = dentry->d_sb;
144	const unsigned char *name = qstr->name;
145	unsigned int len = exfat_striptail_len(qstr->len, qstr->name,
146			       EXFAT_SB(sb)->options.keep_last_dots);
147	unsigned long hash = init_name_hash(dentry);
148	int i, charlen;
149	unicode_t u;
150
151	for (i = 0; i < len; i += charlen) {
152		charlen = utf8_to_utf32(&name[i], len - i, &u);
153		if (charlen < 0)
154			return charlen;
155
156		/*
157		 * exfat_toupper() works only for code points up to the U+FFFF.
158		 */
159		hash = partial_name_hash(u <= 0xFFFF ? exfat_toupper(sb, u) : u,
160					 hash);
161	}
162
163	qstr->hash = end_name_hash(hash);
164	return 0;
165}
166
167static int exfat_utf8_d_cmp(const struct dentry *dentry, unsigned int len,
168		const char *str, const struct qstr *name)
169{
170	struct super_block *sb = dentry->d_sb;
171	unsigned int alen = exfat_striptail_len(name->len, name->name,
172				EXFAT_SB(sb)->options.keep_last_dots);
173	unsigned int blen = exfat_striptail_len(len, str,
174				EXFAT_SB(sb)->options.keep_last_dots);
175
176	unicode_t u_a, u_b;
177	int charlen, i;
178
179	if (alen != blen)
180		return 1;
181
182	for (i = 0; i < alen; i += charlen) {
183		charlen = utf8_to_utf32(&name->name[i], alen - i, &u_a);
184		if (charlen < 0)
185			return 1;
186		if (charlen != utf8_to_utf32(&str[i], blen - i, &u_b))
187			return 1;
188
189		if (u_a <= 0xFFFF && u_b <= 0xFFFF) {
190			if (exfat_toupper(sb, u_a) != exfat_toupper(sb, u_b))
191				return 1;
192		} else {
193			if (u_a != u_b)
194				return 1;
195		}
196	}
197
198	return 0;
199}
200
201const struct dentry_operations exfat_utf8_dentry_ops = {
202	.d_revalidate	= exfat_d_revalidate,
203	.d_hash		= exfat_utf8_d_hash,
204	.d_compare	= exfat_utf8_d_cmp,
205};
206
207/* search EMPTY CONTINUOUS "num_entries" entries */
208static int exfat_search_empty_slot(struct super_block *sb,
209		struct exfat_hint_femp *hint_femp, struct exfat_chain *p_dir,
210		int num_entries, struct exfat_entry_set_cache *es)
211{
212	int i, dentry, ret;
213	int dentries_per_clu;
214	struct exfat_chain clu;
215	struct exfat_sb_info *sbi = EXFAT_SB(sb);
216	int total_entries = EXFAT_CLU_TO_DEN(p_dir->size, sbi);
217
218	dentries_per_clu = sbi->dentries_per_clu;
219
220	if (hint_femp->eidx != EXFAT_HINT_NONE) {
221		dentry = hint_femp->eidx;
222
223		/*
224		 * If hint_femp->count is enough, it is needed to check if
225		 * there are actual empty entries.
226		 * Otherwise, and if "dentry + hint_famp->count" is also equal
227		 * to "p_dir->size * dentries_per_clu", it means ENOSPC.
228		 */
229		if (dentry + hint_femp->count == total_entries &&
230		    num_entries > hint_femp->count)
231			return -ENOSPC;
232
233		hint_femp->eidx = EXFAT_HINT_NONE;
234		exfat_chain_dup(&clu, &hint_femp->cur);
235	} else {
236		exfat_chain_dup(&clu, p_dir);
237		dentry = 0;
238	}
239
240	while (dentry + num_entries < total_entries &&
241	       clu.dir != EXFAT_EOF_CLUSTER) {
242		i = dentry & (dentries_per_clu - 1);
243
244		ret = exfat_get_empty_dentry_set(es, sb, &clu, i, num_entries);
245		if (ret < 0)
246			return ret;
247		else if (ret == 0)
248			return dentry;
249
250		dentry += ret;
251		i += ret;
252
253		while (i >= dentries_per_clu) {
254			if (clu.flags == ALLOC_NO_FAT_CHAIN) {
255				if (--clu.size > 0)
256					clu.dir++;
257				else
258					clu.dir = EXFAT_EOF_CLUSTER;
259			} else {
260				if (exfat_get_next_cluster(sb, &clu.dir))
261					return -EIO;
262			}
263
264			i -= dentries_per_clu;
265		}
266	}
267
268	hint_femp->eidx = dentry;
269	hint_femp->count = 0;
270	if (dentry == total_entries || clu.dir == EXFAT_EOF_CLUSTER)
271		exfat_chain_set(&hint_femp->cur, EXFAT_EOF_CLUSTER, 0,
272				clu.flags);
273	else
274		hint_femp->cur = clu;
275
276	return -ENOSPC;
277}
278
279static int exfat_check_max_dentries(struct inode *inode)
280{
281	if (EXFAT_B_TO_DEN(i_size_read(inode)) >= MAX_EXFAT_DENTRIES) {
282		/*
283		 * exFAT spec allows a dir to grow up to 8388608(256MB)
284		 * dentries
285		 */
286		return -ENOSPC;
287	}
288	return 0;
289}
290
291/* find empty directory entry.
292 * if there isn't any empty slot, expand cluster chain.
293 */
294static int exfat_find_empty_entry(struct inode *inode,
295		struct exfat_chain *p_dir, int num_entries,
296		struct exfat_entry_set_cache *es)
297{
298	int dentry;
299	unsigned int ret, last_clu;
300	loff_t size = 0;
301	struct exfat_chain clu;
302	struct super_block *sb = inode->i_sb;
303	struct exfat_sb_info *sbi = EXFAT_SB(sb);
304	struct exfat_inode_info *ei = EXFAT_I(inode);
305	struct exfat_hint_femp hint_femp;
306
307	hint_femp.eidx = EXFAT_HINT_NONE;
308
309	if (ei->hint_femp.eidx != EXFAT_HINT_NONE) {
310		hint_femp = ei->hint_femp;
311		ei->hint_femp.eidx = EXFAT_HINT_NONE;
312	}
313
314	while ((dentry = exfat_search_empty_slot(sb, &hint_femp, p_dir,
315					num_entries, es)) < 0) {
316		if (dentry == -EIO)
317			break;
318
319		if (exfat_check_max_dentries(inode))
320			return -ENOSPC;
321
322		/*
323		 * Allocate new cluster to this directory
324		 */
325		if (ei->start_clu != EXFAT_EOF_CLUSTER) {
326			/* we trust p_dir->size regardless of FAT type */
327			if (exfat_find_last_cluster(sb, p_dir, &last_clu))
328				return -EIO;
329
330			exfat_chain_set(&clu, last_clu + 1, 0, p_dir->flags);
331		} else {
332			/* This directory is empty */
333			exfat_chain_set(&clu, EXFAT_EOF_CLUSTER, 0,
334					ALLOC_NO_FAT_CHAIN);
335		}
336
337		/* allocate a cluster */
338		ret = exfat_alloc_cluster(inode, 1, &clu, IS_DIRSYNC(inode));
339		if (ret)
340			return ret;
341
342		if (exfat_zeroed_cluster(inode, clu.dir))
343			return -EIO;
344
345		if (ei->start_clu == EXFAT_EOF_CLUSTER) {
346			ei->start_clu = clu.dir;
347			p_dir->dir = clu.dir;
348		}
349
350		/* append to the FAT chain */
351		if (clu.flags != p_dir->flags) {
352			/* no-fat-chain bit is disabled,
353			 * so fat-chain should be synced with alloc-bitmap
354			 */
355			exfat_chain_cont_cluster(sb, p_dir->dir, p_dir->size);
356			p_dir->flags = ALLOC_FAT_CHAIN;
357			hint_femp.cur.flags = ALLOC_FAT_CHAIN;
358		}
359
360		if (clu.flags == ALLOC_FAT_CHAIN)
361			if (exfat_ent_set(sb, last_clu, clu.dir))
362				return -EIO;
363
364		if (hint_femp.cur.dir == EXFAT_EOF_CLUSTER)
365			exfat_chain_set(&hint_femp.cur, clu.dir, 0, clu.flags);
366
367		hint_femp.count += sbi->dentries_per_clu;
368
369		hint_femp.cur.size++;
370		p_dir->size++;
371		size = EXFAT_CLU_TO_B(p_dir->size, sbi);
372
373		/* directory inode should be updated in here */
374		i_size_write(inode, size);
375		ei->i_size_ondisk += sbi->cluster_size;
376		ei->i_size_aligned += sbi->cluster_size;
377		ei->valid_size += sbi->cluster_size;
378		ei->flags = p_dir->flags;
379		inode->i_blocks += sbi->cluster_size >> 9;
380	}
381
382	return dentry;
383}
384
385/*
386 * Name Resolution Functions :
387 * Zero if it was successful; otherwise nonzero.
388 */
389static int __exfat_resolve_path(struct inode *inode, const unsigned char *path,
390		struct exfat_chain *p_dir, struct exfat_uni_name *p_uniname,
391		int lookup)
392{
393	int namelen;
394	int lossy = NLS_NAME_NO_LOSSY;
395	struct super_block *sb = inode->i_sb;
396	struct exfat_sb_info *sbi = EXFAT_SB(sb);
397	struct exfat_inode_info *ei = EXFAT_I(inode);
398	int pathlen = strlen(path);
399
400	/*
401	 * get the length of the pathname excluding
402	 * trailing periods, if any.
403	 */
404	namelen = exfat_striptail_len(pathlen, path, false);
405	if (EXFAT_SB(sb)->options.keep_last_dots) {
406		/*
407		 * Do not allow the creation of files with names
408		 * ending with period(s).
409		 */
410		if (!lookup && (namelen < pathlen))
411			return -EINVAL;
412		namelen = pathlen;
413	}
414	if (!namelen)
415		return -ENOENT;
416	if (pathlen > (MAX_NAME_LENGTH * MAX_CHARSET_SIZE))
417		return -ENAMETOOLONG;
418
419	/*
420	 * strip all leading spaces :
421	 * "MS windows 7" supports leading spaces.
422	 * So we should skip this preprocessing for compatibility.
423	 */
424
425	/* file name conversion :
426	 * If lookup case, we allow bad-name for compatibility.
427	 */
428	namelen = exfat_nls_to_utf16(sb, path, namelen, p_uniname,
429			&lossy);
430	if (namelen < 0)
431		return namelen; /* return error value */
432
433	if ((lossy && !lookup) || !namelen)
434		return (lossy & NLS_NAME_OVERLEN) ? -ENAMETOOLONG : -EINVAL;
435
436	exfat_chain_set(p_dir, ei->start_clu,
437		EXFAT_B_TO_CLU(i_size_read(inode), sbi), ei->flags);
438
439	return 0;
440}
441
442static inline int exfat_resolve_path(struct inode *inode,
443		const unsigned char *path, struct exfat_chain *dir,
444		struct exfat_uni_name *uni)
445{
446	return __exfat_resolve_path(inode, path, dir, uni, 0);
447}
448
449static inline int exfat_resolve_path_for_lookup(struct inode *inode,
450		const unsigned char *path, struct exfat_chain *dir,
451		struct exfat_uni_name *uni)
452{
453	return __exfat_resolve_path(inode, path, dir, uni, 1);
454}
455
456static inline loff_t exfat_make_i_pos(struct exfat_dir_entry *info)
457{
458	return ((loff_t) info->dir.dir << 32) | (info->entry & 0xffffffff);
459}
460
461static int exfat_add_entry(struct inode *inode, const char *path,
462		struct exfat_chain *p_dir, unsigned int type,
463		struct exfat_dir_entry *info)
464{
465	int ret, dentry, num_entries;
466	struct super_block *sb = inode->i_sb;
467	struct exfat_sb_info *sbi = EXFAT_SB(sb);
468	struct exfat_uni_name uniname;
469	struct exfat_chain clu;
470	struct timespec64 ts = current_time(inode);
471	struct exfat_entry_set_cache es;
472	int clu_size = 0;
473	unsigned int start_clu = EXFAT_FREE_CLUSTER;
474
475	ret = exfat_resolve_path(inode, path, p_dir, &uniname);
476	if (ret)
477		goto out;
478
479	num_entries = exfat_calc_num_entries(&uniname);
480	if (num_entries < 0) {
481		ret = num_entries;
482		goto out;
483	}
484
485	/* exfat_find_empty_entry must be called before alloc_cluster() */
486	dentry = exfat_find_empty_entry(inode, p_dir, num_entries, &es);
487	if (dentry < 0) {
488		ret = dentry; /* -EIO or -ENOSPC */
489		goto out;
490	}
491
492	if (type == TYPE_DIR && !sbi->options.zero_size_dir) {
493		ret = exfat_alloc_new_dir(inode, &clu);
494		if (ret) {
495			exfat_put_dentry_set(&es, false);
496			goto out;
497		}
498		start_clu = clu.dir;
499		clu_size = sbi->cluster_size;
500	}
501
502	/* update the directory entry */
503	/* fill the dos name directory entry information of the created file.
504	 * the first cluster is not determined yet. (0)
505	 */
506	exfat_init_dir_entry(&es, type, start_clu, clu_size, &ts);
507	exfat_init_ext_entry(&es, num_entries, &uniname);
508
509	ret = exfat_put_dentry_set(&es, IS_DIRSYNC(inode));
510	if (ret)
511		goto out;
512
513	info->dir = *p_dir;
514	info->entry = dentry;
515	info->flags = ALLOC_NO_FAT_CHAIN;
516	info->type = type;
517
518	if (type == TYPE_FILE) {
519		info->attr = EXFAT_ATTR_ARCHIVE;
520		info->start_clu = EXFAT_EOF_CLUSTER;
521		info->size = 0;
522		info->num_subdirs = 0;
523	} else {
524		info->attr = EXFAT_ATTR_SUBDIR;
525		if (sbi->options.zero_size_dir)
526			info->start_clu = EXFAT_EOF_CLUSTER;
527		else
528			info->start_clu = start_clu;
529		info->size = clu_size;
530		info->num_subdirs = EXFAT_MIN_SUBDIR;
531	}
532	info->valid_size = info->size;
533
534	memset(&info->crtime, 0, sizeof(info->crtime));
535	memset(&info->mtime, 0, sizeof(info->mtime));
536	memset(&info->atime, 0, sizeof(info->atime));
537out:
538	return ret;
539}
540
541static int exfat_create(struct mnt_idmap *idmap, struct inode *dir,
542			struct dentry *dentry, umode_t mode, bool excl)
543{
544	struct super_block *sb = dir->i_sb;
545	struct inode *inode;
546	struct exfat_chain cdir;
547	struct exfat_dir_entry info;
548	loff_t i_pos;
549	int err;
550	loff_t size = i_size_read(dir);
551
552	mutex_lock(&EXFAT_SB(sb)->s_lock);
553	exfat_set_volume_dirty(sb);
554	err = exfat_add_entry(dir, dentry->d_name.name, &cdir, TYPE_FILE,
555		&info);
556	if (err)
557		goto unlock;
558
559	inode_inc_iversion(dir);
560	inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir));
561	if (IS_DIRSYNC(dir) && size != i_size_read(dir))
562		exfat_sync_inode(dir);
563	else
564		mark_inode_dirty(dir);
565
566	i_pos = exfat_make_i_pos(&info);
567	inode = exfat_build_inode(sb, &info, i_pos);
568	err = PTR_ERR_OR_ZERO(inode);
569	if (err)
570		goto unlock;
571
572	inode_inc_iversion(inode);
573	EXFAT_I(inode)->i_crtime = simple_inode_init_ts(inode);
574	exfat_truncate_inode_atime(inode);
575
576	/* timestamp is already written, so mark_inode_dirty() is unneeded. */
577
578	d_instantiate(dentry, inode);
579unlock:
580	mutex_unlock(&EXFAT_SB(sb)->s_lock);
581	return err;
582}
583
584/* lookup a file */
585static int exfat_find(struct inode *dir, struct qstr *qname,
586		struct exfat_dir_entry *info)
587{
588	int ret, dentry, count;
589	struct exfat_chain cdir;
590	struct exfat_uni_name uni_name;
591	struct super_block *sb = dir->i_sb;
592	struct exfat_sb_info *sbi = EXFAT_SB(sb);
593	struct exfat_inode_info *ei = EXFAT_I(dir);
594	struct exfat_dentry *ep, *ep2;
595	struct exfat_entry_set_cache es;
596	/* for optimized dir & entry to prevent long traverse of cluster chain */
597	struct exfat_hint hint_opt;
598
599	if (qname->len == 0)
600		return -ENOENT;
601
602	/* check the validity of directory name in the given pathname */
603	ret = exfat_resolve_path_for_lookup(dir, qname->name, &cdir, &uni_name);
604	if (ret)
605		return ret;
606
607	/* check the validation of hint_stat and initialize it if required */
608	if (ei->version != (inode_peek_iversion_raw(dir) & 0xffffffff)) {
609		ei->hint_stat.clu = cdir.dir;
610		ei->hint_stat.eidx = 0;
611		ei->version = (inode_peek_iversion_raw(dir) & 0xffffffff);
612		ei->hint_femp.eidx = EXFAT_HINT_NONE;
613	}
614
615	/* search the file name for directories */
616	dentry = exfat_find_dir_entry(sb, ei, &cdir, &uni_name, &hint_opt);
617	if (dentry < 0)
618		return dentry; /* -error value */
619
620	info->dir = cdir;
621	info->entry = dentry;
622	info->num_subdirs = 0;
623
624	/* adjust cdir to the optimized value */
625	cdir.dir = hint_opt.clu;
626	if (cdir.flags & ALLOC_NO_FAT_CHAIN)
627		cdir.size -= dentry / sbi->dentries_per_clu;
628	dentry = hint_opt.eidx;
629	if (exfat_get_dentry_set(&es, sb, &cdir, dentry, ES_2_ENTRIES))
630		return -EIO;
631	ep = exfat_get_dentry_cached(&es, ES_IDX_FILE);
632	ep2 = exfat_get_dentry_cached(&es, ES_IDX_STREAM);
633
634	info->type = exfat_get_entry_type(ep);
635	info->attr = le16_to_cpu(ep->dentry.file.attr);
636	info->size = le64_to_cpu(ep2->dentry.stream.valid_size);
637	info->valid_size = le64_to_cpu(ep2->dentry.stream.valid_size);
638	info->size = le64_to_cpu(ep2->dentry.stream.size);
639	if (info->size == 0) {
640		info->flags = ALLOC_NO_FAT_CHAIN;
641		info->start_clu = EXFAT_EOF_CLUSTER;
642	} else {
643		info->flags = ep2->dentry.stream.flags;
644		info->start_clu =
645			le32_to_cpu(ep2->dentry.stream.start_clu);
646	}
647
648	exfat_get_entry_time(sbi, &info->crtime,
649			     ep->dentry.file.create_tz,
650			     ep->dentry.file.create_time,
651			     ep->dentry.file.create_date,
652			     ep->dentry.file.create_time_cs);
653	exfat_get_entry_time(sbi, &info->mtime,
654			     ep->dentry.file.modify_tz,
655			     ep->dentry.file.modify_time,
656			     ep->dentry.file.modify_date,
657			     ep->dentry.file.modify_time_cs);
658	exfat_get_entry_time(sbi, &info->atime,
659			     ep->dentry.file.access_tz,
660			     ep->dentry.file.access_time,
661			     ep->dentry.file.access_date,
662			     0);
663	exfat_put_dentry_set(&es, false);
664
665	if (ei->start_clu == EXFAT_FREE_CLUSTER) {
666		exfat_fs_error(sb,
667			       "non-zero size file starts with zero cluster (size : %llu, p_dir : %u, entry : 0x%08x)",
668			       i_size_read(dir), ei->dir.dir, ei->entry);
669		return -EIO;
670	}
671
672	if (info->type == TYPE_DIR) {
673		exfat_chain_set(&cdir, info->start_clu,
674				EXFAT_B_TO_CLU(info->size, sbi), info->flags);
675		count = exfat_count_dir_entries(sb, &cdir);
676		if (count < 0)
677			return -EIO;
678
679		info->num_subdirs = count + EXFAT_MIN_SUBDIR;
680	}
681	return 0;
682}
683
684static int exfat_d_anon_disconn(struct dentry *dentry)
685{
686	return IS_ROOT(dentry) && (dentry->d_flags & DCACHE_DISCONNECTED);
687}
688
689static struct dentry *exfat_lookup(struct inode *dir, struct dentry *dentry,
690		unsigned int flags)
691{
692	struct super_block *sb = dir->i_sb;
693	struct inode *inode;
694	struct dentry *alias;
695	struct exfat_dir_entry info;
696	int err;
697	loff_t i_pos;
698	mode_t i_mode;
699
700	mutex_lock(&EXFAT_SB(sb)->s_lock);
701	err = exfat_find(dir, &dentry->d_name, &info);
702	if (err) {
703		if (err == -ENOENT) {
704			inode = NULL;
705			goto out;
706		}
707		goto unlock;
708	}
709
710	i_pos = exfat_make_i_pos(&info);
711	inode = exfat_build_inode(sb, &info, i_pos);
712	err = PTR_ERR_OR_ZERO(inode);
713	if (err)
714		goto unlock;
715
716	i_mode = inode->i_mode;
717	alias = d_find_alias(inode);
718
719	/*
720	 * Checking "alias->d_parent == dentry->d_parent" to make sure
721	 * FS is not corrupted (especially double linked dir).
722	 */
723	if (alias && alias->d_parent == dentry->d_parent &&
724			!exfat_d_anon_disconn(alias)) {
725
726		/*
727		 * Unhashed alias is able to exist because of revalidate()
728		 * called by lookup_fast. You can easily make this status
729		 * by calling create and lookup concurrently
730		 * In such case, we reuse an alias instead of new dentry
731		 */
732		if (d_unhashed(alias)) {
733			WARN_ON(alias->d_name.hash_len !=
734				dentry->d_name.hash_len);
735			exfat_info(sb, "rehashed a dentry(%p) in read lookup",
736				   alias);
737			d_drop(dentry);
738			d_rehash(alias);
739		} else if (!S_ISDIR(i_mode)) {
740			/*
741			 * This inode has non anonymous-DCACHE_DISCONNECTED
742			 * dentry. This means, the user did ->lookup() by an
743			 * another name (longname vs 8.3 alias of it) in past.
744			 *
745			 * Switch to new one for reason of locality if possible.
746			 */
747			d_move(alias, dentry);
748		}
749		iput(inode);
750		mutex_unlock(&EXFAT_SB(sb)->s_lock);
751		return alias;
752	}
753	dput(alias);
754out:
755	mutex_unlock(&EXFAT_SB(sb)->s_lock);
756	if (!inode)
757		exfat_d_version_set(dentry, inode_query_iversion(dir));
758
759	return d_splice_alias(inode, dentry);
760unlock:
761	mutex_unlock(&EXFAT_SB(sb)->s_lock);
762	return ERR_PTR(err);
763}
764
765/* remove an entry, BUT don't truncate */
766static int exfat_unlink(struct inode *dir, struct dentry *dentry)
767{
768	struct exfat_chain cdir;
769	struct super_block *sb = dir->i_sb;
770	struct inode *inode = dentry->d_inode;
771	struct exfat_inode_info *ei = EXFAT_I(inode);
772	struct exfat_entry_set_cache es;
773	int entry, err = 0;
774
775	mutex_lock(&EXFAT_SB(sb)->s_lock);
776	exfat_chain_dup(&cdir, &ei->dir);
777	entry = ei->entry;
778	if (ei->dir.dir == DIR_DELETED) {
779		exfat_err(sb, "abnormal access to deleted dentry");
780		err = -ENOENT;
781		goto unlock;
782	}
783
784	err = exfat_get_dentry_set(&es, sb, &cdir, entry, ES_ALL_ENTRIES);
785	if (err) {
786		err = -EIO;
787		goto unlock;
788	}
789
790	exfat_set_volume_dirty(sb);
791
792	/* update the directory entry */
793	exfat_remove_entries(inode, &es, ES_IDX_FILE);
794
795	err = exfat_put_dentry_set(&es, IS_DIRSYNC(inode));
796	if (err)
797		goto unlock;
798
799	/* This doesn't modify ei */
800	ei->dir.dir = DIR_DELETED;
801
802	inode_inc_iversion(dir);
803	simple_inode_init_ts(dir);
804	exfat_truncate_inode_atime(dir);
805	mark_inode_dirty(dir);
806
807	clear_nlink(inode);
808	simple_inode_init_ts(inode);
809	exfat_truncate_inode_atime(inode);
810	exfat_unhash_inode(inode);
811	exfat_d_version_set(dentry, inode_query_iversion(dir));
812unlock:
813	mutex_unlock(&EXFAT_SB(sb)->s_lock);
814	return err;
815}
816
817static int exfat_mkdir(struct mnt_idmap *idmap, struct inode *dir,
818		       struct dentry *dentry, umode_t mode)
819{
820	struct super_block *sb = dir->i_sb;
821	struct inode *inode;
822	struct exfat_dir_entry info;
823	struct exfat_chain cdir;
824	loff_t i_pos;
825	int err;
826	loff_t size = i_size_read(dir);
827
828	mutex_lock(&EXFAT_SB(sb)->s_lock);
829	exfat_set_volume_dirty(sb);
830	err = exfat_add_entry(dir, dentry->d_name.name, &cdir, TYPE_DIR,
831		&info);
832	if (err)
833		goto unlock;
834
835	inode_inc_iversion(dir);
836	inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir));
837	if (IS_DIRSYNC(dir) && size != i_size_read(dir))
838		exfat_sync_inode(dir);
839	else
840		mark_inode_dirty(dir);
841	inc_nlink(dir);
842
843	i_pos = exfat_make_i_pos(&info);
844	inode = exfat_build_inode(sb, &info, i_pos);
845	err = PTR_ERR_OR_ZERO(inode);
846	if (err)
847		goto unlock;
848
849	inode_inc_iversion(inode);
850	EXFAT_I(inode)->i_crtime = simple_inode_init_ts(inode);
851	exfat_truncate_inode_atime(inode);
852	/* timestamp is already written, so mark_inode_dirty() is unneeded. */
853
854	d_instantiate(dentry, inode);
855
856unlock:
857	mutex_unlock(&EXFAT_SB(sb)->s_lock);
858	return err;
859}
860
861static int exfat_check_dir_empty(struct super_block *sb,
862		struct exfat_chain *p_dir)
863{
864	int i, dentries_per_clu;
865	unsigned int type;
866	struct exfat_chain clu;
867	struct exfat_dentry *ep;
868	struct exfat_sb_info *sbi = EXFAT_SB(sb);
869	struct buffer_head *bh;
870
871	dentries_per_clu = sbi->dentries_per_clu;
872
873	if (p_dir->dir == EXFAT_EOF_CLUSTER)
874		return 0;
875
876	exfat_chain_dup(&clu, p_dir);
877
878	while (clu.dir != EXFAT_EOF_CLUSTER) {
879		for (i = 0; i < dentries_per_clu; i++) {
880			ep = exfat_get_dentry(sb, &clu, i, &bh);
881			if (!ep)
882				return -EIO;
883			type = exfat_get_entry_type(ep);
884			brelse(bh);
885			if (type == TYPE_UNUSED)
886				return 0;
887
888			if (type != TYPE_FILE && type != TYPE_DIR)
889				continue;
890
891			return -ENOTEMPTY;
892		}
893
894		if (clu.flags == ALLOC_NO_FAT_CHAIN) {
895			if (--clu.size > 0)
896				clu.dir++;
897			else
898				clu.dir = EXFAT_EOF_CLUSTER;
899		} else {
900			if (exfat_get_next_cluster(sb, &(clu.dir)))
901				return -EIO;
902		}
903	}
904
905	return 0;
906}
907
908static int exfat_rmdir(struct inode *dir, struct dentry *dentry)
909{
910	struct inode *inode = dentry->d_inode;
911	struct exfat_chain cdir, clu_to_free;
912	struct super_block *sb = inode->i_sb;
913	struct exfat_sb_info *sbi = EXFAT_SB(sb);
914	struct exfat_inode_info *ei = EXFAT_I(inode);
915	struct exfat_entry_set_cache es;
916	int entry, err;
917
918	mutex_lock(&EXFAT_SB(inode->i_sb)->s_lock);
919
920	exfat_chain_dup(&cdir, &ei->dir);
921	entry = ei->entry;
922
923	if (ei->dir.dir == DIR_DELETED) {
924		exfat_err(sb, "abnormal access to deleted dentry");
925		err = -ENOENT;
926		goto unlock;
927	}
928
929	exfat_chain_set(&clu_to_free, ei->start_clu,
930		EXFAT_B_TO_CLU_ROUND_UP(i_size_read(inode), sbi), ei->flags);
931
932	err = exfat_check_dir_empty(sb, &clu_to_free);
933	if (err) {
934		if (err == -EIO)
935			exfat_err(sb, "failed to exfat_check_dir_empty : err(%d)",
936				  err);
937		goto unlock;
938	}
939
940	err = exfat_get_dentry_set(&es, sb, &cdir, entry, ES_ALL_ENTRIES);
941	if (err) {
942		err = -EIO;
943		goto unlock;
944	}
945
946	exfat_set_volume_dirty(sb);
947
948	exfat_remove_entries(inode, &es, ES_IDX_FILE);
949
950	err = exfat_put_dentry_set(&es, IS_DIRSYNC(dir));
951	if (err)
952		goto unlock;
953
954	ei->dir.dir = DIR_DELETED;
955
956	inode_inc_iversion(dir);
957	simple_inode_init_ts(dir);
958	exfat_truncate_inode_atime(dir);
959	if (IS_DIRSYNC(dir))
960		exfat_sync_inode(dir);
961	else
962		mark_inode_dirty(dir);
963	drop_nlink(dir);
964
965	clear_nlink(inode);
966	simple_inode_init_ts(inode);
967	exfat_truncate_inode_atime(inode);
968	exfat_unhash_inode(inode);
969	exfat_d_version_set(dentry, inode_query_iversion(dir));
970unlock:
971	mutex_unlock(&EXFAT_SB(inode->i_sb)->s_lock);
972	return err;
973}
974
975static int exfat_rename_file(struct inode *inode, struct exfat_chain *p_dir,
976		int oldentry, struct exfat_uni_name *p_uniname,
977		struct exfat_inode_info *ei)
978{
979	int ret, num_new_entries;
980	struct exfat_dentry *epold, *epnew;
981	struct super_block *sb = inode->i_sb;
982	struct exfat_entry_set_cache old_es, new_es;
983	int sync = IS_DIRSYNC(inode);
984
985	num_new_entries = exfat_calc_num_entries(p_uniname);
986	if (num_new_entries < 0)
987		return num_new_entries;
988
989	ret = exfat_get_dentry_set(&old_es, sb, p_dir, oldentry, ES_ALL_ENTRIES);
990	if (ret) {
991		ret = -EIO;
992		return ret;
993	}
994
995	epold = exfat_get_dentry_cached(&old_es, ES_IDX_FILE);
996
997	if (old_es.num_entries < num_new_entries) {
998		int newentry;
999
1000		newentry = exfat_find_empty_entry(inode, p_dir, num_new_entries,
1001				&new_es);
1002		if (newentry < 0) {
1003			ret = newentry; /* -EIO or -ENOSPC */
1004			goto put_old_es;
1005		}
1006
1007		epnew = exfat_get_dentry_cached(&new_es, ES_IDX_FILE);
1008		*epnew = *epold;
1009		if (exfat_get_entry_type(epnew) == TYPE_FILE) {
1010			epnew->dentry.file.attr |= cpu_to_le16(EXFAT_ATTR_ARCHIVE);
1011			ei->attr |= EXFAT_ATTR_ARCHIVE;
1012		}
1013
1014		epold = exfat_get_dentry_cached(&old_es, ES_IDX_STREAM);
1015		epnew = exfat_get_dentry_cached(&new_es, ES_IDX_STREAM);
1016		*epnew = *epold;
1017
1018		exfat_init_ext_entry(&new_es, num_new_entries, p_uniname);
1019
1020		ret = exfat_put_dentry_set(&new_es, sync);
1021		if (ret)
1022			goto put_old_es;
1023
1024		exfat_remove_entries(inode, &old_es, ES_IDX_FILE);
1025		ei->dir = *p_dir;
1026		ei->entry = newentry;
1027	} else {
1028		if (exfat_get_entry_type(epold) == TYPE_FILE) {
1029			epold->dentry.file.attr |= cpu_to_le16(EXFAT_ATTR_ARCHIVE);
1030			ei->attr |= EXFAT_ATTR_ARCHIVE;
1031		}
1032
1033		exfat_remove_entries(inode, &old_es, ES_IDX_FIRST_FILENAME + 1);
1034		exfat_init_ext_entry(&old_es, num_new_entries, p_uniname);
1035	}
1036	return exfat_put_dentry_set(&old_es, sync);
1037
1038put_old_es:
1039	exfat_put_dentry_set(&old_es, false);
1040	return ret;
1041}
1042
1043static int exfat_move_file(struct inode *inode, struct exfat_chain *p_olddir,
1044		int oldentry, struct exfat_chain *p_newdir,
1045		struct exfat_uni_name *p_uniname, struct exfat_inode_info *ei)
1046{
1047	int ret, newentry, num_new_entries;
1048	struct exfat_dentry *epmov, *epnew;
1049	struct super_block *sb = inode->i_sb;
1050	struct exfat_entry_set_cache mov_es, new_es;
1051
1052	num_new_entries = exfat_calc_num_entries(p_uniname);
1053	if (num_new_entries < 0)
1054		return num_new_entries;
1055
1056	ret = exfat_get_dentry_set(&mov_es, sb, p_olddir, oldentry,
1057			ES_ALL_ENTRIES);
1058	if (ret)
1059		return -EIO;
1060
1061	newentry = exfat_find_empty_entry(inode, p_newdir, num_new_entries,
1062			&new_es);
1063	if (newentry < 0) {
1064		ret = newentry; /* -EIO or -ENOSPC */
1065		goto put_mov_es;
1066	}
1067
1068	epmov = exfat_get_dentry_cached(&mov_es, ES_IDX_FILE);
1069	epnew = exfat_get_dentry_cached(&new_es, ES_IDX_FILE);
1070	*epnew = *epmov;
1071	if (exfat_get_entry_type(epnew) == TYPE_FILE) {
1072		epnew->dentry.file.attr |= cpu_to_le16(EXFAT_ATTR_ARCHIVE);
1073		ei->attr |= EXFAT_ATTR_ARCHIVE;
1074	}
1075
1076	epmov = exfat_get_dentry_cached(&mov_es, ES_IDX_STREAM);
1077	epnew = exfat_get_dentry_cached(&new_es, ES_IDX_STREAM);
1078	*epnew = *epmov;
1079
1080	exfat_init_ext_entry(&new_es, num_new_entries, p_uniname);
1081	exfat_remove_entries(inode, &mov_es, ES_IDX_FILE);
1082
1083	exfat_chain_set(&ei->dir, p_newdir->dir, p_newdir->size,
1084		p_newdir->flags);
1085
1086	ei->entry = newentry;
1087
1088	ret = exfat_put_dentry_set(&new_es, IS_DIRSYNC(inode));
1089	if (ret)
1090		goto put_mov_es;
1091
1092	return exfat_put_dentry_set(&mov_es, IS_DIRSYNC(inode));
1093
1094put_mov_es:
1095	exfat_put_dentry_set(&mov_es, false);
1096
1097	return ret;
1098}
1099
1100/* rename or move a old file into a new file */
1101static int __exfat_rename(struct inode *old_parent_inode,
1102		struct exfat_inode_info *ei, struct inode *new_parent_inode,
1103		struct dentry *new_dentry)
1104{
1105	int ret;
1106	int dentry;
1107	struct exfat_chain olddir, newdir;
1108	struct exfat_chain *p_dir = NULL;
1109	struct exfat_uni_name uni_name;
1110	struct exfat_dentry *ep;
1111	struct super_block *sb = old_parent_inode->i_sb;
1112	struct exfat_sb_info *sbi = EXFAT_SB(sb);
1113	const unsigned char *new_path = new_dentry->d_name.name;
1114	struct inode *new_inode = new_dentry->d_inode;
1115	struct exfat_inode_info *new_ei = NULL;
1116	unsigned int new_entry_type = TYPE_UNUSED;
1117	int new_entry = 0;
1118	struct buffer_head *new_bh = NULL;
1119
1120	/* check the validity of pointer parameters */
1121	if (new_path == NULL || strlen(new_path) == 0)
1122		return -EINVAL;
1123
1124	if (ei->dir.dir == DIR_DELETED) {
1125		exfat_err(sb, "abnormal access to deleted source dentry");
1126		return -ENOENT;
1127	}
1128
1129	exfat_chain_set(&olddir, EXFAT_I(old_parent_inode)->start_clu,
1130		EXFAT_B_TO_CLU_ROUND_UP(i_size_read(old_parent_inode), sbi),
1131		EXFAT_I(old_parent_inode)->flags);
1132	dentry = ei->entry;
1133
1134	/* check whether new dir is existing directory and empty */
1135	if (new_inode) {
1136		ret = -EIO;
1137		new_ei = EXFAT_I(new_inode);
1138
1139		if (new_ei->dir.dir == DIR_DELETED) {
1140			exfat_err(sb, "abnormal access to deleted target dentry");
1141			goto out;
1142		}
1143
1144		p_dir = &(new_ei->dir);
1145		new_entry = new_ei->entry;
1146		ep = exfat_get_dentry(sb, p_dir, new_entry, &new_bh);
1147		if (!ep)
1148			goto out;
1149
1150		new_entry_type = exfat_get_entry_type(ep);
1151		brelse(new_bh);
1152
1153		/* if new_inode exists, update ei */
1154		if (new_entry_type == TYPE_DIR) {
1155			struct exfat_chain new_clu;
1156
1157			new_clu.dir = new_ei->start_clu;
1158			new_clu.size =
1159				EXFAT_B_TO_CLU_ROUND_UP(i_size_read(new_inode),
1160				sbi);
1161			new_clu.flags = new_ei->flags;
1162
1163			ret = exfat_check_dir_empty(sb, &new_clu);
1164			if (ret)
1165				goto out;
1166		}
1167	}
1168
1169	/* check the validity of directory name in the given new pathname */
1170	ret = exfat_resolve_path(new_parent_inode, new_path, &newdir,
1171			&uni_name);
1172	if (ret)
1173		goto out;
1174
1175	exfat_set_volume_dirty(sb);
1176
1177	if (olddir.dir == newdir.dir)
1178		ret = exfat_rename_file(new_parent_inode, &olddir, dentry,
1179				&uni_name, ei);
1180	else
1181		ret = exfat_move_file(new_parent_inode, &olddir, dentry,
1182				&newdir, &uni_name, ei);
1183
1184	if (!ret && new_inode) {
1185		struct exfat_entry_set_cache es;
1186
1187		/* delete entries of new_dir */
1188		ret = exfat_get_dentry_set(&es, sb, p_dir, new_entry,
1189				ES_ALL_ENTRIES);
1190		if (ret) {
1191			ret = -EIO;
1192			goto del_out;
1193		}
1194
1195		exfat_remove_entries(new_inode, &es, ES_IDX_FILE);
1196
1197		ret = exfat_put_dentry_set(&es, IS_DIRSYNC(new_inode));
1198		if (ret)
1199			goto del_out;
1200
1201		/* Free the clusters if new_inode is a dir(as if exfat_rmdir) */
1202		if (new_entry_type == TYPE_DIR &&
1203		    new_ei->start_clu != EXFAT_EOF_CLUSTER) {
1204			/* new_ei, new_clu_to_free */
1205			struct exfat_chain new_clu_to_free;
1206
1207			exfat_chain_set(&new_clu_to_free, new_ei->start_clu,
1208				EXFAT_B_TO_CLU_ROUND_UP(i_size_read(new_inode),
1209				sbi), new_ei->flags);
1210
1211			if (exfat_free_cluster(new_inode, &new_clu_to_free)) {
1212				/* just set I/O error only */
1213				ret = -EIO;
1214			}
1215
1216			i_size_write(new_inode, 0);
1217			new_ei->valid_size = 0;
1218			new_ei->start_clu = EXFAT_EOF_CLUSTER;
1219			new_ei->flags = ALLOC_NO_FAT_CHAIN;
1220		}
1221del_out:
1222		/* Update new_inode ei
1223		 * Prevent syncing removed new_inode
1224		 * (new_ei is already initialized above code ("if (new_inode)")
1225		 */
1226		new_ei->dir.dir = DIR_DELETED;
1227	}
1228out:
1229	return ret;
1230}
1231
1232static int exfat_rename(struct mnt_idmap *idmap,
1233			struct inode *old_dir, struct dentry *old_dentry,
1234			struct inode *new_dir, struct dentry *new_dentry,
1235			unsigned int flags)
1236{
1237	struct inode *old_inode, *new_inode;
1238	struct super_block *sb = old_dir->i_sb;
1239	loff_t i_pos;
1240	int err;
1241	loff_t size = i_size_read(new_dir);
1242
1243	/*
1244	 * The VFS already checks for existence, so for local filesystems
1245	 * the RENAME_NOREPLACE implementation is equivalent to plain rename.
1246	 * Don't support any other flags
1247	 */
1248	if (flags & ~RENAME_NOREPLACE)
1249		return -EINVAL;
1250
1251	mutex_lock(&EXFAT_SB(sb)->s_lock);
1252	old_inode = old_dentry->d_inode;
1253	new_inode = new_dentry->d_inode;
1254
1255	err = __exfat_rename(old_dir, EXFAT_I(old_inode), new_dir, new_dentry);
1256	if (err)
1257		goto unlock;
1258
1259	inode_inc_iversion(new_dir);
1260	simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
1261	EXFAT_I(new_dir)->i_crtime = current_time(new_dir);
1262	exfat_truncate_inode_atime(new_dir);
1263	if (IS_DIRSYNC(new_dir) && size != i_size_read(new_dir))
1264		exfat_sync_inode(new_dir);
1265	else
1266		mark_inode_dirty(new_dir);
1267
1268	i_pos = ((loff_t)EXFAT_I(old_inode)->dir.dir << 32) |
1269		(EXFAT_I(old_inode)->entry & 0xffffffff);
1270	exfat_unhash_inode(old_inode);
1271	exfat_hash_inode(old_inode, i_pos);
1272	if (IS_DIRSYNC(new_dir))
1273		exfat_sync_inode(old_inode);
1274	else
1275		mark_inode_dirty(old_inode);
1276
1277	if (S_ISDIR(old_inode->i_mode) && old_dir != new_dir) {
1278		drop_nlink(old_dir);
1279		if (!new_inode)
1280			inc_nlink(new_dir);
1281	}
1282
1283	inode_inc_iversion(old_dir);
1284	if (new_dir != old_dir)
1285		mark_inode_dirty(old_dir);
1286
1287	if (new_inode) {
1288		exfat_unhash_inode(new_inode);
1289
1290		/* skip drop_nlink if new_inode already has been dropped */
1291		if (new_inode->i_nlink) {
1292			drop_nlink(new_inode);
1293			if (S_ISDIR(new_inode->i_mode))
1294				drop_nlink(new_inode);
1295		} else {
1296			exfat_warn(sb, "abnormal access to an inode dropped");
1297			WARN_ON(new_inode->i_nlink == 0);
1298		}
1299		EXFAT_I(new_inode)->i_crtime = current_time(new_inode);
1300	}
1301
1302unlock:
1303	mutex_unlock(&EXFAT_SB(sb)->s_lock);
1304	return err;
1305}
1306
1307const struct inode_operations exfat_dir_inode_operations = {
1308	.create		= exfat_create,
1309	.lookup		= exfat_lookup,
1310	.unlink		= exfat_unlink,
1311	.mkdir		= exfat_mkdir,
1312	.rmdir		= exfat_rmdir,
1313	.rename		= exfat_rename,
1314	.setattr	= exfat_setattr,
1315	.getattr	= exfat_getattr,
1316};
1317