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