Subversion Repositories freemyipod

Rev

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

Rev Author Line No. Line
69 theseven 1
/***************************************************************************
2
 *             __________               __   ___.
3
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
4
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
5
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
6
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
7
 *                     \/            \/     \/    \/            \/
8
 * $Id: file.c 26191 2010-05-20 12:59:12Z funman $
9
 *
10
 * Copyright (C) 2002 by Björn Stenberg
11
 *
12
 * This program is free software; you can redistribute it and/or
13
 * modify it under the terms of the GNU General Public License
14
 * as published by the Free Software Foundation; either version 2
15
 * of the License, or (at your option) any later version.
16
 *
17
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18
 * KIND, either express or implied.
19
 *
20
 ****************************************************************************/
21
#include "global.h"
114 theseven 22
#include "libc/include/errno.h"
23
#include "libc/include/string.h"
69 theseven 24
#include "file.h"
25
#include "fat.h"
26
#include "dir.h"
27
#include "util.h"
28
 
29
/*
30
  These functions provide a roughly POSIX-compatible file IO API.
31
 
32
  Since the fat32 driver only manages sectors, we maintain a one-sector
33
  cache for each open file. This way we can provide byte access without
34
  having to re-read the sector each time.
35
  The penalty is the RAM used for the cache and slightly more complex code.
36
*/
37
 
58 theseven 38
extern struct scheduler_thread* current_thread;
69 theseven 39
 
40
struct filedesc {
41
    unsigned char cache[SECTOR_SIZE] CACHEALIGN_ATTR;
42
    int cacheoffset; /* invariant: 0 <= cacheoffset <= SECTOR_SIZE */
43
    long fileoffset;
44
    long size;
45
    int attr;
46
    struct fat_file fatfile;
47
    bool busy;
48
    bool write;
49
    bool dirty;
50
    bool trunc;
51
    struct scheduler_thread* process;
52
} CACHEALIGN_ATTR;
53
 
54
static struct filedesc openfiles[MAX_OPEN_FILES] CACHEALIGN_ATTR;
55
 
56
static int flush_cache(int fd);
57
 
