Subversion Repositories freemyipod

Rev

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;
120 theseven 461
    long i;
69 theseven 462
    long nread=0;
463
    struct filedesc* file;
120 theseven 464
    int rc, rc2;
69 theseven 465
 
466
    if (fd < 0 || fd > MAX_OPEN_FILES-1) {
467
        errno = EINVAL;
468
        return -1;
469
    }
470
 
471
    file = &openfiles[fd];
472
 
473
    if ( !file->busy ) {
474
        errno = EBADF;
475
        return -1;
476
    }
477
 
478
    if(file->attr & FAT_ATTR_DIRECTORY) {
479
        errno = EISDIR;
480
        return -1;
481
    }
482
 
483
    DEBUGF( "readwrite(%d,%lx,%ld,%s)",
484
             fd,(long)buf,count,write?"write":"read");
485
 
486
    /* attempt to read past EOF? */
487
    if (!write && count > file->size - file->fileoffset)
488
        count = file->size - file->fileoffset;
489
 
490
    /* any head bytes? */
491
    if ( file->cacheoffset != -1 ) {
492
        int offs = file->cacheoffset;
493
        int headbytes = MIN(count, SECTOR_SIZE - offs);
494
 
495
        if (write) {
496
            memcpy( file->cache + offs, buf, headbytes );
497
            file->dirty = true;
498
        }
499
        else {
500
            memcpy( buf, file->cache + offs, headbytes );
501
        }
502
 
503
        if (offs + headbytes == SECTOR_SIZE) {
504
            if (file->dirty) {
505
                rc = flush_cache(fd);
506
                if ( rc < 0 ) {
507
                    errno = EIO;
508
                    return rc * 10 - 2;
509
                }
510
            }
511
            file->cacheoffset = -1;
512
        }
513
        else {
514
            file->cacheoffset += headbytes;
515
        }
516
 
517
        nread = headbytes;
518
        count -= headbytes;
519
    }
520
 
521
    /* If the buffer has been modified, either it has been flushed already
522
     * (if (offs+headbytes == SECTOR_SIZE)...) or does not need to be (no
523
     * more data to follow in this call). Do NOT flush here. */
524
 
525
    /* read/write whole sectors right into/from the supplied buffer */
526
    sectors = count / SECTOR_SIZE;
120 theseven 527
    rc = 0;
69 theseven 528
    if ( sectors ) {
70 theseven 529
        if (((uint32_t)buf + nread) & (CACHEALIGN_SIZE - 1))
120 theseven 530
            for (i = 0; i < sectors; i++)
531
            {
532
                if (write) memcpy(file->cache, buf+nread+i*SECTOR_SIZE, SECTOR_SIZE);
533
                rc2 = fat_readwrite(&(file->fatfile), 1, file->cache, write );
534
                if (rc2 < 0)
535
                {
536
                    rc = rc2;
537
                    break;
538
                }
539
                else rc += rc2;
540
                if (!write) memcpy(buf+nread+i*SECTOR_SIZE, file->cache, SECTOR_SIZE);
541
            }
69 theseven 542
        else rc = fat_readwrite(&(file->fatfile), sectors, (unsigned char*)buf+nread, write );
543
        if ( rc < 0 ) {
544
            DEBUGF("Failed read/writing %ld sectors",sectors);
545
            errno = EIO;
546
            if(write && file->fatfile.eof) {
547
                DEBUGF("No space left on device");
548
                errno = ENOSPC;
549
            } else {
550
                file->fileoffset += nread;
551
            }
552
            file->cacheoffset = -1;
553
            /* adjust file size to length written */
554
            if ( write && file->fileoffset > file->size )
555
            {
556
                file->size = file->fileoffset;
557
            }
558
            return nread ? nread : rc * 10 - 4;
559
        }
560
        else {
561
            if ( rc > 0 ) {
562
                nread += rc * SECTOR_SIZE;
563
                count -= sectors * SECTOR_SIZE;
564
 
565
                /* if eof, skip tail bytes */
566
                if ( rc < sectors )
567
                    count = 0;
568
            }
569
            else {
570
                /* eof */
571
                count=0;
572
            }
573
 
574
            file->cacheoffset = -1;
575
        }
576
    }
577
 
578
    /* any tail bytes? */
579
    if ( count ) {
580
        if (write) {
581
            if ( file->fileoffset + nread < file->size ) {
582
                /* sector is only partially filled. copy-back from disk */
583
                DEBUGF("Copy-back tail cache");
584
                rc = fat_readwrite(&(file->fatfile), 1, file->cache, false );
585
                if ( rc < 0 ) {
586
                    DEBUGF("Failed writing");
587
                    errno = EIO;
588
                    file->fileoffset += nread;
589
                    file->cacheoffset = -1;
590
                    /* adjust file size to length written */
591
                    if ( file->fileoffset > file->size )
592
                    {
593
                        file->size = file->fileoffset;
594
                    }
595
                    return nread ? nread : rc * 10 - 5;
596
                }
597
                /* seek back one sector to put file position right */
598
                rc = fat_seek(&(file->fatfile), 
599
                              (file->fileoffset + nread) /
600
                              SECTOR_SIZE);
601
                if ( rc < 0 ) {
602
                    DEBUGF("fat_seek() failed");
603
                    errno = EIO;
604
                    file->fileoffset += nread;
605
                    file->cacheoffset = -1;
606
                    /* adjust file size to length written */
607
                    if ( file->fileoffset > file->size )
608
                    {
609
                        file->size = file->fileoffset;
610
                    }
611
                    return nread ? nread : rc * 10 - 6;
612
                }
613
            }
614
            memcpy( file->cache, (unsigned char*)buf + nread, count );
615
            file->dirty = true;
616
        }
617
        else {
618
            rc = fat_readwrite(&(file->fatfile), 1, file->cache,false);
619
            if (rc < 1 ) {
620
                DEBUGF("Failed caching sector");
621
                errno = EIO;
622
                file->fileoffset += nread;
623
                file->cacheoffset = -1;
624
                return nread ? nread : rc * 10 - 7;
625
            }
626
            memcpy( (unsigned char*)buf + nread, file->cache, count );
627
        }
628
 
629
        nread += count;
630
        file->cacheoffset = count;
631
    }
