-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsd_card.c
1602 lines (1361 loc) · 47 KB
/
sd_card.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* File: sd_card.c
* Author: Peter Thornton
* Purpose: Functions to interface with SD card on Pumpkin DB / MBM
* SPI interface and file I/O based on Chapters 13-14 in
* Di Jasio, "Learning to fly the PIC24"
* Created on: 15 May 2020
*/
#include "xc.h"
#include "clock.h"
#include "spi.h"
#include "datetime.h"
#include "sd_card.h"
#include <stdlib.h> // malloc...
#include <ctype.h> // toupper...
#include <string.h> // memcpy...
//-------------------------------------------------------------
// Master Boot Record key fields offsets
#define FO_MBR 0L // master boot record sector LBA
#define FO_FIRST_P 0x1BE // offset of first partition table
#define FO_FIRST_TYPE 0x1C2 // offset of first partition type
#define FO_FIRST_SECT 0x1C6 // first sector of first partition
#define FO_FIRST_SIZE 0x1CA // number of sectors in partition
#define FO_SIGN 0x1FE // MBR signature location (55,AA)
#define FAT_EOF 0xffff // last cluster in a file
#define FAT_MCLST 0xfff8 // max cluster value in a fat
// Partition Boot Record key fields offsets
#define BR_SXC 0xd // (byte) sector per cluster
#define BR_RES 0xe // (word) res sectors boot record
#define BR_FAT_SIZE 0x16 // (word) FAT size sectors
#define BR_FAT_CPY 0x10 // (byte) number of FAT copies
#define BR_MAX_ROOT 0x11 // (odd word) max entries root dir
// directory entry management
#define DIR_ESIZE 32 // size of a directory entry(bytes)
#define DIR_NAME 0 // offset file name
#define DIR_EXT 8 // offset file extension
#define DIR_ATTRIB 11 // offset attribute( 00ARSHDV)
#define DIR_CTIME 14 // creation time
#define DIR_CDATE 16 // creation date
#define DIR_ADATE 18 // last access date
#define DIR_TIME 22 // offset last use time (word)
#define DIR_DATE 24 // offset last use date (word)
#define DIR_CLST 26 // offset first cluster FAT (word)
#define DIR_SIZE 28 // offset of file size (dword)
#define DIR_DEL 0xE5 // marker deleted entry
#define DIR_EMPTY 0 // marker last entry in directory
// global definitions
char FError; // error mail box
MEDIA *D; // mounting info for storage device
// SD card commands
#define RESET 0 // aka GO_IDLE (CMD0)
#define INIT 1 // aka SEND_OP_COND (CMD1)
#define READ_SINGLE 17 // read a block of data
#define WRITE_SINGLE 24 // write a block of data
// SD card return values
#define DATA_START 0xfe // indicates card is ready for reading
#define DATA_ACCEPT 0x05 // indicates card has accepted a written data block
// function to send a 6-byte command to the SD card via SPI
int SendSDCmd(int c, LBA a, int crc)
{
int i,r;
// Enable SD card, via SS (active low). Clocking one byte after selecting gives time for the
// device to recognize SS signal, and maybe also time for the level translators
// to stabilize.
CS_SD = 0;
write_spi1(0xff);
// send the 6-byte command packet
write_spi1(c | 0x40); // send command plus frame bit (bit 6)
write_spi1(a>>24); // MSB of the address
write_spi1(a>>16);
write_spi1(a>>8);
write_spi1(a); // LSB of address
write_spi1(crc | 0x01); // CRC (for CMD0 and CMD8, other commands don't care)
// wait for a response (up to 8 bytes delay)
// device returns 0xff (keeps the line high) until it provides a proper
// response code
i = 9;
do {
r = write_spi1(0xff);
if (r != 0xff) break;
} while (--i > 0);
return (r);
/* return responses:
0xff = timeout, no answer
0x00 = command accepted
0x01 = command received, in idle state (proper response for RESET)
other values indicate errors
*/
}
// Initialize the SD card. There are multiple steps, several of which can
// generate errors. The return value indicates card ready, or which step
// is returning an error. Slot is powered on return if successful, unpowered otherwise.
// Return Indicates
// ------ ---------
// 0x00 No errors, card ready for use
// 0x03 CMD0 error (Reset)
// 0x04 CMD8 error: old version
// 0x05 CMD8 error: wrong voltage or incorrect test pattern
// 0x06 CMD58 error (check OCR)
// 0x08 CMD55 error (ACMD next)
// 0x09 ACMD41 error (test idle)
// 0x0a CMD58 error (check OCR)
// 0x0b CMD58 error: high capacity card (not supported by RamSat code)
// 0xff Timeout error: exceeded the count limit for CMD55+ACMD41 sequence
int SD_init(void)
{
int i,r;
int c8_1, c8_2, c8_3, c8_4;
int c58_1, c58_2, c58_3, c58_4;
// 0. During initialization, lower SPI speed to 250 kHz
SPI1STATbits.SPIEN = 0; // temporarily disable the peripheral
SPI1CON1bits.SPRE = 0b111; // pre2 = 1:1
SPI1CON1bits.PPRE = 0b00; // pre1 = 64:1
SPI1STATbits.SPIROV = 0; // clear overflow buffer
SPI1STATbits.SPIEN = 1; // re-enable the peripheral
// 1. power up the SD slot (-ON_SD, active low), and wait one second.
_RE4 = 0;
TMR1 = 0;
while (TMR1 < 1000L * TMR1MSEC);
// 2. send 80 clock cycles, required to begin device initialization.
// Guidance from others is to have the device de-selected during this
// step. However, due to the use of SD_SS as the signal to power on the level
// translators between PIC and SD card (active low), with SDSS de-selected
// the following clock pulses don't get to the device, and the initialization stalls.
// Testing shows that selecting the device (which also powers the level translators)
// does not interfere with the needed clocking cycles, and the card initializes
// without error.
CS_SD = 0;
for (i=0 ; i<10 ; i++)
write_spi1(0xff);
// 3. send CMD0 (RESET) to enter SPI mode
// NB: the SendSDCmd() routines leaves the CS_SD=0 to allow further reads.
// Setting high and clocking in one more dummy byte via write_spi1() is the
// correct way to disable the SD card after SendSDCmd().
r = SendSDCmd(0, 0, 0x94);
CS_SD = 1; write_spi1(0xff);
if (r != 1)
{
_RE4 = 1; // turn off power to SD card
return 0x03;
}
// 4. send CMD8 to check version (1 or 2)
r = SendSDCmd(8, 0x1aa, 0x86);
if (r > 1)
{
CS_SD = 1; write_spi1(0xff);
_RE4 = 1;
return 0x04;
}
// 5. CMD8 recognized if r = 0 or 1. So it's a v2.0 card. Read the next
// four bytes of the response (it's an R7 5-byte response if v2)
c8_1 = write_spi1(0xff); // should be 0x00
c8_2 = write_spi1(0xff); // should be 0x00
c8_3 = write_spi1(0xff); // should be 0x01
c8_4 = write_spi1(0xff); // should be 0xaa (test pattern)
CS_SD = 1; write_spi1(0xff);
if (c8_3 != 1 || c8_4 != 0xaa)
{
_RE4 = 1;
return 0x05;
}
// 6. CMD58, check OCR (operation condition register)
r = SendSDCmd(58, 0, 0);
if (r > 1)
{
CS_SD = 1; write_spi1(0xff);
_RE4 = 1;
return 0x06;
}
// 7. CMD58 recognized, no error flags. Read the next 4 bytes
// as an R3 response
c58_1 = write_spi1(0xff);
c58_2 = write_spi1(0xff);
c58_3 = write_spi1(0xff);
c58_4 = write_spi1(0xff);
CS_SD = 1; write_spi1(0xff);
// 8-9. repeatedly send CMD55 + ACMD41, until ACMD41 returns 0 (exit IDLE state)
i = 10000; // allow for up to 1s before timeout
do {
// send CMD55, which enables ACMD. Check for errors
r = SendSDCmd(55, 0, 0);
CS_SD = 1; write_spi1(0xff);
if (r > 1)
{
_RE4 = 1;
return 0x08;
}
// send ACMD41, and check for errors
r = SendSDCmd(41, 0, 0);
CS_SD = 1; write_spi1(0xff);
if (r > 1)
{
_RE4 = 1;
return 0x09;
}
// check if exited idle state (return value 0)
if (!r) break; // card is ready!
} while (--i > 0);
// timeout indicator - card not ready
if (i == 0)
{
_RE4 = 1;
return 0xff;
}
// 10. Send CMD58, to see if this is an SD, or SDHC card
r = SendSDCmd(58, 0, 0);
if (r > 0)
{
CS_SD = 1; write_spi1(0xff);
_RE4 = 1;
return 0x0a;
}
// 11. CMD58 recognized, no error flags. Read the next 4 bytes as an R3 response
c58_1 = write_spi1(0xff);
c58_2 = write_spi1(0xff);
c58_3 = write_spi1(0xff);
c58_4 = write_spi1(0xff);
CS_SD = 1; write_spi1(0xff);
if (c58_1 != 0x80) // high capacity card - not supported
{
_RE4 = 1;
return 0x0b;
}
// 12. Initialization complete, can now increase SPI speed to 4MHz
SPI1STATbits.SPIEN = 0; // temporarily disable the peripheral
SPI1CON1bits.SPRE = 0b111; // pre2 = 1:1
SPI1CON1bits.PPRE = 0b10; // pre1 = 4:1
SPI1STATbits.SPIEN = 1; // re-enable the peripheral
return 0; // return value 0 indicates card is ready and slot is powered
}
// read a single 512-byte sector at a given LBA (logic block address)
int SD_read_sector(LBA a, unsigned char *p)
{
unsigned int i;
int r;
// The a<<9 converts LBA to byte value (multiplies by 512)
r = SendSDCmd(READ_SINGLE, (a<<9), 0);
if (r == 0) // command accepted
{
// wait for a response
i=60000;
do {
r=write_spi1(0xff);
if (r == DATA_START) break;
} while (--i > 0);
// if the response loop did not timeout, read 512-byte sector
if (i)
{
for (i=0 ; i<512 ; i++)
*p++ = write_spi1(0xff);
// ignore 16-bit CRC value
write_spi1(0xff);
write_spi1(0xff);
} // data arrived
} //command accepted
// de-select device
CS_SD = 1; write_spi1(0xff);
return (r == DATA_START); // return true if successful
}
// write a single 512-byte sector to a given LBA (logic block address)
int SD_write_sector(LBA a, unsigned char *p)
{
unsigned int r,i;
r = SendSDCmd(WRITE_SINGLE, (a<<9), 0);
if (r == 0) // command accepted
{
write_spi1(DATA_START);
// write sector
for (i=0 ; i<512 ; i++)
write_spi1(*p++);
// send dummy CRC
write_spi1(0xff);
write_spi1(0xff);
// check if data accepted
if ((r = write_spi1(0xff) & 0xf) == DATA_ACCEPT)
{
for (i=65000 ; i>0 ; i--)
{ // wait for end of write operation (SDO goes high)
if ((r = write_spi1(0xff)))
break;
}
} // data block accepted
else
r = 0x0a; // failed to receive data accept response
} // command accepted
CS_SD = 1; write_spi1(0xff);
return r; // returns TRUE if successful
}
//-------------------------------------------------------------
// mount initializes a MEDIA structure for file IO access
//
// will mount only the first partition on the disk/card
MEDIA * SD_mount( void)
{
LBA psize; // number of sectors in partition
LBA firsts; // first sector inside the first partition
int i;
unsigned char *buffer;
// 2. initialize the card
if ( SD_init())
{
// Note that more error info could be returned from SD_init(), if desired
FError = FE_CANNOT_INIT;
return NULL;
}
// 3. allocate space for a MEDIA structure
D = (MEDIA *) malloc( sizeof( MEDIA));
if ( D == NULL) // report an error
{
FError = FE_MALLOC_FAILED;
return NULL;
}
// 4. allocate space for a temp sector buffer
buffer = ( unsigned char *) malloc( 512);
if ( buffer == NULL) // report an error
{
FError = FE_MALLOC_FAILED;
free( D);
return NULL;
}
// 5. get the Master Boot Record
if ( !SD_read_sector( FO_MBR, buffer))
{
FError = FE_CANNOT_READ_MBR;
free( D); free( buffer);
return NULL;
}
// 6. check if the MBR sector is valid
// verify the signature word
if (( buffer[ FO_SIGN] != 0x55) ||
( buffer[ FO_SIGN +1] != 0xAA))
{
FError = FE_INVALID_MBR;
free( D); free( buffer);
return NULL;
}
// Valid Master Boot Record Loaded
// 7. read the number of sectors in partition
psize = ReadL( buffer, FO_FIRST_SIZE);
// 8. check if the partition type is acceptable
i = buffer[ FO_FIRST_TYPE];
switch ( i)
{
case 0x04:
case 0x06:
case 0x0E:
// valid FAT16 options
break;
default:
FError = FE_PARTITION_TYPE;
free( D); free( buffer);
return NULL;
} // switch
// 9. get the first partition first sector -> Boot Record
// get the 32 bit offset to the first partition
firsts = ReadL( buffer, FO_FIRST_SECT);
// assuming FO_MBR == 0
// 10. get the sector loaded (boot record)
if ( !SD_read_sector( firsts, buffer))
{
free( D); free( buffer);
return NULL;
}
// 11. check if the boot record is valid
// verify the signature word
if (( buffer[ FO_SIGN] != 0x55) ||
( buffer[ FO_SIGN +1] != 0xAA))
{
FError = FE_INVALID_BR;
free( D); free( buffer);
return NULL;
}
// Valid Partition Boot Record Loaded
// get the full partition/drive layout
// 12. determine the size of a cluster
D->sxc = buffer[ BR_SXC];
// this will also act as flag that the disk is mounted
// 13. determine fat, root and data LBAs
// FAT = first sector in partition
// (boot record) + reserved records
D->fat = firsts + ReadW( buffer, BR_RES);
D->fatsize = ReadW( buffer, BR_FAT_SIZE);
D->fatcopy = buffer[ BR_FAT_CPY];
// 14. ROOT = FAT + (sectors per FAT * copies of FAT)
D->root = D->fat + ( D->fatsize * D->fatcopy);
// 15. MAX ROOT is the maximum number of entries
// in the root directory
D->maxroot = ReadOddW( buffer, BR_MAX_ROOT) ;
// 16. DATA = ROOT + (MAXIMUM ROOT *32 / 512)
D->data = D->root + ( D->maxroot >> 4);
// assuming maxroot % 16 == 0!!!
// 17. max clusters in this partition
// = (tot sectors - sys sectors )/sxc
D->maxcls = (psize - (D->data - firsts)) / D->sxc;
// 18. free the temporary buffer
free( buffer);
return D;
} // mount
//-------------------------------------------------------------
// umount de-initializes a MEDIA structure for file IO access
// also switch off power to the SD card slot
//
void SD_umount( void)
{
free( D);
D = NULL;
_RE4 = 1;
} // umount
//-------------------------------------------------------------
// Open File on the default storage device D
//
MFILE *fopenM( const char *filename, const char *mode)
{
char c;
int i, r, e;
unsigned short date, time;
unsigned char *b;
MFILE *fp;
// 1. check if storage device is mounted
if ( D == NULL) // unmounted
{
FError = FE_MEDIA_NOT_MNTD;
return NULL;
}
// 2. allocate a buffer for the file
b = (unsigned char*)malloc( 512);
if ( b == NULL)
{
FError = FE_MALLOC_FAILED;
return NULL;
}
// 3. allocate a MFILE structure on the heap
fp = (MFILE *) malloc( sizeof( MFILE));
if ( fp == NULL) // report an error
{
FError = FE_MALLOC_FAILED;
free( b);
return NULL;
}
// 4. set pointers to the MEDIA structure and buffer
fp->mda = D;
fp->buffer = b;
// 5. format the filename into name
for( i=0; i<8; i++)
{
// read a char and convert to upper case
c = toupper( *filename++);
// extension or short name no-extension
if (( c == '.') || ( c == '\0'))
break;
else
fp->name[i] = c;
} // for
// if short fill the rest up to 8 with spaces
while ( i<8) fp->name[i++] = ' ';
// 6. if there is an extension
if ( c != '\0')
{
for( i=8; i<11; i++)
{
// read a char and convert to upper case
c = toupper( *filename++);
if ( c == '.')
c = toupper( *filename++);
if ( c == '\0') // short extension
break;
else
fp->name[i] = c;
} // for
// if short fill the rest up to 3 with spaces
while ( i<11) fp->name[i++] = ' ';
} // if
// 7. copy the file mode character (r, w)
if ((*mode == 'r')||(*mode == 'w'))
fp->mode = *mode;
else
{
FError = FE_INVALID_MODE;
goto ExitOpen;
}
// 8. Search for the file in current directory
if ( ( r = FindDIR( fp)) == FAIL)
{
FError = FE_FIND_ERROR;
goto ExitOpen;
}
// 9. init all counters to the beginning of the file
fp->seek = 0; // first byte in file
fp->sec = 0; // first sector in the cluster
fp->pos = 0; // first byte in sector/cluster
// 10. depending on the mode (read or write)
if ( fp->mode == 'r')
{ // 10.1 'r' open for reading
if ( r == NOT_FOUND)
{
FError = FE_FILE_NOT_FOUND;
goto ExitOpen;
}
else
{ // found
// 10.2 set current cluster pointer on first cluster
fp->ccls = fp->cluster;
// 10.3 read a sector of data from the file
if ( !ReadDATA( fp))
{
goto ExitOpen;
}
// 10.4 determine how much data is really inside buffer
if ( fp->size-fp->seek < 512)
fp->top = fp->size - fp->seek;
else
fp->top = 512;
} // found
} // 'r'
else // 11. open for 'write'
{
if ( r == NOT_FOUND)
{
// 11.1 allocate a first cluster to it
fp->ccls = 0; // indicate brand new file
if ( NewFAT( fp) != TRUE)
{ // must be media full
FError = FE_MEDIA_FULL;
goto ExitOpen;
}
fp->cluster = fp->ccls;
// 11.2 create a new entry
// search again, for an empty entry this time
if ( (r = NewDIR( fp)) == FAIL)
{ // report any error
FError = FE_IDE_ERROR;
goto ExitOpen;
}
// 11.3 new entry not found
if ( r == NOT_FOUND)
{
FError = FE_DIR_FULL;
goto ExitOpen;
}
else // 11.4 new entry identified fp->entry filled
{
// 11.4.1
fp->size = 0;
// 11.4.2 determine offset in DIR sector
e = (fp->entry & 0xf) * DIR_ESIZE;
// 11.4.3 init all fields to 0
for (i=0; i<32; i++)
fp->buffer[ e + i] = 0;
// 11.4.4 set date and time
// read the RTC to get the current date and time in FAT 16-bit format
get_fatdatetime(&date, &time);
fp->date = date;
fp->buffer[ e + DIR_CDATE] = fp->date;
fp->buffer[ e + DIR_CDATE+1]= fp->date>>8;
fp->buffer[ e + DIR_DATE] = fp->date;
fp->buffer[ e + DIR_DATE+1]= fp->date>>8;
fp->time = time;
fp->buffer[ e + DIR_CTIME] = fp->time;
fp->buffer[ e + DIR_CTIME+1]= fp->time>>8;
fp->buffer[ e + DIR_TIME] = fp->time+1;
fp->buffer[ e + DIR_TIME+1]= fp->time>>8;
// 11.4.5 set first cluster
fp->buffer[ e + DIR_CLST] = fp->cluster;
fp->buffer[ e + DIR_CLST+1]= (fp->cluster>>8);
// 11.4.6 set name
for ( i = 0; i<DIR_ATTRIB; i++)
fp->buffer[ e + i] = fp->name[i];
// 11.4.7 set attrib
fp->buffer[ e + DIR_ATTRIB] = ATT_ARC;
// 11.4.8 update the directory sector;
if ( !WriteDIR( fp, fp->entry))
{
FError = FE_IDE_ERROR;
goto ExitOpen;
}
} // new entry
} // not found
else // file exist already, report error
{
FError = FE_FILE_OVERWRITE;
goto ExitOpen;
}
} // w request
// 12. Exit with success
return fp;
// 13. Exit with error
ExitOpen:
free( fp->buffer);
free( fp);
return NULL;
} // fopenM
//-------------------------------------------------------------
// Delete existing file on the default storage device D
//
int fdeleteM( const char *filename, const char *mode)
{
char c;
int i, r;
unsigned e;
unsigned short cur_cluster, next_cluster;
unsigned char *b;
MFILE *fp;
// check if storage device is mounted
if ( D == NULL) // unmounted
{
FError = FE_MEDIA_NOT_MNTD;
return FError;
}
// allocate a buffer for the file
b = (unsigned char*)malloc( 512);
if ( b == NULL)
{
FError = FE_MALLOC_FAILED;
return FError;
}
// allocate a MFILE structure on the heap
fp = (MFILE *) malloc( sizeof( MFILE));
if ( fp == NULL) // report an error
{
FError = FE_MALLOC_FAILED;
free( b);
return FError;
}
// set pointers to the MEDIA structure and buffer
fp->mda = D;
fp->buffer = b;
// format the filename into name
for( i=0; i<8; i++)
{
// read a char and convert to upper case
c = toupper( *filename++);
// extension or short name no-extension
if (( c == '.') || ( c == '\0'))
break;
else
fp->name[i] = c;
} // for
// if short fill the rest up to 8 with spaces
while ( i<8) fp->name[i++] = ' ';
// if there is an extension
if ( c != '\0')
{
for( i=8; i<11; i++)
{
// read a char and convert to upper case
c = toupper( *filename++);
if ( c == '.')
c = toupper( *filename++);
if ( c == '\0') // short extension
break;
else
fp->name[i] = c;
} // for
// if short fill the rest up to 3 with spaces
while ( i<11) fp->name[i++] = ' ';
} // if
// copy the file mode character (d for delete)
if (*mode == 'd')
fp->mode = *mode;
else
{
FError = FE_INVALID_MODE;
goto ExitDelete;
}
// Search for the file in current directory
if ( ( r = FindDIR( fp)) == FAIL)
{
FError = FE_FIND_ERROR;
goto ExitDelete;
}
// found or not found
if ( r == NOT_FOUND)
{
FError = FE_FILE_NOT_FOUND;
goto ExitDelete;
}
else
{ // found
// set current cluster pointer on first cluster
fp->ccls = fp->cluster;
// at this point, fp->buffer holds the root directory sector containing
// the target file. Modify the first character of filename with the
// "deleted file" flag value, and write the entire sector back to root dir.
// First determine the offset in current buffer
e = (fp->entry&0xf) * DIR_ESIZE;
// Then write the deleted flag to first char of file name
fp->buffer[ e + DIR_NAME] = DIR_DEL;
// Now write the modified buffer back to root dir sector
if ( !WriteDIR( fp, fp->entry))
{
FError = FE_IDE_ERROR;
goto ExitDelete;
}
// Begin traverse of FAT clusters, clearing entries for this file
// (in all FAT copies)
cur_cluster = fp->cluster;
while (1)
{
next_cluster = ReadFAT(fp, cur_cluster);
if (!WriteFAT(fp, cur_cluster, 0))
{
FError = FE_WFAT_ERROR;
goto ExitDelete;
}
// advance if this is not the end of the cluster chain
if (next_cluster != FAT_EOF)
{
cur_cluster = next_cluster;
}
else // free memory and return success
{
free( fp->buffer);
free( fp);
return 0;
}
}
} // found
// Exit with error
ExitDelete:
free( fp->buffer);
free( fp);
return FError;
} // fdeleteM
//-------------------------------------------------------------
// Read File
//
// returns number of bytes actually transferred
//
unsigned freadM( void * dest, unsigned size, MFILE *fp)
// fp pointer to MFILE structure
// dest pointer to destination buffer
// count number of bytes to transfer
// returns number of bytes actually transferred
{
MEDIA * mda = fp->mda;
unsigned count=size; // counts bytes to be transfer
unsigned len;
// 1. check if fp points to a valid open file structure
if (( fp->mode != 'r'))
{ // invalid file or not open in read mode
FError = FE_INVALID_FILE;
return 0;
}
// 2. loop to transfer the data
while ( count>0)
{
// 2.1 check if EOF reached
if ( fp->seek >= fp->size)
{
FError = FE_EOF; // reached the end
break;
}
// 2.2 load a new sector if necessary
if (fp->pos == fp->top)
{
fp->pos = 0;
fp->sec++;
// 2.2.1 get a new cluster if necessary
if ( fp->sec == mda->sxc)
{
fp->sec = 0;
if ( !NextFAT( fp, 1))
break;
}
// 2.2.2 load a sector of data
TMR1 = 0;
while(TMR1 < 100*TMR1MSEC);
if ( !ReadDATA( fp))
break;
// 2.2.3 determine how much data is inside buffer
if ( fp->size-fp->seek < 512)
fp->top = fp->size - fp->seek;
else
fp->top = 512;
} // load new sector
// 2.3 copy as many bytes as possible in a single chunk
// take as much as fits in the current sector
if ( fp->pos+count < fp->top)
// fits all in current sector
len = count;
else
// take a first chunk, there is more
len = fp->top - fp->pos;
memcpy( dest, fp->buffer + fp->pos, len);
// 2.4 update all counters and pointers
count-= len; // compute what is left
dest += len; // advance destination pointer
fp->pos += len; // advance pointer in sector
fp->seek += len; // advance the seek pointer
} // while count
// 3. return number of bytes actually transferred
return size-count;
} // freadM
//-------------------------------------------------------------
// Write data to a File
//
unsigned fwriteM( void *src, unsigned count, MFILE * fp)
// src points to source data (buffer)
// count number of bytes to write
// returns number of bytes actually written
{
MEDIA *mda = fp->mda;
unsigned len, size = count;
// 1. check if file is open
if ( fp->mode != 'w')
{ // file not valid or not open for writing
FError = FE_INVALID_FILE;
return FAIL;
}
// 2. loop writing count bytes
while ( count>0)
{
// 2.1 copy as many bytes at a time as possible
if ( fp->pos+count < 512)
len = count;
else
len = 512- fp->pos ;
memcpy( fp->buffer+ fp->pos, src, len);
// 2.2 update all pointers and counters
fp->pos+=len; // advance buffer position
fp->seek+=len; // count the added bytes
count-=len; // update the counter
src+=len; // advance the source pointer
// 2.3 update the file size too
if (fp->seek > fp->size)
fp->size = fp->seek;
// 2.4 if buffer full, write buffer to current sector
if (fp->pos == 512)
{
// 2.4.1 write buffer full of data
if ( !WriteDATA( fp))
return FAIL;
// 2.4.2 advance to next sector in cluster
fp->pos = 0;
fp->sec++;
// 2.4.3 get a new cluster if necessary
if ( fp->sec == mda->sxc)
{
fp->sec = 0;
if ( NewFAT( fp)== FAIL)
return FAIL;
}
} // store sector
} // while count
// 3. number of bytes actually written
return size-count;
} // fwriteM
//-------------------------------------------------------------
// Close a File
//
unsigned fcloseM( MFILE *fp)
{
unsigned e, r;
r = FAIL;
// 1. check if it was open for write
if ( fp->mode == 'w')
{
// 1.1 if the current buffer contains data, flush it
if ( fp->pos >0)
{
if ( !WriteDATA( fp))
goto ExitClose;
}
// 1.2 finally update the dir entry,
// 1.2.1 retrive the dir sector
if ( !ReadDIR( fp, fp->entry))
goto ExitClose;