Subversion Repositories freemyipod

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
211 theseven 1
/***************************************************************************
2
 *             __________               __   ___.
3
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
4
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
5
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
6
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
7
 *                     \/            \/     \/    \/            \/
8
 * $Id: fat.c 25459 2010-04-03 22:02:09Z gevaerts $
9
 *
10
 * Copyright (C) 2002 by Linus Nielsen Feltzing
11
 *
12
 * This program is free software; you can redistribute it and/or
13
 * modify it under the terms of the GNU General Public License
14
 * as published by the Free Software Foundation; either version 2
15
 * of the License, or (at your option) any later version.
16
 *
17
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18
 * KIND, either express or implied.
19
 *
20
 ****************************************************************************/
21
#include "global.h"
22
#include "thread.h"
23
#include "libc/include/string.h"
24
#include "libc/include/stdio.h"
25
#include "fat.h"
26
#include "storage.h"
27
#include "debug.h"
28
#include "panic.h"
29
#include "libc/include/ctype.h"
30
 
31
#define BYTES2INT16(array,pos) \
32
          (array[pos] | (array[pos+1] << 8 ))
33
#define BYTES2INT32(array,pos) \
34
    ((long)array[pos] | ((long)array[pos+1] << 8 ) | \
35
    ((long)array[pos+2] << 16 ) | ((long)array[pos+3] << 24 ))
36
 
37
#define FATTYPE_FAT12       0
38
#define FATTYPE_FAT16       1
39
#define FATTYPE_FAT32       2
40
 
41
/* BPB offsets; generic */
42
#define BS_JMPBOOT          0
43
#define BS_OEMNAME          3
44
#define BPB_BYTSPERSEC      11
45
#define BPB_SECPERCLUS      13
46
#define BPB_RSVDSECCNT      14
47
#define BPB_NUMFATS         16
48
#define BPB_ROOTENTCNT      17
49
#define BPB_TOTSEC16        19
50
#define BPB_MEDIA           21
51
#define BPB_FATSZ16         22
52
#define BPB_SECPERTRK       24
53
#define BPB_NUMHEADS        26
54
#define BPB_HIDDSEC         28
55
#define BPB_TOTSEC32        32
56
 
57
/* fat12/16 */
58
#define BS_DRVNUM           36
59
#define BS_RESERVED1        37
60
#define BS_BOOTSIG          38
61
#define BS_VOLID            39
62
#define BS_VOLLAB           43
63
#define BS_FILSYSTYPE       54
64
 
65
/* fat32 */
66
#define BPB_FATSZ32         36
67
#define BPB_EXTFLAGS        40
68
#define BPB_FSVER           42
69
#define BPB_ROOTCLUS        44
70
#define BPB_FSINFO          48
71
#define BPB_BKBOOTSEC       50
72
#define BS_32_DRVNUM        64
73
#define BS_32_BOOTSIG       66
74
#define BS_32_VOLID         67
75
#define BS_32_VOLLAB        71
76
#define BS_32_FILSYSTYPE    82
77
 
78
#define BPB_LAST_WORD       510
79
 
80
 
81
/* attributes */
82
#define FAT_ATTR_LONG_NAME   (FAT_ATTR_READ_ONLY | FAT_ATTR_HIDDEN | \
83
                              FAT_ATTR_SYSTEM | FAT_ATTR_VOLUME_ID)
84
#define FAT_ATTR_LONG_NAME_MASK (FAT_ATTR_READ_ONLY | FAT_ATTR_HIDDEN | \
85
                                 FAT_ATTR_SYSTEM | FAT_ATTR_VOLUME_ID | \
86
                                 FAT_ATTR_DIRECTORY | FAT_ATTR_ARCHIVE )
87
 
88
/* NTRES flags */
89
#define FAT_NTRES_LC_NAME    0x08
90
#define FAT_NTRES_LC_EXT     0x10
91
 
92
#define FATDIR_NAME          0
93
#define FATDIR_ATTR          11
94
#define FATDIR_NTRES         12
95
#define FATDIR_CRTTIMETENTH  13
96
#define FATDIR_CRTTIME       14
97
#define FATDIR_CRTDATE       16
98
#define FATDIR_LSTACCDATE    18
99
#define FATDIR_FSTCLUSHI     20
100
#define FATDIR_WRTTIME       22
101
#define FATDIR_WRTDATE       24
102
#define FATDIR_FSTCLUSLO     26
103
#define FATDIR_FILESIZE      28
104
 
105
#define FATLONG_ORDER        0
106
#define FATLONG_TYPE         12
107
#define FATLONG_CHKSUM       13
108
#define FATLONG_LAST_LONG_ENTRY 0x40
109
#define FATLONG_NAME_BYTES_PER_ENTRY 26
110
/* at most 20 LFN entries, keep coherent with fat_dir->longname size ! */
111
#define FATLONG_MAX_ORDER    20
112
 
113
#define FATLONG_NAME_CHUNKS 3
114
static unsigned char FATLONG_NAME_POS[FATLONG_NAME_CHUNKS] = {1, 14, 28};
115
static unsigned char FATLONG_NAME_SIZE[FATLONG_NAME_CHUNKS] = {10, 12, 4};
116
 
117
#define CLUSTERS_PER_FAT_SECTOR (SECTOR_SIZE / 4)
118
#define CLUSTERS_PER_FAT16_SECTOR (SECTOR_SIZE / 2)
119
#define DIR_ENTRIES_PER_SECTOR  (SECTOR_SIZE / DIR_ENTRY_SIZE)
120
#define DIR_ENTRY_SIZE       32
121
#define NAME_BYTES_PER_ENTRY 13
122
#define FAT_BAD_MARK         0x0ffffff7
123
#define FAT_EOF_MARK         0x0ffffff8
124
#define FAT_LONGNAME_PAD_BYTE 0xff
125
#define FAT_LONGNAME_PAD_UCS 0xffff
126
 
127
struct fsinfo {
128
    unsigned long freecount; /* last known free cluster count */
129
    unsigned long nextfree;  /* first cluster to start looking for free
130
                               clusters, or 0xffffffff for no hint */
131
};
132
/* fsinfo offsets */
133
#define FSINFO_FREECOUNT 488
134
#define FSINFO_NEXTFREE  492
135
 
136
/* Note: This struct doesn't hold the raw values after mounting if
137
 * bpb_bytspersec isn't 512. All sector counts are normalized to 512 byte
138
 * physical sectors. */
139
struct bpb
140
{
141
    int bpb_bytspersec;  /* Bytes per sector, typically 512 */
142
    unsigned int bpb_secperclus;  /* Sectors per cluster */
143
    int bpb_rsvdseccnt;  /* Number of reserved sectors */
144
    int bpb_numfats;     /* Number of FAT structures, typically 2 */
145
    int bpb_totsec16;    /* Number of sectors on the volume (old 16-bit) */
146
    int bpb_media;       /* Media type (typically 0xf0 or 0xf8) */
147
    int bpb_fatsz16;     /* Number of used sectors per FAT structure */
148
    unsigned long bpb_totsec32;    /* Number of sectors on the volume
149
                                     (new 32-bit) */
150
    unsigned int last_word;       /* 0xAA55 */
151
 
152
    /**** FAT32 specific *****/
153
    long bpb_fatsz32;
154
    long bpb_rootclus;
155
    long bpb_fsinfo;
156
 
157
    /* variables for internal use */
158
    unsigned long fatsize;
159
    unsigned long totalsectors;
160
    unsigned long rootdirsector;
161
    unsigned long firstdatasector;
162
    unsigned long startsector;
163
    unsigned long dataclusters;
164
    struct fsinfo fsinfo;
165
#ifdef HAVE_FAT16SUPPORT
166
    int bpb_rootentcnt;  /* Number of dir entries in the root */
167
    /* internals for FAT16 support */
168
    bool is_fat16; /* true if we mounted a FAT16 partition, false if FAT32 */
169
    unsigned int rootdiroffset; /* sector offset of root dir relative to start
170
                                 * of first pseudo cluster */
171
#endif /* #ifdef HAVE_FAT16SUPPORT */
172
#ifdef HAVE_MULTIVOLUME
173
#ifdef HAVE_MULTIDRIVE
174
    int drive; /* on which physical device is this located */
175
#endif
176
    bool mounted; /* flag if this volume is mounted */
177
#endif
178
};
179
 
180
static struct bpb fat_bpbs[NUM_VOLUMES]; /* mounted partition info */
181
static bool initialized = false;
182
 
183
static int update_fsinfo(IF_MV_NONVOID(struct bpb* fat_bpb));
184
static int flush_fat(IF_MV_NONVOID(struct bpb* fat_bpb));
185
static int bpb_is_sane(IF_MV_NONVOID(struct bpb* fat_bpb));
186
static void *cache_fat_sector(IF_MV2(struct bpb* fat_bpb,)
187
                              long secnum, bool dirty);
188
static void unlock_fat_sector(IF_MV2(struct bpb* fat_bpb,)
189
                              long secnum);
190
static void create_dos_name(const unsigned char *name, unsigned char *newname);
191
static void randomize_dos_name(unsigned char *name);
192
static unsigned long find_free_cluster(IF_MV2(struct bpb* fat_bpb,)
193
                                       unsigned long start);
194
static int transfer(IF_MV2(struct bpb* fat_bpb,) unsigned long start,
195
                    long count, char* buf, bool write );
196
 
197
#define FAT_CACHE_SIZE 4
198
#define FAT_CACHE_MASK (FAT_CACHE_SIZE-1)
199
 
200
struct fat_cache_entry
201
{
202
    long secnum;
203
    bool valid;
204
    int locked;
205
    bool dirty;
206
#ifdef HAVE_MULTIVOLUME
207
    struct bpb* fat_vol; /* shared cache for all volumes */
208
#endif
209
};
210
 
211
static char fat_cache_sectors[FAT_CACHE_SIZE][SECTOR_SIZE] CACHEALIGN_ATTR;
212
static struct fat_cache_entry fat_cache[FAT_CACHE_SIZE];
213
static struct mutex cache_mutex;
214
static struct mutex tempbuf_mutex;
215
static char fat_tempbuf[SECTOR_SIZE] CACHEALIGN_ATTR;
216
static bool tempbuf_locked;
217
 
218
#if defined(HAVE_HOTSWAP) && !(CONFIG_STORAGE & STORAGE_MMC) /* A better condition ?? */
219
void fat_lock(void)
220
{
221
    mutex_lock(&cache_mutex, TIMEOUT_BLOCK);
222
}
223
 
224
void fat_unlock(void)
225
{
226
    mutex_unlock(&cache_mutex);
227
}
228
#endif
229
 
230
static long cluster2sec(IF_MV2(struct bpb* fat_bpb,) long cluster)
231
{
232
#ifndef HAVE_MULTIVOLUME
233
    struct bpb* fat_bpb = &fat_bpbs[0];
234
#endif
235
#ifdef HAVE_FAT16SUPPORT
236
    /* negative clusters (FAT16 root dir) don't get the 2 offset */
237
    int zerocluster = cluster < 0 ? 0 : 2;
238
#else
239
    const long zerocluster = 2;
240
#endif
241
 
242
    if (cluster > (long)(fat_bpb->dataclusters + 1))
243
    {
244
      DEBUGF( "cluster2sec() - Bad cluster number (%ld)", cluster);
245
        return -1;
246
    }
247
 
248
    return (cluster - zerocluster) * fat_bpb->bpb_secperclus 
249
           + fat_bpb->firstdatasector;
250
}
251
 
252
void fat_size(IF_MV2(int volume,) unsigned long* size, unsigned long* free)
253
{
254
#ifndef HAVE_MULTIVOLUME
255
    const int volume = 0;
256
#endif
257
    struct bpb* fat_bpb = &fat_bpbs[volume];
258
    if (size)
259
      *size = fat_bpb->dataclusters * (fat_bpb->bpb_secperclus * SECTOR_SIZE / 1024);
260
    if (free)
261
      *free = fat_bpb->fsinfo.freecount * (fat_bpb->bpb_secperclus * SECTOR_SIZE / 1024);
262
}
263
 
264
void fat_init(void)
265
{
266
    unsigned int i;
267
 
268
    if (!initialized)
269
    {
270
        initialized = true;
271
        mutex_init(&cache_mutex);
272
        mutex_init(&tempbuf_mutex);
273
        tempbuf_locked = false;
274
    }
275
 
276
    /* mark the FAT cache as unused */
277
    for(i = 0;i < FAT_CACHE_SIZE;i++)
278
    {
279
        fat_cache[i].secnum = -1;
280
        fat_cache[i].valid = false;
281
        fat_cache[i].locked = 0;
282
        fat_cache[i].dirty = false;
283
#ifdef HAVE_MULTIVOLUME
284
        fat_cache[i].fat_vol = NULL;
285
#endif
286
    }
287
#ifdef HAVE_MULTIVOLUME
288
    /* mark the possible volumes as not mounted */
289
    for (i=0; i<NUM_VOLUMES;i++)
290
    {
291
        fat_bpbs[i].mounted = false;
292
    }
293
#endif
294
}
295
 
