Subversion Repositories freemyipod

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

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