58
int file_creat(const char *pathname)
59
{
60
    return open(pathname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
61
}
62
 
63
static int open_internal(const char* pathname, int flags, bool use_cache)
64
{
65
    DIR* dir;
66
    struct dirent* entry;
67
    int fd;
68
    char pathnamecopy[MAX_PATH];
69
    char* name;
70
    struct filedesc* file = NULL;
71
    int rc;
72
 
73
    DEBUGF("open(\"%s\",%d)",pathname,flags);
74
 
75
    if ( pathname[0] != '/' ) {
76
        DEBUGF("'%s' is not an absolute path.", pathname);
77
        DEBUGF("Only absolute pathnames supported at the moment");
78
        errno = EINVAL;
79
        return -1;
80
    }
81
 
82
    /* find a free file descriptor */
83
    for ( fd=0; fd<MAX_OPEN_FILES; fd++ )
84
        if ( !openfiles[fd].busy )
85
            break;
86
 
87
    if ( fd == MAX_OPEN_FILES ) {
88
        DEBUGF("Too many files open");
89
        errno = EMFILE;
90
        return -2;
91
    }
92
 
93
    file = &openfiles[fd];
94
    memset(file, 0, sizeof(struct filedesc));
95
 
96
    if (flags & (O_RDWR | O_WRONLY)) {
97
        file->write = true;
98
 
99
        if (flags & O_TRUNC)
100
            file->trunc = true;
101
    }
102
    file->busy = true;
103
    file->process = current_thread;
104
 
105
    strlcpy(pathnamecopy, pathname, sizeof(pathnamecopy));
106
 
107
    /* locate filename */
108
    name=strrchr(pathnamecopy+1,'/');
109
    if ( name ) {
110
        *name = 0; 
111
        dir = opendir(pathnamecopy);
112
        *name = '/';
113
        name++;
114
    }
115
    else {
116
        dir = opendir("/");
117
        name = pathnamecopy+1;
118
    }
119
    if (!dir) {
120
        DEBUGF("Failed opening dir");
121
        errno = EIO;
122
        file->busy = false;
123
        return -4;
124
    }
125
 
126
    if(name[0] == 0) {
127
        DEBUGF("Empty file name");
128
        errno = EINVAL;
129
        file->busy = false;
130
        closedir(dir);
131
        return -5;
132
    }
133
 
134
    /* scan dir for name */
135
    while ((entry = readdir(dir))) {
136
        if ( !strcasecmp(name, entry->d_name) ) {
137
            fat_open(IF_MV2(dir->fatdir.file.volume,)
138
                     entry->startcluster,
139
                     &(file->fatfile),
140
                     &(dir->fatdir));
141
            file->size = file->trunc ? 0 : entry->size;
142
            file->attr = entry->attribute;
143
            break;
144
        }
145
    }
146
 
147
    if ( !entry ) {
148
        DEBUGF("Didn't find file %s",name);
149
        if ( file->write && (flags & O_CREAT) ) {
150
            rc = fat_create_file(name,
151
                                 &(file->fatfile),
152
                                 &(dir->fatdir));
153
            if (rc < 0) {
154
                DEBUGF("Couldn't create %s in %s",name,pathnamecopy);
155
                errno = EIO;
156
                file->busy = false;
157
                closedir(dir);
158
                return rc * 10 - 6;
159
            }
160
            file->size = 0;
161
            file->attr = 0;
162
        }
163
        else {
164
            DEBUGF("Couldn't find %s in %s",name,pathnamecopy);
165
            errno = ENOENT;
166
            file->busy = false;
167
            closedir(dir);
168
            return -7;
169
        }
170
    } else {
171
        if(file->write && (file->attr & FAT_ATTR_DIRECTORY)) {
172
            errno = EISDIR;
173
            file->busy = false;
174
            closedir(dir);
175
            return -8;
176
        }
177
    }
178
    closedir(dir);
179
 
180
    file->cacheoffset = -1;
181
    file->fileoffset = 0;
182
 
183
    if (file->write && (flags & O_APPEND)) {
184
        rc = lseek(fd,0,SEEK_END);
185
        if (rc < 0 )
186
            return rc * 10 - 9;
187
    }
188
 
189
    return fd;
190
}
191
 
192
int file_open(const char* pathname, int flags)
193
{
194
    /* By default, use the dircache if available. */
195
    return open_internal(pathname, flags, true);
196
}
197
 
198
int close(int fd)
199
{
200
    struct filedesc* file = &openfiles[fd];
201
    int rc = 0;
202
 
203
    DEBUGF("close(%d)", fd);
204
 
205
    if (fd < 0 || fd > MAX_OPEN_FILES-1) {
206
        errno = EINVAL;
207
        return -1;
208
    }
209
    if (!file->busy) {
210
        errno = EBADF;
211
        return -2;
212
    }
213
    if (file->write) {
214
        rc = fsync(fd);
215
        if (rc < 0)
216
            return rc * 10 - 3;
217
    }
218
 
219
    file->busy = false;
220
    return 0;
221
}
222
 
223
int close_all_of_process(struct scheduler_thread* process)
224
{
225
    struct filedesc* pfile = openfiles;
226
    int fd;
227
    int closed = 0;
228
    for ( fd=0; fd<MAX_OPEN_FILES; fd++, pfile++)
229
    {
230
        if (pfile->process == process)
231
        {
232
            pfile->busy = false; /* mark as available, no further action */
233
            closed++;
234
        }
235
    }
236
    return closed; /* return how many we did */
237
}
238
 
239
int fsync(int fd)
240
{
241
    struct filedesc* file = &openfiles[fd];
242
    int rc = 0;
243
 
244
    DEBUGF("fsync(%d)", fd);
245
 
246
    if (fd < 0 || fd > MAX_OPEN_FILES-1) {
247
        errno = EINVAL;
248
        return -1;
249
    }
250
    if (!file->busy) {
251
        errno = EBADF;
252
        return -2;
253
    }
254
    if (file->write) {
255
        /* flush sector cache */
256
        if ( file->dirty ) {
257
            rc = flush_cache(fd);
258
            if (rc < 0)
259
            {
260
                /* when failing, try to close the file anyway */
261
                fat_closewrite(&(file->fatfile), file->size, file->attr);
262
                return rc * 10 - 3;
263
            }
264
        }
265
 
266
        /* truncate? */
267
        if (file->trunc) {
268
            rc = ftruncate(fd, file->size);
269
            if (rc < 0)
270
            {
271
                /* when failing, try to close the file anyway */
272
                fat_closewrite(&(file->fatfile), file->size, file->attr);
273
                return rc * 10 - 4;
274
            }
275
        }
276
 
277
        /* tie up all loose ends */
278
        rc = fat_closewrite(&(file->fatfile), file->size, file->attr);
279
        if (rc < 0)
280
            return rc * 10 - 5;
281
    }
282
    return 0;
283
}
284
 
285
int remove(const char* name)
286
{
287
    int rc;
288
    struct filedesc* file;
289
    /* Can't use dircache now, because we need to access the fat structures. */
290
    int fd = open_internal(name, O_WRONLY, false);
291
    if ( fd < 0 )
292
        return fd * 10 - 1;
293
 
294
    file = &openfiles[fd];
295
    rc = fat_remove(&(file->fatfile));
296
    if ( rc < 0 ) {
297
        DEBUGF("Failed removing file: %d", rc);
298
        errno = EIO;
299
        return rc * 10 - 3;
300
    }
301
 
302
    file->size = 0;
303
 
304
    rc = close(fd);
305
    if (rc<0)
306
        return rc * 10 - 4;
307
 
308
    return 0;
309
}
310
 
311
int rename(const char* path, const char* newpath)
312
{
313
    int rc, fd;
314
    DIR* dir;
315
    char* nameptr;
316
    char* dirptr;
317
    struct filedesc* file;
318
    char newpath2[MAX_PATH];
319
 
320
    /* verify new path does not already exist */
321
    /* If it is a directory, errno == EISDIR if the name exists */
322
    fd = open(newpath, O_RDONLY);
323
    if ( fd >= 0 || errno == EISDIR) {
324
        close(fd);
325
        errno = EBUSY;
326
        return -1;
327
    }
328
    close(fd);
329
 
330
    fd = open_internal(path, O_RDONLY, false);
331
    if ( fd < 0 ) {
332
        errno = EIO;
333
        return fd * 10 - 2;
334
    }
335
 
336
    /* extract new file name */
337
    nameptr = strrchr(newpath,'/');
338
    if (nameptr)
339
        nameptr++;
340
    else {
341
        close(fd);
342
        return - 3;
343
    }
344
 
345
    /* Extract new path */
346
    strcpy(newpath2, newpath);
347
 
348
    dirptr = strrchr(newpath2,'/');
349
    if(dirptr)
350
        *dirptr = 0;
351
    else {
352
        close(fd);
353
        return - 4;
354
    }
355
 
356
    dirptr = newpath2;
357
 
358
    if(strlen(dirptr) == 0) {
359
        dirptr = "/";
360
    }
361
 
362
    dir = opendir(dirptr);
363
    if(!dir) {
364
        close(fd);
365
        return - 5;
366
    }
367
 
368
    file = &openfiles[fd];
369
 
370
    rc = fat_rename(&file->fatfile, &dir->fatdir, nameptr,
371
                    file->size, file->attr);
372
#ifdef HAVE_MULTIVOLUME
373
    if ( rc == -1) {
374
        close(fd);
375
        closedir(dir);
376
        DEBUGF("Failed renaming file across volumnes: %d", rc);
377
        errno = EXDEV;
378
        return -6;
379
    }
380
#endif
381
    if ( rc < 0 ) {
382
        close(fd);
383
        closedir(dir);
384
        DEBUGF("Failed renaming file: %d", rc);
385
        errno = EIO;
386
        return rc * 10 - 7;
387
    }
388
 
389
    rc = close(fd);
390
    if (rc<0) {
391
        closedir(dir);
392
        errno = EIO;
393
        return rc * 10 - 8;
394
    }
395
 
396
    rc = closedir(dir);
397
    if (rc<0) {
398
        errno = EIO;
399
        return rc * 10 - 9;
400
    }
401
 
402
    return 0;
403
}
404
 
405
int ftruncate(int fd, off_t size)
406
{
407
    int rc, sector;
408
    struct filedesc* file = &openfiles[fd];
409
 
410
    sector = size / SECTOR_SIZE;
411
    if (size % SECTOR_SIZE)
412
        sector++;
413
 
414
    rc = fat_seek(&(file->fatfile), sector);
415
    if (rc < 0) {
416
        errno = EIO;
417
        return rc * 10 - 1;
418
    }
419
 
420
    rc = fat_truncate(&(file->fatfile));
421
    if (rc < 0) {
422
        errno = EIO;
423
        return rc * 10 - 2;
424
    }
425
 
426
    file->size = size;
427
 
428
    return 0;
429
}
430
 
431
static int flush_cache(int fd)
432
{
433
    int rc;
434
    struct filedesc* file = &openfiles[fd];
435
    long sector = file->fileoffset / SECTOR_SIZE;
436
 
437
    DEBUGF("Flushing dirty sector cache");
438
 
439
    /* make sure we are on correct sector */
440
    rc = fat_seek(&(file->fatfile), sector);
441
    if ( rc < 0 )
442
        return rc * 10 - 3;
443
 
444
    rc = fat_readwrite(&(file->fatfile), 1, file->cache, true );
445
 
446
    if ( rc < 0 ) {
447
        if(file->fatfile.eof)
448
            errno = ENOSPC;
449
 
450
        return rc * 10 - 2;
451
    }
452
 
453
    file->dirty = false;
454
 
455
    return 0;
456
}
457
 
458
static int readwrite(int fd, void* buf, long count, bool write)
459
{
460
    long sectors;
461
    long nread=0;
462
    struct filedesc* file;
463
    int rc;
464
 
465
    if (fd < 0 || fd > MAX_OPEN_FILES-1) {
466
        errno = EINVAL;
467
        return -1;
468
    }
469
 
470
    file = &openfiles[fd];
471
 
472
    if ( !file->busy ) {
473
        errno = EBADF;
474
        return -1;
475
    }
476
 
477
    if(file->attr & FAT_ATTR_DIRECTORY) {
478
        errno = EISDIR;
479
        return -1;
480
    }
481
 
482
    DEBUGF( "readwrite(%d,%lx,%ld,%s)",
483
             fd,(long)buf,count,write?"write":"read");
484
 
485
    /* attempt to read past EOF? */
486
    if (!write && count > file->size - file->fileoffset)
487
        count = file->size - file->fileoffset;
488
 
489
    /* any head bytes? */
490
    if ( file->cacheoffset != -1 ) {
491
        int offs = file->cacheoffset;
492
        int headbytes = MIN(count, SECTOR_SIZE - offs);
493
 
494
        if (write) {
495
            memcpy( file->cache + offs, buf, headbytes );
496
            file->dirty = true;
497
        }
498
        else {
499
            memcpy( buf, file->cache + offs, headbytes );
500
        }
501
 
502
        if (offs + headbytes == SECTOR_SIZE) {
503
            if (file->dirty) {
504
                rc = flush_cache(fd);
505
                if ( rc < 0 ) {
506
                    errno = EIO;
507
                    return rc * 10 - 2;
508
                }
509
            }
510
            file->cacheoffset = -1;
511
        }
512
        else {
513
            file->cacheoffset += headbytes;
514
        }
515
 
516
        nread = headbytes;
517
        count -= headbytes;
518
    }
519
 
520
    /* If the buffer has been modified, either it has been flushed already
521
     * (if (offs+headbytes == SECTOR_SIZE)...) or does not need to be (no
522
     * more data to follow in this call). Do NOT flush here. */
523
 
524
    /* read/write whole sectors right into/from the supplied buffer */
525
    sectors = count / SECTOR_SIZE;
526
    if ( sectors ) {
70 theseven 527
        if (((uint32_t)buf + nread) & (CACHEALIGN_SIZE - 1))
69 theseven 528
        {
529
            if (write) memcpy(file->cache, buf+nread, SECTOR_SIZE);
530
            rc = fat_readwrite(&(file->fatfile), sectors, file->cache, write );
531
            if (!write) memcpy(buf+nread, file->cache, SECTOR_SIZE);
532
        }
533
        else rc = fat_readwrite(&(file->fatfile), sectors, (unsigned char*)buf+nread, write );
534
        if ( rc < 0 ) {
535
            DEBUGF("Failed read/writing %ld sectors",sectors);
536
            errno = EIO;
537
            if(write && file->fatfile.eof) {
538
                DEBUGF("No space left on device");
539
                errno = ENOSPC;
540
            } else {
541
                file->fileoffset += nread;
542
            }
543
            file->cacheoffset = -1;
544
            /* adjust file size to length written */
545
            if ( write && file->fileoffset > file->size )
546
            {
547
                file->size = file->fileoffset;
548
            }
549
            return nread ? nread : rc * 10 - 4;
550
        }
551
        else {
552
            if ( rc > 0 ) {
553
                nread += rc * SECTOR_SIZE;
554
                count -= sectors * SECTOR_SIZE;
555
 
556
                /* if eof, skip tail bytes */
557
                if ( rc < sectors )
558
                    count = 0;
559
            }
560
            else {
561
                /* eof */
562
                count=0;
563
            }
564
 
565
            file->cacheoffset = -1;
566
        }
567
    }
568
 
569
    /* any tail bytes? */
570
    if ( count ) {
571
        if (write) {
572
            if ( file->fileoffset + nread < file->size ) {
573
                /* sector is only partially filled. copy-back from disk */
574
                DEBUGF("Copy-back tail cache");
575
                rc = fat_readwrite(&(file->fatfile), 1, file->cache, false );
576
                if ( rc < 0 ) {
577
                    DEBUGF("Failed writing");
578
                    errno = EIO;
579
                    file->fileoffset += nread;
580
                    file->cacheoffset = -1;
581
                    /* adjust file size to length written */
582
                    if ( file->fileoffset > file->size )
583
                    {
584
                        file->size = file->fileoffset;
585
                    }
586
                    return nread ? nread : rc * 10 - 5;
587
                }
588
                /* seek back one sector to put file position right */
589
                rc = fat_seek(&(file->fatfile), 
590
                              (file->fileoffset + nread) /
591
                              SECTOR_SIZE);
592
                if ( rc < 0 ) {
593
                    DEBUGF("fat_seek() failed");
594
                    errno = EIO;
595
                    file->fileoffset += nread;
596
                    file->cacheoffset = -1;
597
                    /* adjust file size to length written */
598
                    if ( file->fileoffset > file->size )
599
                    {
600
                        file->size = file->fileoffset;
601
                    }
602
                    return nread ? nread : rc * 10 - 6;
603
                }
604
            }
605
            memcpy( file->cache, (unsigned char*)buf + nread, count );
606
            file->dirty = true;
607
        }
608
        else {
609
            rc = fat_readwrite(&(file->fatfile), 1, file->cache,false);
610
            if (rc < 1 ) {
611
                DEBUGF("Failed caching sector");
612
                errno = EIO;
613
                file->fileoffset += nread;
614
                file->cacheoffset = -1;
615
                return nread ? nread : rc * 10 - 7;
616
            }
617
            memcpy( (unsigned char*)buf + nread, file->cache, count );
618
        }
619
 
620
        nread += count;
621
        file->cacheoffset = count;
622
    }
623
 
624
    file->fileoffset += nread;
625
    DEBUGF("fileoffset: %ld", file->fileoffset);
626
 
627
    /* adjust file size to length written */
628
    if ( write && file->fileoffset > file->size )
629
    {
630
        file->size = file->fileoffset;
631
    }
632
 
633
    return nread;
634
}
635
 
636
ssize_t write(int fd, const void* buf, size_t count)
637
{
638
    if (!openfiles[fd].write) {
639
        errno = EACCES;
640
        return -1;
641
    }
642
    return readwrite(fd, (void *)buf, count, true);
643
}
644
 
645
ssize_t read(int fd, void* buf, size_t count)
646
{
647
    return readwrite(fd, buf, count, false);
648
}
649
 
650
 
651
off_t lseek(int fd, off_t offset, int whence)
652
{
653
    off_t pos;
654
    long newsector;
655
    long oldsector;
656
    int sectoroffset;
657
    int rc;
658
    struct filedesc* file = &openfiles[fd];
659
 
660
    DEBUGF("lseek(%d,%ld,%d)",fd,offset,whence);
661
 
662
    if (fd < 0 || fd > MAX_OPEN_FILES-1) {
663
        errno = EINVAL;
664
        return -1;
665
    }
666
    if ( !file->busy ) {
667
        errno = EBADF;
668
        return -1;
669
    }
670
 
671
    switch ( whence ) {
672
        case SEEK_SET:
673
            pos = offset;
674
            break;
675
 
676
        case SEEK_CUR:
677
            pos = file->fileoffset + offset;
678
            break;
679
 
680
        case SEEK_END:
681
            pos = file->size + offset;
682
            break;
683
 
684
        default:
685
            errno = EINVAL;
686
            return -2;
687
    }
688
    if ((pos < 0) || (pos > file->size)) {
689
        errno = EINVAL;
690
        return -3;
691
    }
692
 
693
    /* new sector? */
694
    newsector = pos / SECTOR_SIZE;
695
    oldsector = file->fileoffset / SECTOR_SIZE;
696
    sectoroffset = pos % SECTOR_SIZE;
697
 
698
    if ( (newsector != oldsector) ||
699
         ((file->cacheoffset==-1) && sectoroffset) ) {
700
 
701
        if ( newsector != oldsector ) {
702
            if (file->dirty) {
703
                rc = flush_cache(fd);
704
                if (rc < 0)
705
                    return rc * 10 - 5;
706
            }
707
 
708
            rc = fat_seek(&(file->fatfile), newsector);
709
            if ( rc < 0 ) {
710
                errno = EIO;
711
                return rc * 10 - 4;
712
            }
713
        }
714
        if ( sectoroffset ) {
715
            rc = fat_readwrite(&(file->fatfile), 1, file->cache ,false);
716
            if ( rc < 0 ) {
717
                errno = EIO;
718
                return rc * 10 - 6;
719
            }
720
            file->cacheoffset = sectoroffset;
721
        }
722
        else
723
            file->cacheoffset = -1;
724
    }
725
    else
726
        if ( file->cacheoffset != -1 )
727
            file->cacheoffset = sectoroffset;
728
 
729
    file->fileoffset = pos;
730
 
731
    return pos;
732
}
733
 
734
off_t filesize(int fd)
735
{
736
    struct filedesc* file = &openfiles[fd];
737
 
738
    if (fd < 0 || fd > MAX_OPEN_FILES-1) {
739
        errno = EINVAL;
740
        return -1;
741
    }
742
    if ( !file->busy ) {
743
        errno = EBADF;
744
        return -1;
745
    }
746
 
747
    return file->size;
748
}
749
 
750
 
751
#ifdef HAVE_HOTSWAP
752
/* release all file handles on a given volume "by force", to avoid leaks */
753
int release_files(int volume)
754
{
755
    struct filedesc* pfile = openfiles;
756
    int fd;
757
    int closed = 0;
758
    for ( fd=0; fd<MAX_OPEN_FILES; fd++, pfile++)
759
    {
760
#ifdef HAVE_MULTIVOLUME
761
        if (pfile->fatfile.volume == volume)
762
#else
763
        (void)volume;
764
#endif
765
        {
766
            pfile->busy = false; /* mark as available, no further action */
767
            closed++;
768
        }
769
    }
770
    return closed; /* return how many we did */
771
}
772
#endif /* #ifdef HAVE_HOTSWAP */