296
int fat_mount(IF_MV2(int volume,) IF_MD2(int drive,) long startsector)
297
{
298
#ifndef HAVE_MULTIVOLUME
299
    const int volume = 0;
300
#endif
301
    struct bpb* fat_bpb = &fat_bpbs[volume];
302
    int rc;
303
    int secmult;
304
    long datasec;
305
#ifdef HAVE_FAT16SUPPORT
306
    int rootdirsectors;
307
#endif
308
 
309
    /* Read the sector */
310
    unsigned char* buf = fat_get_sector_buffer();
311
    rc = storage_read_sectors(IF_MD2(drive,) startsector,1,buf);
312
    if(rc)
313
    {
314
        fat_release_sector_buffer();
315
        DEBUGF( "fat_mount() - Couldn't read BPB (error code %d)", rc);
316
        return rc * 10 - 1;
317
    }
318
 
319
    memset(fat_bpb, 0, sizeof(struct bpb));
320
    fat_bpb->startsector    = startsector;
321
#ifdef HAVE_MULTIDRIVE
322
    fat_bpb->drive          = drive;
323
#endif
324
 
325
    fat_bpb->bpb_bytspersec = BYTES2INT16(buf,BPB_BYTSPERSEC);
326
    secmult = fat_bpb->bpb_bytspersec / SECTOR_SIZE; 
327
    /* Sanity check is performed later */
328
 
329
    fat_bpb->bpb_secperclus = secmult * buf[BPB_SECPERCLUS];
330
    fat_bpb->bpb_rsvdseccnt = secmult * BYTES2INT16(buf,BPB_RSVDSECCNT);
331
    fat_bpb->bpb_numfats    = buf[BPB_NUMFATS];
332
    fat_bpb->bpb_media      = buf[BPB_MEDIA];
333
    fat_bpb->bpb_fatsz16    = secmult * BYTES2INT16(buf,BPB_FATSZ16);
334
    fat_bpb->bpb_fatsz32    = secmult * BYTES2INT32(buf,BPB_FATSZ32);
335
    fat_bpb->bpb_totsec16   = secmult * BYTES2INT16(buf,BPB_TOTSEC16);
336
    fat_bpb->bpb_totsec32   = secmult * BYTES2INT32(buf,BPB_TOTSEC32);
337
    fat_bpb->last_word      = BYTES2INT16(buf,BPB_LAST_WORD);
338
 
339
    /* calculate a few commonly used values */
340
    if (fat_bpb->bpb_fatsz16 != 0)
341
        fat_bpb->fatsize = fat_bpb->bpb_fatsz16;
342
    else
343
        fat_bpb->fatsize = fat_bpb->bpb_fatsz32;
344
 
345
    if (fat_bpb->bpb_totsec16 != 0)
346
        fat_bpb->totalsectors = fat_bpb->bpb_totsec16;
347
    else
348
        fat_bpb->totalsectors = fat_bpb->bpb_totsec32;
349
 
350
#ifdef HAVE_FAT16SUPPORT
351
    fat_bpb->bpb_rootentcnt = BYTES2INT16(buf,BPB_ROOTENTCNT);
352
    if (!fat_bpb->bpb_bytspersec)
353
    {
354
        fat_release_sector_buffer();
355
        return -2;
356
    }
357
    rootdirsectors = secmult * ((fat_bpb->bpb_rootentcnt * DIR_ENTRY_SIZE
358
                     + fat_bpb->bpb_bytspersec - 1) / fat_bpb->bpb_bytspersec);
359
#endif /* #ifdef HAVE_FAT16SUPPORT */
360
 
361
    fat_bpb->firstdatasector = fat_bpb->bpb_rsvdseccnt
362
#ifdef HAVE_FAT16SUPPORT
363
        + rootdirsectors
364
#endif
365
        + fat_bpb->bpb_numfats * fat_bpb->fatsize;
366
 
367
    /* Determine FAT type */
368
    datasec = fat_bpb->totalsectors - fat_bpb->firstdatasector;
369
    if (fat_bpb->bpb_secperclus)
370
        fat_bpb->dataclusters = datasec / fat_bpb->bpb_secperclus;
371
    else
372
    {
373
        fat_release_sector_buffer();
374
        return -2;
375
    }
376
 
377
#ifdef TEST_FAT
378
    /*
379
      we are sometimes testing with "illegally small" fat32 images,
380
      so we don't use the proper fat32 test case for test code
381
    */
382
    if ( fat_bpb->bpb_fatsz16 )
383
#else
384
    if ( fat_bpb->dataclusters < 65525 )
385
#endif
386
    { /* FAT16 */
387
#ifdef HAVE_FAT16SUPPORT
388
        fat_bpb->is_fat16 = true;
389
        if (fat_bpb->dataclusters < 4085)
390
        { /* FAT12 */
391
            fat_release_sector_buffer();
392
            DEBUGF("This is FAT12. Go away!");
393
            return -2;
394
        }
395
#else /* #ifdef HAVE_FAT16SUPPORT */
396
        fat_release_sector_buffer();
397
        DEBUGF("This is not FAT32. Go away!");
398
        return -2;
399
#endif /* #ifndef HAVE_FAT16SUPPORT */
400
    }
401
 
402
#ifdef HAVE_FAT16SUPPORT
403
    if (fat_bpb->is_fat16)
404
    { /* FAT16 specific part of BPB */
405
        int dirclusters;  
406
        fat_bpb->rootdirsector = fat_bpb->bpb_rsvdseccnt
407
            + fat_bpb->bpb_numfats * fat_bpb->bpb_fatsz16;
408
        dirclusters = ((rootdirsectors + fat_bpb->bpb_secperclus - 1)
409
            / fat_bpb->bpb_secperclus); /* rounded up, to full clusters */
410
        /* I assign negative pseudo cluster numbers for the root directory,
411
           their range is counted upward until -1. */
412
        fat_bpb->bpb_rootclus = 0 - dirclusters; /* backwards, before the data*/
413
        fat_bpb->rootdiroffset = dirclusters * fat_bpb->bpb_secperclus
414
            - rootdirsectors;
415
    }
416
    else
417
#endif /* #ifdef HAVE_FAT16SUPPORT */
418
    { /* FAT32 specific part of BPB */
419
        fat_bpb->bpb_rootclus  = BYTES2INT32(buf,BPB_ROOTCLUS);
420
        fat_bpb->bpb_fsinfo    = secmult * BYTES2INT16(buf,BPB_FSINFO);
421
        fat_bpb->rootdirsector = cluster2sec(IF_MV2(fat_bpb,)
422
                                             fat_bpb->bpb_rootclus);
423
    }
424
 
425
    rc = bpb_is_sane(IF_MV(fat_bpb));
426
    if (rc < 0)
427
    {
428
        fat_release_sector_buffer();
429
        DEBUGF( "fat_mount() - BPB is not sane");
430
        return rc * 10 - 3;
431
    }
432
 
433
#ifdef HAVE_FAT16SUPPORT
434
    if (fat_bpb->is_fat16)
435
    {
436
        fat_bpb->fsinfo.freecount = 0xffffffff; /* force recalc below */
437
        fat_bpb->fsinfo.nextfree = 0xffffffff;
438
    }
439
    else
440
#endif /* #ifdef HAVE_FAT16SUPPORT */
441
    {
442
        /* Read the fsinfo sector */
443
        rc = storage_read_sectors(IF_MD2(drive,)
444
            startsector + fat_bpb->bpb_fsinfo, 1, buf);
445
        if (rc < 0)
446
        {
447
            fat_release_sector_buffer();
448
            DEBUGF( "fat_mount() - Couldn't read FSInfo (error code %d)", rc);
449
            return rc * 10 - 4;
450
        }
451
        fat_bpb->fsinfo.freecount = BYTES2INT32(buf, FSINFO_FREECOUNT);
452
        fat_bpb->fsinfo.nextfree = BYTES2INT32(buf, FSINFO_NEXTFREE);
453
    }
454
    fat_release_sector_buffer();
455
 
456
    /* calculate freecount if unset */
457
    if ( fat_bpb->fsinfo.freecount == 0xffffffff )
458
    {
459
        fat_recalc_free(IF_MV(volume));
460
    }
461
 
462
    DEBUGF("Freecount: %ld",fat_bpb->fsinfo.freecount);
463
    DEBUGF("Nextfree: 0x%lx",fat_bpb->fsinfo.nextfree);
464
    DEBUGF("Cluster count: 0x%lx",fat_bpb->dataclusters);
465
    DEBUGF("Sectors per cluster: %d",fat_bpb->bpb_secperclus);
466
    DEBUGF("FAT sectors: 0x%lx",fat_bpb->fatsize);
467
 
468
#ifdef HAVE_MULTIVOLUME
469
    fat_bpb->mounted = true;
470
#endif
471
 
472
    return 0;
473
}
474
 
475
#ifdef HAVE_HOTSWAP
476
int fat_unmount(int volume, bool flush)
477
{
478
    int rc;
479
#ifdef HAVE_MULTIVOLUME
480
    struct bpb* fat_bpb = &fat_bpbs[volume];
481
#else
482
    (void)volume;
483
#endif
484
 
485
    if(flush)
486
    {
487
        rc = flush_fat(IF_MV(fat_bpb)); /* the clean way, while still alive */
488
    }
489
    else
490
    {   /* volume is not accessible any more, e.g. MMC removed */
491
        int i;
492
        mutex_lock(&cache_mutex, TIMEOUT_BLOCK);
493
        for(i = 0;i < FAT_CACHE_SIZE;i++)
494
        {
495
            struct fat_cache_entry *fce = &fat_cache[i];
496
            if((fce->valid || fce->locked)
497
#ifdef HAVE_MULTIVOLUME
498
               && fce->fat_vol == fat_bpb
499
#endif
500
              )
501
            {
502
                fce->valid = false; /* discard all from that volume */
503
                fce->locked = 0;
504
                fce->dirty = false;
505
            }
506
        }
507
        mutex_unlock(&cache_mutex);
508
        rc = 0;
509
    }
510
#ifdef HAVE_MULTIVOLUME
511
    fat_bpb->mounted = false;
512
#endif
513
    return rc;
514
}
515
#endif /* #ifdef HAVE_HOTSWAP */
516
 
517
void fat_recalc_free(IF_MV_NONVOID(int volume))
518
{
519
#ifndef HAVE_MULTIVOLUME
520
    const int volume = 0;
521
#endif
522
    struct bpb* fat_bpb = &fat_bpbs[volume];
523
    long free = 0;
524
    unsigned long i;
525
#ifdef HAVE_FAT16SUPPORT
526
    if (fat_bpb->is_fat16)
527
    {
528
        for (i = 0; i<fat_bpb->fatsize; i++) {
529
            unsigned int j;
530
            unsigned short* fat = cache_fat_sector(IF_MV2(fat_bpb,) i, false);
531
            for (j = 0; j < CLUSTERS_PER_FAT16_SECTOR; j++) {
532
                unsigned int c = i * CLUSTERS_PER_FAT16_SECTOR + j;
533
                if ( c > fat_bpb->dataclusters+1 ) /* nr 0 is unused */
534
                    break;
535
 
536
                if (letoh16(fat[j]) == 0x0000) {
537
                    free++;
538
                    if ( fat_bpb->fsinfo.nextfree == 0xffffffff )
539
                        fat_bpb->fsinfo.nextfree = c;
540
                }
541
            }
542
            unlock_fat_sector(IF_MV2(fat_bpb,) i);
543
        }
544
    }
545
    else
546
#endif /* #ifdef HAVE_FAT16SUPPORT */
547
    {
548
        for (i = 0; i<fat_bpb->fatsize; i++) {
549
            unsigned int j;
550
            unsigned long* fat = cache_fat_sector(IF_MV2(fat_bpb,) i, false);
551
            for (j = 0; j < CLUSTERS_PER_FAT_SECTOR; j++) {
552
                unsigned long c = i * CLUSTERS_PER_FAT_SECTOR + j;
553
                if ( c > fat_bpb->dataclusters+1 ) /* nr 0 is unused */
554
                    break;
555
 
556
                if (!(letoh32(fat[j]) & 0x0fffffff)) {
557
                    free++;
558
                    if ( fat_bpb->fsinfo.nextfree == 0xffffffff )
559
                        fat_bpb->fsinfo.nextfree = c;
560
                }
561
            }
562
            unlock_fat_sector(IF_MV2(fat_bpb,) i);
563
        }
564
    }
565
    fat_bpb->fsinfo.freecount = free;
566
    update_fsinfo(IF_MV(fat_bpb));
567
}
568
 
569
static int bpb_is_sane(IF_MV_NONVOID(struct bpb* fat_bpb))
570
{
571
#ifndef HAVE_MULTIVOLUME
572
    struct bpb* fat_bpb = &fat_bpbs[0];
573
#endif
574
    if(fat_bpb->bpb_bytspersec % SECTOR_SIZE)
575
    {
576
        DEBUGF( "bpb_is_sane() - Error: sector size is not sane (%d)",
577
                fat_bpb->bpb_bytspersec);
578
        return -1;
579
    }
580
    if((long)fat_bpb->bpb_secperclus * (long)fat_bpb->bpb_bytspersec
581
                                                                   > 128L*1024L)
582
    {
583
        DEBUGF( "bpb_is_sane() - Error: cluster size is larger than 128K "
584
                "(%d * %d = %d)",
585
                fat_bpb->bpb_bytspersec, fat_bpb->bpb_secperclus,
586
                fat_bpb->bpb_bytspersec * fat_bpb->bpb_secperclus);
587
        return -2;
588
    }
589
    if(fat_bpb->bpb_numfats != 2)
590
    {
591
        DEBUGF( "bpb_is_sane() - Warning: NumFATS is not 2 (%d)",
592
                fat_bpb->bpb_numfats);
593
    }
594
    if(fat_bpb->bpb_media != 0xf0 && fat_bpb->bpb_media < 0xf8)
595
    {
596
        DEBUGF( "bpb_is_sane() - Warning: Non-standard "
597
                "media type (0x%02x)",
598
                fat_bpb->bpb_media);
599
    }
600
    if(fat_bpb->last_word != 0xaa55)
601
    {
602
        DEBUGF( "bpb_is_sane() - Error: Last word is not "
603
                "0xaa55 (0x%04x)", fat_bpb->last_word);
604
        return -3;
605
    }
606
 
607
    if (fat_bpb->fsinfo.freecount >
608
        (fat_bpb->totalsectors - fat_bpb->firstdatasector)/
609
        fat_bpb->bpb_secperclus)
610
    {
611
        DEBUGF( "bpb_is_sane() - Error: FSInfo.Freecount > disk size "
612
                 "(0x%04lx)", fat_bpb->fsinfo.freecount);
613
        return -4;
614
    }
615
 
616
    return 0;
617
}
618
 
