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