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