619
static void flush_fat_sector(struct fat_cache_entry *fce,
620
                             unsigned char *sectorbuf)
621
{
622
    int rc;
623
    long secnum;
624
 
625
    /* With multivolume, use only the FAT info from the cached sector! */
626
#ifdef HAVE_MULTIVOLUME
627
    secnum = fce->secnum + fce->fat_vol->startsector;
628
#else
629
    secnum = fce->secnum + fat_bpbs[0].startsector;
630
#endif
631
 
632
    /* Write to the first FAT */
633
    rc = storage_write_sectors(IF_MD2(fce->fat_vol->drive,)
634
                           secnum, 1,
635
                           sectorbuf);
636
    if(rc < 0)
637
    {
638
        panicf(PANIC_KILLUSERTHREADS, "flush_fat_sector() - Could not write sector %ld"
639
               " (error %d)",
640
               secnum, rc);
641
    }
642
#ifdef HAVE_MULTIVOLUME
643
    if(fce->fat_vol->bpb_numfats > 1)
644
#else
645
    if(fat_bpbs[0].bpb_numfats > 1)
646
#endif
647
    {
648
        /* Write to the second FAT */
649
#ifdef HAVE_MULTIVOLUME
650
        secnum += fce->fat_vol->fatsize;
651
#else
652
        secnum += fat_bpbs[0].fatsize;
653
#endif
654
        rc = storage_write_sectors(IF_MD2(fce->fat_vol->drive,)
655
                               secnum, 1, sectorbuf);
656
        if(rc < 0)
657
        {
658
            panicf(PANIC_KILLUSERTHREADS, "flush_fat_sector() - Could not write sector %ld"
659
                   " (error %d)",
660
                   secnum, rc);
661
        }
662
    }
663
    fce->dirty = false;
664
}
665
 
666
static void *cache_fat_sector(IF_MV2(struct bpb* fat_bpb,)
667
                              long fatsector, bool dirty)
668
{
669
#ifndef HAVE_MULTIVOLUME
670
    struct bpb* fat_bpb = &fat_bpbs[0];
671
#endif
672
    long secnum = fatsector + fat_bpb->bpb_rsvdseccnt;
673
    int cache_index = secnum & FAT_CACHE_MASK;
674
    struct fat_cache_entry *fce = &fat_cache[cache_index];
675
    unsigned char *sectorbuf = &fat_cache_sectors[cache_index][0];
676
    int rc;
677
 
678
    mutex_lock(&cache_mutex, TIMEOUT_BLOCK); /* make changes atomic */
679
 
680
    /* Delete the cache entry if it isn't the sector we want */
681
    if(fce->valid && (fce->secnum != secnum
682
#ifdef HAVE_MULTIVOLUME
683
        || fce->fat_vol != fat_bpb
684
#endif
685
    ))
686
    {
687
        while (fce->locked) sleep(1000);
688
        /* Write back if it is dirty */
689
        if(fce->dirty)
690
        {
691
            flush_fat_sector(fce, sectorbuf);
692
        }
693
        fce->valid = false;
694
    }
695
 
696
    /* Load the sector if it is not cached */
697
    if(!fce->valid)
698
    {
699
        rc = storage_read_sectors(IF_MD2(fat_bpb->drive,)
700
                              secnum + fat_bpb->startsector,1,
701
                              sectorbuf);
702
        if(rc < 0)
703
        {
704
            DEBUGF( "cache_fat_sector() - Could not read sector %ld"
705
                    " (error %d)", secnum, rc);
706
            mutex_unlock(&cache_mutex);
707
            return NULL;
708
        }
709
        fce->valid = true;
710
        fce->secnum = secnum;
711
#ifdef HAVE_MULTIVOLUME
712
        fce->fat_vol = fat_bpb;
713
#endif
714
    }
715
    fce->locked++;
716
    if (dirty)
717
        fce->dirty = true; /* dirt remains, sticky until flushed */
718
    mutex_unlock(&cache_mutex);
719
    return sectorbuf;
720
}
721
 
722
static void unlock_fat_sector(IF_MV2(struct bpb* fat_bpb,) long fatsector)
723
{
724
#ifndef HAVE_MULTIVOLUME
725
    struct bpb* fat_bpb = &fat_bpbs[0];
726
#endif
727
    long secnum = fatsector + fat_bpb->bpb_rsvdseccnt;
728
    int cache_index = secnum & FAT_CACHE_MASK;
729
    fat_cache[cache_index].locked--;
730
}
731
 
732
void* fat_get_sector_buffer()
733
{
734
    mutex_lock(&tempbuf_mutex, TIMEOUT_BLOCK);
735
    if (tempbuf_locked)
736
        panicf(PANIC_KILLUSERTHREADS, "FAT: Tried to lock temporary sector buffer twice!");
737
    tempbuf_locked = true;
738
    return fat_tempbuf;
739
}
740
 
741
void fat_release_sector_buffer()
742
{
743
    tempbuf_locked = false;
744
    mutex_unlock(&tempbuf_mutex);
745
}
746
 
747
static unsigned long find_free_cluster(IF_MV2(struct bpb* fat_bpb,)
748
                                       unsigned long startcluster)
749
{
750
#ifndef HAVE_MULTIVOLUME
751
    struct bpb* fat_bpb = &fat_bpbs[0];
752
#endif
753
    unsigned long sector;
754
    unsigned long offset;
755
    unsigned long i;
756
 
757
#ifdef HAVE_FAT16SUPPORT
758
    if (fat_bpb->is_fat16)
759
    {
760
        sector = startcluster / CLUSTERS_PER_FAT16_SECTOR;
761
        offset = startcluster % CLUSTERS_PER_FAT16_SECTOR;
762
 
763
        for (i = 0; i<fat_bpb->fatsize; i++) {
764
            unsigned int j;
765
            unsigned int nr = (i + sector) % fat_bpb->fatsize;
766
            unsigned short* fat = cache_fat_sector(IF_MV2(fat_bpb,) nr, false);
767
            if ( !fat )
768
                break;
769
            for (j = 0; j < CLUSTERS_PER_FAT16_SECTOR; j++) {
770
                int k = (j + offset) % CLUSTERS_PER_FAT16_SECTOR;
771
                if (letoh16(fat[k]) == 0x0000) {
772
                    unsigned int c = nr * CLUSTERS_PER_FAT16_SECTOR + k;
773
                     /* Ignore the reserved clusters 0 & 1, and also
774
                        cluster numbers out of bounds */
775
                    if ( c < 2 || c > fat_bpb->dataclusters+1 )
776
                        continue;
777
                    unlock_fat_sector(IF_MV2(fat_bpb,) nr);
778
                    DEBUGF("find_free_cluster(%x) == %x",startcluster,c);
779
                    fat_bpb->fsinfo.nextfree = c;
780
                    return c;
781
                }
782
            }
783
            unlock_fat_sector(IF_MV2(fat_bpb,) nr);
784
            offset = 0;
785
        }
786
    }
787
    else
788
#endif /* #ifdef HAVE_FAT16SUPPORT */
789
    {
790
        sector = startcluster / CLUSTERS_PER_FAT_SECTOR;
791
        offset = startcluster % CLUSTERS_PER_FAT_SECTOR;
792
 
793
        for (i = 0; i<fat_bpb->fatsize; i++) {
794
            unsigned int j;
795
            unsigned long nr = (i + sector) % fat_bpb->fatsize;
796
            unsigned long* fat = cache_fat_sector(IF_MV2(fat_bpb,) nr, false);
797
            if ( !fat )
798
                break;
799
            for (j = 0; j < CLUSTERS_PER_FAT_SECTOR; j++) {
800
                int k = (j + offset) % CLUSTERS_PER_FAT_SECTOR;
801
                if (!(letoh32(fat[k]) & 0x0fffffff)) {
802
                    unsigned long c = nr * CLUSTERS_PER_FAT_SECTOR + k;
803
                     /* Ignore the reserved clusters 0 & 1, and also
804
                        cluster numbers out of bounds */
805
                    if ( c < 2 || c > fat_bpb->dataclusters+1 )
806
                        continue;
807
                    unlock_fat_sector(IF_MV2(fat_bpb,) nr);
808
                    DEBUGF("find_free_cluster(%lx) == %lx",startcluster,c);
809
                    fat_bpb->fsinfo.nextfree = c;
810
                    return c;
811
                }
812
            }
813
            unlock_fat_sector(IF_MV2(fat_bpb,) nr);
814
            offset = 0;
815
        }
816
    }
817
 
818
    DEBUGF("find_free_cluster(%lx) == 0",startcluster);
819
    return 0; /* 0 is an illegal cluster number */
820
}
821
 
822
static int update_fat_entry(IF_MV2(struct bpb* fat_bpb,) unsigned long entry,
823
                            unsigned long val)
824
{
825
#ifndef HAVE_MULTIVOLUME
826
    struct bpb* fat_bpb = &fat_bpbs[0];
827
#endif
828
#ifdef HAVE_FAT16SUPPORT
829
    if (fat_bpb->is_fat16)
830
    {
831
        int sector = entry / CLUSTERS_PER_FAT16_SECTOR;
832
        int offset = entry % CLUSTERS_PER_FAT16_SECTOR;
833
        unsigned short* sec;
834
 
835
        val &= 0xFFFF;
836
 
837
        DEBUGF("update_fat_entry(%x,%x)",entry,val);
838
 
839
        if (entry==val)
840
            panicf(PANIC_KILLUSERTHREADS, "Creating FAT loop: %lx,%lx",entry,val);
841
 
842
        if ( entry < 2 )
843
            panicf(PANIC_KILLUSERTHREADS, "Updating reserved FAT entry %ld.",entry);
844
 
845
        sec = cache_fat_sector(IF_MV2(fat_bpb,) sector, true);
846
        if (!sec)
847
        {
848
            DEBUGF( "update_fat_entry() - Could not cache sector %d", sector);
849
            return -1;
850
        }
851
 
852
        if ( val ) {
853
            if (letoh16(sec[offset]) == 0x0000 && fat_bpb->fsinfo.freecount > 0)
854
                fat_bpb->fsinfo.freecount--;
855
        }
856
        else {
857
            if (letoh16(sec[offset]))
858
                fat_bpb->fsinfo.freecount++;
859
        }
860
 
861
        DEBUGF("update_fat_entry: %d free clusters",
862
                fat_bpb->fsinfo.freecount);
863
 
864
        sec[offset] = htole16(val);
865
        unlock_fat_sector(IF_MV2(fat_bpb,) sector);
866
    }
867
    else
868
#endif /* #ifdef HAVE_FAT16SUPPORT */
869
    {
870
        long sector = entry / CLUSTERS_PER_FAT_SECTOR;
871
        int offset = entry % CLUSTERS_PER_FAT_SECTOR;
872
        unsigned long* sec;
873
 
874
        DEBUGF("update_fat_entry(%lx,%lx)",entry,val);
875
 
876
        if (entry==val)
877
            panicf(PANIC_KILLUSERTHREADS, "Creating FAT loop: %lx,%lx",entry,val);
878
 
879
        if ( entry < 2 )
880
            panicf(PANIC_KILLUSERTHREADS, "Updating reserved FAT entry %ld.",entry);
881
 
882
        sec = cache_fat_sector(IF_MV2(fat_bpb,) sector, true);
883
        if (!sec)
884
        {
885
            DEBUGF("update_fat_entry() - Could not cache sector %ld", sector);
886
            return -1;
887
        }
888
 
889
        if ( val ) {
890
            if (!(letoh32(sec[offset]) & 0x0fffffff) &&
891
                fat_bpb->fsinfo.freecount > 0)
892
                fat_bpb->fsinfo.freecount--;
893
        }
894
        else {
895
            if (letoh32(sec[offset]) & 0x0fffffff)
896
                fat_bpb->fsinfo.freecount++;
897
        }
898
 
899
        DEBUGF("update_fat_entry: %ld free clusters",
900
                fat_bpb->fsinfo.freecount);
901
 
902
        /* don't change top 4 bits */
903
        sec[offset] &= htole32(0xf0000000);
904
        sec[offset] |= htole32(val & 0x0fffffff);
905
        unlock_fat_sector(IF_MV2(fat_bpb,) sector);
906
    }
907
 
908
    return 0;
909
}
910
 
