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