xref: /linux/fs/fat/dir.c (revision 22d55f02b8922a097cd4be1e2f131dfa7ef65901)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/fs/fat/dir.c
4  *
5  *  directory handling functions for fat-based filesystems
6  *
7  *  Written 1992,1993 by Werner Almesberger
8  *
9  *  Hidden files 1995 by Albert Cahalan <albert@ccs.neu.edu> <adc@coe.neu.edu>
10  *
11  *  VFAT extensions by Gordon Chaffee <chaffee@plateau.cs.berkeley.edu>
12  *  Merged with msdos fs by Henrik Storner <storner@osiris.ping.dk>
13  *  Rewritten for constant inumbers. Plugged buffer overrun in readdir(). AV
14  *  Short name translation 1999, 2001 by Wolfram Pienkoss <wp@bszh.de>
15  */
16 
17 #include <linux/slab.h>
18 #include <linux/compat.h>
19 #include <linux/uaccess.h>
20 #include <linux/iversion.h>
21 #include "fat.h"
22 
23 /*
24  * Maximum buffer size of short name.
25  * [(MSDOS_NAME + '.') * max one char + nul]
26  * For msdos style, ['.' (hidden) + MSDOS_NAME + '.' + nul]
27  */
28 #define FAT_MAX_SHORT_SIZE	((MSDOS_NAME + 1) * NLS_MAX_CHARSET_SIZE + 1)
29 /*
30  * Maximum buffer size of unicode chars from slots.
31  * [(max longname slots * 13 (size in a slot) + nul) * sizeof(wchar_t)]
32  */
33 #define FAT_MAX_UNI_CHARS	((MSDOS_SLOTS - 1) * 13 + 1)
34 #define FAT_MAX_UNI_SIZE	(FAT_MAX_UNI_CHARS * sizeof(wchar_t))
35 
36 static inline unsigned char fat_tolower(unsigned char c)
37 {
38 	return ((c >= 'A') && (c <= 'Z')) ? c+32 : c;
39 }
40 
41 static inline loff_t fat_make_i_pos(struct super_block *sb,
42 				    struct buffer_head *bh,
43 				    struct msdos_dir_entry *de)
44 {
45 	return ((loff_t)bh->b_blocknr << MSDOS_SB(sb)->dir_per_block_bits)
46 		| (de - (struct msdos_dir_entry *)bh->b_data);
47 }
48 
49 static inline void fat_dir_readahead(struct inode *dir, sector_t iblock,
50 				     sector_t phys)
51 {
52 	struct super_block *sb = dir->i_sb;
53 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
54 	struct buffer_head *bh;
55 	int sec;
56 
57 	/* This is not a first sector of cluster, or sec_per_clus == 1 */
58 	if ((iblock & (sbi->sec_per_clus - 1)) || sbi->sec_per_clus == 1)
59 		return;
60 	/* root dir of FAT12/FAT16 */
61 	if (!is_fat32(sbi) && (dir->i_ino == MSDOS_ROOT_INO))
62 		return;
63 
64 	bh = sb_find_get_block(sb, phys);
65 	if (bh == NULL || !buffer_uptodate(bh)) {
66 		for (sec = 0; sec < sbi->sec_per_clus; sec++)
67 			sb_breadahead(sb, phys + sec);
68 	}
69 	brelse(bh);
70 }
71 
72 /* Returns the inode number of the directory entry at offset pos. If bh is
73    non-NULL, it is brelse'd before. Pos is incremented. The buffer header is
74    returned in bh.
75    AV. Most often we do it item-by-item. Makes sense to optimize.
76    AV. OK, there we go: if both bh and de are non-NULL we assume that we just
77    AV. want the next entry (took one explicit de=NULL in vfat/namei.c).
78    AV. It's done in fat_get_entry() (inlined), here the slow case lives.
79    AV. Additionally, when we return -1 (i.e. reached the end of directory)
80    AV. we make bh NULL.
81  */
82 static int fat__get_entry(struct inode *dir, loff_t *pos,
83 			  struct buffer_head **bh, struct msdos_dir_entry **de)
84 {
85 	struct super_block *sb = dir->i_sb;
86 	sector_t phys, iblock;
87 	unsigned long mapped_blocks;
88 	int err, offset;
89 
90 next:
91 	if (*bh)
92 		brelse(*bh);
93 
94 	*bh = NULL;
95 	iblock = *pos >> sb->s_blocksize_bits;
96 	err = fat_bmap(dir, iblock, &phys, &mapped_blocks, 0, false);
97 	if (err || !phys)
98 		return -1;	/* beyond EOF or error */
99 
100 	fat_dir_readahead(dir, iblock, phys);
101 
102 	*bh = sb_bread(sb, phys);
103 	if (*bh == NULL) {
104 		fat_msg_ratelimit(sb, KERN_ERR,
105 			"Directory bread(block %llu) failed", (llu)phys);
106 		/* skip this block */
107 		*pos = (iblock + 1) << sb->s_blocksize_bits;
108 		goto next;
109 	}
110 
111 	offset = *pos & (sb->s_blocksize - 1);
112 	*pos += sizeof(struct msdos_dir_entry);
113 	*de = (struct msdos_dir_entry *)((*bh)->b_data + offset);
114 
115 	return 0;
116 }
117 
118 static inline int fat_get_entry(struct inode *dir, loff_t *pos,
119 				struct buffer_head **bh,
120 				struct msdos_dir_entry **de)
121 {
122 	/* Fast stuff first */
123 	if (*bh && *de &&
124 	   (*de - (struct msdos_dir_entry *)(*bh)->b_data) <
125 				MSDOS_SB(dir->i_sb)->dir_per_block - 1) {
126 		*pos += sizeof(struct msdos_dir_entry);
127 		(*de)++;
128 		return 0;
129 	}
130 	return fat__get_entry(dir, pos, bh, de);
131 }
132 
133 /*
134  * Convert Unicode 16 to UTF-8, translated Unicode, or ASCII.
135  * If uni_xlate is enabled and we can't get a 1:1 conversion, use a
136  * colon as an escape character since it is normally invalid on the vfat
137  * filesystem. The following four characters are the hexadecimal digits
138  * of Unicode value. This lets us do a full dump and restore of Unicode
139  * filenames. We could get into some trouble with long Unicode names,
140  * but ignore that right now.
141  * Ahem... Stack smashing in ring 0 isn't fun. Fixed.
142  */
143 static int uni16_to_x8(struct super_block *sb, unsigned char *ascii,
144 		       const wchar_t *uni, int len, struct nls_table *nls)
145 {
146 	int uni_xlate = MSDOS_SB(sb)->options.unicode_xlate;
147 	const wchar_t *ip;
148 	wchar_t ec;
149 	unsigned char *op;
150 	int charlen;
151 
152 	ip = uni;
153 	op = ascii;
154 
155 	while (*ip && ((len - NLS_MAX_CHARSET_SIZE) > 0)) {
156 		ec = *ip++;
157 		charlen = nls->uni2char(ec, op, NLS_MAX_CHARSET_SIZE);
158 		if (charlen > 0) {
159 			op += charlen;
160 			len -= charlen;
161 		} else {
162 			if (uni_xlate == 1) {
163 				*op++ = ':';
164 				op = hex_byte_pack(op, ec >> 8);
165 				op = hex_byte_pack(op, ec);
166 				len -= 5;
167 			} else {
168 				*op++ = '?';
169 				len--;
170 			}
171 		}
172 	}
173 
174 	if (unlikely(*ip)) {
175 		fat_msg(sb, KERN_WARNING,
176 			"filename was truncated while converting.");
177 	}
178 
179 	*op = 0;
180 	return op - ascii;
181 }
182 
183 static inline int fat_uni_to_x8(struct super_block *sb, const wchar_t *uni,
184 				unsigned char *buf, int size)
185 {
186 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
187 	if (sbi->options.utf8)
188 		return utf16s_to_utf8s(uni, FAT_MAX_UNI_CHARS,
189 				UTF16_HOST_ENDIAN, buf, size);
190 	else
191 		return uni16_to_x8(sb, buf, uni, size, sbi->nls_io);
192 }
193 
194 static inline int
195 fat_short2uni(struct nls_table *t, unsigned char *c, int clen, wchar_t *uni)
196 {
197 	int charlen;
198 
199 	charlen = t->char2uni(c, clen, uni);
200 	if (charlen < 0) {
201 		*uni = 0x003f;	/* a question mark */
202 		charlen = 1;
203 	}
204 	return charlen;
205 }
206 
207 static inline int
208 fat_short2lower_uni(struct nls_table *t, unsigned char *c,
209 		    int clen, wchar_t *uni)
210 {
211 	int charlen;
212 	wchar_t wc;
213 
214 	charlen = t->char2uni(c, clen, &wc);
215 	if (charlen < 0) {
216 		*uni = 0x003f;	/* a question mark */
217 		charlen = 1;
218 	} else if (charlen <= 1) {
219 		unsigned char nc = t->charset2lower[*c];
220 
221 		if (!nc)
222 			nc = *c;
223 
224 		charlen = t->char2uni(&nc, 1, uni);
225 		if (charlen < 0) {
226 			*uni = 0x003f;	/* a question mark */
227 			charlen = 1;
228 		}
229 	} else
230 		*uni = wc;
231 
232 	return charlen;
233 }
234 
235 static inline int
236 fat_shortname2uni(struct nls_table *nls, unsigned char *buf, int buf_size,
237 		  wchar_t *uni_buf, unsigned short opt, int lower)
238 {
239 	int len = 0;
240 
241 	if (opt & VFAT_SFN_DISPLAY_LOWER)
242 		len =  fat_short2lower_uni(nls, buf, buf_size, uni_buf);
243 	else if (opt & VFAT_SFN_DISPLAY_WIN95)
244 		len = fat_short2uni(nls, buf, buf_size, uni_buf);
245 	else if (opt & VFAT_SFN_DISPLAY_WINNT) {
246 		if (lower)
247 			len = fat_short2lower_uni(nls, buf, buf_size, uni_buf);
248 		else
249 			len = fat_short2uni(nls, buf, buf_size, uni_buf);
250 	} else
251 		len = fat_short2uni(nls, buf, buf_size, uni_buf);
252 
253 	return len;
254 }
255 
256 static inline int fat_name_match(struct msdos_sb_info *sbi,
257 				 const unsigned char *a, int a_len,
258 				 const unsigned char *b, int b_len)
259 {
260 	if (a_len != b_len)
261 		return 0;
262 
263 	if (sbi->options.name_check != 's')
264 		return !nls_strnicmp(sbi->nls_io, a, b, a_len);
265 	else
266 		return !memcmp(a, b, a_len);
267 }
268 
269 enum { PARSE_INVALID = 1, PARSE_NOT_LONGNAME, PARSE_EOF, };
270 
271 /**
272  * fat_parse_long - Parse extended directory entry.
273  *
274  * This function returns zero on success, negative value on error, or one of
275  * the following:
276  *
277  * %PARSE_INVALID - Directory entry is invalid.
278  * %PARSE_NOT_LONGNAME - Directory entry does not contain longname.
279  * %PARSE_EOF - Directory has no more entries.
280  */
281 static int fat_parse_long(struct inode *dir, loff_t *pos,
282 			  struct buffer_head **bh, struct msdos_dir_entry **de,
283 			  wchar_t **unicode, unsigned char *nr_slots)
284 {
285 	struct msdos_dir_slot *ds;
286 	unsigned char id, slot, slots, alias_checksum;
287 
288 	if (!*unicode) {
289 		*unicode = __getname();
290 		if (!*unicode) {
291 			brelse(*bh);
292 			return -ENOMEM;
293 		}
294 	}
295 parse_long:
296 	ds = (struct msdos_dir_slot *)*de;
297 	id = ds->id;
298 	if (!(id & 0x40))
299 		return PARSE_INVALID;
300 	slots = id & ~0x40;
301 	if (slots > 20 || !slots)	/* ceil(256 * 2 / 26) */
302 		return PARSE_INVALID;
303 	*nr_slots = slots;
304 	alias_checksum = ds->alias_checksum;
305 
306 	slot = slots;
307 	while (1) {
308 		int offset;
309 
310 		slot--;
311 		offset = slot * 13;
312 		fat16_towchar(*unicode + offset, ds->name0_4, 5);
313 		fat16_towchar(*unicode + offset + 5, ds->name5_10, 6);
314 		fat16_towchar(*unicode + offset + 11, ds->name11_12, 2);
315 
316 		if (ds->id & 0x40)
317 			(*unicode)[offset + 13] = 0;
318 		if (fat_get_entry(dir, pos, bh, de) < 0)
319 			return PARSE_EOF;
320 		if (slot == 0)
321 			break;
322 		ds = (struct msdos_dir_slot *)*de;
323 		if (ds->attr != ATTR_EXT)
324 			return PARSE_NOT_LONGNAME;
325 		if ((ds->id & ~0x40) != slot)
326 			goto parse_long;
327 		if (ds->alias_checksum != alias_checksum)
328 			goto parse_long;
329 	}
330 	if ((*de)->name[0] == DELETED_FLAG)
331 		return PARSE_INVALID;
332 	if ((*de)->attr == ATTR_EXT)
333 		goto parse_long;
334 	if (IS_FREE((*de)->name) || ((*de)->attr & ATTR_VOLUME))
335 		return PARSE_INVALID;
336 	if (fat_checksum((*de)->name) != alias_checksum)
337 		*nr_slots = 0;
338 
339 	return 0;
340 }
341 
342 /**
343  * fat_parse_short - Parse MS-DOS (short) directory entry.
344  * @sb:		superblock
345  * @de:		directory entry to parse
346  * @name:	FAT_MAX_SHORT_SIZE array in which to place extracted name
347  * @dot_hidden:	Nonzero == prepend '.' to names with ATTR_HIDDEN
348  *
349  * Returns the number of characters extracted into 'name'.
350  */
351 static int fat_parse_short(struct super_block *sb,
352 			   const struct msdos_dir_entry *de,
353 			   unsigned char *name, int dot_hidden)
354 {
355 	const struct msdos_sb_info *sbi = MSDOS_SB(sb);
356 	int isvfat = sbi->options.isvfat;
357 	int nocase = sbi->options.nocase;
358 	unsigned short opt_shortname = sbi->options.shortname;
359 	struct nls_table *nls_disk = sbi->nls_disk;
360 	wchar_t uni_name[14];
361 	unsigned char c, work[MSDOS_NAME];
362 	unsigned char *ptname = name;
363 	int chi, chl, i, j, k;
364 	int dotoffset = 0;
365 	int name_len = 0, uni_len = 0;
366 
367 	if (!isvfat && dot_hidden && (de->attr & ATTR_HIDDEN)) {
368 		*ptname++ = '.';
369 		dotoffset = 1;
370 	}
371 
372 	memcpy(work, de->name, sizeof(work));
373 	/* For an explanation of the special treatment of 0x05 in
374 	 * filenames, see msdos_format_name in namei_msdos.c
375 	 */
376 	if (work[0] == 0x05)
377 		work[0] = 0xE5;
378 
379 	/* Filename */
380 	for (i = 0, j = 0; i < 8;) {
381 		c = work[i];
382 		if (!c)
383 			break;
384 		chl = fat_shortname2uni(nls_disk, &work[i], 8 - i,
385 					&uni_name[j++], opt_shortname,
386 					de->lcase & CASE_LOWER_BASE);
387 		if (chl <= 1) {
388 			if (!isvfat)
389 				ptname[i] = nocase ? c : fat_tolower(c);
390 			i++;
391 			if (c != ' ') {
392 				name_len = i;
393 				uni_len  = j;
394 			}
395 		} else {
396 			uni_len = j;
397 			if (isvfat)
398 				i += min(chl, 8-i);
399 			else {
400 				for (chi = 0; chi < chl && i < 8; chi++, i++)
401 					ptname[i] = work[i];
402 			}
403 			if (chl)
404 				name_len = i;
405 		}
406 	}
407 
408 	i = name_len;
409 	j = uni_len;
410 	fat_short2uni(nls_disk, ".", 1, &uni_name[j++]);
411 	if (!isvfat)
412 		ptname[i] = '.';
413 	i++;
414 
415 	/* Extension */
416 	for (k = 8; k < MSDOS_NAME;) {
417 		c = work[k];
418 		if (!c)
419 			break;
420 		chl = fat_shortname2uni(nls_disk, &work[k], MSDOS_NAME - k,
421 					&uni_name[j++], opt_shortname,
422 					de->lcase & CASE_LOWER_EXT);
423 		if (chl <= 1) {
424 			k++;
425 			if (!isvfat)
426 				ptname[i] = nocase ? c : fat_tolower(c);
427 			i++;
428 			if (c != ' ') {
429 				name_len = i;
430 				uni_len  = j;
431 			}
432 		} else {
433 			uni_len = j;
434 			if (isvfat) {
435 				int offset = min(chl, MSDOS_NAME-k);
436 				k += offset;
437 				i += offset;
438 			} else {
439 				for (chi = 0; chi < chl && k < MSDOS_NAME;
440 				     chi++, i++, k++) {
441 						ptname[i] = work[k];
442 				}
443 			}
444 			if (chl)
445 				name_len = i;
446 		}
447 	}
448 
449 	if (name_len > 0) {
450 		name_len += dotoffset;
451 
452 		if (sbi->options.isvfat) {
453 			uni_name[uni_len] = 0x0000;
454 			name_len = fat_uni_to_x8(sb, uni_name, name,
455 						 FAT_MAX_SHORT_SIZE);
456 		}
457 	}
458 
459 	return name_len;
460 }
461 
462 /*
463  * Return values: negative -> error/not found, 0 -> found.
464  */
465 int fat_search_long(struct inode *inode, const unsigned char *name,
466 		    int name_len, struct fat_slot_info *sinfo)
467 {
468 	struct super_block *sb = inode->i_sb;
469 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
470 	struct buffer_head *bh = NULL;
471 	struct msdos_dir_entry *de;
472 	unsigned char nr_slots;
473 	wchar_t *unicode = NULL;
474 	unsigned char bufname[FAT_MAX_SHORT_SIZE];
475 	loff_t cpos = 0;
476 	int err, len;
477 
478 	err = -ENOENT;
479 	while (1) {
480 		if (fat_get_entry(inode, &cpos, &bh, &de) == -1)
481 			goto end_of_dir;
482 parse_record:
483 		nr_slots = 0;
484 		if (de->name[0] == DELETED_FLAG)
485 			continue;
486 		if (de->attr != ATTR_EXT && (de->attr & ATTR_VOLUME))
487 			continue;
488 		if (de->attr != ATTR_EXT && IS_FREE(de->name))
489 			continue;
490 		if (de->attr == ATTR_EXT) {
491 			int status = fat_parse_long(inode, &cpos, &bh, &de,
492 						    &unicode, &nr_slots);
493 			if (status < 0) {
494 				err = status;
495 				goto end_of_dir;
496 			} else if (status == PARSE_INVALID)
497 				continue;
498 			else if (status == PARSE_NOT_LONGNAME)
499 				goto parse_record;
500 			else if (status == PARSE_EOF)
501 				goto end_of_dir;
502 		}
503 
504 		/* Never prepend '.' to hidden files here.
505 		 * That is done only for msdos mounts (and only when
506 		 * 'dotsOK=yes'); if we are executing here, it is in the
507 		 * context of a vfat mount.
508 		 */
509 		len = fat_parse_short(sb, de, bufname, 0);
510 		if (len == 0)
511 			continue;
512 
513 		/* Compare shortname */
514 		if (fat_name_match(sbi, name, name_len, bufname, len))
515 			goto found;
516 
517 		if (nr_slots) {
518 			void *longname = unicode + FAT_MAX_UNI_CHARS;
519 			int size = PATH_MAX - FAT_MAX_UNI_SIZE;
520 
521 			/* Compare longname */
522 			len = fat_uni_to_x8(sb, unicode, longname, size);
523 			if (fat_name_match(sbi, name, name_len, longname, len))
524 				goto found;
525 		}
526 	}
527 
528 found:
529 	nr_slots++;	/* include the de */
530 	sinfo->slot_off = cpos - nr_slots * sizeof(*de);
531 	sinfo->nr_slots = nr_slots;
532 	sinfo->de = de;
533 	sinfo->bh = bh;
534 	sinfo->i_pos = fat_make_i_pos(sb, sinfo->bh, sinfo->de);
535 	err = 0;
536 end_of_dir:
537 	if (unicode)
538 		__putname(unicode);
539 
540 	return err;
541 }
542 EXPORT_SYMBOL_GPL(fat_search_long);
543 
544 struct fat_ioctl_filldir_callback {
545 	struct dir_context ctx;
546 	void __user *dirent;
547 	int result;
548 	/* for dir ioctl */
549 	const char *longname;
550 	int long_len;
551 	const char *shortname;
552 	int short_len;
553 };
554 
555 static int __fat_readdir(struct inode *inode, struct file *file,
556 			 struct dir_context *ctx, int short_only,
557 			 struct fat_ioctl_filldir_callback *both)
558 {
559 	struct super_block *sb = inode->i_sb;
560 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
561 	struct buffer_head *bh;
562 	struct msdos_dir_entry *de;
563 	unsigned char nr_slots;
564 	wchar_t *unicode = NULL;
565 	unsigned char bufname[FAT_MAX_SHORT_SIZE];
566 	int isvfat = sbi->options.isvfat;
567 	const char *fill_name = NULL;
568 	int fake_offset = 0;
569 	loff_t cpos;
570 	int short_len = 0, fill_len = 0;
571 	int ret = 0;
572 
573 	mutex_lock(&sbi->s_lock);
574 
575 	cpos = ctx->pos;
576 	/* Fake . and .. for the root directory. */
577 	if (inode->i_ino == MSDOS_ROOT_INO) {
578 		if (!dir_emit_dots(file, ctx))
579 			goto out;
580 		if (ctx->pos == 2) {
581 			fake_offset = 1;
582 			cpos = 0;
583 		}
584 	}
585 	if (cpos & (sizeof(struct msdos_dir_entry) - 1)) {
586 		ret = -ENOENT;
587 		goto out;
588 	}
589 
590 	bh = NULL;
591 get_new:
592 	if (fat_get_entry(inode, &cpos, &bh, &de) == -1)
593 		goto end_of_dir;
594 parse_record:
595 	nr_slots = 0;
596 	/*
597 	 * Check for long filename entry, but if short_only, we don't
598 	 * need to parse long filename.
599 	 */
600 	if (isvfat && !short_only) {
601 		if (de->name[0] == DELETED_FLAG)
602 			goto record_end;
603 		if (de->attr != ATTR_EXT && (de->attr & ATTR_VOLUME))
604 			goto record_end;
605 		if (de->attr != ATTR_EXT && IS_FREE(de->name))
606 			goto record_end;
607 	} else {
608 		if ((de->attr & ATTR_VOLUME) || IS_FREE(de->name))
609 			goto record_end;
610 	}
611 
612 	if (isvfat && de->attr == ATTR_EXT) {
613 		int status = fat_parse_long(inode, &cpos, &bh, &de,
614 					    &unicode, &nr_slots);
615 		if (status < 0) {
616 			bh = NULL;
617 			ret = status;
618 			goto end_of_dir;
619 		} else if (status == PARSE_INVALID)
620 			goto record_end;
621 		else if (status == PARSE_NOT_LONGNAME)
622 			goto parse_record;
623 		else if (status == PARSE_EOF)
624 			goto end_of_dir;
625 
626 		if (nr_slots) {
627 			void *longname = unicode + FAT_MAX_UNI_CHARS;
628 			int size = PATH_MAX - FAT_MAX_UNI_SIZE;
629 			int len = fat_uni_to_x8(sb, unicode, longname, size);
630 
631 			fill_name = longname;
632 			fill_len = len;
633 			/* !both && !short_only, so we don't need shortname. */
634 			if (!both)
635 				goto start_filldir;
636 
637 			short_len = fat_parse_short(sb, de, bufname,
638 						    sbi->options.dotsOK);
639 			if (short_len == 0)
640 				goto record_end;
641 			/* hack for fat_ioctl_filldir() */
642 			both->longname = fill_name;
643 			both->long_len = fill_len;
644 			both->shortname = bufname;
645 			both->short_len = short_len;
646 			fill_name = NULL;
647 			fill_len = 0;
648 			goto start_filldir;
649 		}
650 	}
651 
652 	short_len = fat_parse_short(sb, de, bufname, sbi->options.dotsOK);
653 	if (short_len == 0)
654 		goto record_end;
655 
656 	fill_name = bufname;
657 	fill_len = short_len;
658 
659 start_filldir:
660 	ctx->pos = cpos - (nr_slots + 1) * sizeof(struct msdos_dir_entry);
661 	if (fake_offset && ctx->pos < 2)
662 		ctx->pos = 2;
663 
664 	if (!memcmp(de->name, MSDOS_DOT, MSDOS_NAME)) {
665 		if (!dir_emit_dot(file, ctx))
666 			goto fill_failed;
667 	} else if (!memcmp(de->name, MSDOS_DOTDOT, MSDOS_NAME)) {
668 		if (!dir_emit_dotdot(file, ctx))
669 			goto fill_failed;
670 	} else {
671 		unsigned long inum;
672 		loff_t i_pos = fat_make_i_pos(sb, bh, de);
673 		struct inode *tmp = fat_iget(sb, i_pos);
674 		if (tmp) {
675 			inum = tmp->i_ino;
676 			iput(tmp);
677 		} else
678 			inum = iunique(sb, MSDOS_ROOT_INO);
679 		if (!dir_emit(ctx, fill_name, fill_len, inum,
680 			    (de->attr & ATTR_DIR) ? DT_DIR : DT_REG))
681 			goto fill_failed;
682 	}
683 
684 record_end:
685 	fake_offset = 0;
686 	ctx->pos = cpos;
687 	goto get_new;
688 
689 end_of_dir:
690 	if (fake_offset && cpos < 2)
691 		ctx->pos = 2;
692 	else
693 		ctx->pos = cpos;
694 fill_failed:
695 	brelse(bh);
696 	if (unicode)
697 		__putname(unicode);
698 out:
699 	mutex_unlock(&sbi->s_lock);
700 
701 	return ret;
702 }
703 
704 static int fat_readdir(struct file *file, struct dir_context *ctx)
705 {
706 	return __fat_readdir(file_inode(file), file, ctx, 0, NULL);
707 }
708 
709 #define FAT_IOCTL_FILLDIR_FUNC(func, dirent_type)			   \
710 static int func(struct dir_context *ctx, const char *name, int name_len,   \
711 			     loff_t offset, u64 ino, unsigned int d_type)  \
712 {									   \
713 	struct fat_ioctl_filldir_callback *buf =			   \
714 		container_of(ctx, struct fat_ioctl_filldir_callback, ctx); \
715 	struct dirent_type __user *d1 = buf->dirent;			   \
716 	struct dirent_type __user *d2 = d1 + 1;				   \
717 									   \
718 	if (buf->result)						   \
719 		return -EINVAL;						   \
720 	buf->result++;							   \
721 									   \
722 	if (name != NULL) {						   \
723 		/* dirent has only short name */			   \
724 		if (name_len >= sizeof(d1->d_name))			   \
725 			name_len = sizeof(d1->d_name) - 1;		   \
726 									   \
727 		if (put_user(0, d2->d_name)			||	   \
728 		    put_user(0, &d2->d_reclen)			||	   \
729 		    copy_to_user(d1->d_name, name, name_len)	||	   \
730 		    put_user(0, d1->d_name + name_len)		||	   \
731 		    put_user(name_len, &d1->d_reclen))			   \
732 			goto efault;					   \
733 	} else {							   \
734 		/* dirent has short and long name */			   \
735 		const char *longname = buf->longname;			   \
736 		int long_len = buf->long_len;				   \
737 		const char *shortname = buf->shortname;			   \
738 		int short_len = buf->short_len;				   \
739 									   \
740 		if (long_len >= sizeof(d1->d_name))			   \
741 			long_len = sizeof(d1->d_name) - 1;		   \
742 		if (short_len >= sizeof(d1->d_name))			   \
743 			short_len = sizeof(d1->d_name) - 1;		   \
744 									   \
745 		if (copy_to_user(d2->d_name, longname, long_len)	|| \
746 		    put_user(0, d2->d_name + long_len)			|| \
747 		    put_user(long_len, &d2->d_reclen)			|| \
748 		    put_user(ino, &d2->d_ino)				|| \
749 		    put_user(offset, &d2->d_off)			|| \
750 		    copy_to_user(d1->d_name, shortname, short_len)	|| \
751 		    put_user(0, d1->d_name + short_len)			|| \
752 		    put_user(short_len, &d1->d_reclen))			   \
753 			goto efault;					   \
754 	}								   \
755 	return 0;							   \
756 efault:									   \
757 	buf->result = -EFAULT;						   \
758 	return -EFAULT;							   \
759 }
760 
761 FAT_IOCTL_FILLDIR_FUNC(fat_ioctl_filldir, __fat_dirent)
762 
763 static int fat_ioctl_readdir(struct inode *inode, struct file *file,
764 			     void __user *dirent, filldir_t filldir,
765 			     int short_only, int both)
766 {
767 	struct fat_ioctl_filldir_callback buf = {
768 		.ctx.actor = filldir,
769 		.dirent = dirent
770 	};
771 	int ret;
772 
773 	buf.dirent = dirent;
774 	buf.result = 0;
775 	inode_lock_shared(inode);
776 	buf.ctx.pos = file->f_pos;
777 	ret = -ENOENT;
778 	if (!IS_DEADDIR(inode)) {
779 		ret = __fat_readdir(inode, file, &buf.ctx,
780 				    short_only, both ? &buf : NULL);
781 		file->f_pos = buf.ctx.pos;
782 	}
783 	inode_unlock_shared(inode);
784 	if (ret >= 0)
785 		ret = buf.result;
786 	return ret;
787 }
788 
789 static long fat_dir_ioctl(struct file *filp, unsigned int cmd,
790 			  unsigned long arg)
791 {
792 	struct inode *inode = file_inode(filp);
793 	struct __fat_dirent __user *d1 = (struct __fat_dirent __user *)arg;
794 	int short_only, both;
795 
796 	switch (cmd) {
797 	case VFAT_IOCTL_READDIR_SHORT:
798 		short_only = 1;
799 		both = 0;
800 		break;
801 	case VFAT_IOCTL_READDIR_BOTH:
802 		short_only = 0;
803 		both = 1;
804 		break;
805 	default:
806 		return fat_generic_ioctl(filp, cmd, arg);
807 	}
808 
809 	if (!access_ok(d1, sizeof(struct __fat_dirent[2])))
810 		return -EFAULT;
811 	/*
812 	 * Yes, we don't need this put_user() absolutely. However old
813 	 * code didn't return the right value. So, app use this value,
814 	 * in order to check whether it is EOF.
815 	 */
816 	if (put_user(0, &d1->d_reclen))
817 		return -EFAULT;
818 
819 	return fat_ioctl_readdir(inode, filp, d1, fat_ioctl_filldir,
820 				 short_only, both);
821 }
822 
823 #ifdef CONFIG_COMPAT
824 #define	VFAT_IOCTL_READDIR_BOTH32	_IOR('r', 1, struct compat_dirent[2])
825 #define	VFAT_IOCTL_READDIR_SHORT32	_IOR('r', 2, struct compat_dirent[2])
826 
827 FAT_IOCTL_FILLDIR_FUNC(fat_compat_ioctl_filldir, compat_dirent)
828 
829 static long fat_compat_dir_ioctl(struct file *filp, unsigned cmd,
830 				 unsigned long arg)
831 {
832 	struct inode *inode = file_inode(filp);
833 	struct compat_dirent __user *d1 = compat_ptr(arg);
834 	int short_only, both;
835 
836 	switch (cmd) {
837 	case VFAT_IOCTL_READDIR_SHORT32:
838 		short_only = 1;
839 		both = 0;
840 		break;
841 	case VFAT_IOCTL_READDIR_BOTH32:
842 		short_only = 0;
843 		both = 1;
844 		break;
845 	default:
846 		return fat_generic_ioctl(filp, cmd, (unsigned long)arg);
847 	}
848 
849 	if (!access_ok(d1, sizeof(struct compat_dirent[2])))
850 		return -EFAULT;
851 	/*
852 	 * Yes, we don't need this put_user() absolutely. However old
853 	 * code didn't return the right value. So, app use this value,
854 	 * in order to check whether it is EOF.
855 	 */
856 	if (put_user(0, &d1->d_reclen))
857 		return -EFAULT;
858 
859 	return fat_ioctl_readdir(inode, filp, d1, fat_compat_ioctl_filldir,
860 				 short_only, both);
861 }
862 #endif /* CONFIG_COMPAT */
863 
864 const struct file_operations fat_dir_operations = {
865 	.llseek		= generic_file_llseek,
866 	.read		= generic_read_dir,
867 	.iterate_shared	= fat_readdir,
868 	.unlocked_ioctl	= fat_dir_ioctl,
869 #ifdef CONFIG_COMPAT
870 	.compat_ioctl	= fat_compat_dir_ioctl,
871 #endif
872 	.fsync		= fat_file_fsync,
873 };
874 
875 static int fat_get_short_entry(struct inode *dir, loff_t *pos,
876 			       struct buffer_head **bh,
877 			       struct msdos_dir_entry **de)
878 {
879 	while (fat_get_entry(dir, pos, bh, de) >= 0) {
880 		/* free entry or long name entry or volume label */
881 		if (!IS_FREE((*de)->name) && !((*de)->attr & ATTR_VOLUME))
882 			return 0;
883 	}
884 	return -ENOENT;
885 }
886 
887 /*
888  * The ".." entry can not provide the "struct fat_slot_info" information
889  * for inode, nor a usable i_pos. So, this function provides some information
890  * only.
891  *
892  * Since this function walks through the on-disk inodes within a directory,
893  * callers are responsible for taking any locks necessary to prevent the
894  * directory from changing.
895  */
896 int fat_get_dotdot_entry(struct inode *dir, struct buffer_head **bh,
897 			 struct msdos_dir_entry **de)
898 {
899 	loff_t offset = 0;
900 
901 	*de = NULL;
902 	while (fat_get_short_entry(dir, &offset, bh, de) >= 0) {
903 		if (!strncmp((*de)->name, MSDOS_DOTDOT, MSDOS_NAME))
904 			return 0;
905 	}
906 	return -ENOENT;
907 }
908 EXPORT_SYMBOL_GPL(fat_get_dotdot_entry);
909 
910 /* See if directory is empty */
911 int fat_dir_empty(struct inode *dir)
912 {
913 	struct buffer_head *bh;
914 	struct msdos_dir_entry *de;
915 	loff_t cpos;
916 	int result = 0;
917 
918 	bh = NULL;
919 	cpos = 0;
920 	while (fat_get_short_entry(dir, &cpos, &bh, &de) >= 0) {
921 		if (strncmp(de->name, MSDOS_DOT   , MSDOS_NAME) &&
922 		    strncmp(de->name, MSDOS_DOTDOT, MSDOS_NAME)) {
923 			result = -ENOTEMPTY;
924 			break;
925 		}
926 	}
927 	brelse(bh);
928 	return result;
929 }
930 EXPORT_SYMBOL_GPL(fat_dir_empty);
931 
932 /*
933  * fat_subdirs counts the number of sub-directories of dir. It can be run
934  * on directories being created.
935  */
936 int fat_subdirs(struct inode *dir)
937 {
938 	struct buffer_head *bh;
939 	struct msdos_dir_entry *de;
940 	loff_t cpos;
941 	int count = 0;
942 
943 	bh = NULL;
944 	cpos = 0;
945 	while (fat_get_short_entry(dir, &cpos, &bh, &de) >= 0) {
946 		if (de->attr & ATTR_DIR)
947 			count++;
948 	}
949 	brelse(bh);
950 	return count;
951 }
952 
953 /*
954  * Scans a directory for a given file (name points to its formatted name).
955  * Returns an error code or zero.
956  */
957 int fat_scan(struct inode *dir, const unsigned char *name,
958 	     struct fat_slot_info *sinfo)
959 {
960 	struct super_block *sb = dir->i_sb;
961 
962 	sinfo->slot_off = 0;
963 	sinfo->bh = NULL;
964 	while (fat_get_short_entry(dir, &sinfo->slot_off, &sinfo->bh,
965 				   &sinfo->de) >= 0) {
966 		if (!strncmp(sinfo->de->name, name, MSDOS_NAME)) {
967 			sinfo->slot_off -= sizeof(*sinfo->de);
968 			sinfo->nr_slots = 1;
969 			sinfo->i_pos = fat_make_i_pos(sb, sinfo->bh, sinfo->de);
970 			return 0;
971 		}
972 	}
973 	return -ENOENT;
974 }
975 EXPORT_SYMBOL_GPL(fat_scan);
976 
977 /*
978  * Scans a directory for a given logstart.
979  * Returns an error code or zero.
980  */
981 int fat_scan_logstart(struct inode *dir, int i_logstart,
982 		      struct fat_slot_info *sinfo)
983 {
984 	struct super_block *sb = dir->i_sb;
985 
986 	sinfo->slot_off = 0;
987 	sinfo->bh = NULL;
988 	while (fat_get_short_entry(dir, &sinfo->slot_off, &sinfo->bh,
989 				   &sinfo->de) >= 0) {
990 		if (fat_get_start(MSDOS_SB(sb), sinfo->de) == i_logstart) {
991 			sinfo->slot_off -= sizeof(*sinfo->de);
992 			sinfo->nr_slots = 1;
993 			sinfo->i_pos = fat_make_i_pos(sb, sinfo->bh, sinfo->de);
994 			return 0;
995 		}
996 	}
997 	return -ENOENT;
998 }
999 
1000 static int __fat_remove_entries(struct inode *dir, loff_t pos, int nr_slots)
1001 {
1002 	struct super_block *sb = dir->i_sb;
1003 	struct buffer_head *bh;
1004 	struct msdos_dir_entry *de, *endp;
1005 	int err = 0, orig_slots;
1006 
1007 	while (nr_slots) {
1008 		bh = NULL;
1009 		if (fat_get_entry(dir, &pos, &bh, &de) < 0) {
1010 			err = -EIO;
1011 			break;
1012 		}
1013 
1014 		orig_slots = nr_slots;
1015 		endp = (struct msdos_dir_entry *)(bh->b_data + sb->s_blocksize);
1016 		while (nr_slots && de < endp) {
1017 			de->name[0] = DELETED_FLAG;
1018 			de++;
1019 			nr_slots--;
1020 		}
1021 		mark_buffer_dirty_inode(bh, dir);
1022 		if (IS_DIRSYNC(dir))
1023 			err = sync_dirty_buffer(bh);
1024 		brelse(bh);
1025 		if (err)
1026 			break;
1027 
1028 		/* pos is *next* de's position, so this does `- sizeof(de)' */
1029 		pos += ((orig_slots - nr_slots) * sizeof(*de)) - sizeof(*de);
1030 	}
1031 
1032 	return err;
1033 }
1034 
1035 int fat_remove_entries(struct inode *dir, struct fat_slot_info *sinfo)
1036 {
1037 	struct super_block *sb = dir->i_sb;
1038 	struct msdos_dir_entry *de;
1039 	struct buffer_head *bh;
1040 	int err = 0, nr_slots;
1041 
1042 	/*
1043 	 * First stage: Remove the shortname. By this, the directory
1044 	 * entry is removed.
1045 	 */
1046 	nr_slots = sinfo->nr_slots;
1047 	de = sinfo->de;
1048 	sinfo->de = NULL;
1049 	bh = sinfo->bh;
1050 	sinfo->bh = NULL;
1051 	while (nr_slots && de >= (struct msdos_dir_entry *)bh->b_data) {
1052 		de->name[0] = DELETED_FLAG;
1053 		de--;
1054 		nr_slots--;
1055 	}
1056 	mark_buffer_dirty_inode(bh, dir);
1057 	if (IS_DIRSYNC(dir))
1058 		err = sync_dirty_buffer(bh);
1059 	brelse(bh);
1060 	if (err)
1061 		return err;
1062 	inode_inc_iversion(dir);
1063 
1064 	if (nr_slots) {
1065 		/*
1066 		 * Second stage: remove the remaining longname slots.
1067 		 * (This directory entry is already removed, and so return
1068 		 * the success)
1069 		 */
1070 		err = __fat_remove_entries(dir, sinfo->slot_off, nr_slots);
1071 		if (err) {
1072 			fat_msg(sb, KERN_WARNING,
1073 			       "Couldn't remove the long name slots");
1074 		}
1075 	}
1076 
1077 	fat_truncate_time(dir, NULL, S_ATIME|S_MTIME);
1078 	if (IS_DIRSYNC(dir))
1079 		(void)fat_sync_inode(dir);
1080 	else
1081 		mark_inode_dirty(dir);
1082 
1083 	return 0;
1084 }
1085 EXPORT_SYMBOL_GPL(fat_remove_entries);
1086 
1087 static int fat_zeroed_cluster(struct inode *dir, sector_t blknr, int nr_used,
1088 			      struct buffer_head **bhs, int nr_bhs)
1089 {
1090 	struct super_block *sb = dir->i_sb;
1091 	sector_t last_blknr = blknr + MSDOS_SB(sb)->sec_per_clus;
1092 	int err, i, n;
1093 
1094 	/* Zeroing the unused blocks on this cluster */
1095 	blknr += nr_used;
1096 	n = nr_used;
1097 	while (blknr < last_blknr) {
1098 		bhs[n] = sb_getblk(sb, blknr);
1099 		if (!bhs[n]) {
1100 			err = -ENOMEM;
1101 			goto error;
1102 		}
1103 		memset(bhs[n]->b_data, 0, sb->s_blocksize);
1104 		set_buffer_uptodate(bhs[n]);
1105 		mark_buffer_dirty_inode(bhs[n], dir);
1106 
1107 		n++;
1108 		blknr++;
1109 		if (n == nr_bhs) {
1110 			if (IS_DIRSYNC(dir)) {
1111 				err = fat_sync_bhs(bhs, n);
1112 				if (err)
1113 					goto error;
1114 			}
1115 			for (i = 0; i < n; i++)
1116 				brelse(bhs[i]);
1117 			n = 0;
1118 		}
1119 	}
1120 	if (IS_DIRSYNC(dir)) {
1121 		err = fat_sync_bhs(bhs, n);
1122 		if (err)
1123 			goto error;
1124 	}
1125 	for (i = 0; i < n; i++)
1126 		brelse(bhs[i]);
1127 
1128 	return 0;
1129 
1130 error:
1131 	for (i = 0; i < n; i++)
1132 		bforget(bhs[i]);
1133 	return err;
1134 }
1135 
1136 int fat_alloc_new_dir(struct inode *dir, struct timespec64 *ts)
1137 {
1138 	struct super_block *sb = dir->i_sb;
1139 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
1140 	struct buffer_head *bhs[MAX_BUF_PER_PAGE];
1141 	struct msdos_dir_entry *de;
1142 	sector_t blknr;
1143 	__le16 date, time;
1144 	u8 time_cs;
1145 	int err, cluster;
1146 
1147 	err = fat_alloc_clusters(dir, &cluster, 1);
1148 	if (err)
1149 		goto error;
1150 
1151 	blknr = fat_clus_to_blknr(sbi, cluster);
1152 	bhs[0] = sb_getblk(sb, blknr);
1153 	if (!bhs[0]) {
1154 		err = -ENOMEM;
1155 		goto error_free;
1156 	}
1157 
1158 	fat_time_unix2fat(sbi, ts, &time, &date, &time_cs);
1159 
1160 	de = (struct msdos_dir_entry *)bhs[0]->b_data;
1161 	/* filling the new directory slots ("." and ".." entries) */
1162 	memcpy(de[0].name, MSDOS_DOT, MSDOS_NAME);
1163 	memcpy(de[1].name, MSDOS_DOTDOT, MSDOS_NAME);
1164 	de->attr = de[1].attr = ATTR_DIR;
1165 	de[0].lcase = de[1].lcase = 0;
1166 	de[0].time = de[1].time = time;
1167 	de[0].date = de[1].date = date;
1168 	if (sbi->options.isvfat) {
1169 		/* extra timestamps */
1170 		de[0].ctime = de[1].ctime = time;
1171 		de[0].ctime_cs = de[1].ctime_cs = time_cs;
1172 		de[0].adate = de[0].cdate = de[1].adate = de[1].cdate = date;
1173 	} else {
1174 		de[0].ctime = de[1].ctime = 0;
1175 		de[0].ctime_cs = de[1].ctime_cs = 0;
1176 		de[0].adate = de[0].cdate = de[1].adate = de[1].cdate = 0;
1177 	}
1178 	fat_set_start(&de[0], cluster);
1179 	fat_set_start(&de[1], MSDOS_I(dir)->i_logstart);
1180 	de[0].size = de[1].size = 0;
1181 	memset(de + 2, 0, sb->s_blocksize - 2 * sizeof(*de));
1182 	set_buffer_uptodate(bhs[0]);
1183 	mark_buffer_dirty_inode(bhs[0], dir);
1184 
1185 	err = fat_zeroed_cluster(dir, blknr, 1, bhs, MAX_BUF_PER_PAGE);
1186 	if (err)
1187 		goto error_free;
1188 
1189 	return cluster;
1190 
1191 error_free:
1192 	fat_free_clusters(dir, cluster);
1193 error:
1194 	return err;
1195 }
1196 EXPORT_SYMBOL_GPL(fat_alloc_new_dir);
1197 
1198 static int fat_add_new_entries(struct inode *dir, void *slots, int nr_slots,
1199 			       int *nr_cluster, struct msdos_dir_entry **de,
1200 			       struct buffer_head **bh, loff_t *i_pos)
1201 {
1202 	struct super_block *sb = dir->i_sb;
1203 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
1204 	struct buffer_head *bhs[MAX_BUF_PER_PAGE];
1205 	sector_t blknr, start_blknr, last_blknr;
1206 	unsigned long size, copy;
1207 	int err, i, n, offset, cluster[2];
1208 
1209 	/*
1210 	 * The minimum cluster size is 512bytes, and maximum entry
1211 	 * size is 32*slots (672bytes).  So, iff the cluster size is
1212 	 * 512bytes, we may need two clusters.
1213 	 */
1214 	size = nr_slots * sizeof(struct msdos_dir_entry);
1215 	*nr_cluster = (size + (sbi->cluster_size - 1)) >> sbi->cluster_bits;
1216 	BUG_ON(*nr_cluster > 2);
1217 
1218 	err = fat_alloc_clusters(dir, cluster, *nr_cluster);
1219 	if (err)
1220 		goto error;
1221 
1222 	/*
1223 	 * First stage: Fill the directory entry.  NOTE: This cluster
1224 	 * is not referenced from any inode yet, so updates order is
1225 	 * not important.
1226 	 */
1227 	i = n = copy = 0;
1228 	do {
1229 		start_blknr = blknr = fat_clus_to_blknr(sbi, cluster[i]);
1230 		last_blknr = start_blknr + sbi->sec_per_clus;
1231 		while (blknr < last_blknr) {
1232 			bhs[n] = sb_getblk(sb, blknr);
1233 			if (!bhs[n]) {
1234 				err = -ENOMEM;
1235 				goto error_nomem;
1236 			}
1237 
1238 			/* fill the directory entry */
1239 			copy = min(size, sb->s_blocksize);
1240 			memcpy(bhs[n]->b_data, slots, copy);
1241 			slots += copy;
1242 			size -= copy;
1243 			set_buffer_uptodate(bhs[n]);
1244 			mark_buffer_dirty_inode(bhs[n], dir);
1245 			if (!size)
1246 				break;
1247 			n++;
1248 			blknr++;
1249 		}
1250 	} while (++i < *nr_cluster);
1251 
1252 	memset(bhs[n]->b_data + copy, 0, sb->s_blocksize - copy);
1253 	offset = copy - sizeof(struct msdos_dir_entry);
1254 	get_bh(bhs[n]);
1255 	*bh = bhs[n];
1256 	*de = (struct msdos_dir_entry *)((*bh)->b_data + offset);
1257 	*i_pos = fat_make_i_pos(sb, *bh, *de);
1258 
1259 	/* Second stage: clear the rest of cluster, and write outs */
1260 	err = fat_zeroed_cluster(dir, start_blknr, ++n, bhs, MAX_BUF_PER_PAGE);
1261 	if (err)
1262 		goto error_free;
1263 
1264 	return cluster[0];
1265 
1266 error_free:
1267 	brelse(*bh);
1268 	*bh = NULL;
1269 	n = 0;
1270 error_nomem:
1271 	for (i = 0; i < n; i++)
1272 		bforget(bhs[i]);
1273 	fat_free_clusters(dir, cluster[0]);
1274 error:
1275 	return err;
1276 }
1277 
1278 int fat_add_entries(struct inode *dir, void *slots, int nr_slots,
1279 		    struct fat_slot_info *sinfo)
1280 {
1281 	struct super_block *sb = dir->i_sb;
1282 	struct msdos_sb_info *sbi = MSDOS_SB(sb);
1283 	struct buffer_head *bh, *prev, *bhs[3]; /* 32*slots (672bytes) */
1284 	struct msdos_dir_entry *uninitialized_var(de);
1285 	int err, free_slots, i, nr_bhs;
1286 	loff_t pos, i_pos;
1287 
1288 	sinfo->nr_slots = nr_slots;
1289 
1290 	/* First stage: search free directory entries */
1291 	free_slots = nr_bhs = 0;
1292 	bh = prev = NULL;
1293 	pos = 0;
1294 	err = -ENOSPC;
1295 	while (fat_get_entry(dir, &pos, &bh, &de) > -1) {
1296 		/* check the maximum size of directory */
1297 		if (pos >= FAT_MAX_DIR_SIZE)
1298 			goto error;
1299 
1300 		if (IS_FREE(de->name)) {
1301 			if (prev != bh) {
1302 				get_bh(bh);
1303 				bhs[nr_bhs] = prev = bh;
1304 				nr_bhs++;
1305 			}
1306 			free_slots++;
1307 			if (free_slots == nr_slots)
1308 				goto found;
1309 		} else {
1310 			for (i = 0; i < nr_bhs; i++)
1311 				brelse(bhs[i]);
1312 			prev = NULL;
1313 			free_slots = nr_bhs = 0;
1314 		}
1315 	}
1316 	if (dir->i_ino == MSDOS_ROOT_INO) {
1317 		if (!is_fat32(sbi))
1318 			goto error;
1319 	} else if (MSDOS_I(dir)->i_start == 0) {
1320 		fat_msg(sb, KERN_ERR, "Corrupted directory (i_pos %lld)",
1321 		       MSDOS_I(dir)->i_pos);
1322 		err = -EIO;
1323 		goto error;
1324 	}
1325 
1326 found:
1327 	err = 0;
1328 	pos -= free_slots * sizeof(*de);
1329 	nr_slots -= free_slots;
1330 	if (free_slots) {
1331 		/*
1332 		 * Second stage: filling the free entries with new entries.
1333 		 * NOTE: If this slots has shortname, first, we write
1334 		 * the long name slots, then write the short name.
1335 		 */
1336 		int size = free_slots * sizeof(*de);
1337 		int offset = pos & (sb->s_blocksize - 1);
1338 		int long_bhs = nr_bhs - (nr_slots == 0);
1339 
1340 		/* Fill the long name slots. */
1341 		for (i = 0; i < long_bhs; i++) {
1342 			int copy = min_t(int, sb->s_blocksize - offset, size);
1343 			memcpy(bhs[i]->b_data + offset, slots, copy);
1344 			mark_buffer_dirty_inode(bhs[i], dir);
1345 			offset = 0;
1346 			slots += copy;
1347 			size -= copy;
1348 		}
1349 		if (long_bhs && IS_DIRSYNC(dir))
1350 			err = fat_sync_bhs(bhs, long_bhs);
1351 		if (!err && i < nr_bhs) {
1352 			/* Fill the short name slot. */
1353 			int copy = min_t(int, sb->s_blocksize - offset, size);
1354 			memcpy(bhs[i]->b_data + offset, slots, copy);
1355 			mark_buffer_dirty_inode(bhs[i], dir);
1356 			if (IS_DIRSYNC(dir))
1357 				err = sync_dirty_buffer(bhs[i]);
1358 		}
1359 		for (i = 0; i < nr_bhs; i++)
1360 			brelse(bhs[i]);
1361 		if (err)
1362 			goto error_remove;
1363 	}
1364 
1365 	if (nr_slots) {
1366 		int cluster, nr_cluster;
1367 
1368 		/*
1369 		 * Third stage: allocate the cluster for new entries.
1370 		 * And initialize the cluster with new entries, then
1371 		 * add the cluster to dir.
1372 		 */
1373 		cluster = fat_add_new_entries(dir, slots, nr_slots, &nr_cluster,
1374 					      &de, &bh, &i_pos);
1375 		if (cluster < 0) {
1376 			err = cluster;
1377 			goto error_remove;
1378 		}
1379 		err = fat_chain_add(dir, cluster, nr_cluster);
1380 		if (err) {
1381 			fat_free_clusters(dir, cluster);
1382 			goto error_remove;
1383 		}
1384 		if (dir->i_size & (sbi->cluster_size - 1)) {
1385 			fat_fs_error(sb, "Odd directory size");
1386 			dir->i_size = (dir->i_size + sbi->cluster_size - 1)
1387 				& ~((loff_t)sbi->cluster_size - 1);
1388 		}
1389 		dir->i_size += nr_cluster << sbi->cluster_bits;
1390 		MSDOS_I(dir)->mmu_private += nr_cluster << sbi->cluster_bits;
1391 	}
1392 	sinfo->slot_off = pos;
1393 	sinfo->de = de;
1394 	sinfo->bh = bh;
1395 	sinfo->i_pos = fat_make_i_pos(sb, sinfo->bh, sinfo->de);
1396 
1397 	return 0;
1398 
1399 error:
1400 	brelse(bh);
1401 	for (i = 0; i < nr_bhs; i++)
1402 		brelse(bhs[i]);
1403 	return err;
1404 
1405 error_remove:
1406 	brelse(bh);
1407 	if (free_slots)
1408 		__fat_remove_entries(dir, pos, free_slots);
1409 	return err;
1410 }
1411 EXPORT_SYMBOL_GPL(fat_add_entries);
1412