911
static long read_fat_entry(IF_MV2(struct bpb* fat_bpb,) unsigned long entry)
912
{
913
#ifdef HAVE_FAT16SUPPORT
914
#ifndef HAVE_MULTIVOLUME
915
    struct bpb* fat_bpb = &fat_bpbs[0];
916
#endif
917
    if (fat_bpb->is_fat16)
918
    {
919
        int sector = entry / CLUSTERS_PER_FAT16_SECTOR;
920
        int offset = entry % CLUSTERS_PER_FAT16_SECTOR;
921
        unsigned short* sec;
922
 
923
        sec = cache_fat_sector(IF_MV2(fat_bpb,) sector, false);
924
        if (!sec)
925
        {
926
            DEBUGF( "read_fat_entry() - Could not cache sector %d", sector);
927
            return -1;
928
        }
929
 
930
        long val = letoh16(sec[offset]);
931
        unlock_fat_sector(IF_MV2(fat_bpb,) sector);
932
 
933
        return val;
934
    }
935
    else
936
#endif /* #ifdef HAVE_FAT16SUPPORT */
937
    {
938
        long sector = entry / CLUSTERS_PER_FAT_SECTOR;
939
        int offset = entry % CLUSTERS_PER_FAT_SECTOR;
940
        unsigned long* sec;
941
 
942
        sec = cache_fat_sector(IF_MV2(fat_bpb,) sector, false);
943
        if (!sec)
944
        {
945
            DEBUGF( "read_fat_entry() - Could not cache sector %ld", sector);
946
            return -1;
947
        }
948
 
949
        long val = letoh32(sec[offset]) & 0x0fffffff;
950
        unlock_fat_sector(IF_MV2(fat_bpb,) sector);
951
 
952
        return val;
953
    }
954
}
955
 
956
static long get_next_cluster(IF_MV2(struct bpb* fat_bpb,) long cluster)
957
{
958
    long next_cluster;
959
    long eof_mark = FAT_EOF_MARK;
960
 
961
#ifdef HAVE_FAT16SUPPORT
962
#ifndef HAVE_MULTIVOLUME
963
    struct bpb* fat_bpb = &fat_bpbs[0];
964
#endif
965
    if (fat_bpb->is_fat16)
966
    {
967
        eof_mark &= 0xFFFF; /* only 16 bit */
968
        if (cluster < 0) /* FAT16 root dir */
969
            return cluster + 1; /* don't use the FAT */
970
    }
971
#endif
972
    next_cluster = read_fat_entry(IF_MV2(fat_bpb,) cluster);
973
 
974
    /* is this last cluster in chain? */
975
    if ( next_cluster >= eof_mark )
976
        return 0;
977
    else
978
        return next_cluster;
979
}
980
 
981
static int update_fsinfo(IF_MV_NONVOID(struct bpb* fat_bpb))
982
{
983
#ifndef HAVE_MULTIVOLUME
984
    struct bpb* fat_bpb = &fat_bpbs[0];
985
#endif
986
    unsigned long* intptr;
987
    int rc;
988
 
989
#ifdef HAVE_FAT16SUPPORT
990
    if (fat_bpb->is_fat16)
991
        return 0; /* FAT16 has no FsInfo */
992
#endif /* #ifdef HAVE_FAT16SUPPORT */
993
 
994
    /* update fsinfo */
995
    unsigned char* fsinfo = fat_get_sector_buffer();
996
    rc = storage_read_sectors(IF_MD2(fat_bpb->drive,)
997
                          fat_bpb->startsector + fat_bpb->bpb_fsinfo, 1,fsinfo);
998
    if (rc < 0)
999
    {
1000
        fat_release_sector_buffer();
1001
        DEBUGF( "update_fsinfo() - Couldn't read FSInfo (error code %d)", rc);
1002
        return rc * 10 - 1;
1003
    }
1004
    intptr = (long*)&(fsinfo[FSINFO_FREECOUNT]);
1005
    *intptr = htole32(fat_bpb->fsinfo.freecount);
1006
 
1007
    intptr = (long*)&(fsinfo[FSINFO_NEXTFREE]);
1008
    *intptr = htole32(fat_bpb->fsinfo.nextfree);
1009
 
1010
    rc = storage_write_sectors(IF_MD2(fat_bpb->drive,)
1011
                           fat_bpb->startsector + fat_bpb->bpb_fsinfo,1,fsinfo);
1012
    fat_release_sector_buffer();
1013
    if (rc < 0)
1014
    {
1015
        DEBUGF( "update_fsinfo() - Couldn't write FSInfo (error code %d)", rc);
1016
        return rc * 10 - 2;
1017
    }
1018
 
1019
    return 0;
1020
}
1021
 
1022
static int flush_fat(IF_MV_NONVOID(struct bpb* fat_bpb))
1023
{
1024
    int i;
1025
    int rc;
1026
    unsigned char *sec;
1027
    DEBUGF("flush_fat()");
1028
 
1029
    mutex_lock(&cache_mutex, TIMEOUT_BLOCK);
1030
    for(i = 0;i < FAT_CACHE_SIZE;i++)
1031
    {
1032
        struct fat_cache_entry *fce = &fat_cache[i];
1033
        if(fce->valid 
1034
#ifdef HAVE_MULTIVOLUME
1035
            && fce->fat_vol == fat_bpb
1036
#endif
1037
            && fce->dirty)
1038
        {
1039
            sec = fat_cache_sectors[i];
1040
            flush_fat_sector(fce, sec);
1041
        }
1042
    }
1043
    mutex_unlock(&cache_mutex);
1044
 
1045
    rc = update_fsinfo(IF_MV(fat_bpb));
1046
    if (rc < 0)
1047
        return rc * 10 - 3;
1048
 
1049
    return 0;
1050
}
1051
 
1052
static void fat_time(unsigned short* date,
1053
                     unsigned short* time,
1054
                     unsigned short* tenth )
1055
{
1056
#if CONFIG_RTC
1057
    struct tm* tm = get_time();
1058
 
1059
    if (date)
1060
        *date = ((tm->tm_year - 80) << 9) |
1061
            ((tm->tm_mon + 1) << 5) |
1062
            tm->tm_mday;
1063
 
1064
    if (time)
1065
        *time = (tm->tm_hour << 11) |
1066
            (tm->tm_min << 5) |
1067
            (tm->tm_sec >> 1);
1068
 
1069
    if (tenth)
1070
        *tenth = (tm->tm_sec & 1) * 100;
1071
#else
1072
 
1073
    if (date) *date = 0;
1074
    if (time) *time = 0;
1075
    if (tenth) *tenth = 0;
1076
 
1077
#endif /* CONFIG_RTC */
1078
}
1079
 
1080
static int write_long_name(struct fat_file* file,
1081
                           unsigned int firstentry,
1082
                           unsigned int numentries,
1083
                           const unsigned char* name,
1084
                           const unsigned char* shortname,
1085
                           bool is_directory)
1086
{
1087
    unsigned char* entry;
1088
    unsigned int idx = firstentry % DIR_ENTRIES_PER_SECTOR;
1089
    unsigned int sector = firstentry / DIR_ENTRIES_PER_SECTOR;
1090
    unsigned char chksum = 0;
1091
    unsigned int i, j=0;
1092
    unsigned int nameidx=0, namelen = strlen(name);
1093
    int rc;
1094
    unsigned short name_utf16[namelen + 1];
1095
 
1096
    DEBUGF("write_long_name(file:%lx, first:%d, num:%d, name:%s)",
1097
            file->firstcluster, firstentry, numentries, name);
1098
 
1099
    rc = fat_seek(file, sector);
1100
    if (rc<0)
1101
        return rc * 10 - 1;
1102
 
1103
    unsigned char* buf = fat_get_sector_buffer();
1104
    rc = fat_readwrite(file, 1, buf, false);
1105
    if (rc<1)
1106
    {
1107
        fat_release_sector_buffer();
1108
        return rc * 10 - 2;
1109
    }
1110
 
1111
    /* calculate shortname checksum */
1112
    for (i=11; i>0; i--)
1113
        chksum = ((chksum & 1) ? 0x80 : 0) + (chksum >> 1) + shortname[j++];
1114
 
1115
    /* calc position of last name segment */
1116
    if ( namelen > NAME_BYTES_PER_ENTRY )
1117
        for (nameidx=0;
1118
             nameidx < (namelen - NAME_BYTES_PER_ENTRY);
1119
             nameidx += NAME_BYTES_PER_ENTRY);
1120
 
1121
    /* we need to convert the name first    */
1122
    /* since it is written in reverse order */
1123
    for (i = 0; i <= namelen; i++)
1124
        name_utf16[i] = *(name++);
1125
 
1126
    for (i=0; i < numentries; i++) {
1127
        /* new sector? */
1128
        if ( idx >= DIR_ENTRIES_PER_SECTOR ) {
1129
            /* update current sector */
1130
            rc = fat_seek(file, sector);
1131
            if (rc<0)
1132
            {
1133
                fat_release_sector_buffer();
1134
                return rc * 10 - 3;
1135
            }
1136
 
1137
            rc = fat_readwrite(file, 1, buf, true);
1138
            if (rc<1)
1139
            {
1140
                fat_release_sector_buffer();
1141
                return rc * 10 - 4;
1142
            }
1143
 
1144
            /* read next sector */
1145
            rc = fat_readwrite(file, 1, buf, false);
1146
            if (rc<0) {
1147
                fat_release_sector_buffer();
1148
                DEBUGF("Failed writing new sector: %d",rc);
1149
                return rc * 10 - 5;
1150
            }
1151
            if (rc==0)
1152
                /* end of dir */
1153
                memset(buf, 0, SECTOR_SIZE);
1154
 
1155
            sector++;
1156
            idx = 0;
1157
        }
1158
 
1159
        entry = buf + idx * DIR_ENTRY_SIZE;
1160
 
1161
        /* verify this entry is free */
1162
        if (entry[0] && entry[0] != 0xe5 )
1163
        {
1164
            fat_release_sector_buffer();
1165
            panicf(PANIC_KILLUSERTHREADS, "Dir entry %d in sector %x is not free! "
1166
                   "%02x %02x %02x %02x",
1167
                   idx, sector,
1168
                   entry[0], entry[1], entry[2], entry[3]);
1169
        }
1170
 
1171
        memset(entry, 0, DIR_ENTRY_SIZE);
1172
        if ( i+1 < numentries ) {
1173
            /* longname entry */
1174
            unsigned int k, l = nameidx;
1175
 
1176
            entry[FATLONG_ORDER] = numentries-i-1;
1177
            if (i==0) {
1178
                /* mark this as last long entry */
1179
                entry[FATLONG_ORDER] |= FATLONG_LAST_LONG_ENTRY;
1180
 
1181
                /* pad name with 0xffff  */
1182
                for (k=1; k<11; k++) entry[k] = FAT_LONGNAME_PAD_BYTE;
1183
                for (k=14; k<26; k++) entry[k] = FAT_LONGNAME_PAD_BYTE;
1184
                for (k=28; k<32; k++) entry[k] = FAT_LONGNAME_PAD_BYTE;
1185
            };
1186
            /* set name */
1187
            for (k=0; k<5 && l <= namelen; k++) {
1188
                entry[k*2 + 1] = (unsigned char)(name_utf16[l] & 0xff);
1189
                entry[k*2 + 2] = (unsigned char)(name_utf16[l++] >> 8);
1190
            }
1191
            for (k=0; k<6 && l <= namelen; k++) {
1192
                entry[k*2 + 14] = (unsigned char)(name_utf16[l] & 0xff);
1193
                entry[k*2 + 15] = (unsigned char)(name_utf16[l++] >> 8);
1194
            }
1195
            for (k=0; k<2 && l <= namelen; k++) {
1196
                entry[k*2 + 28] = (unsigned char)(name_utf16[l] & 0xff);
1197
                entry[k*2 + 29] = (unsigned char)(name_utf16[l++] >> 8);
1198
            }
1199
 
1200
            entry[FATDIR_ATTR] = FAT_ATTR_LONG_NAME;
1201
            entry[FATDIR_FSTCLUSLO] = 0;
1202
            entry[FATLONG_TYPE] = 0;
1203
            entry[FATLONG_CHKSUM] = chksum;
1204
            DEBUGF("Longname entry %d (%d): %s", idx, nameidx, name+nameidx);
1205
        }
1206
        else {
1207
            /* shortname entry */
1208
            unsigned short date=0, time=0, tenth=0;
1209
            DEBUGF("Shortname entry: %s", shortname);
1210
            memcpy(entry + FATDIR_NAME, shortname, 11);
1211
            entry[FATDIR_ATTR] = is_directory?FAT_ATTR_DIRECTORY:0;
1212
            entry[FATDIR_NTRES] = 0;
1213
 
1214
            fat_time(&date, &time, &tenth);
1215
            entry[FATDIR_CRTTIMETENTH] = tenth;
1216
            *(unsigned short*)(entry + FATDIR_CRTTIME) = htole16(time);
1217
            *(unsigned short*)(entry + FATDIR_WRTTIME) = htole16(time);
1218
            *(unsigned short*)(entry + FATDIR_CRTDATE) = htole16(date);
1219
            *(unsigned short*)(entry + FATDIR_WRTDATE) = htole16(date);
1220
            *(unsigned short*)(entry + FATDIR_LSTACCDATE) = htole16(date);
1221
        }
1222
        idx++;
1223
        nameidx -= NAME_BYTES_PER_ENTRY;
1224
    }
1225
 
1226
    /* update last sector */
1227
    rc = fat_seek(file, sector);
1228
    if (rc<0)
1229
    {
1230
        fat_release_sector_buffer();
1231
        return rc * 10 - 6;
1232
    }
1233
 
1234
    rc = fat_readwrite(file, 1, buf, true);
1235
    fat_release_sector_buffer();
1236
    if (rc<1)
1237
        return rc * 10 - 7;
1238
 
1239
    DEBUGF("write_long_name: success");
1240
    return 0;
1241
}
1242
 
