Subversion Repositories freemyipod

Rev

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