Home
µC/FS User`s Manual
Contents
1. Section Functions begin with General file system functions FS POXIX API functions fs_ Device functions FSDev_ Directory functions FSDir_ Entry functions FSEntry_ File functions FSFile_ Time functions FSTime_ Volume functions FSVol_ RAMDisk driver functions FSDev_RAM_ NAND driver functions FS_NAND SD MMC driver functions FSDev_SD_ NAND driver functions FSDev_NAND_ NOR driver functions FSDev_NOR_ MSC driver functions FSDev_MSC_ FAT functions FS_FAT_ BSP functions FS Dep OS functions FS OS 224 A 1 GENERAL FILE SYSTEM FUNCTIONS void FS DevDrvAdd FS DEV API p dev api FS ERR p err FS ERR FS Init FS _CFG p fs cfg CPU_INTO8U FS_VersionGet void void FS WorkingDirGet CPU CHAR path dir CPU SIZE T len max FS ERR p err void FS WorkingDirSet CPU CHAR path dir FS ERR p err void FS DevDrvAdd FS DEV API p dev drv FS ERR p err 225 Appendix A A 1 1 FS DevDrvAdd void FS DevDrvAdd FS DEV API p dev drv FS ERR p err File Called from Code enabled by fs c Application N A Adds a device driver to the file system ARGUMENTS p dev drv Pointer to device driver see Section C 08 p err Pointer to variable that will receive the return error code from this function FS ERR NONE Device driver added FS ERR NULL PIR Argument p dev drv passed a NULL pointer FS ERR DEV DRV ALREADY ADDED Device drive
2. nunnannu nnen enanne nen ennennenenenennerenennn 118 Organization of Directories and Directory Entries 119 Organization of the File Allocation Table REENEN 120 FATA2 EFATIGMPFAT 32 eege Seege 122 Short and Long File Names nnnnsn nevens nnnerennnnnseenennennenenensnnnennenn 123 Bel lt Le En 126 Sources of Corruption in FAT Volumes 2 se seeeeeeeeeeeeeeeeeeeeeeeeees 127 Optional Journaling System ENEE EEN EEEEE EN 127 Licensing ISSUCS 2 srvervie sue eevec cee eee ccs anniina oani ane vaaan aniani 129 Licenses for Long File Names LENS seen 129 Extended File Allocation Table exFAT REENEN 129 RAM DISK Diver EE 131 Files and Directores a a a aa e ae raana eaa aaa ad aaia Eaa ENEE 131 Using the RAM Disk Driver essssssnsssununnnnununrnnnnnnnnnnnnnnnnnnnunnnnnnnnnnnnnnn 132 Table of Contents Chapter 12 12 1 12 2 12 2 1 12 2 2 12 2 3 12 3 12 3 1 12 3 2 12 3 3 Chapter 13 13 1 13 2 13 3 13 3 1 13 3 2 13 4 13 4 1 13 4 2 13 5 13 6 13 7 13 8 13 8 1 13 8 2 13 8 3 13 8 4 Chapter 14 14 1 14 2 14 3 14 3 1 14 3 2 14 3 3 EIS duleflely TC 135 Files andi Directores eraren araa ee e ae a die igs oct amaaan aara aa saraaa aaan 137 Using the SD MMC CardMode Driver annen en enee nennen 138 SD MMC CardMode Communication ee eenen een 141 SD MMC CardMode Communication Debugging nnn 144 SD MMC CardMode BSP Overview nnnnnnnne senen ven ven eenenensen 148
3. Create a file or directory See also fs mkdir ARGUMENTS name full Name of the entry See section 4 3 uC FS File and Directory Names and Paths on page 62 entry type Indicates whether the new entry shall be a directory or a file see Note 1 FS ENTRY TYPE DIR if the entry shall be a directory FS ENTRY TYPE FILE if the entry shall be a file excl Indicates whether the creation of the new entry shall be exclusive see Notes DEF YES if the entry shall be created only if p_ name full does not exist DEE MO if the entry shall be created even if p name full does exist 302 p_err FS ERR NONE FS ERR NAME NULL FS ERR NAME INVALID FS ERR NAME PATH TOO LONG FS ERR VOL NOT OPEN FS ERR VOL NOT MOUNTED FS ERR PUE NONE AVAIL FS ERR DEV RETURNED VALUE None NOTES WARNINGS Pointer to variable that will the receive return error code from this function Entry created successfully Argument name full passed a NULL pointer Entry name specified invalid OR volume could not be found Entry name specified too long Volume was not open Volume was not mounted Buffer not available Device access error Or entry error If the entry exists and is a file entry_type is FS ENIRY TYPE FILE and excl is DEF_NO then the existing entry will be truncated If the entry exists and is a directory and entry_type is FS ENTRY TYPE DIR then no change will be made to the file system If the entry exists
4. Get the working directory for the current task ARGUMENTS path dir String buffer that will receive the working directory path size Size of string buffer RETURNED VALUE Pointer to path_dir if no error occurs Pointer to NULL otherwise NOTES WARNINGS None 255 Appendix A A 2 22 fs_localtime_r struct fs tm fs localtime r const fs time t struct fs tm File Called from Code enabled by fs_api c Application Convert timestamp to date time FS_CFG API EN ARGUMENTS p ts Pointer to time value p time Pointer to variable that will receive broken down time RETURNED VALUE Pointer to p_time if NO errors Pointer to NULL otherwise NOTES WARNINGS None 256 A 2 23 fs_mkdir int fs_mkdir const char name full File Called from Code enabled by fs_api c FS_CFG RD ONLY EN Application FS CFG API EN and not Create a directory ARGUMENTS name full Name of the directory RETURNED VALUE 0 if the directory is created 1 if the directory is NOT created NOTES WARNINGS None EXAMPLE void App Fnct void int err err fs_mkdir sd 0 data old Make dir if err 0 APP TRACE INFO Could not make dir 257 Appendix A A 2 24 fs_mktime fs time t fs mktime struct fs tm p time File Called from Code enabled by fs_api c Application FS CFG API EN Convert date time to timestamp
5. 510 F 2 USING THE SHELL COMMANDS To use shell commands four files in addition to the generic file system files must be included in the build E fs shell c m fs shell h E shell c located in Micrium Software uC Shell1 Source E shell h located in Micrium Software uC Shell1 Source The file fs_shell h and shell h must also be included in any application or header files initialize uC Shell or handle shell commands The shell command configuration file fs shell _cfg h should be copied to your application directory and modified The following directories must be on the project include path B Micrium Software uC FS Cmd B Micrium Software uC Shell Source uC Shell with the uC FS shell commands is initialized in Listing F 1 The file system initialization FS_Init function should have previously been called CPU BOOLEAN App ShellInit void CPU_BOOLEAN ok ok Shell Init if ok DEF_FAIL return DEF_FAIL ok FSShell Init if ok DEF FAIL return DEF_FAIL return DEF_OK Listing F 1 Initializing pC Shell 511 Appendix F It s assumed that the application will create a task to receive input from a terminal this task should be written as shown in Listing F 2 void App ShellTask void p arg CPU_CHAR cmd_line MAX_CMD_LEN SHELL ERR err SHELL CMD PARAM cmd param CPU CHAR cwd_path FS_ CFG FULL NAME LEN lu Init cmd param see Note 1 Str Copy amp cw
6. nnnnnn nnen nen venen enenn 452 Table of Contents C 6 C 7 C 7 1 C 7 2 C 7 3 C 7 4 C 7 5 C 7 6 C 7 7 C 8 C 9 C 9 1 C 9 2 C 9 3 C 9 4 C 9 5 C 9 6 C 10 C 10 1 C 10 2 C 10 3 C 10 4 C 10 5 C 10 6 C 11 Appendix D D 1 D 2 D 3 D 4 D 5 D 6 D 7 D 8 D 9 SD MMC SPI mode BSP naar even ennenne ne nemen eenenennnnseenenn 452 IS EE 453 OPO ex oad cas EEN tede eat deu envel ea ee 457 GIOSE IE E ON E EIE I e Eed dude lect geed 459 Lock UNIOCK siisii iiini oaaanoeenn Eege et aanta aaraa dndrn vend 460 ROO NEE 461 Wil SE 462 ChipSelEn ChipSelDis nanne nanne nen ennn eenen ennen ennnen na 463 ET e Ce UE 464 NAND Flash Physical Layer Driver anneer seo ennneerenenneeeree renner 464 NOR Flash Physical Layer Driver nnnnnanannnneneeeennnnereenenneeerenennnnen 464 OPEN ereen deerne dennen E E nee enden ae arden eed 467 GIOSE sassen roteren deden deene ege 468 RO nennen de eterniet deense ee Eed 469 MVR caaeaae a leticeelsthadecadsteacedecs ECKER EES ee tee ebe 470 EraseBlk secda eren pita a ANa AAEN A AAEE 471 IO GI EE 472 NOR Flash TE 473 FSDev_NOR_BSP_Openi cccccecceseeesseeeeeeceeeeeeeeesnseneeeeeneeeseeeeeeees 474 FSDev_NOR_BSP_ClOS ccccssssccceeeeseeeceeeeeseaeeeeeesaeeeeeeeseaeeeeenenees 475 FSDev_ NOR BSP_Rd XX annen eeen denenin raakana 476 FSDev_NOR BSP_RdWord XX na neee enneneneneeenneer 477 FSDev_NOR BSP_WrWord XX nee eenen eneenneneneeeen
7. Device error x APP_TRACE_DBG opening volume failed w err d r n r n err return DEF FAIL return DEF OK Listing 11 1 Opening a RAM disk volume L11 1 1 The sector size and number of sectors in the RAM disk must be defined The sector size should be 512 1024 2048 or 4096 the number of sectors will be determined by your application requirements This defines a 24 MB RAM disk 49152 512 B sectors On most CPUs it is beneficial to 32 bit align the RAM disk since this will speed up access L11 1 2 Register the RAM disk driver FSDev_RAM 111 103 The RAM disk parameters sector size size in sectors and pointer to the disk should be assigned to a FS_DEV_RAM CFG structure 133 Chapter 11 L11 1 4 L11 1 5 L11 1 6 FSDev Open opens initializes a file system device The parameters are the device name 3a and a pointer to a device driver specific configuration structure 3b The device name a s composed of a device driver name Cram a single colon an ASCII formatted integer the unit number and another colon FSVol_Open opens mounts a volume The parameters are the volume name Ga the device name 5b and the partition that will be opened 5c There is no restriction on the volume name 5a however it is typical to give the volume the same name as the underlying device If the default partition is to be opened or if the device is not partition then the partition number 5c
8. FSVol_Open sd 0 a sd 0 b void 0 amp err In this case the name of the volume a is the same as the name as the device b When multiple volumes exist in the same application the volume name should be prefixed to the file or directory path name p file fs fopen sd 0 dir01l file0l txt w File on SD card fs fopen ram 0 dir01 file0l txt w File on RAM disk p file 4 3 uHC FS FILE AND DIRECTORY NAMES AND PATHS Files and directories are identified by a path string for example a file can be opened p file fs fopen test file001 txt w In this case test file001 txt is the path string An application specifies the path of a file or directory using either an absolute or a relative path An absolute path is a character string which specifies a unique file and follows the pattern lt vol_name gt lt Path gt lt File gt where lt vol_name gt is the name of the volume identical to the string specified in FSVol_Open lt Path gt is the file path which must always begin and end with a V lt File gt is the file Cor leaf directory name including any extension 62 UC FS File and Directory Names and Paths For example p file fs fopen sd 0 file txt wii a p file fs fopen file txt wii b p file fs fopen sd 0 dir01 file0l txt w C p file fs opendir sd 0
9. FS_ERR_NULL PTR Argument p dest passed a NULL pointer Or device access error see section B 4 Device Error Codes on page 394 RETURNED VALUE None NOTES WARNINGS Device state change will result from device I O not present or timeout error 288 A 3 15 FSDev_Refresh CPU BOOLEAN FSDev_Refresh CPU CHAR name dev FS ERR p err File Called from Code enabled by fs deu Application N A Refresh a device Arguments name dev Device name p err Pointer to variable that will receive the return error code from this function FS ERR NONE Device opened successfully FS ERR DEV INVALID SEC SIZE Invalid device sector size FS ERR DEV INVALID SIZE Invalid device size FS ERR DEV INVALID UNIT NBR Specified unit number invalid FS ERR NAME NULL Argument name dev passed a NULL pointer Or device access error see section B 4 Device Error Codes on page 394 RETURNED VALUE DEF YES if the device has not changed DEF MO if the device has not changed NOTES WARNINGS B If device has changed all volumes open on the device must be refreshed and all files closed and reopened B A device status change may be caused by A device was connected but no longer is A device was not connected but now is 289 Appendix A A different device is connected 290 A 3 16 FSDev_Wr void FSDev_Wr CPU_CHAR name dev void p src FS SEC NBR start FS SEC OTY ent FS ERR p err File Calle
10. File Called from Code enabled by fs file c Application fs ftrylockfile FS _CFG FILE LOCK EN Acquire task ownership of a file Gf available See fs flockfile for more information ARGUMENTS p file Pointer to a file p err Pointer to variable that will the receive return error code from this function FS ERR NONE File lock acquired FS ERR NULL PIR Argument p file passed a NULL pointer FS ERR INVALID TYPE Argument p file s type is invalid or unknown FS ERR FILE NOT OPEN File NOT open FS ERR FILE LOCKED File owned by another task RETURNED VALUE None NOTES WARNINGS None 321 Appendix A A 6 9 FSFile Locke void FSFile LockGet FS FILE p file FS ERR p err File Called from Code enabled by fs file c Application fs flockfile FS _CFG FILE LOCK EN Acquire task ownership of a file See fs flockfile for more information ARGUMENTS p file Pointer to a file p err Pointer to variable that will the receive return error code from this function FS ERR NONE File lock acquired FS ERR NULL PIR Argument p file passed a NULL pointer FS ERR INVALID TYPE Argument p file s type is invalid or unknown FS ERR FILE NOT OPEN File NOT open RETURNED VALUE None NOTES WARNINGS None 322 A 6 10 FSFile_LockSet void FSFile LockSet FS FILE p file FS ERR p err File Called from Code enabled by fs file c Application FS CFG FILE LOCK EN
11. If two entries are needed as in Figure 10 4 byte 0 of the entries carry order numbers of 0x43 and 0x01 respectively In entries that store part of a LFN byte 11 where the Attributes value is stored in a SFN is always 0x0F Microsoft found that no software would modify or use a directory entry with this marker In entries that store part of a LFN byte 13 contains the checksum which is calculated from the SFN FAT s file system software recalculates the checksum each time it parses the directory entries If the stored checksum is not the same as the recalculated checksum FAT s file system software knows that the SFN was modified presumably by a program that is not LFN aware 125 Chapter 10 10 4 FORMATTING A volume once it is open may need to be formatted before files or directories can be created The default format is selected by passing a NULL pointer as the second parameter of FSVol_Fmt Alternatively the exact properties of the file system can be configured with a FS FAT SYS CFG structure An example of populating and using the FAT configuration is shown in Listing 10 1 If the configuration is invalid an error will be returned from FSVol_Fmt For more information about the FS FAT SYS CFG structure see Appendix D FS_FAT_SYS_CFG on page 492 void App InitFS void FS_ERR err FS_FAT SYS CFG fat cfg fat_cfg ClusSize 4 Cluster size 4 512 B 2 kB fat_cfg RsvdAreaSize ip Reserved
12. Invalid volume sector size Invalid volume cluster size Volume operation invalid Invalid volume sector number Invalid file system on volume No cache assigned to volume No vol avail No vols exist Vol NOT open Vol NOT mounted Vol already open Files open on vol FS ERR VOL DIRS OPEN FS ERR JOURNAL ALREADY OPEN FS ERR JOURNAL CFG CHANGED FS ERR JOURNAL FILE INVALID FS ERR JOURNAL FULL FS ERR JOURNAL LOG INVALID ARG FS ERR JOURNAL LOG INCOMPLETE FS ERR JOURNAL LOG NOT PRESENT FS ERR JOURNAL NOT OPEN FS ERR JOURNAL NOT REPLAYING FS ERR JOURNAL NOT STARTED FS ERR JOURNAL NOT STOPPED FS ERR VOL LABEL INVALID FS ERR VOL LABEL NOT FOUND FS ERR VOL LABEL TOO LONG Dirs open on vol Journal already open File system suite cfg changed since log created Journal file invalid Journal full Invalid arg read from journal log Log not completely entered in journal Log not present in journal Journal not open Journal not being replayed Journaling not started Journaling not stopped Volume label is invalid Volume label was not found Volume label is too long B 15 OS LAYER ERROR CODES FS ERR OS LOCK FS ERR OS INIT FS ERR OS INIT LOCK FS ERR OS INIT LOCK NAME Lock not acquired OS not initialized Lock signal not successfully initialized Lock signal name not successfully initialized 399 Appendix B 400 Appendix UC FS Porting Manual uC FS adapts to its environment via a nu
13. a single colon an ASCII formatted integer the unit number and another colon L14 1 4 FSDev_NOR_LowFmt low level formats a NOR If the NOR has never been used with uC FS it must be low level formatted before being used Low level formatting will associate logical sectors with physical areas of the device 206 Using a Parallel NOR Device FSVol Open opens mounts a volume The parameters are the volume name 5a the device name 5b and the partition that will be opened 5c There is no restriction on the volume name 5a however it is typical to give the volume the same name as the underlying device If the default partition is to be opened or if the device is not partition then the partition number 5c should be zero FSVol Fmt formats a file system device If the NOR has just been low level format it will have no file system on it after it is opened Gt will be unformatted and must be formatted before files can be created or accessed If the NOR initialization succeeds the file system will produce the trace output as shown in Figure 14 1 Gf a sufficiently high trace level is configured See section E 9 Trace Configuration on page 507 about configuring the trace level d blks found Figure 14 1 NOR detection trace output 207 Chapter 14 14 3 1 DRIVER ARCHITECTURE When used with a parallel NOR device the NOR driver is three layered as depicted in the figure below The generic NOR driver as al
14. d p file fs opendir e p file fs opendir sd 0 dir01 Which demonstrate a opening a file in the root directory of a specified volume b opening a file in the root directory on a default volume c opening a file in a non root directory d opening the root directory of a specified volume e opening the root directory of the default volume f opening a non root directory Relative paths can be used if working directories are enabled FS_CFG_WORKING_DIR_EN is DEF ENABLED see Appendix E on page 501 A relative path begins with neither a volume name nor a V lt Relative Path gt lt File gt where lt Relative Path gt is the file path which must not begin with a V but must end with a V lt File gt is the file or leaf directory name including any extension o zm D Two special path components can be used moves the path to the parent directory keeps the path in the same directory basically it does nothing A relative path is appended to the current working directory of the calling task to form the absolute path of the file or directory The working directory functions fs chdir and fs_getcwd can be used to set and get the working directory 63 Chapter 4 4 4 uC FS NAME LENGTHS The configuration constants FS CFG MAX PATH NAME LEN FS CFG MAX FILE NAME LEN and FS CFG MAX VOL NAME LEN in fs cfg h set the maximum length of path names fi
15. format failed r n return DEF FAIL else Gi APP_TRACE_DBG opening device failed w err d r n r n err return 0 endif break 163 Chapter 13 case FS_ERR_DEV Device error SG case FS ERR DEV IO case FS ERR DEV TIMEOUT case FS ERR DEV NOT PRESENT APP_TRACE_DBG Opened volume unmounted r n return DEF_FAIL default APP_TRACE_DBG opening volume failed w err d r n r n err return DEF FAIL return DEF OK L13 1 1 L13 1 2 L13 1 3 L13 1 4 L13 1 5 164 Listing 13 1 Opening a NAND device volume Declare and initialize configuration structures Structures should be initialized to allow for forward compatibility in case some new fields in those structures are added in future pC FS versions Register the NAND device driver FS_NAND The NAND part layer configuration structure should be initialized For more information about these parameters see section Statically configured part layer on page 181 The NAND controller layer configuration structure should be initialized For more information about these parameters see section 13 4 1 Generic Controller Layer Implementation on page 179 Please note that you might need to use a different controller layer If this is the case the configuration might be different see section 13 4 Controller Layer on page 178 The NAND generic controller software ECC extension should be in
16. gt are not part of the actual name BSP This directory is always called BSP 35 Chapter 3 VK These are the source files of the BSP Typically all the file names start with BSP_ but they don t have to It s thus typical to find bsp c and bsp h in this directory Again the BSP code should contain functions such as LED control functions initialization of timers interface to Ethernet controllers and more 3 4 pC CPU CPU SPECIFIC SOURCE CODE HC CPU consists of files that encapsulate common CPU specific functionality as well as CPU and compiler specific data types Micrium Software uC CPU cpu_core c cpu_core h cpu_def h Cfg Template cpu_cfg h lt architecture gt lt compiler gt cpu h cpu_a asm cpu_c c Micrium This directory contains all software components and projects provided by Micrium Software This sub directory contains all the software components and projects uC CPU This is the main pC CPU directory 36 LC CPU CPU Specific Source Code cpu_core c contains C code that is common to all CPU architectures Specifically this file contains functions to measure the interrupt disable time of the CPU_CRITICAL ENTER and CPU_CRITICAL EXIT macros a function that emulates a count leading zeros instruction and a few other functions cpu_core h contains the function prototypes of the functions provided in cpu_core c as well as allocation of the variables used by this module to m
17. which frees the volume structure FSVol_Query which returns information about the device If FS ERR DEV FS ERR DEV NOT PRESENT FS ERR DEV IO or FS ERR DEV TIMEOUT is returned then the volume has been added to the file system though the underlying device is probably not present The volume will need to be either closed and re added or refreshed 351 Appendix A A 7 12 FSVol Query void FSVol Query CPU CHAR name vol FS VOL INFO p info FS ERR p err File Called from Code enabled by fs vol c Application N A Obtain information about a volume ARGUMENTS name vol Volume name p info Pointer to structure that will receive volume information see Note p err Pointer to variable that will receive the return error code from this function FS ERR NONE FS ERR DEV FS ERR NAME NULL FS ERR NULL PTR FS ERR VOL NOT OPEN RETURNED VALUE None NOTES WARNINGS None 352 Volume information obtained Device access error Argument name vol passed a NULL pointer Argument p_info passed a NULL pointer Volume is not open A 7 13 FSVol Rd void FSVol Rd CPU CHAR name vol void p dest FS SEC NBR start FS SEC OTY ent FS ERR p err File Called from Code enabled by fs vol c Application N A Reads data from volume sector s ARGUMENTS name vol Volume name p dest Pointer to destination buffer start Start sector of read cnt Number of sectors to read p err Pointer to va
18. File in parent of working directory oo The two standard special path components are supported The path component moves to the parent of the current working directory The path component essentially it means the current working directory D makes no change 97 Chapter 8 fs chdir is used to set the working directory If a relative path is employed before any working directory is set the root directory of the default volume is used The application can get the working directory with fs _getcwd A terminal interface may use this function to implement an equivalent to the standard pwd print working directory command while calling fs chdir to carry out a cd operation If working directories are enabled the pC Shell commands for uC FS manipulate and access the working directory with fs_chdir and fs_getcwd see also Appendix F Shell Commands on page 509 8 3 FILE ACCESS FUNCTIONS The file access functions provide an API for performing a sequence of operations on a file located on a volume s file system The file object pointer returned when a file is opened is passed as an argument of all file access function and the file object so referenced maintains information about the actual file on the volume and the state of the file access The file access state includes the file position the next place data will be read written error conditions and if file buffering is enabled the state of
19. Format volume Yes FSVol_IsMounted Determine whether volume is mounted Yes FSVol_LabelGet Get volume label No FSVol_LabelSet Set volume label No FSVol_Open Open mount volume een FSVol_Query Get volume information Yes FSVol_Rd Read sector on volume No FSVol_Refresh Refresh a volume No FSVol_Wr Write sector on volume No Table 5 2 Volume API functions 5 7 USING VOLUMES A volume is opened with FSVol Open FSVol Open CPU _ CHAR ide 0 lt a volume name CPU_CHAR ide 0 lt b device name FS_PARTITION NBR 0 lt c partition number FS_ERR amp err lt d return error Listing 5 1 FSVol_Open The parameters are the volume name a the device name b and the partition that will be opened c There is no restriction on the volume name a however it is typical to give the volume the same name as the underlying device If the default partition is to be opened or if the device is not partitioned then the partition number c should be zero 77 Chapter 5 The return error code from this function provides important information about the volume state B If the return error code is FS ERR NONE then the volume has been mounted and is ready to use B If the return error code is FS ERR PARTITION NOT FOUND then no valid file system could be found on the device or the specified partition does not exist The device may need to be formatted see below B If
20. In the first form of this command the second argument must not be an existing directory The file source entry will be renamed dest entry In the second form of this command the second argument must be an existing directory source entry will be renamed to an entry with name formed by concatenating dest dir a path separator character and the final component of source entry In both forms if source entry is a directory the entire directory tree rooted at source entry will be copied and then deleted Additionally both source entry and dest entry or dest dir must specify locations on the same volume 525 Appendix F F 3 11 fs_od Dump file contents to the terminal output USAGES fs od file ARGUMENTS file Path of file to dump to terminal output OUTPUT File contents in hexadecimal form REQUIRED CONFIGURATION Available only if FS SHELL CFG OD EN is DEF_ENABLED NOTES WARNINGS None COM4 PuTTY 00000020 F 00000030 OO6F 00000040 0020 OOOOOGEO 4 2004200 000000Fro 6 00000100 690041 R gt 3006F00 6 00000110 200074 6F 64007200 2D002000 Figure F 7 fs_od output 526 F 3 12 fs_pwd Write to terminal output pathname of current working directory USAGES fs_pwd ARGUMENTS None OUTPUT Pathname of current working directory REQUIRED CONFIGURATION Available only if FS SHELL CFG PWD EN is DEF ENABLED NOTES WARNINGS None 527 Appendix F F 3 13 fs_rm Remove a fi
21. fs c Application fs_chdir FS_CFG WORKING DIR EN Set the working directory for the current task ARGUMENTS path_dir String buffer that specified EITHER a the absolute working directory path to set b a relative path that will be applied to the current working directory p err Pointer to variable that will receive the return error code from this function FS ERR NONE Working directory set FS ERR NAME NULL Argument path dir passed a NULL pointer FS ERR VOL NONE EXIST No volumes exist FS ERR WORKING DIR NONE AVAIL No working directories available FS ERR WORKING DIR INVALID Argument path dir passed an invalid directory RETURNED VALUE None NOTES WARNINGS None 230 A 2 POSIX API FUNCTIONS char fs_asctime_r const struct fs tm p time char str time int fs chdir const char path dir void fs clearerr FS FILE p file int fs closedir FS DIR p dir char fs ctime r const fs time t p ts char str time int fs fclose FS FILE p file int fs feof FS FILE p file int fs ferror FS FILE p file int fs fflush FS FILE p file int fs fgetpos FS FILE p file fs fpos t p pos void fs_flockfile FS_FILE p file FS FILE fs fopen const char name full const char str mode 231 Appendix A fs size t fs fread void p dest fs size t size fs size t nitems FS FILE p file int fs f
22. p data REG BLOCK COUNT p cmd gt BlkCnt REG BLOCK SIZE p cmd gt BlkSize REG ARGUMENT p_cmd gt Arg REG_TRANSFER_MODE transfer_mode REG_COMMAND command p err FS DEV SD CARD ERR NONE LC 7 1 LC 7 2 LC 7 3 LC 7 4 Listing C 7 FSDev_SD Card _BSP_CmdStart Check whether the controller is busy Though no successful operation should return without the controller idle an error condition programming mistake or unexpected condition could make an assumption about initial controller state false This simple validation is recommended to avoid side effects and to aid port debugging Calculate the transfer mode register value The command s DataType and DataDir members specify the type and direction of any transfer Since this examples uses DMA DMA is enabled in the transfer mode register Calculate the command register value The command index is available in the command s Cmd member which is supplemented by the bits OR d into Flags to describe the expected result response and data transfer following the command execution The hardware registers are written to execute the command The sequence in which the registers are written is important Typically as in this example the assignment to the command register actually triggers execution 435 Appendix C C 5 4 FSDev_SD_Card_BSP_CmdWaitEnd void FSDev_SD Card BSP CmdWaitEnd FS OTY unit_nbr FS DEV SD CARD CMD p cmd CPU INT32U p
23. void S E E amp FS NAND BSP_SAM9M10 FS_NAND CTRLR API amp FS NAND CtrlrGeneric amp cfg_ctrlr FS_NAND_PART_API amp cfg part S125 2038u 10u 10u 2u 10u 7 I L opened device r n amp FS NAND PartStatic Si a b case FS ERR DEV INVALID LOW FMT case FS ERR DEV INCOMPATIBLE LOW PARAMS case FS ERR DEV CORRUPT LOW FMT Getting Started APP_TRACE_DBG opened device not low level formatted r n if FS_CFG RD ONLY EN DEF ENABLED FS_NAND LowFmt nand 0 amp err 8 CG if err FS ERR NONE APP TRACE DBG low level format failed r n return 0 else APP_TRACE_DBG opening device failed w err d r n r n err return 0 endif break case FS ERR DEV ALREADY OPEN break case FS ERR DEV case FS ERR DEV IO case FS ERR DEV TIMEOUT case FS ERR DEV NOT PRESENT default APP TRACE DG opening device failed w err d r n r n err return DEF FAIL 9 E FSVol_Open nand 0 Z a nand 0 ZS b 0 c amp err switch err case FS_ERR NONE APP TRACE DG opened volume mounted r n break case FS ERR PARTITION NOT FOUND Volume error APP TRACE DBG opened device not formatted r n if FS CFG RD ONLY EN DEF DISABLED FSVol_Fmt nand 0 void 0 amp err 10 if err FS ERR NONE APP TRACE DBG
24. A 11 6 FSDev_NOR_PhyRd void FSDev NOR PhyRd CPU CHAR name dev void p dest CPU INT32U start CPU_INT32U FS_ERR p err File Called from Code enabled by fs_dev_nor c Application N A Read from a NOR device and store data in buffer ARGUMENTS name_dev Device name see Note p dest Pointer to destination buffer start Start address of read relative to start of device cnt Number of octets to read p err Pointer to variable that will the receive return error code from this function FS_ERR_NONE Octets read successfully FS ERR NAME NULL FS ERR NULL PTR FS ERR DEV INVALID FS ERR DEV NOT OPEN FS ERR DEV NOT PRESENT FS ERR DEV INVALID LOW FMT FS ERR DEV IO FS ERR DEV TIMEOUT Argument name dev passed a NULL pointer Argument p dest passed a NULL pointer Argument name dev specifies an invalid device Device is not open Device is not present Device needs to be low level formatted Device I O error Device timeout 379 Appendix A RETURNED VALUE None NOTES WARNINGS The device must be a NOR device e g nor 0 380 A 11 7 FSDev_NOR_PhyWr void FSDev NOR PhyWr CPU CHAR name dev void p src CPU INT32U start CPU INT32U cnt FS ERR p err File Called from Code enabled by fs dev nor c Application N A Write to a NOR device from a buffer ARGUMENTS name dev Device name see Note p src Pointer to source buffer start Start address of write rel
25. COGGS 55 nanne ke eESSEde ee T T 397 File System Error Codes nnnnsnan nanne nneeesennenenenennnenenenennenneenvennnenn 398 Volume Error Codes ansanssee verven naaien ENNEN ENEE dee ver vinvn inn 398 OS Layer Error COd S aa aaa a a Aaaa EE ENNER dee ee 399 HC FS Porting Manual nnn onnenee ne nenenserenennnnnrnenensennenerenenennnenen 401 Date Time Management un 403 CPU POM E 403 OS Kennel E EA EE 404 Device DIVO aaea aE aaa aa aaa a ten zeeman a aa ae a Eaa Dea Ea 412 NameGet sipna anaana AENA 414 MIO E 415 OPEN anana EENS NENNEN 416 GIOSE I EE IEEE EAS E I ET A T avian AA TEA 418 RO oreert EE A eren a N AE E ees eee 419 NEU tee EE EA E ee 421 QUOPY E dere E E wanna jdsatensbcuessunecs 423 1O Ctl EE 424 SD MMC Cardmode BSP arne nemen se neneenennenenennenseeevenn 425 FSDev SD Card BSP Open nnen nennen vennen eneen eenen eenen 429 FSDev_ SD Card BSP _Lock Unlock na neen veeneeen 430 FSDev SD Card BSP _CmdStart annae eene REENEN 431 FSDev SD Card BSP CmdWaitEnd nnee een 436 FSDev SD Card BSP CmdDataRd nnn eenn 440 FSDev SD Card BSP CmdDataWr nanne eee eenn 443 FSDev SD Card BSP GetBlkCntMax nnen senen ennen 446 FSDev SD Card BSP _GetBusWidthMax aaneen 447 FSDev SD Card BSP SetBusWidth aaan ennenen nnne 448 FSDev SD Card BSP SetClkFrea anssen RRE NEE 450 FSDev SD Card BSP SetTimeoutData annae nan ennenen 451 FSDev SD Card BSP SetTimeoutResp
26. Chapter 3 uC FS Directories and Files This chapter explains the directory structure and files needed to build a pC FS based application Learn about the files that are needed where they should be placed which module does what and more Chapter 4 Useful Information In this chapter you will learn the nomenclature used in HC FS to access files and folders and the resources needed to use pC FS in your application Chapter 5 Devices and Volumes Every file and directory accessed with uC FS is a constituent of a volume a collection of files and directories on a device a physical or logical sector addressed entity This chapter explains how devices and volumes are managed Chapter 6 Files uC FS complements the POSIX API with its own file access API This chapter explains this API Chapter 7 Directories uC FS complements the POSIX API with its own directory access API This chapter explains this API Chapter 8 POSIX API The best known API for accessing and managing files and directories is specified within the POSIX standard IEEE Std 1003 1 which is based in part in the ISO C standard ISO IEC 9899 This chapter explains how to use this API and examines some of its pitfalls and shortcomings Chapter 10 FAT File System This chapter details the low level architecture of the FAT file system Though the API of uC FS is file system agnostic the file system type does affect performance re
27. Device access error Or entry error RETURNED VALUE None NOTES WARNINGS E When a file is removed the space occupied by the file is freed and shall no longer be accessible B A directory can be removed only if it is an empty directory B The root directory cannot be deleted 305 Appendix A A 5 5 FSEntry Query void FSEntry Query CPU CHAR name full FS ENTRY INFO p info FS ERR p err File Called from Code enabled by fs entry c Application N A fs_stat Get information about a file or directory ARGUMENTS name full Name of the entry See section 4 3 uC FS File and Directory Names and Paths on page 62 p_info Pointer to structure that will receive the file information p err Pointer to variable that will the receive return error code from the function FS ERR NONE File information obtained successfully FS ERR NAME NULL Argument name full passed a NULL pointer FS ERR NAME INVALID Entry name specified invalid OR volume could not be found FS ERR NAME PATH TOO LONG Entry name specified too long FS ERR VOL NOT OPEN Volume was not open FS ERR VOL NOT MOUNTED Volume was not mounted FS ERR BUF NONE AVAIL Buffer not available FS ERR DEV Device access error RETURNED VALUE None NOTES WARNINGS None 306 A 5 6 FSEntry_Rename void FSEntry Rename CPU_CHAR name full old CPU CHAR name full new CPU BOOLEAN excl FS ERR p err File Called from Co
28. F3 1 12 HC FS does not require an RTOS However if uC FS is used with an RTOS a set of functions must be implemented to prevent simultaneous access of devices and core uC FS structures by multiple tasks F3 1 13 This uC FS configuration file defines which uC FS features fs_cfg h are included in the application 3 1 APPLICATION CODE When Micrium provides you with example projects we typically place those in a directory structure as shown below Of course you can use whatever directory structure suits your project product Mierium Software EvalBoards lt manufacturer gt lt board name gt lt compiler gt lt project name gt Micrium This is where we place all software components and projects provided by Micrium This directory generally starts from the root directory of your computer 32 Application Code Software This sub directory contains all the software components and projects EvalBoards This sub directory contains all the projects related to the evaluation boards supported by Micrium lt manufacturer gt Is the name of the manufacturer of the evaluation board The lt and gt are not part of the actual name lt board name gt This is the name of the evaluation board A board from Micrium will typically be called uC Eval xxxx where xxxx will represent the CPU or MCU used on the evaluation board The lt and gt are not part of the actual name
29. FAT12 volumes can not be opened nor can a device be formatted as a FAT12 volume FS FAT CFG FAT16_ EN FS FAT CFG FAT16 EN is used to control whether FAT16 is supported When DEF DISABLED FAT16 volumes can not be opened nor can a device be formatted as a FAT16 volume FS_FAT CFG FAT32_EN FS_FAT CFG FAT32_EN is used to control whether FAT32 is supported When DEF DISABLED FAT32 volumes can not be opened nor can a device be formatted as a FAT32 volume 505 Appendix E FS_FAT_CFG_JOURNAL_EN FS FAT CFG JOURNAL EN selects whether journaling functions will be present When DEF_ENABLED journaling functions are present when DEF_DISABLED journaling functions are NOT present If disabled the functions in Table E 8 will not be available Function File FS FAT JournalOpen fs fat journal c h FS FAT JournalClose fs fat journal c n FS FAT JournalStart fs fat journal c n FS FAT JournalEnd fs fat journal c n Table E 8 Journaling function exclusion These functions are NOT included if FS_ FAT CFG JOURNAL EN is DEF DISABLED FS Pat CFG VOL_CHK EN FS FAT CFG VOL CHK EN selects whether volume check is supported When DEF_ENABLED volume check is supported when DEF DISABLED the function FS FAT VolChk will not be available FS Pat CFG_VOL CHK MAX LEVELS FS FAT CFG VOL CHK MAX LEVELS specifies the maximum number of directory levels that will be checked by the volume check function Each level requires an addi
30. Function File fs fwrite fs api c fs_remove fs api c fs_rename fs api c fs mkdir fs api c fs truncate fs api c fs rmdir fs api c FSDev PartitionAdd fs deu FSDev_PartitionInit fs_dev c FSDev_Wr fs dev c FSEntry AttribSet fs entry c FSEntry Copy fs entry c FSEntry Create fs entry c FSEntry TimeSet fs entry c FSEntry Del fs entry c FSEntry Rename fs entry c 502 Function File FSFile_Truncate fs file c FSFile Wr fs file c FSVol Fmt fs vol c FSVol_LabelSet fs vol c FSVol_Wr fs vol c Table E 7 Read only function exclusion continued These functions are not included if FS_CFG_RD_ONLY_EN is DEF_ENABLED FS_CFG 64 BITS LBA_EN FS CFG 64 BIT LBA EN selects whether support for 64 logical block addressing LBA is enabled When DEF_ENABLED support 64 bit LBA will be included otherwise LBA will be limited to 32 bit Applications that need support for 48 bit LBA should set this feature to DEF ENABLED E 3 NAME RESTRICTION CONFIGURATION Individual file system features may be selectively disabled FS_CFG MAX PATH NAME LEN FS CFG MAX PATH NAME LEN configures the maximum path name length in characters not including the final NULL character The default value is 260 the maximum path name length for paths on FAT volumes FS_CFG MAX FILE NAME LEN FS CFG MAX FILE NAME LEN configures the maximum file name length in characters not including the final NULL character The
31. Note that all unused function pointers should be set to DEF_NULL typedef struct fs nand ctrlr gen ext void Init FS_ERR p err 1 void Open PS HAND CTRLR GEN DATA p ctrlr data 2 void p ext cfg FS ERR SPEEN void Close void p ext data 3 FS Mann PG SIZE Setup FS_NAND CTRLR GEN DATA p ctrlr data 4 void p ext data FS ERR p err void RdStatusChk void p ext data 5 FS ERR SEET void ECC_Calc void p ext data 6 void p sec buf void p_oos_buf FS_NAND PG SIZE oos_size FS_ERR p err void ECC_Verify void p ext data 7 void p sec but void p_oos buf FS_NAND PG SIZE oos_size FS_ERR p err FS_NAND CTLRR GEN EXT Listing 13 10 API structure type for generic controller extension 191 Chapter 13 113 100 L13 10 2 L13 10 3 L13 10 4 L13 10 5 L13 10 6 L13 10D 192 The Init funtion provides an opportunity to initialize an extension This will be called only once when the extension is registered with the generic controller during FSDev_Open If multiple generic controller instances are configured with the same extension the Init function will still be called only once The Open function is called by the generic controllers own Open function This function will also receive the controller extension configuration pointer The Close function might be called by the generic controllers own Close function and allow the extension
32. See section 4 3 uC FS File and Directory Names and Paths on page 62 Name of the destination file Indicates whether the creation of the new entry shall be exclusive DEF YES if the entry shall be copied only if name full dest does not exist DEE MO if the entry shall be copied even if name full dest does exist Pointer to variable that will the receive return error code from this function FS ERR NONE FS ERR NAME NULL FS ERR NAME INVALID FS ERR NAME PATH TOO LONG FS ERR VOL NOT OPEN FS ERR VOL NOT MOUNTED FS ERR PUE NONE AVAIL FS ERR DEV File copied successfully Argument name full src or name full dest passed a NULL pointer Entry name specified invalid OR volume could not be found Entry name specified too long Volume was not open Volume was not mounted Buffer not available Device access error Or entry error See section B 8 Entry Error Codes on page 395 RETURNED VALUE None NOTES WARNINGS E name full src must be an existing file It may not be an existing directory m If excl is DEF NO name full dest must either not exist or be an existing file it may not be an existing directory If excl is DEF YES name full dest must not exist 301 Appendix A A 5 3 FSEntry_Create void FSEntry Create CPU CHAR name full FS FLAGS entry type CPU BOOLEAN excl FS ERR p err File Called from Code enabled by fs entry c Application not FS CG BD ONLY EN fs mkdir
33. Using the SD MMC SPI Driver annua onaneerenennnneerenennnnenserennnen 150 SD MMC SPI Communication EENEG 153 SD MMC SPI Communication Debugging EEN 154 SD MMC SPI BSP Overview nnansnversananneeevenen senen ennnnnseenenn 157 NAND Flash DAVET E 159 Getting Started auvinn aa saevsrn anniina anauia kaanan KEANE EEANN a REENA 160 Architecture Overview REENEN 167 NAND Translation Layer a eaaa ae aaea atna Ae aana aE 168 Translation Layer Configuration ecseeccesseeeeeeeeeeeeeeseeeeeeneneeeneeeeees 171 Translation Layer Source Files nnsnnnnnnne neven eenen nennen nen venenenenn 178 Gontrollef LAY Or aE E E E dn ddenvervinnkendhbhnpannandend 178 Generic Controller Layer Implementation REENEN 179 Pa d E E 181 Board Support Package Generic Controller csssssseeeeeeees 185 Board Support Package Other Controllers nnen 186 Performance Considerations cccccceseseeeeeeeeeeeeeeeeeeeeeeneeeeneeeeeeeenees 187 Development Guide nennen see neeevenenennenanennnentennenneennen 188 BSP Development Guide Generic Controller 0s0sesseeeeeeees 189 Generic Controller Extension Development Guide ekkeeekeN 191 ECC Module Development Guide nennen see nenenvenenenenn 193 Controller Layer Development Guide nassau an annannen en ennense nen eeens 194 NOR Flash Driver ss arterteverszerssensntgenesdaern der exten ed dette ege guer 199 Files and
34. i COM4 PuTTY fs we lib str c 15091 532 Figure F 8 fs_wc output F 4 CONFIGURATION Configuration constants can be used to enable disable features within the uC FS shell commands FS_SHELL_CFG_BUF_LEN FS FAT CFG BUF LEN defines the length of the buffer in octets used to read write from files during file access operations Since this buffer is placed on the task stack the task stack must be sized appropraitely FS_SHELL_CFG CMD int EN Each FS FAT CFG CMD EN separately enables disables a particular fs_ 44H command FS FAT CFG CMD CAT EN FS FAT CFG CMD CD EN FS FAT CFG CMD CP EN FS FAT CFG CMD DF EN FS FAT CFG CMD DATE EN FS FAT CFG CMD LS EN FS FAT CFG CMD MKDIR EN FS FAT CFG CMD MKFS EN FS FAT CFG CMD MOUNT EN FS FAT CFG CMD MV EN FS FAT CFG CMD OD EN FS FAT CFG CMD PWD EN Enable disable fs cat Enable disable fs cd Enable disable fs cp Enable disable fs d Enable disable fs date Enable disable fs Le Enable disable fs _mkdir Enable disable fs_mkfs Enable disable Ce mount Enable disable Ce ma Enable disable Ce od Enable disable Ce pwd 533 Appendix F FS FAT CFG CMD RM EN FS FAT CFG CMD RMDIR EN FS FAT CFG CMD TOUCH EN FS FAT CFG CMD UMOUNT EN FS FAT CFG CMD WC EN 534 Enable disable fs_xm Enable disable fs_rmdir Enable disable s_touch Enable disable fs_umount Enable disable Ce wc Appendix Bibliography Labrosse Jean J 2009 pC O
35. 3 uC FS This is the main nC FS directory os This is the main OS directory lt rtos_name gt This is the directory that contains the files to perform RTOS abstraction Note that files for the selected RTOS abstraction layer must always be named fs os HC FS has been tested with pC OS II wC OS II and without an RTOS The RTOS layer files are found in the following directories Micrium Software uC Clk 0S None fs_os Micrium Software uC Clk 0S Template fs_os Micrium Software uC Cl1k OS uCOS II fs_os Mierium Software uC C1k OS uCOS III fs os 3 13 SUMMARY Below is a summary of all the directories and files involved in a uC FS based project The lt Cfg on the far right indicates that these files are typically copied into the application Oe project directory and edited based on project requirements Micrium Software EvalBoards lt manufacturer gt lt board name gt lt compiler gt lt project name gt app c app h other BSP bsp c bsp h 52 other CPU lt manufacturer gt lt architecture gt L uC FS APP Template fs_app c fs_app h CFG Template fs_cfg h Dev MSC fs_dev_msc c fs_dev_msc h NAND fs_dev_nand c fs_dev_nand h Ctrlr fs_dev_nand_ctrlr_gen c fs_dev_nand_ctrlr_gen h Summary lt Cfg lt Cfg lt Cfg fs_dev_nand_ctrlr_gen_soft_ecc c fs_dev_nand_ctrlr_gen_soft_ecc h fs dev nand ctrlr gen micron ecc c fs dev nand ctrlr
36. 3 8 3 4 8 3 5 8 4 8 5 Chapter 9 9 1 9 1 1 9 2 Chapter 10 10 1 10 2 10 2 1 10 3 10 3 1 10 3 2 10 4 10 5 10 6 10 7 10 7 1 10 7 2 Chapter 11 11 1 11 2 POSIX AP E 95 Supported Functions nannsnneeneenneenveneenenannannnsensenenenensnnanannnnennenen 96 Working Directory Functions nannnn an oananne eer ennensenerenenseneeennennanenenenn 97 File Access Functions uorsarnerteseserwenrserverhdngennndndenden eege dE 98 Opening Reading and Writing Files ccccceessseeeeeeeeeneeeeeseeneeeeees 100 Getting or Setting the File Position nanne ven enan nee enennenne nen enenn 103 Configuring a File Buffer nnnnsn nn aananne nen ennennenenensnnnrenennensenve rens 104 Diagnosing a File Error aaneen enn ennenereerennneerenenneneerenennnnernenenneeen 106 Atomic File Operations Using File LOCK REENEN 106 Directory Access Functions nnsnannenneneene neen vensenenennnnntenneeneenenn 107 Entry Access Functions nn annsnenensonneeerenennnenenenennnnneeesennneevenennenr 109 Device Drivers Sege ENEE Eeer EE rende EEN 111 Provided Device Drivers nanne nennen nee ne ne venennenennnneennennnenenn 112 Driver Characterization naan anan sense ne nee nenevenennnnennenrnenvenseenenn 113 Drivers comparison een 115 FAT File SySt M 2 ege 117 Why Embedded Systems Use FAT nnnnnnrannennenenensn nere nensnnneneenn 117 Organization of a FAT Volume
37. API fs_buf c h contains the code for the buffer management used internally by uC FS fs_dev c h contains code for device management See Chapter x Devices for details about devices LIC FS FAT Filesystem Source Code fs_dir c h contains code for directory access See Chapter x Directories for details about directory access fs_entry c h contains code for entry access See Chapter x Entries for details about entry access fs_file c h contains code for file access See Chapter x Files for details about file access fs_inc h is a master include file that includes all fs_sys c h contains the code for system driver management used internally by yC FS fs_unicode c h contains the code for handling Unicode strings used internally by HC FS 3 9 uC FS FAT FILESYSTEM SOURCE CODE The files in these directories are available to uC FS licensees see Appendix H Licensing Policy Micrium Software uC FS FAT fs_fat c fs_fat h fs_fat_dir c fs_fat_dir h fs_fat_entry c fs_fat_entry h fs_fat_fat1l2 c fs_fat_fat12 h fs_fat_fatl6 c fs_fat_fat16 h fs_fat_fat32 c 45 Chapter 3 fs_fat_fat32 h fs_fat_file c fs_fat_file h fs_fat_journal c fs fat journal h fs fat lfn c fs fat lfn h fs fat sfn c fs fat sfn h fs fat type h Micrium This is where we place all software components and projects provided by Micripm Software This sub directory contains all the software components and pro
38. ARGUMENTS p_time Pointer to date time to convert RETURNED VALUE Time value if NO errors fs_time_t 1 otherwise NOTES WARNINGS None 258 A 2 25 fs_opendir FS DIR fs opendir const char name full File Called from Code enabled by fs_api c Application FS_CFG API ENand FS CFG DIR EN Open a directory ARGUMENTS name full Name of the directory See section 4 3 uC FS File and Directory Names and Paths on page 62 for information about directory names RETURNED VALUE Pointer to a directory if NO errors Pointer to NULL otherwise NOTES WARNINGS None 259 Appendix A A 2 26 fs_readdir_r int fs readdir FS DIR p dir struct fs dirent p dir entry struct fs dirent pp result File Called from Code enabled by fs_api c Application FS_CFG API EN and FS CFG DIR EN Read a directory entry from a directory ARGUMENTS p dir Pointer to a directory p dir entry Pointer to variable that will receive directory entry information pp result Pointer to variable that will receive Ep dir entry if NO error occurs AND directory does not encounter EOF Epointer to NULL if an error occurs OR directory encounters EOF RETURNED VALUE 1 if an error occurs 0 otherwise NOTES WARNINGS B Entries for dot current directory and dot dot parent directory shall be returned if present No entry with an empty name shall be returned E If an ent
39. Argument p dirs TYPE is invalid or unknown FS ERR DIR DIS Directory module disabled FS ERR DIR NOT OPEN Directory NOT open FS ERR EOF End of directory reached FS ERR DEV Device access error FS ERR BUF NONE AVAIL Buffer not available RETURNED VALUE None NOTES WARNINGS None 296 A 5 ENTRY ACCESS FUNCTIONS void FSEntry AttribSet CPU_CHAR name full FS_FLAGS attrib FS_ERR p err void FSEntry Copy CPU _CHAR name full src CPU CHAR name full dest CPU BOOLEAN excl FS ERR p err void FSEntry Create CPU CHAR name full FS FLAGS entry type CPU BOOLEAN excl FS ERR p err void FSEntry Del CPU CHAR name full FS FLAGS entry type FS ERR p err void FSEntry Query CPU _CHAR name full FS ENIRY INFO p info FS ERR p err void FSEntry Rename CPU CHAR name full src CPU CHAR name full dest CPU BOOLEAN excl FS ERR p err void FSEntry TimeSet CPU CHAR name full FS DATE TIME p time CPU INTO8U flag FS ERR p err 297 Appendix A A 5 1 FSEntry_AttribSet void FSEntry AttribSet CPU CHAR name full FS FLAGS attrib FS ERR p err File Called from Code enabled by fs entry c Application not FS CG RD ONLY EN Set a file or directory s attributes ARGUMENTS name full Name of the entry See section 4 3 uC FS File and Directory Names and Paths on page 62 attrib Entry attributes to set see Note 2 p err Poi
40. Calc transfer mode reg value 2 if p cmd gt DataType FS DEV SD CARD DATA TYPE MULTIPLE BLOCK transfer mode BIT TRANSFER MODE MULTIPLE BLOCK BIT TRANSFER MODE AUTO CMD12 BIT TRANSFER MODE BLOCK COUNT ENABLE if p cmd gt DataDir FS DEV SD CARD DATA DIR CARD TO HOST transfer mode BIT TRANSFER MODE READ BIT TRANSFER MODE DMA ENABLE else transfer mode BIT TRANSFER MODE DMA ENABLE command CPU INT16U p cmd gt Cmd lt lt 8 Calc command register value 3 if DEF BIT IS SET p cmd gt Flags FS DEV SD CARD CMD FLAG DATA START DEF YES command BIT COMMAND DATA PRESENT if DEF BIT IS SET p cmd gt Flags FS DEV SD CARD CMD FLAG IX VALID DEF YES command BIT COMMAND DATA COMMAND IX CHECK if DEF BIT IS SET p cmd gt Flags FS DEV SD CARD CMD FLAG CRC VALID DEF YES command BIT COMMAND DATA COMMAND CRC CHECK if DEF BIT IS SET p cmd gt Flags FS DEV SD CARD CMD FLAG RESP DEF YES if DEF BIT IS SET p cmd gt Flags FS DEV SD CARD CMD FLAG RESP LONG DEF YES command E BIT COMMAND DATA COMMAND RESPONSE LENGTH 136 else if DEF BIT IS SET p cmd gt Flags FS DEV SD CARD CMD FLAG BUSY DEF YES command BIT COMMAND DATA COMMAND RESPONSE LENGTH 48 else command BIT COMMAND DATA COMMAND RESPONSE LENGTH 48 BUSY Write registers to exec cmd 4 REG SDMA ADDESS
41. DEV DRV structure that is registered with the file system with FS_DevDrvAdd as part of application start up immediately following FS Init Several restrictions are enforced to preserve the uniqueness of device drivers and simplify management B Each device driver must have a unique name B No driver may be registered more than once B Device drivers cannot be unregistered B All device driver functions must be implemented even if one or more is empty 111 Chapter 9 9 1 PROVIDED DEVICE DRIVERS Portable device drivers are provided for standard media categories B RAM disk driver The RAM disk driver supports using internal or external RAM as a storage medium E SD MMC driver The SD MMC driver supports SD SD high capacity and MMC cards including micro and mini form factors Either cardmode and SPI mode can be used B NAND driver The NAND flash driver support parallel typically ONFI compliant NAND flash devices B NOR driver The NOR flash driver support parallel typically CFI compliant and serial typically SPI NOR flash devices E MSC driver The MSC Mass Storage Class driver supports USB host MSC devices Oe thumb drives or USB drives via pC USB Host Table 9 1 summarizes the drivers driver names and driver API structure names If you require more information about a driver please consult the listed chapter Driver Driver Name Driver API Structure Name Reference RAM disk ram
42. DEV SD CARD CMD FLAG BUSY Busy signal expected after command FS DEV SD CARD CMD FLAG CRC VALID CRC valid after command FS DEV SD CARD CMD FLAG IX VALID Index valid after command FS DEV SD CARD CMD FLAG OPEN DRAIN Command line is open drain FS DEV SD CARD CMD FLAG DATA START Data start command FS DEV SD CARD CMD FLAG DATA STOP Data stop command FS DEV SD CARD CMD FLAG RESP Response expected FS DEV SD CARD CMD FLAG RESP LONG Long response expected E p cmd gt DataDir indicates the direction of any data transfer that should follow this command if any FS DEV SD CARD DATA DIR NONE No data transfer FS DEV SD CARD DATA DIR HOST TO CARD Transfer host to card write FS DEV SD CARD DATA DIR CARD TO HOST Transfer card to host read 432 E p cmd gt DataType indicates the type of the data transfer that should follow this command if any FS DEV SD CARD DATA TYPE NONE FS DEV SD CARD DATA TYPE SINGLE BLOCK FS DEV SD CARD DATA TYPE MULTI BLOCK FS DEV SD CARD DATA TYPE STREAM No data transfer Single data block Multiple data blocks Stream data E p cmd gt RespType indicates the type of the response that should be expected from this command FS DEV SD CARD RESP TYPE NONE FS DEV SD CARD RESP TYPE R1 FS DEV SD CARD RESP TYPE R1B FS DEV SD CARD RESP TYPE Ri FS DEV SD CARD RESP TYPE R3 FS DEV SD CARD RESP TYPE R4 FS DEV SD CARD RESP TYPE BS FS DEV SD CARD RESP TYPE R5B FS DEV SD CARD RESP TYPE Be FS DEV SD C
43. Device is not present FS_ERR_DEV_TIMEOUT Device timeout 421 Appendix C RETURNED VALUE None NOTES WARNINGS 1 Tracking whether a device is open is not necessary because this should only be called when a device is open 2 The device driver Wr function is called while the caller holds the device lock 422 C 4 7 Query static void FSDev Query FS DEV p dev FS DEV INFO p info FS ERR p err File Called from Code enabled by fs dev HH c FSDev_Open N A FSDev Refresh FSDev_QueryLocked The device driver Query function gets information about a device ARGUMENTS p_dev Pointer to device to query p_info Pointer to structure that will receive device information p_err Pointer to variable that will receive the return error code from this function FS_ERR_ NONE Device information obtained FS ERR DEV INVALID UNIT NBR Device unit number is invalid FS ERR DEV NOT OPEN Device s not open FS ERR DEV NOT PRESENT Device is not present RETURNED VALUE None NOTES WARNINGS 1 Tracking whether a device is open is not necessary because this should ONLY be called when a device is open 2 The device driver Query function is called while the caller holds the device lock For more information about the FS_DEV_INFO structure see section D 2 FS_DEV_INFO on page 484 423 Appendix C C 4 8 IOC static void FSDev IO Ctrl FS DEV FS IO CTRL CMD cmd File Void FS ERR Cal
44. ERR OS LOCK TIMEOUT Time out waiting for device access lock RETURNED VALUE None NOTES WARNINGS None 273 Appendix A A 3 2 FSDev_AccessUnlock void FSDev AccessUnlock CPU CHAR name dev FS ERR p err File Called from Code enabled by fs dev c Application N A Release exclusive access to a device See also section 5 4 Raw Device IO on page 72 ARGUMENTS name dev Device name p err Pointer to variable that will receive return error code from this function FS ERR NONE FS ERR DEV NOT OPEN FS ERR NAME NULL RETURNED VALUE None NOTES WARNINGS None 274 Device removed successfully Device is not open Argument name dev passed a NULL pointer A 3 3 FSDev_Close void FSDev_Close CPU CHAR name dev FS_ERR p err File Called from Code enabled by fs_dev c Application N A Close and free a device ARGUMENTS name_dev Device name p err Pointer to variable that will receive return error code from this function FS ERR NONE Device removed successfully FS ERR DEV NOT OPEN Device is not open FS ERR NAME NULL Argument name dev passed a NULL pointer RETURNED VALUE None NOTES WARNINGS None 275 Appendix A A 3 4 FSDev_GetDevName void FSDev_GetDevName FS OTY dev_nbr CPU CHAR name dev File Called from Code enabled by fs deu Application N A Get name of the nth open device dev nbr should be between 0 and th
45. EXT EN FS CFG ARG CHK EXT EN allows code to be generated to check arguments for functions that can be called by the user and for functions which are internal but receive arguments from an API that the user can call FS_CFG_ARG CHK _DBG_EN FS CFG ARG CHK DBG EN allows code to be generated which checks to make sure that pointers passed to functions are not NULL that arguments are within range etc 504 E 6 FILE SYSTEM COUNTER CONFIGURATION HC FS contains code that increments counters to keep track of statistics such as the number of packets received the number of packets transmitted etc Also uC FS contains counters that are incremented when error conditions are detected FS_CFG_CTR_STAT_EN FS_CFG CTR STAT EN determines whether the code and data space used to keep track of statistics will be included When DEF_ENABLED statistics counters will be maintained FS_CFG_CTR_ERR_EN FS_CFG CTR STAT EN determines whether the code and data space used to keep track of errors will be included When DEF_ENABLED error counters will be maintained E 7 FAT CONFIGURATION Configuration constants can be used to enable disable features within the FAT file system driver FS Pat CFG LEN EN FS FAT CFG LFN EN is used to control whether long file names LFNs are supported When DEF_DISABLED all file names must be valid 8 3 short file names FS_FAT CFG FAT12_EN FS FAT CFG FAT12 EN is used to control whether FAT12 is supported When DEF DISABLED
46. FILE ACCESS MODE RD File opened for reads FS FILE ACCESS MODE WR File opened for writes FS FILE ACCESS MODE CREATE File will be created if necessary FS FILE ACCESS MODE TRUNC File length will be truncated to 0 FS FILE ACCESS MODE APPEND All writes will be performed at EOF FS FILE ACCESS MODE EXCL File will be opened if and only if it does not already exist FS FILE ACCESS MODE CACHED File data will be cached For example if you wanted to create a file to write to if and only if it does not exist you would use the flags FS FILE ACCESS MODE WR FS FILE ACCESS MODE CREATE FS FILE ACCESS MODE EXCL It is impossible to do this in a single atomic operation using fs_fopen 85 Chapter 6 The table below lists the mode flag equivalents of the s_fopen mode strings upr or rb FS FILE ACCESS MODE_RD w or wb FS FILE ACCESS MODE WR FS FILE ACCESS MODE CREATE FS FILE ACCESS MODE TRUNC a or ab FS FILE ACCESS MODE WR FS FILE ACCESS MODE CREATE FS FILE ACCESS MODE APPEND rt or rbt or r b FS FILE ACCESS MODE RD FS FILE ACCESS MODE WR wH or wbt or wtb FS FILE ACCESS MODE RD FS FILE ACCESS MODE WR FS FILE ACCESS MODE CREATE FS FILE ACCESS MODE TRUNC at or abt or atb FS FILE ACCESS MODE RD FS FILE ACCESS MODE WR FS FILE ACCESS MODE CREATE FS FILE ACCESS MODE APPEND Tabl
47. FS ERR ENTRY RD ONLY FS ERR ENTRY ROOT DIR FS ERR ENTRY TYPE INVALID FS ERR ENTRY OPEN B 9 FILE ERROR CODES FS ERR FILE ALREADY OPEN FS ERR FILE BUF ALREADY ASSIGNED FS ERR FILE ERR FS ERR FILE INVALID ACCESS MODE FS ERR FILE INVALID ATTRIB FS ERR FILE INVALID BUF MODE FS ERR FILE INVALID BUF SIZE FS ERR FILE INVALID DATE TIME FS ERR FILE INVALID DATE TIME FLAG FS ERR FILE INVALID NAME FS ERR FILE INVALID ORIGIN FS ERR FILE INVALID OFFSET FS ERR FILE INVALID FILES FS ERR FILE INVALID OP FS ERR FILE INVALID OP SEQ FS ERR FILE INVALID POS FS ERR FILE LOCKED 396 Paths do not both specify files OR directories Paths specify file system entries on different vols File system entry is corrupt File system entry exists File system entry invalid File system entry NOT a directory File system entry NOT empty File system entry NOT a file File system entry NOT found Entry parent NOT found Entry parent NOT a directory File system entry marked read only File system entry is a root directory File system entry type is invalid Operation not allowed on entry corresponding to an open file dir File already open Buf already assigned Error indicator set on file Access mode is specified invalid Attributes are specified invalid Buf mode is specified invalid or unknown Buf size is specified invalid Date time is specified invalid Date time flag is specified invalid Name is specified invali
48. FSVol Open CPU CHAR name vol CPU_CHAR name_dev FS PARTITION NBR partition nbr FS ERR p err File Called from Code enabled by fs vol c Application Open a volume ARGUMENTS name vol name dev Device name partition nbr p err See Note 2 FS ERR NONE FS ERR DEV VOL OPEN FS ERR INVALID SIG FS ERR NAME NULL FS ERR PARTITION INVALID NBR FS ERR PARTITION NOT FOUND FS ERR VOL ALREADY OPEN FS ERR VOL INVALID NAME FS ERR VOL NONE AVAIL N A Volume name See Section 2 04 for information about device names Partition number If 0 the default partition will be mounted Pointer to variable that will receive the return error code from this function Volume opened Volume open on device Invalid MBR signature Argument name vol name dev passed a NULL pointer Invalid partition number Partition not found Volume is already open Volume name invalid No volumes available Or device access error see section B 4 Device Error Codes on page 394 350 RETURNED VALUE None NOTES WARNINGS If FS ERR PARTITION NOT FOUND is returned then no valid partition or valid file system was found on the device It is still placed on the list of used volumes however it cannot be addressed as a mounted volume eg files cannot be accessed Thereafter unless a new device is inserted the only valid commands are FSVol Fmt which creates a file system on the device FSVol_Close
49. II pC OS II and the RTOS layer files for these RTOS are found in the following directories Micrium Software uC C1k 0S uCOS II clk_os c Micrium Software uC C1k 0S uCOS III clk_os c Source This directory contains the CPU independant source code for wC Clk All file in this directory should be included in the build assuming the presence of the source code Features that are not required will be compiled out based on the value of define constants in clk_cfg h 40 LIC CRC Checksums and Error Correction Codes 3 7 HC CRC CHECKSUMS AND ERROR CORRECTION CODES HC ERC consists of functions to compute different error detection and correction codes The functions are speed optimized to avoid the important impact on performances that these CPU intensive calcutions may present Micrium Software uC CRC Cfg Template erc_cfg h Ports lt architecture gt lt compiler gt ecc_hamming a asm edc_crc_a asm Source edc_crc h edc_crc c ecc_hamming h ecc_hamming c ecc h erc_util h erc_util c Micrium This directory contains all software components and projects provided by Micrium Software This sub directory contains all the software components and projects uC CRC This is the main pC CRC directory Cfg Template This directory contains a configuration template file erc_efg h that must be copied to the application directory to configure the pC CRC module based on application requirements 41 Chap
50. The driver configuration defines available in the configuration file are listed below FS_NAND CFG AUTO SYNC_EN This define determines if for each operation on the device i e each call to the device s APD the metadata should be synchronized Synchronizing at the end of each operation is safer it ensures the device can be remounted and appear exactly as it should Disabling automatic synchronization can result in a large write speed increase as the metadata won t be committed automatically unless triggered by the application If a power down occurs between a device operation and a sync operation the device will appear as it was in a prior state when remounted Device synchronization can be forced with a call to FSDev_Sync 171 Chapter 13 Note that using large write buffers will reduce the metadata synchronization performance hit as fewer calls to the device API will be needed FS_NAND_ CFG _UPDATE_BLK_META CACHE EN This define determines if for each update block the metadata will be cached Enabling this will allow searching for a specific updated sector through data in RAM instead of accessing the device which would require additional read page operations More RAM will be consumed if this option is enabled but write read speed will be improved RAM usage lt Nbr update blks gt x log2 lt Max associativity gt log2 lt Nbr secs per blk gt 8 octets The result should be rounded up FS_NAND CFG DIRTY MA
51. VOS lt template gt fs_os c lt Cfg fs_os h lt Cfg lt rtos_name gt fs_os c fs_os h Source fs_c fs h fs_api c fs_api h fs_buf c 55 Chapter 3 fs_buf h fs_cache c fs_cache h fs_cfg_fs h fs_ctr h fs_def h fs_dev c fs_dev h fs_dir c fs_dir h fs_entry c fs_entry h fs_err h fs_file c fs_file h fs_inc h fs_partition c fs_partition h fs_sys c fs_sys h fs_type h fs_unicode c fs_unicode h fs_util c fs_util h fs_vol c fs_vol h lt architecture gt lt compiler gt os_cpu h os_cpu_a asm os_cpu_c c uC CPU 56 cpu_core c cpu_core h cpu_def h C g Template Summary cpu_cfg h lt Cfg lt architecture gt lt compiler gt cpu h cpu_a asm cpu_c c uC Clk Cfg Template clk_cfg h lt Cfg VOS lt rtos_name gt clk_os c Source clk c clk h uC CRC Cfg Template erc_cfg h lt Cfg Ports lt architecture gt lt compiler gt ecc_hamming a asm edc_crc_a asm Source edc_crc h edc_crc c ecc_hamming h ecc_hamming c ecc h uC LIB lib_ascii c lib ascii h lib def bh lib math c lib math h lib mem c 57 Chapter 3 58 lib mem h lib str c lib str h Ccfg Template lib_cfg h lt Cfg Chapter Useful Information 4 1 NOMENCLATURE This manual uses a set of terms to consistently describe operation of uC FS and its hardware and software environment The following is a small list of thes
52. a file system device The parameters are the device name la and a pointer to a device driver specific configuration structure 1b The device name la is composed of a device driver name sdcard a single colon an ASCII formatted integer the unit number and another colon Since the SD MMC CardMode driver requires no configuration the configuration structure 1b should be passed a NULL pointer Since SD MMC are often removable media it is possible for the device to not be present when FSDev_Open is called The device will still be added to the file system and a volume opened on the not yet present device When the volume is later accessed the file system will attempt to refresh the device information and detect a file system see section 5 2 Using Devices on page 69 for more information FSVol_Open opens mounts a volume The parameters are the volume name 2a the device name 2b and the partition that will be opened 2c There is no restriction on the volume name 2a however it is typical to give the volume the same name as the underlying device If the default partition is to be opened or if the device is not partitioned then the partition number 2c should be zero Using the SD MMC CardMode Driver If the SD MMC initialization succeeds the file system will produce the trace output as shown in Figure 12 1 if a sufficiently high trace level is configured See section E 9 Trace Configuration on page 5
53. address of block relative to start of device size Size of block in octets p err Pointer to variable that will the receive return error code from this function FS ERR NONE Block erased successfully FS ERR NAME NULL FS ERR DEV INVALID FS ERR DEV NOT OPEN FS ERR DEV NOT PRESENT FS ERR DEV INVALID LOW FMT FS ERR DEV IO FS ERR DEV TIMEOUT Argument name dev passed a NULL pointer Argument name dev specifies an invalid device Device is not open Device is not present Device needs to be low level formatted Device I O error Device timeout 383 Appendix A RETURNED VALUE None NOTES WARNINGS The device must be a NOR device e g nor 0 Care should be taken if this function is used while a file system exists on the device or if the device is low level formatted The erased block is NOT validated as being outside any existing file system or low level format information 384 A 11 9 FSDev_NOR_PhyEraseChip void FSDev NOR PhyEraseChip CPU CHAR name dev FS ERR p err File Called from Code enabled by fs dev nor c Application N A Erase entire NOR device ARGUMENTS name dev Device name see Note p err Pointer to variable that will the receive return error code from this function FS ERR NONE Device erased successfully FS ERR NAME NULL Argument name dev passed a NULL pointer FS ERR DEV INVALID Argument name dev specifies an invalid device FS ERR DEV NOT OPEN Device is no
54. based upon returned error values may be useful while debugging a port Read the response if any Note that the order in which a long response is stored in the buffer may oppose its storage in the controller s register or FIFO 439 Appendix C C 5 5 FSDev SD Card BSP_CmdDataRd void FSDev SD Card BSP CmdDataRd FS OTY unit nbr FS DEV SD CARD CMD p cmd void p dest FS DEV SD CARD ERR p err File Called from Code enabled by fs dev sd card bsp c FSDev_SD Card RdData N A Read data following a command ARGUMENTS unit nbr Unit number of SD MMC card p cmd Pointer to command that was started p dest Pointer to destination buffer p err Pointer to variable that will receive the return error code from this function FS DEV SD CARD ERR NONE No error FS DEV SD CARD ERR NO CARD No card present FS DEV SD CARD ERR UNKNOWN Unknown or other error FS DEV SD CARD ERR WAIT TIMEOUT Timeout in waiting for data FS DEV SD CARD ERR DATA OVERRUN Data overrun FS DEV SD CARD ERR DATA TIMEOUT Timeout in receiving data FS DEV SD CARD ERR DATA CHKSUM Error in data checksum FS DEV SD CARD ERR DATA START BIT Data start bit error FS DEV SD CARD ERR DATA Other data error RETURNED VALUE None NOTES WARNINGS None 440 EXAMPLE The implementation of FSDev_SD Card BSP CmdDataRd in Listing C 9 is targeted for the same host controller as the other listings in this chapter for more information see F
55. be set to the size of the available blocks table Available blocks are ready to be erased and used as update or data blocks The table must at least be large enough to contain the reserved available blocks see section FS_NAND_CFG_RSVD_AVAIL_BLK_CNT on page 173 and a few more for general operations The value FS _NAND CFG DEFAULT instructs the translation layer to use 10 or 1 FS _NAND CFG RSVD AVAIL BLK CNT entries whichever is larger 177 Chapter 13 13 3 2 TRANSLATION LAYER SOURCE FILES The files relevant to the NAND translation layer are outlined in this section the generic file system files outlined in Chapter 3 uC FS Directories and Files on page 29 are also required Micrium Software uC FS Dev NAND This directory contains the NAND driver files fs_dev_nand These files compose the NAND translation layer These following source files contain the code for the NAND translation layer Cfg Template fs_dev_nand_cfg h This is a template file that is required to be copied to the application directory to configure the uC FS NAND driver based on application requirements 13 4 CONTROLLER LAYER The controller layer implementations distributed with the NAND driver see Table 13 1 support a wide variety of flash devices from major vendors Driver API Files FS_NAND CtrlrGen fs_dev_nand_ctrir_gen in Micrium Software uC FS Dev NA ND Ctrlr Description Supports most parallel flash de
56. being folded Each update block can be of one of the two sub types random update blocks RUBs and sequential update blocks SUBs Sequential update blocks can only refer to a single data block associativity is always 1 Also they must use the same exact layout as a data block i e logical sector 0 written at physical sector 0 logical sector 1 written at physical sector 1 etc The advantage of SUBs is that they have a much lower merge cost They can be converted into data blocks in place by copying missing sectors from the associated data block and updating some metadata Random update blocks on the other hand can contain sectors from multiple data blocks Those sectors can be written at any location in the RUB since it contains additional metadata to map each sector to an appropriate location in a data block resulting in an increased merge cost but allowing for better wear leveling since it leads to better block usage in the case of random writes Another important functionality of the translation layer is to keep track of the number of erase operations performed on each block The erase count is critical for two reasons First the erase count can be used to efficiently drive the wear leveling algorithm allowing seldom erased blocks to be preferred over frequently erased blocks when a new block is required Secondly the erase count allows the translation layer to detect the blocks that have reached their erase limit 170 NAND Tran
57. between the logical addresses of the blocks and their physical locations is used to enable wear leveling This mapping as well as other metadata is contained in metadata blocks Typically only one block is used to store metadata This block is also moved around for wear leveling reasons 169 Chapter 13 The third type of blocks are update blocks All data written on the device must first be written through update blocks Under specific circumstances including an update block becoming full the contents of an update block are folded onto data blocks The folding operation roughly consists of three steps The first step is to find an unused block and erase it Secondly the contents of the corresponding data block must be merged with the more recent but incomplete data contained in the update block This merged data is written in the recently erased block Once this operation is complete metadata must be updated the old data block and the update block are marked as free to erase and use and the block mapping must be updated to point to the new data block In this implementation it is possible to specify how many different data blocks pointed to by a single update block This specification is called maximum associativity see the configuration field RUB_MaxAssoc in section Device configuration on page 175 If this value is greater than one the merge operation must be performed for each data block associated with the update block
58. by fs file c Application fs fflush FS _CFG FILE PUE EN Flush buffer contents to file See fs fflush for more information ARGUMENTS p file Pointer to a file p err Pointer to variable that will receive the return error code from this function FS ERR NONE File buffer flushed successfully FS ERR NULL PIR Argument p file passed a NULL pointer FS ERR INVALID TYPE Argument p file s type is invalid or unknown FS ERR FILE NOT OPEN File NOT open RETURNED VALUE None NOTES WARNINGS None 315 Appendix A A 6 3 FSFile_Close void FSFile Close FS FILE p file FS ERR p err File Called from Code enabled by fs file c Application N A fs fclose Close and free a file See fs fclose for more information ARGUMENTS p file Pointer to a file p err Pointer to variable that will the receive return error code from this function FS ERR NONE File closed FS ERR NULL PIR Argument p file passed a NULL pointer FS ERR INVALID TYPE Argument p file s type is invalid or unknown FS ERR FILE NOT OPEN File NOT open RETURNED VALUE None NOTES WARNINGS None 316 A 6 4 FSFile_ClirErr void FSFile ClrErr FS FILE p file FS ERR p err File Called from Code enabled by fs file c Application N A fs_clearerr Clear EOF and error indicators on a file See fs_clearerr for more information ARGUMENTS p_file Pointer to a file p err Poi
59. c FSDev_SD Card Refresh N A Set data timeout ARGUMENTS unit nbr Unit number of SD MMC card to ms Timeout in milliseconds RETURNED VALUE None NOTES WARNINGS None C 6 SD MMC SPI MODE BSP SD MMC card can also be accessed through an SPI bus also described as the one wire mode Please refer to section C 7 SPI BSP on page 453 for the details on how to implement the software port for your SPI bus 452 C 7 SPI BSP Among the most common and simplest serial interfaces supported by built in CPU peripherals is Serial Peripheral Interface SPI Four hardware signals connect a defined master or host to each slave or device a slave select a clock a slave input and a slave output Three of these all except the slave select may be shared among all slaves though hosts often have several SPI controllers to simplify integration and allow simultaneous access to multiple slaves Serial flash serial EEPROM and SD MMC cards are among the many devices which use SPI Signal Description SSEL CS Slave select SCLK Clock SO MISO Slave output master input SI MOST Slave input master output Table C 3 SPI signals No specification exists for SPI a condition which invites technological divergence So though the simplicity of the interface limits variations between implementations the required transfer unit length shift direction clock frequency and clock polarity and phase do vary from
60. choices First block data can typically be read written either directly from a FIFO or transferred automatically by the peripheral to from a memory buffer with DMA While the former approach may be simpler no DMA controller need be setup it may not be reliable Unless the host can stop the host clock upon FIFO underrun for write or overrun for read effectively pausing the operation from the card s perspective transfers at high clock frequency or multiple bus configurations will probably fail Interrupts or other tasks can interrupt the operation or the CPU just may be unable to fill the FIFO fast enough DMA avoids those pitfalls by offloading the responsibility for moving data directly to the CPU Second the completion of operations such as command execution and data read write are often signaled via interrupts unless some error occurs whereupon a different interrupt is triggered During large transfers these operations occur frequently and the typical wait between initiation and completion is measured in microseconds On most platforms polling the interrupt status register within the task performs better G e results in faster reads and writes than waiting on a semaphore for an asynchronous notification from the ISR because the penalty of extra context switches is not incurred 428 C 5 1 FSDev SD Card BSP Open CPU BOOLEAN FSDev SD Card BSP Open FS OTY unit nbr File Called from Code enabled by fs dev sd c
61. cluster A lost cluster is marked as allocated in the FAT but is not linked to any file Optionally lost cluster chains may be recovered to a file 10 6 OPTIONAL JOURNALING SYSTEM Since cluster allocation information is stored separately from file information and directory entries even file operations that make a simple change to one file eg adding data to the end of a file updating data in place are non atomic An atomic operation is made up of a set of sub operations which must all be completed the atomic operation is completed successfully only if all the sub operations complete successfully The repercussions can be innocuous e g wasted disk space or very serious corrupted directories corrupted files and lost data see section 10 5 Sources of Corruption in FAT volumes on page 127 127 Chapter 10 One way that uC FS reduces the risk of corruption by ordering modifications wisely for example by forcing an update to the FAT after every Write operation It also has an optional journaling system that allows you to log data about impending and completed changes to files and directories Without the journaling system any atomic operation even a single Write operation at the API level can be interrupted by a power failure or a crash of the application or the operating system Accordingly FAT file systems without journaling are not fail safe Journaling means that a file system logs all changes to a journal befor
62. comparison the driver for a raw NAND flash is more complicated Flash is divided into large blocks often 16 kB to 512 kB however the high level software for example a FAT file system expects to read or write small sectors 512 bytes to 4096 bytes atomically The driver implements a NAND block abstraction to conceal the device geometry from the file system To aggravate matters each block may be subjected to a finite number of erases A wear leveling algorithm must be employed so that each block is used equally All these mechanisms are grouped in the main layer of the driver called the NAND translation layer The NAND flash driver included in pC FS has the following features Dynamic wear leveling Using logical block addressing the driver is able to change the physical location of written data on the NAND flash so that a single memory location does not wear early while other locations are not used Fail safe to unexpected power loss The NAND flash driver was designed so that write transactions are atomic After an unexpected power down the NAND flash s low level format will still be consistent the device will be remounted as if the transaction never occurred Scalable Various configuration options see section 13 3 1 Translation Layer Configuration on page 171 are available for you to adjust the memory footprint the speed and the wear leveling performance of the driver Flexible controller layer You can provide your
63. consisting of a few semaphores in order to prevent simultaneous access to core structures from different tasks If you are not using a RTOS this port layer may consist of empty functions 16 Typical Usages 1 2 TYPICAL USAGES Applications have sundry reasons for non volatile storage A subset require or benefit from organizing data into named files within a directory hierarchy on a volume basically from having a file system Perhaps the most obvious expose the structure of information to the user like products that store images video or music that are transferred to or from a PC A web interface poses a similar opportunity since the URLs of pages and images fetched by the remote browser would resolve neatly to locations on a volume Another typical use is data logging A primary purpose of a device may be to collect data from its environment for later retrieval If the information must persist across device reset events or will exceed the capacity of its RAM some non volatile memory is necessary The benefit of a file system is the ability to organize that information logically with a fitting directory structure through a familiar API A file system can also store programs In a simple embedded CPU the program is stored at a fixed location in a non volatile memory usually flash If an application must support firmware updates a file system may be a more convenient place since the software handles the details of storing the pr
64. contents to file ARGUMENTS p file Pointer to a file RETURNED VALUE 0 if flushing succeeds FS_EOF otherwise NOTES WARNINGS B Ifthe most recent operation is output write all unwritten data is written to the file B If the most recent operation is input read all buffered data is cleared 242 A 2 10 fs_fgetpos int fs fgetpos FS FILE p file fs fpos t p pos File Called from Code enabled by fs_api c Application FS CFG API EN Get file position indicator ARGUMENTS p_file Pointer to a file D Dos Pointer to variable that will receive the file position indicator RETURNED VALUE 0 if no error occurs Non zero value otherwise NOTES WARNINGS B The return value should be tested against 0 rtn fs fgetpos p file amp pos if rtn 0 No error occurred else Handle error E The value placed in pos should be passed to FS_fsetpos to reposition the file to its position at the time when this function was called 243 Appendix A A 2 11 fs_flockfile void fs flockfile FS FILE p file File Called from Code enabled by fs_api c FS CFG FILE LOCK EN Application FS CFG API EN and Acquire task ownership of a file ARGUMENTS p file Pointer to a file RETURNED VALUE None NOTES WARNINGS A lock count is associated with each file B The file is unlocked when the lock count is zero B Ifthe lock count is positive a task owns
65. default value is 255 the maximum file name length for FAT long file names FS_CFG_MAX DEV_DRV_NAME LEN FS CFG MAX DEV DRV NAME LEN configures the maximum device driver name length in characters not including the final NULL character The default value is 10 503 Appendix E FS_CFG MAX DEV_NAME LEN FS CFG MAX DEV NAME LEN configures the maximum device name length in characters not including the final NULL character The default value is 15 FS_CFG MAX VOL NAME LEN FS CFG MAX VOL NAME LEN configures the maximum volume name length in characters not including the final NULL character The default value is 10 E 4 DEBUG CONFIGURATION A fair amount of code in uC FS has been included to simplify debugging There are several configuration constants used to aid debugging FS_CFG_DBG_MEM CLR_EN FS CFG DBG MEM CLR EN is used to clear internal file system data structures when allocated or deallocated When DEF_ENABLED internal file system data structures will be cleared FS_CFG_DBG_WR_VERIFY_EN FS CFG DBG WR VERIFY EN is used verify writes by reading back data This is a particularly convenient feature while debugging a driver E 5 ARGUMENT CHECKING CONFIGURATION Most functions in uC FS include code to validate arguments that are passed to it Specifically uC FS checks to see if passed pointers are NULL if arguments are within valid ranges etc The following constants configure additional argument checking FS_CFG_ARG CHK
66. device configuration p err see Note 2 FS ERR NONE FS ERR DEV ALREADY OPEN FS ERR DEV INVALID LOW FMT FS ERR DEV INVALID NAME FS ERR DEV INVALID SEC SIZE FS ERR DEV INVALID SIZE FS ERR DEV INVALID UNIT NBR FS ERR DEV IO FS ERR DEV NONE AVAIL FS ERR DEV NOT PRESENT FS ERR DEV TIMEOUT FS ERR DEV UNKNOWN FS ERR NAME NULL RETURNED VALUE None Pointer to variable that will receive the return error code from this function Device opened successfully Device is already open Device needs to be low level formatted Specified device name not valid Invalid device sector size Invalid device size Specified unit number invalid Device I O error No devices available Device is not present Device timeout error Unknown device error Argument name dev passed a NULL pointer 281 Appendix A NOTES WARNINGS The return error code from the function SHOULD always be checked by the calling application to determine whether the device was successfully opened Repeated calls to FSDev_Open resulting in errors that do not indicate failure to open such as FS ERR DEV LOW FMT INVALID without matching FSDev_Close calls may exhaust the supply of device structures 282 If FS_ERR_NONE is returned then the device has been added to the file system and is immediately accessible If FS DEV INVALID LOW FMT is returned then the device has been added to the file system but needs to be low level formatted th
67. device to device Take as an example Figure C 3 which gives the bit form of a basic command response exchange on a typical serial flash The command and response both divide into 8 bit chunks the transfer unit for the device Within these units the data is transferred from most significant bit MSB to least significant bit LSB which is the slave s shift direction Though not evident from the diagram the horizontal axis being labeled in clocks rather than time the slave cannot operate at a frequency higher than 20 MHz Finally the clock signal prior to slave select activation is low clock polarity or CPOL is 0 and data is latched on the rising clock edge clock phase or CPHA is 0 Together those are the aspects of SPI communication that may need to be configured B Transfer unit length A transfer unit is the underlying unit of commands responses and data The most common value is eight bits though slaves commonly require and masters commonly support between 8 and 16 bits P Shift direction Either the MSB or LSB of each transfer unit can be the first transmitted on the data line 453 Appendix C B Clock frequency Limits are usually imposed upon the frequency of the clock signal Of all variable SPI communication parameters only this one is explicitly set by the device driver B Clock polarity and phase CPOL and CPHA SPI communication takes place in any of four modes depending on the clock phase and clock polarity
68. driver The following directory must be on the project include path B Mierium Software uC FS Dev MSC Before uC FS is initialized the pC USB host stack must be initialized as shown in Listing 15 1 The file system initialization function FS_Init must then be called and the MSC driver FSDev_MSC restivered using FS_DevDrvAdd The USB notification function should add remove devices when events occur as shown in Listing 15 1 ROM RAM characteristics and performance benchmarks of the MSC driver can be found in section 9 1 1 Driver Characterization on page 113 static void App InitUSB Host void USBH_ERR err err USBH HostCreate amp App USB Host amp USBH_AT91SAM9261 Drv if err USBH_ERR_NONE return err USBH_HostInit amp App USB Host if err USBH_ERR_NONE return USBH_ClassDrvReg amp App USB Host amp USBH MSC ClassDrv USBH_ CLASS NOTIFY FNCT App USB HostMSC ClassNotify void 0 Listing 15 1 Example pC USB initialization 220 Using the MSC Driver static void App USB HostMSC ClassNotify void pclass dev CPU INTO8U is conn void pctx USBH_MSC_DEV p_msc_dev USBH_ERR usb_err FS_ERR fs_err p_msc_dev USBH_MSC_DEV pclass_dev switch is_conn case USBH CLASS DEV STATE CONNECTED MASS STORAGE DEVICE CONN D z usb err USBH MSC RefAdd p msc_dev if usb err USBH ERR NONE FSDev_ MSC DevOpen p msc_dev amp fs err break case USB
69. ee LT aana E 260 TS E e VT EE 261 fe renamel EEN 263 fS rewind EE 265 ER e ue EE 266 ES d TU EE 267 S SStVDU EN 268 Device FUNCTIONS seissen 270 FSDeV ACGSSSLOEK nessen sene deg eer cn a ar a EES SEN ees 273 FSDev AccessUnlock naan nee REENEN 274 EEE e E E E A cde chsdaucceveleeneredss 275 FSDev_GetDevName annen eeseeenenenennenanennneneennsene eenen 276 FSDev GetDevGnt nrs nsi detent detente eden EEN 277 FSDev_GetDevCntMax cccccceceeeeeseeeeeeceeeeeeeeeeeeseeeeseeneeeeeseeeees 278 FSDev_GetNbrPartitions nanus anannenen enne neenenennnnerenreeneeen 279 FSDev Invalidatel sarrssesserseenennernanrenineaeven vireavanndenenendendendeant 280 FSDev Open uusns nana ri beveren evi atten oenen needed 281 FSDev Partition Addl s E 283 FSDev Partition Rind vzrrsnterrrenn ao naaa venten ENEE eee nearness 284 FSDev_Partitioninit annen een enne eenen nennnnevenennnnereerennseen 286 FSDev QUSry ironie dee geed e deeg dennen 287 SCHRETT 288 FSDev Refresh u gege ENEE Egger EE 289 FSDev2 WII zessen geheelt gelee GES 291 Directory Access Functions unnsnannenneneneenenevensenenennnnneennenneenenn 292 PSD Close i EE 293 E Jegen esst degeg ee EES eg 294 FSDir2 el LR 295 A 4 4 A 5 A 5 1 A 5 2 A 5 3 A 5 4 A 5 5 A 5 6 A 5 7 A 6 A 6 1 A 6 2 A 6 3 A 6 4 A 6 5 A 6 6 A 6 7 A 6 8 A 6 9 A 6 10 A 6 11 A 6 12 A 6 13 A 6 14 A 6 15 A 6 16 A 6 17 A 7 A
70. esac 327 FSFil Cette ee den etalk aes 329 FSFie Le A 330 FSFile Truncate turnastsrnerseosernertenddrtanvendeederenvidseeheannddnidnwacdendvenn 332 FSFile Wr oc onervaren order eerden beid venen nde Breanna 333 Volume FUNCTIONS Aaria dnne a een ennrdenannaardenetearieidendanvandannnnnndeedervann 335 FSVol Close ue det ster Rented eneen derven deeded eden et lente deed oS 337 Se d TEE 338 FSVol GetDfltVolName ccccesssecceeeeseeeeeeeeeseaeeeeeeesaeeeeeeseaeseeenenees 340 ESVol GetVolGnt ers deers Zeene Segen ot Zeg id es dis 341 FSVol_ GetVolGntMax nnen en eeneeevenenennenenennnnntenneeneeneen 342 FSVol GetVolName 55 varden deed vaat er weds ae Seege 343 RTR E RL 344 FSVol ISMounted az Eege Eesen dee EES EE ECKE 345 FSVol EabelGet c cch 3 4 nicki eatin iii cea a 346 FSVol LabelSet 2c cccssseisvecststaecs cos ege red teenies ENEE ee 348 Table of Contents A 7 11 A 7 12 A 7 13 A 7 14 A 8 A 8 1 A 8 2 A 8 3 A 9 A 9 1 A 9 2 A 9 3 A 10 A 10 1 A 10 2 A 10 3 A 11 A 11 1 A 11 2 A 11 3 A 11 4 A 11 5 A 11 6 A 11 7 A 11 8 A 11 9 A 12 A 12 1 A 12 2 A 12 3 A 12 4 A 12 5 Appendix B B 1 B 2 B 3 B 4 10 ESVol Open ornin enaa aa Arrar EEOAE RPNE Arr ah eend den nee 350 PSVOl Query EE 352 ESVOliRd iiia A A T A e Dec 353 FSV WED aioin aeni EA AAAA 355 Volume Cache Functions nanne seeneeeneeneenr enn enenannneneenneeneeneen 356 FSVol_ CacheAssign ra
71. file See fs fread for more information ARGUMENTS p file Pointer to a file p dest Pointer to destination buffer size Number of octets to read p err Pointer to variable that will the receive return error code from the function FS_ERR_NONE File read successfully FS_ERR_EOF End of file reached FS ERR NULL PTR Argument p file p dest passed a NULL pointer FS ERR INVALID TYPE Argument p file s type is invalid or unknown FS ERR FILE NOT OPEN File NOT open FS ERR FILE INVALID OP Invalid operation on file FS ERR DEV Device access error 330 RETURNED VALUE The number of bytes read if file read successful 0 otherwise NOTES WARNINGS None 331 Appendix A A 6 16 FSFile_Truncate void FSFile Truncate FS_FILE p file FS FILE SIZE size FS_ERR p err File Called from Code enabled by fs file c Application not FS CG RD ONLY EN fs ftruncate Truncate a file See fs_ftruncate for more information ARGUMENTS p file Pointer to a file size Size of the file after truncation p err Pointer to variable that will the receive return error code from the function FS ERR NONE File truncated successfully FS ERR NULL PTR Argument p file passed a NULL pointer FS ERR INVALID TYPE Argument p file s type is invalid or unknown FS ERR FILE NOT OPEN File NOT open RETURNED VALUE None NOTES WARNINGS None 332 A 6 17 FSFile Wr CPU_SIZE T FSFile Wr FS_FILE p file void p sr
72. fs funlockfile Release task ownership of a file See fs funlockfile for more information ARGUMENTS p file Pointer to a file p err FS ERR NONE FS ERR NULL PTR FS ERR INVALID TYPE FS ERR FILE NOT OPEN FS ERR FILE NOT LOCKED RETURNED VALUE None NOTES WARNINGS None Pointer to variable that will the receive return error code from this function File lock acquired Argument p file passed a NULL pointer Argument p file s type is invalid or unknown File NOT open File NOT locked or locked by different task 323 Appendix A A 6 11 FSFile_Open FS FILE FSFile Open CPU CHAR name full FS FLAGS mode FS ERR p err File Called from Code enabled by fs file c Application N A fs fopen Open a file See fs fopen for more information ARGUMENTS name full Name of the file See section 4 3 uC FS File and Directory Names and Paths on page 62 for information about file names mode File access mode see Notes 1 and 2 p err Pointer to variable that will the receive return error code from this function FS ERR NONE File opened FS ERR NAME NULL Argument name full passed a NULL pointer Or entry error see Section B 04 RETURNED VALUE None NOTES WARNINGS B The access mode should be the logical OR of one or more flags FS FILE ACCESS MODE RD File opened for reads FS FILE ACCESS MODE WR File opened for writes FS FILE ACCESS MODE CREATE File will b
73. functions to get low level card information and read the Card ID and Card Specific Data registers see section A 12 FAT System Driver Functions on page 386 CPU_BOOLEAN App FS AddSD Card void FS_ERR err FS_DevDrvAdd FS_DEV_API amp FSDev_SD Card 1 FS_ERR amp err if err FS ERR NONE amp amp err FS ERR DEV DRV ALREADY ADDED return DEF_FAIL 2 FSDev_Open CPU CHAR sdcard 0 a void 0 CS b PS ERR amp err switch err case FS ERR NONE break case FS ERR DEV case FS ERR DEV IO case FS ERR DEV _TIMEOUT case FS ERR DEV NOT PRESENT return DEF FAIL default return DEF FAIL en E FSVol_Open CPU_CHAR sdcard 0 a CPU_CHAR sdeard 0 ZS b FS PARTITION NBR 0 c FS_ERR serr 139 Chapter 12 switch err case PS ERR NONE APP_TRACE_DBG Opened volume mounted r n break case FS ERR DEV case FS ERR DEV IO case FS ERR DEV TIMEOUT case FS ERR DEV NOT PRESENT case FS ERR PARTITION NOT FOUND APP_TRACE_DBG opened device unmounted r n return DEF FAIL default APP TRACE DG opening volume failed w err d r n r n err return DEF FAIL return DEF OK L12 1 1 L12 1 2 L12 1 3 140 Listing 12 1 Opening a SD MMC device volume Register the SD MMC CardMode device driver FSDev SD Card FSDev_Open opens initializes
74. gen micron ecc h Part fs dev nand part static c fs dev nand part static h fs dev nand part onfi c fs dev nand part _onfi h C g Template fs dev nand cfg h BSP Template fs dev nand ctrlr gen bsp c NOR fs_dev_nor c fs_dev_nor h 53 Chapter 3 PHY fs_dev_nor_amd_1x08 c fs_dev_nor_amd_1x08 h fs_dev_nor_amd_1x16 c fs_dev_nor_amd_1x16 h fs_dev_nor_intel c fs_dev_nor_intel h fs_dev_nor_sst25 c fs_dev_nor_sst25 h fs_dev_nor_sst39 c fs_dev_nor_sst39 h fs_dev_nor_stm25 c fs_dev_nor_stm25 h fs_dev_nor_stm29_1x08 c fs_dev_nor_stm29_1x08 h fs_dev_nor_stm29_1x16 c fs_dev_nor_stm29_1x16 h Template fs_dev_nor_template c lt Cfg fs dev nor template h lt Cfg BSP lt template gt fs dev nor bsp c lt Cfg RAMDisk fs_ dev Com CG fs_ dev ram h SD fs dev sd c fs dev sd h Card fs_dev_sd_card c fs_dev_sd_card h BSP Template fs_dev_sd_card_bsp c lt Cfg SPI fs_dev_sd_spi c fs_dev_sd_spi h BSP Template fs_dev_sd_spi bsp c lt Cfg 54 Summary Template fs_dev_template c lt Cfg fs_dev_template h lt Cfg FAT fs_fat c fs_fat h fs_fat_dir c fs_fat_dir h fs_fat_entry c fs_fat_entry h fs fat fatl2 c fs fat fatl2 h fs fat fatl6 c fs fat fatl6 h fs fat fat32 c fs fat fat32 h fs fat file c fs fat file h fs fat journal c fs fat journal h fs fat lfn c fs fat lfn h fs fat sfn c fs fat sfn h fs fat type h
75. given file It does not even know the name of any files That information is stored in the directory As described in the section above the directory entry for each file contains a value called a cluster address This is a pointer to the first entry in the File Allocation Table for a given file This FAT entry in turn points to the first cluster in the volume s data area that has been allocated to the file If the file has been allocated more than one cluster then the FAT table entry will contain the address of the second cluster which is also the index number of the second cluster s entry in the FAT table The second cluster entry points to the third and so forth A FAT entry like this forms a linked list commonly called a cluster chain Figure 10 3 illustrates the relationship between the directory entry and the FAT 120 Organization of the File Allocation Table One Directory Entry 32 bytes Start of File Cluster example 40 File Allocation Table 4 bytes per entry Figure 10 3 A directory entry points to the first entry in a cluster chain FAT 16 In Figure 10 3 the directory entry for a file points to the 40th entry in the FAT table The 40th entry points to the 41st the 41st to the 46th the 46th is not a pointer as the entry contains a special end of cluster chain marker The means that for Figure 10 3 the 41st cluster is the final cluster allocated to the file Other entries in the FAT area in illustra
76. lt compiler gt This is the name of the compiler or compiler manufacturer used to build the code for the evaluation board The lt and gt are not part of the actual name lt project name gt This is the name of the project that will be demonstrated For example a simple uC FS project might have a project name of FS Ex1 The Ex1 represents a project containing only uC FS A project name of FS Probe Ex1 would represent a project containing uC FS as well as pC Probe The lt and gt are not part of the actual name VK These are the source files for the project product You are certainly welcomed to call the main files APP for your own projects but you don t have to This directory also contains the configuration file FS_CFG H and other files as needed by the project 33 Chapter 3 3 2 CPU As shown below is the directory where we place semiconductor manufacturer peripheral interface source files Of course you can use whatever directory structure suits your project product Micrium Software CPU lt manufacturer gt lt architecture gt Micrium This is where we place all software components and projects provided by Micrium Software This sub directory contains all the software components and projects CPU This sub directory is always called CPU lt manufacturer gt Is the name of the semiconductor manufacturer who provided the peripheral library The ei and g
77. mode strings and mode equivalents 325 Appendix A A 6 12 FSFile_PosGet FS FILE SIZE FSFile PosGet FS FILE p file FS ERR p err File Called from Code enabled by fs file c Application N A fs ftell fs fgetpos Set file position indicator See fs ftell for more information ARGUMENTS p file Pointer to a file p err Pointer to variable that will the receive return error code from the function FS ERR NONE FS ERR NULL PTR FS ERR INVALID TYPE FS ERR FILE NOT OPEN FS ERR FILE INVALID POS RETURNED VALUE The current file position if no errors see Note 0 otherwise NOTES WARNINGS File position gotten successfully Argument p file passed a NULL pointer Argument p file s type is invalid or unknown File NOT open Invalid file position The file position returned is the number of bytes from the beginning of the file up to the current file position 326 A 6 13 FSFile_PosSet void FSFile PosSet FS FILE p file FS FILE OFFSET offset FS FLAGS origin FS ERR p err File Called from Code enabled by fs file c Application N A fs fseek fs fsetpos Get file position indicator See fs fseek for more information ARGUMENTS p file Pointer to a file offset Offset from the file position specified by origin origin Reference position for offset FS FILE ORIGIN START Offset is from the beginning of the file FS FILE ORIGIN CUR Offset is from the current file position FS FIL
78. out LC 6 4 FS OS SemPost signals a semaphore 411 Appendix C C 4 DEVICE DRIVER Devices drivers for the most popular devices are already available for uC FS If you use a particular device for which no driver exist you should read this section to understand how to build your own driver A device driver is registered with the file system by passing a pointer to its API structure as the first parameter of FS_DevDrvAdd The API structure FS DEV API includes pointers to eight functions used to control and access the device const FS DEV API FSDev_ FSDev_ _NameGet FSDev_ _Init FSDev_ _Open FSDev_ _Close FSDev_ Rd if FS CFG RD ONLY EN DEF_DISABLED FSDev_ _Wr endif FSDev_ _Query FSDev_ _I0_Ctrl H The functions which must be implemented are listed and described in Table C 1 The first two functions NameGet and Init act upon the driver as a whole neither should interact with any physical devices The remaining functions act upon individual devices and the first argument of each is a pointer to a FS_DEV structure which holds device information including the unit number which uniquely identifies the device unit member UnitNbr 412 Function Description NameGet Get driver name Init Initialize driver Open Open a device Close Close a device Rd Read from a device Wr Write to a device Query Get information about a d
79. page programming splitting the operation to write a full page into multiple operations that each write a sub section of the page Other devices can only have their pages written in a single operation before they are erased B Some devices must write the pages of a block in a sequential manner page 0 page 1 page 2 etc B Blocks can only be erased a limited number of times typically 10k to 100k before the integrity of the memory is compromised B Some device blocks can t be used reliably and are considered bad blocks These blocks are either marked at the factory or become bad during the device s life B Electric disturbance can cause read errors An error correction mechanism must be used to decrease the bit error rate The role of the translation layer is to translate those NAND flash specific requirements into a disk interface based on sector access This disk interface allows the NAND driver to be used with traditional sector based file systems like FAT which is used by uC FS The translation layer implementation provided with the NAND driver is inspired by the KAST K Associative Sector Translation as proposed by Cho see Appendix G Bibliography on page 535 In the provided implementation three types of blocks are present on the device The data blocks typically occupy the major portion of the storage space Data blocks are used to contain the data written to the device by the application or file system A mapping
80. proper responses are returned The command responses in SPI mode are identical to those in cardmode see Figure 12 5 and Figure 12 6 except each is preceded by a R1 status byte Obvious errors such as improper initialization or failed chip select manipulation will typically be caught here More subtle conditions may appear intermittently during reading or writing 156 Using the SD MMC SPI Driver 12 3 3 SD MMC SPI BSP OVERVIEW An SPI BSP is required so that the SD MMC SPI driver will work on a particular system For more information about these functions see section C 7 SPI BSP on page 453 Function Description FSDev_SD SPI BSP SPI Open Open initialize SPI FSDev SD SPI BSP SPI Close Close uninitialize SPI FSDev_ SD SPI BSP SPI Lock Acquire SPI lock FSDev_SD SPI BSP SPI Unlock Release SPI lock FSDev SD SPI BSP SPI Rd Read from SPI FSDev_SD SPI BSP SPI Wr Write to SPI FSDev_ SD SPI BSP SPI ChipSelEn Enable chip select FSDev SD SPI BSP SPI ChipSelDis Disable chip select FSDev SD SPI BSP SPI SetClkFreg Set SPI clock frequency Table 12 5 SD MMC SPI BSP functions 157 Chapter 12 158 Chapter 13 NAND Flash Driver Standard storage media such as hard drives and managed flash based devices such as SD MMC and CF cards require relatively simple drivers that convert the file system s request to read or write a sector into a hardware transaction In
81. receive the return error code from this function FS ERR NONE Volume formatted FS ERR DEV Device error FS ERR DEV INVALID SIZE Invalid device size FS ERR NAME NULL Argument name vol passed a NULL pointer FS ERR VOL DIRS OPEN Directories open on volume FS ERR VOL FILES OPEN Files open on volume FS ERR VOL INVALID SYS Invalid file system parameters FS ERR VOL NOT OPEN Volume not open REQUIRED CONFIGURATION None 338 NOTES WARNINGS Function blocked if files or directories are open on the volume All files and directories must be closed prior to formatting the volume For any file system driver if p fs cfg is a pointer to NULL then the default configuration will be selected If non NULL the argument should be passed a pointer to the appropriate configuration structure For the FAT file system driver p fs efg should be passed a pointer toa FS FAT SYS CFG 389 Appendix A A 7 3 FSVol_GetDfitVoIName void FSVol GetDfltVolName CPU CHAR name vol File Called from Code enabled by fs vol c Application N A Get name of the default volume ARGUMENTS name vol String buffer that will receive the volume name see Note 2 RETURNED VALUE None NOTES WARNINGS B name vol MUST point to a character array of FS CFG MAX VOL NAME LEN characters B If the volume does not exist name vol will receive an empty string 340 A 7 4 FSVol GetVolCnt FS OTY FSVol GetVolCnt void File Cal
82. refer to pC Clk manual for more details C 2 CPU PORT HC CPU is a processor compiler port needed for nC FS to be CPU compiler independant Ports for the most popular architectures are already available in the pC CPU distribution If the pC CPU port for your target architecture is not available you should create your own based on the port template also available in uC CPU distribution You should refer to the pC CPU user manual to know how you should use it in your project 403 Appendix C C 3 OS KERNEL uC FS can be used with or without an RTOS Either way an OS port must be included in your project The port includes one code header file pair fs os c fs os h HC FS manages devices and data structures that may not be accessed by severally tasks simultaneously An OS kernel port leverages the kernel s mutual exclusion services mutexes for that purpose These files are generally placed in a directory named according to the following rubric Micrium Software uC FS 0S lt os_name gt Four sets of files are included with the uC FS distribution Micrium Software uC FS 0S Template Template Micrium Software uC FS 0S None No OS kernel port Micrium Software uC FS 0S uCOS II pC OS II port Micrium Software uC FS 0S uCOS III pC OS III port If you don t use any OS including a custom in house OS you should include the port for no OS in your project You must also make sure that you manage interrupts correctly If you are
83. returned Start command execution A FSDev SD Card BSP CmdStart C Error Return Wait for command to execute and returned je response to be returned Return j FSDev SD Card BSP CmdWaitEnd FSDev_ SD Card BSP CmdDataWr FSDev_ SD Card BSP CmdDataRd Return N Figure 12 9 Command execution 149 Chapter 12 12 3 USING THE SD MMC SPI DRIVER To use the SD MMC SPI driver five files in addition to the generic file system files must be included in the build E fs dev sd c E fs dev sd h E fs dev sd spi c E fs dev sd spi h E fs dev sd spi bsp c The file fs dev sd spi h must also be included in any application or header files that directly reference the driver for example by registering the device driver The following directories must be on the project include path P Micrium Software uC FS Dev SD E Micrium Software uC FS Dev SD SPI A single SD MMC volume is opened as shown in Listing 12 2 The file system initialization FS_Init function must have previously been called ROM RAM characteristics and performance benchmarks of the SD MMC driver can be found in section 9 1 1 Driver Characterization on page 113 The SD MMC driver also provides interface functions to get low level card information and read the Card ID and Card Specific Data registers see section A 12 FAT System Driver Functions on page 386 FS ERR App FS AddSD SPI void FS_ERR err FS
84. see section B 4 Device Error Codes on page 394 RETURNED VALUE The index of the created partition The first partition on the device has an index of 0 FS INVALID PARTITION NBR is returned if the function fails to add the partition NOTES WARNINGS Device state change will result from device I O not present or timeout error 283 Appendix A A 3 11 FSDev_PartitionFind void FSDev PartitionFind CPU CHAR name dev FS PARTITION NBR partition nbr FS PARTITION ENTRY p partition entry FS ERR p err File Called from Code enabled by fs deu Application FS _CFG PARTITION EN Find a partition on a device See also section 5 5 Partitions on page 73 ARGUMENTS name dev Device name partition nbr Index of the partition to find p partition entry Pointer to variable that will receive the partition information p err Pointer to variable that will receive return error code from this function FS ERR NONE Partition found FS ERR DEV VOL OPEN Volume open on device FS ERR INVALID PARTITION Invalid partition FS ERR INVALID SEC NBR Sector start or count invalid FS ERR INVALID SIG Invalid MBR signature FS ERR NAME NULL Argument name dev passed a NULL pointer FS ERR NULL PIR Argument p partition entry passed a NULL pointer Or device access error see section B 4 Device Error Codes on page 394 284 RETURNED VALUE None NOTES WARNINGS Device state change will result from device I O not
85. the p sre buffer into the physical sector sec_ix phy of the NAND device It must also write the out of sector data OOS the section of the spare area excluding ECC bad block marks and unused sections found in the p_src_oos buffer into the spare area It should also store error correction codes ECC in the spare area BLOCK ERASE FUNCTION The BlkErase function should erase the block blk ix phy of the device IO CONTROL FUNCTION The IO Ctrl function body can be left empty It was created to perform device or controller specific commands without the need of a custom API It can simply return the FS ERR DEV INVALID IO CIRL error code 197 Chapter 13 Note that the ONFI part layer implementation makes use of the FS DEV IO CTRL NAND PARAM PG RD I O control operation In order to retain compatibility with the ONFI part layer implementation your controller implementation must support that operation 198 Chapter 14 NOR Flash Driver NOR flash is a low capacity on board storage solution Traditional parallel NOR flash located on the external bus of a CPU offers extremely fast read performance but comparatively slow writes typically performed on a word by word basis Often these store application code in addition to providing a file system The parallel architecture of traditional NOR flash restricts use to a narrow class of CPUs and may consume valuable PCB space Increasingly serial NOR flash are a valid alternative w
86. the return error code is FS ERR DEV FS ERR DEV NOT PRESENT FS ERR DEV IO or FS ERR DEV TIMEOUT the device is either not present or did not respond This is an important consideration for removable devices The volume is still registered with the file system suite and the file system will attempt to re open the volume each time the application accesses it see section 5 2 Using Devices on page 69 for more information B If any other error code is returned the volume is not registered with the file system The developer should examine the error code to determine the source of the error FSVol Fmt formats a device re initializing the file system on the device FSVol Fmt CPU CHAR ide 0 lt a volume name void 3 Op lt b pointer to system configuration FS_ERR amp err lt c return error The parameters are the volume name a and a pointer to file system specific configuration b The configuration is not required if you are willing to accept the default format a NULL pointer should be passed Alternatively the exact properties of the file system can be configured by passing a pointer to a FS FAT SYS CFG structure as the second argument For more information about the FS FAT SYS CFG structure see section D 7 FS_FAT_SYS_CFG on page 492 78 Using Volume Cache 5 8 USING VOLUME CACHE File accesses often incur repeated reading of the same volume sectors On a FAT volume these may be sect
87. these each of which could be mounted as a volume uC FS can handle and make DOS style partitions which is a common partitioning system The first sector on a device with DOS style partitions is the Master Boot Record MBR with a partition table with four entries each describing a partition An MBR entry contains the start address of a partition the number of sectors it contains and its type The structure of a MBR entry and the MBR sector is shown in Figure 5 4 4 8 Flag Start CHS Addr Type End CHS Addr Start LBA Addr Size in Sectors Figure 5 3 Partition entry format 448 464 1 Entry Boot Code 2nd Entry 480 496 3 Entry 4 Entry Signature OxAA55 Figure 5 4 Master boot record An application can write an MBR to a device and create an initial partition with FSDev PartitionInit For example if you wanted to create an initial 256 MB partition on a 1 GB device ide 0 FSDev_PartitionInit CPU CHAR ide 0 lt a device name FS_SEC QTY 512 1024 lt b size of partition FS_ERR amp err lt C return error 73 Chapter 5 The parameters are the device name a and the size of the partition in sectors b If b is 0 then the partition will take up the entire device After this call the device will be divided as shown in Figure 5 5 This new partition is called a primary partiti
88. visible or hidden One byte Reserved area One byte Created Time milliseconds and is the fraction of the second of the date and time the file was created One byte Created Time is the hour minute and second the file was created Two bytes Created Date is the day month and year the file was created Two bytes Last Accessed Day is the day month and year the file was last accessed Two byte 119 Chapter 10 F10 2 9 Extended Attribute Index In FAT16 this field is used for extended attributes for some operating systems In FAT32 this field contains the high two bytes of the cluster address Two bytes F10 2 10 Last Modified Time is hour minute and second when the file was last modified Two bytes F10 2 11 Last Modified Date is the day month and year when the file was last modified Two bytes F10 2 12 Cluster address is the address of the first cluster allocated to the file Oe the first cluster that contains file data In FAT16 this field contains the entire cluster address In FAT32 this field contains the low two bytes of the cluster address Two bytes F10 2 13 File Size is the size of the file in octets If the entry is a directory this field is blank Four bytes 10 3 ORGANIZATION OF THE FILE ALLOCATION TABLE The File Allocation Table is a map of all the clusters that make up the data area of the volume The FAT does not know the location of the first cluster that has been allocated to a
89. void FSDev Open FS DEV p dev void p dev cfg FS ERR p err File Called from Code enabled by fs dev HH c FSDev_Open N A The device driver Open function should initialize the hardware to access a device and attempt to initialize that device If this function is successful Oe it returns FS ERR NONE then the file system suite expects the device to be ready for read and write accesses ARGUMENTS p dev Pointer to device to open p dev cfg Pointer to device configuration p err Pointer to variable that will receive the return error code from this function FS ERR NONE Device opened successfully FS ERR DEV ALREADY OPEN Device unit is already opened FS ERR DEV INVALID CFG Device configuration specified invalid FS ERR DEV INVALID LOW FMT Device needs to be low level formatted FS ERR DEV INVALID LOW PARAMS Device low level device parameters invalid FS ERR DEV INVALID UNIT NBR Device unit number is invalid FS ERR DEV IO Device I O error FS ERR DEV NOT PRESENT Device unit is not present FS_ERR_DEV_TIMEOUT Device timeout FS ERR MEM ALLOC Memory could not be allocated RETURNED VALUE None 416 NOTES WARNINGS 1 Tracking whether a device is open is not necessary because this should NEVER be called when a device is already open Some drivers may need to track whether a device has been previously opened indicating that the hardware has previously been initialized This will be called
90. with name name_vol exists DEF_NO or the volume with name name_vol is not the default volume NOTES WARNINGS None 344 A 7 8 FSVol_IsMounted CPU BOOLEAN FSVol_IsMounted CPU CHAR name_vol File Called from Code enabled by fs vol c Application N A Determine whether a volume is mounted ARGUMENTS name vol Volume name RETURNED VALUE DEF YES if the volume is open and is mounted DEF MO if the volume is not open or is not mounted NOTES WARNINGS None 345 Appendix A A 7 9 FSVol_LabelGet void FSVol LabelGet CPU CHAR name vol CPU CHAR label CPU SIZE T len max FS ERR p err File Called from Code enabled by fs vol c Application N A Get volume label ARGUMENTS name vol Volume name label String buffer that will receive volume label len max Size of string buffer p err Pointer to variable that will receive the return error code from this function FS ERR NONE Label gotten FS ERR DEV CHNGD FS ERR NAME NULL FS ERR NULL PTR FS ERR DEV FS ERR VOL LABEL NOT FOUND FS ERR VOL LABEL TOO LONG FS ERR VOL NOT MOUNTED FS ERR VOL NOT OPEN 346 Device has changed Argument name vol passed a NULL pointer Argument label passed a NULL pointer Device access error Volume label was not found Volume label is too long Volume is not mounted Volume is not open REQUIRED CONFIGURATION None NOTES WARNINGS len_max is the maximum length string
91. working directory Otherwise the preliminary working directory path is formed by the concatenation of the current working directory a path separator character and dir 516 The preliminary working directory path is then refined from the first to last path component a If the component is a dot component it is removed b If the component is a dot dot component and the preliminary working directory path is not NULL the previous path component is removed In any case the dot dot component is removed c Trailing path separator characters are removed and multiple path separator characters are replaced by a single path separator character The volume is examined to determine whether the preliminary working directory exists If it does it becomes the new working directory Otherwise an error is output and the working directory is unchanged 517 Appendix F F 3 3 fs_cp Copy a file USAGES fs cp source file dest file fs cp source file dest dir ARGUMENTS source file Source file path dest_file Destination file path dest dir Destination directory path OUTPUT None REQUIRED CONFIGURATION Available only if FS SHELL CFG CP EN is DEF ENABLED and FS CFG RD ONLY EN is DEF DISABLED NOTES WARNINGS In the first form of this command neither argument may be an existing directory The contents of source file will be copied to a file named dest file located in the same directory as sour
92. you are ready to go to production If you are unsure about whether you need to obtain a license for your application please contact Micrium and discuss your use with a sales representative CONTACT MICRIUM Micrium 1290 Weston Road Suite 306 Weston FL 33326 1 954 217 2036 1 954 217 2037 FAX E Mail sales Micrium com Website www Micrium com 537 Appendix H H 1 2 uC FS MAINTENANCE RENEWAL Licensing uC FS provides one year of limited technical support and maintenance and source code updates Renew the maintenance agreement for continued support and source code updates Contact sales Micrim com for additional information H 1 3 uC FS SOURCE CODE UPDATES If you are under maintenance you will be automatically emailed when source code updates become available You can then download your available updates from the Micrium FTP server If you are no longer under maintenance or forget your Micrium FTP username or password please contact sales Micrinm com H 1 4 uC FS SUPPORT Support is available for licensed customers Please visit the customer support section in www Micrijm com If you are not a current user please register to create your account A web form will be offered to you to submit your support question Licensed customers can also use the following contact CONTACT MICRIUM Micrium 1290 Weston Road Suite 306 Weston FL 33326 1 954 217 2036 1 954 217 2037 FAX 538
93. 07 about configuring the trace level COM1 PuTTY Figure 12 1 SD MMC detection trace output 12 2 1 SD MMC CARDMODE COMMUNICATION In card mode seven nine or thirteen pins on the SD MMC device are used with the functions listed in the table below All cards start up in 1 bit mode upon entering identification mode which involves only a single data line Once the host the MCU MPU discovers the capabilities of the card it may initiate 4 or 8 bit communication the latter available only on new MMCs Some card holders contain circuitry for card detect and write protect indicators which the MCU MPU may also monitor Pin Name Type Description 1 CD DAT3 1 0 Card Detect Data Line Bit 3 2 CMD WO Command Response 3 Vss1 S Supply voltage ground 4 VDD S Supply voltage 5 CLK Clock 6 VSS2 S Supply voltage ground 7 DATO VO Data Line Bit 0 141 Chapter 12 Pin Name Type Description 8 DAT VO Data Line Bit 1 9 DAT2 VO Data Line Bit 2 10 DAT4 1 0 Data Line Bit 4 11 DAT5 VO Data Line Bit 5 12 DAT6 1 0 Data Line Bit 6 13 DAT7 VO Data Line Bit 7 Table 12 2 SD MMC pinout Card mode Only present in MMC cards Exchanges between the host and card begin with a command sent by the host on the CMD line often followed by a response from the card also on the CMD line finally one or more blocks data may be sent in one direction on the data line s ea
94. 2 and FAT 16 volumes contain a fixed amount of space for the root directory In FAT32 volumes there is no area reserved for the root directory the root directory is instead stored in a fixed location in the data area Data area The data area contains files and directories A directory or folder is a special type of file FAT supports only four attributes for its files and directories Read Only Hidden System and Archive Organization of a FAT Volume 10 2 1 ORGANIZATION OF DIRECTORIES AND DIRECTORY ENTRIES In the FAT file system directories are just special files composed of 32 byte structures called directory entries The topmost directory the root directory is located using information in the boot sector The normal short file name entries in this directory and all other directories follow the format shown below in Figure 10 2 Cong file name are discussed a little further on in section 10 3 2 Short and Long File Names on page 123 One Directory Entry Byte F10 2 1 F10 2 2 F10 2 3 F10 2 4 F10 2 5 F10 2 6 F10 2 7 F10 2 8 mogte elen 8 9 12 13 14 15 17 19 21 23 25 27 29 32 Figure 10 2 The entry for a file in a FAT directory Filename is the 8 character short file name SFN Eight bytes File extension is the three character file name extension Three bytes File Attributes are the attributes of the entry indicating whether it is a file or directory writable or read only and
95. 21BA5B7E ALL_SEND_CID gt MID Manufacturer ID 0x1E Fig 15 6 5 OID OEM Application ID 0xFFFF PNM Product name 0x4D4D43202020 MMC PRV Product revision 0x10 1 0 PSN Product serial number 0x5E6021BA MDT Manufacturing date 0x5B Examples 127 SS TAAC NSAC TRAN_SPEED 0x902F002A SEND CSD C_SIZE 0x1 F5A83C7 Fig 15 6 6 63 0x6DB79FFF 0x9680000E Figure 12 6 Command responses MMC card SD_BUS_WIDTHS Bit 0 1 bit Bit 2 4 bit Figure 12 7 SD SCR register 147 Chapter 12 00b 1 bit 01b 4 bit DAT_BUS_WIDTH SD_CARD_TYPE SIZE_OF_PROTECTED_AREA 0x0000 Regular rd wr card SPEED_CLASS 0x00 Class 0 0x01 Class 2 0x02 Class 3 0x03 Class 4 Figure 12 8 SD status 12 2 3 SD MMC CARDMODE BSP OVERVIEW A BSP is required so that the SD MMC cardmode driver will work on a particular system The functions shown in the table below must be implemented Pleaser refer to section C 5 SD MMC Cardmode BSP on page 425 for the details about implementing your own BSP Functio n Description FSDev _S D Card BSP Open Open initialize SD MMC card interface FSDev _S D Card BSP Close Close uninitialize SD MMC card interface FSDev S D Card BSP Lock Acquire SD MMC card bus lock FSDev _S D Card BSP Unlock Release SD MMC card bus lock FSDev
96. 3 2 Architecture Overview on page 167 To use the NAND driver you must include the following ten files in the build in addition to the generic file system files E fs dev nand c Micrium Software uC FS Dev NAND E fs dev nand h Micrium Software uC FS Dev NAND E fs dev nand ctrlr gen c Micrium Software uC FS Dev NAND Ctrlr E fs dev nand ctrlr gen h Micrium Software uC FS Dev NAND Ctrlr 160 Getting Started E fs dev nand part static c Micrium Software uC FS Dev NAND Part E fs dev nand part static h Micrium Software uC FS Dev NAND Part E ecc_hamming c Micrium Software uC CRC Source E ecc_hamming h Micrium Software uC CRC Source E ecc h Mierium Software uC CRC Source B Your BSP layer implementation derived from fs dev nand ctrlr gen bsp c in Micrium Software uC FS Dev NAND BSP Template The example in Listing 13 1 shows how to open a single NAND volume The file system initialization function FS_Init must have previously been called include include include include include include include include lt ecc_hamming h gt lt fs h gt lt fs_err h gt lt fs_vol h gt lt fs_dev_nand h gt lt fs_dev_nand_ctrlr_gen h gt lt fs dev nand ctrlr gen soft ecc h gt lt fs dev nand part static h gt FS NAND FREE SPARE MAP App SpareMap 2 1 63 ely A Jip static CPU BOOLEAN App FS AddNAND void it 1 FS_NAND_CFG cfg_nand FS_NAND
97. 5 3 Cache types Using Volume Cache 5 8 1 CHOOSING CACHE PARAMETERS The following is an example using the cache for the volume sdcard 0 The cache is used in write back mode and the cache parameters are 25 of cache size is used for management sector 15 is used for directories sectors and the remaining 60 is used for file sectors FSVol CacheAssign CPU CHAR sdcard 0 lt volume name FS_VOL_CACHE API NULL lt pointer to vol cache API void amp CACHE BUF 0 lt pointer to the cache buf CPU_INT32U CACHE_BUF_LEN lt cache buf size in bytes CPU_INTO8U 25 lt see 1 CPU_INTO8U 15 lt see 2 FS_FLAGS FS VOL CACHE MODE WR BACK lt cache mode FS_ERR amp err lt used for error code if err FS_ERR_NONE APP TRACE INFO Error could not assign Volume cache return pfile FSFile Open sdcard 0 file txt FS_FILE ACCESS MODE WR FS_FILE ACCESS MODE CACHED Serr if pFile FS_FILE 0 return J DO THE WRITE OPERATIONS TO THE FILE EE FSFile Close pFile amp err FSVol CacheFlush sdcard 0 amp err lt Flush volume cache Listing 5 2 Cache L5 2 1 Percent of cache buffer dedicated to management sectors L5 2 2 Percent of cache buffer dedicated to directory sectors 81 Chapter 5 The application using uC FS volume cache should vary the third and fourth parameters passed to FSVol_CacheAssign and se
98. 6 D Card BSP CmdStart Start a command FSDev _S FSDev _S D Card BSP CmdWaitEnd D Card BSP CmdDataRd Wait for a command to end and get response Read data following command FSDev _S D Card BSP CmdDataWr Write data following command FSDev _S D Card BSP GetBlkCntMax Get max block count FSDev _S D Card BSP_GetBusWidthMax Get maximum bus width in bits FSDev _S D Card BSP SetBusWidth Set bus width FSDev _S 148 D Card BSP SetClkFreq Set clock frequency Using the SD MMC CardMode Driver Function Description FSDev_SD_Card_BSP_SetTimeoutData Set data timeout FSDev_SD Card BSP SetTimeoutResp Set response timeout Table 12 3 SD MMC cardmode BSP functions The Open Close functions are called upon open close or medium change these calls are always matched The status and information functions GetBlkCntMax GetBusWidthMax SetBusWidth SetClkFreg SetTimeoutData SetTimeoutResp help configure the new card upon insertion Lock and Unlock surround all card accesses The remaining functions CmdStart CmdWaitEnd CmdDataRd CmdDataWr constitute the command execution state machine see Figure 12 9 A return error from one of the functions will abort the state machine so the requisite considerations such as preparing for the next command or preventing further interrupts must be first handled Error
99. 7 1 A 7 2 A 7 3 A 7 4 A 7 5 A 7 6 A 7 7 A 7 8 A 7 9 A 7 10 FSDi RA E 296 Entry Access Functions cceccceceeeeeeceeeeeeeeeeeeeeeneeseeeeesneeeeeeesneeseeeenenes 297 FSEntry AttribSet enca even nd eenden 298 FSEntfy Gopy urine aneneerennennseerdeennderrddennnnernenenne eren denn KAARE aah 300 FSEntry Greatel 2 zzuissinassers vaeenerven wenwersoansoannerd oieivnkdankwakentgendddndnnvand 302 Fakt Belt isegen ee ca tines 304 FSEntry Query soeren ein eege leede nett 306 FSEntry_ Rename nnn unnnvansneer ensen ennneeeenneennensenennenenennenenaneeeennnenn 307 FSEntry TIM Se t tsaren sene neen vern versaatanennddederdnvidinan waande geed ven 309 File Functions zunszerssav aeaa aa aaaea aa aaa aaa aa aaa aaa aai vedienen 311 ESFile BufAssign street Eege na aaa aauina ANENA NERAK NAERAA 313 FSFile BufFlush 2egvegereteeone d ceed ieee avandia aaa 315 FSFile GloSe ee de ege Een e geheie eege 316 FSFE CWE estote rte vals vives in tend dee ege er deed 317 FSFile ISEOF ites a tetin ege igeenge ee aca aetna eet 318 FSFile ISErr EE 319 Fale ISOpen si snares ieee neden ial eren nn needs 320 FSFile LockAccept nennen eneeneenenenennenanennnentenneeneennen 321 FSFile LOCKGOU 7 msnen ereen eenden meeer Gries Nee en ae 322 FSEile LockSet zernike terde era ede need nde dee 323 FSFilec Open 255 SCENE deeg eier 324 ESFile P sGet sss 0e denge EENS 326 FSFile POSSet aerie iesen de eee ee
100. A ASM CPU_CORE C H BogtwerereiEirresa are a ee 5 i cpu interrupt Devires Controller Figure 3 1 HC FS Architecture F3 1 1 The application code consist of project or product files For convenience we simply called these app c and app h but your application can contain any number of files and they do not have to be called app The application code is typically where you would find main 30 F3 1 2 F3 16 F3 1 4 F3 1 5 F3 1 6 F3 1 7 F3 1 8 F3 1 9 Quite often semiconductor manufacturers provide library functions in source form for accessing the peripherals on their CPU Central Processing Unit or MCU Micro Controller Unit These libraries are quite useful and often save valuable time Since there is no naming convention for these files ze and h are assumed The Board Support Package BSP is code that you would typically write to interface to peripherals on your target board For example you can have code to turn on and off LEDs light emitting diodes functions to turn on and off relays and code to read switches and temperature sensors uC CPU is an abstraction of basic CPU specific functionality These files define functions to disable and enable interrupts data types e g CPU INTO8U CPU_FP32 independent of the CPU and compiler and many more functions uC LIB consists of a group of source files to provide common functions for memory copy string manipulation and character mappi
101. A danane dadde vens 387 FS FAT Jo rnal Close ae enpara arenae Aa apaa denken 388 FS_FAT_JournalStart raara ma aaae amda adaa deer Eaa aea a aaaea Aa daa 389 FES FAT JournalStop oana naana eege dee AEA enden ENEE Aai 390 FS FAT Noch sorreran A AA 391 UC FS Error GOdesS v sana aeaaaee aE eaae et aa a aena Eaa eens 393 System Error CodeS snunssssarenaensennenansenneternannnesenannnenn evianennsiernannnme dk 393 Buffer Error GOdeS n srsanserarndenterdvanmervaar EENS EEN dende 393 Cache Error COG S oons cessive anaiena naaa aaa aaa a dnvenwdan wann deneenn 394 Device Error Codes nnnnnnnnnnnnnnennn enn enanenneeneneneeenennennenannenennnnennenren 394 B 5 B 6 B 7 B 8 B 9 B 10 B 11 B 12 B 13 B 14 B 15 Appendix C C 1 C 2 C 3 C 4 C 4 1 C 4 2 C 4 3 C 4 4 C 4 5 C 4 6 C 4 7 C 4 8 C 5 C 5 1 C 5 2 C 5 3 C 5 4 C 5 5 C 5 6 C 5 7 C 5 8 C 5 9 C 5 10 C 5 11 C 5 12 Device Driver Error Codes nnnnnannnenenennene nen ennnnnnnennenenenvenseenenn 395 Directory Error Codes aaraa aaa daa ee e penaa a raea ae aaa Aaea ae a ENEA 395 EGG Error Code aeina aaia iaaa anaa a EENEG eaa aAa aaa a aaa aa 395 Entry Error Codes eege Edge Edge 395 File Error COGS zinansennninrsnsrers aarenevensversandearensnaans oi anaana iiaia aiaeei auian 396 Name Error Codes EEE A 397 Partition Error Cod ES ass soan snterearherten malin senden se dree ege dea nend 397 Pools Error
102. AR name dev FS ERR p err void FSDev_ NOR LowCompact CPU CHAR name dev FS ERR p err void FSDev NOR LowDefrag CPU _CHAR name dev FS ERR p err void FSDev NOR PhyRd CPU _ CHAR name dev void p dest CPU INT32U start CPU INT32U cnt FS ERR p err void FSDev_ NOR PhyWr CPU_CHAR name dev void p src CPU INT32U start CPU INT32U ent FS ERR p err void FSDev NOR PhyEraseBlk CPU CHAR name dev CPU INT32U start CPU INT32U size FS ERR p err void FSDev NOR PhyEraseChip CPU CHAR FS ERR name dev p err 373 Appendix A A 11 1 FSDev NOR LowFmt void FSDev NOR LowFmt CPU CHAR name dev FS ERR p err File Called from Code enabled by fs dev nor c Application N A Low level format a NOR device ARGUMENTS name dev Device name see Note p err Pointer to variable that will the receive return error code from this function FS ERR NONE Device low level formatted successfully FS ERR NAME NULL Argument name dev passed a NULL pointer FS ERR DEV INVALID Argument name dev specifies an invalid device FS ERR DEV NOT OPEN Device is not open FS ERR DEV NOT PRESENT Device is not present FS ERR DEV INVALID LOW FMT Device needs to be low level formatted FS ERR DEV IO Device I O error FS ERR DEV TIMEOUT Device timeout RETURNED VALUE None NOTES WARNINGS The device must be a NOR device e g nor 0 Low level formating associates physical areas s
103. ARD RESP TYPE RI No response R1 response Normal Response Command R1b response R2 response CID CSD Register R3 response OCR Register R4 response Fast I O Response MMC R5 response Interrupt Request Response MMC R5B response R6 response Published RCA Response R7 response Card Interface Condition E p cmd gt BlkSize and p cmd gt BlkCnt are the block size and block count of the data transfer that should follow this command if any The pointer to the data buffer that will receive the data transfer that should follow this command p data is given so that a DMA transfer can be set up EXAMPLE The example implementation of FSDev SD Card BSP CmdStart in like the examples in subsequent sections targets a generic host conformant to the SD card association s host controller specification While few hosts do conform most have a similar mixture of registers and registers fields and require the same sequences of basic actions 433 Appendix C void FSDev SD Card BSP CmdStart FS QTY unit nbr 434 FS DEV SD CARD CMD p cmd void p data FS DEV SD CARD ERR p err CPU INT16U command CPU INT32U present state CPU INT16U transfer mode present state REG STATE Chk if controller busy Z GN if DEF BIT IS SET ANY present state BIT STATE CMD INHIBIT DAT BIT STATE CMD INHIBIT CMD DEF YES p err FS DEV SD CARD ERR BUSY return transfer mode DEF BIT NONE
104. ATE Response No response Fig 15 6 1 Response only for SD V2 cards Voltage range SEND_IF_COND Reserved Check pattern Fig 15 6 2 0x00000 0x1 0xA5 20 bits 4 bits 8 bits Card power May not be 1 on initial up status reading s Card Capacity 1 High capacity Status 0 Standard capacity SD_SEND_OP_COND Reserved VDD Voltage Window Fig 15 6 3 1 0x00 OxFF8000 6 bits 24 bits OCR Example 127 MID OID 0x03534453 PNM 0x44303247 63 PRV PSN 0x80021A7C MDT cre 0x83008B3A ALL SEND CID S a MID Manufacturer ID 0x03 Fig 15 6 5 OID OEM Application ID 0x5344 PNM Product name 0x5344303247 SD02G PRV Product revision 0x80 8 0 PSN Product serial number 0x021A7C83 MDT Manufacturing date 0x008 Examples 127 0x400E0032 a 0x5B590000 2 63 Ox1E5C7F80 SEND_CSD 0x0A4040DE Fig 15 6 6 2 127 TRAN SPEED 0x00260032 o S C_SIZE Ox5F5A83C9 i e 63 Ox3EFBCFFF Ei 0x928040CA Figure 12 5 Command responses SD card Command Response Using the SD MMC CardMode Driver GO_IDLE_STATE Fig 15 6 1 No response SEND_OP_COND Card power May not be 1 on initial up status reading s Reserved VDD Voltage Window Fig 15 6 4 1 0x00 OxFF8000 7 bits 24 bits OCR Example 127 MID OID Ox1lEFFFF4D PNM 0x4D432020 63 PRV PSN 0x20105E60 MDT CRC 0x
105. C engines are often found in MCU and in NAND flash devices Consult their datasheets to determine if you have access to such a feature If data safety is a concern you can consider using an ECC module with better correction capacity For most applications the recommended level of correction is sufficient However using an ECC engine that can correct more bit errors can improve long term readability of the data especially for cold data that never or rarely changes Another option is to reduce the codeword size The same number of bit errors can be corrected but since codewords are smaller the bit error rate will be smaller While those design choices will slightly improve reliability they will also increase the overhead and hence reduce the read write speed and increase the worst case locking time CONFIGURE THE TRANSLATION LAYER The configuration of the translation layer is complicated Take the time needed to read carefully each description and make sure you choose a configuration that is appropriate for your application When in most cases the basic configuration will be enough optimizing it will help you to reach your goals whether they are about CPU usage footprints reliability or speed The translation layer configuration options are described in section 13 3 1 Translation Layer Configuration on page 171 CONSIDERING ANOTHER CONTROLLER LAYER Some MCUs have advanced peripherals that interface with NAND flash devices I
106. CHE FS The Embedded File System User s Manual Micrium For the Way Engineers Work Micrium 1290 Weston Road Suite 306 Weston FL 33326 USA www micrium com Designations used by companies to distinguish their products are often claimed as trademarks In all instances where Micrium Press is aware of a trademark claim the product name appears in initial capital letters in all capital letters or in accordance with the vendor s capitalization preference Readers should contact the appropriate companies for more complete information on trademarks and trademark registrations All trademarks and registered trademarks in this book are the property of their respective holders Copyright 2012 by Micrium except where noted otherwise All rights reserved Printed in the United States of America No part of this publication may be reproduced or distributed in any form or by any means or stored in a database or retrieval system without the prior written permission of the publisher with the exception that the program listings may be entered stored and executed in a computer system but they may not be reproduced for publication The programs and code examples in this book are presented for instructional value The programs and examples have been carefully tested but are not guaranteed to any particular purpose The publisher does not offer any warranties and does not guarantee the accuracy adequacy or completeness of any informati
107. DfltCfg FS NAND CTRLR GENERIC CFG efg etrlr FS NAND CtrlrGen DfltCfg FS NAND CTRLR GEN SOFT ECC CFG ecfg soft ecc FS NAND CtrlrGen SoftEcc_DfltCfg FS_NAND PART STATIC CFG cfg part FS _NAND PartStatic D LtCfg FS ERR err FS DevDrvAdd FS DEV API amp FS NAND 2 amp err if err FS ERR NONE amp amp err FS ERR DEV DRV ALREADY ADDED APP TRACE DBG could not add driver w err d r n r n err return DEF FAIL 161 Chapter 13 162 3 cfg_part BlkCnt 2048 cfg_part PgPerBlk 64 cfg_part PgSize 2048 cfg_part SpareSize 64 cfg_part SupportsRndPgPgm DEF_NO cfg_part NbrPgmPerPg 4 cfg_part BusWidth 8 cfg_part ECC_NbrCorrBits 1 cfg_part ECC_CodewordSize 512 16 cfg_part DefectMarkType DEFECT SPARE L 1 PG 1 OR N ALL EH cfg_part MaxBadB1kCnt 40 cfg_part MaxBlkErase 100000 cfg_part FreeSpareMap amp spare map 0 efg etrlr CtrlrExt efg etrlr CtrlrExtCfg efg soft ecc ECC ModulePtr efg nand BSPPtr efg nand CtrlrPtr Cfg nand CtrlrCfgPtr efg nand PartPtr efg nand PartCfgPtr efg nand SecSize efg nand BlkCnt efg nand BlkIxFirst efg nand Up CntMax efg nand BUR MaxAssoc cfg nand AvailBlkTblEntryCntMax FSDev_Open nand 0 void scfg nand amp err switch err case FS ERR NONE APP_TRACE_DBG break We eS amp FS_NAND_CtrlrGen_SoftECC amp soft_ecc_cfg 5 ECC_CALC amp Hamming ECC 6
108. Directories naaar a nenennenenenvenennenennenenenvenenenenn 200 Driver and Device Characteristics nnen enen NEEN 202 Using a Parallel NOR Device nnnnnnsnennen ren enensenenen nnn nenenen vereen 204 Driver ArchitectUf ze eee e e den a a a a aaaea araa aak daranau aldandi anii 208 ee ME 208 Klee 210 14 4 14 4 1 14 4 2 14 5 14 5 1 14 5 2 14 5 3 14 5 4 14 5 5 Chapter 15 15 1 15 2 Appendix A A 1 A 1 1 A 1 2 A 1 3 A 1 4 A 1 5 A 2 A 2 1 A 2 2 A 2 3 A 2 4 A 2 5 A 2 6 A 2 7 A 2 8 A 2 9 A 2 10 A 2 11 A 2 12 A 2 13 A 2 14 A 2 15 Using a Serial NOR Device nnn annnsernenennnenrenennnnereeeennnnenvenennnen 211 ele H 212 NOR SPI BSP Overview cccceceeceeeeeseeeeeeeceeeeeeeeeseseeessneaneeseeeeenees 213 Physical Layer Drivers nanus anse ennen sennenenenennneneenvennnneneenennneevenennenn 214 FSDev_ NOR AMD 1x08 FSDev_ NOR AMD 1xvip en 215 FSDev_ NOR Intel 1x16 ENEE 215 FSDev NOR SST39 oanns ecient winded eke J 216 FSDev NOR STM25 ee ee dee EE SEEEEA VEER ENEE 216 FSDev NORM SST25 eiiean vent reretde eli detente dive eeeh 217 MSG DIVO EE 219 Files and Directories aaneen nenenenneneenevenennenennenrnennenenenenn 219 Using the MSC Driver onver anenannenenenensenenvenenannennennnensenven 220 UC FS API Reference nnnnannnsnsennenenenensnnenannenneeen sene ennenanennnnnenneen 223 General File System Functions aanannan oer enenserenennnnaen
109. E For a command with a long 136 bit response a 16 byte response should be returned in p resp The first 4 byte word should hold bits 127 96 of the response The second 4 byte word should hold bits 95 64 of the response The third 4 byte word should hold bits 63 32 of the response The four 4 byte word should hold bits 31 0 of the response EXAMPLE The implementation of FSDev_SD Card BSP CmdWaitEnd in is targeted for the same host controller as the other listings in this chapter for more information see FSDev SD Card BSP CmdStart 437 Appendix C void FSDev SD Card BSP CmdWaitEnd FS QTY unit nbr FS DEV SD CARD CMD p cmd CPU_INT32U p resp FS DEV SD CARD ERR p err CPU INT16U interrupt status CPU INT16U error status CPU INT16U timeout timeout Ou Wait until cmd exec complete 1 REG INTERRUPT STATUS while DEF BIT IS CLR interrupt status BIT INTERRUPT STATUS ERROR BIT INTERRUPT STATUS COMMAND COMPLETE DEF YES interrupt status timeout interrupt status REG INTERRUPT STATUS if timeout TIMEOUT RESP MAX p err FS DEV SD CARD ERR WAIT TIMEOUT return Handle error he 2 if DEF BIT IS SET interrupt status BIT INTERRUPT STATUS ERROR DEF YES error status REG ERROR STATUS if DEF BIT IS SET error status REG ERROR STATUS COMMAND INDEX DEF YES p err FS DEV SD CARD ERR RESP CMD IX else if DEF BIT IS SET e
110. E ORIGIN END Offset is from the end of the file p err Pointer to variable that will the receive return error code from the function FS ERR NONE File position set successfully FS ERR NULL PTR Argument p file passed a NULL pointer FS ERR INVALID TYPE Argument p file s type is invalid or unknown FS ERR FILE INVALID ORIGIN Invalid origin specified FS ERR FILE INVALID OFFSET Invalid offset specified FS ERR FILE NOT OPEN File NOT open 327 Appendix A RETURNED VALUE None NOTES WARNINGS None 328 A 6 14 FSFile_Query void FSFile Query FS FILE p file FS ENTRY INFO p info FS ERR p err File Called from Code enabled by fs file c Application N A fs fstat FSFile Query is used to get information about a file ARGUMENTS p file Pointer to a file p info Pointer to structure that will receive the file information see Note p err Pointer to variable that will the receive return error code from the function FS ERR NONE File information obtained successfully FS ERR NULL PIR Argument p file or p info passed a NULL pointer FS ERR INVALID TYPE Argument p file s type is invalid or unknown FS ERR FILE NOT OPEN File NOT open RETURNED VALUE None NOTES WARNINGS None 329 Appendix A A 6 15 FSFile_Rd CPU SIZE T FSFile Rd FS FILE p file void p dest CPU SIZE T size FS ERR p err File Called from Code enabled by fs file c Application N A fs fread Read from a
111. ED VALUE Pointer to str_time if NO errors Pointer to NULL otherwise NOTES WARNINGS str_time MUST be at least 26 characters long Buffer overruns MUST be prevented by caller 234 A 2 2 fs_chdir int fs chdir const char path dir File Called from Code enabled by fs api c FS_CFG WORKING DIR EN Application FS CFG API EN and Set the working directory for the current task ARGUMENTS path dir String buffer that specifies EITHER Ethe absolute working directory path to set Erelative path that will be applied to the current working directory RETURNED VALUE 0 if no error occurs 1 otherwise NOTES WARNINGS None 235 Appendix A A 2 3 fs_clearerr void fs clearerr FS FILE p file File Called from Code enabled by fs_api c Application FS_CFG_API_EN Clear EOF and error indicators on a file ARGUMENTS p file Pointer to a file RETURNED VALUE None NOTES WARNINGS None 236 A 2 4 fs_closedir int fs_closedir FS DIR p dir File Called from Code enabled by fs_api c Application Close and free a directory ARGUMENTS p dir Pointer to a directory RETURNED VALUE 0 if the directory is successfully closed 1 if any error was encountered NOTES WARNINGS FS_CFG_API_EN and FS_CFG _DIR_EN After a directory is closed the application MUST desist from accessing its directory pointer This could cause file system
112. F103ZE ST M29W128GL 16MB NOR 2 750 kB s 3 810 kB s 72 MHz flash 158 kB s 310 kB s NOR serial ST STM32F103VE ST M25P64 serial flash 691 kB s kB s 72 MHz 55 kB s kB s MSC Atmel AT91SAM9M10 64 GB SanDisk Cruzer 613 kB s 2 301kB s 400 MHz 153 kB s 883 kB s 9 2 DRIVERS COMPARISON Table 9 4 Driver performance file test NAND flash is a low cost on board storage solution Typically NAND flash have a multiplexed bus for address and data resulting in a much lower pin count than parallel NOR devices Their low price per bit and relatively high capacities often makes these preferable to NOR though the higher absolute cost because the lowest capacity devices are at least 128 Mb reverses the logic for applications requiring very little storage 115 Chapter 9 116 Chapter 10 FAT File System Microsoft originally developed FAT File Allocation Table as a simple file system for diskettes and then hard disks FAT originally ran on very early very small microcomputers e g IBM PCs with 256 KB of memory Windows Mac OS Linux and many Unix like systems also use FAT as a file interchange format FAT was designed for magnetic disks but today supports Flash memory and other storage devices uC FS is an implementation of FAT that supports FAT12 FAT16 and FAT32 By default HC FS supports only short 8 3 file names To enable long file names LFNs you must set a configuration switch By setting thi
113. FAT16 volumes on which the root directory is a separate area of the file system and is a fixed size The root directory entry count caps the number of files and directories that can be located in the root directory FAT Type The type of FAT This should be 12 for FAT12 16 for FAT16 or 32 for 492 FAT32 Ths choice of FAT type must observe restrictions on the maximum number a clusters A FAT12 file system may have no more than 4085 clusters a FAT16 file system no more than 65525 NbrFATs The number of actual FATs file allocation tables to create on the disk The typical value is 2 one for primary use a secondary for backup NOTES Further restrictions on the members of this structure can be found in Chapter 4 File Systems FAT on page 153 493 Appendix D D 8 FS PARTITION ENTRY typedef struct fs partition entry FS SEC NBR Start FS SEC OTY Size CPU_INTO8U Type FS PARTITION ENTRY File Used for fs_partition h Third argument of FSDev_PartitionFind Receives information about a partition entry MEMBERS Start The start sector of partition Size The size of partition in sectors Type The type of data in the partition NOTES None 494 D 9 FS_VOL_INFO typedef struct fs vol info FS STATE State FS STATE DevState FS SEC OTY DevSize FS SEC SIZE DevSecSize FS SEC OTY PartitionSize FS SEC OTY VolBadSecCnt FS SEC OTY VolFreeSecCnt FS SEC OTY VolUsedSecCnt FS SEC OTY VolTo
114. FSDev_RAM Chapter 11 on page 131 SD MMC sd sdcard FSDev SD SPI FSDev SD Card Chapter 12 on page 135 NAND nand FSDev_NAND Chapter 13 on page 159 NOR nor FSDev_NOR Chapter 14 on page 199 MSC msc FSDev_MSC Chapter 15 on page 219 Table 9 1 Device driver API structures If your medium is not supported by one of these drivers a new driver can be written based on the template driver Appendix C Device Driver on page 412 describes how to do this 112 9 1 1 DRIVER CHARACTERIZATION Typical ROM requirements are summarized in Table 9 2 IAR EWARM v6 40 with high size optimization Provided Device Drivers The ROM data were collected on R ROM Thumb ROM ARM Driver Mode Mode RAM disk 0 4 kB 0 6 kB SD MMC CardMode 3 9 kB 6 2 kB SD MMC SPI 4 7 kB 7 3 kB NOR 5 7 kB 9 1 kB MSC 0 6 kB 0 9 kB Not including BSP Not including pC USB Table 9 2 Driver ROM requirements Using the generic controller and software ECC not including BSP Typical RAM requirements are summarized in Table 9 3 118 Chapter 9 Driver RAM Overhead RAM Per Device MSC 12 bytes 32 bytes NOR 4 bytes bytes RAM disk 4 bytes 24 bytes SD MMC CardMode 4 bytes 64 bytes SD MMC SPI 4 bytes 52 bytes Table 9 3 Driver RAM requirements Not including uC USB See section 14 2 Driver amp Device Characteristics on page 202 Performance can v
115. FS_NAND BSP WaitWhileBusy 9 ti Listing 13 9 Example BSP API structure for generic controller A proper BSP should implement all of these functions OPEN CLOSE FUNCTIONS The Open and Close functions will be called respectively by FSDev_Open and FSDev_Close Typically FSDev_Open is called during initialization and FSDev_Close is never called closing a fixed device doesn t make much sense When implementing the Open function of the BSP layer you should add all necessary code for the hardware initialization That might include setting up the memory controller general settings and timings for the bank associated with the NAND device configuring the chip select and ready busy through either the memory controller or GPIO configuring the memory controller clock configuring the memory controller I O pins etc The Close function is typically left empty 189 Chapter 13 CHIP SELECTION FUNCTIONS The ChipSelEn and ChipSelDis are called in pairs each time the device must be accessed In these functions you should implement any chip selection mechanism needed If the bus and or hardware is shared with more than one task the chip selection functions should also implement proper locking If the shared bus and or hardware must be configured differently when used outside the NAND driver the configuration changes must be done within the ChipSelEn and ChipSelDis functions COMMAND WRITE FUNCTION The CmdWr f
116. HAR path_ buf reg_val OSTaskRegGet p_tcb FS_OS_REG ID WORKING DIR amp os err if os_err OS_ERR_NONE return if reg val Ou 1 return path_buf CPU_CHAR reg val FS WorkingDirObjFree path buf 2 endif Listing C 2 FS_OS_WorkingDirFree uC OS III LC 2 1 If the register value is zero no working directory has been assigned and no action need be taken LC 2 2 FS WorkingDirObjFree frees the working directory object to the working directory pool If this were not done the unfreed object would constitute a memory leak that could deplete the heap memory eventually 407 Appendix C The character string for the working directory is allocated from the uC LIB heap If a task is deleted it must be freed made available for future allocation to avert a crippling memory leak The internal file system function FS WorkingDirObjFree releases the string to an object pool In the port for pC OS II that function is called by FS OS WorkingDirFree which must be called by the assigned task delete hook FS_OS_Dly_ms Device drivers and example device driver ports delay task execution FS OS Dly ms Common functions allow BSP developers to optimize implementation easily A millisecond delay may be accomplished with an OS kernel service if available The trivial implementation of a delay particularly a sub millisecond delay is a while loop better performance may be achieved with hardware timer
117. HAR xname dev FS_ERR p err void FSDev_Open CPU_CHAR name_dev void p dev cfg FS_ERR p err FS PARTITION NBR FSDev_PartitionAdd CPU_CHAR name_dev FS SEC OTY partition size FS ERR p err void FSDev PartitionFind CPU CHAR name dev FS PARTITION NBR FS PARTITION ENTRY partition_nbr p partition entry FS ERR p err void FSDev PartitionInit CPU _ CHAR name_ dev FS SEC OTY partition size FS ERR p err void FSDev Query CPU CHAR name dev FS DEV INFO p info FS ERR p err void FSDev_Rd CPU_CHAR name_dev void p dest FS_SEC_NBR start FS SEC QTY cnt FS_ERR p err CPU_BOOLEAN FSDev_Refresh CPU_CHAR name_dev FS_ERR p err 271 Appendix A void FSDev_Wr CPU_CHAR name_dev void p src FS_SEC_NBR start FS SEC QTY cnt FS_ERR p err 272 A 3 1 FSDev_AccessLock void FSDev_AccessLock CPU CHAR name_dev CPU_INT32U timeout FS_ERR p err File Called from Code enabled by fs_dev c Application N A Acquire exclusive access to a device See also section 5 4 Raw Device IO on page 72 ARGUMENTS name_dev Device name timeout Time to wait for a lock in milliseconds p err Pointer to variable that will receive return error code from this function FS ERR NONE Device removed successfully FS ERR DEV NOT OPEN Device is not open FS ERR NAME NULL Argument name dev passed a NULL pointer FS ERR OS LOCK Error acquiring device access lock FS
118. H_CLASS DEV_STATE REMOVED MASS STORAGE DEVICE REMOVED FSDev_MSC_DevClose p_msc_dev USBH_MSC_RefRel p_msc_dev break default break Listing 15 2 HC USB MSC notification function If the file system and USB stack initialization succeed the file system will produce the trace output as shown in Figure 15 1 Gf a sufficiently high trace level is configured when the a MSC device is connected See section E 9 Trace Configuration on page 507 about configuring the trace level COM1 PuTTY Figure 15 1 MSC detection trace output EEN Chapter 15 222 Appendix UC FS API Reference This chapter provides a reference to uC FS services The following information is provided for each entry A brief description of the service The function prototype The filename of the source code The define constant required to enable code for the service A description of the arguments passed to the function A description of returned value s Specific notes and warnings regarding use of the service One or two examples of how to use the function Many functions return error codes These error codes should be checked by the application to ensure that the uC FS function performed its operation as expected Each of the user accessible file system services is presented in alphabetical order within an appropriate section the section for a particular function can be determined from its name 223 Appendix A
119. However the uC FS source code is delivered with port examples Mierium Software uC FS Examples BSP Dev lt memory type gt lt manufacturer gt lt board name gt fs_dev_ lt memory type gt _bsp c Micrium This directory contains all software components and projects provided by Micrium 50 uC FS OS Abstraction Layer Software This sub directory contains all the software components and projects uc FS This is the main nC FS directory Examples This is where you will find the device driver BSP example files Dev lt memory type gt This is where you will find the examples BSP for one memory type The lt and gt are not part of the actual name The memory types supported by uC FS are the following NAND NOR SD CARD SD SPI lt manufacturer gt The name of the manufacturer of the evaluation board The lt and gt are not part of the actual name 3 12 HC FS OS ABSTRACTION LAYER This directory contains the RTOS abstraction layer which allows the use of uC FS with nearly any commercial of in house RTOS or without any RTOS at all The abstraction layer for the selected RTOS is placed in a sub directory under OS as follows Micrium Software uC FS VOS lt rtos_name gt fs_os c fs_os h Micrium This directory contains all software components and projects provided by Micrium Software This sub directory contains all the software components and projects 51 Chapter
120. ID LOW FMT APP_TRACE_DBG FSDev_NOR_LowFmt nor 0 if err FS ERR NONE APP_TRACE_DBG return DEF FAIL break default APP_TRACE DBG return DEF FAIL opening device failed w err H 4 ay low level format failed r n Sd r n r n err Device error 205 Chapter 14 Ze 5 SS FSVol_Open CPU_CHAR nor 0 a CPU_CHAR nor 0 b FS PARTITION NBR 0 c FS_ERR amp err switch err case FS_ERR_NONE APP_TRACE_DBG opened volume mounted r n break case FS ERR PARTITION NOT FOUND Volume error APP TRACE DG opened device not formatted r n FSVol_Fmt nor 0 void 0 amp err 6 if err FS ERR NONE APP TRACE DBG format failed r n return DEF_FAIL break default Device error Ey APP_TRACE_DBG opening volume failed w err d r n r n err return DEF FAIL return DEF OK Listing 14 1 Opening a NOR device volume L14 1 1 Register the NOR device driver FSDev NOR L14 1 2 The NOR device configuration should be assigned For more information about these parameters see section D 3 FS_DEV_NOR_CFG on page 485 114 13 FSDev_Open opens initializes a file system device The parameters are the device name 3a and a pointer to a device driver specific configuration structure 3b The device name 3a s composed of a device driver name nor
121. INCOMPATIBLE LOW PARAMS will be returned A low level format is required If an existing and compatible on device low level format is found but is not usable because of some metadata corruption FS ERR DEV CORRUPT LOW FMT will be returned A chip erase and or low level format is required 371 Appendix A A 10 3 FSDev_NAND_LowUnmount void FSDev_NAND LowUnmount CPU CHAR name dev FS_ERR p err File Called from Code enabled by fs_dev_nand c Application N A Low level unmount a NAND device ARGUMENTS name_dev Device name see Note p err Pointer to variable that will the receive return error code from this function FS ERR NONE Device low level unmounted successfully FS ERR NAME NULL Argument name dev passed a NULL pointer FS ERR DEV INVALID Argument name dev specifies an invalid device FS ERR DEV NOT OPEN Device is not open FS ERR DEV NOT PRESENT Device is not present FS ERR DEV IO Device 1 O error FS ERR DEV TIMEOUT Device timeout RETURNED VALUE None NOTES WARNINGS The device must be a NAND device eg nand 0 Low level unmounting clears software knowledge of the on disk structures forcing the device to again be low level mounted or formatted prior to further use 372 A 11 NOR DRIVER FUNCTIONS void FSDev_NOR_LowFmt CPU_CHAR name dev FS_ERR p err void FSDev_NOR_LowMount CPU_CHAR name dev FS_ERR p err void FSDev_NOR_LowUnmount CPU CH
122. INGS None 443 Appendix C EXAMPLE The implementation of FSDev SD Card BSP CmdDataWr in Listing C 10 is targeted for the same host controller as the other listings in this chapter for more information see FSDev SD Card BSP CmdStart void FsDev SD Card BSP CmdDataWr FS QTY unit nbr FS DEV SD CARD CMD p cmd void p src FS DEV SD CARD ERR p err CPU INT16U interrupt status CPU INT16U error status CPU INT16U timeout timeout Ou Wait until data xfer compl 1 interrupt_status REG_INTERRUPT_STATUS while DEF BIT IS CLR interrupt status BIT INTERRUPT STATUS ERROR BIT INTERRUPT STATUS TRANSFER COMPLETE DEF YES timeout interrupt status REG INTERRUPT STATUS if timeout TIMEOUT TRANSFER MAX p err FS DEV SD CARD ERR WAIT TIMEOUT return Handle error kj 2 if DEF BIT IS SET interrupt status BIT INTERRUPT STATUS ERROR DEF YES error status REG ERROR STATUS if DEF BIT IS SET error status REG ERROR STATUS DATA END BIT DEF YES p err FS DEV SD CARD ERR DATA else if DEF BIT IS SET error status REG ERROR STATUS DATA CRC DEF YES p err FS DEV SD CARD ERR DATA CRC else if DEF BIT IS SET error status REG ERROR STATUS DATA TIMEOUT DEF YES p err FS DEV SD CARD ERR DATA TIMEOUT else p err FS DEV SD CARD ERR UNKONWN REG ERROR STATUS REG INTERRUPT STATUS return error status interrupt statu
123. IRED CONFIGURATION Available only if FS SHELL CFG LS EN is DEF ENABLED NOTES WARNINGS The output resembles the output from the standard UNIX command Is l See the figure below jun jun 0 jun 9 jun jun jun Figure F 6 fs_Is output 521 Appendix F F 3 7 fs_mkdir Make a directory USAGES fs mkdir dir ARGUMENTS dir Directory path OUTPUT None REQUIRED CONFIGURATION Available only if FS SHELL CFG MKDIR EN is DEF ENABLED and FS CFG RD ONLY EN is DEF_DISABLED NOTES WARNINGS None 522 F 3 8 fs_mkfs Format a volume USAGES fs mkfs vol ARGUMENTS vol Volume name OUTPUT None REQUIRED CONFIGURATION Available only if FS SHELL CFG MKFS EN is DEF ENABLED and FS CFG RD ONLY EN is DEF DISABLED NOTES WARNINGS None 523 Appendix F F 3 9 fs mount Mount volume USAGES fs mount dev vol ARGUMENTS dev Device to mount vol Name which will be given to volume OUTPUT None REQUIRED CONFIGURATION Available only if FS SHELL CFG MOUNT EN is DEF ENABLED NOTES WARNINGS None 524 F 3 10 fs_mv Move files USAGES fs mv source entry dest entry fs mv source entry dest dir ARGUMENTS source entry Source entry path dest entry Destination entry path dest dir Destination directory path OUTPUT None REQUIRED CONFIGURATION Available only if FS SHELL CFG MV EN is DEF ENABLED and FS CFG RD ONLY EN is DEF DISABLED NOTES WARNINGS
124. LAGS mode FS ERR p err void FSVol CacheInvalidate CPU CHAR name vol FS ERR p err void FSVol CacheF lush CPU CHAR name vol FS ERR p err 356 A 8 1 FSVol_CacheAssign void FSVol_CacheAssign CPU CHAR FS VOL CACHE API name vol p cache api void p cache data CPU _INT32U size CPU INTO8U pet mgmt CPU _INTO8U pet dir FS FLAGS mode FS ERR p err File Called from Code enabled by fs vol c Application FS CFG CACHE EN Assign cache to a volume ARGUMENTS name vol Volume name p cache api Pointer to a cache API to use OR b NULL if default cache API should be used p cache data Pointer to cache data size Size in bytes of cache buffer pct mgmt Percent of cache buffer dedicated to management sectors pct dir Percent of cache buffer dedicated to directory sectors mode Cache mode FS VOL CACHE MODE WR THROUGH FS VOL CACHE MODE WR BACK FS VOL CACHE MODE RD 357 Appendix A p_err Pointer to variable that will receive return error code from this function FG ERR NONE Cache created FS ERR NAME NULL name_vol passed a NULL pointer FS ERR VOL NOT OPEN Volume not open FS ERR NULL PIR p cache data passed a NULL pointer FS ERR CACHE INVALID MODE Mode specified invalid FS ERR CACHE INVALID SEC TYPE Sector type sepecified invalid FS ERR CACHE TOO SMALL Size specified too small for cache RETURNED VALUE None NOTES WARNINGS None 358 A 8 2 FSVol_Cacheln
125. LE BUF EN is DEF DISABLED FS_CFG_FILE_LOCK_EN FS CFG FILE LOCK EN enables when set to DEF ENABLED or disables when set to DEF DISABLED code generation of file lock functions When enabled a file can be locked across several operations when disabled a file is only locked during a single operation and the functions in the following table will not be available Function File fs flockfile fs api c fs funlockfile fs api c fs ftrylockfile fs api c FSFile LockGet fs file c FSFile_LockSet fs file c FSFile LockAccept fs file c 500 Table E 4 File lock function exclusion These functions are not included if FS CFG_FILE LOCK EN is DEF DISABLED FS_CFG_ PARTITION EN When FS CFG PARTITION EN is enabled DEF ENABLED volumes can be opened on secondary partitions and partitions can be created When it is disabled DEF DISABLED volumes can be opened only on the first partition and the functions in the following table will not be available The function FSDev PartitionInit which initializes the partition structure on a volume will be included in both configurations Function File FSDev GetNbrPartitions fs deu FSDev PartitionAdd fs dev c FSDev PartitionFind fs dev c Table E 5 Partition function exclusion These functions are not included if FS CFG PARTITION EN is DEF DISABLED FS_CFG WORKING DIR EN When FS CFG WORKING DIR EN is enabled DEF ENABLED file system operations ca
126. LL B 4 DEVICE ERROR CODES FS ERR DEV FS ERR DEV ALREADY OPEN FS ERR DEV CHNGD FS ERR DEV FIXED FS ERR DEV FULL FS ERR DEV INVALID FS ERR DEV INVALID CFG FS ERR DEV INVALID ECC FS ERR DEV INVALID IO CTRL FS ERR DEV INVALID LOW FMT FS ERR DEV INVALID LOW PARAMS FS ERR DEV INVALID MARK FS ERR DEV INVALID NAME FS ERR DEV INVALID OP FS ERR DEV INVALID SEC NBR FS ERR DEV INVALID SEC SIZE FS ERR DEV INVALID SIZE FS ERR DEV INVALID UNIT NBR FS ERR DEV IO FS ERR DEV NONE AVAIL FS ERR DEV NOT OPEN FS ERR DEV NOT PRESENT FS ERR DEV TIMEOUT FS ERR DEV UNIT NONE AVAIL FS ERR DEV UNIT ALREADY EXIST FS ERR DEV UNKNOWN FS ERR DEV VOL OPEN FS ERR DEV INCOMPATIBLE LOW PARAMS FS ERR DEV INVALID METADATA 394 Mode specified invalid Device already open Device has changed Device access error Device already open Device has changed Device is fixed cannot be closed Device is full no space could be allocated Invalid device Invalid dev cfg Invalid ECC I O control invalid Low format invalid Invalid low level device parameters Invalid mark Invalid device name Invalid operation Invalid device sec nbr Invalid device sec size Invalid device size Invalid device unit nbr Device I O error No device avail Device not open Device not present Device timeout No unit avail Unit already exists Unknown Vol open on dev Incompatible low level device parameters Device d
127. LOC if timeout Ou sem_val 0u while sem val Ou CPU CRITICAL ENTER sem val p sem If semaphore available if sem val gt Ou p sem sem val lu fe decrement semaphore count Ss CPU CRITICAL EXIT else timeout ents timeout FS BSP CNTS PER MS sem val 0 while timeout ents gt Ou amp amp sem val 0u CPU_CRITICAL ENTER sem val p sem If semaphore available if sem_val gt 0 p sem sem val lu Z decrement semaphore count SCH CPU_CRITICAL EXIT timeout_cnts if sem val Ou return DEF FAIL else return DEF OK Listing C 5 FS_OS_Sem trivial implementations continued LC 5 1 FS OS SemCreate creates a semaphore in the variable p_sem For this trivial implementation FS BSP SEM is a integer type which stores the current count i e the number of objects available LC 5 2 FS OS SemDel deletes a semaphore created by FS OS SemCreate 410 CPU BOOLEAN FS OS SemPost FS BSP SEM p sem 4 CPU INT16U sem val CPU Sp ALLOC CPU CRITICAL ENTER sem val p sem Increment semaphore value sem val p sem sem val CPU _CRITICAL EXIT return DEF OK Listing C 6 FS_OS_Sem trivial implementations continued LC 6 3 FS OS SemPend waits until a semaphore is signaled If a zero timeout is given the wait is possibly infinite Git never times
128. NAND CTRLR GEN BSP API Listing 13 8 BSP API type for the generic controller layer implementation Typically you will provide the board support package implementation See section 13 8 1 BSP Development Guide Generic Controller on page 189 for details on how to implement the BSP layer 13 6 BOARD SUPPORT PACKAGE OTHER CONTROLLERS If you use a different controller layer implementation than the generic you will typically need a BSP layer implementation identical or mostly similar Please refer to section 13 5 Board Support Package Generic Controller on page 185 unless there is a section of this chapter dedicated to your BSP 186 Performance Considerations 13 7 PERFORMANCE CONSIDERATIONS Several performance aspects can be considered when using the NAND driver Depending on your priorities you will need to configure and use the NAND driver in a proper way so that your specific goals are met The different performance metrics include the write and read speed the RAM usage the data safety level and the worst case locking time CHOOSING AN APPROPRIATE SECTOR SIZE It is important to choose carefully the sector size for each device Unless your device supports partial page programming it is mandatory for the sector size to be identical to the page size or larger If your device supports partial page programming it is possible for you to set a sector size smaller than the page size as long as it does not force the d
129. NULL Argument name dev passed a NULL pointer Or device access error see section B 4 Device Error Codes on page 394 RETURNED VALUE Number of partitions on the device if no error was encountered Zero otherwise NOTES WARNINGS Device state change will result from device I O not present or timeout error 279 Appendix A A 3 8 FSDev_Invalidate void FSDev_Invalidate CPU CHAR name dev FS ERR p err File Called from Code enabled by fs deu Application N A Invalidate files and volumes opened on a device See also section 5 4 Raw Device IO on page 72 ARGUMENTS name dev Device name p err Pointer to variable that will receive return error code from this function FS ERR NONE Partition added FS ERR NAME NULL Argument name dev passed a NULL pointer Or device access error see section B 4 Device Error Codes on page 394 RETURNED VALUE None NOTES WARNINGS 1 Operations on an affected file or volume will fail with an FS_ERR_DEV_CHNGD error 2 Invalidation will happen automatically following a removable media change 280 A 3 9 FSDev_Open void FSDev_Open CPU CHAR name dev void p dev cfg FS ERR p err File Called from Code enabled by fs deu Application N A Open a device ARGUMENTS name dev Device name See section 4 3 uC FS File and Directory Names and Paths on page 62 for information about device names p dev efg Pointer to
130. P CACHE EN This define determines if the dirty blocks map will be cached With this feature enabled a copy of the dirty blocks map on the device is cached It is possible then to determine if the state dirty of a block is committed on the device without the need to actually read the device With this feature enabled overall write and read speed should be improved Also robustness will be improved for specific cases However more RAM will be consumed RAM usage lt Nbr of blks on device gt 8 octets The result should be rounded up FS_NAND CFG _UPDATE_BLK_TBL_SUBSET_SIZE This define controls the size of the subsets of sectors pointed by each entry of the update block tables The value must be a power of 2 or 0 If for example the value is 4 each time a specific updated sector is requested the NAND translation layer must search the sector in a group of four sectors Thus if the update block metadata cache FS_NAND CFG UPDATE BLK META CACHE EN is disabled four sectors must be read from the device to find the requested sector The four entries will instead be read 172 NAND Translation Layer from the cache if it is enabled If the value is set to 0 the table will be disabled completely meaning that all sectors of the block might have to be read before the specified sector is found If the value is 1 the table completely specifies the location of the sector and thus no search must be performed In that case enabli
131. PI The application should NOT use the same bus to access another device until the matching call to Unlock has been made The clock frequency set by the SetClkFreq function is a parameter of the device not the bus If multiple devices are located on the same bus those parameters must be saved in memory when set and restored by Lock The same should be done for initialization parameters such as transfer unit size and shift direction that vary from device to device 460 C 7 4 Rd void FSDev BSP SPI Rd FS OTY unit nbr void p dest CPU SIZE T ent File Called from Code enabled by fs_dev_ lt dev_name gt _bsp c Device driver N A Read from SPI bus ARGUMENTS unit_nbr Unit number of device p dest Pointer to destination buffer ent Number of octets to read RETURNED VALUE None NOTES WARNINGS None 461 Appendix C C 7 5 Wr void FSDev BSP SPI Wr FS OTY unit nbr void p src CPU SIZE T ent File Called from Code enabled by fs dev lt dev name gt bsp c Device driver N A Write to SPI bus ARGUMENTS unit nbr Unit number of device p src Pointer to source buffer ent Number of octets to write RETURNED VALUE None NOTES WARNINGS None 462 C 7 6 ChipSelEn ChipSelDis void FSDev BSP SPI ChipSelEn FS OTY unit nbr void FSDev BSP SPI ChipSelDis FS OTY unit nbr File Called from Code enabled by fs dev lt dev name gt bsp c Device dri
132. R name_dev FS PARTITION NBR FS ERR partition_nbr p err 335 Appendix A void FSVol_Query CPU_CHAR name_vol FS VOL INFO p info FS ERR p err void FSVol Rd CPU CHAR name vol void p dest FS SEC NBR start FS SEC OTY ent FS ERR p err void FSVol We CPU CHAR name vol void p src FS SEC NBR start FS SEC OTY ent FS ERR p err 336 A 7 1 FSVol_Close void FSVol Close CPU CHAR name vol FS_ERR p err File Called from Code enabled by fs vol c Application N A Close and free a volume ARGUMENTS name_vol Volume name p err Pointer to variable that will receive the return error code from this function See Note 2 FS ERR NONE Volume opened FS ERR NAME NULL Argument name vol passed a NULL pointer FS ERR VOL NOT OPEN Volume not open RETURNED VALUE None NOTES WARNINGS None 337 Appendix A A 7 2 FSVol_Fmt void FSVol Fmt CPU CHAR name vol File void p fs cfg FS_ERR p err Called from Code enabled by fs vol c Application not FS_CFG_RD_ONLY_EN Format a volume ARGUMENTS name_vol p fs cfg p err Colume name Pointer to file system driver specific configuration For all file system drivers if this is a pointer to NULL then the default configuration will be selected More information about the appropriate structure for the FAT file system driver can be found in Chapter 6 Pointer to variable that will
133. Rsvd CPU_INT16U EraseCntDiffTh FS DEV NOR PHY API PhyPtr CPU_INTO8U BusWidth CPU_INTO8U BusWidthMax CPU INTO8U PhyDevCnt CPU_INT32U MaxClkF req FS DEV WOR CFG File Used for fs_dev_nor h Second argument of FSDev_Open when opening a NOR device Configures the properties of a NOR device that will be opened A pointer to this structure is passed as the second argument of FSDev_Open for a NOR device MEMBERS AddrBase must specify 1 the base address of the NOR flash memory for a parallel NOR 2 0x00000000 for a serial NOR RegionNbr must specify the block region which will be used for the file system area Block regions are enumerated by the physical layer driver for more information see the physical layer driver header file on monolithic devices devices with only one block region this must be 0 485 Appendix D 1 the absolute start address of the file system area in the NOR flash memory 2 the offset of the start of the file system in the NOR flash for a serial NOR The address specified by AddrStart MUST lie within the region RegionNbr must specify the number of octets that will belong to the file system area must specify the sector size for the NOR flash either 512 1024 2048 or must specify the percentage of sectors on the NOR flash that will be reserved for extra file system storage to improve efficiency This value must be between 5 and 35 except if 0 is specified wh
134. S ERR DEV NOT PRESENT Device is not present FS ERR DEV IO Device I O error FS ERR DEV TIMEOUT Device timeout 362 RETURNED VALUE None NOTES WARNINGS The device must be a SD MMC device for FSDev SD Card QuerySD e g sdcard 0 for FSDev_SD SPI QuerySD e g sd 0 363 Appendix A A 9 2 FSDev_SD_xxx_RdCID void FSDev_SD Card RJCID CPU CHAR name_dev CPU INTO8U p info FS ERR p err void FSDev SD SPI RJCID CPU CHAR name dev CPU INTO8U p info FS ERR p err File Called from Code enabled by fs dev sd card c Application N A fs dev sd spi c Read SD MMC Card ID CID register ARGUMENTS name dev Device name see Note 1 p_dest Pointer to 16 byte buffer that will receive SD MMC Card ID register p err Pointer to variable that will the receive return error code from this function FS ERR NONE SD MMC Card ID register read FS ERR NAME NULL Argument name dev passed a NULL pointer FS ERR NULL PTR Argument p dest passed a NULL pointer FS ERR DEV INVALID Argument name dev specifies an invalid device FS ERR DEV NOT OPEN Device is not open FS ERR DEV NOT PRESENT Device is not present FS ERR DEV IO Device I O error FS ERR DEV TIMEOUT Device timeout 364 RETURNED VALUE None NOTES WARNINGS B The device must be a SD MMC device for FSDev_SD Card QuerySD e g sdcard 0 for FSDev SD SPI QuerySD e g sd 0 B For SD cards the structure of the CID i
135. S II The Real Time Kernel Micrium Press 2009 ISBN 978 0 98223375 3 0 L gar Christian 2010 wC TCP IP The Embedded Protocol Stack Micrium Press 2010 ISBN 978 0 98223375 0 9 POSIX 2008 The Open Group Base Specifications Issue 7 IEEE Standard 1003 1 2008 Programming Lauguages C ISO IEC 9899 1999 The Motor Industry Software Reliability Association MISRA C 2004 Guidelines for the Use of the C Language in Critical Systems October 2004 www misra c com http www clusterbuilder org Cho H Shin D Eom Y I 2009 KAST K Associative Sector Translation for NAND Flash Memory in Real Time Systems Architecture 507 512 IEEE 535 Appendix G 536 Appendix UC FS Licensing Policy H 1 uC FS LICENSING H 1 1 uC FS SOURCE CODE This book contains uC FS precompiled in linkable object form an evaluation board and tools compiler assembler linker debugger Use uC FS for free as long as it is only used with the evaluation board that accompanies this book You will need to purchase a license when using this code in a commercial product where the intent is to make a profit Users do not pay anything beyond the price of the book evaluation board and tools as long as they are used for educational purposes You will need to license pC FS if you intend to use pC FS in a commercial product where you intend to make a profit You need to purchase this license when you make the decision to use HC FS in a design not when
136. S RegIdWorkingDir OS_REG reg val amp os err if os err OS ERR NONE p err FS ERR OS return p err FS ERR NONE endif Listing C 1 FS_ OS WorkingDirGet Set uC OS III LC 1 1 FS OS WorkingDirGet gets the pointer to the working directory associated with the active task In pC OS III the pointer is stored in one of the task registers a set of software data that is part of the task context Gust like hardware register values The implantation casts the integral register value to a pointer to a character If no working directory has been assigned the return value must be a pointer to NULL In the case of uC OS III that will be done because the register values are cleared upon task creation 406 LC 1 2 FS OS WorkingDirSet associates a working directory with the active task The pointer is cast to the integral register data type and stored in a task register The application calls either of the core file system functions FS WorkingDirSet or fs chdir to set the working directory The core function forms the full path of the working directory and saves it with the OS port function FS_OS WorkingDirSet The port function should associate it with the task in some manner so that it can be retrieved with FS OS WorkingDirGet even after many context switches have occurred if FS CFG WORKING DIR EN DEF ENABLED void FS OS WorkingDirFree OS TCB p tcb OS_ERR os err CPU INT32U reg val CPU_C
137. SDev SD Card BSP CmdStart void FSDev SD Card BSP CmdDataRd FS QTY unit nbr FS DEV SD CARD CMD p cmd void p dest FS DEV SD CARD ERR p err CPU_INT16U interrupt status CPU INT16U error status CPU INT16U timeout timeout Ou Wait until data xfer compl 1 interrupt status REG INTERRUPT STATUS while DEF BIT IS CLR interrupt status BIT INTERRUPT STATUS ERROR BIT INTERRUPT STATUS TRANSFER COMPLETE DEF YES timeout interrupt status REG INTERRUPT STATUS if timeout TIMEOUT TRANSFER MAX p err FS DEV SD CARD ERR WAIT TIMEOUT return Handle error ki 2 if DEF BIT IS SET interrupt status BIT INTERRUPT STATUS ERROR DEF YES error status REG ERROR STATUS if DEF BIT IS SET error status REG ERROR STATUS DATA END BIT DEF YES p err FS DEV SD CARD ERR DATA else if DEF BIT IS SET error status REG ERROR STATUS DATA CRC DEF YES p err FS DEV SD CARD ERR DATA CRC else if DEF BIT IS SET error status REG ERROR STATUS DATA TIMEOUT DEF YES p err FS DEV SD CARD ERR DATA TIMEOUT else p err FS DEV SD CARD ERR UNKONWN REG_ERROR_STATUS error_status REG INTERRUPT STATUS interrupt status return p err FS DEV SD CARD ERR NONE 3 ke Listing C 9 FSDev_ SD Card _BSP_CmdDataRd 441 Appendix C LC 9 1 LC 9 2 LC 9 3 442 Wait until data transfer completes or an error occurs The wait lo
138. SPI mode communication sequence F12 11 1 When no data is being transmitted DataOut line is held high F12 11 2 During busy signaling DataOut line is held low F12 11 3 The CRC is the 16 bit CCITT CRC By default this is optional and dummy bytes may be transmitted instead The card only checks the CRC if CRC_ON_OFF has been executed 154 Using the SD MMC SPI Driver Start bit Transmission bit Command Argument format 32 bits Start bit Address Out Of Range Block Length Error Address Misalign Erase Sequence Error Com CRC Error Illegal Command Switch Error Erase Reset In Idle State Response Additional format response if any See a R1 Response Figure 12 12 SD MMC SPI mode command and response formats 155 Chapter 12 Power On GO_IDLE_STATE 1 Inactive state Invalid Valid command command SEND_IF_COND 2 Invalid y y command ros SD_SEND_OP_COND SD_SEND_OP_COND 3 3 y EI D KE SEND OP COND oA READ_OCR 4 5 READ_OCR CCS in 5 response v v v MMC V1 x Standard V2 0 Standard V2 0 High Capacity SD card Capacity SD card Capacity SD card y 8e SEND CID 6 SS SS 85 D ae ER SEND CSD 7 SE ga Figure 12 13 Simplified SD MMC SPI mode initialization and state transitions The initialization process reveals that commands can be executed and
139. T size FS_ERR p err void FSFile BufFlush FS FILE p file FS_ERR p_err For more information about and an example Configuring a File Buffer on page 104 POSIX API Equivalent int fs_setvbuf FS FILE stream char buf int mode fs size t size int fs fflush FS FILE stream of configuring a file buffer see section 8 3 3 87 Chapter 6 6 1 4 FILE ERROR FUNCTIONS The file module has functions get and clear a file s error status that are almost exact equivalents to POSIX API functions the primary difference is the advantage of valuable return error codes to the application File Module Function void FSFile ClrErr FS_FILE p file FS ERR p err CPU BOOLEAN FSFile IsErr FS FILE p file FS ERR p err CPU BOOLEAN FSFile IsEOF FS FILE p file FS ERR p err POSIX API Equivalent void fs clearerr FS FILE stream int fs ferror FS FILE stream int fs feof FS FILE stream For more information about this functionality see section 8 3 4 Diagnosing a File Error on page 106 6 1 5 ATOMIC FILE OPERATIONS USING FILE LOCK The file module has functions lock files across several operations that are almost exact equivalents to POSIX API functions the primary difference is the advantage of valuable return error codes to the application File Module Function void FSFile_LockGet FS_FILE p file FS ERR p err void FSFile LockAccept FS FILE p file FS ERR p err v
140. TS should generally be set to the platform natural alignment for performance reasons FS_CFG_API_EN FS CFG API EN enables when set to DEF ENABLED or disables when set to DEF DISABLED code generation of the POSIX API functions This API includes functions like fs fopen or fs opendir which mirror standard POSIX functions like fopen or opendir 498 FS_CFG_DIR_EN FS CFG DIR EN enables when set to DEF ENABLED or disables when set to DEF DISABLED code generation of directory access functions When disabled the functions in the following table will not be available Function File fs_opendir fs api c fs closedir fs api c fs readdir r fs api c FSDir Open fs dir c FSDir_Close fs dir c FSDir_Rd fs dir c Table E 2 Directory function exclusion These functions are not included if FS_CFG_DIR_EN is DEF_DISABLED 499 Appendix E E 2 FEATURE INCLUSION CONFIGURATION Individual file system features may be selectively disabled FS_CFG FILE BU EN FS CFG BUF EN enables when set to DEF ENABLED or disables when set to DEF_DISABLED code generation of file buffer functions When disabled the functions in the following table will not be available Function File fs fflush fs api c fs setbuf fs api c fs setvbuf fs api c FSFile BufAssign fs file c FSFile BufFlush fs file c Table E 3 File buffer function exclusion These functions are not included if FS CFG_FI
141. _DevDrvAdd FS_DEV_API amp FSDev_SD_SPI 1 FS_ERR amp err if err FS ERR NONE amp amp err FS ERR DEV DRV ALREADY ADDED return DEF FAIL 150 Using the SD MMC SPI Driver 2 FSDev_Open CPU_CHAR sd 0 a void yO b EFS ERR amp err switch err case FS ERR NONE break case FS ERR DEV case FS ERR DEV IO case FS ERR DEV TIMEOUT case FS ERR DEV NOT PRESENT return DEF FAIL default return DEF FAIL AS 3 ef FSVol Open CPU CHAR sd 0 a CPU_CHAR sd 0 b FS PARTITION NBR 0 L c FS_ERR amp err switch err case FS_ERR_NONE APP_TRACE_DBG Opened volume mounted r n break case FS ERR DEV case FS ERR DEV 10 case FS ERR DEV _TIMEOUT case FS ERR DEV NOT PRESENT case FS ERR PARTITION NOT FOUND APP TRACE DBG opened device unmounted r n return DEF_FAIL default APP_TRACE_DBG opening volume failed w err d r n r n err return DEF FAIL return DEF OK Listing 12 2 Opening a SD MMC device volume L12 2 1 Register the SD MMC SPI device driver FSDev_SD SPI 151 Chapter 12 L12 2 2 L12 2 3 FSDev Open opens initializes a file system device The parameters are the device name la and a pointer to a device driver specific configuration structure 1b The device name la is composed of a device driver name sd a single col
142. _NAND BLK OTY BlkCnt 1 FS_NAND PG PER BLK OTY PgPerBlk 2 PS Mann PG SIZE PgSize 3 PS Mann PG SIZE SpareSize 4 CPU_INTO8U NbrPgmPerPg 5 CPU_INTO8U BusWidth 6 CPU_INTO8U ECC_NbrCorrBits 7 FS_NAND PG SIZE ECC _Codewordsize 8 FS_NAND DEFECT MARK TYPE DefectMarkType 9 FS_NAND BLK OTY MaxBadB1kCnt 10 CPU_INT32U MaxBlkErase 11 FS_NAND FREE SPARE DATA FreeSpareMap 12 FS_NAND PART STATIC CFG Listing 13 5 NAND static part layer configuration structure L13 5 1 Number of blocks in your device L13 5 2 Number of pages per block in your device L13 5 3 Page size in octets of your device L13 5 4 Size of the spare area in octets of your device 113 565 Number of partial page programming allowed before an erase operation for example it would be set to 4 if a device with 2048 octets pages could be written in 4 accesses of 512 octets L13 5 6 Number of input output lines of the device s bus L13 5 7 Minimum required number of correctable bits per codeword for the ECC L13 5 8 Codeword size required for ECC The codeword size corresponds to the maximum data size in octets that must be sent to the ECC calculation module to get a single error correction code 182 L13 5 9 L13 5 10 113 501 L13 5 12 Controller Layer Factory defect mark type This determines how the translation layer can detect if a block factory is marked as a defect block The possible values are listed belo
143. _dev_ramdisk h Second argument of FSDev_Open when opening a RAM disk Configures the properties of a RAM disk that will be opened A pointer to this structure is passed as the second argument of FSDev_Open for a RAM disk MEMBERS SecSize The sector size of RAM disk either 512 1024 2048 or 4096 Size The size of the RAM disk in sectors DiskPtr The pointer to the RAM disk NOTES None 488 D 5 FS DIR ENTRY struct fs_dirent typedef struct fs dirent CPU CHAR Name FS CFG MAX FILE NAME LEN lu FS ENIRY INFO Info FS DIR ENTRY File Used for fs_dir h Second argument of fs_readdir_r and FSDir Rd Receives information about a directory entry MEMBERS Name The name of the file Info Entry information For more information see section D 2 FS_DEV_INFO on page 484 NOTES None 489 Appendix D D 6 FS_ENTRY_INFO typedef struct fs entry info FS FLAGS Attrib FS FILE SIZE Size CLK TS SEC DateTimeCreate CLK TS SEC DateAccess CLK TS SEC DateTimeWr FS SEC QTY BlkCnt FS SEC SIZE BlkSize FS ENTRY INFO File Used for fs_entry h Second argument of FSEntry_Query and FSFileQuery The Info member of FS DIR ENTRY struct fs_dirent Receives information about a file or directory MEMBERS Attrib The file or directory attributes see section 6 2 1 File and Directory Attributes on page 90 Size The size of the file in octets DateTimeCrea
144. advanced features for these a released physical layer may need to be modified In all cases the manufacturer s reference should be compared to the driver description below Driver API Files Description FSDev_NOR_AMD 1x08 fs_dev_nor_amd_1x08 Supports CFl compatible devices with 8 bit data bus implementing AMD command set FSDev_NOR_AMD 1x16 fs_dev_nor_amd_1x16 Supports CFl compatible devices i with 16 bit data bus mplementing AMD command set FSDev_NOR_Intel_1x16 fs_dev_nor_intel Supports CFl compatible devices i with 16 bit data bus mplementing Intel command set FSDev_NOR_SST39 fs_dev_nor_sst39 Supports various SST SST39 devices with 16 bit data bus FSDev_NOR_STM29_ 1x08 fs dev nor stm29 1x08 Supports various ST M29 devices with 8 bit data bus FSDev_NOR STM29 1x16 fs dev nor stm29 1x16 Supports various ST M29 devices with 16 bit data bus FSDev_NOR_STM25 fs_dev_nor_stm25 Supports various ST M25 serial devices FSDev_NOR_SST25 214 fs dev nor sst25 Supports various SST SST25 serial devices Table 14 6 Physical layer drivers Physical Layer Drivers 14 5 1 FSDEV_NOR_AMD_1X08 FSDEV_NOR_AMD_1X16 FSDev_NOR_AMD 1x08 and FSDev_NOR_AMD 1x16 support CFI NOR flash implementing AMD command set including E Most AMD and Spansion devices E Most ST Numonyx devices B Others The fast programming command write to buff
145. ained FS ERR NULL PIR Argument p file passed a NULL pointer FS ERR INVALID TYPE Argument p file s type is invalid or unknown FS ERR FILE NOT OPEN File NOT open RETURNED VALUE DEF_NO if error indicator is NOT set or if an error occurred DEF YES if error indicator is set NOTES WARNINGS None 319 Appendix A A 6 7 FSFile_IsOpen CPU BOOLEAN FSFile IsOpen CPU CHAR name full FS FLAGS p mode FS ERR p err File Called from Code enabled by fs file c Application N A FSFile Open Test if file is already open ARGUMENTS name full D mode p err Name of the file See section 4 3 uC FS File and Directory Names and Paths on page 62 for information about file names Pointer to variable that will receive the file access mode see section 6 1 1 Opening Files on page 85 for the description the file access mode Pointer to variable that will receive the return error code from this function FS ERR NONE Error indicator obtained FS ERR NULL PTR Argument p file passed a NULL pointer FS ERR BUF NONE AVAIL No buffer available FS ERR ENTRY NOT FILE Entry NOT a file FS ERR NAME INVALID Invalid file name or path FS ERR VOL INVALID SEC NBR Invalid sector number found in directory entry RETURNED VALUE DEF_NO if file is NOT open DEF_YES if file is open NOTES WARNINGS None 320 A 6 8 FSFile_LockAccept void FSFile LockAccept FS FILE p file FS ERR p err
146. amed fs_dev_nand_ctrlr_ lt ext_name gt may also be required For more details on this driver please refer to Chapter 13 NAND Flash Driver on page 159 NOR This directory contains the NOR driver files fs_dev_nor are the device driver for NOR devices These files require a set of physical layer functions defined in a file name fe de nor lt physical type gt as well as BSP functions to be defined in a file named fs_dev_nor_bsp c to work with a particular hardware setup For more details on this driver please refer to Chapter 14 NOR Flash Driver on page 199 49 Chapter 3 RAMDisk This directory contains the RAM disk driver files fs_dev_ramdisk constitue the RAM disk driver For more details on this driver please refer to Chapter 11 RAM Disk Driver on page 131 sD This directory contains the SD MMC driver files fs_dev_sd are device driver for SD devices Theses files require to be used with either the fs dev sd spi for SPI one wire mode or fs_dev_sd_card for Card 4 wires mode files These files require a set of BSP functions to be defined in a file named either fs_dev sd spi bsp c or fs dev sd card bsp c to work with a particular hardware setup For more details on this driver please refer to Chapter 12 SD MMC Drivers on page 135 3 11 HC FS PLATFORM SPECIFIC SOURCE CODE These files are provided by the pC FS device driver developer See Chapter 17 Porting HC FS
147. an OS kernel networking TCP IP stack or USB stack that may integrate with pC FS A Windows based development platform is assumed The directories and files make references to typical Windows type directory structures However since uC FS is available in source form then it can certainly be used on Unix Linux or other development platforms This of course assumes that you are a valid nC FS licensee in order to obtain the source code The names of the files are shown in upper case to make them stand out The file names however are actually lower case 29 Chapter 3 FS_CFG H FS C H FS_API C H FS_BUF C H FS_CACHE C H FS_CFG_FS H FS_CTR H FS_DEF H FS_DEV C H FS_DIR C H FS_ENTRY C H ESP Platform Independent FS_ERR H FS_FILE C H FS_INC H FS_PARTITION C H FS_SYS C H FS_TYPE H FS_UNICODE C H FS_UTIL C H FS_VOL C H uCiFS Filesystem Driver FS_FAT C H FS_FAT_DIR C H FS_FAT_ENTRY C H FS_FAT_FAT12 C H FS_FAT_FAT16 C H FS_FAT_FAT32 C H FS_FAT_FILE C H FS_FAT_JOURNAL C H FS_FAT_LFN C H FS_FAT_SFN C H FS_FAT_TYPE H RIES Device Drivers FS_DEV_ C H D pGiFS Platform Specific APP C H FS_APP C H TE pense P Libraries LIB_ASCII C H LIB_DEF H LIB_MATH C H LIB_MEM C H LIB_STR C H CLK C H CLK_OS C H EDC_CRC C H ECC_HAMMING C H CRC_UTIL C H mers eps OS Specific FS_OS C H is mee Te pecific Board Support Package FS_DEV_ BSP C CPU H BSP C H CPU_
148. ananenenenrenenenenn 36 HC LIB Portable Library Functions nnnnnnoneeenenennnnee nen ennnnennenenneeen 38 yC Clk Time Calendar Management anneer onnnerenennnneerenenneeen 39 uHC CRC Checksums and Error Correction Codes cccceceeeeeeeeeeee 41 uC FS Platform Independent Source Code anneer eneen 42 UC FS FAT Filesystem Source Code nananananenensnrenenenenn 45 UC FS Memory Device Drivers EEN nenneennensenenensnnnnennnentensen 46 uC FS Platform Specific Source Code aanname nemen e nemen 50 Table of Contents 3 12 3 13 Chapter 4 4 1 4 2 4 3 4 4 4 5 Chapter 5 5 1 5 2 5 3 5 4 5 5 5 6 5 7 5 8 5 8 1 5 8 2 Chapter 6 6 1 6 1 1 6 1 2 6 1 3 6 1 4 6 1 5 6 2 6 2 1 6 2 2 6 2 3 Chapter 7 7 1 UC FS OS Abstraction Layer nnnnnnunannnnerserennnerrenensenenenennnneerenennneen 51 SUMMA See dE EE 52 Useful Information ecececeeseeecee eee nnen eee REENEN 59 Klee EE 59 UC FS Device and Volume Names c cceseeeeeeeeeeeeeceeeeeeeeeeeeeeeeeeeeees 61 uC FS File and Directory Names and Paths nanne eneen 62 HC FS Name Lengths GeetiesrtektkeEteCE EVERS EEZEEER NEE aauina 64 Resource USAGE goera E aE aE E EA EE 65 Devices and Volumes cesssecceecesseeeeeeesseeeceeensneeeceeensnenecesessneeeeeessnaees 67 Device Operations s ssssssssesssssnnnnnnunnernnennnnnnnnunnnnnnnnnnnnnnnnnnnnnn nnmnnn nnmnnn 68 Elle Ne ELE 69 Using Removable Devices nnn annanar enn e
149. and is a directory dir is DEF NO and excl is DEF NO then no change will be made to the file system Similarly if the entry exists and is a file dir is DEF YES and excl is DEF_NO then no change will be made to the file system The root directory may not be created 303 Appendix A A 5 4 FSEntry Del void FSEntry Del CPU CHAR name full FS FLAGS entry type FS ERR p err File Called from Code enabled by fs entry c Application not FS _CFG_RD ONLY EN fs rmdir fs_remove Delete a file or directory See also fs_remove and fs_rmdir ARGUMENTS name full Pointer to character string representing the name of the entry See section 4 3 uC FS File and Directory Names and Paths on page 62 entry type Indicates whether the entry MAY be a file see Notes 1 and 2 FS ENTRY TYPE DIR FS ENTRY TYPE FILE FS ENTRY TYPE ANY if the entry must be a dir if the entry must be a file if the entry may be any type p err Pointer to variable that will the receive return error code from this function FS ERR NONE FS ERR NAME NULL FS ERR NAME INVALID FS ERR NAME PATH TOO LONG FS ERR VOL NOT OPEN FS ERR VOL NOT MOUNTED FS ERR BUF NONE AVAIL FS ERR DEV 304 Entry date time set successfully Argument name full passed a NULL pointer Entry name specified invalid OR volume could not be found Entry name specified too long Volume was not open Volume was not mounted Buffer not available
150. and the return value a is DEE MO then the same device e g SD card is still inserted The application can continue to access open files directories and volumes B If the return error is neither FS ERR NONE nor FS ERR DEV INVALID LOW FMT then no functioning device is present The device must be refreshed at a later time A device can be refreshed explicitly with FSDev Refresh however refresh also happens automatically If a volume access Leg FSVol Fmt FSVol Rd entry access FSEntry Create fs remove file open s fopen or FSFile Open or 71 Chapter 5 directory open s opendir or FSDir Open is initiated on a device that was not present at the last attempted access uC FS attempts to refresh the device information if that succeeds it attempts to refresh the volume information Files and directories have additional behavior If a file is opened on a volume and the underlying device is subsequently removed or changed all further accesses using the file API e g FSFile_Rd will fail with the error code FS ERR DEV CHNGD all POSIX API functions will return error values The file should then be closed to free the file structure Similarly if a directory is opened on a volume and the underlying device is subsequently removed or changed all further FSDir_Rd attempts will fail with the error code FS ERR DEV CHNGD fs readdir r will return 1 The directory should then be closed to free the directo
151. any file buffer As data is read from or written to a file the file position is incremented by the number of bytes transferred from to the volume The file position may also be directly manipulated by the application using the position set function fs_fsetpos and the current absolute file position may be gotten with the position get function s fgetpos to be later used with the position set function 98 File Access Functions Closed Open amp Reading file at EOF Figure 8 1 File state transitions The file maintains flags that reflect errors encountered in the previous file access and subsequent accesses will fail under certain conditions outlined here unless these flags are explicitly cleared using fs_clearerr There are actually two sets of flags One reflects whether the file encountered the end of file EOF during the previous access and if this is set writes will not fail but reads will fail The other reflects device errors and no subsequent file access will succeed except file close unless this is first cleared The functions fs ferror and fs feof can be used to get the state of device error and EOF conditions respectively If file buffering is enabled FS CFG FILE BUF EN is DEF ENABLED then input output buffering capabilities can be used to increase the efficiency of file reads and writes A buffer can be assigned to a file using fs setbuf or fs setvbuf the contents of the b
152. ard bsp c FSDev SD Card Refresh N A Open initialize SD MMC card interface ARGUMENTS unit nbr Unit number of SD MMC card RETURNED VALUE DEF OR if interface was opened DEF FAIL otherwise NOTES WARNINGS This function will be called EVERY time the device is opened 429 Appendix C C 5 2 FSDev SD Card BSP Lock Unlock void FSDev SD Card BSP Lock FS OTY unit nbr void FSDev SD Card BSP Unlock FS OTY unit nbr File Called from Code enabled by fs dev sd card bsp c SD MMC cardmode driver Acquire release SD MMC card bus lock ARGUMENTS unit nbr Unit number of SD MMC card RETURNED VALUE None NOTES WARNINGS FSDev SD Card BSP Lock will be called before the driver begins to access the SD MMC card bus The application should NOT use the same bus to access another device until the N A matching call to FSDev SD Card BSP Unlock has been made The clock frequency bus width and timeouts set by the FSDev SD Card BSP Set H F functions are parameters of the card not the bus If multiple cards are located on the same bus those parameters must be saved in memory when set and restored when FSDev_SD Card BSP Lock is called 430 C 5 3 FSDev SD Card BSP CmdStart void FSDev SD Card BSP CmdStart FS OTY unit nbr FS DEV SD CARD CMD p cmd void p data FS DEV SD CARD ERR p err File Called from Code enabled by fs dev sd card bsp c SD MMC cardmode
153. area 1 sector tay fat_cfg RootDirEntryCnt 512 Entries in root dir 512 S fat cfg FAT Type 12 FAT type FAT12 fat cfg NbrFATs 2 Number of FATs 2 S FSVol Fmt ram 0 amp fat_cfg amp err if err FS ERR NONE APP TRACE DEBUG Format failded r n Listing 10 1 Example device format 126 Sources of Corruption in FAT Volumes 10 5 SOURCES OF CORRUPTION IN FAT VOLUMES Errors may accrue on a FAT volume either by device removal during file system modifications power loss or by improper host operation Several corruptions are common B Cross linked files If a cluster becomes linked to two files then it is called cross linked The only way to resolve this is by deleting both files if necessary they can be copied first so that the contents can be verified B Orphaned directory entries If LFNs are used a single file name may span several directory entries If a file deletion is interrupted some of these may be left behind or orphaned to be deleted later B Invalid cluster The cluster specified in a directory entry or linked in a chain may be invalid The only recourse is to zero the cluster if in a directory entry or replace with end of cluster Gf in a chain B Chain length mismatch Too many or too few clusters may be linked to a file compared to its size If too many the extra clusters should be freed If too few the file size should be adjusted B Lost
154. ary significantly as a result of CPU and hardware differences both as well as file system format All test were compiled using IAR EWARM 6 40 1 using high speed optimization Table 9 4 lists results for two general performance tests B Read file test Read a file in 4 kB and 64kB chunks The time to open the file is NOT included in the time P Write file test Write a file in 4 kB and 64kB chunks The time to open create the file is NOT included in the time 114 Drivers comparison Performance kB s Driver CPU Media 4k Read 64k Read 4k Write 64k Write RAM Disk ST STM32F207IGH6 IS61WV102416BLL 10MLI 16 622 kB s 31 186 kB s 120Mhz 16Mbit 10 ns SRAM 10 839 kB s 26 473 kB s RAM Disk Atmel AT91SAM9M10 MT47H64M8CF 3 F DDR2 27 478 kB s 96 866 kB s 400 Mhz 2x8bit 2 banks interleaved 18 858 kB s 84121 kB s SD MMC CardMode ST STM32F207IGH6 Nokia 64 MB SMSO64FF SD 5 333 kB s 8 595 kB s 120 MHz 4 bit mode Card 661 kB s 1 607 kB s SD MMC SPI ST STM32F107VC Nokia 64 MB SMSO64FF SD 947 kB s 1 010kB s 72 Mhz Card 444 kB s 793 kB s SD MMC SPI ST STM32F107VC Nokia 64 MB SMSO64FF SD 759 kB s 800 kB s 72 MHz w CRC Card 388 kB s 655 kB s NAND Atmel AT91SAM9M10 Micron MT29F2GO8ABDHC 9 039 kB s 10 732 kB s 400 Mhz 2Gb NAND flash 1 950 kB s 4 332 kB s NAND auto sync Atmel AT91SAM9M10 Micron MT29F2GO8ABDHC 9039 kB s 10 732 kB s 400 Mhz 2Gb NAND flash 1 336 kB s 2 695 kB s NOR parallel ST STM32
155. associated with a file File accesses constitute reading data from files writing data to files creating new files renaming files copying files etc File access is accomplished via file module level functions which are covered in Chapter 6 Files on page 83 Directories can be accessed on a volume A directory is a container for files and other directories Operations include iterating through the contents of the directory creating new directories renaming directories etc Directory access is accomplished via directory module level functions which are covered in Chapter 7 Directories on page 93 A volume can be formatted More specifically high level formatted Formatting writes the control information for a file system to the partition on which a volume is located A volume can be closed unmounted During the closing of a volume any cached data is written to the underlying device and associated structures are freed For information about using volume names see section 4 2 uC FS Device and Volume Names on page 61 For FAT specific volume functions see Chapter 4 File Systems FAT on page 153 76 Using Volumes Function Description Valid for Unmounted Volume FSVol_CacheAssign Assign cache to volume Yes FSVol_Cachelnvalidate Invalidate cache for volume No FSVol_CacheFlush Flush cache for volume No FSVol_Close Close unmount volume Yes FSVol_Fmt
156. ate BSP for traditional parallel NOR devices See section C 10 NOR Flash BSP on page 473 for more information BSP Template SPI fs_dev_nor_bsp c This is a template BSP for serial SPI NOR devices See section C 11 NOR Flash SPI BSP on page 480 for more information BSP Template SPI GPIO fs_dev_nor_bsp c This is a template BSP for serial SPI NOR devices using GPIO bit banging See section C 11 NOR Flash SPI BSP on page 480 for more information Files and Directories PHY This directory contains physical level drivers for specific NOR types fs dev nor amd 1x08 CFI compatible parallel NOR implementing AMD command set 1 chip 8 bit data bus fs dev nor amd 1x16 CFI compatible parallel NOR implementing AMD command set 1 chip 16 bit data bus fs dev nor intel CFI compatible parallel NOR implementing Intel command set 1 chip 16 bit data bus fs_dev_nor_sst39 SST SST39 Multi Purpose Flash fs dev nor stm25 ST STM25 serial flash fs dev nor sst25 SST SST25 serial flash Micrium Software uC FS Examples BSP Dev NOR Each subdirectory contains an example BSP for a particular platform These are named according to the following rubric lt Chip Manufacturer gt lt Board or CPU gt fs_dev_nor_bsp c 201 Chapter 14 14 2 DRIVER AND DEVICE CHARACTERISTICS NOR devices no matter what attachment interface serial or parallel share certain characteristics The medium is always organize
157. ation to store a file location continue reading or writing the file and then go back to that place at a later time An example of using file position get and set is given in Listing 8 2 void App Fnct void FS_FILE p file fs fpos t pos int err p file fs fopen file txt r Open file St if p file FS_FILE 0 APP TRACE INFO Could not open file return read from file ay err fs fgetpos p file amp pos Save file position if err 0 APP TRACE INFO Could not get file position return read some more from file SZ err fs fsetpos p file amp pos Set file to saved position if err 0 APP TRACE INFO Could not set file position return read some more from file af FS_fclose p file When finished close file Listing 8 2 Example file position set get 103 Chapter 8 8 3 3 CONFIGURING A FILE BUFFER In order to increase the efficiency of file reads and writes input output buffering capabilities are provided Without an assigned buffer reads and writes will be immediately performed within fs fread and fs fwrite Once a buffer has been assigned data will always be read from or written to the buffer device access will only occur once the file position moves beyond the window represented by the buffer fs setbuf and fs setvbuf assign the buffer to a file The contents of the bu
158. ation will typically be chosen from the implementations included with the NAND driver This implementation can either rely on statically defined parameters or values read directly from the device for an ONFI compliant part The ECC layer provides code calculation and error correction functions For performance reasons only a 1 bit ECC software module based on Hamming codes is provided part of the pC CRC product bundled with pC FS If a more robust ECC correction scheme is required it is strongly recommended to use hardware engines Since the ECC specific code of the generic controller driver is implemented in generic controller extension modules it can easily be adapted if the micro controller or NAND flash device can handle ECC automatically 13 3 NAND TRANSLATION LAYER The NAND translation layer is the main layer of the driver implemented by the files fs dev nand c and fs dev nand h This layer contains most of the algorithms necessary to overcome the following limitations of NAND flash technology B Write operations can only change a bit state from 1 to 0 Only erase operations can revert the bit state from 0 to T B Erase operations are only performed on large sections of the memory called blocks typically between 16 kB and 512 kB 168 NAND Translation Layer E Write operations are performed on a sub section of a block called a page typically between 512 and 8192 octets B Some devices support partial
159. ative to start of device ent Number of octets to write p err Pointer to variable that will the receive return error code from this function FS ERR NONE Octets written successfully FS ERR NAME NULL FS ERR NULL PTR FS ERR DEV INVALID FS ERR DEV NOT OPEN FS ERR DEV NOT PRESENT Argument name dev passed a NULL pointer Argument D src passed a NULL pointer Argument name_dev specifies an invalid device Device is not open Device is not present FS ERR DEV INVALID LOW FMT Device needs to be low level formatted FS ERR DEV IO FS ERR DEV TIMEOUT Device I O error Device timeout 381 Appendix A RETURNED VALUE None NOTES WARNINGS The device must be a NOR device e g nor 0 Care should be taken if this function is used while a file system exists on the device or if the device is low level formatted The octet location s modified are NOT validated as being outside any existing file system or low level format information During a program operation only 1 bits can be changed a 0 bit cannot be changed to a 1 The application must know that the octets being programmed have not already been programmed 382 A 11 8 FSDev_NOR_PhyEraseBlk void FSDev NOR PhyEraseBlk CPU CHAR name dev CPU INI32U start CPU INT32U size FS ERR p err File Called from Code enabled by fs dev nor c Application N A Erase block of NOR device ARGUMENTS name dev Device name see Note start Start
160. atted Device I O error Device timeout error Device is not present A 9 SD MMC DRIVER FUNCTIONS void FSDev_SD Card QuerySD CPU_CHAR name_ dev FS DEV SD INFO p info FS_ERR p err void FSDev SD SPI_QuerySD CPU CHAR name dev FS DEV SD INFO p info FS ERR p err void FSDev SD Card RdCID CPU CHAR name dev CPU _INTO8U p info FS ERR p err void FSDev SD SPI RJCID CPU _CHAR name dev CPU _INTO8U p info FS ERR p err void FSDev SD Card RdCSD CPU CHAR name dev CPU _INTO8U p info FS ERR p err void FSDev SD SPI RdCSD CPU CHAR name dev CPU _INTO8U p info FS ERR p err 361 Appendix A A 9 1 FSDev SD xxx QuerySD void FSDev SD Card QuerySD CPU CHAR name dev FS DEV SD INFO p info FS ERR p err void FSDev SD SPI _QuerySD CPU CHAR xname dev FS DEV SD INFO p info FS ERR p err File Called from Code enabled by fs dev sd card c Application N A fs dev sd spi c Get low level information abou SD MMC card ARGUMENTS name dev Device name see Note p info Pointer to structure that will receive SD MMC card information p err Pointer to variable that will the receive return error code from this function FS ERR NONE SD MMC info obtained FS ERR NAME NULL Argument name dev passed a NULL pointer FS ERR NULL PTR Argument p info passed a NULL pointer FS ERR DEV INVALID Argument name dev specifies an invalid device FS ERR DEV NOT OPEN Device is not open F
161. being used m A device can be high level formatted High level formatting writes the control information for a file system to a device so that a volume on it can be mounted Essentially high level formatting is the process of creating a volume on an empty device or partition B A device can be closed During the closing of a device it is uninitialized if necessary and associated structures are freed These operations and the corresponding API functions are discussed in this section For information about using device names see section 4 2 uC FS Device and Volume Names on page 61 Function Description FSDev_AccessLock Acquire exclusive access to a device FSDev_AccessUnlock Release exclusive access to a device FSDev_Close Remove device from file system FSDev_GetNbrPartitions Get number of partitions on a device FSDev_Invalidate Invalidate files and volumes open on a device FSDev_IO Ctrl Perform device I O control operation 68 Using Devices Function Description FSDev_Open Add device to file system FSDev_PartitionAdd Add partition to device FSDev PartitionFind Find partition on device and get information about partition FSDev PartitionInit Initialize partition on device FSDev Ouere Get device information FSDev_Rd Read sector on device FSDev Refresh Refresh device in file system FSDev_Wr Write sector on device Table 5 1 Devic
162. ber of octets to read p err Pointer to variable that will receive the return error code from this function FS_ERR_NONE Octets read successfully FS ERR DEV IO Device I O error FS_ERR_DEV_TIMEOUT Device timeout error RETURNED VALUE None NOTES WARNINGS None 469 Appendix C C 9 4 Wr void Wr FS DEV NOR PHY DATA p phy data void p src CPU_INT32U start CPU_INT32U cnt FS_ERR p err File Called from Code enabled by NOR physical layer driver FSDev_NOR_PhyWrHandler N A Write to a NOR device from a buffer ARGUMENTS p phy data Pointer to NOR phy data p src Pointer to source buffer start Start address of write relative to start of device ent Number of octets to write p err Pointer to variable that will receive the return error code from this function FS ERR NONE Octets written successfully FS ERR DEV IO Device 1 O error FS ERR DEV TIMEOUT Device timeout error RETURNED VALUE None NOTES WARNINGS None 470 C 9 5 EraseBlk void EraseBlk FS DEV NOR PHY DATA p phy data CPU_INT32U start CPU_INT32U size FS_ERR p err File Called from Code enabled by NOR physical layer driver FSDev NOR PhyEraseBlkHandler N A Erase block of NOR device ARGUMENTS p_phy data Pointer to NOR phy data start Start address of block relative to start of device size Size of block in octets p err Pointer to variable that will receive the return error code from t
163. c CPU SIZE T size FS ERR p err File Called from Code enabled by fs file c Application not FS CFG RD ONLY EN fs fwrite Write to a file See fs fwrite for more information ARGUMENTS p file Pointer to a file p src Pointer to source buffer size Number of octets to write p err Pointer to variable that will the receive return error code from the function FS ERR NONE File write successfully FS ERR NULL PTR Argument p file p src passed a NULL pointer FS ERR INVALID TYPE Argument p file s type is invalid or unknown FS ERR FILE NOT OPEN File NOT open FS ERR FILE INVALID OP Invalid operation on file FS ERR DEV Device access error 383 Appendix A RETURNED VALUE The number of bytes written if file write successful 0 otherwise NOTES WARNINGS None 334 A 7 VOLUME FUNCTIONS void FSVol_Close CPU_CHAR name_vol FS_ERR p err void FSVol_Fmt CPU_CHAR name_vol void p fs cfg FS_ERR p err void FSVol GetDfltVolName CPU CHAR name vol FS OTY FSVol GetVolCnt void FS_OTY FSVol_GetVolCntMax void void FSVol_GetVolName FS OTY vol nbr CPU CHAR name vol CPU_BOOLEAN FSVol_IsMounted CPU_CHAR name vol void FSVol_LabelGet CPU_CHAR name_vol CPU_CHAR label CPU_SIZE T len max FS ERR p err void FSVol LabelSet CPU CHAR name vol CPU_CHAR label FS_ERR p err void FSVol_Open CPU_CHAR name_vol CPU_CHA
164. c fs_unicode h fs_util c fs_util h fs_vol c fs_vol h Micrium This is where we place all software components and projects provided by Micripm 43 Chapter 3 Software This sub directory contains all the software components and projects uC FS This is the main nC FS directory APP Template This directory contains a template of the code for initializing the file system Cfg Template This directory contains a configuration template file lib_cfg h that is required to be copied to the application directory to configure the wC FS module based on application requirements fs_cfg h specifies which features of uC FS you want in your application If uC FS is provided in linkable object code format then this file will be provided to show you what features are available in the object file See Appendix B uC FS Configuration Manual Source This directory contains the platform independent source code for uC FS All the files in this directory should be included in your build assuming you have the source code Features that you don t want will be compiled out based on the value of define constants in fs cfg h 44 fs c h contains core functionality for nC FS including FS Init called to initialize uC FS and FS WorkingDirSet FS WorkingDirGet used to get and set the working directory fs _api c h contains the code for the POSIX compatible API See Chapter x API for details about the POSIX compatible
165. c fs_dev_nand_part_static Manually configure the in parameters of each NAND flash Micrium Software uC FS Dev NA device you use ND Part FS _NAND PartONFI fs_dev_nand_part_onfi Use the parameters automatically in obtained by reading the Micrium Software uC FS Dev NA parameter page of ND Part ONFl compliant NAND flash devices Table 13 3 Part layer implementations provided It is mandatory to use one part layer implementation for the NAND driver to work It is recommended to use one of the provided implementations STATICALLY CONFIGURED PART LAYER This part layer implementation is the basic one It lets you set all the physical characteristics of the device through a configuration structure of type FS_NAND PART STATIC CFG Typically the pointer to the configuration structure is then assigned to the field PartCfgPtr of the translation layer configuration structure see section 13 3 NAND Translation Layer on page 168 The pointer to the translation layer configuration structure can then be passed as an argument to the function FSDev_Open Refer to section 13 1 Getting Started on page 160 for an example of configuration The part configuration 181 Chapter 13 structure should be initialized to FS_NAND PartStatic_DfltCfg to ensure upward compatibility with future versions The configuration fields available for the static part layer are described in Listing 13 5 typedef struct fs nand part static cfg FS
166. cal to give the volume the same name as the underlying device If the default partition is to be opened or if the device is not partition then the partition number c should be 0 FSVol Fmt formats a file system device If the NAND has just been low level formatted there will be no file system on the corresponding volume after it is opened O will be unformatted The volume must be formatted before files can be created or accessed If the NAND initialization succeeds the file system traces if a sufficiently high trace level is configured will produce an output similar to Listing 13 1 See section E 9 Trace Configuration on page 507 about configuring the trace level 165 Chapter 13 Adding opening NAND volume nand 0 NAND Ctrlr Gen found NAND manuf id 2c dev id aa FS HAND Open Using default blk cnt all blocks 2048 PS HAND Open Default number of entries in avail blk tbl NAND FLASH FOUND Name nand 0 Sec Size 2048 bytes Size 127360 sectors Update blks 10 FS_NAND LowMountHandler Low level mount succeeded opened device FSPartition RdEntry Found possible partition Start 0 sector Size 0 sectors Type 00 FS_FAT_VolOpen File system found Type FAT16 Sec size 2048 B Clus size 4 sec Vol size 127360 sec Clus 31822 FATs SE Opened volume mounted init succeeded Listing 13 2 NAND detection trace output HANDLING DIFFERENT USE CASES If the above exam
167. cate FS FILE p file FS FILE SIZE size FS ERR p err CPU SIZE T FSFile Wr FS FILE p file void p src CPU SIZE T size FS ERR p err 312 A 6 1 FSFile_BufAssign void FSFile BufAssign FS FILE p file void p buf FS_FLAGS mode CPU SIZE T size FS ERR p err File Called from Code enabled by fs file c Application FS CFG FILE BUF EN fs setbuf fs setvbuf Assign buffer to a file See fs setvbuf for more information ARGUMENTS p file Pointer to a file p_buf Pointer to buffer mode Buffer mode FS FILE BUF MODE RD Data buffered for reads FS FILE BUF MODE WR Data buffered for writes FS FILE BUF MODE RD WR Data buffered for reads and writes FS FILE BUF MODE SEC ALIGNED Force buffers to be aligned on sector boundaries size Size of buffer in octets 318 Appendix A p_err Pointer to variable that will receive the return error code from this function FS_ERR_NONE File buffer assigned FS ERR NULL PTR Argument p file or p buf passed a NULL pointer FS ERR INVALID TYPE Argument p file s type is invalid or unknown FS ERR FILE INVALID BUF MODE Invalid buffer mode FS ERR FILE INVALID BUF SIZE Invalid buffer size FS ERR FILE BUF ALREADY ASSIGNED Buffer already assigned FS ERR FILE NOT OPEN File NOT open RETURNED VALUE None NOTES WARNINGS None 314 A 6 2 FSFile BufFlush void FSFile BufFlush FS FILE p file FS ERR p err File Called from Code enabled
168. ce file In the second form of this command the first argument must not be an existing directory and the second argument must be an existing directory The contents of source file will be copied to a file with name formed by concatenating dest dir a path separator character and the final component of source file 518 F 3 4 fs_date Write the date and time to terminal output or set the system date and time USAGES fs date fs date time ARGUMENTS time If specified time to set in the form mmddhhmmccyy lst mm the month 1 12 dd the day 1 29 30 or 31 hh the hour 0 23 2nd mm the minute 0 59 ccyy the year 1900 or larger OUTPUT If no argument date and time REQUIRED CONFIGURATION Available only if FS SHELL CFG DATE EN is DEF ENABLED NOTES WARNINGS None COM4 PuTTY fs date Thu Jun 11 18 18 10 Figure F 4 fs_date output 519 Appendix F F 3 5 fs_df Report disk free space USAGES fs df fs df vol ARGUMENTS vol If specified volume on which to report free space Otherwise information about all volumes will be output OUTPUT Name total space free space and used space of volumes REQUIRED CONFIGURATION Available only if FS SHELL CFG DF EN is DEF ENABLED NOTES WARNINGS None COM4 PuTTY Figure F 5 fs_df output 520 F 3 6 fs Is List directory contents USAGES fs ls ARGUMENTS None OUTPUT List of directory contents REQU
169. ce name must be between 0 and 255 64 Resource Usage ee E sdcard 0 Pie ee driver name Figure 4 2 Device and device driver name lengths Each of the maximum name length configurations specifies the maximum string length without the NULL character Consequently a buffer which holds one of these names must be one character longer than the define value 4 5 RESOURCE USAGE HC FS resource usage of both ROM and RAM depends heavily on application usage How many and which interface functions are referenced determines the code and constant data space requirements The greater the quantity of file system objects buffers files directories devices and volumes the more RAM needed Table 2 1 give the ROM usage for the file system core plus additional components that can be included optionally collected on IAR EWARM v6 40 1 The core ROM size includes all file system components and functions except those itemized in the table this is significantly larger than most installations because most applications use a fraction of the API Component ROM Thumb Mode ROM ARM Mode High Size Opt High Speed Opt High Size Opt High Speed Opt Core 43 1 kB 59 2 kB 66 5 kB 91 2 kB OS port uC OS III 1 1kB 1 4kB 1 8kB 2 2 kB LFN support 4 3 kB 5 2 kB 6 9 kB 8 2 kB Directories 1 7 kB 2 1 kB 2 7 kB 3 3 kB Volume check 0 9 kB 1 0 kB 1 4 kB 1 6 kB Partitions 1 3 kB 1 8 kB 2 2 kB 2 9 kB Table 4 1 ROM requi
170. ch appended with a CRC F12 2 1 F12 2 2 F12 2 3 F12 2 4 F12 2 5 F12 2 6 142 Host to card Card to host 5 6 Card to host read Host to card write write only DAT OI EN ERLE EN AT Data g barrae Busy 2 3 4 Figure 12 2 SD MMC communication sequence When no data is being transmitted data lines are held low Data block is preceded by a start bit 0 an end bit 1 follows the CRC The CRC is the 16 bit CCITT CRC During the busy signaling following a write DATO only is held low See Figure 12 3 for description of the command format See Figure 12 3 for description of the command format Using the SD MMC CardMode Driver Start bit a Transmission bit End bit Command Di Cmd ix Argument CRC 1 format 6 bits 32 bits 7 bits Start bit Transmission bit End bit Response P Response format 32 or 128 bits 1 2 Figure 12 3 SD MMC command and response formats F12 3 1 Command index is not valid for response formats R2 and R3 F12 3 2 CRC is not valid for response format R3 When a card is first connected to the host at card power on it is in the inactive state awaiting a GO IDLE STATE command to start the initialization process which is dependent on the card type During initialization the card starting in the idle state moves through the ready as long as it supports the voltage range specified by the host and
171. cified invalid Entry name specified invalid OR volume could not be found Entry name specified too long Volume was not open Volume was not mounted Buffer not available Device access error 309 Appendix A RETURNED VALUE None NOTES WARNINGS None 310 A 6 FILE FUNCTIONS void FSFile BufAssign FS FILE p file void p buf FS FLAGS mode CPU SIZE T size FS ERR p err void FSFile BufFlush FS FILE p file FS ERR p err void FSFile Close FS FILE p file FS ERR p err void FSFile ClrErr FS FILE p file FS ERR p err CPU_BOOLEAN FSFile_IsEOF FS_FILE p file FS_ERR p err CPU_BOOLEAN FSFile IsErr FS FILE p file FS ERR p err CPU_BOOLEAN FSFile IsOpen CPU _CHAR name full FS FLAGS p mode FS ERR p err void FSFile LockAccept FS FILE p file FS ERR p err void FSFile LockGet FS FILE p file FS ERR p err 311 Appendix A void FSFile LockSet FS FILE p file FS_ERR p err FS FILE FSFile Open CPU_CHAR name full FS FLAGS mode FS ERR p err FS FILE SIZE FSFile PosGet FS FILE p file FS ERR p err void FSFile PosSet FS FILE p file FS FILE OFFSET offset FS FLAGS origin FS ERR p err void FSFile Query FS FILE p file FS ENIRY INFO p info FS ERR p err CPU SIZE T FSFile Rd FS_FILE p file void p dest CPU_SIZE T size FS_ERR p err void FSFile Trun
172. communication can easily be accomplished by software control of GPIO pins software SPI or bit banging a SD MMC card can be connected to almost any platform In SPI mode seven pins on the SD MMC device are used with the functions listed in Table 12 4 As with any SPI device four signals are used to communicate with the host CS Dataln CLK and DataOut Some card holders contain circuitry for card detect and write protect indicators which the MCU MPU may also monitor Pin Name Type Description 1 cs l Chip Select 2 Dataln l Host to card commands and data 3 Vss1 S Supply voltage ground 4 VDD S Supply voltage 5 CLK l Clock 6 VSS2 S Supply voltage ground 7 DataOut O Card to host data and status Table 12 4 SD MMC pinout SPI mode The four signals connecting the host or master and card also known as the slave are named variously in different manuals and documents The Dataln pin of the card is also known as MOSI Master Out Slave In it is the data output of the host CPU Similarly the DataOut pin of the card is also known as MISO Master In Slave Out it is the data input of the host CPU The CS and CLK pins also known as SSEL and SCK are the chip select and clock pins The host selects the slave by asserting CS potentially allowing it to choose a single peripheral among several that are sharing the bus Oe by sharing the CLK MOSI and MISO signals When a card is first connected to t
173. corruption since this handle may be re used for a different directory 237 Appendix A A 2 5 fs_ctime_r char fs ctime r const fs time t p ts char str_time File Called from Code enabled by fs_api c Application FS_CFG_API_EN Converts timestamp to string in the form Sun Sep 16 01 03 52 1973 n 0 ARGUMENTS p ts Pointer to timestamp to format str time String buffer that will receive date time string see Note RETURNED VALUE Pointer to str_time if NO errors Pointer to NULL otherwise NOTES WARNINGS str time MUST be at least 26 characters long Buffer overruns MUST be prevented by caller 238 A 2 6 fs_fclose int fs fclose FS FILE p file File Called from Code enabled by fs_api c Application Close and free a file ARGUMENTS p file Pointer to a file RETURNED VALUE 0 if the file was successfully closed FS_EOF otherwise NOTES WARNINGS FS_CFG_API_EN E After a file is closed the application MUST desist from accessing its file pointer This could cause file system corruption since this handle may be re used for a different file m Ifthe most recent operation is output write all unwritten data is written to the file B Any buffer assigned with fs setbuf or fs setvbuf shall no longer be accessed by the file system and may be re used by the application 239 Appendix A A 2 7 fs_feof int fs feof FS FILE p file File Cal
174. d Origin is specified invalid or unknown Offset is specified invalid Invalid file arguments File operation invalid File operation sequence invalid File position invalid File locked FS ERR FILE NONE AVAIL FS ERR FILE NOT OPEN FS ERR FILE NOT LOCKED FS ERR FILE OVF FS ERR FILE OVF OFFSET B 10 NAME ERROR CODES FS ERR NAME BASE TOO LONG FS ERR NAME EMPTY FS ERR NAME EXT TOO LONG FS ERR NAME INVALID FS ERR NAME MIXED CASE FS ERR NAME NULL FS ERR NAME PATH TOO LONG FS ERR NAME BUF TOO SHORT FS ERR NAME TOO LONG No file available File NOT open File NOT locked File size overflowed max file size File offset overflowed max file offset Base name too long Name empty Extension too long Invalid file name or path Name is mixed case Name ptr arg s passed NULL ptr s Entry path is too long Buffer for name is too short Full name is too long B 11 PARTITION ERROR CODES FS ERR PARTITION INVALID FS ERR PARTITION INVALID NBR FS ERR PARTITION INVALID SIG FS ERR PARTITION INVALID SIZE FS ERR PARTITION MAX FS ERR PARTITION NOT FINAL FS ERR PARTITION NOT FOUND FS ERR PARTITION ZERO B 12 POOLS ERROR CODES FS ERR POOL EMPTY FS ERR POOL FULL FS ERR POOL INVALID BLK ADDR FS ERR POOL INVALID BLK IN POOL Partition invalid Partition nbr specified invalid Partition sig invalid Partition size invalid Max nbr partitions have been created in MBR Prev partition is not final partit
175. d after its primary data structure a large table that records what clusters of the disk are allocated A cluster or group of sectors is the minimum data allocation unit of the FAT file system 60 LIC FS Device and Volume Names 4 2 HC FS DEVICE AND VOLUME NAMES Devices are specified by name For example a device can be opened FSDev Open sd 0 void 0 amp err In this case sd 0 is the device name It is a concatenation of 3 sd The name of the device driver A single colon 0 The unit number A final colon The unit number allows multiple devices of the same type for example there could be several SD MMC devices connected to the CPU sd 0 sd 1 sd 2 The maximum length of a device name is FS_CFG MAX DEV NAME LEN this must be at least three characters larger than the maximum length of a device driver name FS CFG MAX DEV DRV NAME LEN A device name or device driver name must not contain the characters Volumes are also specified by name For example a volume can be formatted FSVol Fmt vol void 0 amp err Here vol is the volume name uC FS imposes no restrictions on these names except that they must end with a colon must be no more than FS_CFG MAX VOL NAME LEN characters long and must not contain either of the characters V or 61 Chapter 4 It is typical to name a volume the same as a device for example a volume may be opened
176. d by the part layer as its sector size L13 3 7 L13 3 8 L13 3 9 L13 3 10 L13 3 11 NAND Translation Layer This field must contain the number of blocks you want HC FS to use This can be useful if you want to reserve blocks for data to be used outside the file system by a bootloader for example The value FS NAND CFG DEFAULT instructs the translation layer to use the number of blocks reported by the part layer This field must contain the index of the first block you want uC FS to use This can be useful if you want to reserve blocks for data to be used outside the file system by a bootloader for example This field must be set to the maximum number of update blocks you want the NAND translation layer to use A greater number can improve performance but will also reduce available space on the device and consume RAM You are encouraged to experiment with different values to evaluate which one suits your application best This field must be set to the maximum associativity of the random update blocks RUB The update blocks temporarily contain sectors from data blocks until they are merged copied to respective data blocks The associativity specifies the number of data blocks from which a single RUB can contain sectors A high setting will usually lead to better overall write and read speeds and will reduce wear However a low setting will lower the time of execution of the worst case write operation This field must
177. d from Code enabled by fs deu Application not FS CG RD ONLY EN Write data to device sector s See also section 5 4 Raw Device IO on page 72 ARGUMENTS name dev Device name p src Pointer to source buffer start Start sector of write ent Number of sectors to write p err Pointer to variable that will receive the return error code from this function FS ERR NONE Sector s written FS ERR NAME NULL Argument name dev passed a NULL pointer FS ERR NULL PTR Argument D src passed a NULL pointer Or device access error see section B 4 Device Error Codes on page 394 RETURNED VALUE None NOTES WARNINGS Device state change will result from device I O not present or timeout error 291 Appendix A A 4 DIRECTORY ACCESS FUNCTIONS void FSDir Close FS DIR p dir FS ERR p err CPU BOOLEAN FSDir IsOpen CPU CHAR name full FS ERR p err FS DIR FSDir Open CPU _CHAR name full FS ERR p err void FSDir Rd FS_DIR p dir FS DIR ENTRY p dir entry FS_ERR p err 292 A 4 1 FSDir_Close void FSDir Close FS DIR p dir FS ERR p err File Called from Code enabled by Application fs closedir fs dir c Close and free a directory See Ca closedir for more information FS _CFG DIR EN ARGUMENTS p dir Pointer to a directory p err Pointer to variable that will the receive return error code from this function FS ERR NONE Directory clos
178. d from a file ARGUMENTS p dest Pointer to destination buffer size Size of each item to read nitems Number of items to read p file Pointer to a file RETURNED VALUE Number of items read NOTES WARNINGS B The size or nitems is 0 then the file is unchanged and zero is returned B If the file is buffered and the last operation is output write then a call to fs_flush or fs fsetpos or fs fseek MUST occur before input read can be performed B The file must have been opened in read or update read write mode 246 A 2 14 fs fseek int fs fseek FS FILE p file long int offset int origin File Called from Code enabled by fs_api c Application fs_frewind FS CFG API EN Set file position indicator ARGUMENTS p file Pointer to a file offset Offset from the file position specified by whence origin Reference position for offset FS SEEK SET Offset is from the beginning of the file FS SEEK CUR Offset is from the current file position FS SEEK END Offset is from the end of the file RETURNED VALUE 0 if the function succeeds 1 otherwise 247 Appendix A NOTES WARNINGS E Ifa read or write error occurs the error indicator shall be set B The new file position measured in bytes form the beginning of the file is obtained by adding offset to 0 the beginning of the file if whence is FS SEEK SET the current file position if whence is FS_SEEK_CUR the fil
179. d into units called blocks which are erased at the same time when erased all bits are 1 Only an erase operation can change a bit from a 0 to a 1 but any bit can be individually programmed from a 1 to a 0 The uC FS driver requires that any 2 byte word can be individually accessed read or programmed The driver RAM requirement depends on flash parameters such as block size and run time configurations such as sector size For a particular instance a general formula can give an approximate if secs per blk lt 255 templ ceil blk ent used 8 blk_cnt_used 1 else templ ceil blk ent used 8 blk_cnt_used 2 if sec ent lt 65535 temp2 sec cnt 2 else temp2 sec cnt 4 temp3 sec size TOTAL templ temp2 temp3 where secs per blk The number of sectors per block blk ent used The number of blocks on the flash which will be used for the file system sec cnt The total number of sectors on the device sec size The sector size configured for the device in octets 202 Driver and Device Characteristics secs per blk and sec_cnt can be calculated from more basic parameters secs per blk floor blk_size sec size sec _cnt secs per blk blk ent used where blk size The size of a block on the device in octets Take as an example a 16 Mb NOR that is entirely dedicated to file system usage with a 64 KB block size configured with a 512 B sector The following parameters desc
180. d on a 64 KB block basis and support a command to read a JEDEC compatible ID Manufacturer Device Capacity Block Size Block Count SST SST25VF010B 1 Mb 4 KB 32 SST SST25VF020B 2 Mb 4 KB 64 SST SST25VF040B 4 Mb 4 KB 128 SST SST25VF080B 8 Mb 32 KB 32 SST SST25VF016B 16 Mb 32 KB 64 SST SST25VF032B 32 Mb 32 KB 128 Table 14 8 Supported SST25 serial flash 217 Chapter 14 218 Chapter 19 MSC Driver The MSC driver supports USB mass storage class devices Oe USB drives thumb drives using the uC USB host stack 15 1 FILES AND DIRECTORIES The files inside the MSC driver directory are outlined in this section the generic file system files outlined in Chapter 3 uC FS Directories and Files on page 29 are also required Micrium Software uC FS Dev This directory contains device specific files Micrium Software uC FS Dev MSC This directory contains the MSC driver files fs_dev_msc constitute the MSC device driver Micrium Software uC USB This directory contains the code for uC USB For more information please see the uC USB user manual 219 Chapter 15 15 2 USING THE MSC DRIVER To use the MSC driver two files in addition to the generic file system files must be included in the build E fs dev msc c E fs dev msc h The file fs dev mse h must also be included in any application or header files that directly reference the driver for example by registering the device
181. d path 0 CPU CHAR emd Garam Dour working dir void cwd_path 0 cmd_param pout_opt void 0 while DEF_TRUE App ShellIn cmd_line MAX CMD LEN Rd cmd see Note 2 Exec cmd see Note 3 Shell Exec cmd line App ShellOut amp cmd param amp err switch err case SHELL ERR CMD NOT FOUND case SHELL ERR CMD SEARCH case SHELL ERR ARG TBL FULL App ShellOut Command not found r n 19 cmd Garam Gout opt break default break LE KKK KKK KKK KKK KKK e KR RRR KKK kee ke k k KEK RRR RRR k k k KKK k k RK k k k k k k k k k k k k k k k k k k k k k kk k kk k k ek kk k kkk k App ShellIn kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk kkkkkk xf CPU_LINT16S App ShellIn CPU CHAR pbuf CPU INT16U buf len Store line from terminal command line into pbuf return length of line 512 J E K k H H H K KKK KK ee ke kkk KKK ER KEK kkk k k k k k KKK k k k k kk k k k k k k k k k k k k k k k k k k k kk kk k k kk kk k kkk k App _ShellOut KK KKK KKK KK KKK KKK EEE EEE EEEE E EEEE E E E E EEEE E E E EEEE E E E E E EEE E E E EEEE E E E E E EEE E E E EEE EEE EE E E a 20 CPU_LINT16S App Shellout CPU CHAR pbuf CPU_INT16U buf_len void popt Output pbuf data on terminal command line return nbr bytes Cord LF 2 1 LF 2 2 LF 2 3 Listing F 2 Executing shell commands amp handling shell output Th
182. de enabled by fs entry c Application not FS CG BD ONLY EN fs rename Rename a file or directory See also fs_rename ARGUMENTS name full old Old path of the entry See section 4 3 uC FS File and Directory Names and Paths on page 62 name full new New path of the entry excl Indicates whether the creation of the new entry shall be exclusive see Note 1 DEF YES if the entry shall be renamed only if name full new does not exist DEE MO if the entry shall be renamed even if name full new does exist p err Pointer to variable that will the receive return error code from this function FS ERR NONE FS ERR NAME NULL FS ERR NAME INVALID FS ERR NAME PATH TOO LONG FS ERR VOL NOT OPEN FS ERR VOL NOT MOUNTED File copied successfully Argument name full old or name full new passed a NULL pointer Entry name specified invalid OR volume could not be found Entry name specified too long Volume was not open Volume was not mounted 307 Appendix A FS ERR BUF NONE AVAIL Buffer not available FS ERR DEV Device access error RETURNED VALUE None NOTES WARNINGS 308 If name full old and name full new specify entries on different volumes then name full old MUST specify a file If name full old specifies a directory an error will be returned If name full old and name full new specify the same entry the volume will not be modified and no error will be returned If name full old specifies a file name fu
183. device information see Note p err Pointer to variable that will receive the return error code from this function FS ERR NONE Device information obtained FS ERR NAME NULL Argument name dev passed a NULL pointer FS ERR NULL PTR Argument p_info passed a NULL pointer FS ERR INVALID SEC NBR Sector start or count invalid Or device access error see section B 4 Device Error Codes on page 394 RETURNED VALUE None NOTES WARNINGS For removable medias FSDev_Query will return a valid value for the State and Fixed members of p_info even if the media is not present Size and SecSize will be set to 0 In such cases an error will be returned stating the reason why the device was unaccessible Otherwise if a fatal error occurs or the device is not opened an appropriate error will be return and the content of p_info will be invalid 287 Appendix A A 3 14 FSDev_Rd void FSDev_Rd CPU_CHAR name dev void p dest FS SEC NBR start D FS SEC OTY ent FS ERR p err File Called from Code enabled by fs_dev c Application N A Read data from device sector s See also section 5 4 Raw Device IO on page 72 ARGUMENTS name_dev Device name p dest Pointer to destination buffer start Start sector of read cnt Number of sectors to read p err Pointer to variable that will receive the return error code from this function FS_ERR_NONE Sector s read FS_ERR_NAME NULL Argument name dev passed a NULL pointer
184. driver N A Start a command ARGUMENTS unit nbr Unit number of SD MMC card p cmd Pointer to command to transmit see Note 2 p data Pointer to buffer address for DMA transfer see Note 3 p err Pointer to variable that will receive the return error code from this function FS DEV SD CARD ERR NONE No error FS DEV SD CARD ERR NO CARD No card present FS DEV SD CARD ERR BUSY Controller is busy FS DEV SD CARD ERR UNKNOWN Unknown or other error RETURNED VALUE None NOTES WARNINGS 1 The command start will be followed by zero one or two additional BSP function calls depending on whether data should be transferred and on whether any errors occur a FSDev SD Card BSP CmdStart starts execution of the command IT may also set up the DMA transfer if necessary 431 Appendix C b FSDev SD Card BSP CmdWaitEnd waits for the execution of the command to end getting the command response if any c If data should transferred from the card to the host FSDev_SD Card BSP CmdDataRd will read that data if data should be transferred from the host to the card FSDev_SD_Card_BSP_CmdDataWr will write that data 2 The command p cmd has the following parameters E p cmd gt Cmd is the command index E p cmd gt Arg is the 32 bit argument or 0 if there is no argument E p cmd gt Flags is a bit mapped variable with zero or more command flags FS DEV SD CARD CMD FLAG INIT Initialization sequence before command FS
185. e 6 2 fopen mode strings and mode equivalents 6 1 2 GETTING INFORMATION ABOUT A FILE Detailed information about an open file such as size and date time stamps can be obtained using the FSFile Query function FS _ENIRY INFO info FSFile Query p file lt file pointer amp info lt pointer to info structure amp err lt return error The FS ENTRY INFO structure has the following members E Attrib contains the file attributes see section 6 2 1 File and Directory Attributes on page 90 Size is the size of the file in octets 86 File Access Functions E DateTimeCreate is the creation timestamp of the file E DateAccess is the access timestamp date only of the file E DateTimeWr is the last write or modification timestamp of the file B BlkCnt is the number of blocks allocated to the file For a FAT file system this is the number of clusters occupied by the file data 8 size of a cluster BlkSize is the size of each block allocated in octets For a FAT file system this is the DateTimeCreate DateAccess and DateTimeWr are structures of type CLK TS SEC 6 1 3 CONFIGURING A FILE BUFFER The file module has functions to assign and flush a file buffer that are equivalents to POSIX API functions the primary difference is the advantage of valuable return error codes to the application File Module Function void FSFile BufAssign FS FILE p file void p buf FS_FLAGS mode CPU SIZE
186. e API functions 5 2 USING DEVICES A device is opened with FSDev_Open FSDev_Open CPU CHAR ide 0 lt a device name void le lt b pointer to configuration FS_ERR amp err lt c return error The parameters are the device name a and a pointer to a device driver specific configuration structure b If a device driver requires no configuration structure as the SD driver does not the configuration structure b should be passed a NULL pointer For other devices like RAM disks this must point to a valid structure 69 Chapter 5 Device Object Pool Device closed All references released Device not present Device could not be initialized Opening Device removed or unresponsive Device ins rted Device closed low level formatted Figure 5 2 Device state transition Prior to FSDev_Open being called a software is ignorant of the presence state or characteristics of the particular device After all references to the device are released b this ignorance again prevails and any buffers or structures are freed for later use The return error code from this functions provides important information about the device state 70 If the return error code is FS ERR NONE then the device is present responsive and low level formatted basically it is ready to use If the return error code is FS ERR DEV INVALID LOW FMT then the device
187. e SHELL CMD PARAM structure that will be passed to Shell_Exec must be initialized The peur working dir member must be assigned a pointer to a string of at least FS SHELL CFG MAX PATH LEN characters This string must have been initialized to the default working directory path if the root directory Ne The next command ending with a newline should be read from the command line The received command should be executed with Shell Exec If the command is a valid command the appropriate command function will be called For example the command fs ls will result in FSShell_1s in fs_shell c being called FSShell_1s will then print the entries in the working directory to the command line with the output function App ShellOut passed as the second argument of Shell_Exec 513 Appendix F F 3 COMMANDS The supported commands listed in the table below are equivalent to the standard UNIX commands of the same names though the functionality is typically simpler with few or no special options Command Description fs_cat Print file contents to the terminal output fs_cd Change the working directory fs_cp Copy a file fs_date Write the date and time to terminal output or set the system date and time fs df Report disk free space fs ls List directory contents fs_mkdir Make a directory fs_mkfs Format a volume fs_mount Mount volume fs_mv Move files fs od Dump f
188. e block SUB to merge it to allocate another update block If the threshold is exceeded a random update block RUB will be merged instead This threshold must be set so that SUBs with a lot of free space are not merged Merging SUBs early will generate additional wear This threshold is set as a percentage relative to number of sectors per block FS NAND CFG TH SUB MIN IDLE TO FOLD This define indicates the minimum idle time specified as the number of driver accesses since the last access that has written to the SUB for a sequential update block SUB to be converted to a random update block RUB This threshold must be set so that hot SUBs are not converted to RUBs DEVICE CONFIGURATION You must configure the NAND translation layer for each device you use in your project This configuration is made through a structure of type FS_NAND_CFG A pointer to this structure is then passed to the function FSDev_Open Each NAND device will need to be initialized by calling FSDev_Open and passing it a unique structure pointer of the type FS_NAND CFG Note that the FS NAND DfltCfg constant should be used to initialize the FS_NAND_CFG structure to default values This will ensure all fields will automatically be set to sane default values 175 Chapter 13 typedef struct fs nand cfg void BSPPtr 1 FS_NAND CTRLR API CtrlrPtr 2 void CtrlrCfgPtr 3 FS_NAND PART API PartPtr 4 void PartCfgPtr 5 FS_SEC_SIZE SecSi
189. e committing them to the main file system Each file system operation is then in fact done twice Journaling protects the file system at the expense of time Data can be lost in case of unexpected Reset in either the File System Layer or in the Device Driver Layer Your entire system is fail safe only if both layers are fail safe The journaling add on makes the file system layer fail safe Your entire system is only fail safe if the driver layer is fail safe as well The device drivers supplied with uC FS are each fail safe as the chapter for each specific driver shows 128 Licensing Issues 10 7 LICENSING ISSUES There are licensing issues related to FAT particularly relating to Microsoft patents that deal with long file names LFNs 10 7 1 LICENSES FOR LONG FILE NAMES LFNS Microsoft announced on 2003 12 03 that it would be offering licenses for use of its FAT specification and associated intellectual property The royalty for using LFNs is US 0 25 royalty per unit sold with a maximum of US 250 000 per license agreement Micrium uC FS is delivered with complete source code for FAT this includes source code for LFNs To enable long file names LFNs you must set a configuration switch By setting this switch you agree to contact Microsoft to obtain a license to use LFNs 10 7 2 EXTENDED FILE ALLOCATION TABLE EXFAT Microsoft has developed a new proprietary file system exFAT also known as FAT64 exFAT was designed to ha
190. e created if necessary FS FILE ACCESS MODE TRUNC File length will be truncated to 0 324 FS FILE ACCESS MODE APPEND All writes will be performed at EOF FS FILE ACCESS MODE EXCL File will be opened if and only if it does not already exist FS FILE ACCESS MODE CACHED File data will be cached E If FS_ FILE ACCESS MODE TRUNC is set then FS FILE ACCESS MODE WR must also be set E If FS FILE ACCESS MODE EXCL is set then FS FILE ACCESS MODE CREATE must also be set E FS FILE ACCESS MODE RD and or FS FILE ACCESS MODE WR must be set B The mode string argument of fs fopen function can specify a subset of the possible valid modes for this function The equivalent modes of fs_fopen mode strings are shown in Table 5 4 fopen Mode String mode Equivalent vm or rb FS FILE ACCESS MODE RD w or wb FS FILE ACCESS MODE WR FS FILE ACCESS MODE CREATE FS FILE ACCESS MODE TRUNC a or ab FS FILE ACCESS MODE WR FS FILE ACCESS MODE CREATE FS FILE ACCESS MODE APPEND r or rb or r b FS FILE ACCESS MODE RD FS FILE ACCESS MODE WR w or wb or w b FS FILE ACCESS MODE RD FS FILE ACCESS MODE WR FS FILE ACCESS MODE CREATE FS FILE ACCESS MODE TRUNC at or ab or a b FS FILE ACCESS MODE RD FS FILE ACCESS MODE WR FS FILE ACCESS MODE CREATE FS FILE ACCESS MODE APPEND Table A 1 fs_fopen
191. e dev Device name see Note p err Pointer to variable that will the receive return error code from this function FS ERR NONE FS ERR NAME NULL FS ERR DEV INVALID FS ERR DEV NOT OPEN FS ERR DEV NOT PRESENT FS ERR DEV IO FS ERR DEV TIMEOUT RETURNED VALUE None NOTES WARNINGS Device low level unmounted successfully Argument name_dev passed a NULL pointer Argument name_dev specifies an invalid device Device is not open Device is not present Device I O error Device timeout The device must be a NOR device e g nor 0 Low level unmounting clears software knowledge of the on disk structures forcing the device to again be low level mounted or formatted prior to further use 376 A 11 4 FSDev_NOR_LowCompact void FSDev NOR LowCompact CPU CHAR name dev FS ERR p err File Called from Code enabled by fs dev nor c Application N A Low level compact a NOR device ARGUMENTS name dev Device name see Note p err Pointer to variable that will the receive return error code from this function FS ERR NONE FS ERR NAME NULL FS ERR DEV INVALID FS ERR DEV NOT OPEN FS ERR DEV NOT PRESENT FS ERR DEV INVALID LOW FMT FS ERR DEV IO FS ERR DEV TIMEOUT RETURNED VALUE None NOTES WARNINGS Device low level compacted successfully Argument name dev passed a NULL pointer Argument name dev specifies an invalid device Device is not open Device is not present Device
192. e low level formatted with this driver prior to access by the high level file system a requirement which the device module enforces 369 Appendix A A 10 2 FSDev_NAND_LowMount void FSDev_NAND LowMount CPU CHAR name dev FS ERR p err File Called from Code enabled by fs dev nand c Application N A Low level mount a NAND device ARGUMENTS name dev Device name see Note p err Pointer to variable that will receive the return error code from this function FS ERR NONE Device low level mounted successfully FS ERR NAME NULL Argument name dev passed a NULL pointer FS ERR DEV INVALID Argument name dev specifies an invalid device FS ERR DEV NOT OPEN Device is not open FS ERR DEV NOT PRESENT Device is not present FS ERR CORRUPT LOW FMT Device low level format corrupted FS ERR DEV INVALID LOW FMT Device needs to be low level formatted FS ERR DEV INCOMPATIBLE LOW PARAMS Device configuration not compatible with existing format S ERR DEV IO Device I O error FS_ERR_DEV_TIMEOUT Device timeout RETURNED VALUE None NOTES WARNINGS The device must be a NAND device e g nand 0 370 Low level mounting parses the on device structure detecting the presence of a valid low level format If FS_ERR_DEV_INVALID_LOW_FMT is returned the device is NOT low level formatted If an existing on device low level format is found but doesn t match the format prompted by specified device configuration FS ERR DEV
193. e return value of FSDev GetNbrDevs inclusive ARGUMENTS dev nbr Device number name dev String buffer that will receive the device name see Note 2 RETURNED VALUE None NOTES WARNINGS E name dev must point to a character array of FS CFG MAX DEV NAME LEN characters B If the device does not exist name dev will receive an empty string 276 A 3 5 FSDev_GetDevCnt FS OTY FSDev_GetDevCnt void File Called from Code enabled by fs dev c Application Gets the number of open devices ARGUMENTS None RETURNED VALUE Number of devices currently open NOTES WARNINGS None N A 277 Appendix A A 3 6 FSDev_GetDevCntMax FS OTY FSDev_GetDevCntMax void File Called from Code enabled by fs_dev c Application N A Gets the maximum possible number of open devices ARGUMENTS None RETURNED VALUE Maximum number of open devices NOTES WARNINGS None 278 A 3 7 FSDev_GetNbrPartitions FS PARTITION NBR FSDev_GetNbrPartitions CPU CHAR name dev FS ERR p err File Called from Code enabled by fs deu Application FS _CFG PARTITION EN Get number of partitions on a device ARGUMENTS name dev Pointer to the device name p err Pointer to variable that will receive return error code from this function FS ERR NONE Number of partitions obtained FS ERR DEV VOL OPEN Volume open on device FS ERR INVALID SIG Invalid MBR signature FS ERR NAME
194. e size if whence is FS_SEEK_END E The end of file indicator is cleared B If the file position indicator is set beyond the file s current data and data is later written to that point reads from the gap will read 0 the file MUST be opened in write or read write mode 248 A 2 15 fs_fsetpos int fs fsetpos FS FILE p file fs fpos t p pos File Called from Code enabled by fs_api c Application FS CFG API EN Set file position indicator ARGUMENTS p file Pointer to a file p pos Pointer to variable containing file position indicator RETURNED VALUE 0 if the function succeeds Non zero value otherwise NOTES WARNINGS B The return value should be tested against 0 rtn fs fsetpos pfile amp pos if rtn 0 No error occurred else Handle error B If a read or write error occurs the error indicator shall be set B The value stored in pos should be the value from an earlier call to fs_fgetpos No attempt is made to verify that the value in pos was obtained by a call to s_fgetpos E See also fs_fseek 249 Appendix A A 2 16 fs_ftell long int fs ftell FS FILE p file File Called from Code enabled by fs_api c Application FS CFG API EN Get file position indicator ARGUMENTS p file Pointer to a file RETURNED VALUE The current file system position if the function succeeds 1 otherwise NOTES WARNINGS The file position
195. e terms with definitions A file system suite is software which can find and access files and directories Using file system suite rather than file system eliminates any need for disambiguation among the second term s several meanings which include a system for organizing directories and files a collection of files and directories stored on a drive and commonly the software which will be referred to as a file system suite The term file system will always mean a collection of files and directories stored on a drive or in this document volume A device driver or just driver is a code module which allows the general purpose file system suite to access a specific type of device A device driver is registered with the file system suite A device is an instance of a device type that is accessed using a device driver An addressable area typically of 512 bytes on a device is a sector A sector is the smallest area that from the file system suite s point of view can be atomically read or written Several devices can use the same device driver These are distinguished by each having a unique unit number Consequently lt DEVICE NAME gt lt UNIT NUMBER gt is a unique device identifier if all devices are required to have unique names That requirement is enforced in this file system suite 59 Chapter 4 A logical device is the combination of two or more separate devices To form a logical device the sect
196. e that will receive the return error code from this function RETURNED VALUE None NOTES WARNINGS Several members of p phy data may need to be used assigned 1 BlkCnt and BlkSize must be assigned the block count and block size of the device respectively 2 RegionNbr specifies the block region that will be used AddrRegionStart must be assigned the start address of this block region 3 DataPtr may store a pointer to any driver specific data 4 UnitNbr is the unit number of the NOR device 5 MaxClkFreg specifies the maximum SPI clock frequency 6 BusWIdth BusWidthMax and PhyDevCnt specify the bus configuration AddrBase specifies the base address of the NOR flash memory 467 Appendix C C 9 2 Close void Close FS DEV NOR PHY DATA p phy data File Called from Code enabled by NOR physical layer driver FSDev_ NOR Close N A Close uninitialize a NOR device instance ARGUMENTS p phy data Pointer to NOR phy data RETURNED VALUE None NOTES WARNINGS None 468 C 9 3 Ba void Rd FS DEV NOR PHY DATA p phy data void p dest CPU_INT32U start CPU_INT32U ent FS ERR p err File Called from Code enabled by NOR physical layer driver FSDev NOR PhyRdHandler N A Read from a NOR device and store data in buffer ARGUMENTS p phy data Pointer to NOR phy data p dest Pointer to destination buffer start Start address of read relative to start of device cnt Num
197. each of those calls must be matched with a call to s_funlockfile void App Fnct void unsigned char datal 50 unsigned char data2 10 if App FilePtr FS FILE 0 fs_flockfile App FilePtr Lock file S See Note 1 Wr data atomically ST fs_fwrite datal 1 sizeof datal App FilePtr fs_fwrite data2 1 sizeof datal App FilePtr fs_funlockfile App FilePtr Unlock file Listing 8 4 Example file lock usage 106 Directory Access Functions L8 4 1 fs flockfile will block the calling task until the file is available If the task must write to the file only if no other task is currently accessing it the non blocking function fs funlockfile can be used 8 4 DIRECTORY ACCESS FUNCTIONS The directory access functions provide an API for iterating through the entries within a directory The fs opendir function initiates this procedure and each subsequent call to fs readdir r until all entries have been examined returns information about a particular entry in a struct fs_dirent The fs closedir function releases any file system structures and locks Figure 8 2 gives an example using the directory access functions to list the files in a directory An example result of listing a directory is shown in Figure 4 1 void App Fnct void FS_DIR p dir struct fs dirent dirent struct fs dirent p dirent char str 50 char p_cwd_path fs_time_t ts p dir fs opendir p cwd pa
198. easure interrupt disable time cpu_def h contains miscellaneous define constants used by the pC CPU module Cfg Template This directory contains a configuration template file cpu_cfg h that you will need to copy to your application directory in order to configure the pC CPU module based on your application requirements cpu_cfg h determines whether you will enable measurement of the interrupt disable time whether your CPU implements a count leading zeros instruction in assembly language or whether it will need to be emulated in C and more lt architecture gt This is the name of the CPU architecture for which uC CPU was ported to The lt and gt are not part of the actual name lt compiler gt This is the name of the compiler or compiler manufacturer used to build the code for the pC CPU port The lt and gt are not part of the actual name The files in this directory contain the pC CPU port cpu h contains type definitions to make uC FS and other modules independent of the CPU and compiler word sizes Specifically you will find the declaration of the CPU_INT16U CPU_INT32U CPU_FP32 and many other data types Also this file specifies whether the CPU is a big or little endian machine and contains function prototypes for functions that are specific to the CPU architecture and more 37 Chapter 3 cpu_a asm contains the assembly language functions to implement the code to disable and enable CPU
199. ectors of the device with logical sector numbers A NOR medium MUST be low level formatted with this driver prior to access by the high level file system a requirement which the device module enforces 374 A 11 2 FSDev_NOR_LowMount void FSDev_NOR_LowMount CPU CHAR name dev FS ERR p err File Called from Code enabled by fs dev nor c Application N A Low level mount a NOR device ARGUMENTS name dev Device name see Note p err Pointer to variable that will the receive return error code from this function FS ERR NONE Device low level mounted successfully FS ERR NAME NULL Argument name dev passed a NULL pointer FS ERR DEV INVALID Argument name dev specifies an invalid device FS ERR DEV NOT OPEN Device is not open FS ERR DEV NOT PRESENT Device is not present FS ERR DEV INVALID LOW FMT Device needs to be low level formatted FS ERR DEV IO Device I O error FS ERR DEV TIMEOUT Device timeout RETURNED VALUE None NOTES WARNINGS The device must be a NOR device e g nor 0 Low level mounting parses the on device structure detecting the presence of a valid low level format If FS ERR DEV INVALID LOW FMT is returned the device is NOT low level formatted 375 Appendix A A 11 3 FSDev NOR LowUnmount void FSDev NOR LowUnmount CPU CHAR name dev FS ERR p err File Called from Code enabled by fs dev nor c Application N A Low level unmount a NOR device ARGUMENTS nam
200. ed FS ERR NULL PTR FS ERR INVALID TYPE FS ERR DIR DIS FS ERR DIR NOT OPEN RETURNED VALUE None NOTES WARNINGS None Argument p_dir passed a NULL pointer Argument p dir s TYPE is invalid or unknown Directory module disabled Directory NOT open 293 Appendix A A 4 2 FSDir IsOpen CPU BOOLEAN FSDir Open CPU CHAR name full FS ERR p err File Called from Code enabled by fs dir c Application FS CFG DIR EN fs opendir FSEntry Test if a directory is already open This function is also called by various FSEntry functions to prevent concurrent access to an entry in the FAT filesystem ARGUMENTS name full Name of the directory See section 4 3 uC FS File and Directory Names and Paths on page 62 p err Pointer to variable that will the receive return error code from this function FS ERR NONE Directory opened FS ERR NAME NULL Argument name full passed a NULL pointer FS ERR NAME INVALID Entry name specified invalid or volume could not be found Or entry error see section B 8 Entry Error Codes on page 395 RETURNED VALUE DEE MO if dir is NOT open DEF YES if dir is open NOTES WARNINGS None 294 A 4 3 FSDir_Open FS DIR FSDir Open CPU CHAR name full FS ERR p err File Called from Code enabled by Application fs opendir fs dir c FS CFG DIR EN Open a directory See fs opendir for more information ARGUMENTS name full Na
201. enenennaere rens 225 FS DevDiwAdd eege eege eege eege 226 FS INI raervser Seta tiled dennie enden dicta Ae ee a ee 227 EEEE A EE EE dan enn dedrendddanndn nnen din deddeann den 228 FS WorkingDirGet nn annanee sen nianna eer ennneerenrennneerenennnnennenennnnen 229 FS WorkingDirSet ccs geegent desks geen edd Een Deg ege 230 Posix API FUNCUIONS sek dennen SNE aidian iaaa t eaha aiian aitaan 231 S ASCHME EE 234 TS CHOIR EE 235 EE EE 236 fs elosedin E 237 te cume EN 238 fs2fclose niea A A 239 Le N EECH 240 FS Sferror eebe vita sete retasesteces ccd ee EA EE Aa AEAEE RANE 241 fs TE WE 242 TS TQOCTPOS E 243 fS flocktile enee Bea dann ei a 244 TS TOPON EP 245 fs Tread E 246 FSAASCOK nere dekens A ra den linden iad de Rae nd edelen 247 S fsetpOS iarzars ar eege ee dead 249 Table of Contents A 2 16 A 2 17 A 2 18 A 2 19 A 2 20 A 2 21 A 2 22 A 2 23 A 2 24 A 2 25 A 2 26 A 2 27 A 2 28 A 2 29 A 2 30 A 2 31 A 2 32 A 3 A 3 1 A 3 2 A 3 3 A 3 4 A 3 5 A 3 6 A 3 7 A 3 8 A 3 9 A 3 10 A 3 11 A 3 12 A 3 13 A 3 14 A 3 15 A 3 16 A 4 A 4 1 A 4 2 A 4 3 ER CT EE 250 fs TILING ATE EE 251 TS_ftrylOCkfile seed 252 fs TUMIOCKTIS ee zrvannerdereennsredernnenveneannandegesoadsandeen consbsdonduexs Waada 253 EA LL EEn 254 TSEQOTC WO ten taten atte cnet tes cee ethan date denderende teven adden 255 fs l caltime EE 256 TS MKE vennen ge EENS 257 ER mkimel WE 258 TSLOPONGIN EE 259 TS
202. enn 506 Trace Configuration sssaaa naain aahei aii iaaa aaaea aaa raa re aarden denn 507 Shell ell ue E 509 Files and Directories geseet EEESEENEVEESEE ENEE VEER einden ENEE EN 510 Using the Shell Commande nnen annenenne nennen REENEN 511 GoMMANES Sn E acl 20a eda See Gea ce ak cn eae oa Se nena ce densan E 514 PSE E 515 FSSC E 516 Ee on 518 Ee RE 519 LC LE 520 DE CE 521 LE Co Ae Ee 522 LE EE 523 LE e EE 524 PS EEn 525 PS ele EH 526 IS PWA EE 527 PS EE 528 PS SINGIN A sachs sd a E E E 529 fS TOUCH EE 530 PS Te Uu EE 531 E EE 532 CONTIQUIAUI ON BEE 533 Table of Contents Appendix G Appendix H H 1 H 1 1 H 1 2 H 1 3 H 1 4 Bibliography sisirain iarere rain aN AEn OEEO Ae Ai Irea ENAA ER A 535 HC FS Licensing PoliCy nnnn sen anansenenenennereerennnnnererenenaenenenennaerenennn 537 PGES LIC ON SING EE 537 HC FS Source Code E 537 UC FS Maintenance Renewal 2 cccccceceseeeeeeseeeeeeeeeeeeeeeeeeeeeeeeeaees 538 UC FS Source Code Updates nnee eenen ennen nen nen neenven 538 leide ln GE 538 Chapter Introduction Files and directories are common abstractions which we encounter daily when sending an e mail attachment downloading a new application or archiving old information Those same abstractions may be leveraged in an embedded system for similar tasks or for unique ones A device may serve web pages play or record media images video or music or log data The file system software which performs s
203. er and program supported by many flash implementing the AMD command set is used in this driver if the Maximum number of bytes in a multi byte write On the CFI device geometry definition is non zero Some flash implementing AMD command set have non zero multi byte write size but do not support the write to buffer amp program command Often these devices will support alternate fast programming methods This driver MUST be modified for those devices to ignore the multi byte write size in the CFI information Define NOR_NO_BUF_PGM to force this mode of operation 14 5 2 FSDEV_NOR_INTEL_1X16 FSDev NOR Intel 1x16 supports CFI NOR flash implementing Intel command set including E Most Intel Numonyx devices B Some ST Numonyx M28 device B Others 215 Chapter 14 14 5 3 FSDEV_NOR_SST39 FSDev_NOR_SST39 supports SST s SST39 Multi Purpose Flash memories as described in various datasheets at SST http www sst com SST39 devices use a modified form of the AMD command set A more significant deviation is in the CFI device geometry information which describes two different views of the memory organization division in to small sectors and division into large blocks rather than contiguous separate regions The driver always uses the block organization 14 5 4 FSDEV_NOR_STM25 FSDev_NOR_STM25 supports Numonyx ST s M25 amp M45 serial flash memories as described in various datasheets at Numonyx http www numonyx c
204. ereupon the default will be must specify the difference between minimum and maximum erase counts that will trigger passive wear leveling This value must be between 5 and 100 except if 0 is specified whereupon the default will be used 20 AddrStart must specify for a paralel NOR DevSize SecSize 4096 PctRsvd used 10 EraseCntDiffTh PhyPtr 486 must point to the appropriate physical layer driver FSDev_NOR_AMD 1x08 FSDev_NOR_AMD 1x16 FSDev NOR Intel 1x16 FSDev NOR SST39 CFI compatible parallel NOR implementing AMD command set 8 bit data bus CFI compatible parallel NOR implementing AMD command set 16 bit data bus CFI compatible parallel NOR implementing Intel command set 16 bit data bus SST SST39 Multi Purpose Flash BusWidth BusWidthMax PhyDevCnt NOTES None FSDev_NOR_STM25 ST M25 serial flash FSDev_NOR_SST25 SST SST25 serial flash Other User developed For a parallel NOR the bus configuration is specified via BusWidth BusWidthMax and PhyDevCnt is the bus width in bits between the MCU MPU and each connected device is the maximum width supported by each connected device is the number of devices interleaved on the bus For a serial flash the maximum clock frequency is specified via MaxClkFreg 487 Appendix D D 4 FS_DEV_RAM CFG typedef struct fs dev ram cfg FS SEC SIZE SecSize FS SEC OTY Size void DiskPtr FS_DEV_RAM CFG File Used for fs
205. erface FSDev SD Card BSP Lock Acquire SD MMC card bus lock FSDev SD Card BSP Unlock Release SD MMC card bus lock FSDev_SD Card BSP CmdStart Start a command FSDev SD Card BSP CmdWaitEnd Wait for a command to end and get response FSDev SD Card BSP CmdDataRd Read data following command FSDev SD Card BSP CmdDataWr Write data following command FSDev SD Card BSP GetBlkCntMax Get max block count FSDev_SD Card BSP GetBusWidthMax Get maximum bus width in bits FSDev SD Card BSP SetBusWidth Set bus width FSDev_SD Card BSP SetClkFrea Set clock frequency FSDev_SD Card BSP SetTimeoutData Set data timeout FSDev_SD Card BSP SetTimeoutResp Set response timeout Table C 2 SD MMC cardmode BSP functions Each BSP must implement the functions in Table C 2 For information about creating a port for a platform accessing a SD MMC device in SPI mode see section C 6 SD MMC SPI mode BSP on page 452 This software interface was designed by reviewing common host implementations as well as the SD card association s SD Specification Part A2 SD Host Controller Simplified Specification Version 2 00 which recommends a host architecture and provides the state machines that would guide operations Example function implementations for a theoretical compliant host are provided in this chapter Common 426 advanced requirements such as multiple cards per slot and optimizations such as DMA are possible N
206. estination buffer start Start sector of read cnt Number of sectors to read p err Pointer to variable that will receive the return error code from this function FS_ERR_NONE Sector s read FS ERR DEV INVALID UNIT NBR Device unit number is invalid FS ERR DEV IO Device I O error FS ERR DEV NOT OPEN Device is not open FS ERR DEV NOT PRESENT Device is not present FS ERR DEV TIMEOUT Device timeout 419 Appendix C RETURNED VALUE None NOTES WARNINGS 1 Tracking whether a device is open is not necessary because this should only be called when a device is open 2 The device driver Rd function is called while the caller holds the device lock 420 C 4 6 Wr static void FSDev_ Wr FS DEV p dev void p src FS SEC NBR start FS SEC OTY ent FS ERR p err File Called from Code enabled by fs dev HH c FSDev_WrLocked N A The device driver Wr function should write to a device the data from a buffer If an error is returned the file system suite assumes that no data has been written ARGUMENTS p dev Pointer to device to write to p src Pointer to source buffer start Start sector of write ent Number of sectors to write p err Pointer to variable that will receive the return error code from this function FS ERR NONE Sector s written FS ERR DEV INVALID UNIT NBR Device unit number is invalid FS ERR DEV IO Device 1 O error FS ERR DEV NOT OPEN Device is not open FS ERR DEV NOT PRESENT
207. etc have been re written to follow the same quality as the rest of the file system software 2 1 3 POSIX API LAYER Your application interfaces to uC FS using the well known stdio h API Application Programming Interface Alternately you can use ptC FS s own file and directory interface functions Basically POSIX API layer is a layer of software that converts POSIX file access calls to uC FS file access calls 25 Chapter 2 2 1 4 FS LAYER This layer contains most of the CPU RTOS and compiler independent code for uC FS There are three categories of files in this section 1 File system object specific files E Devices fs_dev B Directories fs_dir B Entries fs_entry m Files fs file E Partitions fs_partition E Volumes fs_vol 2 Support files E Buffer management fs_buf B Cache management fs_cache B Counter management fs_ctr h B File system driver s_sys B Unicode encoding support s_unicode P Utility functions s util 3 Miscellaneous header files Master uC FS header file C s h B Error codes fs_err h E Aggregate header file fs_inc h B Miscellaneous data types fs_type h B Miscellaneous definitions fs_def h B Configuration definitions s cfg fs h 26 Architecture Components 2 1 5 FILE SYSTEM DRIVER LAYER The file system driver layer understands the organization of a particular file system type such as FAT The current version of uC FS on
208. etvbuf MUST be used after a stream is opened but before any other operation is performed on stream B size MUST be more than or equal to the size of one sector it will be rounded DOWN to the nearest size of a multiple of full sectors B Once a buffer is assigned to a file a new buffer may not be assigned nor may the assigned buffer be removed To change the buffer the file should be closed and re opened B Upon power loss any data stored in file buffers will be lost 269 Appendix A A 3 DEVICE FUNCTIONS Most device access functions can return any of the following device errors FS ERR DEV INVALID LOW FMT FS ERR DEV FS ERR DEV IO FS ERR DEV NOT OPEN FS ERR DEV NOT PRESENT FS ERR DEV TIMEOUT Device needs to be low level formatted Device access error Device I O error Device is not open Device is not present Device timeout error Each of these indicates that the state of the device is not suitable for the intended operation void FSDev_AccessLock CPU_CHAR name_dev CPU_INT32U timeout FS_ERR p err void FSDev_AccessUnlock CPU_CHAR name dev FS ERR p err void FSDev Close CPU CHAR name dev FS ERR p err FS PARTITION NBR FSDev_GetNbrPartitions CPU_CHAR name_dev FS ERR p err void FSDev_GetDevName FS OTY dev Dr CPU_CHAR name_dev FS_QTY FSDev_GetDevCnt void FS_QTY FSDev_GetDevCntMax void 270 void FSDev_Invalidate CPU_C
209. every time the device is opened The driver should identify the device instance to be opened by checking p_dev gt UnitNbr For example if template 2 is to be opened then p_dev gt UnitNbr will hold the integer 2 The device driver Open function is called while the caller holds the device lock 417 Appendix C C 4 4 Close static void FSDev_ HH Close FS DEV p dev File Called from Code enabled by fs dev HH c FSDev_Close N A The device driver Close function should uninitialize the hardware and release or free any resources acquired in the Open function ARGUMENTS p dev Pointer to device to close RETURNED VALUE None NOTES WARNINGS 1 Tracking whether a device is open is not necessary because this should ONLY be called when a device is open 2 This will be called EVERY time the device is closed 3 The device driver Close function is called while the caller holds the device lock 418 C 4 5 Ba static void FSDev _ Rd FS DEV p dev void p dest FS SEC NBR start FS SEC OTY ent FS ERR p err File Called from Code enabled by fs dev HH c FSDev_RdLocked N A The device driver Rd function should read from a device and store data in a buffer If an error is returned the file system suite assumes that no data is read if not all data can be read an error MUST be returned ARGUMENTS p dev Pointer to device to read from p dest Pointer to d
210. evice IO Ctrl Execute device I O control operation Table C 1 Device driver API functions 413 Appendix C C 4 1 NameGet static const CPU CHAR FSDev_ NameGet void File Called from Code enabled by fs_dev_ HHH c various N A Device drivers are identified by unique names on which device names are based For example the unique name for the NAND flash driver is nand the NAND devices will be o o named nand 0 nand 1 etc ARGUMENTS None RETURNED VALUE Pointer to the device driver name NOTES WARNINGS 1 The name must not include the character 2 The name must be constant each time this function is called the same name MUST be returned 3 The device driver NameGet function is called while the caller holds the FS lock 414 C 4 2 Init static void FSDev Init void File Called from Code enabled by fs dev HH c FS_DevDrvAdd N A The device driver Init function should initialize any structures tables or variables that are common to all devices or are used to manage devices accessed with the driver This function should not initialize any devices that will be done individually for each with the device driver s Open function ARGUMENTS None RETURNED VALUE None NOTES WARNINGS 1 The device driver Init function is called while the caller holds the FS lock 415 Appendix C C 4 3 Open static
211. f this is the case consider using or developing a specialized controller layer implementation to take advantage of those peripherals and save some CPU time or increase performances 13 8 DEVELOPMENT GUIDE This section describes the code you might need to implement to adapt the driver to your specific hardware and application Typically you will only need to implement the BSP layer for an available controller layer implementation In other cases you might need to provide an implementation for the ECC module and or the controller layer 188 Development Guide 13 8 1 BSP DEVELOPMENT GUIDE GENERIC CONTROLLER If you use the generic controller layer implementation a BSP is required so that it will work for a particular board micro controller or application Other controller layer implementations might require a similar BSP layer The BSP must declare an instance of the BSP API type FS_NAND_CTRLR_GEN BSP API as a global variable within the source code The API structure is an ordered list of function pointers used by the generic controller layer implementation The BSP API type is shown in Listing 13 8 An example of a BSP API structure definition is shown in Listing 13 9 const FS NAND CTRLR GEN BSP API FS NAND BSP SAM9M10 FS_NAND BSP Open 1 FS_NAND BSP Close 2 FS_NAND BSP ChipSelEn 3 FS_NAND BSP ChipSelDis 4 FS_NAND BSP_CmdWr 5 FS_NAND BSP Addrwr 6 FS_NAND BSP DataWr 7 FS_NAND BSP DataRd 8
212. ff7 OxOfff fff8 In pC FS you can enable support for FAT12 FAT16 and FAT32 individually this means that you can enable only the FAT version that you need for your embedded system see Appendix E uC FS Configuration on page 497 FAT32 introduced some innovations B The root directory in the earlier systems was a fixed size i e when the medium is formatted the maximum number of files that could be created in the root directory typically 512 is set In FAT32 the root directory is dynamically resizable like all other directories E Two special sectors have been added to the volume the FS info sector and the backup boot sector The former stores information convenient to the operation of the host such as the last used cluster The latter is a copy of the first disk sector the boot sector in case the original is corrupted 122 Organization of the File Allocation Table 10 3 2 SHORT AND LONG FILE NAMES In the original version of FAT files could only carry short 8 dot 3 names with eight or fewer characters in the main name and three or fewer in its extension The valid characters in these names are letters digits characters with values greater than OxFF and the following 3 Sco ae Ur Se ads AE In uC FS the name passed by the application is always verified both for invalid length and invalid characters If valid the name is converted to upper case for storage in the directory entry Accordin
213. ffer can be flushed to the storage device with fs fflush If a buffer is assigned to a file that was opened in update read write mode then a write may only be followed by a read if the buffer has been flushed by calling s_fflush or a file positioning function A read may be followed by a write only if the buffer has been flushed except when the read encountered the end of file in which case a write may happen immediately The buffer is automatically flushed when the file is closed File buffering is particularly important when data is written in small chunks to a medium with slow write time or limited endurance An example is NOR flash or even NAND flash where write times are much slower than read times and the lifetime of device is constrained by limits on the number of times each block can be erased and programmed 104 File Access Functions static CPU INT32U App FileBuf 512 4 Define file buffer void App Fnct void CPU_INTO8U datal 50 p_file FS _fopen file txt w if p file FS FILE 0 L8 3 1 L8 3 2 Set buffer see Note 1 fs setvbuf p file void App FileBuf FS _IOFBF sizeof App FileBuf fs_fflush p file Make sure data is written to file fs_fclose p file When finished close file Listing 8 3 Example file buffer usage The buffer must be assigned immediately after opening the file An attempt to set the buffer after read or writing t
214. for each possible file FS OS FileLock FS OS FileAccept and FS OS FileUnlock acquire and release access to a specific file Lock operations for the same file MAY be nested so the implementations must be able to determine whether the active task owns the mutex If it does then an associated lock count should be incremented otherwise it should try to acquire the resource as normal FS_OS_WorkingDirGet and FS_OS_WorkingDirSet File and directory paths are typically interpreted absolutely they must start at the root directory specifying every intermediate path component If much work will be accomplished upon files in a certain directory or a task requires a root directory as part of its context working directories are valuable Once a working directory is set for a task subsequent non absolute paths will be interpreted relative to the set directory 405 Appendix C if FS CFG WORKING DIR EN DEF ENABLED CPU CHAR FS OS WorkingDirGet void 1 OS_ERR os err CPU INT32U reg val CPU _CHAR p working dir reg val OSTaskRegGet OS TCB 0 FS OS REG ID WORKING DIR amp os err if os err OS ERR NONE reg val Ou p working dir CPU CHAR reg val return p working dir endif if FS_CFG WORKING DIR EN DEF ENABLED void FS OS WorkingDirSet CPU CHAR p working dir FS ERR p err OS ERR os_err CPU_INT32U reg val reg val CPU INT32U p working dir OSTaskRegSet OS TCB 0 FS O
215. fs fat fat32 fe fat journal ecc h Js fat Ge Js fat Jm crc_util x Device Driver Layer RAM Disk fs_dev_ram SD MMC fs_dev_sd fs_dev_sd_spi fs_dev_sd_card NOR IDE fs_dev_nor fs_dev_ide USB MSC fs_dev_msc l D y 24 uC CPU cpu_a asm cpu h cpu_def h UC Clk Layer clk Device Driver BSP fs_dev_ lt driver gt _bsp c RTOS Layer fs_os clh Time management Device RTOS Figure 2 1 HC FS architecture Architecture Components 2 1 ARCHITECTURE COMPONENTS HC FS consists of a set of modular software components It also requires a few external components provided with the release be compiled into the application and a few configuration and BSP files be adapted to the application 2 1 1 YOUR APPLICATION Your application needs to provide configuration information to uC FS in the form of one C header file named fs_cfg h Some of the configuration data in fs_cfg h consist of specifying whether certain features will be present For example LFN support volume cache and file buffering are all enabled or disabled in this file In all there are about 30 define to set However most of these can be set to their default values 2 1 2 C LIB LIBRARIES Because uC FS is designed to be used in safety critical applications all standard library functions like strcpy memset
216. gly FAT file names are not case sensitive Later in a backwards compatible extension Microsoft introduced long file names LFN LFNs are limited to 255 characters stored as 16 bit Unicode in long directory entries Each LFN is stored with a short file name SFN created by truncating the LFN and attaching a numeric tail to the original this results in names like file 1 txt In addition to the characters allowed in short file names SFN the following characters are allowed in LFNs As described in section E 7 FAT Configuration on page 505 support for LFNs can be disabled if desired If LFNs are enabled the application may choose to specify file names in UTF 8 format which will be converted to 16 bit Unicode for storage in directory entries This option is available if FS CFG UTF8_EN is DEF ENABLED see Appendix E Feature Inclusion Configuration on page 500 123 Chapter 10 ENTRIES FOR FILES THAT HAVE LONG FILE NAMES To allow FAT to support long file names Microsoft devised the LFN directory entry as shown in Figure 10 4 4 8 12 1 4 8 12 16 sum sum 6 cafje j fer oxoo oxoo Ct Creation ms Time H st st Creation Access 1 Cluster Write Time Write Date 1 Cluster File Size Date Date High Low Figure 10 4 LFN directory entry An LFN entry is essentially a workaround to store long file names in several contiguous 32 byte entries that were originally intended for short fi
217. h a flash with some blocks of one size and some blocks of another will require a custom driver adapted from the generic driver for the most similar medium type Multiple small blocks should be grouped together to form large blocks effectively making the flash appear uniform to the generic driver A custom physical layer driver can also implement advanced program operations unique to a NOR device family The physical layer driver acts via a BSP The generic drivers for traditional NOR flash require a BSP as described in Appendix C NOR Flash BSP on page 473 The drivers for SPI flash require a SPI BSP as described in Appendix C NOR Flash SPI BSP on page 480 Parallel Interface bus interface BSP bus interface Each physical layer driver FS DEV NOR PHY API structure Physical Layer Driver Implements particular NOR flash command set Accesses NOR on a ZS der nor bsp c Initialize uninitial ize read write on the NOR Device must NOR Driver ZS deu por ch Provides generic driver interface e g init read write and performs wear leveling so all blocks are used equally Serial Interface Physical Layer Driver Implements particular NOR flash command set Accesses NAND on an SPI interface Jfs_dev_nor_bsp c Initialize uninitial ize read write on the SPI interface NOR Device SPI BSP Figure C 4 NOR driver architecture implement the functions to be placed in
218. he file will fail While it is not necessary to flush the buffer before closing the file some applications may want to make sure at certain points that all previously written data is stored on the device before writing more 105 Chapter 8 8 3 4 DIAGNOSING A FILE ERROR The file maintains flags that reflect errors encountered in the previous file access and subsequent accesses will fail under certain conditions outlined here unless these flags are explicitly cleared using fs_clearerr There are actually two sets of flags One reflects whether the file encountered the end of file EOF during the previous access and if this is set writes will not fail but reads will fail The other reflects device errors and no subsequent file access will succeed except file close unless this is first cleared The functions fs ferror and fs feof can be used to get the state of device error and EOF conditions respectively 8 3 5 ATOMIC FILE OPERATIONS USING FILE LOCK If a file is shared between several tasks in an application the file lock can be employed to guarantee that a series of file operations are executed atomically fs flockfile or its non blocking equivalent fs_ftrylockfile acquires the lock for a task Gf it does not already own it Accesses from other tasks will be blocked until s_funlockfile is called Each file actually has a lock count associated with it This allows nested calls by a task to acquire a file lock
219. he host at card power on it is in the inactive state awaiting a GO_IDLE STATE command to start the initialization process The card will enter SPI mode rather than card mode because the driver holds the CS signal low while executing the GO IDLE STATE command The card now in the idle state moves through the ready as long as it supports the voltage range specified by the host before ending up in standby It can now get selected by the host using the chip select for data transfers Figure 15 5 flowcharts this procedure 153 Chapter 12 12 3 2 SD MMC SPI COMMUNICATION DEBUGGING The SD MMC SPI driver accesses the hardware through a port SPI BSP as described in section C 6 SD MMC SPI mode BSP on page 452 A new BSP developed according to MCU MPU documentation or by example must be verified step by step until flawless operation is achieved 1 Initialization Initialization must succeed 2 Read data Data must be read from card in both single and multiple block transactions 3 Write data Data must be written to the card in both single and multiple block transactions and subsequently verified by reading the modified sectors and comparing to the intended contents Start bit Transmission bit End bit Command Di Cmd ix Argument CRC 1 format 6 bits 32 bits 7 bits Start bit Transmission bit End bit Response Response CRC format 32 or 128 bits 7 bits 1 2 Figure 12 11 SD MMC
220. hed The remaining functions Rd XX RdWord_XX WrWord XX read data from or write data to the NOR If a single parallel NOR device will be accessed these function may be defined as macros to speed up bus accesses 210 Using a Serial NOR Device 14 4 USING A SERIAL NOR DEVICE When used with a serial NOR device the NOR driver is three layered as depicted in the figure below The generic NOR driver as always provides sector abstraction and performs wear leveling to make certain all blocks are used equally Below this the physical layer driver implements a particular command set to read and program the flash and erase blocks Lastly a BSP implements function to communicate with the device over SPI Device commands are executed though this BSP NOR Driver fs_dev_nor c h Provides generic driver interface e g init read write and performs wear leveling so all blocks are used equally Physical Layer Driver fs_dev_nor_stm25 fs_dev_nor_sst25 Implements particular serial NOR flash command set accesses NOR through SPI interface SPI BSP fs_dev_nor_bsp c Implements SPI communication for a particular MCU MPU Figure 14 3 NOR driver architecture serial NOR flash 211 Chapter 14 14 4 1 HARDWARE Serial NOR devices typically connect to a host MCU MPU via an SPI or SPI like bus Eight pin devices with the functions listed in Table 14 5 or similar are common and are often employed with the HOLD a
221. his function FS ERR NONE Block erased successfully FS ERR DEV INVALID OP Invalid operation for device FS ERR DEV IO Device I O error FS ERR DEV TIMEOUT Device timeout error RETURNED VALUE None NOTES WARNINGS None 471 Appendix C C 9 6 IOC void IO Ctrl FS DEV NOR PHY DATA p phy data CPU _INTO8U opt void p data FS ERR p err File Called from Code enabled by NOR physical layer driver various N A Perform NOR device I O control operation ARGUMENTS p_phy data Pointer to NOR phy data opt Control command p data Buffer which holds data to be used for operation OR Buffer in which data will be stored as a result of operation p err Pointer to variable that will receive the return error code from this function FS_ERR_NONE Control operation performed successfully FS ERR DEV INVALID IO CTRL I O Control unknown to driver FS ERR DEV INVALID OP Invalid operation for device FS ERR DEV IO Device I O error FS ERR DEV TIMEOUT Device timeout error RETURNED VALUE None NOTES WARNINGS None 472 C 10 NOR FLASH BSP A traditional NOR flash has two buses one for addresses and another for data For example the host initiates a data read operation with the address of the target location latched onto the address bus the device responds by outputting a data word on the data bus A BSP abstracts the flash interface for the physical layer driver The port includes one code f
222. id conflicting with other size_t definitions 8 1 SUPPORTED FUNCTIONS The supported POSIX functions are listed in the table below These are divided into four groups First the functions which operate on file objects FS_FILEs are grouped under file access or simply file functions An application stores information in a file system by creating a file or appending new information to an existing file At a later time this information may be retrieved by reading the file Other functions support these capabilities for example the application can move to a specified location in the file or query the file system to get information about the file A separate set of file operations or entry functions manage the files and directories available on the system Using these functions the application can create delete and rename files and directories The entries within a directory can be traversed using the directory access or simply directory functions which operate on directory objects FS_DIRs The name and properties of the entries are returned within a struct fs _dirent structure The final group of functions is the working directory functions For information about using file and path names see section 4 3 uC FS File and Directory Names and Paths on page 62 Function POSIX Equivalent Function POSIX Equivalent fs asctime r asctime r fs ftruncate ftruncate fs chdir chdir fs ftrylockfile ftryl
223. idated In this manual as in the design of uC FS the terms device and volume have distinct non overlapping meanings We define a device as a single physical or logical entity which contains a continuous sequence of addressable sectors An SD MMC card is a physical device We define a volume as a collection of files and directories on a device These definitions were selected so that multiple volumes could be opened on a device as shown in Figure 5 1 without requiring ambiguous terminology ide 0 ide 1 partition1 partition1 partition2 Device layer ide ta ide 1b Volume layer Figure 5 1 Device and volume architecture 67 Chapter 5 5 1 DEVICE OPERATIONS The ultimate purpose of a file system device is to hold data Consequently two major operations that can occur on a device are the reading and writing of individual sectors Five additional operations can be performed which affect not just individual sectors but the whole device B A device can be opened During the opening of a device it is initialized and its characteristics are determined sector size number of sectors vendor B A device can be partitioned Partitioning divides the final unallocated portion of the device into two parts so that a volume could be located on each ee section 5 5 Partitions on page 73 B A device can be low level formatted Some device must be low level formatted before
224. identification states Gf it is assigned an address by or is assigned an address before ending up in standby It can now get selected by the host for data transfers Figure 15 9 flowcharts this procedure 143 Chapter 12 12 2 2 SD MMC CARDMODE COMMUNICATION DEBUGGING The SD MMC cardmode driver accesses the hardware through a port BSP A new BSP developed according to MCU MPU documentation or by example must be verified step by step until flawless operation is achieved 1 Initialization 1 bit Initialization must succeed for a SD MMC card in 1 bit mode 2 Initialization 4 or 8 bit Initialization must succeed for a SD MMC card in 4 or 8 bit mode 3 Read data Data must be read from card in both single and multiple block transactions 4 Write data Data must be written to the card in both single and multiple block transactions and subsequently verified by reading the modified sectors and comparing to the intended contents The 1 bit initialization process reveals that commands can be executed and responses are returned with the proper bits in the correct byte order Example responses for each step in the sequence are given in Figure 12 5 and Figure 12 6 The first command executed GO_IDLE STATE never receives a response from the card Only V2 SD cards respond to SEND IF COND returning the check pattern sent to the card and the accepted voltage range The OCR register read with SD_SEND_OP_COND or SEND OP COND as
225. idth types eg CPU INT16U used in the file system suite are defined here The RTOS port adapts the file system suite to the OS kernel if any included in the application The files FS_OS C H contain functions primarily aimed at making accesses to devices and critical information in memory thread safe HC FS interfaces with memory devices through drivers following a generic driver model It is possible to create a driver for a different type of device from this model template The SD MMC driver can be ported to any SD MMC host controller for cardmode access FC 1 6 The SD MMC driver can be ported to any SPI peripheral for SPI mode access FC 1 7 The NAND driver can be ported for many physical organizations page size bus width SLC MLC etc FC 1 8 The NAND driver can be ported to any bus interface A NAND device can also be located directly on GPIO and accessed by direct toggling of port pins FC 1 9 The NOR driver can be ported to many physical organization command set bus type etc FC 1 10 The NOR driver can be ported to any bus interface FC 1 11 The NOR driver can be ported to any SPI peripheral for SPI flash C 1 DATE TIME MANAGEMENT Depending on the settings of uC Clk you might have to write time management functions that are specific to your application For example you might have to define the function Clk ExtTS Get to obtain the timestamp of your system provided by a real time clock peripheral Please
226. ile FS DEV NOR BSP C This file is generally placed with other BSP files in a directory named according to the following rubric Mierium Software EvalBoards lt manufacturer gt lt board Dame lt compiler gt BSP Function Description FSDev_NOR_BSP_Open Open initialize bus for NOR FSDev_NOR_BSP_Close Close uninitialize bus for NOR FSDev NOR BSP Rd 08 16 Read from bus interface FSDev NOR BSP RdWord 08 16 Read word from bus interface FSDev NOR BSP WrWord 08 16 Write word to bus interface FSDev NOR BSP WaitwhileBusy Wait while NOR is busy Table C 6 NOR BSP functions 473 Appendix C C 10 1 FSDev NOR BSP Open CPU BOOLEAN FSDev NOR BSP Open FS OTY unit nbr CPU _ADDR addr base CPU INTO8U bus width CPU INTO8U phy dev ent File Called from Code enabled by s_dev_nor_bsp c NOR physical layer driver N A Open initialize bus for NOR ARGUMENTS unit nbr Unit number of NOR addr base Base address of NOR bus width Bus width in bits phy dev ent Number of devices interleaved RETURNED VALUE DEF OR if interface was opened DEF FAIL otherwise NOTES WARNINGS This function will be called every time the device is opened 474 C 10 2 FSDev_NOR BSP Close void FSDev NOR BSP Close FS OTY unit nbr File Called from Code enabled by fs dev nor bsp c NOR physical layer driver N A Close uninitialize bus for NOR ARGUMENTS
227. ile contents to terminal output fs_pwd Write to terminal output pathname of current working directory fs mm Remove a directory entry fs rmdir Remove a directory fs_touch Change file modification time fs_umount Unmount volume fs_we Determine the number of newlines words and bytes in a file Table F 1 Commands Information about each command can be obtained using the help h option COM4 PuTTY erminal output Figure F 3 Help option output 514 F 3 1 fs_cat Print file contents to the terminal output USAGES fs cat file ARGUMENTS file Path of file to print to terminal output OUTPUT File contents in the ASCII character set Non printable non space characters are transmitted as full stops periods character code 46 For a more convenient display of binary files use fs_od REQUIRED CONFIGURATION Available only if FS SHELL CFG CAT EN is DEF ENABLED NOTES WARNINGS None 515 Appendix F F 3 2 fs cd Change the working directory USAGES fs cd dir ARGUMENTS dir Absolute directory path OR Path relative to current working directory OUTPUT None REQUIRED CONFIGURATION Available only if FS SHELL CFG CD EN is DEF ENABLED NOTES WARNINGS The new working directory is formed in three steps 1 If the argument dir begins with the path separator character slash or a volume name it will be interpreted as an absolute directory path and will become the preliminary
228. ils 208 Using a Parallel NOR Device B Command set Three different command sets are common Intel AMD and SST All three are supported B Geometry A device is composed of one or more regions of identically sized erase blocks Uniform devices contain only one region Boot block devices often have one or two regions of small blocks for code storage at the top or bottom of the device All of these are supported by the NOR driver Offset Length Bytes Contents 0x10 1 Query string Q 0x11 1 Query string R 0x12 1 Query string Y 0x13 2 Command set 0x27 1 Device size in bytes 2n Ox2A 2 Maximum number of bytes in multi byte write 2N 0x2C 1 Number of erase block regions m 0x2D 2 Region 1 Number of erase blocks x 1 Ox2F 2 Region 1 Size of each erase block y 256 bytes 0x31 2 Region 2 Number of erase blocks x 1 0x33 2 Region 2 Size of each erase block y 256 bytes 0x2D m 1 4 2 Region m Number of erase blocks x 1 Ox2F m 1 4 2 Region m Size of each erase block y 256 bytes Table 14 2 CFI query information Table 14 2 gives the format of CFI query information The first three bytes should constitute the marker string QRY by which the retrieval of correct parameters is verified A two byte command set identifier follows this must match the identifier for the command set supported by the physical layer driver Beyo
229. interface is more flexible but is also more complex to implement If you choose that route it is strongly recommended to use the provided implementations as an example Listing 13 12 describes the API that must be implemented for the controller layer 194 typedef struct fs nand ctrlr api void Open void Close FS NAND PART DATA PartDataGet FS_NAND PG SIZE Setup void SecRd void OOSRdRaw void SpareRdRaw void secWr void BlkErase void TOEG EN FS_NAND CTRLR API FS _NAND PART API Development Guide p part api void void FS_ERR void void void FS_NAND PG SIZE FS_ERR void void void FS_SEC_NBR FS_ERR void void FS_SEC_NBR FS_NAND PG SIZE FS_NAND PG SIZE FS_ERR void void FS_SEC_QTY FS_NAND PG SIZE FS_NAND PG SIZE FS_ERR void void void FS_SEC_NBR FS_ERR void CPU_INT32U FS_ERR void CPU_INTO8U void FS_ERR p bsp api p Otrin Chen p err p ctrlr data p ctrlr data p ctrlr data sec size p err p ctrlr data p dest p dest oos sec ix phy p err p ctrlr data p dest oos sec_nbr phy offset length p err p ctrlr data p dest oos pg_nbr_phy offset length p err p ctrlr data p src p src spare sec_nbr phy p err p ctrlr data blk nbr phy p err p ctrlr data cmd p buf p err Listing 13 12 Controller API type definition 195 Cha
230. interrupts count leading zeros Gf the CPU supports that instruction and other CPU specific functions that can only be written in assembly language This file could also contain code to enable caches setup MPUs and MMU and more The functions provided in this file are accessible from C cpu_c c contains C code of functions that are specific to the specific CPU architecture but written in C for portability As a general rule if a function can be written in C then it should unless there are significant performance benefits by writing it in assembly language 3 5 HC LIB PORTABLE LIBRARY FUNCTIONS HC LIB consists of library functions that are meant to be highly portable and not tied to any specific compiler This was done to facilitate third party certification of Micrium products Micrium Software uC LIB lib_ascii c lib_ascii h lib def h lib_math c lib math h lib mem c lib mem bh lib_str c lib str h Cfg Template lib ecfg h Ports lt architecture gt lt compiler gt lib mem a asm Micrium This directory contains all software components and projects provided by Micrium 38 UC CIk Time Calendar Management Software This sub directory contains all the software components and projects uC LIB This is the main pC LIB directory Cfg Template This directory contains a configuration template file lib efg h that must be copied to the application directory to configure the pC LIB module ba
231. ion Partition NOT found Partition zero Pool is empty Pool is full Block not found in used pool pointers Block found in free pool pointers 397 Appendix B FS ERR POOL INVALID BLK IX FS ERR POOL INVALID BLK NBR FS ERR POOL INVALID BLK SIZE Block index invalid Number blocks specified invalid Block size specified invalid B 13 FILE SYSTEM ERROR CODES FS ERR SYS TYPE NOT SUPPORTED FS ERR SYS INVALID SIG FS ERR SYS DIR ENTRY PLACE FS ERR SYS DIR ENTRY NOT FOUND FS ERR SYS DIR ENTRY NOT FOUND YET FS ERR SYS SEC NOT FOUND FS ERR SYS CLUS CHAIN END FS ERR SYS CLUS CHAIN END EARLY FS ERR SYS CLUS INVALID FS ERR SYS CLUS NOT AVAIL FS ERR SYS SFN NOT AVAIL FS ERR SYS LFN ORPHANED B 14 VOLUME ERROR CODES FS ERR VOL INVALID NAME FS ERR VOL INVALID SIZE FS ERR VOL INVALID SEC SIZE FS ERR VOL INVALID CLUS SIZE FS ERR VOL INVALID OP FS ERR VOL INVALID SEC NBR FS ERR VOL INVALID SYS FS ERR VOL NO CACHE FS ERR VOL NONE AVAIL FS ERR VOL NONE EXIST FS ERR VOL NOT OPEN FS ERR VOL NOT MOUNTED FS ERR VOL ALREADY OPEN FS ERR VOL FILES OPEN 398 File sys type not supported Sec has invalid OR illegal sig Dir entry could not be placed Dir entry not found Dir entry not found yet Sec not found Cluster chain ended Cluster chain ended before number clusters traversed Cluster invalid Cluster not avail SFN is not avail LFN entry orphaned Invalid volume name Invalid volume size
232. ion of the spare area will use one index of the array There must also be a last entry set to 1 1 for the driver to 183 Chapter 13 know when to stop parsing the table Note that the factory defect mark should be excluded of the free regions You can also refer to the example see section 13 1 Getting Started on page 160 typedef struct fs nand free spare data FS_NAND PG SIZE OctetOffset 1 FS_NAND PG SIZE OctetLen 2 FS_NAND FREE SPARE DATA Listing 13 6 NAND configuration structure for free regions of the spare area L13 6 1 Offset Gin octets of a free region L13 6 2 Length in octets of a free region ONFI PART LAYER The ONFI part layer implementation is able to obtain from ONFI compliant devices all the parameters necessary for the NAND driver to operate The different parameters are extracted from the device parameter page Table 13 4 lists the versions of the ONFI standard for which automatic parameter page parsing is supported If your device does not respect this standard it should be used with a different implementation o f the part layer ONFI version Supported parameter page ONFI 3 0 YES ONFI 2 3a YES ONFI 2 2 YES ONFI 2 1 YES ONFI 2 0 YES ONFI 1 0 YES Table 13 4 ONFI parameter page support for different ONFI versions 184 Board Support Package Generic Controller The ONFI part layer implementation does not have a lot of configuration options since most parameter
233. ion returns an error See fs flockfile 252 A 2 19 fs_funlockfile void fs funlockfile FS FILE p file File Called from Code enabled by fs_api c Application FS CFG API EN and FS _CFG FILE LOCK EN Release task ownership of a file ARGUMENTS p file Pointer to a file RETURNED VALUE None NOTES WARNINGS See fs flockfile 253 Appendix A A 2 20 fs_fwrite fs size t fs fwrite void p src fs size t size fs size t nitems FS FILE p file File Called from Code enabled by fs_api c FS_CFG RD ONLY EN Application FS CFG API EN and not Write to a file ARGUMENTS p src Pointer to source buffer size Size of each item to write nitems Number of items to write p file Pointer to a file RETURNED VALUE Number of items written NOTES WARNINGS E The size or nitems is 0 then the file is unchanged and zero is returned B Ifthe file is buffered and the last operation is input read then a call to fs fsetpos or fs fseek MUST occur before output write can be performed unless the end of file was encountered B The file must have been opened in write or update read write mode B If the file was opened in append mode all writes are forced to the end of file 254 A 2 21 fs_getcwd char fs getcwd char path dir fs size t size File Called from Code enabled by fs_api c Application FS CFG API EN and not FS_CFG WORKING DIR EN
234. is chapter for more information see FSDev SD Card BSP CmdStart void FsDev SD Card BSP SetBusWidth FS QTY unit nbr CPU _INTO8U width if width lu REG HOST CONTROL amp BIT HOST CONTROL DATA TRANSFER WIDTH else REG HOST CONTROL BIT_HOST_CONTROL_DATA TRANSFER_WIDTH Listing C 11 FSDev_SD_Card_BSP_SetBusWidth 449 Appendix C C 5 10 FSDev_SD Card BSP_SetCikFreq void FSDev_SD Card BSP SetClkFreq FS OTY unit_nbr CPU_INT32U freq File Called from Code enabled by fs_dev_sd_card_bsp c FSDev_SD Card Refresh N A Set clock frequency ARGUMENTS unit nbr Unit number of SD MMC card freq Clock frequency in Hz RETURNED VALUE None NOTES WARNINGS The effective clock frequency MUST be no more than freq If the frequency cannot be configured equal to freq it should be configured less than freq 450 C 5 11 FSDev SD Card BSP_SetTimeoutData void FSDev SD Card BSP SetTimeoutData FS OTY unit nbr CPU INI32U to clks File Called from Code enabled by fs dev sd card bsp c FSDev_SD Card Refresh N A Set data timeout ARGUMENTS unit nbr Unit number of SD MMC card to clks Timeout in clocks RETURNED VALUE None NOTES WARNINGS None 451 Appendix C C 5 12 FSDev_SD Card BSP_SetTimeoutResp void FSDev_SD Card BSP SetTimeoutResp FS OTY unit nbr CPU INI32U to ms File Called from Code enabled by fs dev sd card bsp
235. is present and responsive but must be low level formatted The application should next call FSDev_NOR LowFmt for the NOR flash Using Removable Devices B If the return error code is FS ERR DEV NOT PRESENT FS ERR DEV IO or FS ERR DEV TIMEOUT the device is either not present or did not respond This is an important consideration for removable devices It is still registered with the file system suite and the file system will attempt to re open the device each time the application accesses it B If any other error code is returned the device is not registered with the file system The developer should examine the error code to determine the source of the error 5 3 USING REMOVABLE DEVICES HC FS expects that any call to a function that accesses a removable device may fail since the device may be removed powered off or suddenly unresponsive If uC FS detects such an event the device will need to be refreshed or closed and re opened FSDev Refresh refreshes a device chngd FSDev_Refresh CPU_CHAR ide 0 lt b device name FS ERR amp err lt c return error There are several cases to consider Bm If the return error is FS ERR NONE and the return value a is DEF YES then a new device e g SD card has been inserted All files and directories that are open on volumes on the device must be closed and all volumes that are open on the device must be closed or refreshed Bm If the return error is FS ERR NONE
236. isk driver can be found in section 9 1 1 Driver Characterization on page 113 For more information about the FS DEV RAN CFG structure see section D 4 FS_DEV_RAM_CFG on page 488 define APP CFG FS RAM SEC SIZE 512 1 define APP CFG FS RAM NBR SECS 48 1024 static CPU INT32U App FS RAM Disk APP CFG FS RAM SEC SIZE APP CFG FS RAM NBR SECS 4 CPU_BOOLEAN App FS AddRAM void FS_ERR err FS DEV RAM CFG cfg FS _DevDrvAdd FS DEV API amp FSDev RAM 2 FS_ERR amp err if err FS ERR NONE amp amp err FS ERR DEV DRV ALREADY ADDED return DEF FAIL ram cfg SecSize APP CFG FS RAM SEC SIZE fe 3 ER ram_cfg Size APP CFG FS RAM NBR_SECS ram cfg DiskPtr void amp App FS RAM Disk 0 132 Using the RAM Disk Driver 4 FSDev Open CPU CHAR ram 0 a void amp ram cfg ha b FS_ERR Ae if err ls FS ERR NONE return DEF FAIL PEs xy FSVol_Open CPU_CHAR ram 0 a CPU_CHAR ram 0 b FS PARTITION NBR 0 c FS_ERR amp err switch err case FS_ERR_NONE APP_TRACE_DBG opened volume mounted r n break case FS ERR PARTITION NOT FOUND Volume error APP TRACE DG opened device not formatted r n FSVol_Fmt ram 0 void 0 amp err 6 if err FS ERR NONE APP TRACE DBG format failed r n return DEF FAIL break default
237. ite Truncate Create Append r or rb Yes No No No No w or wb No Yes Yes Yes No a or ab No Yes No Yes Yes r or rb or r b Yes Yes No No No w or wb or w b Yes Yes Yes Yes No a or ab or a b Yes Yes No Yes Yes Table 8 2 fs_fopen mode strings interpretations 100 File Access Functions After a file is opened any of the file access functions valid for that its mode can be called The most commonly used functions are fs_fread and fs_fwrite which read or write a certain number of items from a file number of items read gt cnt fs fread p buf lt pointer to buffer iby lt size of each item 100 lt number of items p_file lt pointer to file The return value the number of items read or written should be less than or equal to the third argument If the operation is a read this value may be less than the third argument for one of two reasons First the file could have encountered the end of file EOF which means that there is no more data in the file Second the device could have been removed or some other error could have prevented the operation To diagnose the cause the fs_feof function should be used This function returns a non zero value if the file has encountered the EOF Once the file access is complete the file must be closed if an application fails to close files then the file system sui
238. ite buffered data to volume FSFile Close Close a file FSFile ClrErr Clear error s on a file FSFile IsEOF Determine whether a file is at EOF FSFile IsErr Determine whether error occurred on a file FSFile IsOpen Determine whether a file is open or not FSFile LockGet Acquire task ownership of a file FSFile LockSet Release task ownership of a file FSFile LockAccept Acquire task ownership of a file if available FSFile Open Open a file FSFile PosGet Get file position FSFile PosSet Set file position FSFile Query Get information about a file FSFile Rd Read from a file FSFile Truncate Truncate a file FSFile Wr Write to a file 84 Table 6 1 File access functions File Access Functions 6 1 1 OPENING FILES When an application needs to access a file it must first open it using fs fopen or FSFile Open For most applications the former with its familiar interface suffices In some cases the flexibility of the latter is demanded file ptr gt p file FSFile Open file txt lt file name FS FILE ACCESS MODE RD lt access mode amp err lt return error if p file FS_FILE 0 Handle error The return value of this function should always be verified as non NULL before the application proceeds to access the file The second argument to this function is a logical OR of mode flags FS
239. ith fast reads speeds and comparable capacities but demanding less of the CPU and hardware being accessed by SPI or SPI like protocols Table 14 1 briefly compares these two technologies specific listings of supported devices are located in section 14 5 Physical Layer Drivers on page 214 Device Category Typical Packages Manufacturers Description Parallel NOR Flash TSOP32 TSOP48 AMD Spansion Intel Parallel data 8 or 16 bit and BGA48 TSOP56 Numonyx SST ST address bus 20 bits Most devices BGA56 Numonyx have CFI query information and use one of several standard command sets Serial NOR Flash SOIC 8N SOIC 8W Atmel SST ST SPI or multi bit SPI like interface SOIC 16 WSON Numonyx Command sets are generally similar USON Table 14 1 NOR flash devices 199 Chapter 14 14 1 FILES AND DIRECTORIES The files inside the RAM disk driver directory are outlined in this section the generic file system files outlined in Chapter 3 uC FS Directories and Files on page 29 are also required Micrium Software uC FS Dev This directory contains device specific files Micrium Software uC FS Dev NOR This directory contains the NOR driver files 200 fs_dev_nor These files are device driver for NOR flash devices This file requires a set of BSP functions be defined in a file named fs_dev_nor_bsp c to work with a certain hardware setup BSP Template fs_dev_nor_bsp c This is a templ
240. itialized For more information about these parameters see section Generic Controller Extension Layer on page 180 Please note that if you are using a different controller layer implementation there probably won t be a controller extension layer Also if using the generic controller you might need to use a different extension Refer to section Generic Controller Extension Layer on page 180 for a list of available controller extensions L13 1 6 113 17 113 18 113 1029 L13 1 10 Getting Started The NAND translation layer structure should be initialized For more information about these parameters see section 13 3 1 Translation Layer Configuration on page 171 FSDev_Open opens initializes a file system device The parameters are the device name a and a pointer to a device driver specific configuration structure b The device name a is composed of a device driver name nand a single colon an ASCII formatted integer the unit number and another colon FS _NAND LowFmt low level formats a NAND If the NAND has never been used with uC FS it must be low level formatted before being used Low level formatting will create and initialize the low level driver metadata on the device FSVol_Open opens mounts a volume The parameters are the volume name a the device name b and the index of the partition that will be opened c There is no restriction on the volume name a however it is typi
241. jects uc FS This is the main nC FS directory FAT This directory contains the FAT system driver for pC FS All the files in this directory should be included in your build assuming you have the source code 3 10 HC FS MEMORY DEVICE DRIVERS These files are generic drivers to use with differenty memory devices Mierium Software uC FS Dev MSC fs_dev_msc c fs_dev_msc h NAND 46 uC FS Memory Device Drivers fs_dev_nand c fs_dev_nand h Ctrlr fs_dev_nand_ctrlr_gen c fs dev nand ctrlr gen h fs dev nand ctrlr gen soft ecc c fs dev nand ctrlr gen soft ecc h fs dev nand ctrlr gen micron ecc c fs dev nand ctrlr gen micron ecc h Part fs dev nand part _static c fs dev nand part static h fs dev nand part _onfi c fs dev nand part _onfi h C g Template fs dev nand cfg h BSP Template fs dev nand ctrlr gen bsp c NOR fs_ dev por CG fs_dev_nor h PHY fs_dev_nor_amd_1x08 c fs_dev_nor_amd_1x08 h fs_dev_nor_amd_1x16 c fs_dev_nor_amd_1x16 h fs_dev_nor_intel c fs_dev_nor_intel h fs_dev_nor_sst25 c fs_dev_nor_sst25 h fs_dev_nor_sst39 c fs_dev_nor_sst39 h fs_dev_nor_stm25 c fs_dev_nor_stm25 h fs_dev_nor_stm29_1x08 c fs_dev_nor_stm29_1x08 h fs_dev_nor_stm29_1x16 c fs_dev_nor_stm29_1x16 h 47 Chapter 3 Template fs dev nor template c fs_dev nor template h BSP Template fs dev nor bsp c BSP Template SPI GPIO fs dev nor bsp c BSP Template SPI fs de
242. k of flash chips FAT All standard FAT variants and features are supported including FAT12 FAT16 FAT32 and long file names which encompasses Unicode file names Files can be up to 4 GB and volumes up to 8 TB the standard maximum An optional journaling module provides total power fail safety to the FAT system driver Application Programming Interface API uC FS provides two APIs for file and directory access A proprietary API with parallel argument placement and meaningful return error codes is provided with functions like FSFile Wr FSFile Rd and FSFile PosSet Alternatively a standard POSIX compatible API is provided including functions like fs_fwrite fs fread and fs_fsetpos that have the same arguments and return values as the POSIX functions fwrite fread and fsetpos Scalable The memory footprint of uC FS can be adjusted at compile time based on the features you need and the desired level of run time argument checking For applications with limited RAM features such as cache and read write buffering can be disabled for applications with sufficient RAM these features can be enabled in order to gain better performance Portable uC FS was designed for resource constrained embedded applications Although HC FS can work on 8 and 16 bit processors it will work best with 32 or 64 bit CPUs RTOS uC FS does not assume the presence of a RTOS kernel However if you are using a RTOS a simple port layer is required
243. layout is shown below for a device with 2048 octets pages using 512 bytes sectors EN 8 Q Im Q Ee Ee En Sector 1 Sector 2 Sector 3 Sector 4 S 5 le 5 CO 8 le 3 old gl A Nn N bk AP a Vv k DOD BV ANO D AN d S G PE TAS Figure 13 2 Example generic controller driver page layout To determine if the generic controller driver is compatible with your hardware you can study its BSP interface described in section 13 8 1 BSP Development Guide Generic Controller on page 189 179 Chapter 13 GENERIC CONTROLLER EXTENSION LAYER The generic controller extension layer extends the functionality of the generic controller mostly with regards to ECC It allows for the reuse of the generic controller code enabling easy customizations of the controller layer The NAND driver ships with two generic controller extensions Extension API Files Description FS _NAND CtrlrGen SoftECC fs_dev_nand_ctrir_gen_soft_ecc in Micrium Software uC FS Dev NAN D Ctrir Supports software ECC calculation and correction through uC CRC ECC modules FS_NAND_CtrlrGen_MicronECC fs_dev_nand_ctrir_gen_micron_ecc in Micrium Software uC FS Dev NAN D Ctrir Supports on chip ECC hardware for some Micron parts ex MT29F01GO8ABADA Table 13 2 Generic controller layer extensions provided The software ECC generic controller extension FS_NAND CtrlrGen_SoftECC u
244. le USAGES fs rm file ARGUMENTS file File path OUTPUT None REQUIRED CONFIGURATION Available only if FS SHELL CFG RM EN is DEF ENABLED and FS CFG RD ONLY EN is DEF DISABLED NOTES WARNINGS None 528 F 3 14 fs_rmdir Remove a directory USAGES fs rmdir dir ARGUMENTS dir Directory path OUTPUT None REQUIRED CONFIGURATION Available only if FS SHELL CFG RMDIR EN is DEF ENABLED and FS CFG RD ONLY EN is DEF_DISABLED NOTES WARNINGS None 529 Appendix F F 3 15 fs touch Change file modification time USAGES fs touch file ARGUMENTS file File path OUTPUT None REQUIRED CONFIGURATION Available only if FS SHELL CFG TOUCH EN is DEF ENABLED and FS CFG RD ONLY EN is DEF DISABLED NOTES WARNINGS The file modification time is set to the current time 530 F 3 16 fs umount Unount volume USAGES fs umount vol ARGUMENTS vol Volume to unmount OUTPUT None REQUIRED CONFIGURATION Available only if FS SHELL CFG UMOUNT EN is DEF ENABLED NOTES WARNINGS None 531 Appendix F F 3 17 fs wc Determine the number of newlines words and bytes in a file USAGES fs wc file ARGUMENTS file Path of file to examine OUTPUT Number of newlines words and bytes equivalent to printf d Sd 3d Ser newline cnt word ent byte ent file REQUIRED CONFIGURATION Available only if FS SHELL CFG WC EN is DEF ENABLED NOTES WARNINGS None
245. le names and volume names The constant FS_CFG MAX FULL NAME LEN is defined in fs cfg fs h to describe the maximum full name length The path name begins with a path separator character and includes the file name the file name is just the portion of the path name after the last non final path separator character The full name is composed of an explicit volume name optional and a path name the maximum full name length can be calculated FullNameLenmax VolNameLenmax PathNameLenmax Figure 2 3 demonstrates these definitions ee full name cl path name myvolume MyDir0 MyDirl MyDir2 my very very long file name txt E parent name _ file name volume name Figure 4 1 File path and volume name lengths No maximum parent name length is defined though one may be derived The parent name must be short enough so that the path of a file in the directory would be valid Strictly the minimum file name length is 1 character though some OSs may enforce larger values eleven on some Windows systems thereby decreasing the maximum parent name length ParentNameLenmax PathNameLenmax FileNameLenmin 1 The constants FS CFG MAX DEV DRV NAME LEN and FS CFG MAX DEV NAME LEN in fs cfg h set the maximum length of device driver names and device names as shown in Figure 2 4 The device name is between three and five characters longer than the device driver name since the unit number the integer between the colons of the devi
246. le for nC FS These may simply expedite evaluation of the file system suite or become part a primary method of access or gathering debug information in your final product COM4 PuTTY jun 0 jun jun jun 0 jun 0 jun 07 ate jun 07 54 uC LIB Manual pdf r r r jun 07 54 uC LIB Re cp uC LIB Manual pdf copy f uC LIB Manual pdf jun 0 jun Figure F 1 HC FS shell command usage 509 Appendix F F 1 FILES AND DIRECTORIES HC FS with the shell commands and uC Shell is organized into the directory structure shown in Figure F 2 The files constituting the shell commands ares outlined in this section the generic file system files outlined in Chapter 3 uC FS Directories and Files on page 29 are also required Micrium B Software CD uc cPu CD uc crc a uc Fs a O APP amp O BSP E DD cra amp cmd CFG Template a O Dev Doc 1 O Examples FAT Gos Source UC LIB S uc Shell 5 cre Template Source Figure F 2 Directory structure Micrium Software uC FS Cmd fs_shell contain the shell commands for nC FS Micrium Software uC FS Cmd Template Cfg fs shell ecfg h is the template configuration file for the uC FS shell commands This file should be copied to your application directory and modified Micrium Software uC Shell This directory contains pC Shell which is used to process the commands See the pC Shell user manual for more information
247. le names A file with an LFN also has a SFN this is derived from the LFN The last block of an LFN stores the SFN that corresponds to the LFN The two or more preceding blocks each store parts of the LFN Figure 10 4 shows four blocks B The first block shows the names for the fields in an LEN entry the actual LFN entry is shown in the next three blocks E The middle two blocks show how FAT stores the LFN for a file named abcdefghijklm op in two 32 byte FAT table entries 124 Organization of the File Allocation Table The final block shows how FAT stores the SFN derived from the LFN In this case the SEN is abcdef 1 op Note that the of an 8 3 filename is not actually stored The final 32 bytes for an LFN entry has the same fields as the 32 byte entry for in this example a file with a SFN of abcdef 1 op Accordingly it is able to store in addition to the file s SFN the properties creation date and time etc for file abedefghijklm op Together the three blocks make up one LEN directory entry in this case the LEN entry for file abcdefghijklm op A long file name is stored in either two or three 32 bit entries of a directory table If three entries are needed to store the long file name byte 0 of the entries carry order numbers of 0x43 0x02 and 0x01 respectively Byte 0 is labelled Ord in Figure 10 4 None of these are valid characters which allows backward compatibility
248. lect the values that give the best performance For an efficient cache usage it is better to do not allocate space in the cache for sectors of type file when the write size is greater than sector size When the cache is used in write back mode all cache dirty sectors will be updated on the media storage only when the cache is flushed 5 8 2 OTHER CACHING AND BUFFERING MECHANISMS Volume cache is just one of several important caching mechanisms which should be balanced for optimal performance within the bounds of platform resources The second important software mechanism is the file buffer see section 6 1 3 Configuring a File Buffer on page 87 which makes file accesses more efficient by buffering data so a full sector s worth will be read or written Individual devices or drivers may also integrate a cache Standard hard drives overcome long seek times by buffering extra data upon read in anticipation of future requests or clumping writes to eliminate unnecessary movement The latter action can be particularly powerful but since it may involve re ordering the sequence of sector writes will eliminate any guarantee of fail safety of most file systems For that reason write cache in most storage devices should be disabled A driver may implement a buffer to reduce apparent write latency Before a write can occur to a flash medium the driver must find a free erased area of a block occasionally a block will need to be erased to
249. led from Code enabled by fs vol c Application Get the number of open volumes ARGUMENTS None RETURNED VALUE Number of volumes currently open NOTES WARNINGS None N A 341 Appendix A A 7 5 FSVol_GetVolCntMax FS OTY FSVol_GetVolCntMax void File Called from Code enabled by fs vol c Application N A Get the maximum possible number of open volumes ARGUMENTS None RETURNED VALUE The maximum number of open volumes NOTES WARNINGS None 342 A 7 6 FSVol_GetVolIName void FSVol GetVolName FS OTY vol nbr CPU CHAR name vol File Called from Code enabled by fs vol c Application N A Get name of the nth open volume vol nbr should be between 0 and the return value of FSVol GetNbrVols inclusive ARGUMENTS vol nbr Volume number name vol String buffer that will receive the volume name see Note 2 RETURNED VALUE None NOTES WARNINGS E name vol MUST point to a character array of FS CFG MAX VOL NAME LEN characters B If the volume does not exist name vol will receive an empty string 343 Appendix A A 7 7 FSVol IsDfit CPU BOOLEAN FSVol IsDflt CPU CHAR name vol File Called from Code enabled by fs vol c Application N A Determine whether a volume is the default volume ARGUMENTS name vol Volume name RETURNED VALUE DEF YES if the volume with name name_vol is the default volume DEF_NO if no volume
250. led from Code enabled by fs_api c Application Test EOF indicator on a file ARGUMENTS p file Pointer to a file RETURNED VALUE 0 if EOF indicator is NOT set or if an error occurred Non zero value if EOF indicator is set NOTES WARNINGS FS_CFG APL EN B The return value from this function should ALWAYS be tested against 0 rtn fs feof p file if rtn 0 EOF indicator is NOT set else EOF indicator is set h B If the end of file indicator is set Oe fs_feof returns DEF YES fs clearerr can be used to clear that indicator 240 A 2 8 fs_ferror int fs ferror FS FILE p file File Called from Code enabled by fs_api c Application FS_CFG_API_EN Test error indicator on a file ARGUMENTS p file Pointer to a file RETURNED VALUE 0 if error indicator is NOT set or if an error occurred Non zero value if error indicator is set NOTES WARNINGS B The return value from this function should ALWAYS be tested against 0 rtn fs ferror p file if rtn 0 Error indicator is NOT set else Error indicator is set B If the error indicator is set ie fs ferror returns a non zero value fs_clearerr can be used to clear that indicator 241 Appendix A A 2 9 fs_fflush int fs fflush FS FILE p file File Called from Code enabled by fs_api c Application FS_CFG_API_EN and FS_CF_FILE_BUF_EN Flush buffer
251. led from p dev p buf p err Code enabled by fs dev A C various N A The device driver IO_Ctr1 function performs an I O control operation Buffer in which data will be stored as a result of operation ARGUMENTS D dev Pointer to device to query p_buf Buffer which holds data to be used for operations OR p_err Pointer to variable that will receive the return error code from this function FS_ERR NONE FS ERR DEV INVALID IO CTRL FS ERR DEV INVALID UNIT NBR FS ERR DEV IO FS ERR DEV NOT OPEN FS ERR DEV NOT PRESENT FS ERR DEV TIMEOUT RETURNED VALUE None 424 Control operation performed successfully I O control operation unknown to driver Device unit number is invalid Device I O error Device is not open Device is not present Device timeout NOTES WARNINGS 1 C 5 SD MMC CARDMODE BSP Tracking whether a device is open is not necessary because this should ONLY be called when a device is open Defined I O control operations are a FS DEV IO CTRL REFRESH b FS DEV IO CTRL LOW FMT c FS DEV IO CTRL LOW MOUNT d FS DEV IO CTRL LOW UNMOUNT e FS DEV IO CTRL LOW COMPACT f FS DEV IO CTRL LOW DEFRAH g FS DEV IO CTRL SEC RELEASE h FS DEV IO CTRL PHY RD i FS DEV IO CTRL PHY WR j FS DEV IO CTRL PHY RD PAGE k FS DEV IO CTRL PHY WR PAGE 1 FS DEV IO CTRL PHY ERASE BLK m FS DEV IO CIRL PHY ERASE CHIP Refresh device Low level format device Low level moun
252. liability and security as explained here as well Chapter 9 Device Drivers All hardware accesses are eventually performed by a device driver This chapter describes the drivers available with uC FS and broadly profiles supported media types in terms of cost performance and complexity 19 Chapter 7 Chapter 11 RAM Disk Driver This chapter demonstrates the use of the simplest storage medium the RAM disk Chapter 12 SD MMC Drivers SD and MMC cards are flash based removable storage devices commonly used in consumer electronics For embedded CPUs a SD MMC card is an appealing medium because of its simple and widely supported physical interfaces one choice is SPD This chapter describes the interface and function of these devices Chapter 13 NAND Flash Driver NAND flash is the first category of flash media Write speeds are fast compared to NOR flash at the expense of slower read speeds and complexities such as bit errors and page program limitations This chapter describes the functions of these devices and the architecture of the supporting driver Chapter 14 NOR Flash Driver NOR flash is the second category of flash media They suffer slow write speeds balanced with blazingly fast read speeds Importantly they are not plagued by the complications of NAND flash which simplifies interfacing with them This chapter describes the function of these devices and the architecture of the supporting drive
253. ll be removed E If path old specifies a directory path_new must NOT specify a file 263 Appendix A if path_new is a directory path_new MUST be empty if so it will be removed B The root directory may NOT be renamed EXAMPLE void App Fnct void int err See Note 1 err fs rename sd 0 data file001 txt Rename file sd 0 data old file001 txt if err 0 APP_TRACE INFO Could not rename file L4 6 1 For this example file rename to succeed the following must be true when the function is called EThe file sd 0 data file001 txt must exist The directory sd 0 data old must exist BI sd 0 data old file001 txt exists it must not be read only If sd 0 data old file001 txt exists and is not read only it will be removed and sd 0 data file001 txt will be renamed 264 A 2 29 fs_rewind void fs rewind FS FILE p file File Called from Code enabled by fs api c Application FS CFG API EN Reset file position indicator of a file ARGUMENTS p file Pointer to a file RETURNED VALUE None NOTES WARNINGS E fs rewind is equivalent to void fs fseek p file 0 FS SEEK SET except that it also clears the error indictor of the file 265 Appendix A A 2 30 fs_rmdir int fs rmdir const char name full File Called from Code enabled by fs api c Application Delete a directory ARGUMENTS name full Name
254. ll new must NOT specify a directory if excl is DEF MO and name full new is a file it will be removed If name full old specifies a directory name full new must NOT specify a file if excl is DEF NO and name full new is a directory name full new MUST be empty if so it will be removed If excl is DEF NO name full new must not exist The root directory may NOT be renamed A 5 7 FSEntry_TimeSet void FSEntry TimeSet CPU CHAR name full FS DATE TIME p time CPU_INTO8U flag FS_ERR p err File Called from Code enabled by fs_entry c Application not FS_CFG_RD_ONLY_EN Set a file or directory s date time ARGUMENTS name full Paths on page 62 p time Pointer to date time flag FS DATE TIME CREATE FS DATE TIME MODIFY FS DATE TIME ACCESS FS DATE TIME ALL p_err FS ERR NONE FS ERR NAME NULL FS ERR FILE INVALID DATE TIME FS ERR NAME INVALID FS ERR NAME PATH TOO LONG FS ERR VOL NOT OPEN FS ERR VOL NOT MOUNTED FS ERR BUF NONE AVAIL FS ERR DEV Name of the entry See section 4 3 uC FS File and Directory Names and Flag to indicate which Date Time should be set Entry Created Date Time will be set Entry Modified Date Time will be set Entry Accessed Date will be set All the above will be set Pointer to variable that will the receive return error code from this function Entry date time set successfully Argument name full or p time passed a NULL pointer Date time spe
255. lose journal on volume ARGUMENTS name vol Volume name p err Pointer to variable that will the receive return error code from this function FS ERR NONE Journal closed FS ERR DEV Device access error RETURNED VALUE None NOTES WARNINGS None 388 A 12 3 FS_FAT_JournalStart void FS FAT JournalStart CPU CHAR name vol FS ERR p err File Called from Code enabled by fs fat journal c Application FS CFG FAT JOURNAL EN Start journaling on volume ARGUMENTS name vol Volume name p err Pointer to variable that will the receive return error code from this function FS ERR NONE Journaling started FS ERR DEV Device access error RETURNED VALUE None NOTES WARNINGS None 389 Appendix A A 12 4 FS FAT JournalStop void FS FAT JournalStop CPU CHAR name vol FS ERR p err File Called from Code enabled by fs fat journal c Application FS CFG FAT JOURNAL EN Stop journaling on volume ARGUMENTS name vol Volume name p err Pointer to variable that will the receive return error code from this function FS ERR NONE Journaling stopped FS ERR DEV Device access error RETURNED VALUE None NOTES WARNINGS None 390 A 12 5 FS FAT VolChk File Called from Code enabled by fs fat c Application Check the file system on a volume ARGUMENTS name vol Volume name FS _CFG FAT VOL CHK EN p_err Pointer to variable that will the receive re
256. ly supports FAT file systems fs_fat contains the file system driver which should be used for FAT12 FAT16 FAT32 disks with or without Long File Name LFN support 2 1 6 DEVICE DRIVER LAYER The device driver layer understands about types of file system media SD MMC card NOR flash etc In order for the device drivers to be independent of your CPU we use additional files to encapsulate such details as the access of registers reading and writing to a data bus and setting clock rates Each device driver is named according to the pattern fs dev lt dev drv name gt c where lt dev drv name gt is the an identifier for the device driver For example the driver for SD MMC cards using SPI mode is called fs dev sd spi c Most device drivers require a BSP layer with code for accessing registers reading from or writing to a data bus etc This file is named according to the pattern fs dev lt dev drv name gt bsp c For example fs dev sd spi bsp c contains the BSP functions for the driver SD MMC cards using SPI mode 27 Chapter 2 2 1 7 pC CPU uC FS can work with either an 8 16 32 or even 64 bit CPU but needs to have information about the CPU you are using The uC CPU layer defines such things as the C data type corresponding to 16 bit and 32 bit variables whether the CPU is little or big endian and how interrupts are disabled and enabled on the CPU etc CPU specific files are found in the uC CPU directory and in order t
257. m necessary BufCnt can be calculated from the number of volumes BufCnt gt VolCnt 2 If FSEntry Copy or FSEntry Rename is used then up to one additional buffer for each volume may be necessary DevDrvCnt Maximum number of device drivers that can be added It MUST be greater than or equal to 1 MaxSecSize Maximum sector size in octets It must be 512 1024 2048 or 4096 No device with a sector size larger than MaxSecSize can be opened NOTES None 483 Appendix D D 2 FS_DEV_INFO typedef struct fs dev info FS STATE State FS SEC OTY Size FS SEC SIZE SecSize CPU_BOOLEAN Fixed FS_DEV_INFO File Used for fs_dev h Second argument of FSDev_Query Receives information about a device MEMBERS State Size SecSize Fixed NOTES None 484 The device state FS DEV STATE CLOSED FS DEV STATE CLOSING FS DEV STATE OPENING FS DEV STATE OPEN FS DEV STATE PRESENT FS DEV STATE LOW FMT VALID Device is closed Device is closing Device is opening Device is open but not present Device is present but not low level formatted Device low level format is valid The number of sectors on the device The size of each device sector Indicates whether the device is fixed or removable D 3 FS DEV NOR CFG typedef struct fs dev nor cfg CPU _ADDR AddrBase CPU_INTO8U RegionNbr CPU_ADDR AddrStart CPU_INT32U DevSize FS SEC SIZE SecSize CPU_INTO8U Pct
258. make room for the next write Incoming data can be buffered while the long erase occurs in the background thereby uncoupling the application s wait time from the real maximum flash write time The ideal system might use both volume cache and file buffers A volume cache is most powerful when confined to the sector types most subject to repeated reads management and directory Caching of files if enabled should be limited to important often read files File buffers are more flexible since they cater to the many applications that find small reads and writes more convenient than those of full sectors 82 Chapter Files An application stores information in a file system by creating a file or appending new information to an existing file At a later time this information may be retrieved by reading the file Other functions support these capabilities for example the application can move to a specified location in the file or query the file system to get information about the file These functions which operate on file structures FS_FILEs are grouped under file access or simply file functions The available file functions are listed in Table 6 1 A separate set of file operations or entry functions manage the files and directories available on the system Using these functions the application can copy create delete and rename files and get and set a file or directory s attributes and date time The available entry functions a
259. mber of ports The simplest ones common to all installations interface with the application OS kernel Gf any and CPU More complicated may be ports to media drivers which require additional testing validation and optimization but many of those are still straightforward Figure C 1 diagrams the relationship between HC FS and external modules and hardware The sections in this chapter describe each require function and give hints for implementers Anyone creating a new port should first check the example ports are included in the pC FS distribution in the following directory Micrium Software uC FS Examples BSP Dev The port being contemplated may already exist failing that some similar CPU device may have already be supported 401 Appendix C FC 1 1 FC 1 2 FC 1 3 FC 1 4 FC 1 5 402 1 i Cik HC FS 2 gt CPU Platform Independent 3 3 i RTOS y HC FS Drivers 4 SD MMC NAND NOR Driver Driver Driver 9 5 7 Ke 6 8 11 y y y SD MMC NAND NOR Host Device Device Controller Figure C 1 HC FS ports architecture HC CIk act as a centralized clock management module If you use an external real time clock you will have to write functions to let uC FS know the date and time The CPU port within uC CPU adapts the file system suite to the CPU and compiler characteristics The fixed w
260. me of the directory See section 4 3 uC FS File and Directory Names and Paths on page 62 p err Pointer to variable that will the receive return error code from this function FS ERR NONE Directory opened FS ERR NAME NULL Argument name full passed a NULL pointer FS ERR DIR DIS Directory module disabled FS ERR DIR NONE AVAIL No directory available FS ERR DEV Device access error FS ERR NAME INVALID Entry name specified invalid or volume could not be found FS ERR NAME PATH TOO LONG Entry name is too long FS ERR VOL NOT OPEN Volume not opened FS ERR VOL NOT MOUNTED Volume not mounted FS ERR BUF NONE AVAIL Buffer not available Or entry error see section B 8 Entry Error Codes on page 395 RETURNED VALUE Pointer to a directory if NO errors Pointer to NULL otherwise NOTES WARNINGS None 295 Appendix A A 4 4 FSDir Rail void FSDir Rd FS DIR p dir FS DIR ENTRY p dir entry FS_ERR p err File Called from Code enabled by fs dir c Application FS CFG DIR EN fs readdir r Read a directory entry from a directory See fs readdir r for more information ARGUMENTS p dir Pointer to a directory p dir entry Pointer to variable that will receive directory entry information p err Pointer to variable that will the receive return error code from this function FS ERR NONE Directory read successfully FS ERR NULL PTR Argument p dir p dir entry passed a NULL pointer FS ERR INVALID TYPE
261. munication may need to be configured including a Transfer unit length b Shift direction c Clock frequency d Clock polarity and phase CPOL and CPHA e Slave select polarity 457 Appendix C 458 For a SD MMC card the following settings should be used a Transfer unit length 8 bits b Shift direction MSB first c Clock frequency 400 kHz initially d Clock polarity and phase CPOL and CPHA CPOL 0 CPHA 0 e Slave select polarity active low The slave select SSEL or CS MUST be configured as a GPIO output it should not be controlled by the CPU s SPI peripheral The SPI ports ChipSelEn and ChipSelDis functions manually enable and disable the SSEL C 7 2 Close void FSDev_BSP_SPI Close FS OTY unit nbr File Called from Code enabled by fs_dev_ lt dev_name gt _bsp c Device driver N A Close uninitialize hardware for SPI ARGUMENTS unit_nbr Unit number of device RETURNED VALUE None NOTES WARNINGS This function will be called every time the device is closed 459 Appendix C C 7 3 Lock Unlock void FSDev BSP SPI Lock FS OTY unit nbr void FSDev BSP SPI Unlock FS OTY unit nbr File Called from Code enabled by fs dev lt dev name gt bsp c Device driver N A Acquire release SPI bus lock ARGUMENTS unit nbr Unit number of device RETURNED VALUE None NOTES WARNINGS Lock will be called before the driver begins to access the S
262. n be performed relative to a working directory When it is disabled DEF DISABLED all file system operations must be performed on absolute paths and the functions in the following table will not be available Function File fs chdir fs api c fs getcwd fs api c FS WorkingDirGet fs h FS WorkingDirset fs h Table E 6 Working directory function exclusion These functions are not included if FS_CFG_ WORKING DIR EN is DEF DISABLED 501 Appendix E FS_CFG_UTF8_EN FS CFG UIF8 EN selects whether file names may be specified in UTF 8 When enabled DEF ENABLED file names may be specified in UTF 8 when disabled DEF DISABLED file names must be specified in ASCII FS_CFG_CONCURRENT ENTRIES ACCESS EN FS CFG CONCURRENT ENTRIES ACCESS EN selects whether one file can be open multiple times Gin one or more task When enabled DEF_ENABLED files may be open concurrently multiple times and without protection When disabled DEF_DISABLED files may be open concurrently only in read only mode but may not be open concurrently in write mode This option makes the file system safer when disabled FS_CFG_ RD ONLY EN FS CFG RD ONLY EN selects whether write access to files volumes and devices will be possible When DEF_ENABLED files volumes and devices may only be read code for write operations will not be included and the functions in the following table will not be available
263. n other words this allows the ROM and RAM footprints of uC FS to be adjusted based on your requirements Most of the defines should be configured with the default configuration values This leaves about a dozen or so values that should be configured with values that may deviate from the default configuration 497 Appendix E E 1 FILE SYSTEM CONFIGURATION Core file system modules may be selectively disabled FS_CFG_ BUILD FS CFG BUILD selects the file system build Should always be set to FS BUILD FULL in this release FS_CFG_SYS_DRV_SEL FS CFG SYS DRV SEL selects which file system driver s will be included Currently there is only one option When FS SYS DRV SEL FAT the FAT system driver will be included FS_CFG_ CACHE EN FS CFG CACHE EN enables when set to DEF ENABLED or disables when set to DEF DISABLED code generation of volume cache functions Function File FSVol CacheAssign fs vol c FSVol CacheFlush fs vol c FSVol_CacheInvalidate fs_vol c Table E 1 Cache function exclusion These functions are not included if FS_CFG_CACHE_EN is DEF_DISABLED FS_CFG_BUF_ALIGN OCTETS FS CFG BUF ALIGN OCTETS configures the minimum alignment of the internal buffers in octets This should be set to the maximum alignment required by the any of the CPU system buses and if relevant the peripherals and DMA controller involved in the file system operations When no minimum alignment is required FS_CFG BUF ALIGN OCTE
264. nd WP pins held high logic low or inactive as shown in Table 14 5 As with any SPI device four signals are used to communicate with the host CS SI SCK and SO MCU MPU SERIAL NOR HHI Figure 14 4 Typical serial NOR connections 212 Using a Serial NOR Device 14 4 2 NOR SPI BSP OVERVIEW An NOR BSP is required so that a physical layer driver for a serial flash will work on a particular system For more information about these functions see section C 11 on page 480 Function Description FSDev_NOR_BSP_SPI_Open Open initialize SPI FSDev NOR BSP SPI Close Close uninitialize SPI FSDev NOR BSP SPI Lock Acquire SPI lock FSDev NOR BSP SPI Unlock Release SPI lock FSDev NOR BSP SPI Rd Read from SPI FSDev_ NOR BSP SPI Wr Write to SPI FSDev NOR BSP SPI ChipSelEn Enable chip select FSDev_ NOR BSP SPI ChipSelDis Disable chip select FSDev NOR BSP SPI SetClkFreg Set SPI clock frequency Table 14 5 NOR SPI BSP functions 213 Chapter 14 14 5 PHYSICAL LAYER DRIVERS The physical layer drivers distributed with the NOR driver see the table below support a wide variety of parallel and serial flash devices from major vendors Whenever possible advanced programming algorithms such as the common buffered programming commands are used to optimize performance Within the diversity of NOR flash some may be found which implement the basic command set but not the
265. nd computer scientists is the command line In an embedded system a UART is a port over which commands can be executed easily even for debug purposes A set of shell commands have been developed for pC FS that mirror the syntax of UNIX utilities as described in this chapter Appendix G Bibliography Appendix H uC FS Licensing Policy 21 Chapter 7 22 Chapter UC FS Architecture HC FS was written from the ground up to be modular and easy to adapt to different CPUs Central Processing Units RTOSs Real Time Operating Systems storage media and compilers Figure 2 1 shows a simplified block diagram of the different uC FS modules and their relationships Notice that all of the uC FS files start with fs_ This convention allows you to quickly identify which files belong to pC FS Also note that all functions and global variables start with FS and all macros and defines start with FS 23 Chapter 2 Your Application fs cfg h UC LIB lib def h lib_ascii lib_mem lib_str y UC FS POSIX API Layer fs_api FS Layer fs fs_dev fs_partition fs_buf fs_dir fe aus fs_cache fs_entry fs_type h fs_cfe_fs h fs_errh fs_unicode fs_ctrh fs_file fs_util fs_def h fs_inc h fs_vol File System Driver Layer UC CRC fs fat fs fat fatl2 _ fs fat sfn edc or fs fat dir fs fat fatl6 GG fat type h ecc _hamming Js fat entry
266. nd is the geometry information the device size the number of erase block regions and the size and number of blocks in each region For most flash these regions are contiguous and sequential the first at the beginning of the device the second just after Since this is not always true see section 14 5 3 209 Chapter 14 FSDev_NOR_SST39 on page 216 for an example the manufacturer s information should always be checked and for atypical devices the physical layer driver copied to the application directory and modified Command Set Identifier Description 0x0001 Intel 0x0002 AMD Spansion 0x0003 Intel 0x0102 SST Table 14 3 Common command sets 14 3 3 NOR BSP OVERVIEW A BSP is required so that a physical layer driver for a parallel flash will work on a particular system The functions shown in the table below must be implemented Pleaser refer to section C 10 NOR Flash BSP on page 473 for the details about implementing your own BSP Function Description FSDev_NOR_BSP_Open Open initialize bus for NOR FSDev NOR BSP Close Close uninitialize bus for NOR FSDev NOR BSP Rd XX Read from bus interface FSDev_ NOR BSP RdWord _XX Read word from bus interface FSDev_ NOR BSP Word XX Write word to bus interface FSDev NOR BSP WaitWhileBusy Wait while NOR is busy Table 14 4 NOR BSP functions The Open Close functions are called upon open close these calls are always matc
267. ndle very large storage media Microsoft requires a license to make or distribute implementations of exFAT Micrium does not offer exFAT in uC FS at this time 129 Chapter 10 130 Chapter 11 RAM Disk Driver The simplest device driver is the RAM disk driver which uses a block of memory internal or external as a storage medium 11 1 FILES AND DIRECTORIES The files inside the RAM disk driver directory are outlined in this section the generic file system files outlined in Chapter 3 uC FS Directories and Files on page 29 are also required Micrium Software uC FS Dev This directory contains device specific files Micrium Software uC FS Dev RAMDisk This directory contains the RAM disk driver files fs dev ramdisk constitute the RAM disk device driver 131 Chapter 11 11 2 USING THE RAM DISK DRIVER To use the RAM disk driver two files in addition to the generic FS files must be included in the build E fs dev ramdisk c E fs dev ramdisk h The file fs dev ramdisk h must also be included in any application or header files that directly reference the driver for example by registering the device driver The following directory must be on the project include path B Micrium Software uC FS Dev RAMDisk A single RAM disk is opened as shown in The file system initialization FS Init function must have previously been called ROM RAM characteristics and performance benchmarks of the RAM d
268. nee naaa aeaea paaie Eaa aeaea eda Aaaa iaa aidad inn 357 FSVol_Cachelnvalidate cccccceeseesseeseeeceeeeeeeeeseeeeessaneeeeeeeeeeees 359 FSVol CacheFlush ccccccesseccceeessseeceeesseeeeeesesseaeeeeeeseaaeeeeenseaeeeeeneeaas 360 SD MMC Driver Functions keen 361 FSDev_SD xxx _QuernySD anne eere versneden ad en even rde en ewa 362 FSDev_SD 500ERAGID Y steden deden eenen citadel ennen 364 FSDev SD 0 RACSD eens verver ei d er den Sede CEEE RAEE ANAE 366 NAND Driver Functions REENEN EEN 368 FSDev_NAND LowFmt neee eenen EAEAN Aa NE EKEKA vennen 369 FSDev_NAND LowMount na eenen enneneneenenneeenenennneen 370 FSDev_NAND LowUnmount nennen eeneneereneenneneereensen 372 NOR Driver Functions nanne ennen neeneensenen enn ennnnannenneneeenven 373 FSDev_NOR LowFmt nnee eenneee RRE nenanem REENEN 374 FSDev_NOR LowMount nennen senen en enne nennenenenneeneeeeen 375 FSDev_NOR LowUnmount na eenen ennen NENNEN 376 FSDev_NOR LowGompact nne neen sene nenvenenenenn 377 FSDev_NOR LowDefrag nana anaeee REENEN NEEN 378 FSDev_NOR PhyRd annen nanie eieiei aN 379 FSDev NOR PHYWr vcore E benen al AOA EE LEERAREA 381 FSDev_NOR_PhyEraseBIK annen enn enneee eene enneeeneneenneen 383 FSDev_NOR PhyEraseChip an aaneen eee enneee REENEN 385 FAT System Driver Functions nnnnannansnnnnne neren ennnnnnnennenenenvenseenenn 386 FS FAT JournalOpen nn a aaan a aaaea alaaa aa aiana
269. needs to be low level formatted Device I O error Device timeout The device must be a NOR device e g nor 0 Compacting groups sectors containing high level data into as few blocks as possible If an image of a file system is to be formed for deployment to be burned into chips for production then it should be compacted after all files and directories are created 377 Appendix A A 11 5 FSDev NOR LowDefrag void FSDev NOR LowDefrag CPU CHAR name dev FS ERR p err File Called from Code enabled by fs dev nor c Application N A Low level defragment a NOR device ARGUMENTS name dev Device name see Note p err Pointer to variable that will the receive return error code from this function FS ERR NONE Device low level defragmented successfully FS ERR NAME NULL Argument name dev passed a NULL pointer FS ERR DEV INVALID Argument name dev specifies an invalid device FS ERR DEV NOT OPEN Device is not open FS ERR DEV NOT PRESENT Device is not present FS ERR DEV INVALID LOW FMT Device needs to be low level formatted FS ERR DEV IO Device I O error FS ERR DEV TIMEOUT Device timeout RETURNED VALUE None NOTES WARNINGS The device must be a NOR device e g nor 0 Defragmentation groups sectors containing high level data into as few blocks as possible in order of logical sector A defragmented file system should have near optimal access speeds in a read only environment 378
270. neeen 478 FSDev_NOR BSP_WaitWhileBusy annae nan enne nen RRE 479 NOR Flash SPI GE 480 UC FS Types and Structures REENEN EEN 481 EO CEE 482 FS DEV INFO gege REESEN AEN EEN eat standen nnie ease 484 FS DEV NOR CFG zin sredenern gare nine E 485 FS DEV RAM GENEE eege deed 488 FS_DIR_ENTRY Struct fs_dirent nennen nen venenenenn 489 FS ENTRY IN O etterende denna daneen iedereen nde denna el 490 FS FAT SYS CRG E 492 FS PARTITION ENTRY skonnert verende deel NASA 494 FS VOLINFO insite tea neds ie enden oden diene eee 495 Appendix E E 1 E 2 E 3 E 4 E 5 E 6 E 7 E 8 E 9 Appendix F F 1 F 2 F 3 F 3 1 F 3 2 F 3 3 F 3 4 F 3 5 F 3 6 F 3 7 F 3 8 F 3 9 F 3 10 F 3 11 F 3 12 F 3 13 F 3 14 F 3 15 F 3 16 F 3 17 F 4 HOFS Configuration nnn EnaA EEE EN E AA ONE ONAA AR ENEE E 497 File System Configuration nnnnn nan ananner en vennenervenennnerrenennnneneerennenen 498 Feature Inclusion Configuration nnn anneeerensennneerenenneenreenenneeen 500 Name Restriction Configuration nnnnnnnnsananerrenenneneeeenennnnersenennneen 503 Debug Configuration cccceceeecceeeeeseeeeeeeeeeeeeeeeeeseeeseeeeseeneeeeesneeeseeeneenes 504 Argument Checking Configuration anneer ensen neerennenneeerennenseneenn 504 File System Counter Configuration unanse nan onnenne ren ennneereerennenen 505 FAT GonfiguratlOf EE 505 SD MMC SPI Configuration nnn aannanseerennennenerennensenenensnnnene
271. next dir entry void fs readdir r pdir amp dirent amp p dirent fs closedir p dir Close dir If dir could not be opened else dir does not exist APP TRACE INFO Dir does not exist s r n p od path Listing 8 5 Directory listing output example 108 Entry Access Functions COM1 PuTTY Figure 8 2 Example directory listing The second argument fs_readdir_r is a pointer to a struct fs_dirent which has two members The first is Name which holds the name of the entry the second is Info which has file information For more information about the struct fs_dirent structure see section D 5 FS_DIR_ENTRY struct fs_dirent on page 489 8 5 ENTRY ACCESS FUNCTIONS The entry access functions provide an API for performing single operations on file system entries files and directories such as renaming or deleting a file Each of these operations is atomic consequently in the absence of device access errors either the operation will have completed or no change to the storage device will have been made upon function return A new directory can be created with s mkdir or an existing file or directory deleted or renamed with fs _remove or fs_rename 109 Chapter 8 110 Chapter Device Drivers The file system initializes controls reads and writes a device using a device driver A nC FS device driver has eight interface functions grouped into a FS
272. ng First some cards now integrate both USB and SD MMC connectivity for increased ease of access in both PCs and embedded devices The second are embedded MMC trademarked eMMC fixed flash based media addressed like MMC cards 135 Chapter 12 Card Size Pin Count Description MMCPlus 32 x 24x 1 4mm 13 MMCmobile 18 x 24x 1 4 mm 13 MMCmicro 14 x 12 x 1 1 mm 13 Most current MMC cards can operate with 1 4 or 8 data lines though legacy media were limited to a single data line The maximum clock frequency is 20 MHz providing for maximum theoretical transfer speeds of 20 MB s 80 MB s and 160 MB s for the three possible bus widths SD or SDHC 32 x 24x 1 4mm SDmini 21 5 x 20x 1 4 mm 11 SDmicro 15x 11x 1 0 mm SD cards can operate in cardmode with 1 or 4 data lines or in SPI mode The maximum clock frequency is 25 MHz providing for maximum theoretical transfer speeds of 25 MHz and 50 MHz for the two possible bus widths Table 12 1 SD MMC devices SD MMC cards can be used in two modes card mode also referred to as MMC mode and SD mode and SPI mode The former offers up to 8 data lines depending on the type of card the latter only one data line but the accessibility of a communication bus common on many MCUs MPUs Because these modes involve different command protocols they require different drivers 136 Files and Directo
273. ng Some of the functions replace stdlib functions provided by the compiler These are provided to ensure that they are fully portable from application to application and most importantly from compiler to compiler HC CIk is an independant clock calendar management module with source code for easily managing date and time in a product uC FS uses the date and time information from pC Clk to update files and directories with the proper creation modification access time HC CRC is a stand alone module for calculating checksums and error correction codes This module is used by some of uC FS device drivers This is the pC FS platform independent code free of dependencies on CPU and memory device This code is written in highly portable ANSI C code This code is only available to pC FS licensees This is the uC FS system driver for FAT file systems This code is only available to uC FS licensees 31 Chapter 3 F3 1 10 This is the collection of device drivers for uC FS Each driver supports a certain device type such as SD MMC cards NAND flash or NOR flash Drivers are only available to uC FS licensees F3 1 11 This is the pC FS code that is adapted to a specific platform It consists of small code modules written for specific drivers called ports that must be adapted to the memory device controllers or peripherals integrated into or attached to the CPU The requirements for these ports are described in Appendix C Porting Manual
274. ng the update block metadata cache will yield no performance benefit RAM usage lt Nbr update blks gt x log2 Nbr secs per blk gt log2 lt Subset size gt x lt Max associativity gt 8 octets The result should be rounded up FS_NAND CFG _RSVD_AVAIL_BLK_CNT This define indicates the number of blocks in the available blocks table that are reserved for metadata block folding Since this operation is critical and must be done before adding blocks to the available blocks table the driver needs enough reserved blocks to make sure at least one of them is not bad so that the metadata can be folded successfully When set to 3 probability of the metadata folding operation failing is almost null This value is sufficient for most applications FS_NAND CFG MAX RD RETRIES This define indicates the maximum number of retries performed when a read operation fails It is recommended by most manufacturers to retry reading a page if it fails as successive read operations might be successful This number should be at least set to 2 for smooth operation but might be set higher to improve reliability Please be aware that a high number of retries will reduce the response time of the system when it tries to read a defective sector FS_NAND CFG MAX SUB_PCT This define indicates the maximum allowed number of sequential update blocks SUB This value is set as a percentage of the total number of update blocks SUBs will improve the performance fo
275. nnenenennenneervenennenenennenneerenn 71 Raw Device IO aaa ae Te aa aa aa aeiae aa Aaa ae a dentereedtcneeuscaaecddueneas de 72 En EE 73 Volume Operations nnn enasssddenvennindaaresrseneersearandennae sne dendenven td dannnnd dan 76 Using Wel 77 Using Volume Cache sageis aeii aE aa ie E aa 79 Choosing Cache Parameters sssssusssseunsnnnnnnnnnnnunnnnnnnnnnnnnnnnnnnnnnnnnnnnn 81 Other Caching and Buffering Mechanisms asssssnssssssnnsnnrnnnsennnnnnnnnns 82 E E E E E AT 83 File Access F nctions assaraas orenverse soe EENS CERN oew vab aian 84 ss Ha IT 85 Getting Information About a File 0 ccccceesseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeseeeeeeees 86 Configuring a File Buffer nnnnnn un snnnnernenennnneerenensenenenennnneeren rennen 87 File Error el Tree EE 88 Atomic File Operations Using File LOCK ccceecccsesseneeeeeeseeeeeeeeeeeeees 88 Entry Access Functions ns esnane sr saanans en vanvenan se vedanan ee edsnansanvennannd denn 89 File and Directory Attributes annen anneennne neren ennenenennennennneen vereen 90 Creating New Files and Directories anansan en onnenenenennnneerenenneeen 91 Deleting Files and Directories cecccseseeeceeeeeeneeeeeeeeeeeeeeneeeeeeeeeeseees 92 Bt te aaneen indinteer se venddengedanke nand aedn send beden A 93 Directory Access Functions nn ananannanneenenenenenennennnnennenennnnennenenn 94 Chapter 8 8 1 8 2 8 3 8 3 1 8 3 2 8 3
276. nter to variable that will receive the return error code from this function FS ERR NONE Error and end of file indicators cleared FS ERR NULL PIR Argument p file passed a NULL pointer FS ERR INVALID TYPE Argument p file s type is invalid or unknown FS ERR FILE NOT OPEN File NOT open RETURNED VALUE None NOTES WARNINGS None 317 Appendix A A 6 5 FSFile ISEOF CPU BOOLEAN FSFile IsEOF FS FILE p file FS ERR p err File Called from Code enabled by fs file c Application N A fs feof Test EOF indicator on a file See fs_feof for more information ARGUMENTS p file Pointer to a file p err Pointer to variable that will receive the return error code from this function FS ERR NONE EOF indicator obtained FS ERR NULL PIR Argument p file passed a NULL pointer FS ERR INVALID TYPE Argument p file s type is invalid or unknown FS ERR FILE NOT OPEN File NOT open RETURNED VALUE DEF_NO if EOF indicator is NOT set or if an error occurred DEF_YES if EOF indicator is set NOTES WARNINGS None 318 A 6 6 FSFile_IsErr CPU BOOLEAN FSFile IsErr FS FILE p file FS ERR p err File Called from Code enabled by fs file c Application N A fs ferr Test error indicator on a file See fs ferror for more information ARGUMENTS p file Pointer to a file p err Pointer to variable that will receive the return error code from this function FS ERR NONE Error indicator obt
277. nter to variable that will the receive return error code from this function FS ERR NONE Entry attributes set successfully FS ERR NAME NULL Argument name full passed a NULL pointer FS ERR NAME INVALID Entry name specified invalid OR volume could not be found FS ERR NAME PATH TOO LONG Entry name specified too long FS ERR VOL NOT OPEN Volume was not open FS ERR VOL NOT MOUNTED Volume was not mounted FS ERR BUF NONE AVAIL Buffer not available FS ERR DEV Device access error Or entry error See section B 8 Entry Error Codes on page 395 RETURNED VALUE None 298 NOTES WARNINGS If the entry does not exist an error is returned Three attributes may be modified by this function FS_ENTRY_ATTRIB_RD Entry is readable FS_ENTRY ATTRIB WR Entry is writable FS ENTRY ATTRIB HIDDEN Entry is hidden from user level processes An attribute will be cleared if its flag is not OR d into attrib An attribute will be set if its flag is OR d into attrib If another flag besides these are set then an error will be returned The attributes of the root directory may NOT be set 299 Appendix A A 5 2 FSEntry_Copy void FSEntry Copy CPU_CHAR name full src CPU CHAR name full dest CPU BOOLEAN excl FS ERR p err File Called from Code enabled by fs entry c Application not FS CG RD ONLY EN Copy a file ARGUMENTS name full src name full dest excl p err 300 Name of the source file
278. nterface functions to perform low level operations see section A 12 FAT System Driver Functions on page 386 204 CPU_BOOLEAN App FS AddNOR void FS_DEV_NOR CFG FS_ERR FS_DevDrvAdd FS_DEV_API FS_ERR if err FS ERR NONE return DEF FAIL nor cfg err nor cfg AddrBase nor cfg RegionNbr nor cfg AddrStart nor_cfg DevSize nor_cfg SecSize nor_cfg PctRsvd nor_cfg PctRsvdSecActive nor_cfg EraseCntDiffTh nor_cfg PhyPtr nor_cfg BusWidth nor_cfg BusWidthMax nor_cfg PhyDevCnt nor_cfg MaxClkFreq amp FSDev Nor amp err amp amp err FS ERR DEV DRV ALREADY ADDED Using a Parallel NOR Device Pe N xy APP CFG FS_NO APP CFG ES MO 2 R_ADDR_BASE R_REGION_NBR APP CFG ES MO APP CFG FS_NO APP CFG ES MO APP CFG FS_NO APP CFG FS_NO R_ADDR_START R DEV SIZE R SEC SIZE R_PCT_RSVD R_PCT_RSVD_SEC_ACTIVE APP CFG FS MO R_ERASE CNT DIFF TH FS_DEV_NOR PHY API APP CFG FS NOR PHY PIR APP CFG FS_NO APP CFG FS_NO R_BUS WIDTH R_BUS WIDTH MAX APP CFG FS NO R_PHY DEV CNT APP CFG FS NO R MAX CLK FREQ FSDev Open CPU CHAR nor 0 void FS_ERR switch err case FS ERR NONE APP_TRACE_DBG amp nor cfg EEEN ERS zj ifs ay 7 ye b opened device r n Low fmt invalid opened device not low level formatted r n amp err break case FS ERR DEV INVAL
279. ntry Rename Rename a file or directory FSEntry TimeSet Set a file or directory s date time Table 6 3 Entry API functions 89 Chapter 6 6 2 1 FILE AND DIRECTORY ATTRIBUTES The FSEntry Query function gets information about file system entry including its attributes which indicate whether it is or hidden FS_FLAGS attrib FS ENTRY INFO info FSEntry Query path name amp info amp err attrib info Attrib a file or directory writable or read only and visible pointer to full path name pointer to info return error The return value is a logical OR of attribute flags FS ENTRY ATTRIB RD FS ENTRY ATTRIB WR FS ENTRY ATTRIB HIDDEN FS ENTRY ATTRIB DIR FS ENTRY ATTRIB ROOT DIR Entry is readable Entry is writable Entry is hidden from user level processes Entry is a directory Entry is a root directory If no error is returned and FS ENTRY ATTRIB DIR is not set then the entry is a file An entry can be made read only or writable or hidden or visible by setting its attributes 90 Entry Access Functions The second argument should be the logical OR of relevant attribute flags attrib FS_ENTRY_ATTRIB_RD FSEntry AttribSet path name lt pointer to full path name attrib lt attributes amp err lt return error FS_ENTRY ATTRIB RD Entry is readable FS_ENTRY ATTRIB WR Entry is writable FS_ENTRY ATTRIB HIDDEN Entry is hidden from user level proce
280. o adapt uC FS to a different CPU you would need to either modify the cpu files or create new ones based on the ones supplied in the uC CPU directory In general it s much easier to modify existing files because you have a better chance of not forgetting anything 2 1 8 RTOS LAYER HC FS does not require an RTOS However if C FS is used with an RTOS a set of functions must be implemented to prevent simultaneous access of devices and core uC FS structures by multiple tasks uC FS is provided with a no RTOS which contains just empty functions a HC OS II and a HC OS III interface If you use a different RTOS you can use the fs_os for pC OS II as a template to interface to the RTOS of your choice 28 Chapter UC FS Directories and Files HC FS is fairly easy to use once you understand which source files are needed to make up a HC FS based application This chapter will discuss the modules available for uC FS and how everything fits together Figure 3 1 shows the uC FS architecture and its relationship with the hardware Memory devices may include actual media both removable SD MMC CF cards and fixed NAND flash NOR flash as well as any controllers for such devices Of course your hardware would most likely contain other devices such as UARTs Universal Asynchronous Receiver Transmitters ADCs Analog to Digital Converters and Ethernet controller s Moreover your application may include other middleware components like
281. o attempt has been made however to accommodate non storage devices that are accessed on a SD MMC cardmode including SDIO devices The core operation being abstracted is the command response sequence for high level card transactions The key functions CmdStart CmdWaitEnd CmdDataRd and CmdDataWr are called within the state machine of Figure C 2 If return error from one of the functions will abort the state machine so the requisite considerations such as preparing for the next command or preventing further interrupts must be handled if an operation cannot be completed Error returned Start command execution FSDev_SD Card_BSP_CmdStart Error Wait for command to execute and returned response to be returned FSDev SD Card BSP _CmdWaitEnd FSDev SD Card BSP _CmdDataRd FSDev SD Card _BSP_CmdDataWr Figure C 2 Command execution The remaining functions either investigate host capabilities GetBlkCntMax GetBusWidthMax or set operational parameters SetBusWidth SetClkFreq SetTimeoutData SetTimeoutResp Together these function sets help configure a new card upon insertion Note that the parameters configured by the set functions belong to the card not the slot if multiple cards may be multiplexed in a single slot these must be saved when set and restored whenever Lock is called 427 Appendix C Two elements of host behavior routinely influence implementation and require design
282. ockfile fs clearerr clearerr fs funlockfile funlockfile fs closedir closedir fs fwrite fwrite fs ctime r ctime_r fs_getcwd getcwd fs_fclose fclose fs localtime r localtime r fs feof feof fs mkdir mkdir 96 Working Directory Functions Function POSIX Equivalent Function POSIX Equivalent fs ferror ferror fs_mktime mktime fs fflush fflush fs rewind rewind fs_fgetpos fgetpos fs_opendir opendir fs flockfile flockfile fs readdir r readdir r fs fopen fopen s_remove remove fs_fread fread fs _rename rename fs fseek fseek fs_rmdir rmdir fs_fsetpos fsetpos fs_setbuf setbuf fs fstat fstat fs_setvbuf setvbuf fs ftell ftell fs_stat stat 8 2 WORKING DIRECTORY FUNCTIONS Table 8 1 POSIX API functions Normally all file or directory paths must be absolute either on the default volume or on an explicitly specified volume p filel fs _fopen file txt Zei p file2 fs_fopen sdcard 0 file txt r File on default volume File on explicitly specified volume If working directory functionality is enabled paths may be specified relative to the working directory of the current task p file2 fs fopen file txt r p_filel fs fopen file txt r File in working directory
283. of the file RETURNED VALUE 0 if the directory is removed 1 if the directory is NOT removed NOTES WARNINGS FS CFG API EN and not FS CFG RD ONLY EN A directory can be removed only if it is an empty directory B The root directory cannot be removed EXAMPLE void App Fnct void int err err fs rmdir sd 0 data old Remove dir if err 0 APP_TRACE_INFO Could not remove dir 266 G A 2 31 fs_setbuf int fs setbuf FS FILE p file char p buf File Called from Code enabled by fs api c Application FS CFG API EN and FS _CFG FILE PUE EN Assign buffer to a file ARGUMENTS p file Pointer to a file p buf Pointer to a buffer of FS_BUFSIZ bytes RETURNED VALUE 1 if an error occurs 0 if no error occurs NOTES WARNINGS fs setbuf is equivalent to fs_setvbuf invoked with FS _IOFBF for mode and FS_BUFSIZE for size 267 Appendix A A 2 32 fs_setvbuf int fs setvbuf FS FILE p file char p buf int mode fs size t size File Called from Code enabled by fs api c Application Assign buffer to a file ARGUMENTS p file Pointer to a file p_buf Pointer to buffer mode Buffer mode FS _IONBR FS __IOFBF size RETURNED VALUE 1 if an error occurs 0 if no error occurs 268 FS_CFG API EN and FS _CFG FILE PUE EN Unbuffered Fully buffered Size of buffer in octets NOTES WARNINGS E fs_s
284. ogram The boot loader of course would need to be able to load the application but since that requires only read only access no imposing program is required The ROM boot loaders in some CPUs can check the root directory of a SD card for a binary in addition to the more usual locations such as external NAND or NOR flash 1 3 WHY FAT File Allocation Table FAT is a simple file system widely supported across major OSs While it has been supplanted as the format of hard drives in Windows PCs removable media still use FAT because of its wide support That is suitable for embedded systems which would often be challenged to muster the resources for the modern file systems developed principally for large fixed disks HC FS supports FAT because of the interoperability requirements of removable media allowing that a storage medium be removed from an embedded device and connected to a PC All variants and extensions are supported to specification 17 Chapter 7 A notorious weakness of FAT exacerbated by early Windows system drivers is its non fail safe architecture Certain operations leave the file system in an inconsistent state albeit briefly which may corrupt the disk or force a disk check upon unexpected power failure HC FS minimizes the problem by ordering modifications wisely The problem is completely solved in an optional journaling module which logs information about pending changes so those can be resumed on start up after a po
285. oid FSFile LockSet FS FILE ap file FS ERR p err POSIX API Equivalent void fs flockfile ES FILE file int fs ftrylockfile FS FILE file void fs funlockfile FS FILE file For more information about and an example of using file locking see section 8 3 5 Atomic File Operations Using File Lock on page 106 88 Entry Access Functions 6 2 ENTRY ACCESS FUNCTIONS The entry access functions provide an API for performing single operations on file system entries files and directories such as copying renaming or deleting Each of these operations is atomic consequently in the absence of device access errors either the operation will have completed or no change to the storage device will have been made upon function return One of these functions FSEntry_Query obtains information about an entry including the attributes date time stamp and file size Two functions set entry properties FSEntry AttribSet and FSEntry TimeSet which set a file s attributes and date time stamp A new file entry can be created with FSEntry Create or an existing entry deleted copied or renamed with FSEntry Del FSEntry Copy or FSEntry Rename Function Description FSEntry AttribSet Set a file or directory s attributes FSEntry_Copy Copy a file FSEntry_Create Create a file or directory FSEntry Del Delete a file or directory FSEntry Ouere Get information about a file or directory FSE
286. om This driver has been tested with or should work with the devices in the table below The M25P series devices are programmed on a page 256 byte basis and erased on a sector 32 or 64 KB basis The M25PE series devices are also programmed on a page 256 byte basis but are erased on a page subsector 4 KB or sector 64 KB basis Manufacturer Device Capacity Block Size Block Count ST M25P10 1 Mb 64 KB 2 ST M25P20 2 Mb 64 KB 4 ST M25P40 4 Mb 64 KB 8 ST M25P80 8 Mb 64 KB 16 ST M25P16 16 Mb 64 KB 32 ST M25P32 32 Mb 64 KB 64 ST M25P64 64 Mb 64 KB 128 ST M25P128 128 Mb 64 KB 256 ST M25PE10 1 Mb 64 KB 2 ST M25PE20 2 Mb 64 KB 4 ST M25PE40 4 Mb 64 KB 8 ST M25PE80 8 Mb 64 KB 16 ST M25PE16 16 Mb 64 KB 32 Table 14 7 Supported M25 serial flash 216 14 5 5 FSDEV NOR SST25 Physical Layer Drivers FSDev NOR SST25 supports SST s SST25 serial flash memories as described in various datasheets at Numonyx http www numonyx com This driver has been tested with or should work with the devices in the table below The M25P series devices are programmed on a word 2 byte basis and erased on a sector 4 KB or block 32 KB basis The revision A devices and revision B devices differ slightly Both have an Auto Address Increment AAI programming mode In revision A devices the programming is performed byte by byte in revision B devices word by word Revision B devices can also be erase
287. on an ASCII formatted integer the unit number and another colon Since the SD MMC SPI driver requires no configuration the configuration structure 1b should be passed a NULL pointer Since SD MMC are often removable media it is possible for the device to not be present when FSDev_Open is called The device will still be added to the file system and a volume opened on the not yet present device When the volume is later accessed the file system will attempt to refresh the device information and detect a file system see section 5 2 Using Devices on page 69 for more information FSVol_Open opens mounts a volume The parameters are the volume name 2a the device name 2b and the partition that will be opened 2c There is no restriction on the volume name 2a however it is typical to give the volume the same name as the underlying device If the default partition is to be opened or if the device is not partition then the partition number 2c should be zero If the SD MMC initialization succeeds the file system will produce the trace output as shown in Figure 12 10 Gf a sufficiently high trace level is configured See section E 9 Trace Configuration on page 507 about configuring the trace level 152 Figure 12 10 SD MMC detection trace output Using the SD MMC SPI Driver 12 3 1 SD MMC SPI COMMUNICATION SPI is a simple protocol supported by peripherals commonly built in on CPUs Moreover since the
288. on because its entry is in the MBR The four circles in the MBR represent the four partition entries the one that is now used points to Primary Partition 1 M B Beie 4 Unallocated space ol _ 256 MB SEM O O Figure 5 5 Device after partition initialization More partitions can now be created on the device Since the MBR has four partition entries three more can be made without using extended partitions as discussed below The function FSDev_PartitionAddO should be called three times FSDev PartitionAdd CPU CHAR ide 0 lt a device name FS_SEC_QTY 512 1024 lt b size of partition FS_ERR HEEEL lt Q return error Again the parameters are the device name a and the size of the partition in sectors b After this has been done the device is divided as shown in Figure 5 6 M B R Primary Primary Primary Primary r Partition 1 Partition 2 Partition 3 Partition 4 256 MB 256 MB 256 MB 256 MB Figure 5 6 Device after four partitions have been created 74 Partitions When first instituted DOS partitioning was a simple scheme allowing up to four partitions each with an entry in the MBR It was later extended for larger devices requiring more with extended partitions partitions that contains other partitions The primary extended partition is the extended partition with its entry in the MBR it sho
289. on herein and is not responsible for any errors or omissions The publisher assumes no liability for damages resulting from the use of the information in this book or for any infringement of the intellectual property rights of third parties that would result from the use of this information Micrium 600 uC FS 001 For the Way Engineers Work Chapter 1 1 1 1 2 1 3 1 4 Chapter 2 2 1 2 1 1 2 1 2 2 1 3 2 1 4 2 1 5 2 1 6 2 1 7 2 1 8 Chapter 3 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 3 10 3 11 Table of Contents idee ele BEE 15 HESE shoe sees EE ee A ee heres aes ende neden ah aes 15 Mee E 17 Why FAT i Scere anni a ditties ae 17 Chapter Contents e aea da aa aeea a aaan a aerae Aae aa arai aaeain aiai 18 UG FS Architecture geduet eege aaa daa ai aaa la a aa a eerie 23 Architecture Components nnnanannenennen enen senmenenennenneenvenseennenenennen 25 Your ApplicatlOft isvsarsaarersssar ees AEELAEed E SEELEN 25 uC LIB LibrarieS nnnnannennenenenseen enn REENEN 25 POSIX ARTMANN Eege at 25 FS LAY OM Eege ee EE EE EE ccs 26 File System Driver Layer nnnnaenen enne nerennennenenenenneneenenennennennnenneneenn 27 Device Driver Layer u saven NEESS vennen NEESS NEES 27 TOE E WEE 28 PTOS EE 28 UC FS Directories and Files aaan an aan nnnenenenenenenenenenvenenenenn 29 Application Code E 32 od U EEN 34 Board Support Package BSP een 35 uC CPU CPU Specific Source Code aan
290. op or wait on semaphore should always have a timeout to avoid blocking the task in the case of an unforeseen hardware malfunction or a software flaw Check if an error occurred The error status register is decoded to produce the actual error condition That is not necessary strictly but error counters that accumulate within the generic driver based upon returned error values may be useful while debugging a port Return no error The data has been transferred already to the memory buffer using DMA C 5 6 FSDev SD Card BSP CmdDataWr void FSDev SD Card BSP CmdDataWr FS OTY unit nbr File FS DEV SD CARD CMD p cmd void p src FS DEV SD CARD ERR p err Called from Code enabled by fs dev sd card bsp c FSDev_SD Card WrData N A Write data following a command ARGUMENTS unit nbr p_cmd p src p err Unit number of SD MMC card Pointer to command that was started Pointer to source buffer Pointer to variable that will receive the return error code from this function FS DEV SD CARD ERR NONE No error FS DEV SD CARD ERR NO CARD No card present FS DEV SD CARD ERR UNKNOWN Unknown or other error FS DEV SD CARD ERR WAIT TIMEOUT Timeout in waiting for data FS DEV SD CARD ERR DATA UNDERRUN Data underrun FS DEV SD CARD ERR DATA CHKSUM Error in data checksum FS DEV SD CARD ERR DATA START BIT Data start bit error FS DEV SD CARD ERR DATA Other data error RETURNED VALUE None NOTES WARN
291. or address spaces of the constituent devices are concatenated to form a single continuous address space A device can be partitioned or subdivided into one or more regions called partitions each consisting of a number of consecutive sectors Typically structures are written to the device instructing software as to the location and size of these partitions This file system suite supports DOS partitions A volume is a device or device partition with a file system A device or device partition must go through a process called mounting to become a volume which includes finding the file system and making it ready for use The name by which a volume is addressed may also be called the volume s mount point A device or volume may be formatted to create a new file system on the device For disambiguation purposes this process is also referred to as high level formatting The volume or device will automatically be mounted once formatting completes For certain devices it is either necessary or desirable to perform low level formatting This is the process of associating logical sector numbers with areas of the device A file system driver is a code module which allows the general purpose file system suite to access a specific type of file system For example this file system suite includes a FAT file system driver FAT File Allocation Table is a common file system type prevalent in removable media that must work with various OSs It is name
292. or more information 137 Chapter 12 Micrium Software uC FS Examples BSP Dev SD Card Each subdirectory contains an example BSP for a particular platform These are named according to the following rubric lt Chip Manufacturer gt lt Board or CPU gt fs dev sd card bsp c Micrium Software uC FS Examples BSP Dev SD SPI Each subdirectory contains an example BSP for a particular platform These are named according to the following rubric lt Chip Manufacturer gt lt Board or CPU gt fs dev sd spi bsp c 12 2 USING THE SD MMC CARDMODE DRIVER To use the SD MMC cardmode driver five files in addition to the generic file system files must be included in the build E fs dev sd c E fs dev sd h E fs dev sd card c E fs dev sd card h E fs dev sd card bsp c The file fs dev sd card h must also be included in any application or header files that directly reference the driver for example by registering the device driver The following directories must be on the project include path B Micrium Software uC FS Dev SD B Micrium Software uC FS Dev SD Card 138 Using the SD MMC CardMode Driver A single SD MMC volume is opened as shown in Listing 12 1 The file system initialization FS _Init function must have previously been called ROM RAM characteristics and performance benchmarks of the SD MMC driver can be found in section 9 1 1 Driver Characterization on page 113 The SD MMC driver also provides interface
293. ord_XX void FSDev_NAND BSP WrWord 08 FS OTY unit nbr CPU _ADDR addr src CPU INTO8U datum void FSDev NAND BSP WrWord 16 FS OTY unit nbr CPU _ADDR addr src CPU INT16U datum File Called from Code enabled by fs dev nor bsp c NOR physical layer driver N A Write data to bus interface ARGUMENTS unit nbr Unit number of NOR addr src Source address datum Word to write RETURNED VALUE None NOTES WARNINGS Data should be written o the bus in words sized to the data bus for any unit only the function with its access width will be called 478 C 10 6 FSDev NOR BSP WaitWhileBusy CPU_BOOLEAN FSDev_NOR_BSP_WaitWhileBusy FS_OTY unit_nbr FS DEV NOR PHY DATA p phy data CPU BOOLEAN poll fnct FS DEV NOR PHY DATA CPU INT32U to us File Called from Code enabled by fs dev_nor_bsp c NOR physical layer driver N A Wait while NAND is busy ARGUMENTS unit_nbr Unit number of NOR p_phy data Pointer to NOR phy data poll fnct Pointer to function to poll if there is no hardware ready busy signal to us Timeout in microseconds RETURNED VALUE DEF_OK if NAND became ready DEF_FAIL otherwise NOTES WARNINGS None 479 Appendix C CPU BOOLEAN FSDev_NOR_BSP_WaitWhileBusy FS_QTY unit nbr FS_DEV NOR PHY DATA p phy data CPU_BOOLEAN poll fnct FS DEV NOR PHY DATA CPU_INT32U to us CPU INT32U time our us CPU INT32U time start us CPU BOOLEAN
294. orm all the operations that need to be done a single time only when opening the device The Close function is typically left empty PART DATA GET FUNCTION The PartDataGet function should return an instance of the type FS_NAND_ PART DATA associated to a particular device SETUP FUNCTION The Setup function is called a single time after the Open function It must perform the proper calculation to make sure that the out of sector data OOS and the error correction codes ECC can fit in the spare area 196 Development Guide SECTOR READ FUNCTION The SectorRd function must copy the data found at the physical sector sec_ix_phy into the p_dest buffer It must also copy the out of sector data OOS the section of the spare area excluding ECC bad block marks and unused sections into the p_dest_oos buffer Before returning successfully the function should check for errors and correct them if needed with ECC OUT OF SECTOR OOS RAW READ FUNCTION The OOSRdRaw function must copy len octets from the offset octet in the OOS of the sector sec_ix phy into the p dest_oos buffer This function should not perform error correction SPARE AREA RAW READ FUNCTION The SpareRdRaw function must copy len octets from the offset octet in the spare area of the page pg ix phy into the p dest spare buffer This function should not perform error correction SECTOR WRITE FUNCTION The SectorWr function must write the data found in
295. ors in the root directory the area of the file allocation table FAT from which clusters are being allocated or data from important often read files A cache wedged between the system driver and volume layers as shown in Figure 5 8 will eliminate many unnecessary device accesses Sector data is stored upon first read or write Further reads return the cached data further writes update the cache entry and possibly the data on the volume depending on the cache mode FAT System Driver fs_sys fs_fat Figure 5 8 Volume cache architecture A cache is defined by three parameters size sector type allocation and mode The size of the cache is the number of sectors that will fit into it at any time Every sector is classified according to its type either management directory or file the sector type allocation determines the percentage of the cache that will be devoted to each type The mode determines when cache entries are created i e when sectors are cached and what happens upon write 79 Chapter 5 Cache Mode Description Cache Mode define Read cache Sectors cached upon read never cached upon write FS_VOL_CACHE_MODE_RD Write through cache Sectors cached upon read and write data on volume always updated upon write FS_VOL_CACHE_MODE_WR_THROUGH Write back cache 80 Sectors cached upon read and write data on volume never updated upon write FS_VOL_CACHE_MODE_WR_BACK Table
296. ough it is present If FS ERR DEV NOT PRESENT FS ERR DEV IO or FS ERR DEV TIMEOUT is returned then the device has been added to the file system though it is probably not present The device will need to be either closed and re added or refreshed If any of the follwing is retutrned FS ERR DEV INVALID NAME FS ERR DEV INVALID SEC SIZE FS ERR DEV INVALID SIZE FS ERR DEV INVALID UNIT NBR FS ERR DEV NONE AVAIL then the device has NOT been added to the file system If FS_ERR_DEV_UNKNOWN is returned then the device driver is in an indeterminate state The system MAY need to be restarted and the device driver should be examined for errors The device has NOT been added to the file system A 3 10 FSDev_PartitionAdd FS PARTITION NBR FSDev PartitionAdd CPU CHAR name dev FS SEC OTY partition size FS ERR p err File Called from Code enabled by fs dev c FS _CFG RD ONLY EN Application FS CFG PARTITION EN and not Adds a partition to a device See also section 5 5 Partitions on page 73 ARGUMENTS name dev Device name partition size Size in sectors of the partition to add p err Pointer to variable that will receive return error code from this function FS ERR NONE Partition added FS ERR INVALID PARTITION Invalid partition FS ERR INVALID SEC NBR Sector start or count invalid FS ERR INVALID SIG Invalid MBR signature FS ERR NAME NULL Argument name dev passed a NULL pointer Or device access error
297. own implementation of the controller layer to take advantage of hardware peripherals and reduce CPU usage However a generic controller driver that is compatible with most parallel NAND flash devices and micro controllers is provided 159 Chapter 13 Error correction codes ECC management Error correction codes are used to eliminate the bit read errors typical to NAND flash It is easy to provide a software implementation of an ECC scheme or to interface to a hardware engine for each device used It is then possible to configure the size of the codewords and the level of protection required to suit the needs of your application Wide support for different NAND flashes Most NAND flash memories are compatible with the driver including large pages small pages SLC and MLC single and multiple level cells flash memory Please contact Micrium to inquire about uC FS s compatibility with specific NAND devices 13 1 GETTING STARTED The following section shows an example on how to get started in a typical case comprising the following B The generic controller layer implementation included with the NAND driver P The 1 bit software ECC implementation included with the NAND driver E The static part layer implementation included with the NAND driver B Your BSP layer implementation to adapt the driver to your specific platform In case you need additional information and details regarding the different layers please refer to the section 1
298. pendix A A 1 3 FS _VersionGet CPU INT16U FS VersionGet void File Called from Code enabled by fs c Application N A Gets the uC FS software version ARGUMENTS None RETURNED VALUE HC FS software version NOTES WARNINGS The value returned is multiplied by 100 For example version 4 03 would be returned as 403 228 A 1 4 FS WorkingDirGet void FS WorkingDirGet CPU CHAR path dir CPU SIZE T size FS ERR p err File Called from Code enabled by fs c Application FS CFG WORKING DIR EN fs getcwd Get the working directory for the current task ARGUMENTS path dir String buffer that will receive the working directory path size Size of string buffer p err Pointer to variable that will receive the return error code from this function FS ERR NONE Working directory obtained FS ERR NULL PIR Argument path_dir passed a NULL pointer FS ERR NULL ARG Argument size passed a NULL value FS ERR NAME BUF TOO SHORT Argument size less than length of path FS ERR VOL NONE EXIST No volumes exist RETURNED VALUE None NOTES WARNINGS If no working directory is assigned for the task the default working directory the root directory on the default volume will be returned in the user buffer and set as the task s working directory 229 Appendix A A 1 5 FS WorkingDirSet void FS WorkingDirSet CPU CHAR path dir FS ERR p err File Called from Code enabled by
299. ple does not apply to your situation we strongly recommend you read the sections about the different layers This will help you determine if other existing implementations are suitable for you or if you need to develop your own implementation of some of those layers 166 Architecture Overview 13 2 ARCHITECTURE OVERVIEW The NAND driver comprises multiple layers as depicted in Figure 13 1 Interface with filesystem and or application Part layer NAND Driver fs_dev_nand Obtain in a fs_dev nand cfg h static or Provides generic driver interface e g dynamic init read write and performs wear manner all leveling so all blocks are used equally parameters Lo ern nnn nnn enn nnn e nner nnn rn cre creer nes R of the for generic controller specific part chip Controller layer Controller extension fs_dev_nand ctrlr_gen soft ecc fs_dev nand ctrlr_gen micron ecc Implements particular controller data Manages ECC calculation and bus and manages ECC correction correction fs_dev nand _ctrir_gen BSP ECC Module fs der nand xxxx_bsp c ecc_hamming Access NAND device via bus interface or Software implementation of ECC GPIO Interface specific to controller layer calculation and correction implementation for software ECC ext Figure 13 1 NAND driver architecture The generic NAND translation layer provides sector abstraction and performs wear leveling to ensure all blocks are used equally The con
300. present or timeout error 285 Appendix A A 3 12 FSDev Partitioninit void FSDev PartitionInit CPU CHAR name dev FS SEC OTY partition size FS ERR p err File Called from Code enabled by fs deu Application not FS _CFG_RD ONLY EN Initialize the partition structure on a device See also section 5 5 Partitions on page 73 ARGUMENTS name dev Device name partition size Size of partition in sectors OR 0 if partition will occupy entire device p err Pointer to variable that will receive the return error code from this function FS ERR NONE Partition structure initialized FS ERR DEV VOL OPEN Volume open on device FS ERR INVALID SEC NBR Sector start or count invalid FS ERR NAME NULL Argument name dev passed a NULL pointer Or device access error see section B 4 Device Error Codes on page 394 RETURNED VALUE None NOTES WARNINGS 1 Function blocked if a volume is open on the device All volume and files must be closed prior to initializing the partition structure since it will obliterate any existing file system 2 Device state change will result from device I O not present or timeout error 286 A 3 13 FSDev_Query void FSDev_Query CPU_CHAR name_dev FS DEV INFO p info FS ERR p err File Called from Code enabled by fs deu Application N A Obtain information about a device ARGUMENTS name dev Device name p info Pointer to structure that will receive
301. pter 13 Before implementing the following functions it is important to understand the difference between out of sector OOS data and the spare area In a NAND device each page has a spare area typically used to store metadata and error correction codes ECC The spare area also contains a factory defect mark and optionally reserved sections In the implementation of the pC FS NAND driver the OOS data is metadata sent to the controller layer by the translation layer It must be stored in the spare area without overwriting the bad block mark and without writing to the reserved section It must also be protected by ECC The OOS data is only a part of what is inside the spare area It doesn t include the factory defect marks the reserved sections and the ECC data Also if the sector size is not equal to the page size the OOS data will be associated to a single sector while the spare area will be associated to a single page In that case multiple OOS sections would be fit in a single spare area OPEN CLOSE FUNCTIONS The Open and Close function will be called respectively by FSDev_Open and FSDev_Close Typically FSDev_Open is called during initialization and FSDev_Close is never called When implementing the Open function of the controller layer you should typically add all necessary code for the bus controller initialization or call the Open function of the BSP layer You should also allocate the necessary memory and perf
302. r Chapter 15 MSC Driver The now common USB drive implements the Mass Storage Class MSC protocol and a CPU with a USB host interface can access these devices with appropriate software The MSC driver discussed in this chapter with uC USB Host is just such appropriate software Appendix A uC FS API Reference The reference manual describes every API function The arguments and return value of each function are given supplemented by notes about its use and an example code listing Appendix B uC FS Error Codes This appendix provides a brief explanation of uC FS error codes defined in fs_err h Appendix C uC FS Porting Manual The portability of uC FS relies upon ports to interface between its modules and the platform or environment Most of the ports constitute the board support package BSP which is interposed between the file system suite or driver and hardware The OS port adapts the software to a particularly OS kernel The porting manual describes each port function Appendix D uC FS Types and Structures This appendix provides a reference to the uC FS types and structures 20 Chapter Contents Appendix E uC FS Configuration wC FS is configured via defines in a single configuration file fs cfg h The configuration manual specifies each define and the meaning of possible values Appendix F Shell Commands A familiar method of accessing a file system at least to engineers a
303. r already added FS ERR DEV DRV INVALID NAME Device driver name invalid FS ERR DEV DRV NO TBL POS AVAIL No device driver table position available RETURNED VALUE None NOTES WARNINGS E The NameGet device driver interface function MUST return a valid name The name must be unique e g a name that is not returned by any other device driver The name must NOT include any of the characters or 7 The name must contain fewer than FS_CFG MAX DEV DRV NAME LEN characters The name must NOT be an empty string B The Init device driver interface function is called to initialize driver structures and any hardware for detecting the presence of devices for a removable medium 226 A 1 2 FS Init FS ERR FS Init FS CFG p fs cfg File Called from Code enabled by fs h Application N A Initializes uC FS and MUST be called prior to calling any other uC FS API functions ARGUMENTS p fs cfg Pointer to file system configuration see Section C 01 RETURNED VALUE FS ERR NONE if successful Specific initialization error code otherwise The return value SHOULD be inspected to determine whether uC FS is successfully initialized or not If p FS did NOT successfully initialize search for the returned error in fs_err h and source files to locate where pC FS initialization failed NOTES WARNINGS uC LIB memory management function Mem Init MUST be called prior to calling this function 227 Ap
304. r large transactions on the file system ex copying multi MB files Small files or small iterative changes to large files are best handled by RUBs It is important to note that the translation layer will automatically determine what type of update block is the best depending on the parameters of the transaction itself This parameter is only to limit the number of update blocks that can be SUBs 173 Chapter 13 ADVANCED CONFIGURATION OPTIONS The following configuration defines should be left at their default values Advanced understanding of the wear leveling and block abstraction algorithms is necessary to set these configurations FS_NAND CFG TH PCT MERGE_RUB_ START SUB This define indicates the minimum size in sectors of the write operation needed to create a sequential update block SUB when a random update block RUB already exists SUBs offer a substantial gain in merge speed when a large quantity of sectors are written sequentially within a single or multiple write operations However if many SUBs are created and merged early the device will wear faster less sectors written between block erase operations This threshold is set as a percentage relative to the number of sectors per block Set higher than default for better overall wear leveling and lower than default for better overall write speed FS_NAND CFG _TH PCT CONVERT _SUB_TO RUB This define indicates the minimum size in sectors of free space needed in a
305. r structure B The definition of the type or structure B The filename of the source code E A description of the meaning of the type or the members of the structure E Specific notes and warnings regarding use of the type 481 Appendix D D 1 FS_CFG typedef struct fs cfg FS OTY FS OTY FS OTY FS OTY FS OTY FS OTY DevCnt VolCnt FileCnt DirCnt BufCnt DevDrvCnt FS_SEC_ SIZE MaxSecSize FS_CFG File Used for fs h First argument of FS_Init A pointer to a FS_CFG structure is the argument of FS_Init It configures the number of devices files MEMBERS DevCnt VolCnt FileCnt DirCnt 482 and other objects in the file system suite The maximum number of devices that can be open simultaneously MUST be greater than or equal to 1 The maximum number of volumes that can be open simultaneously MUST be greater than or equal to 1 The maximum number of files that can be open simultaneously MUST be greater than or equal to 1 Maximum number of directories that can be open simultaneously If DirCnt is 0 the directory module functions will be blocked after successful initialization and the file system will operate as if compiled with directory support disabled If directory support is disabled DirCnt is ignored otherwise if directories will be used DirCnt should be greater than or equal to 1 BufCnt Maximum number of buffers that can be used successfully The minimu
306. rdware ECC modules integrated within a NAND device or a micro controller s memory controller can be handled through a generic controller extension module However if your ECC module can be interfaced with the software ECC generic controller extension you could limit the code to be developed to the ECC layer only If this is the case you will need to provide the implementation of the API as shown in Listing 13 11 typedef struct ecc calc CPU_SIZE_T BufLenMin 1 CPU_SIZE_T BufLenMax 2 CPU_INTO8U ECC_Len 3 CPU_INTO8U NbrCorrectableBits 4 ECC_CALC_FNCT Calc 5 ECC_CHK_FNCT Chk 6 ECC_CORRECT_FNCT Correct 7 ECC_CALC Listing 13 11 ECC API type definition 113 110 Minimum buffer length that the ECC module can handle L13 11 2 Maximum buffer length that the ECC module can handle 113 113 Length in octets of the code for a single buffer L13 11 4 Number of bits the module can correct for each buffer 113 1165 Pointer to the code calculation function L13 11 6 Pointer to the error detection function L13 11 7 Pointer to the error correction function For more details on the implementation please refer to the uC CRC User Manual 193 Chapter 13 13 8 4 CONTROLLER LAYER DEVELOPMENT GUIDE To fully take advantage of advanced peripherals for example NAND flash controllers you might decide to provide your own implementation of the controller layer The controller layer is one level above the BSP layer Its
307. rdy GET CURRENT TIME IN MICROSECONDS time_start_us time_cur_us time_cur_us while time_cur_us time_start_us lt to_us 1 rdy poll fnct p phy data 2 if rdy DEF_OK return DEF_OK time cur_us GET CURRENT TIME IN MICROSECONDS return DEF_FAIL 3 Listing C 12 FSDev_NOR_BSP_WaitWhileBusy without hardware read busy signal LC 12 1 At least to us microseconds should elapse before the function gives up and returns Returning early can cause disruptive timeout errors within the physical layer driver LC 12 2 poll fnet should be called with p_phy data as its sole argument If it returns DEF_OK then the device is ready and the function should return DEF_OK LC 12 3 If to us microseconds elapse without the poll function or hardware ready busy signaling indicating success the function should return DEF FAIL C 11 NOR FLASH SPI BSP The NOR driver must adapt to the specific hardware using a BSP A serial NOR Flash will be interfaced on a SPI bus See Appendix C SPI BSP on page 453 for the details on how to implement the software port for your SPI bus 480 Appendix UC FS Types and Structures Your application may need to access or populate the types and structures described in this appendix Each of the user accessible structures is presented in alphabetical order The following information is provided for each entry E A brief description of the type o
308. re listed in Table 6 3 The entry functions and the FSFile Open function accept full file paths For information about using file and path names see section 4 3 uC FS File and Directory Names and Paths on page 62 The functions listed in Table 6 1 and Table 6 3 are core functions in the file access module FSFile 4 functions and entry module FSEntry_ 44 functions These are matched in most cases by API level functions that correspond to standard C or POSIX functions The core and API functions provide basically the same functionality the benefits of the former are enhanced capabilities a consistent interface and meaningful return error codes 83 Chapter 6 6 1 FILE ACCESS FUNCTIONS The file access functions provide an API for performing a sequence of operations on a file located on a volume s file system The file object pointer returned when a file is opened is passed as the first argument of all file access functions a characteristic which distinguishes these from the entry access functions and the file object so referenced maintains information about the actual file on the volume and the state of the file access The file access state includes the file position the next place data will be read written error conditions and if file buffering is enabled the state of any file buffer Function Description FSF ile BufAssign Assign buffer to a file FS File BufFlush Wr
309. rements 65 Chapter 4 Includes code and data for all file system components and functions except those itemized in the table RAM requirements are summarized in Table 2 2 The total depends on the number of each object allocated and the maximum sector size set by values passed to FS_Init in the file system configuration structure and various name length configuration parameters see Appendix E FS_CFG_MAX_PATH_NAME_LEN on page 503 Item RAM bytes Core 932 Per device 44 FS CFG MAX DEV NAME LEN Per volume 152 FS CFG MAX VOL NAME LEN Per file 144 Per directory 100 Per buffer 36 MaxSectorSize Per device driver 8 bytes Working directories FS_CFG MAX PATH NAME LEN 2 8 TaskCnt Table 4 2 RAM characteristics The number of tasks that use relative path names See also section 9 1 1 Driver Characterization on page 113 for ROM RAM characteristics of file system suite drivers 66 Chapter Devices and Volumes To begin reading files from a medium or creating files on a medium that medium hereafter called a device and the driver which will be used to access it must be registered with the file system After that a volume must be opened on that device analogous to mounting This operation will succeed if and only if the device responds and the file system control structures for FAT the Boot Parameter Block or BPB are located and val
310. resp FS DEV SD CARD ERR p err File Called from Code enabled by fs dev sd card bsp c SD MMC cardmode driver N A Wait for command to end and get command response ARGUMENTS unit nbr Unit number of SD MMC card p cmd Pointer to command that is ending p resp Pointer to buffer that will receive command response if any p err Pointer to variable that will receive the return error code from this function FS DEV SD CARD ERR NONE No error FS DEV SD CARD ERR NO CARD No card present FS DEV SD CARD ERR UNKNOWN Unknown or other error FS DEV SD CARD ERR WAIT TIMEOUT Timeout in waiting for command response FS DEV SD CARD ERR RESP TIMEOUT Timeout in receiving command response FS DEV SD CARD ERR RESP CHKSUM Error in response checksum FS DEV SD CARD ERR RESP CMD IX Response command index error FS DEV SD CARD ERR RESP END BIT Response end bit error FS DEV SD CARD ERR RESP Other response error FS DEV SD CARD ERR DATA Other data error 436 RETURNED VALUE None NOTES WARNINGS 1 This function will be called even if no response is expected from the command 2 This function will not be called if FSDev SD Card BSP CmdStart returned an error 3 The data stored in the response buffer should include only the response data i e should not include the start bit transmission bit command index CRC and end bit E For a command with a normal 48 bit response a 4 byte response should be stored in p resp
311. returned is measured in bytes from the beginning of the file 250 A 2 17 fs_ftruncate int fs ftruncate FS FILE p file fs off t size File Called from Code enabled by fs_api c Application FS CFG API EN and not FS _CFG RD ONLY EN Truncate a file ARGUMENTS p file Pointer to a file size Size of the file after truncation RETURNED VALUE 0 if the function succeeds 1 otherwise NOTES WARNINGS E The file MUST be opened in write or read write mode E If fs _ftruncate succeeds the size of the file shall be equal to length If the size of the file was previously greater than length the extra data shall no longer be available If the file previously was smaller than this length the size of the file shall be increased B If the file position indicator before the call to fs_ftruncate lay in the extra data destroyed by the function then the file position will be set to the end of file 251 Appendix A A 2 18 fs_ftrylockfile int fs ftrylockfile FS FILE p file File Called from Code enabled by fs_api c FS_CFG FILE LOCK EN Application FS CFG API EN and Acquire task ownership of a file Gf available ARGUMENTS p file Pointer to a file RETURNED VALUE 0 if no error occurs and the file lock is acquired Non zero value otherwise NOTES WARNINGS fs ftrylockfile is the non blocking version of fs flockfile if the lock is not available the funct
312. riable that will receive the return error code from this function FS_ERR_NONE Sector s read FS_ERR_DEV Device access error FS ERR NAME NULL FS ERR NULL PTR FS ERR VOL NOT MOUNTED FS ERR VOL NOT OPEN Argument name vol passed a NULL pointer Argument p dest passed a NULL pointer Volume is not mounted Volume is not open 353 Appendix A RETURNED VALUE None REQUIRED CONFIGURATION None NOTES WARNINGS None 354 A 7 14 FSVol_Wr void FSVol Wr CPU CHAR FS SEC OTY ent name vol void p src FS SEC NBR start FS ERR p err File Called from Code enabled by fs vol c Application not FS CG RD ONLY EN Writes data to volume sector s ARGUMENTS name vol Volume name p src Pointer to source buffer start Start sector of write ent Number of sectors to write p err Pointer to variable that will receive the return error code from this function FS ERR NONE Sector s written FS_ERR_DEV Device access error FS ERR NAME NULL FS ERR NULL PTR FS ERR VOL NOT MOUNTED FS ERR VOL NOT OPEN RETURNED VALUE None NOTES WARNINGS None Argument name vol passed a NULL pointer Argument p_src passed a NULL pointer Volume is not mounted Volume is not open 355 Appendix A A 8 VOLUME CACHE FUNCTIONS void FSVol_CacheAssign CPU_CHAR name vol FS VOL CACHE API p cache api void p cache data CPU _INT32U size CPU INTO8U pet_mgmt CPU_INTO8U pet dir FS F
313. ribe the format blk ent used 32 blk size 65536 sec size 512 secs per blk 65536 512 128 sec ent A gt SZ 4096 and the RAM usage is approximately D templ 32 8 32 2 68 temp2 4096 2 8192 temp3 512 TOTAL 68 8192 512 8772 In this example as in most situations increasing the sector size will decrease the RAM usage If the sector size were 1024 B only 5188 B would have been needed but a moderate performance penalty would be paid 203 Chapter 14 14 3 USING A PARALLEL NOR DEVICE To use the NOR driver five files in addition to the generic file system files must be included in the build E fs dev nor c E fs dev nor h E fs dev nor bsp c located in the user application or BSP B A physical layer driver eg as provided in Micrium Software uC FS Dev NOR PHY The file fs dev nor h must also be included in any application or header files that directly reference the driver for example by registering the device driver The following directories must be on the project include path B Micrium Software uC FS Dev NOR E Micrium Software uC FS Dev NOR PHY A single NOR volume is opened as shown in Table 14 1 The file system initialization FS_Init function must have previously been called ROM characteristics and performance benchmarks of the NOR driver can be found in section 9 1 1 Driver Characterization on page 113 The NOR driver also provides i
314. ries 12 1 FILES AND DIRECTORIES The files inside the SD MMC driver directory is outlined in this section the generic file system files outlined in Chapter 3 uC FS Directories and Files on page 29 are also required Micrium Software uC FS Dev This directory contains device specific files Micrium Software uC FS Dev SD This directory contains the SD MMC driver files fs dev sd contain functions and definitions required for both SPI and card modes Micrium Software uC FS Dev SD Card This directory contains the SD MMC driver files for card mode fs_dev_sd_card are device driver for SD MMC cards using card mode This file requires a set of BSP functions be defined in a file named fs dev sd card bsp c to work with a certain hardware setup BSP Template fs_dev_sd_card_bsp c is a template BSP See section C 5 SD MMC Cardmode BSP on page 425 for more information Micrium Software uC FS Dev SD SPI This directory contains the SD MMC driver files for SPI mode fs dev sd spi are device driver for SD MMC cards using SPI mode This file requires a set of BSP functions be defined in a file named fs dev sd spi bsp c to work with a certain hardware setup BSP Template fs dev sd spi bsp c is a template BSP See section C 6 SD MMC SPI mode BSP on page 452 for more information BSP Template GPIO fs dev sd spi bsp c is a template GPIO bit banging BSP See section C 6 SD MMC SPI mode BSP on page 452 f
315. river metadata is invalid FS ERR DEV OP ABORTED Operation aborted FS ERR DEV CORRUPT LOW FMT Corrupted low level fmt FS ERR DEV INVALID SEC DATA Retrieved sec data is invalid FS ERR DEV WR PROT Device is write protected FS ERR DEV OP FAILED Operation failed FS ERR DEV NAND NO AVAIL BLK No blk avail FS ERR DEV NAND NO SUCH SEC This sector is not available FS ERR DEV NAND ECC NOT SUPPORTED The needed ECC scheme is not supported FS ERR DEV NAND ONFI EXT PARAM PAGE NAND device extended parameter page must be read B 5 DEVICE DRIVER ERROR CODES FS ERR DEV DRV ALREADY ADDED Device driver already added FS ERR DEV DRV INVALID NAME Invalid device driver name FS ERR DEV DRV NONE AVAIL No driver available B 6 DIRECTORY ERROR CODES FS ERR DIR ALREADY OPEN Directory already open FS ERR DIR DIS Directory module disabled FS ERR DIR FULL Directory is full FS ERR DIR NONE AVAIL No directory avail FS ERR DIR NOT OPEN Directory not open B 7 ECC ERROR CODES FS ERR ECC CORRECTABLE Correctable ECC error FS ERR ECC UNCORRECTABLE Uncorrectable ECC error B 8 ENTRY ERROR CODES FS ERR ENTRIES SAME Paths specify same file system entry 395 Appendix B FS ERR ENTRIES TYPE DIFF FS ERR ENTRIES VOLS DIFF FS ERR ENTRY CORRUPT FS ERR ENTRY EXISTS FS ERR ENTRY INVALID FS ERR ENTRY NOT DIR FS ERR ENTRY NOT EMPTY FS ERR ENTRY NOT FILE FS ERR ENTRY NOT FOUND FS ERR ENTRY PARENT NOT FOUND FS ERR ENTRY PARENT NOT DIR
316. river to exceed the maximum number of partial page programs If this is not respected the driver will fail the initialization phase and return an error code One of the advantages of choosing a sector size smaller than the page size is to reduce the RAM usage The size of the buffers in the file system are based on the sector size A large sector size implies large buffers For the best performance the sector size should be in the ballpark of a typical transaction If most of your write operations are a couple of octets you should if possible choose a small sector size typically 512 octets On the other hand if you want to obtain good transfer rates and you have large application buffers with multimedia applications for example then the sector size should be set higher The optimal choice will almost always be the same as the page size 512 2048 4096 octets CHOOSING ERROR CORRECTION CODES Each device needs an error correction codes ECC module able to correct a minimal number of bits per codeword Choosing a module that satisfies the minimum required level of error correction is often the best option if you want to avoid the extra calculation time of modules with enhanced bit error correction 187 Chapter 13 To reduce the calculation load on your CPU it is recommended to consider using a hardware ECC module This is especially true with parts that require more than 1 bit per codeword of error correction These hardware EC
317. rom SPI bus Wr Write to SPI bus ChipSelEn Enable device chip select ChipSelDis Disable device chip select SetClkFreg Set SPI clock frequency Table C 4 SPI port functions The first argument of each of these port functions is the device unit number an identifier unique to each driver device type after all it is the number in the device name For example sd 0 and nor 0 both have unit number 1 If two SPI devices are located on the same SPI bus either of two approaches can resolve unit number conflicts if each device has a unique unit number serial NOR nor 1 require only one BSP Unique unit numbers All devices on the same bus can use the same SPI BSP if and only For example the SD MMC card sd 0 and Unique SPI BSPs Devices of different types e g a SD MMC card and a serial NOR can have the same unit number if and only if each device uses a separate BSP For example the SD MMC card sd 0 and serial nor 0 require separate BSPs 456 C 7 1 Open CPU BOOLEAN FSDev_BSP_SPI_Open FS OTY unit nbr File Called from Code enabled by fs dev lt dev name gt bsp c Device driver N A Open initialize hardware for SPI ARGUMENTS unit nbr Unit number of device RETURNED VALUE DEF OR if interface was opened DEF FAIL otherwise NOTES WARNINGS 1 This function will be called every time the device is opened 2 Several aspects of SPI com
318. rror status REG ERROR STATUS COMMAND END BIT DEF YES p err FS DEV SD CARD ERR RESP END BIT else if DEF BIT IS SET error status REG ERROR STATUS COMMAND CRC DEF YES p err FS DEV SD CARD ERR RESP CRC else if DEF BIT IS SET error status REG ERROR STATUS COMMAND TIMEOUT DEF YES p err FS DEV SD CARD ERR RESP TIMEOUT else p err FS DEV SD CARD ERR RESP REG ERROR STATUS error status REG INTERRUPT STATUS interrupt status return 438 Read response 3 REG INTERRUPT STATUS BIT INTERRUPT STATUS COMMAND COMPLETE if DEF BIT IS SET p cmd gt Flags FS DEV SD CARD CMD FLAG RESP DEF YES if DEF BIT IS SET p cmd gt Flags FS DEV SD CARD CMD FLAG RESP LONG DEF YES p resp 3 REG RESPONSE 00 p resp 2 REG RESPONSE 01 p resp 1 REG RESPONSE 02 p resp 0 REG RESPONSE 03 else p resp 0 REG RESPONSE 00 p err FS DEV SD CARD ERR NONE LC 8 1 LC 8 2 LC 8 3 Listing C 8 FSDev_SD_Card_BSP_CmdWaitEnd Wait until command execution completes or an error occurs The wait loop or wait on semaphore should always have a timeout to avoid blocking the task in the case of an unforeseen hardware malfunction or a software flaw Check if an error occurred The error status register is decoded to produce the actual error condition That is not necessary strictly but error counters that accumulate within the generic driver
319. ry is removed from or added to the directory after the directory has been opened information may or may not be returned for that entry 260 A 2 27 fs_remove int fs remove const char name full File Called from Code enabled by fs_api c FS_CFG RD ONLY EN Application FS CFG API EN and not Delete a file or directory ARGUMENTS name full Name of the entry RETURNED VALUE 0 if the file is NOT removed 1 if the file is NOT removed NOTES WARNINGS E When a file is removed the space occupied by the file is freed and shall no longer be accessible A directory can be removed only if it is an empty directory B The root directory cannot be removed 261 Appendix A EXAMPLE 262 A 2 28 fs_rename int fs rename const char name_full old const char name full new File Called from Code enabled by fs_api c Application FS CFG API EN and not FS _CFG RD ONLY EN Rename a file or directory ARGUMENTS name full old Old name of the entry name full new New name of the entry RETURNED VALUE 0 if the entry is NOT renamed 1 if the entry is NOT renamed NOTES WARNINGS E name full old and name full new MUST specify entries on the same volume E If path old and path new specify the same entry the volume will not be modified and no error will be returned E If path old specifies a file path_new must NOT specify a directory if path_new is a file it wi
320. ry structure 5 4 RAW DEVICE IO Opened devices can be accessed directly at the sector level completely bypassing the file system Such read and write operations on raw devices are accomplished by using FSDev Rd and FSDev Wr to respectively read and write one or more sector at a time However doing so may have the unwanted side effect of corrupting an existing file system on the device and as such should be done carefully Applications wishing to use both the high level file system API of uC FS and raw device access concurrently may acquire a global lock to a device with FSDev AccessLock While the application has ownership of a device s access lock all higher level operations such as the FSFile_ and FSEntry_ type of functions will wait for the lock to be released The lock can then be released using FSDev_AccessUnlock to give back access to the device When raw device operations are used to make changes on opened files and volumes it is generally required to invalidate them to prevent uC FS from performing inconsistent operations on the file system A call to FSDev_InvalidateO will make every operations on files and volumes opened on a device fail with an FS_ERR_DEV_CHNGD error Affected files and volumes will then have to be closed and re opened to continue similarly to a removable media change 72 5 5 PARTITIONS Partitions A device can be partitioned into two or more regions and a file system created on one or more of
321. s p err FS DEV SD CARD ERR NONE 3 Listing C 10 FSDev_ SD Card BSP_CmdDataWr 444 LC 10 1 Wait until data transfer completes or an error occurs The wait loop or wait on semaphore SHOULD always have a timeout to avoid blocking the task in the case of an unforeseen hardware malfunction or a software flaw LC 10 2 Check if an error occurred The error status register is decoded to produce the actual error condition That is not necessary strictly but error counters that accumulate within the generic driver based upon returned error values may be useful while debugging a port LC 10 3 Return no error The data has been transferred already from the memory buffer using DMA 445 Appendix C C 5 7 FSDev_SD Card BSP GetBlkCntMax CPU _INT32U FSDev SD Card BSP GetBlkCntMax FS QTY unit nbr CPU INT32U blk size File Called from Code enabled by fs dev sd card bsp c FSDev_SD Card Refresh N A Get maximum number of blocks that can be transferred with a multiple read or multiple write command ARGUMENTS unit nbr Unit number of SD MMC card blk size Block size in octets RETURNED VALUE Maximum number of blocks NOTES WARNINGS 1 The DMA region from which data is read or written may be a limited size The count returned by this function should be the maximum number of blocks of size blk size that can fit into this region 2 If the controller is not capable of multiple block reads or write
322. s 1 should be returned 3 If the controller has no limit on the number of blocks in a multiple block read or write DEF_INT_32U_MAX VAL should be returned 4 This function SHOULD always return the same value If hardware constraints change at run time the device MUST be closed and re opened for any changes to be effective 446 C 5 8 FSDev SD Card BSP_GetBusWidthMax CPU INTO8U FSDev SD Card BSP GetBusWidthMax FS OTY unit nbr File Called from Code enabled by fs dev sd card bsp c FSDev SD Card Refresh N A Get maximum bus width in bits ARGUMENTS unit nbr Unit number of SD MMC card RETURNED VALUE Maximum bus width NOTES WARNINGS 1 Legal values are typically 1 4 and 8 2 This function should always return the same value If hardware constraints change at run time the device must be closed and re opened for any changes to be effective 447 Appendix C C 5 9 FSDev_SD_Card_BSP_SetBusWidth void FSDev_SD Card BSP SetBusWidth FS OTY unit_nbr CPU_INTO8U width File Called from Code enabled by fs dev sd card bsp c FSDev_SD Card Refresh N A FSDev SD Card SetBusWidth Set bus width ARGUMENTS unit nbr Unit number of SD MMC card width Bus width in bits RETURNED VALUE None NOTES WARNINGS None 448 EXAMPLE The implementation of FSDev SD Card BSP SetBusWidth in Listing C 11 is targeted for the same host controller as the other listings in th
323. s are read from the device s parameter page The part configuration structure should be initialized to FS_NAND_PartONFI_DfltCfg to ensure upward compatibility with future versions The configuration fields available for the ONFI part layer implementation are described in Listing 13 7 typedef struct fs nand part onfi cfg FS_NAND FREE SPARE DATA FreeSpareMap 1 FS HAND PART ONFI CFG Listing 13 7 NAND ONFI part layer configuration structure L13 7 1 Pointer to the map of the free regions in the spare area see Listing 13 6 13 5 BOARD SUPPORT PACKAGE GENERIC CONTROLLER If you use the generic controller layer implementation you will have to provide a board support package to interface with your board layout and hardware The board support package must be provided in the form of an API pointer of the type FS _NAND CTRLR GEN BSP API like shown in Listing 13 8 185 Chapter 13 typedef struct fs nand ctrlr gen bsp api void Open FS ERR p err void Close void void ChipSelEn void void ChipSelDis void void CmdWr CPU_INTO8U p cmd CPU_SIZE_T ent FS ERR p err void AddrWr CPU_INTO8U p_addr CPU_SIZE_T ent FS ERR p err Es void DataWr void p Sre CPU_SIZE_T cnt FS_ERR tp err void DataRd void p dest CPU_SIZE_T ent FS ERR p err void WaitWhileBusy void poll fent arg CPU BOOLEAN poll fent void arg CPU_INT32U to us FS ERR p err FS _
324. s defined in the SD Card Association s Physical Layer Simplified Specification Version 2 00 Section 5 1 For MMC cards the structure of the CID is defined in the JEDEC s MultiMediaCard MMC Electrical Standard High Capacity Section 8 2 365 Appendix A A 9 3 FSDev SD xxx RdCSD void FSDev SD Card RJCSD CPU CHAR name dev CPU INTO8U p info FS ERR p err void FSDev SD SPI RJCSD CPU CHAR name dev CPU INTO8U p info FS ERR p err File Called from Code enabled by fs dev sd card c Application N A fs dev sd spi c Read SD MMC Card Specific Data CSD register ARGUMENTS name dev D dest p err 366 Device name see Note 1 Pointer to 16 byte buffer that will receive SD MMC Card Specific Data register Pointer to variable that will the receive return error code from this function FS ERR NONE SD MMC Card Specific Data register read FS ERR NAME NULL Argument name dev passed a NULL pointer FS ERR NULL PTR Argument p dest passed a NULL pointer FS ERR DEV INVALID Argument name dev specifies an invalid device FS ERR DEV NOT OPEN Device is not open FS ERR DEV NOT PRESENT Device is not present FS ERR DEV IO Device I O error FS ERR DEV TIMEOUT Device timeout RETURNED VALUE None NOTES WARNINGS B The device must be a SD MMC device for FSDev_SD Card QuerySD e g sdcard 0 for FSDev SD SPI QuerySD e g sd 0 B For SD cards the str
325. s switch you agree to contact Microsoft to obtain a license to use LFNs 10 1 WHY EMBEDDED SYSTEMS USE FAT Since FAT s inception it has been extended multiple times to support larger disks as well as longer file names However it remains simple enough for the most resource constrained embedded system Because FAT is supported by all major operating systems it still dominates the removable storage market USB flash drives are embedded systems and most are formatted in FAT Cameras MP3 players and other consumer electronics that depend on easy file transfer to and from the device also normally use FAT FAT is also widely used in embedded systems especially ones that run on microcontrollers 117 Chapter 10 10 2 ORGANIZATION OF A FAT VOLUME As shown in Figure 10 1 a FAT volume Oe a logical disk contains several areas FAT12 16 Reserved 1st FAT 2nd FAT Root Data Area Area Area Area Directory FAT32 Reserved 1st FAT 2nd FAT Data Area Area Area Area 118 Figure 10 1 FAT volume layout Reserved area The reserved area includes the boot sector which contains basic format information like the number of sectors in the volume File allocation table area The FAT file system is named after the file allocation table a large table with one entry for each cluster in the volume This area must contain at least one FAT area for redundancy it may also contain one or more additional FAT areas Root directory area FAT 1
326. s with semaphores for wait and asynchronous notification The best solution will vary from one platform to another since the additional context switches may prove burdensome No matter which strategy is selected the function MUST delay for at least the specified time amount otherwise sporadic errors can occur Ideally the actual time delay will equal the specified time amount to avoid wasting processor cycles void FS BSP Dly ms CPU_INT16U ms Insert code to delay for specified number of millieconds Listing C 3 FS_OS_Dly_ms FS_OS_Sem The four generic OS semaphore functions provide a complete abstraction of a basic OS kernel service FS_OS SemCreate creates a semaphore which may later be deleted with FS OS SemDel FS OS SemPost signals the semaphore with or without timeout and FS OS SemPend waits until the semaphore is signaled On systems without an OS kernel the trivial implementations in Listing C 4 are recommended 408 CPU_BOOLEAN FS OS SemCreate FS BSP SEM p sem 1 CPU_INT16U cnt p sem cnt Create semaphore with initial count cnt return DEF OK CPU_BOOLEAN FS OS SemDel FS BSP SEM p sem 2 p sem Ou Delete semaphore return DEF_OK Listing C 4 FS_OS_Sem trivial implementations 409 Appendix C CPU BOOLEAN FS OS SemPend FS BSP SEM p sem 3 CPU_INT32U timeout CPU_INT32U timeout ents CPU INT16U sem val CPU_SR_AL
327. sed on application requirements lib cfg h determines whether to enable assembly language optimization assuming there is an assembly language file for the processor i e lib mem a asm and a few other defines 3 6 HC CLK TIME CALENDAR MANAGEMENT HC CIk consists of functions that are meant to centralize time management in one independant module This way the same time info can be easily shared across all Micrium products Micrium Software uC Clk Cfg Template clk_cfg h VOS lt rtos_name gt clk_os c Source clk c clk h Micrium This directory contains all software components and projects provided by Micrium 39 Chapter 3 Software This sub directory contains all the software components and projects uc Clk This is the main pC Clk directory Cfg Template This directory contains a configuration template file clk efg h that must be copied to the application directory to configure the uC Clk module based on application requirements clk_cfg h determines whether clock will be managed by the RTOS or in your application A few other defines are used to enable disable some features of pC Clk and to configure some parameteres like the clock frequency os This is the main OS directory lt rtos_name gt This is the directory that contains the file to perform RTOS abstraction Note that the file for the selected RTOS abstraction layer must always be named clk_os c HC CIk has been tested with pC OS
328. seek FS FILE p file long int offset int origin int fs fsetpos FS FILE p file fs fpos t p pos long int fs ftell FS_FILE p file int fs ftruncate FS FILE p file fs off t size int fs ftrylockfile FS FILE p file void fs funlockfile FS FILE p file fs size t fs fwrite void p src fs size t size fs size t nitems FS FILE p file char fs getcwd char path dir fs size t size struct fs tm fs localtime r const fs time t p ts struct fs tm p time 232 int fs_mkdir const char name full fs time t fs mktime struct fs tm p time FS DIR fs opendir const char name full int fs readdir FS DIR struct fs dirent struct fs dirent p dir p dir entry pp result int fs remove const char name full int fs rename const char name full old const char name full new void fs rewind FS FILE p file int fs setbuf FS FILE p file fs size_t size int fs setvbuf FS FILE p file char p buf int mode fs size_t size 233 Appendix A A 2 1 fs_asctime_r char fs asctime r const struct fs tm p time char str_time File Called from Code enabled by fs api c Application FS CFG API EN Converts date time to string in the form Sun Sep 16 01 03 52 1973 n 0 ARGUMENTS p_time Pointer to date time to format str_time String buffer that will receive date time string see Note RETURN
329. sequential update block SUB to convert it to a random update block RUB RUBs have more flexible write rules at the expense of a longer merge time If the SUB s usage is over the threshold the SUB will be merged and a new RUB will be started instead of performing the conversion from SUB to RUB This threshold is set as a percentage relative to number of sectors per block Set higher than default for better overall write speed and lower than default for better overall wear leveling To take advantage of this threshold it must be set higher than the value of FS NAND CFG TH PCT PAD SUB Otherwise this threshold won t have any effect 174 NAND Translation Layer FS_NAND CFG TH PCT PAD SUB This define indicates the maximum size in sectors that can be skipped in a sequential update block SUB Since each sector of a SUB must be written at a single location sector physical index sector logical index it is possible to allow small gaps in the sequence Larger gaps are more flexible and can improve the overall merge speed at the cost of faster weat since some sectors are left empty between erase operations This threshold is set as a percentage relative to number of sectors per block Set higher than default for better overall write speed and lower than default for better overall wear leveling FS H nn CFG TH PCT MERGE _SUB This define indicates the maximum size in sectors of free space needed in a sequential updat
330. ses uC CRC s ECC modules for the ECC codewords calculation and data correction The extension is configurable through a FS_NAND_CTRLR_GEN SOFT ECC CFG type structure It should be initialized to the value FS_NAND CtrlrGen SoftEcc DfltCfg before its fields are overridden to the appropriate values for your application typedef struct fs nand cfg const ECC CALC ECC_ModulePtr 1 1 FS_NAND CFG L13 4 1 Listing 13 4 NAND translation layer configuration structure Pointer to an ECC CALC API structure that will be used to provide software ECC calculation and correction Refer to section 13 8 3 ECC Module Development Guide on page 193 and uC CRC s user manual for more information on ECC modules 180 Controller Layer The Micron ECC generic controller extension FS_NAND CtrlrGen MicronECC allows the use of internal on chip hardware ECC engines for some Micron NAND flash parts The extension has been designed as an example for the Micron MT29F1GO8ABADA but should function properly with other similar Micron devices with internal ECC hardware modules This module doesn t have any configuration options you should use DEF_NULL as the generic controller extension configuration pointer CtrlrExtCfg field of the FS NAND CTRLR GEN CFG structure 13 4 2 PART LAYER There are two different part layer implementations distributed with the NAND driver see Table 13 3 Driver API Files Description FS_NAND PartStati
331. settings If CPOL 0 the clock is low when inactive If CPOL 1 the clock is high when inactive If CPHA 0 data is read on the leading edge of the clock and changed on the following edge If CPHA 1 data is changed on the leading edge of the clock and read on the leading edge The most commonly supported settings are CPOL CPHA 0 0 and 1 1 B Slave select polarity The active level of the slave select may be electrically high or low Low is ubiquitous high rare SSEL 123 4 5 6 7 8 9 10 11 12 13 14 15 SCLK Command 0x SF NE mame SO Figure C 3 Example SPI transaction SE Response 0x20 454 A BSP is required that abstracts a CPU s SPI peripheral The port includes one code file named according to the following rubric FS DEV lt dev name gt BSP C or FS DEV lt dev name gt SPI BSP c This file is generally placed with other BSP files in a directory named according to the following rubric Micrium Software EvalBoards lt manufacturer gt lt board_name gt lt compiler gt BSP Several example ports are included in the uC FS distribution in files named according to the following rubric Micrium Software uC FS Examples BSP Dev NAND lt manufacturer gt lt cpu_name gt Micrium Software uC FS Examples BSP Dev NOR lt manufacturer g
332. should be zero FSVol Fmt formats a file system volume If the RAM disk is in volatile RAM it have no file system on it after it is opened Gt will be unformatted and must be formatted before a volume on it is opened If the RAM disk initialization succeeds the file system will produce the trace output as shown in Figure 11 1 if a sufficiently high trace level is configured See section E 9 Trace Configuration on page 507 about configuring the trace level 134 Terminal 1 0 Output Log file Off RAM DISK FOUND Sec Size 512 bytes Size 32768 secs FS_FAT_Fmt CREATING FILE SYSTEM Type FAT16 Sec size 512 B Clus size 2 sec Vol size 32767 sec Clus 16303 FATs SS FS_FAT_Open FILE SYSTEM FOUND Type FAT16 Sec size 512 B Clus size 2 sec Vol size 32767 sec Clus 16302 FATs s2 Ctrl codes Input Mode Buffer size 0 Figure 11 1 RAM disk initialization trace output Chapter 12 SD MMC Drivers SD Secure Digital cards and MMCs MultiMedia Cards are portable low cost media often used for storage in consumer devices Six variants as shown in Table 12 1 are widely available to electronic retail outlets all supported by SD MMC driver The MMCplus and SD or SDHC are offered in compatible large card formats Adapters are offered for the remaining devices so that these can fit in standard SD MMC card slots Two further products incorporating SD MMC technology are emergi
333. slation Layer Since the erase count information is stored in each block each erase count must be backed up somewhere else in the device prior to erasing a block Blocks that have their erase count backed up are called available blocks When the translation layer needs a new block it will always be taken from the available blocks table to make sure its erase count is not lost in the case of an unexpected power down All this functionality is embedded within the translation layer Using the software itself does not require a deep understanding of the mechanisms as they are all abstracted into a simpler easier to understand disk interface However understanding the internals can be useful to efficiently configure the translation layer 13 3 1 TRANSLATION LAYER CONFIGURATION The configuration of the NAND translation layer s dev nand must be done through two mechanisms First you need to specify driver wide configuration options in the configuration file fs dev nand efg h Then you need to configure the device specific options passed to the function FSDev_Open through a structure pointer You need to call FSDev_Open for each device you want to access and provide a proper device specific configuration for each of them DRIVER CONFIGURATION FILE The driver configuration file for the NAND translation layer is fs dev nand cfg h A template for this file is located in the following path Micrium Software uC FS Dev NAND Cfg Template
334. sses If a flag is clear not OR d in then that attribute will be clear In the example above the entry will be made read only i e not writable and will be visible G e not hidden since the WR and HIDDEN flags are not set in attrib Since there is no way to make files write only Oe not readable the RD flag should always be set 6 2 2 CREATING NEW FILES AND DIRECTORIES A new file can be created using FSFile Open or fs fopen if opened in write or append mode There are a few other ways that new files can be created most of which also apply to new directories The simplest is the FSEntry_Create function which just makes a new file or directory FSEntry_Create file txt lt file name FS_ENTRY_TYPE FILE lt means entry will be a file DEF_NO lt DEF_NO means creation NOT exclusive amp err lt return error If the second argument entry type is FS ENIRY TYPE DIR the new entry will be a directory The third argument excl indicates whether the creation should be exclusive If it is exclusive excl is DEF YES nothing will happen if the file already exists Otherwise the file currently specified by the file name will be deleted and a new empty file with that name created 91 Chapter 6 Similar functions exist to copy and rename an entry FSEntry_Copy dir sre txt lt source file name dir dest txt lt destination file name DEF_NO lt DEF_NO means creation not excl
335. sumes basically the same format for all card types Finally the CID card ID and CSD card specific data registers are read the only times long 132 bit responses are returned Multiple bit initialization often 4 bit when performed on a SD card further confirms that the 8 byte SCR register and 64 byte SD status can be read and that the bus width can be set in the BSP Though all current cards support 4 bit mode operation the SD BUS WIDTHS field of the SCR is checked before configure the card bus width Afterwards the 64 byte SD status is read to see whether the bus width change was accomplished When first debugging a port it may be best to force multi bit operation disabled by returning 1 from the BSP function FSDev SD Card BSP GetBusWidthMax 144 Power On on NON GO_IDLE_STATE Invalid command SEND_IF_COND 2 Invalid Vv command pees SD_SEND_OP_COND 3 y SEND_OP_COND 4 y y READ_OCR 5 v v MMC V1 x Standard Capacity SD card V2 0 Standard Capacity SD card Using the SD MMC CardMode Driver Valid command SD_SEND_OP_COND READ_OCR 9 CCS in response v V2 0 High Capacity SD card SEND_CID 6 SEND_CSD 7 Inactive state Idle State Figure 12 4 Simplified SD MMC cardmode initialization and state transitions 145 Chapter 12 146 Command GO_IDLE_ST
336. t are not part of the actual name lt architecture gt This is the name of the specific library and is generally associated with a CPU name or an architecture Vi k These are the library source files The names of the files are determined by the semiconductor manufacturer 34 Board Support Package BSP 3 3 BOARD SUPPORT PACKAGE BSP The BSP is generally found with the evaluation or target board because the BSP is specific to that board In fact if well written the BSP should be used for multiple projects Micrium Software EvalBoards lt manufacturer gt lt board name gt lt compiler gt BSP VW Micrium This is where we place all software components and projects provided by Micrium Software This sub directory contains all the software components and projects EvalBoards This sub directory contains all the projects related to evaluation boards lt manufacturer gt Is the name of the manufacturer of the evaluation board The lt and gt are not part of the actual name lt board name gt This is the name of the evaluation board A board from Micrium will typically be called uC Eval xxxx where xxxx will be the name of the CPU or MCU used on the evaluation board The lt and gt are not part of the actual name lt compiler gt This is the name of the compiler or compiler manufacturer used to build the code for the evaluation board The lt and
337. t lt cpu_name gt Micrium Software uC FS Examples BSP Dev SD SPI lt manufacturer gt lt cpu_name gt Check all of these directories for ports for a CPU if porting any SPI device the CPU may be been used with a different type of device but the port should support another with none or few modifications Each port must implement the functions to be placed into a FS_DEV_SPI_APT structure const FS DEV SPI API FSDev_ BSP SPI FSDev_BSP SPI Open FSDev_BSP SPI Close FSDev_BSP SPI Lock FSDev_BSP_ SPI Unlock FSDev_BSP SPI Rd FSDev_BSP SPI Wr FSDev_BSP SPI ChipSelEn FSDev_BSP SPI ChipSelDis FSDev_BSP SPI SetClkFreg ti The functions which must be implemented are listed and described in Table C 4 SPI is no more than a physical interconnect The protocol of command response interchange the master follows to control a slave is specified on a per slave basis Control of the chip select SSEL is separated from the reading and writing of data to the slave because multiple bus 455 Appendix C transactions e g a read then a write then another read are often performed without breaking slave selection Indeed some slaves AFTER the select has been disabled require bus transactions or empty clocks Function Description Open Open initialize hardware for SPI Close Close uninitialize hardware for SPI Lock Acquire SPI bus lock Unlock Release SPI bus lock Rd Read f
338. t device Low level unmount device Low level compact device Low level defragment device Release data in sector Read physical device Write physical device Read physical device page Write physical device page Erase physical device block Erase physical device Not all of these operations are valid for all devices The device driver TO Ctrl function is called while the caller holds the device lock The SD MMC cardmode protocol is unique to SD and MMC compliant devices The generic driver handles the peculiarities for initializing reading and writing a card including state transitions and error handling but each CPU has a different host controller that must be individually ported To that end a BSP supplementary to the general uC FS BSP is required that abstracts the SD MMC interface The port includes one code file FS DEV SD CARD BSP C following rubric This file is generally placed with other BSP files in a directory named according to the 425 Appendix C Micrium Software EvalBoards lt manufacturer gt lt board_name gt lt compiler gt BSP Several example ports are included in the uC FS distribution in files named according to the following rubric Micrium Software uC FS Examples BSP Dev SD Card lt cpu_name gt Function Description FSDev_SD Card BSP Open Open initialize SD MMC card interface FSDev SD Card BSP Close Close uninitialize SD MMC card int
339. t open FS ERR DEV NOT PRESENT Device is not present FS ERR DEV INVALID LOW FMT Device needs to be low level formatted FS ERR DEV IO Device I O error FS ERR DEV TIMEOUT Device timeout RETURNED VALUE None NOTES WARNINGS The device must be a NOR device e g nor 0 This function should not be used while a file system exists on the device or if the device is low level formatted unless the intent is to destroy all existing information 385 Appendix A A 12 FAT SYSTEM DRIVER FUNCTIONS void FS FAT JournalOpen CPU CHAR name vol FS ERR p err void FS FAT JournalClose CPU CHAR name vol FS ERR p err void FS FAT JournalStart CPU CHAR name vol FS ERR p err void FS FAT JournalStop CPU CHAR name vol FS ERR p err void FS FAT VolChk CPU CHAR name vol FS ERR p err 386 A 12 1 FS_FAT_JournalOpen File Called from Code enabled by fs fat journal c Application FS CFG FAT JOURNAL EN Open journal on volume ARGUMENTS name vol Volume name p err Pointer to variable that will the receive return error code from this function FS ERR NONE Journal opened FS ERR DEV Device access error RETURNED VALUE None NOTES WARNINGS None 387 Appendix A A 12 2 FS_FAT_JournalClose void FS FAT JournalClose CPU CHAR name vol FS ERR p err File Called from Code enabled by fs fat journal c Application FS CFG FAT JOURNAL EN C
340. tSecCnt FS VOL INFO File Used for fs_vol h Receives information about a volume MEMBERS State The volume state FS VOL STATE CLOSED FS VOL STATE CLOSING FS VOL STATE OPENING FS VOL STATE OPEN FS VOL STATE PRESENT FS VOL STATE MOUNTED DevState The device state FS DEV STATE CLOSED FS DEV STATE CLOSING FS DEV STATE OPENING FS DEV STATE OPEN FS DEV STATE PRESENT FS DEV STATE LOW FMT VALID Second argument of FSVol Query Volume is closed Volume is closing Volume is opening Volume is open Volume device is present Volume is mounted Device is closed Device is closing Device is opening Device is open but not present Device is present but not low level formatted Device low level format is valid 495 Appendix D DevSize The number of sectors on the device DevSecSize PartitionSize VolBadSecCnt VolFreeSecCnt VolUsedSecCnt VolTotSecCnt NOTES None 496 The size of each device sector The number of sectors in the partition The number of bad sectors on the volume The number of free sectors on the volume The number of used sectors on the volume The total number of sectors on the volume Appendix UC FS Configuration HC FS is configurable at compile time via approximately 30 defines in an application s fs cfg h file uC FS uses defines because they allow code and data sizes to be scaled at compile time based on enabled features I
341. te The creation timestamp of the file or directory DateAccess The last access date of the file or directory DateTimeWr The last write or modification timestamp of the file or directory 490 BlkCnt The number of blocks allocated to the file For a FAT file system this is the number of clusters occupied by the file data BlkSize The size of each block allocated in octets For a FAT file system this is the size of a cluster NOTES None 491 Appendix D D 7 FS_FAT_SYS CFG typedef struct fs fat sys cfg FS SEC OTY ClusSize FS FAT SEC NBR RsvdAreaSize CPU _INT16U RootDirEntryCnt CPU_INTO8U FAT Type CPU_INTO8U NbrFATs FS_FAT SYS CFG File Used for fs_fat_type h Second argument of FSVol_Fmt when opening a FAT volume optional A pointer to a FS FAT SYS CFG structure may be passed as the second argument of FSVol_Fmt It configures the properties of the FAT file system that will be created MEMBERS ClusSize The size of a cluster in sectors This should be 1 2 4 8 16 32 64 or 128 The size of a cluster in bytes must be less than or equal to 65536 so some of the upper values may be invalid for devices with large sector sizes RsvdAreaSize The size of the reserved area on the disk in sectors For FAT12 and FAT16 volumes the reserved should be 1 sector for FAT32 volumes 32 sectors RootDirEntryCnt The number of entries in the root directory This applies only to FAT12 and
342. te resources such as file objects may be depleted An example of reading a file is given in Listing 8 1 101 Chapter 8 void App Fnct void FS_FILE p file fs size t ent unsigned char buf 50 p file fs fopen file txt Zei Open file St if p file FS FILE 0 If file is opened 7 read from file S do cnt fs_fread amp buf 0 1 sizeof buf p file alse ere SO Hf APP TRACE INFO Read d bytes r n cnt while cnt gt sizeof buf eof fs feof p file Chk for EOF xf if eof 0 See Note 1 S App TRACE INFO Reached EOF r n else err fs_ferror p file Chk for error if err 0 See Note 2 APP TRACE INFO Read error r n fs fclose p file Close file else APP TRACE INFO Could not open file txt r n Listing 8 1 Example file read L8 1 1 To determine whether a file read terminates because of reaching the EOF or a device error removal the EOF condition should be checked using fs_feof L8 1 2 In most situations either the EOF or the error indicator will be set on the file if 102 the return value of fs fread is smaller than the buffer size Consequently this check is unnecessary File Access Functions 8 3 2 GETTING OR SETTING THE FILE POSITION Another common operation is getting or setting the file position The fs fgetpos and fs_fsetpos allow the applic
343. ted Figure 10 3 are either not allocated to a file or allocated to a file whose cluster chain is terminated by the 43rd entry To summarize a cluster s entry in the File Allocation Table typically contains a pointer to the entry for the next cluster in a file s cluster chain Other values that can be stored in a cluster s entry in the FAT are special markers for B End of cluster chain this cluster is the final cluster for a file B Cluster not allocated free cluster mark no file is using this cluster B Damaged cluster this cluster cannot be used NOTE Updating the FAT table is time consuming but updating it frequently is very important If the FAT table gets out of sync with its files files and directories can become corrupted resulting in the loss of data see See Optional Journaling System on page 127 121 Chapter 10 10 3 1 FAT12 FAT16 FAT32 The earliest version of FAT the file system integrated into MS DOS is now called FAT12 so called because each cluster address in the File Allocation Table is 12 bits long This limits disk size to approximately 32 MB Extensions to 16 and 32 bit addresses Oe FAT16 and FAT32 expand support to 2 GB and 8 TB respectively FAT version Pointer size Max size Free cluster Damaged End of cluster Table entry size of disk marker cluster marker chain marker FAT12 12 bits 32 MB 0 Oxff7 Oxff8 FAT16 16 bits 2GB 0 Oxfff7 Oxfff8 FAT32 32 bits 8 TB 0 OxOfff f
344. ter 3 erc_cfg h determines whether to enable assembly language optimization assuming there is an assembly language file for the processor and a few other defines lt architecture gt The name of the CPU architecture that uC CRC was ported to The lt and gt are not part of the actual name lt compiler gt The name of the compiler or compiler manufacturer used to build code for the pC CRC port The lt and gt are not part of the actual name ecc_hamming_a asm contains the assembly language functions to optimize the calculation speed of Hamming code edc_crce_a asm contains the assembly language functions to optimize the calculation speed of CRC cyclic redundancy checks Source This is the directory that contains all the CPU independent source code files of nC CRC 3 8 pC FS PLATFORM INDEPENDENT SOURCE CODE The files in these directories are available to uC FS licensees see Appendix H Licensing Policy Micrium Software uC FS APP Template fs_app c fs_app h Cfg Template fs_cfg h OS Template fs_os c fs_os h 42 LC FS Platform Independent Source Code Source fs_c fs h fs_api c fs_api h fs_buf c fs_buf h fs_cache c fs_cache h fs cfg fs h fs_ctr h fs_def h fs_dev c fs_dev h fs_dir c fs_dir h fs_entry c fs_entry h fs_err h fs_file c fs_file h fs_inc h fs_partition c fs_partition h fs_sys c fs_sys h fs_type h fs_unicode
345. th Open dir if p dir FS DIR 0 void fs readdir r pdir amp dirent amp p dirent Rd first dir entry if p dirent FS DIRENT 0 If NULL dir is empty APP TRACE INFO Empty dir s r n p cwd_path else Fmt info for each entry Str Copy str r r r 8 nz while p dirent struct dirent 0 Chk if file is dir SZ if DEF BIT IS SET dirent Info Attrib FS_ENTRY_ATTRIB DIR DEF YES str 0 dis Chk if file is rd only S 107 Chapter 8 if DEF BIT IS SET dirent Info Attrib FS ENTRY ATTRIB WR DEF YES str 2 w str 5 w str 8 w Get file size SZ if p dirent gt Info Size 0 if DEF BIT IS CLR dirent Info Attrib FS ENTRY ATTRIB DIR DEF YES Str_Copy amp str 11 Hm else Str_FmtNbr_Int32U dirent Info Size 10 10 0 DEF NO DEF NO amp str 11 Get file date time af if p dirent gt Info DateTimeCreate Month 0 Str_Copy amp str 22 CPU_CHAR App MonthNames dirent Info DateTimeCreate Month 1 Str_FmtNbr_Int32U dirent Info DateTimeWr Day 2 10 DEE NO DEF NO amp str 26 Str_FmtNbr_Int32U dirent Info DateTimeWr Hour 2 10 DEE MO DEF NO amp str 29 Str_FmtNbr_Int32U dirent Info DateTimeWr Minute 2 10 DEE NO DEF NO amp str 32 Output info for entry ad APP_TRACE INFO 3s3s r n str dirent Name Rd
346. that can be stored in the buffer label it does NOT include the final NULL character The buffer label MUST be of at least len max 1 characters 347 Appendix A A 7 10 FSVol_LabelSet void FSVol LabelSet CPU CHAR name vol CPU CHAR label FS ERR p err File Called from Code enabled by fs vol c Application Set volume label ARGUMENTS name vol Volume name not FS_CFG_RD ONLY EN label Volume label p err Pointer to variable that will receive the return error code from this function FS ERR NONE Label set FS ERR DEV CHNGD FS ERR NAME NULL FS ERR NULL PTR FS ERR DEV FS ERR DIR FULL FS ERR DEV FULL FS ERR VOL LABEL INVALID FS ERR VOL LABEL TOO LONG FS ERR VOL NOT MOUNTED FS ERR VOL NOT OPEN 348 Device has changed Argument name vol passed a NULL pointer Argument label passed a NULL pointer Device access error Directory is full space could not be allocated Device is full space could not be allocated Volume label is invalid Volume label is too long Volume is not mounted Volume is not open RETURNED VALUE None NOTES WARNINGS The label on a FAT volume must be no longer than 11 characters each belonging to the set of valid short file name SFN characters Before it is committed to the volume the label will be converted to upper case and will be padded with spaces until it is an 11 character string 349 Appendix A A 7 11 FSVol_Open void
347. the file E When fs flockfile is called if the lock count is zero OR the lock count is positive and the caller owns the file the lock count will be incremented and the caller will own the file Otherwise the caller will wait until the lock count returns to zero B Each call to fs funlockfile incremenets the lock count Matching calls to fs flockfile or fs_ftrylockfile and fs_funlockfile can be nested 244 A 2 12 fs_fopen FS FILE fs fopen const char name full const char str_mode File Called from Code enabled by fs_api c Application FS CFG API EN Open a file ARGUMENTS name full Name of the file See section 4 3 uC FS File and Directory Names and Paths on page 62 for information about file names str mode Access mode of the file RETURNED VALUE Pointer to a file if NO errors Pointer to NULL otherwise NOTES WARNINGS P The access mode should be one of the strings shown in section Table 6 2 fopenO mode strings and mode equivalents on page 86 E The character b has no effect E Opening a file with read mode fails if the file does not exist E Opening a file with append mode causes all writes to be forced to the end of file 245 Appendix A A 2 13 fs_fread fs size t fs fread void p dest fs size t size fs size t nitems FS FILE p file File Called from Code enabled by fs_api c Application FS CFG API EN Rea
348. the wC FS proprietary API FSFile FSDir 4 FSEntry_ H etc The best known API for accessing and managing files and directories is specified within the POSIX standard IEEE Std 1003 1 The basis of some of this functionality in particular buffered input output lies in the ISO C standard ISO IEC 9899 though many extensions provide new features and clarify existing behaviors Functions and macros prototyped in four header files are of particular importance E stdio h Standard buffered input output fopen fread etc operating on FILE objects E dirent h Directory accesses opendir readdir etc operating on DIR objects B unistd h Miscellaneous functions including working directory management chdir getcwd ftruncate and rmdir E sys stat h File statistics functions and mkdir HC FS provides a POSIX compatible API based on a subset of the functions in these four header files To avoid conflicts with the user compilation environment files functions and objects are renamed B All functions begin with fs For example fopen is renamed fs fopen opendir is renamed fs opendir getcwd is renamed fs_getcwd etc 95 Chapter 8 m All objects begin with FS So fs fopen returns a pointer to a FS FILE and fs_opendir returns a pointer to a FS_DIR B Some argument types are renamed For example the second and third parameters of fs fread are typed fs size t to avo
349. tion initiates this procedure and each subsequent call to FSDir Rd until all entries have been examined returns a FS DIRENT which holds information about a particular entry The FSDir Close function releases any file system structures and locks Function Description FSDir Open Open a directory FSDir_Close Close a directory FSDir_Rd Read a directory entry FSDir_IsOpen Determine whether a directory is open or not Table 7 1 Directory API functions These functions are almost exact equivalents to POSIX API functions the primary difference is the advantage of valuable return error codes to the application Directory Module Function FS_DIR FSDir Open CPU_CHAR FS_ERR void FSDir Close FS DIR void FSDir Rd FS_ERR FS_DIR FS_DIR_ENTRY FS_ERR p name full p err p dir ID PTEI p dir p dir entry p err POSIX API Equivalent FS DIR fs_opendir const char dirname int fs closedir FS_DIR dirp int fs readdir r FS_DIR dirp struct fs_dirent entry struct fs dirent result For more information about and an example of using directories see section 8 4 Directory Access Functions on page 107 94 Chapter POSIX API Important warning about the POSIX API The pC FS implementation of the POSIX API is not 100 compliant Most notably the errno error flag isn t set when an error occurs and thus it is recommended to use
350. tional 12 bytes stack space E 8 SD MMC SPI CONFIGURATION FS_DEV_SD SPI _CFG_CRC_EN Data blocks received from the card are accompanied by CRCs as are the blocks transmitted to the card FS DEV SD SPI CFG CRC EN enables CRC validation by the card as well as the generation and checking of CRCs If DEF ENABLED CRC generation and checking will be performed 506 E 9 TRACE CONFIGURATION The file system debug trace is enabled by define ing FS TRACE LEVEL in your application s fs cfg h define FS TRACE LEVEL TRACE LEVEL DBG The valid trace levels are described in the table below A trace functions should also be defined define FS TRACE printf This should be a printf type function that redirects the trace output to some accessible terminal for example the terminal I O window within your debugger or a serial port When porting a driver to a new platform this information can be used to debug the fledgling port Trace Level Meaning TRACE LEVEL OFF No trace TRACE LEVEL INFO Basic event information e g volume characteristics TRACE LEVEL DBG Debug information TRACE LEVEL LOG Event log Table E 9 Trace levels 507 Appendix E 508 Appendix Shell Commands The command line interface is a traditional method for accessing the file system on a remote system or in a device with a serial port be that RS 232 or USB A group of shell commands derived from standard UNIX equivalents are availab
351. to a 465 Appendix C const FS DEV NOR PHY API FSDev NOR FSDev_NOR PHY Open FSDev_NOR PHY Close FSDev_NOR PHY Rd FSDev_NOR_PHY_Wr FSDev_NOR_PHY_EraseBlk FSDev_NOR_PHY_IO Ctrl ti The functions which must be implemented are listed and described in Table C 5 The first argument of each of these is a pointer to a FS_DEV_NOR_PHY_ DATA structure which holds physical device information Specific members will be described in subsequent sections as necessary The NOR driver populates an internal instance of this type based upon configuration information Before the file system suite has been initialized the application may do the same if raw device accesses are a necessary part of its start up procedure Function Description Open Open initialize a NOR device and get NOR device information Close Close uninitialize a NOR device Rd Read from a NOR device and store data in buffer Wr Write to a NOR device from a buffer EraseBlk Erase block of NOR device IO Ctr1 Perform NOR device I O control operation 466 Table C 5 NOR flash physical layer driver functions C 9 1 Open void Open FS DEV NOR PHY DATA p phy data FS_ERR p err File Called from Code enabled by NOR physical layer driver FSDev_NOR_Open N A Open initialize a NOR device instance and get NOR device information ARGUMENTS p_phy data Pointer to NOR phy data p err Pointer to variabl
352. to release its resources Close will typically never be called The Setup function is called during the generic controllers own Setup function and provides an opportunity to setup some internal parameters according to the generic controllers operating conditions The generic controller s instance data is provided as an argument to this function The function must return the amount of required OOS storage space in octets ECC data for example The RdStatusChk function is called after a sector read operation by the generic controller s SecRd function It should determine if a read error has occurred and return an error accordingly The ECC_Calc function is called before a sector is written to the NAND device by the generic controllers SecWr function and provides an opportunity to calculate the ECC data and to append it to the OOS metadata The ECC_VerifyO function is called after a sector is read from the NAND device by the generic controllers SecRdO function It should read the ECC data from the OOS metadata verify the sector and OOS data integrity and correct any errors found if possible It should return an appropriate error code if ECC errors are found Development Guide 13 8 3 ECC MODULE DEVELOPMENT GUIDE Before undertaking the task of writing a software ECC module or a software interface to a hardware ECC module you should evaluate whether or not modifications to the controller layer are needed as well Some ha
353. troller layer driver interfaces with the NAND translation layer at the physical level block erase sector write read spare area write read operations The controller layer is also responsible for the placement of sectors and metadata within a NAND page Interfacing at this level allows more flexibility if your micro controller has dedicated hardware like an ECC calculation engine or a NAND flash memory controller you can interface directly with it by providing your own controller layer implementation instead of using the generic implementation see section 13 4 1 Generic Controller Layer Implementation on page 179 included with the NAND driver 167 Chapter 13 The controller extension layer is specific to the generic controller implementation s_dev nand ctrlr gen It provides an interface that allows different types of ECC calculation and correction schemes to be used while avoiding duplication of the generic controller code Implementations for software ECC and some Micron on chip ECC devices including MT29F1G08ABADA are provided with the NAND flash driver The BSP layer will implement code that depends on your platform and application for the specific controller layer implementation chosen In most cases you will need to develop your own implementation of the BSP layer The part layer is meant to provide the specifics for each part chip you use in your design to the controller and NAND translation layers This layer implement
354. turn error code from this function FS ERR NONE FS ERR NAME NULL FS ERR DEV FS ERR VOL NOT OPEN FS ERR PUE NONE AVAIL RETURNED VALUE None NOTES WARNINGS None Volume checked without errors Argument name vol passed a null pointer Device access error Volume not open No buffers available 391 Appendix A 392 Appendix UC FS Error Codes This appendix provides a brief explanation of nC FS error codes defined in fs_err h Any error codes not listed here may be searched in fs_err h for both their numerical value and usage B 1 SYSTEM ERROR CODES FS ERR NONE FS ERR INVALID ARG FS ERR INVALID CFG FS ERR INVALID CHKSUM FS ERR INVALID LEN FS ERR INVALID TIME FS ERR INVALID TIMESTAMP FS ERR INVALID TYPE FS ERR MEM ALLOC FS ERR NULL ARG FS ERR NULL PTR FS ERR OS FS ERR OVF FS ERR EOF FS ERR WORKING DIR NONE AVAIL FS ERR WORKING DIR INVALID B 2 BUFFER ERROR CODES FS ERR PUE NONE AVAIL No error Invalid argument Invalid configuration Invalid checksum Invalid length Invalid date time Invalid timestamp Invalid object type Mem could not be alloc d Arg s passed NULL val s Ptr arg s passed NULL ptr s OS err Value too large to be stored in type EOF reached No working dir avail Working dir invalid No buffer available 393 Appendix B B 3 CACHE ERROR CODES FS ERR CACHE INVALID MODE FS ERR CACHE INVALID SEC TYPE FS ERR CACHE TOO SMA
355. uch actions must meet the general expectations of an embedded environment a limited code footprint for instance while still delivering good performance 1 1 HC FS HC FS is a compact reliable high performance file system It offers full featured file and directory access with flexible device and volume management including support for partitions Source Code uC FS is provided in ANSI C source to licensees The source code is written to an exacting coding standard that emphasizes cleanness and readability Moreover extensive comments pepper the code to elucidate its logic and describe global variables and functions Where appropriate the code directly references standards and supporting documents Device Drivers Device drivers are available for most common media including SD MMC cards NAND flash NOR flash Each of these is written with a clear layered structure so that it can easily be ported to your hardware The device driver structure is simple basically just initialization read and write functions so that pC FS can easily be ported to a new medium 15 Chapter 7 Devices and Volumes Multiple media can be accessed simultaneously including multiple instances of the same type of medium since all drivers are re entrant DOS partitions are supported so more than one volume can be located on a device In addition the logical device driver allows a single volume to span several typically identical devices such as a ban
356. ucture of the CSD is defined in the SD Card Association s Physical Layer Simplified Specification Version 2 00 Section 5 3 2 vl x and v2 0 standard capacity or Section 5 3 3 v2 0 high capacity For MMC cards the structure of the CSD is defined in the JEDEC s MultiMediaCard MMC Electrical Standard High Capacity Section 8 3 367 Appendix A A 10 NAND DRIVER FUNCTIONS void FSDev_NAND LowFmt CPU_CHAR name dev FS_ERR p err void FSDev_NAND LowMount CPU_CHAR name dev FS_ERR p err void FSDev_NAND LowUnmount CPU_CHAR name dev FS_ERR p err 368 A 10 1 FSDev_NAND_LowFmt void FSDev NAND LowFmt CPU CHAR name_ dev FS_ERR p err File Called from Code enabled by fs_dev_nand c Application N A Low level format a NAND device ARGUMENTS name_dev Device name see Note p err Pointer to variable that will receive the return error code from this function FS ERR NONE Device low level formatted successfully FS ERR NAME NULL Argument name dev passed a NULL pointer FS ERR DEV INVALID Argument name dev specifies an invalid device FS ERR DEV NOT OPEN Device is not open FS ERR DEV NOT PRESENT Device is not present FS ERR DEV INVALID LOW FMT Device needs to be low level formatted FS ERR DEV IO Device I O error FS ERR DEV TIMEOUT Device timeout RETURNED VALUE None NOTES WARNINGS The device must be a NAND device eg nand 0 A NAND medium MUST b
357. uffer can be flushed to the storage device using fs fflush 99 Chapter 8 If a file is shared between several tasks in an application a file lock can be employed to guarantee that a series of file operations are executed atomically fs flockfile or its non blocking equivalent fs_ftrylockfile acquires the lock for a task Gf it does not already own it Accesses from other tasks will be blocked until a fs_funlockfile is called This functionality is available if FS CFG FILE LOCK EN is DEF ENABLED 8 3 1 OPENING READING AND WRITING FILES When an application needs to access a file it must first open it using fs_fopenO file pointer gt p file fs fopen file txt lt file name wt lt mode string if p file FS_FILE 0 Handle error The return value of this function should always be verified as non NULL before the application proceeds to access the file The first argument of this function is the path of the file if working directories are disabled this must be the absolute file path beginning with either a volume name or a V see section 4 3 uC FS File and Directory Names and Paths on page 62 The second argument of this function is a string indicating the mode of the file this must be one of the strings shown in the table below Note that in all instances the b binary option has no affect on the behavior of file accesses fs_fopen Mode String Read Wr
358. uld be the last occupied entry An extended partition begins with a partition table that has up to two entries typically The first defines a secondary partition which may contain a file system The second may define another extended partition in this case a secondary extended partition which can contain yet another secondary partition and secondary extended partition Basically the primary extended partition heads a linked list of partitions Primary Partition 1 256 MB Primary Partitition 2 128 MB oO S SS Primary EZ o Extended Partition d Si 512 MB D Secondary Secondary Partition Extended O Partition 4 Partition O 256 MB 256 MB hd Secondary O Partition O Partition 5 cl 256 MB Figure 5 7 Device with five partitions For the moment extended partitions are not supported in pC FS 75 Chapter 5 5 6 VOLUME OPERATIONS Five general operations can be performed on a volume A volume can be opened Gmounted During the opening of a volume file system control structures are read from the underlying device parsed and verified Files can be accessed on a volume A file is a linear data sequence file contents associated with some logical typically human readable identifier file name Additional properties such as size update date time and access mode e g read only write only read write may be
359. unction must write cnt octets on the bus with the CLE Command Latch Enable pin asserted ADDRESS WRITE FUNCTION The AddrWr function must write cnt octets on the bus with the ALE Address Latch Enable pin asserted DATA WRITE FUNCTION The DataWr function must write cnt octets on the bus with both ALE and CLE not asserted DATA READ FUNCTION The DataRd function must read cnt octets from the bus and store it starting from the p src address The ALE and CLE signals must not be asserted WAIT WHILE BUSY FUNCTION This function should block until the ready pin of the NAND device is in the appropriate state If for any reason this pin is not accessible you should call the poll fent with the poll fent arg as argument This poll function will verify if the NAND device is ready by polling the NAND device status instead Once the poll function returns DEF_YES the WaitWhileBusy can return without setting an error code If the time out limit is reached the function should return with an error code set to FS_ERR_DEV_TIMEOUT 190 Development Guide 13 8 2 GENERIC CONTROLLER EXTENSION DEVELOPMENT GUIDE The generic controller extension layer allows extending the generic controller through a number of hook functions that are used by the generic controller when flexibility in handling a specific operation is desirable A generic controller extension is defined through a structure of type FS _NAND CTRLR GEN EXT described in Listing 13 10
360. unit nbr Unit number of NOR RETURNED VALUE None NOTES WARNINGS This function will be called every time the device is closed 475 Appendix C C 10 3 FSDev_NOR_BSP_Rd_XX void FSDev_NAND BSP Rd 08 FS OTY unit nbr void p dest CPU _ADDR addr src CPU SIZE T ent void FSDev NAND BSP Rd 16 FS OTY unit nbr void p dest CPU _ADDR addr src CPU SIZE T ent File Called from Code enabled by fs dev nor ep NOR physical layer driver Read data from bus interface ARGUMENTS unit nbr Unit number of NOR p dest Pointer to destination memory buffer addr src Source address cnt Number of words to read RETURNED VALUE None NOTES WARNINGS N A Data should be read from the bus in words sized to the data bus for any unit only the function with its access width will be called 476 C 10 4 FSDev_NOR_BSP_RdWord_XX CPU INTO8U FSDev_NAND BSP RdWord 08 FS OTY unit nbr CPU ADDR addr src CPU INT16U FSDev NAND BSP RdWord 16 FS OTY unit nbr CPU ADDR addr src File Called from Code enabled by fs dev_nor_bsp c NOR physical layer driver N A Read data from bus interface ARGUMENTS unit_nbr Unit number of NOR addr src Source address RETURNED VALUE Word read NOTES WARNINGS Data should be read from the bus in words sized to the data bus for any unit only the function with its access width will be called 477 Appendix C C 10 5 FSDev_NOR_BSP_WrW
361. using pC OS II or pC OS HI you should include the appropriate ports in your project If you use another OS you should create your own port based on the template The functions that need to be written in this port are described here FS_OS_Init FS_OS_Lock and FS OS Unlock The core data structures are protected by a single mutex FS OS Init creates this semaphore FS OS Lock and FS OS Unlock acquire and release the resource Lock operations are never nested 404 FS OS DevInit FS OS DevLock and FS_OS DevUnlock File system device generally do not tolerate multiple simultaneous accesses A different mutex controls access to each device and information about it in RAM FS OS DevInit creates one mutex for each possible device FS OS DevLock and FS OS DevUnlock acquire and release access to a specific device Lock operations for the same device are never nested FS OS FileInit FS OS FileAccept FS OS FileLock and FS OS FileUnlock Multiple calls to file access functions may be required for a file operation that must be guaranteed atomic For example a file may be a conduit of data from one task to several If a data entry cannot be read in a single file read some lock is necessary to prevent preemption by another consumer File locks represented by API functions like FSFile LockGet and flockfile provide a solution Four functions implement the actual lock in the OS port FS OS FileInit creates one mutex
362. usive serr lt return error FSEntry Rename dir oldname txt lt old file name dir newname txt lt new file name DEF_NO lt DEF_NO means creation not exclusive amp err lt return error FSEntry_Copy can only be used to copy files The first two arguments of each of these are both full paths the second path is not relative to the parent directory of the first As with FSEntry Create the third argument of each excl indicates whether the creation should be exclusive If it is exclusive excl is DEF_YES nothing will happen if the destination or new file already exists 6 2 3 DELETING FILES AND DIRECTORIES A file or directory can be deleted using FSEntry Del FSEntry Del dir lt entry name FS ENTRY TYPE DIR lt means entry must be a dir amp err lt return error The second argument entry type restricts deletion to specific types If it is FS ENIRY TYPE DIR then the entry specified by the first argument must be a directory if it is a file an error will be returned If it is FS ENTRY TYPE FILE then the entry must be a file If it is FS ENTRY TYPE ANY then the entry will be deleted whether it is a file or a directory 92 Chapter Directories An application stores information in a file system by creating a file or appending new information to an existing file At a later time this information may be retrieved by reading the file However if a certain file m
363. ust be found or all files may be listed the application can iterate through the entries in a directory using the directory access or simply directory functions The available directory functions are listed in Table 6 1 A separate set of directory operations or entry functions manage the files and directories available on the system Using these functions the application can create delete and rename directories and get and set a directory s attributes and date time More information about the entry functions can be found in section 6 2 Entry Access Functions on page 89 The entry functions and the directory Open function accept one or more full directory paths For information about using file and path names see section 4 3 uC FS File and Directory Names and Paths on page 62 The functions listed in Table 7 1 are core functions in the directory access module FSDir functions These are matched by API level functions that correspond to standard C or POSIX functions More information about the APl level functions can be found in Chapter 8 POSIX API on page 95 The core and API functions provide basically the same functionality the benefits of the former are enhanced capabilities a consistent interface and meaningful return error codes 93 Chapter 7 7 1 DIRECTORY ACCESS FUNCTIONS The directory access functions provide an API for iterating through the entries within a directory The FSDir Open func
364. v nor bsp c RAMDisk fs_dev_ram c fs_dev_ram h sD fs_dev_sd c fs_dev_sd h Card fs_dev_sd_card c fs_dev_sd_card h BSP Template fs_dev_sd_card_bsp c SPI fs_dev_sd_spi c fs_dev_sd_spi h BSP Template fs_dev_sd_spi bsp c Template fs_dev_template c fs_dev_template h Micrium This directory contains all software components and projects provided by Micrium Software This sub directory contains all the software components and projects uc FS This is the main nC FS directory 48 uC FS Memory Device Drivers Dev This is where you will find the device driver files for the storage devices you are planning on using MSC This directory contains the MSC Mass Storage Class USB drives driver files fs_dev_msc are device driver for MSC devices This driver is designed to work with uC USB host stack For more details on this driver please refer to Chapter 15 MSC Driver on page 219 NAND This directory contains the NAND driver files fs_dev_nand are the device driver for NAND devices These files require a set of controller layer functions defined in a file named fs_dev_nand_ctrlr_ lt type gt as well as BSP functions specific to particular hardware and associated with chosen controller layer to be defined in a file named fs_dev_nand_ctrlr_ lt type gt _bsp c Note that in the case of the generic controller layer implementation some controller extensions files defined in files n
365. validate void FSVol CacheInvalidate CPU CHAR name_vol FS ERR p err File Called from Code enabled by fs vol c Application FS CFG CACHE EN Invalidate cache on a volume ARGUMENTS name vol Volume name p err Pointer to variable that will receive return error code from this function FS ERR NONE Cache created FS ERR NAME NULL name vol passed a NULL pointer FS ERR DEV CHNGD Device has changed FS ERR VOL NO CACHE No cache assigned to volume FS ERR VOL NOT OPEN Volume not open FS ERR VOL NOT MOUNTED Volume not mounted RETURNED VALUE None NOTES WARNINGS None 359 Appendix A A 8 3 FSVol_CacheFlush void FSVol CacheFlush CPU CHAR name vol FS ERR p err File Called from Code enabled by fs vol c Application FS CFG CACHE EN Flush cache on a volume ARGUMENTS name vol Volume name p err FS ERR NONE FS ERR NAME NULL FS ERR DEV CHNGD FS ERR VOL NO CACHE FS ERR VOL NOT OPEN FS ERR VOL NOT MOUNTED FS ERR DEV INVALID SEC NBR FS ERR DEV INVALID 1OW FMT FS ERR DEV IO FS ERR DEV TIMEOUT FS ERR DEV NOT PRESENT RETURNED VALUE None NOTES WARNINGS None 360 Pointer to variable that will receive return error code from this function Cache created name vol passed a NULL pointer Device has changed No cache assigned to volume Volume not open Volume not mounted Sector start or count invalid Device needs to be low level form
366. ver N A Enable disable device chip select ARGUMENTS unit nbr Unit number of device RETURNED VALUE None NOTES WARNINGS The chip select is typically active low To enable the device the chip select pin should be cleared to disable the device the chip select pin should be set 463 Appendix C C 7 7 SetCikFreq void FSDev BSP SPI SetClkFreq FS OTY unit nbr CPU INT32U freq File Called from Code enabled by fs dev lt dev name gt bsp c Device driver N A Set SPI clock frequency ARGUMENTS unit nbr Unit number of device RETURNED VALUE None NOTES WARNINGS The effective clock frequency must be no more than freq If the frequency cannot be configured equal to freq it should be configured less than freq C 8 NAND FLASH PHYSICAL LAYER DRIVER The information about porting the NAND driver to a new platform through either a controller layer implementation or a generic controller BSP is available in Chapter 13 NAND Flash Driver on page 159 C 9 NOR FLASH PHYSICAL LAYER DRIVER The NOR driver is divided into three layers The topmost layer the generic driver requires an intermediate physical layer driver to effect flash operations like erasing blocks and writing octets The physical layer driver includes one code header file pair named according to the following rubric FS DEV NOR lt device name gt C 464 FS DEV NOR lt device_name gt H A non uniform flas
367. vices interfaced on an MCU s external memory bus Table 13 1 Controller layer implementations provided Of course it is possible that your specific device and or micro controller requires a different controller layer implementation or that a different implementation could take advantage of hardware modules like a memory controller on a MCU Please refer to the section 13 8 4 Controller Layer Development Guide on page 194 for the details on how to implement your own controller layer 178 Controller Layer 13 4 1 GENERIC CONTROLLER LAYER IMPLEMENTATION The generic controller layer driver is an implementation of the controller layer that is compatible with most parallel NAND devices and most simple memory controllers It has the following features Supports multiple sector per page Packs out of sector OOS metadata around reserved spare area zones Extensible through extensions that provides multiple hooks to allow for different ECC protection schemes an extension for software ECC is provided Supports reading ONFI parameter pages through a its IO_Ctr1 function Supports both 8 bit and 16 bit bus devices The generic controller driver imposes a specific page layout the sectors are stored sequentially in the main page area and OOS metadata zones are stored sequentially in the spare area packed in the free spare zones specified by the FreeSpareMap field of the associated FS PART DATA data structure An example
368. w Unless otherwise specified any unset bit in the defect mark indicates a defective block A byte refers to an 8 bit value a word refers to a 16 bit value and a location is a bus width wide value byte for 8 bit bus and word for 16 bit bus DEFECT SPARE L 1 PG 1 OR N ALL 0 the defect mark is in the first location of the spare area first byte or first word depending on bus width of the first or last page If the mark reads 0 the block is defective DEFECT SPARE ANY PG 1 OR N ALL 0 any location in the spare area or the first or last page equal to 0 indicates a defective block first word of the spare area depending on bus width of the first or second page DEFECT SPARE L 1 PG 1 OR 2 the defect mark is the first location in the spare area of the first or second page or the first word of the spare area depending on bus width of the first page DEFECT PG L 1 OR N PG 1 OR 2 the defect mark is the first or last location of the page area in the first or second page Maximum number of bad blocks within a single device during its lifetime Maximum number of erase operations that can be performed on a single block Pointer to the map of the free regions in the spare area see Listing 13 6 Listing 13 6 shows the data type used to specify the contiguous regions of the spare area that are available for the NAND driver to write The map of the free regions is an array of FS_NAND FREE SPARE DATA values Each free contiguous sect
369. ways provides sector abstraction and performs wear leveling to make certain all blocks are used equally Below this the physical layer driver implements a particular command set to read and program the flash and erase blocks Lastly a BSP implements function to initialize and unitialize the bus interface Device commands are executed by direct access to the NOR at locations appropriately offset from the configured base address NOR Driver fs_dev_nor c h Provides generic driver interface e g init read write and performs wear leveling so all blocks are used equally Physical Layer Driver fs_dev_nor_amd_1x16 fs der nor cf _intel fs dev nor cf sei Implements particular NOR flash command set accesses NOR directly on bus interface Bus interface BSP fs dev nor _bsp c Initialize uninitial ize bus interface Figure 14 2 NOR driver architecture parallel NOR flash 14 3 2 HARDWARE Parallel NOR devices typically connect to a host MCU MPU via an external bus interface EBD with an 8 or 16 bit data lines and 20 or more address lines depending on the device size Many silicon vendors offer parallel NOR product lines most devices currently marketed are conformant to the Common Flash Interface CFI A set of query information allows the pC FS NOR driver physical layer drivers to interface with almost any NOR flash without configuration or modification The standard query information provides the following deta
370. wer failure 1 4 CHAPTER CONTENTS Figure 1 1 shows the layout and flow of the book This diagram should be useful to understand the relationship between chapters The first leftmost column lists chapters that should be read in order to understand uC F9 s structure The chapters in the second column give greater detail about the application of uC FS Each of the chapters in the third column examines a storage technology and its device driver Finally the fourth column lists the appendices the topmost being the uC FS reference configuration and porting manuals Reference these sections regularly when designing a product using uC FS A ucies Apt Reference Manual g B uC FS Introduction E Codes uC FS 2 C HCIFS Architecture Porting Manual UC FS Directories 3 SE 11 D WIES ele Driver Types and Files Structures 4 SC 12 E uC FS Useful Information Dri Configuration Ver Manual 11 9 13 B GE FAT NAND Flash Volumes File System Driver 14 F Device NOR Flash F SE Drivers Driver Commands 7 Mass Storage 15 Directories Class MSC Driver 8 G POSIX Bibliography API Figure 1 1 C FS book layout 18 Chapter Contents Chapter 1 Introduction This chapter Chapter 2 uC FS Architecture This chapter contains a simplified block diagram of the various different pC FS modules and their relationships The relationships are then explained
371. ze 6 FS_NAND BLK QTY BlkCnt 7 FS_NAND BLK QTY BlkIxFirst 8 FS_NAND UB QTY UB_CntMax 9 CPU_INTO8U RUB_MaxAssoc 10 CPU_INTO8U AvailBlkTblEntryCntMax 11 FS_NAND CFG 113 301 L13 3 2 L13 3 3 L13 3 4 L13 3 5 L13 3 6 176 Listing 13 3 NAND translation layer configuration structure This field must be set to a pointer to the controller specific BSP layer implementation s API you want the controller layer to use see section 13 5 Board Support Package Generic Controller on page 185 If you use a different controller layer implementation that field might not be needed This field must be set to a pointer to the controller layer implementation s API you wish to use see section 13 4 Controller Layer on page 178 This field must be set to a pointer to the configuration structure for the specified controller layer implementation This field must be set to a pointer to the part layer implementation s API you wish to use see section Listing 13 10 API structure type for generic controller extension on page 191 This field must be set to a pointer to the configuration structure specific to the chosen part layer implementation This field must contain the sector size for the device care must be taken when choosing sector size see section 13 7 Performance Considerations on page 187 The value FS NAND CFG DEFAULT instructs the translation layer to use the page size reporte
Download Pdf Manuals
Related Search
Related Contents
LE D T V - Voelkner HTC-201 Installation Manual Maxtor Serial ATA Hard Drive Installation Guide, Multilingual 足受けボード Guida dell`utente HP 15 15-g137ds LAMP 法用プライマーセット L. londiniensis 取扱説明書 WILBURY AXLE Operational Service Manual Intelligent Door Peephole Viewer User Manual MEB-3810N 取扱説明書 Copyright © All rights reserved.
Failed to retrieve file