1243
static int fat_checkname(const unsigned char* newname)
1244
{
1245
    static const char invalid_chars[] = "\"*/:<>?\\|";
1246
    int len = strlen(newname);
1247
    /* More sanity checks are probably needed */
1248
    if (len > 255 || newname[len - 1] == '.')
1249
    {
1250
        return -1;
1251
    }
1252
    while (*newname)
1253
    {
1254
        if (*newname < ' ' || strchr(invalid_chars, *newname) != NULL)
1255
            return -1;
1256
        newname++;
1257
    }
1258
    /* check trailing space(s) */
1259
    if(*(--newname) == ' ')
1260
        return -1;
1261
 
1262
    return 0;
1263
}
1264
 
1265
static int add_dir_entry(struct fat_dir* dir,
1266
                         struct fat_file* file,
1267
                         const char* name,
1268
                         bool is_directory,
1269
                         bool dotdir)
1270
{
1271
#ifdef HAVE_MULTIVOLUME
1272
    struct bpb* fat_bpb = &fat_bpbs[dir->file.volume];
1273
#else
1274
    struct bpb* fat_bpb = &fat_bpbs[0];
1275
#endif
1276
    unsigned char shortname[12];
1277
    int rc;
1278
    unsigned int sector;
1279
    bool done = false;
1280
    int entries_needed, entries_found = 0;
1281
    int firstentry;
1282
 
1283
    DEBUGF( "add_dir_entry(%s,%lx)",
1284
             name, file->firstcluster);
1285
 
1286
    /* Don't check dotdirs name for validity */
1287
    if (dotdir == false) {
1288
        rc = fat_checkname(name);
1289
        if (rc < 0) {
1290
            /* filename is invalid */
1291
            return rc * 10 - 1;
1292
        }
1293
    }
1294
 
1295
#ifdef HAVE_MULTIVOLUME
1296
    file->volume = dir->file.volume; /* inherit the volume, to make sure */
1297
#endif
1298
 
1299
    /* The "." and ".." directory entries must not be long names */
1300
    if(dotdir) {
1301
        int i;
1302
        strlcpy(shortname, name, 12);
1303
        for(i = strlen(shortname); i < 12; i++)
1304
            shortname[i] = ' ';
1305
 
1306
        entries_needed = 1;
1307
    } else {
1308
        create_dos_name(name, shortname);
1309
 
1310
        /* one dir entry needed for every 13 bytes of filename,
1311
           plus one entry for the short name */
1312
        entries_needed = (strlen(name) + (NAME_BYTES_PER_ENTRY-1))
1313
                         / NAME_BYTES_PER_ENTRY + 1;
1314
    }
1315
 
1316
    unsigned char* buf = fat_get_sector_buffer();
1317
  restart:
1318
    firstentry = -1;
1319
 
1320
    rc = fat_seek(&dir->file, 0);
1321
    if (rc < 0)
1322
    {
1323
        fat_release_sector_buffer();
1324
        return rc * 10 - 2;
1325
    }
1326
 
1327
    /* step 1: search for free entries and check for duplicate shortname */
1328
    for (sector = 0; !done; sector++)
1329
    {
1330
        unsigned int i;
1331
 
1332
        rc = fat_readwrite(&dir->file, 1, buf, false);
1333
        if (rc < 0) {
1334
            fat_release_sector_buffer();
1335
            DEBUGF( "add_dir_entry() - Couldn't read dir"
1336
                    " (error code %d)", rc);
1337
            return rc * 10 - 3;
1338
        }
1339
 
1340
        if (rc == 0) { /* current end of dir reached */
1341
            DEBUGF("End of dir on cluster boundary");
1342
            break;
1343
        }
1344
 
1345
        /* look for free slots */
1346
        for (i = 0; i < DIR_ENTRIES_PER_SECTOR; i++)
1347
        {
1348
            switch (buf[i * DIR_ENTRY_SIZE]) {
1349
              case 0:
1350
                entries_found += DIR_ENTRIES_PER_SECTOR - i;
1351
                DEBUGF("Found end of dir %d",
1352
                        sector * DIR_ENTRIES_PER_SECTOR + i);
1353
                i = DIR_ENTRIES_PER_SECTOR - 1;
1354
                done = true;
1355
                break;
1356
 
1357
              case 0xe5:
1358
                entries_found++;
1359
                DEBUGF("Found free entry %d (%d/%d)",
1360
                        sector * DIR_ENTRIES_PER_SECTOR + i,
1361
                        entries_found, entries_needed);
1362
                break;
1363
 
1364
              default:
1365
                entries_found = 0;
1366
 
1367
                /* check that our intended shortname doesn't already exist */
1368
                if (!strncmp(shortname, buf + i * DIR_ENTRY_SIZE, 11)) {
1369
                    /* shortname exists already, make a new one */
1370
                    randomize_dos_name(shortname);
1371
                    DEBUGF("Duplicate shortname, changing to %s",
1372
                            shortname);
1373
 
1374
                    /* name has changed, we need to restart search */
1375
                    goto restart;
1376
                }
1377
                break;
1378
            }
1379
            if (firstentry < 0 && (entries_found >= entries_needed))
1380
                firstentry = sector * DIR_ENTRIES_PER_SECTOR + i + 1
1381
                             - entries_found;
1382
        }
1383
    }
1384
 
1385
    /* step 2: extend the dir if necessary */
1386
    if (firstentry < 0)
1387
    {
1388
        DEBUGF("Adding new sector(s) to dir");
1389
        rc = fat_seek(&dir->file, sector);
1390
        if (rc < 0)
1391
        {
1392
            fat_release_sector_buffer();
1393
            return rc * 10 - 4;
1394
        }
1395
        memset(buf, 0, SECTOR_SIZE);
1396
 
1397
        /* we must clear whole clusters */
1398
        for (; (entries_found < entries_needed) ||
1399
               (dir->file.sectornum < (int)fat_bpb->bpb_secperclus); sector++)
1400
        {
1401
            if (sector >= (65536/DIR_ENTRIES_PER_SECTOR))
1402
            {
1403
                fat_release_sector_buffer();
1404
                return -5; /* dir too large -- FAT specification */
1405
            }
1406
 
1407
            rc = fat_readwrite(&dir->file, 1, buf, true);
1408
            if (rc < 1)  /* No more room or something went wrong */
1409
            {
1410
                fat_release_sector_buffer();
1411
                return rc * 10 - 6;
1412
            }
1413
 
1414
            entries_found += DIR_ENTRIES_PER_SECTOR;
1415
        }
1416
 
1417
        firstentry = sector * DIR_ENTRIES_PER_SECTOR - entries_found;
1418
    }
1419
    fat_release_sector_buffer();
1420
 
1421
    /* step 3: add entry */
1422
    sector = firstentry / DIR_ENTRIES_PER_SECTOR;
1423
    DEBUGF("Adding longname to entry %d in sector %d",
1424
            firstentry, sector);
1425
 
1426
    rc = write_long_name(&dir->file, firstentry,
1427
                         entries_needed, name, shortname, is_directory);
1428
    if (rc < 0)
1429
        return rc * 10 - 7;
1430
 
1431
    /* remember where the shortname dir entry is located */
1432
    file->direntry = firstentry + entries_needed - 1;
1433
    file->direntries = entries_needed;
1434
    file->dircluster = dir->file.firstcluster;
1435
    DEBUGF("Added new dir entry %d, using %d slots.",
1436
            file->direntry, file->direntries);
1437
 
1438
    return 0;
1439
}
1440
 
1441
static unsigned char char2dos(unsigned char c, int* randomize)
1442
{
1443
    static const char invalid_chars[] = "\"*+,./:;<=>?[\\]|";
1444
 
1445
    if (c <= 0x20)
1446
        c = 0;   /* Illegal char, remove */
1447
    else if (strchr(invalid_chars, c) != NULL)
1448
    {
1449
        /* Illegal char, replace */
1450
        c = '_';
1451
        *randomize = 1; /* as per FAT spec */
1452
    }
1453
    else
1454
        c = toupper(c);
1455
 
1456
    return c;
1457
}
1458
 
1459
static void create_dos_name(const unsigned char *name, unsigned char *newname)
1460
{
1461
    int i;
1462
    unsigned char *ext;
1463
    int randomize = 0;
1464
 
1465
    /* Find extension part */
1466
    ext = strrchr(name, '.');
1467
    if (ext == name)         /* handle .dotnames */
1468
        ext = NULL;
1469
 
1470
    /* needs to randomize? */
1471
    if((ext && (strlen(ext) > 4)) ||
1472
       ((ext ? (unsigned int)(ext-name) : strlen(name)) > 8) )
1473
        randomize = 1;
1474
 
1475
    /* Name part */
1476
    for (i = 0; *name && (!ext || name < ext) && (i < 8); name++)
1477
    {
1478
        unsigned char c = char2dos(*name, &randomize);
1479
        if (c)
1480
            newname[i++] = c;
1481
    }
1482
 
1483
    /* Pad both name and extension */
1484
    while (i < 11)
1485
        newname[i++] = ' ';
1486
 
1487
    if (newname[0] == 0xe5) /* Special kanji character */
1488
        newname[0] = 0x05;
1489
 
1490
    if (ext)
1491
    {   /* Extension part */
1492
        ext++;
1493
        for (i = 8; *ext && (i < 11); ext++)
1494
        {
1495
            unsigned char c = char2dos(*ext, &randomize);
1496
            if (c)
1497
                newname[i++] = c;
1498
        }
1499
    }
1500
 
1501
    if(randomize)
1502
        randomize_dos_name(newname);
1503
}
1504
 
1505
static void randomize_dos_name(unsigned char *name)
1506
{
1507
    unsigned char* tilde = NULL;    /* ~ location */
1508
    unsigned char* lastpt = NULL;   /* last point of filename */
1509
    unsigned char* nameptr = name;  /* working copy of name pointer */
1510
    unsigned char num[9];           /* holds number as string */
1511
    int i = 0;
1512
    int cnt = 1;
1513
    int numlen;
1514
    int offset;
1515
 
1516
    while(i++ < 8)
1517
    {
1518
        /* hunt for ~ and where to put it */
1519
        if((!tilde) && (*nameptr == '~'))
1520
            tilde = nameptr;
1521
        if((!lastpt) && ((*nameptr == ' ' || *nameptr == '~')))
1522
            lastpt = nameptr;
1523
        nameptr++;
1524
    }
1525
    if(tilde)
1526
    {
1527
        /* extract current count and increment */
1528
        memcpy(num,tilde+1,7-(unsigned int)(tilde-name));
1529
        num[7-(unsigned int)(tilde-name)] = 0;
1530
        cnt = atoi(num) + 1;
1531
    }
1532
    cnt %= 10000000; /* protection */
1533
    snprintf(num, 9, "~%d", cnt);   /* allow room for trailing zero */
1534
    numlen = strlen(num);           /* required space */
1535
    offset = (unsigned int)(lastpt ? lastpt - name : 8); /* prev startpoint */
1536
    if(offset > (8-numlen)) offset = 8-numlen;  /* correct for new numlen */
1537
 
1538
    memcpy(&name[offset], num, numlen);
1539
 
1540
    /* in special case of counter overflow: pad with spaces */
1541
    for(offset = offset+numlen; offset < 8; offset++)
1542
        name[offset] = ' ';
1543
}
1544
 