632
 
633
    file->fileoffset += nread;
634
    DEBUGF("fileoffset: %ld", file->fileoffset);
635
 
636
    /* adjust file size to length written */
637
    if ( write && file->fileoffset > file->size )
638
    {
639
        file->size = file->fileoffset;
640
    }
641
 
642
    return nread;
643
}
644
 
645
ssize_t write(int fd, const void* buf, size_t count)
646
{
647
    if (!openfiles[fd].write) {
648
        errno = EACCES;
649
        return -1;
650
    }
651
    return readwrite(fd, (void *)buf, count, true);
652
}
653
 
654
ssize_t read(int fd, void* buf, size_t count)
655
{
656
    return readwrite(fd, buf, count, false);
657
}
658
 
659
 
660
off_t lseek(int fd, off_t offset, int whence)
661
{
662
    off_t pos;
663
    long newsector;
664
    long oldsector;
665
    int sectoroffset;
666
    int rc;
667
    struct filedesc* file = &openfiles[fd];
668
 
669
    DEBUGF("lseek(%d,%ld,%d)",fd,offset,whence);
670
 
671
    if (fd < 0 || fd > MAX_OPEN_FILES-1) {
672
        errno = EINVAL;
673
        return -1;
674
    }
675
    if ( !file->busy ) {
676
        errno = EBADF;
677
        return -1;
678
    }
679
 
680
    switch ( whence ) {
681
        case SEEK_SET:
682
            pos = offset;
683
            break;
684
 
685
        case SEEK_CUR:
686
            pos = file->fileoffset + offset;
687
            break;
688
 
689
        case SEEK_END:
690
            pos = file->size + offset;
691
            break;
692
 
693
        default:
694
            errno = EINVAL;
695
            return -2;
696
    }
697
    if ((pos < 0) || (pos > file->size)) {
698
        errno = EINVAL;
699
        return -3;
700
    }
701
 
702
    /* new sector? */
703
    newsector = pos / SECTOR_SIZE;
704
    oldsector = file->fileoffset / SECTOR_SIZE;
705
    sectoroffset = pos % SECTOR_SIZE;
706
 
707
    if ( (newsector != oldsector) ||
708
         ((file->cacheoffset==-1) && sectoroffset) ) {
709
 
710
        if ( newsector != oldsector ) {
711
            if (file->dirty) {
712
                rc = flush_cache(fd);
713
                if (rc < 0)
714
                    return rc * 10 - 5;
715
            }
716
 
717
            rc = fat_seek(&(file->fatfile), newsector);
718
            if ( rc < 0 ) {
719
                errno = EIO;
720
                return rc * 10 - 4;
721
            }
722
        }
723
        if ( sectoroffset ) {
724
            rc = fat_readwrite(&(file->fatfile), 1, file->cache ,false);
725
            if ( rc < 0 ) {
726
                errno = EIO;
727
                return rc * 10 - 6;
728
            }
729
            file->cacheoffset = sectoroffset;
730
        }
731
        else
732
            file->cacheoffset = -1;
733
    }
734
    else
735
        if ( file->cacheoffset != -1 )
736
            file->cacheoffset = sectoroffset;
737
 
738
    file->fileoffset = pos;
739
 
740
    return pos;
741
}
742
 
743
off_t filesize(int fd)
744
{
745
    struct filedesc* file = &openfiles[fd];
746
 
747
    if (fd < 0 || fd > MAX_OPEN_FILES-1) {
748
        errno = EINVAL;
749
        return -1;
750
    }
751
    if ( !file->busy ) {
752
        errno = EBADF;
753
        return -1;
754
    }
755
 
756
    return file->size;
757
}
758
 
759
 
760
#ifdef HAVE_HOTSWAP
761
/* release all file handles on a given volume "by force", to avoid leaks */
762
int release_files(int volume)
763
{
764
    struct filedesc* pfile = openfiles;
765
    int fd;
766
    int closed = 0;
767
    for ( fd=0; fd<MAX_OPEN_FILES; fd++, pfile++)
768
    {
769
#ifdef HAVE_MULTIVOLUME
770
        if (pfile->fatfile.volume == volume)
771
#else
772
        (void)volume;
773
#endif
774
        {
775
            pfile->busy = false; /* mark as available, no further action */
776
            closed++;
777
        }
778
    }
779
    return closed; /* return how many we did */
780
}
781
#endif /* #ifdef HAVE_HOTSWAP */