1545
static int update_short_entry( struct fat_file* file, long size, int attr )
1546
{
1547
    int sector = file->direntry / DIR_ENTRIES_PER_SECTOR;
1548
    unsigned long* sizeptr;
1549
    unsigned short* clusptr;
1550
    struct fat_file dir;
1551
    int rc;
1552
 
1553
    DEBUGF("update_file_size(cluster:%lx entry:%d size:%ld)",
1554
            file->firstcluster, file->direntry, size);
1555
 
1556
    /* create a temporary file handle for the dir holding this file */
1557
    rc = fat_open(IF_MV2(file->volume,) file->dircluster, &dir, NULL);
1558
    if (rc < 0)
1559
        return rc * 10 - 1;
1560
 
1561
    rc = fat_seek( &dir, sector );
1562
    if (rc<0)
1563
        return rc * 10 - 2;
1564
 
1565
    unsigned char* buf = fat_get_sector_buffer();
1566
    unsigned char* entry =
1567
        buf + DIR_ENTRY_SIZE * (file->direntry % DIR_ENTRIES_PER_SECTOR);
1568
    rc = fat_readwrite(&dir, 1, buf, false);
1569
    if (rc < 1)
1570
    {
1571
        fat_release_sector_buffer();
1572
        return rc * 10 - 3;
1573
    }
1574
 
1575
    if (!entry[0] || entry[0] == 0xe5)
1576
    {
1577
        fat_release_sector_buffer();
1578
        panicf(PANIC_KILLUSERTHREADS, "Updating size on empty dir entry %d", file->direntry);
1579
    }
1580
 
1581
    entry[FATDIR_ATTR] = attr & 0xFF;
1582
 
1583
    clusptr = (short*)(entry + FATDIR_FSTCLUSHI);
1584
    *clusptr = htole16(file->firstcluster >> 16);
1585
 
1586
    clusptr = (short*)(entry + FATDIR_FSTCLUSLO);
1587
    *clusptr = htole16(file->firstcluster & 0xffff);
1588
 
1589
    sizeptr = (long*)(entry + FATDIR_FILESIZE);
1590
    *sizeptr = htole32(size);
1591
 
1592
    {
1593
#if CONFIG_RTC
1594
        unsigned short time = 0;
1595
        unsigned short date = 0;
1596
#else
1597
        /* get old time to increment from */
1598
        unsigned short time = htole16(*(unsigned short*)(entry+FATDIR_WRTTIME));
1599
        unsigned short date = htole16(*(unsigned short*)(entry+FATDIR_WRTDATE));
1600
#endif
1601
        fat_time(&date, &time, NULL);
1602
        *(unsigned short*)(entry + FATDIR_WRTTIME) = htole16(time);
1603
        *(unsigned short*)(entry + FATDIR_WRTDATE) = htole16(date);
1604
        *(unsigned short*)(entry + FATDIR_LSTACCDATE) = htole16(date);
1605
    }
1606
 
1607
    rc = fat_seek( &dir, sector );
1608
    if (rc < 0)
1609
    {
1610
        fat_release_sector_buffer();
1611
        return rc * 10 - 4;
1612
    }
1613
 
1614
    rc = fat_readwrite(&dir, 1, buf, true);
1615
    fat_release_sector_buffer();
1616
    if (rc < 1)
1617
        return rc * 10 - 5;
1618
 
1619
    return 0;
1620
}
1621
 
1622
static int parse_direntry(struct fat_direntry *de, const unsigned char *buf)
1623
{
1624
    int i=0,j=0;
1625
    unsigned char c;
1626
    bool lowercase;
1627
 
1628
    memset(de, 0, sizeof(struct fat_direntry));
1629
    de->attr = buf[FATDIR_ATTR];
1630
    de->crttimetenth = buf[FATDIR_CRTTIMETENTH];
1631
    de->crtdate = BYTES2INT16(buf,FATDIR_CRTDATE);
1632
    de->crttime = BYTES2INT16(buf,FATDIR_CRTTIME);
1633
    de->wrtdate = BYTES2INT16(buf,FATDIR_WRTDATE);
1634
    de->wrttime = BYTES2INT16(buf,FATDIR_WRTTIME);
1635
    de->filesize = BYTES2INT32(buf,FATDIR_FILESIZE);
1636
    de->firstcluster = ((long)(unsigned)BYTES2INT16(buf,FATDIR_FSTCLUSLO)) |
1637
        ((long)(unsigned)BYTES2INT16(buf,FATDIR_FSTCLUSHI) << 16);
1638
    /* The double cast is to prevent a sign-extension to be done on CalmRISC16.
1639
       (the result of the shift is always considered signed) */
1640
 
1641
    /* fix the name */
1642
    lowercase = (buf[FATDIR_NTRES] & FAT_NTRES_LC_NAME);
1643
    c = buf[FATDIR_NAME];
1644
    if (c == 0x05)  /* special kanji char */
1645
        c = 0xe5;
1646
    i = 0;
1647
    while (c != ' ') {
1648
        de->name[j++] = lowercase ? tolower(c) : c;
1649
        if (++i >= 8)
1650
            break;
1651
        c = buf[FATDIR_NAME+i];
1652
    }
1653
    if (buf[FATDIR_NAME+8] != ' ') {
1654
        lowercase = (buf[FATDIR_NTRES] & FAT_NTRES_LC_EXT);
1655
        de->name[j++] = '.';
1656
        for (i = 8; (i < 11) && ((c = buf[FATDIR_NAME+i]) != ' '); i++)
1657
            de->name[j++] = lowercase ? tolower(c) : c;
1658
    }
1659
    return 1;
1660
}
1661
 
1662
int fat_open(IF_MV2(int volume,)
1663
             long startcluster,
1664
             struct fat_file *file,
1665
             const struct fat_dir* dir)
1666
{
1667
    /* Remember where the file's dir entry is located
1668
     * Do it before assigning other fields so that fat_open
1669
     * can be called with file == &dir->file (see fat_opendir) */
1670
    if ( dir ) {
1671
        file->direntry = dir->entry - 1;
1672
        file->direntries = dir->entrycount;
1673
        file->dircluster = dir->file.firstcluster;
1674
    }
1675
 
1676
    file->firstcluster = startcluster;
1677
    file->lastcluster = startcluster;
1678
    file->lastsector = 0;
1679
    file->clusternum = 0;
1680
    file->sectornum = 0;
1681
    file->eof = false;
1682
#ifdef HAVE_MULTIVOLUME
1683
    file->volume = volume;
1684
    /* fixme: remove error check when done */
1685
    if (volume >= NUM_VOLUMES || !fat_bpbs[volume].mounted)
1686
    {
1687
        DEBUGF("fat_open() illegal volume %d", volume);
1688
        return -1;
1689
    }
1690
#endif
1691
 
1692
    DEBUGF("fat_open(%lx), entry %d",startcluster,file->direntry);
1693
    return 0;
1694
}
1695
 
1696
int fat_create_file(const char* name,
1697
                    struct fat_file* file,
1698
                    struct fat_dir* dir)
1699
{
1700
    int rc;
1701
 
1702
    DEBUGF("fat_create_file(\"%s\",%lx,%lx)",name,(long)file,(long)dir);
1703
    rc = add_dir_entry(dir, file, name, false, false);
1704
    if (!rc) {
1705
        file->firstcluster = 0;
1706
        file->lastcluster = 0;
1707
        file->lastsector = 0;
1708
        file->clusternum = 0;
1709
        file->sectornum = 0;
1710
        file->eof = false;
1711
    }
1712
 
1713
    return rc;
1714
}
1715
 
1716
int fat_create_dir(const char* name,
1717
                   struct fat_dir* dir)
1718
{
1719
#ifdef HAVE_MULTIVOLUME
1720
    struct bpb* fat_bpb = &fat_bpbs[dir->file.volume];
1721
#else
1722
    struct bpb* fat_bpb = &fat_bpbs[0];
1723
#endif
1724
    int i;
1725
    long sector;
1726
    int rc;
1727
    struct fat_file newdir;
1728
 
1729
    DEBUGF("fat_create_dir(\"%s\",%lx)",name,(long)dir);
1730
 
1731
    /* First, add the entry in the parent directory */
1732
    rc = add_dir_entry(dir, &newdir, name, true, false);
1733
    if (rc < 0)
1734
        return rc * 10 - 1;
1735
 
1736
    /* Allocate a new cluster for the directory */
1737
    newdir.firstcluster = find_free_cluster(IF_MV2(fat_bpb,)
1738
                                            fat_bpb->fsinfo.nextfree);
1739
    if(newdir.firstcluster == 0)
1740
        return -6;
1741
 
1742
    update_fat_entry(IF_MV2(fat_bpb,) newdir.firstcluster, FAT_EOF_MARK);
1743
 
1744
    /* Clear the entire cluster */
1745
    unsigned char* buf = fat_get_sector_buffer();
1746
    sector = cluster2sec(IF_MV2(fat_bpb,) newdir.firstcluster);
1747
    for(i = 0;i < (int)fat_bpb->bpb_secperclus;i++) {
1748
        memset(buf, 0, SECTOR_SIZE);
1749
        if (!i)
1750
        {
222 theseven 1751
            memcpy(buf, ".          \x10", 12);
1752
            memcpy(&buf[0x20], "..         \x10", 12);
211 theseven 1753
            ((uint16_t*)buf)[0xd] = newdir.firstcluster;
1754
            ((uint16_t*)buf)[0xa] = newdir.firstcluster >> 16;
1755
            if(dir->file.firstcluster == fat_bpb->bpb_rootclus)
1756
            {
1757
                ((uint16_t*)buf)[0x1d] = fat_bpb->bpb_rootclus;
1758
                ((uint16_t*)buf)[0x1a] = fat_bpb->bpb_rootclus >> 16;
1759
            }
1760
        }
1761
        rc = transfer(IF_MV2(fat_bpb,) sector + i, 1, buf, true );
1762
        if (rc < 0)
1763
        {
1764
            fat_release_sector_buffer();
1765
            return rc * 10 - 2;
1766
        }
1767
    }
1768
    fat_release_sector_buffer();
1769
 
1770
    /* Set the firstcluster field in the direntry */
1771
    update_short_entry(&newdir, 0, FAT_ATTR_DIRECTORY);
1772
 
1773
    rc = flush_fat(IF_MV(fat_bpb));
1774
    if (rc < 0)
1775
        return rc * 10 - 5;
1776
 
1777
    return 0;
1778
}
1779
 
1780
int fat_truncate(const struct fat_file *file)
1781
{
1782
    /* truncate trailing clusters */
1783
    long next;
1784
    long last = file->lastcluster;
1785
#ifdef HAVE_MULTIVOLUME
1786
    struct bpb* fat_bpb = &fat_bpbs[file->volume];
1787
#endif
1788
 
1789
    DEBUGF("fat_truncate(%lx, %lx)", file->firstcluster, last);
1790
 
1791
    for ( last = get_next_cluster(IF_MV2(fat_bpb,) last); last; last = next ) {
1792
        next = get_next_cluster(IF_MV2(fat_bpb,) last);
1793
        update_fat_entry(IF_MV2(fat_bpb,) last,0);
1794
    }
1795
    if (file->lastcluster)
1796
        update_fat_entry(IF_MV2(fat_bpb,) file->lastcluster,FAT_EOF_MARK);
1797
 
1798
    return 0;
1799
}
1800
 
1801
int fat_closewrite(struct fat_file *file, long size, int attr)
1802
{
1803
    int rc;
1804
#ifdef HAVE_MULTIVOLUME
1805
    struct bpb* fat_bpb = &fat_bpbs[file->volume];
1806
#endif
1807
    DEBUGF("fat_closewrite(size=%ld)",size);
1808
 
1809
    if (!size) {
1810
        /* empty file */
1811
        if ( file->firstcluster ) {
1812
            update_fat_entry(IF_MV2(fat_bpb,) file->firstcluster, 0);
1813
            file->firstcluster = 0;
1814
        }
1815
    }
1816
 
1817
    if (file->dircluster) {
1818
        rc = update_short_entry(file, size, attr);
1819
        if (rc < 0)
1820
            return rc * 10 - 1;
1821
    }
1822
 
1823
    flush_fat(IF_MV(fat_bpb));
1824
 
1825
#ifdef TEST_FAT
1826
    if ( file->firstcluster ) {
1827
        /* debug */
1828
#ifdef HAVE_MULTIVOLUME
1829
        struct bpb* fat_bpb = &fat_bpbs[file->volume];
1830
#else
1831
        struct bpb* fat_bpb = &fat_bpbs[0];
1832
#endif
1833
        long count = 0;
1834
        long len;
1835
        long next;
1836
        for ( next = file->firstcluster; next;
1837
              next = get_next_cluster(IF_MV2(fat_bpb,) next) ) {
1838
            DEBUGF("cluster %ld: %lx", count, next);
1839
            count++;
1840
        }
1841
        len = count * fat_bpb->bpb_secperclus * SECTOR_SIZE;
1842
        DEBUGF("File is %ld clusters (chainlen=%ld, size=%ld)",
1843
                count, len, size );
1844
        if ( len > size + fat_bpb->bpb_secperclus * SECTOR_SIZE)
1845
            panicf(PANIC_KILLUSERTHREADS, "Cluster chain is too long");
1846
        if ( len < size )
1847
            panicf(PANIC_KILLUSERTHREADS, "Cluster chain is too short");
1848
    }
1849
#endif
1850
 
1851
    return 0;
1852
}
1853
 
1854
static int free_direntries(struct fat_file* file)
1855
{
1856
    struct fat_file dir;
1857
    int numentries = file->direntries;
1858
    unsigned int entry = file->direntry - numentries + 1;
1859
    unsigned int sector = entry / DIR_ENTRIES_PER_SECTOR;
1860
    int i;
1861
    int rc;
1862
 
1863
    /* create a temporary file handle for the dir holding this file */
1864
    rc = fat_open(IF_MV2(file->volume,) file->dircluster, &dir, NULL);
1865
    if (rc < 0)
1866
        return rc * 10 - 1;
1867
 
1868
    rc = fat_seek( &dir, sector );
1869
    if (rc < 0)
1870
        return rc * 10 - 2;
1871
 
1872
    unsigned char* buf = fat_get_sector_buffer();
1873
    rc = fat_readwrite(&dir, 1, buf, false);
1874
    if (rc < 1)
1875
    {
1876
        fat_release_sector_buffer();
1877
        return rc * 10 - 3;
1878
    }
1879
 
1880
    for (i=0; i < numentries; i++) {
1881
        DEBUGF("Clearing dir entry %d (%d/%d)",
1882
                entry, i+1, numentries);
1883
        buf[(entry % DIR_ENTRIES_PER_SECTOR) * DIR_ENTRY_SIZE] = 0xe5;
1884
        entry++;
1885
 
1886
        if ( (entry % DIR_ENTRIES_PER_SECTOR) == 0 ) {
1887
            /* flush this sector */
1888
            rc = fat_seek(&dir, sector);
1889
            if (rc < 0)
1890
            {
1891
                fat_release_sector_buffer();
1892
                return rc * 10 - 4;
1893
            }
1894
 
1895
            rc = fat_readwrite(&dir, 1, buf, true);
1896
            if (rc < 1)
1897
            {
1898
                fat_release_sector_buffer();
1899
                return rc * 10 - 5;
1900
            }
1901
 
1902
            if ( i+1 < numentries ) {
1903
                /* read next sector */
1904
                rc = fat_readwrite(&dir, 1, buf, false);
1905
                if (rc < 1)
1906
                {
1907
                    fat_release_sector_buffer();
1908
                    return rc * 10 - 6;
1909
                }
1910
            }
1911
            sector++;
1912
        }
1913
    }
1914
 
1915
    if ( entry % DIR_ENTRIES_PER_SECTOR ) {
1916
        /* flush this sector */
1917
        rc = fat_seek(&dir, sector);
1918
        if (rc < 0)
1919
        {
1920
            fat_release_sector_buffer();
1921
            return rc * 10 - 7;
1922
        }
1923
 
1924
        rc = fat_readwrite(&dir, 1, buf, true);
1925
        if (rc < 1)
1926
        {
1927
            fat_release_sector_buffer();
1928
            return rc * 10 - 8;
1929
        }
1930
    }
1931
 
1932
    fat_release_sector_buffer();
1933
    return 0;
1934
}
1935
 
1936
int fat_remove(struct fat_file* file)
1937
{
1938
    long next, last = file->firstcluster;
1939
    int rc;
1940
#ifdef HAVE_MULTIVOLUME
1941
    struct bpb* fat_bpb = &fat_bpbs[file->volume];
1942
#endif
1943
 
1944
    DEBUGF("fat_remove(%lx)",last);
1945
 
1946
    while ( last ) {
1947
        next = get_next_cluster(IF_MV2(fat_bpb,) last);
1948
        update_fat_entry(IF_MV2(fat_bpb,) last,0);
1949
        last = next;
1950
    }
1951
 
1952
    if ( file->dircluster ) {
1953
        rc = free_direntries(file);
1954
        if (rc < 0)
1955
            return rc * 10 - 1;
1956
    }
1957
 
1958
    file->firstcluster = 0;
1959
    file->dircluster = 0;
1960
 
1961
    rc = flush_fat(IF_MV(fat_bpb));
1962
    if (rc < 0)
1963
        return rc * 10 - 2;
1964
 
1965
    return 0;
1966
}
1967
 
1968
int fat_rename(struct fat_file* file, 
1969
                struct fat_dir* dir, 
1970
                const unsigned char* newname,
1971
                long size,
1972
                int attr)
1973
{
1974
    int rc;
1975
    struct fat_file newfile = *file;
1976
    unsigned char* entry = NULL;
1977
    unsigned short* clusptr = NULL;
1978
    unsigned int parentcluster;
1979
#ifdef HAVE_MULTIVOLUME
1980
    struct bpb* fat_bpb = &fat_bpbs[file->volume];
1981
 
1982
    if (file->volume != dir->file.volume) {
1983
        DEBUGF("No rename across volumes!");
1984
        return -1;
1985
    }
1986
#else
1987
    struct bpb* fat_bpb = &fat_bpbs[0];
1988
#endif
1989
 
1990
    if ( !file->dircluster ) {
1991
        DEBUGF("File has no dir cluster!");
1992
        return -2;
1993
    }
1994
 
1995
    /* create new name */
1996
    rc = add_dir_entry(dir, &newfile, newname, false, false);
1997
    if (rc < 0)
1998
        return rc * 10 - 2;
1999
 
2000
    /* write size and cluster link */
2001
    rc = update_short_entry(&newfile, size, attr);
2002
    if (rc < 0)
2003
        return rc * 10 - 3;
2004
 
2005
    /* remove old name */
2006
    rc = free_direntries(file);
2007
    if (rc < 0)
2008
        return rc * 10 - 4;
2009
 
2010
    rc = flush_fat(IF_MV(fat_bpb));
2011
    if (rc < 0)
2012
        return rc * 10 - 5;
2013
 
2014
    /* if renaming a directory, update the .. entry to make sure
2015
       it points to its parent directory (we don't check if it was a move) */
2016
    if(FAT_ATTR_DIRECTORY == attr) {
2017
        /* open the dir that was renamed, we re-use the newfile struct */
2018
 
2019
        rc = fat_open(IF_MV2(volume,) newfile.firstcluster, &newfile, NULL);
2020
        if (rc < 0)
2021
            return rc * 10 - 6;
2022
 
2023
        /* get the first sector of the dir */
2024
        rc = fat_seek(&newfile, 0);
2025
        if (rc < 0)
2026
            return rc * 10 - 7;
2027
 
2028
        unsigned char* buf = fat_get_sector_buffer();
2029
        rc = fat_readwrite(&newfile, 1, buf, false);
2030
        if (rc < 0)
2031
        {
2032
            fat_release_sector_buffer();
2033
            return rc * 10 - 8;
2034
        }
2035
 
2036
        /* parent cluster is 0 if parent dir is the root - FAT spec (p.29) */
2037
        if(dir->file.firstcluster == fat_bpb->bpb_rootclus)
2038
            parentcluster = 0;
2039
        else
2040
            parentcluster = dir->file.firstcluster;
2041
 
2042
        entry = buf + DIR_ENTRY_SIZE;
2043
        if(strncmp("..         ", entry, 11))
2044
        {
2045
            fat_release_sector_buffer();
2046
            /* .. entry must be second entry according to FAT spec (p.29) */
2047
            DEBUGF("Second dir entry is not double-dot!");
2048
            return rc * 10 - 9;
2049
        }
2050
        clusptr = (short*)(entry + FATDIR_FSTCLUSHI);
2051
        *clusptr = htole16(parentcluster >> 16);
2052
 
2053
        clusptr = (short*)(entry + FATDIR_FSTCLUSLO);
2054
        *clusptr = htole16(parentcluster & 0xffff);
2055
 
2056
        /* write back this sector */
2057
        rc = fat_seek(&newfile, 0);
2058
        if (rc < 0)
2059
        {
2060
            fat_release_sector_buffer();
2061
            return rc * 10 - 7;
2062
        }
2063
 
2064
        rc = fat_readwrite(&newfile, 1, buf, true);
2065
        fat_release_sector_buffer();
2066
        if (rc < 1)
2067
            return rc * 10 - 8;
2068
    }
2069
 
2070
    return 0;
2071
}
2072
 
2073
static long next_write_cluster(struct fat_file* file,
2074
                              long oldcluster,
2075
                              long* newsector)
2076
{
2077
#ifdef HAVE_MULTIVOLUME
2078
    struct bpb* fat_bpb = &fat_bpbs[file->volume];
2079
#else
2080
    struct bpb* fat_bpb = &fat_bpbs[0];
2081
#endif
2082
    long cluster = 0;
2083
    long sector;
2084
 
2085
    DEBUGF("next_write_cluster(%lx,%lx)",file->firstcluster, oldcluster);
2086
 
2087
    if (oldcluster)
2088
        cluster = get_next_cluster(IF_MV2(fat_bpb,) oldcluster);
2089
 
2090
    if (!cluster) {
2091
        if (oldcluster > 0)
2092
            cluster = find_free_cluster(IF_MV2(fat_bpb,) oldcluster+1);
2093
        else if (oldcluster == 0)
2094
            cluster = find_free_cluster(IF_MV2(fat_bpb,)
2095
                                        fat_bpb->fsinfo.nextfree);
2096
#ifdef HAVE_FAT16SUPPORT
2097
        else /* negative, pseudo-cluster of the root dir */
2098
            return 0; /* impossible to append something to the root */
2099
#endif
2100
 
2101
        if (cluster) {
2102
            if (oldcluster)
2103
                update_fat_entry(IF_MV2(fat_bpb,) oldcluster, cluster);
2104
            else
2105
                file->firstcluster = cluster;
2106
            update_fat_entry(IF_MV2(fat_bpb,) cluster, FAT_EOF_MARK);
2107
        }
2108
        else {
2109
#ifdef TEST_FAT
2110
            if (fat_bpb->fsinfo.freecount>0)
2111
                panicf(PANIC_KILLUSERTHREADS, "There is free space, but find_free_cluster() "
2112
                       "didn't find it!");
2113
#endif
2114
            DEBUGF("next_write_cluster(): Disk full!");
2115
            return 0;
2116
        }
2117
    }
2118
    sector = cluster2sec(IF_MV2(fat_bpb,) cluster);
2119
    if (sector<0)
2120
        return 0;
2121
 
2122
    *newsector = sector;
2123
    return cluster;
2124
}
2125
 
2126
static int transfer(IF_MV2(struct bpb* fat_bpb,) 
2127
                    unsigned long start, long count, char* buf, bool write )
2128
{
2129
#ifndef HAVE_MULTIVOLUME
2130
    struct bpb* fat_bpb = &fat_bpbs[0];
2131
#endif
2132
    int rc;
2133
 
2134
    DEBUGF("transfer(s=%lx, c=%lx, %s)",
2135
        start+ fat_bpb->startsector, count, write?"write":"read");
2136
    if (write) {
2137
        unsigned long firstallowed;
2138
#ifdef HAVE_FAT16SUPPORT
2139
        if (fat_bpb->is_fat16)
2140
            firstallowed = fat_bpb->rootdirsector;
2141
        else
2142
#endif
2143
            firstallowed = fat_bpb->firstdatasector;
2144
 
2145
        if (start < firstallowed)
2146
            panicf(PANIC_KILLUSERTHREADS, "Write %ld before data", firstallowed - start);
2147
        if (start + count > fat_bpb->totalsectors)
2148
            panicf(PANIC_KILLUSERTHREADS, "Write %ld after data",
2149
                start + count - fat_bpb->totalsectors);
2150
        rc = storage_write_sectors(IF_MD2(fat_bpb->drive,)
2151
                               start + fat_bpb->startsector, count, buf);
2152
    }
2153
    else
2154
        rc = storage_read_sectors(IF_MD2(fat_bpb->drive,)
2155
                              start + fat_bpb->startsector, count, buf);
2156
    if (rc < 0) {
2157
        DEBUGF( "transfer() - Couldn't %s sector %lx"
2158
                " (error code %d)", 
2159
                write ? "write":"read", start, rc);
2160
        return rc;
2161
    }
2162
    return 0;
2163
}
2164
 
2165
 
2166
long fat_readwrite( struct fat_file *file, long sectorcount,
2167
                   void* buf, bool write )
2168
{
2169
#ifdef HAVE_MULTIVOLUME
2170
    struct bpb* fat_bpb = &fat_bpbs[file->volume];
2171
#else
2172
    struct bpb* fat_bpb = &fat_bpbs[0];
2173
#endif
2174
    long cluster = file->lastcluster;
2175
    long sector = file->lastsector;
2176
    long clusternum = file->clusternum;
2177
    long numsec = file->sectornum;
2178
    bool eof = file->eof;
2179
    long first=0, last=0;
2180
    long i;
2181
    int rc;
2182
 
2183
    DEBUGF( "fat_readwrite(file:%lx,count:0x%lx,buf:%lx,%s)",
2184
             file->firstcluster,sectorcount,(long)buf,write?"write":"read");
2185
    DEBUGF( "fat_readwrite: sec=%lx numsec=%ld eof=%d",
2186
             sector,numsec, eof?1:0);
2187
 
2188
    if ( eof && !write)
2189
        return 0;
2190
 
2191
    /* find sequential sectors and write them all at once */
2192
    for (i=0; (i < sectorcount) && (sector > -1); i++ ) {
2193
        numsec++;
2194
        if ( numsec > (long)fat_bpb->bpb_secperclus || !cluster ) {
2195
            long oldcluster = cluster;
2196
            long oldsector = sector;
2197
            long oldnumsec = numsec;
2198
            if (write)
2199
                cluster = next_write_cluster(file, cluster, &sector);
2200
            else {
2201
                cluster = get_next_cluster(IF_MV2(fat_bpb,) cluster);
2202
                sector = cluster2sec(IF_MV2(fat_bpb,) cluster);
2203
            }
2204
 
2205
            clusternum++;
2206
            numsec=1;
2207
 
2208
            if (!cluster) {
2209
                eof = true;
2210
                if ( write ) {
2211
                    /* remember last cluster, in case
2212
                       we want to append to the file */
2213
                    sector = oldsector;
2214
                    cluster = oldcluster;
2215
                    numsec = oldnumsec;
2216
                    clusternum--;
2217
                    i = -1; /* Error code */
2218
                    break;
2219
                }
2220
            }
2221
            else
2222
                eof = false;
2223
        }
2224
        else {
2225
            if (sector)
2226
                sector++;
2227
            else {
2228
                /* look up first sector of file */
2229
                sector = cluster2sec(IF_MV2(fat_bpb,) file->firstcluster);
2230
                numsec=1;
2231
#ifdef HAVE_FAT16SUPPORT
2232
                if (file->firstcluster < 0)
2233
                {   /* FAT16 root dir */
2234
                    sector += fat_bpb->rootdiroffset;
2235
                    numsec += fat_bpb->rootdiroffset;
2236
                }
2237
#endif
2238
            }
2239
        }
2240
 
2241
        if (!first)
2242
            first = sector;
2243
 
2244
        if ( ((sector != first) && (sector != last+1)) || /* not sequential */
2245
             (last-first+1 == 256) ) { /* max 256 sectors per ata request */
2246
            long count = last - first + 1;
2247
            rc = transfer(IF_MV2(fat_bpb,) first, count, buf, write );
2248
            if (rc < 0)
2249
                return rc * 10 - 1;
2250
 
2251
            buf = (char *)buf + count * SECTOR_SIZE;
2252
            first = sector;
2253
        }
2254
 
2255
        if ((i == sectorcount-1) && /* last sector requested */
2256
            (!eof))
2257
        {
2258
            long count = sector - first + 1;
2259
            rc = transfer(IF_MV2(fat_bpb,) first, count, buf, write );
2260
            if (rc < 0)
2261
                return rc * 10 - 2;
2262
        }
2263
 
2264
        last = sector;
2265
    }
2266
 
2267
    file->lastcluster = cluster;
2268
    file->lastsector = sector;
2269
    file->clusternum = clusternum;
2270
    file->sectornum = numsec;
2271
    file->eof = eof;
2272
 
2273
    /* if eof, don't report last block as read/written */
2274
    if (eof)
2275
        i--;
2276
 
2277
    DEBUGF("Sectors written: %ld", i);
2278
    return i;
2279
}
2280
 
2281
int fat_seek(struct fat_file *file, unsigned long seeksector )
2282
{
2283
#ifdef HAVE_MULTIVOLUME
2284
    struct bpb* fat_bpb = &fat_bpbs[file->volume];
2285
#else
2286
    struct bpb* fat_bpb = &fat_bpbs[0];
2287
#endif
2288
    long clusternum=0, numclusters=0, sectornum=0, sector=0;
2289
    long cluster = file->firstcluster;
2290
    long i;
2291
 
2292
#ifdef HAVE_FAT16SUPPORT
2293
    if (cluster < 0) /* FAT16 root dir */
2294
        seeksector += fat_bpb->rootdiroffset;
2295
#endif
2296
 
2297
    file->eof = false;
2298
    if (seeksector) {
2299
        /* we need to find the sector BEFORE the requested, since
2300
           the file struct stores the last accessed sector */
2301
        seeksector--;
2302
        numclusters = clusternum = seeksector / fat_bpb->bpb_secperclus;
2303
        sectornum = seeksector % fat_bpb->bpb_secperclus;
2304
 
2305
        if (file->clusternum && clusternum >= file->clusternum)
2306
        {
2307
            cluster = file->lastcluster;
2308
            numclusters -= file->clusternum;
2309
        }
2310
 
2311
        for (i=0; i<numclusters; i++) {
2312
            cluster = get_next_cluster(IF_MV2(fat_bpb,) cluster);
2313
            if (!cluster) {
2314
                DEBUGF("Seeking beyond the end of the file! "
2315
                       "(sector %ld, cluster %ld)", seeksector, i);
2316
                return -1;
2317
            }
2318
        }
2319
 
2320
        sector = cluster2sec(IF_MV2(fat_bpb,) cluster) + sectornum;
2321
    }
2322
    else {
2323
        sectornum = -1;
2324
    }
2325
 
2326
    DEBUGF("fat_seek(%lx, %lx) == %lx, %lx, %lx",
2327
            file->firstcluster, seeksector, cluster, sector, sectornum);
2328
 
2329
    file->lastcluster = cluster;
2330
    file->lastsector = sector;
2331
    file->clusternum = clusternum;
2332
    file->sectornum = sectornum + 1;
2333
    return 0;
2334
}
2335
 
2336
int fat_opendir(IF_MV2(int volume,) 
2337
                struct fat_dir *dir, unsigned long startcluster,
2338
                const struct fat_dir *parent_dir)
2339
{
2340
#ifdef HAVE_MULTIVOLUME
2341
    struct bpb* fat_bpb = &fat_bpbs[volume];
2342
    /* fixme: remove error check when done */
2343
    if (volume >= NUM_VOLUMES || !fat_bpbs[volume].mounted)
2344
    {
2345
        DEBUGF("fat_open() illegal volume %d", volume);
2346
        return -1;
2347
    }
2348
#else
2349
    struct bpb* fat_bpb = &fat_bpbs[0];
2350
#endif
2351
    int rc;
2352
 
2353
    if (startcluster == 0)
2354
        startcluster = fat_bpb->bpb_rootclus;
2355
 
2356
    rc = fat_open(IF_MV2(volume,) startcluster, &dir->file, parent_dir);
2357
    if(rc)
2358
    {
2359
        DEBUGF( "fat_opendir() - Couldn't open dir"
2360
                " (error code %d)", rc);
2361
        return rc * 10 - 1;
2362
    }
2363
 
2364
    /* assign them after fat_open call so that fat_opendir can be called with the same
2365
     * fat_dir as parent and result */
2366
    dir->entry = 0;
2367
    dir->sector = 0;
2368
 
2369
    return 0;
2370
}
2371
 
2372
int fat_getnext(struct fat_dir *dir, struct fat_direntry *entry)
2373
{
2374
    bool done = false;
2375
    int i, j;
2376
    int rc;
2377
    int order;
2378
    unsigned char firstbyte;
2379
    /* Long file names are stored in special entries. Each entry holds
2380
       up to 13 characters. Names can be max 255 chars (not bytes!) long */
2381
    /* The number of long entries in the long name can be retrieve from the first
2382
     * long entry because there are stored in reverse order and have an ordinal */
2383
    int nb_longs = 0;
2384
    /* The long entries are expected to be in order, so remember the last ordinal */
2385
    int last_long_ord = 0;
2386
 
2387
    dir->entrycount = 0;
2388
 
2389
    while(!done)
2390
    {
2391
        if ( !(dir->entry % DIR_ENTRIES_PER_SECTOR) || !dir->sector )
2392
        {
2393
            rc = fat_readwrite(&dir->file, 1, dir->sectorcache, false);
2394
            if (rc == 0) {
2395
                /* eof */
2396
                entry->name[0] = 0;
2397
                break;
2398
            }
2399
            if (rc < 0) {
2400
                DEBUGF( "fat_getnext() - Couldn't read dir"
2401
                        " (error code %d)", rc);
2402
                return rc * 10 - 1;
2403
            }
2404
            dir->sector = dir->file.lastsector;
2405
        }
2406
 
2407
        for (i = dir->entry % DIR_ENTRIES_PER_SECTOR;
2408
             i < DIR_ENTRIES_PER_SECTOR; i++) {
2409
            unsigned int entrypos = i * DIR_ENTRY_SIZE;
2410
 
2411
            firstbyte = dir->sectorcache[entrypos];
2412
            dir->entry++;
2413
 
2414
            if (firstbyte == 0xe5) {
2415
                /* free entry */
2416
                dir->entrycount = 0;
2417
                continue;
2418
            }
2419
 
2420
            if (firstbyte == 0) {
2421
                /* last entry */
2422
                entry->name[0] = 0;
2423
                dir->entrycount = 0;
2424
                return 0;
2425
            }
2426
 
2427
            dir->entrycount++;
2428
 
2429
            /* LFN entry? */
2430
            if ( ( dir->sectorcache[entrypos + FATDIR_ATTR] &
2431
                   FAT_ATTR_LONG_NAME_MASK ) == FAT_ATTR_LONG_NAME ) {
2432
                /* extract ordinal */
2433
                order = dir->sectorcache[entrypos + FATLONG_ORDER] & ~FATLONG_LAST_LONG_ENTRY;
2434
                /* is this entry the first long entry ? (first in order but containing last part) */
2435
                if (dir->sectorcache[entrypos + FATLONG_ORDER] & FATLONG_LAST_LONG_ENTRY) {
2436
                    /* check that order is not too big ! (and non-zero) */
2437
                    if(order <= 0 || order > FATLONG_MAX_ORDER)
2438
                        continue; /* ignore the whole LFN, will trigger lots of warnings */
2439
                    nb_longs = order;
2440
                    last_long_ord = order;
2441
                }
2442
                else {
2443
                    /* check orphan entry */
2444
                    if (nb_longs == 0) {
2445
                        DEBUGF("fat warning: orphan LFN entry");
2446
                        /* ignore */
2447
                        continue;
2448
                    }
2449
 
2450
                    /* check order */
2451
                    if (order != (last_long_ord - 1)) {
2452
                        DEBUGF("fat warning: wrong LFN ordinal");
2453
                        /* ignore the whole LFN, will trigger lots of warnings */
2454
                        nb_longs = 0;
2455
                    }
2456
 
2457
                    last_long_ord = order;
2458
                }
2459
 
2460
                /* copy part, reuse [order] for another purpose :) */
2461
                order = (order - 1) * FATLONG_NAME_BYTES_PER_ENTRY;
2462
                for(j = 0; j < FATLONG_NAME_CHUNKS; j++) {
2463
                    memcpy(dir->longname + order,
2464
                            dir->sectorcache + entrypos + FATLONG_NAME_POS[j],
2465
                            FATLONG_NAME_SIZE[j]);
2466
                    order += FATLONG_NAME_SIZE[j];
2467
                }
2468
            }
2469
            else {
2470
                if ( parse_direntry(entry, dir->sectorcache + entrypos) ) {
2471
 
2472
                    /* don't return volume id entry */
2473
                    if ( (entry->attr &
2474
                          (FAT_ATTR_VOLUME_ID|FAT_ATTR_DIRECTORY))
2475
                         == FAT_ATTR_VOLUME_ID)
2476
                        continue;
2477
 
2478
                    /* replace shortname with longname? */
2479
                    /* check that the long name is complete */
2480
                    if (nb_longs != 0 && last_long_ord == 1) {
2481
                        /* hold a copy of the shortname in case the long one is too long */
2482
                        unsigned char shortname[13]; /* 8+3+dot+\0 */
2483
                        int longname_utf8len = 0;
2484
                        /* One character at a time, add 1 for trailing \0, 4 is the maximum size
2485
                         * of a UTF8 encoded character in rockbox */
2486
                        unsigned char longname_utf8segm[4 + 1];
2487
                        unsigned short ucs;
2488
                        int segm_utf8len;
2489
                        /* Temporarily store short name */
2490
                        strcpy(shortname, entry->name);
2491
                        entry->name[0] = 0;
2492
 
2493
                        /* Convert the FAT name to a utf8-encoded one.
2494
                         * The name is not necessary NUL-terminated ! */
2495
                        for (j = 0; j < nb_longs * FATLONG_NAME_BYTES_PER_ENTRY; j += 2) {
2496
                            ucs = dir->longname[j] | (dir->longname[j + 1] << 8);
2497
                            if(ucs == 0 || ucs == FAT_LONGNAME_PAD_UCS)
2498
                                break;
2499
                            /* utf8encode will return a pointer after the converted
2500
                             * string, subtract the pointer to the start to get the length of it */
2501
                            segm_utf8len = 1;
2502
 
2503
                            /* warn the trailing zero ! (FAT_FILENAME_BYTES includes it) */
2504
                            if (longname_utf8len + segm_utf8len >= FAT_FILENAME_BYTES) {
2505
                                /* force use of short name */
2506
                                longname_utf8len = FAT_FILENAME_BYTES + 1;
2507
                                break; /* fallback later */
2508
                            }
2509
                            else {
2510
                                if (ucs < 128) longname_utf8segm[0] = (unsigned char)ucs;
2511
                                else longname_utf8segm[0] = '?';
2512
                                longname_utf8segm[segm_utf8len] = 0;
2513
                                strcat(entry->name + longname_utf8len, longname_utf8segm);
2514
                                longname_utf8len += segm_utf8len;
2515
                            }
2516
                        }
2517
 
2518
                        /* Does the utf8-encoded name fit into the entry? */
2519
                        /* warn the trailing zero ! (FAT_FILENAME_BYTES includes it) */
2520
                        if (longname_utf8len >= FAT_FILENAME_BYTES) {
2521
                            /* Take the short DOS name. Need to utf8-encode it
2522
                               since it may contain chars from the upper half of
2523
                               the OEM code page which wouldn't be a valid utf8.
2524
                               Beware: this file will be shown with strange
2525
                               glyphs in file browser since unicode 0x80 to 0x9F
2526
                               are control characters. */
2527
                            DEBUGF("SN-DOS: %s", shortname);
2528
                            unsigned char *utf8;
2529
                            memcpy(entry->name, shortname, strlen(shortname));
2530
                            *(entry->name + strlen(shortname)) = 0;
2531
                            DEBUGF("SN: %s", entry->name);
2532
                        } else {
2533
                            DEBUGF("LN: %s", entry->name);
2534
                            DEBUGF("LNLen: %d", longname_utf8len);
2535
                        }
2536
                    }
2537
                    done = true;
2538
                    i++;
2539
                    break;
2540
                }
2541
            }
2542
        }
2543
    }
2544
    return 0;
2545
}
2546
 
2547
unsigned int fat_get_cluster_size(IF_MV_NONVOID(int volume))
2548
{
2549
#ifndef HAVE_MULTIVOLUME
2550
    const int volume = 0;
2551
#endif
2552
    struct bpb* fat_bpb = &fat_bpbs[volume];
2553
    return fat_bpb->bpb_secperclus * SECTOR_SIZE;
2554
}
2555
 
2556
#ifdef HAVE_MULTIVOLUME
2557
bool fat_ismounted(int volume)
2558
{
2559
    return (volume<NUM_VOLUMES && fat_bpbs[volume].mounted);
2560
}
2561
#endif