 yaffs original specification yaffs original specification yaffs yet another flash file system  version 3 charles manning and wookey december 2001   revision history v00 201201 first draft v01 110102 minor corrections cosmetics change use of data status byte v02 280102 added observations about inodes file headers and hard links v03 260202 w added some general observations on compatibility partitions and bootloading  scope the purpose of this document is to outline a potential nandfriendly file system for linux background there are already various flashfile systems ffss or block drivers for flash on top of which a regular fs runs there are pros and cons with all of these flash memory has quite a few constraints which will not be addressed here various approaches are available to work around these constraints to provide a file system it is important to recognise that flash includes both nor and nand flash which have different sets of constraints it is easy to be mislead by the generic term flash into thinking that approaches appropriate for nor flash are immediately suitable for nand flash the nand block drivers eg smartmedia currently not available for linux and diskonchip nftl typically use fat16 as the file system this isn t too robust and nor is it that flashfriendly these block drivers provide a logical to physical mapping layer to emulate rewritable blocks that look like disk sectors when used with fat16 these file systems work reasonably well they have a low memory footprint and scale well like all fat based systems they are prone to corruption lost clusters etc the other approach is to design an entire file system which does not work through a block driver layer and is flashfriendly this allows more scope to work around issues currently two linux file systems that support nor flash very well are jffs and its derivative jffs2 both of these are based on the principles of journaling hence the leading j which significantly increases robustness a particularly important feature in embedded systems unfortunately neither of these file systems scale particularly well in both boot time and ram usage scaling is particularly relevant when one considers that a 16mb nor array would be considered large while a 128mb nand is available as a single chip jffs requires a rambased jffsnode structure for each journalling node in the flash each of these nodes is 48 bytes jffs2 makes a significant improvement here by reducing the equivalent structure jffs2rawnoderef to 16 bytes still at say an average nodesize of 512 bytes a 128mb nand might need 250000 of these 4mb both jffs and jffs2 require scanning the flash array at boot time to find the journaling nodes and determine the file structures since nand is large slow serially accessed and needs ecc this does not scale well and will take an unacceptably long boot time for the target systems as a thumbsuck the scanning of a 128mb nand array might take approx 25 seconds the intentions of the design sketched here are be nandflash friendly robustness through journaling strategies significantly reduce the ram overheads and boot times associated with jffsx this fs is intended primarily for internal nand rather than removable nand sm cards on removable sm cards smartmedia compatibility is likely to be important so sm fat will normally be used although of course yaffs makes a lot of sense if reliability is more important than compatibility overview here follows a simplified overview of yaffs yaffs uses a physical flash format similar to smartmedia this is done for various reasons some of the formatting eg placement of bad block markers is determined by the nand manufacturers and can t be changed potential to reuse code if it ain t broke don t fix some of the fields are obviously different to reflect the different usage despite the similarities yaffs is not actually compatible with sm fat sm cards need to be reformatted to switch from using sm fat to yaffs or vice versa file data is stored in fixed size chunks consistent with the size of a page ie 512 bytes each page is marked with a file id and chunk number these tags are stored in the spare data region of the flash the chunk number is determined by dividing the file position by the chunk size when data in a file is overwritten the relevant chunks are replaced by writing new pages to flash containing the new data but the same tags the overwritten data is marked as discarded file headers are stored as a single page marked so as to be differentiated from data pages pages are also marked with a short 2 bit serial number that increments each time the page at this position is incremented the reason for this is that if power loss crash other act of demonic forces happens before the replaced page is marked as discarded it is possible to have two pages with the same tags the serial number is used to arbitrate a block containing only discarded pages termed a dirty block  is an obvious candidate for garbage collection otherwise valid pages can be copied off a block thus rendering the whole block discarded and ready for garbage collection in theory you don t need to hold the file structure in ram you could just scan the whole flash looking for pages when you need them in practice though you d want better file access times than that the mechanism proposed here is to have a list of u16 page addresses associated with each file since there are 218 pages in a 128mb nand a u16 is insufficient to uniquely identify a page but is does identify a group of 4 pages a small enough region to search exhaustively this mechanism is clearly expandable to larger nand devices within reason the ram overhead with this approach is approx 2 bytes per page 512kb of ram for a whole 128mb nand boottime scanning to build the file structure lists should require just one pass reading nand since only the the spare data needs to be read this should be relatively fast approx 3 seconds for 128mb improvements can be achieved by partitioning the nand ie mount the critical partition first then mount the data partition afterwards various runtime improvements can be achieved by changing the chunk size to 1024 bytes or more however this would likely reduce flash efficiency as always life is a compromise  spare area details the following table summarizes the layout of the spare area of each page byte smartmedia usageyaffs usage 511 data data either file data or file header depending on tags 512515 reserved tags 516 data status byte not used in sm code from samsung data status byte if more than 4 bits are zero then this page is discarded 517 block status byte block status byte 518519 block address tags 520522 ecc on second 256 bytes part of data ecc on second 256 bytes of data 523524 block address tags 525527 ecc on first 256 bytes part of data ecc on first 256 bytes part of data the block status is a reserved value that shows whether the block is damaged the data status tracks whether the page is valid if less than 4 bits are zero then the page is valid otherwise it is discarded there are 8 bytes 64 bits for use by yaffs tags this is partitioned as follows number of bitsusage 18 18bit file id ie limit of 218 over 260000 files file id  is not valid and indicates a deleted page file id 0x3ffff i is also not valid 2 2bit serial number 20 20bit page id within file limit of 220 pages per file ie over 500mb file max size page id  means the file header for this file 10 10bit counter of the number of bytes used in the page 12 12bit ecc on tags 2 unused keep as 1 64 total  a bit of explanation on the usage of some of these fields file id is synonymous with inode the serial number is incremented each time a page with the same fileid pageid is rewritten because of data changes or copy during garbage collection when a page is replaced there is a brief period during which there are two pages with the same id the serial number resolves this since there should never be a difference of less than more than one a twobit counter is sufficient to determine which is the current page when the page is rewritten the file id these data status byte and the 12bit ecc are all written to zero the byte counter indicates how many bytes are valid in this page since the page would not exist if it contains zero bytes this field should thus hold 512 for all pages except the last page in the file the use of counters means that the file length integrity is preserved while the file is open without having to constantly update the file length in the file header the file header only needs to be refreshed when the file is closed rather than whenever it is appended to this field is wide enough to allow expansion to 1024byte chunks file headers come in two flavours file info the mode ower id group id length the hard link s that refers to the file a directory also appears as a file ie has an inode and hard link s but has no data the 12bit ecc applies to only the tag data uses a similar algorithm to the 22bit eccs used for file system data they are kept independent ram data details block management details are reasonably obvious and i feel don t need to be addressed here apart from stating that there will be a structure to track block status eg number of pages in use failed blocks and which are candidates for garbage collection etc the files need an indexing structure of sorts to locate and track the pages in the file some sort of tree structure should work rather well the lookup needs to be quite efficient in both cpu time and space page allocation and garbage collection pages are allocated sequentially from the currently selected block when all the pages in the block are filled another clean block is selected for allocation at least two or three clean blocks are reserved for garbage collection purposes if there are insufficient clean blocks available then a dirty block ie one containing only discarded pages is erased to free it up as a clean block if no dirty blocks are available then the dirtiest block is selected for garbage collection garbage collection is performed by copying the valid data pages into new data pages thus rendering all the pages in this block dirty and freeing it up for erasure i also like the idea of selecting a block at random some small percentage of the time thus reducing the chance of wear differences relative to nor nand writes and erases very fast therefore garbage collection might be performed ondemand eg during a write without significant degradation in performance alternatively garbage collection might be delegated to a kernel tasklet relative to jffsx the garbage collection presented here is incredibly simple thanks mainly to the use of fixedsize pages instead of journaling nodes flash writing as presented here yaffs only writes to the page s data area once and to the spare area twice once when new page is written and once when it gets stomped on before an erasure this is within the limits of the most restrictive nand flashes wear levelling no wear levelling is explicitly used here instead we rely on two strategies reserving some blocks to cater for failure you need to do this anyway with nand the main purpose behind wear levelling is to prevent some blocks getting more wear and failing since we expect and handle failure this is no longer as important the infrequent random block selection should prevent lowwear blocks getting stuck  partitioning partitioning is not included in this spec but could be added if required bootloading bootloaders cannot just read files direct from nand due to the high probability of bad blocks because yaffs is quite simple it will be relatively straightforward for bootloaders to read from it eg reading a kernel  conclusion yaffs is very simple it is also nandfriendly is relatively frugal with resources especially ram and boots quickly like jffsx it has journaling which makes it far more robust than fat while it might seem highrisk to develop yaffs it is probably about the same amount of effort as implementing changes to jffs to get it to work effectively within the constraints of nand a resulting jffsx system would still require significant amounts of ram and have long boot times while yaffs is indeed a new file system internally much of the file system glue code including inode management link management etc can likely be stolen from jffsx yaffs development notes build options yaffs can be built as either a kernel module ie a linux file system or as an application of course the goal is to build yaffs as a file system running on top of real nand flash but yaffs can be built to run on a ram emulation layer for inkernel testing without nand flash in the system building as an application allows the yaffsguts algorithms to be tested debugged in a more friendly debugging environment the test harness is in yaffsdevc trying it out yaffs can be built to run with either mtd or ram emulation or both the file system that interfaces to mtd is called yaffs  the file system that uses internal ram is called yaffsram  yaffs simultaneously supports both if they are enabled hack the makefile and change the kerneldir define to your kernel directory if you don t have mtd support in your kernel then you might need to turn off usemtd otherwise the yaffs module might not load type make clean make to build yaffs load yaffs as a module by typing  sbin insmod yaffso  ya gotta be root create a mount point eg mkdir mnt y to mount the ram emulation version of yaffs  mount t yaffsram none mnt y alternatively to mount the mtd version of yaffs  mount t yaffs dev mtd0 mnt y   yaffs data structures all data types are defined in yaffsgutsh yaffs uses the following major objects yaffsobject a yaffsobject can be a file directory symlink or hardlink the yaffsobjects know about their corresponding yaffsobjectheader in nand and the data for that object yaffsobjects also bind together the directory structure as follows parent pointer to the yaffsobject that is a parent of this yaffsobject in the directory structure siblings this field is used to link together a list of all the yaffsobjects in the same directory children if the object is a directory then children holds the head of the list of objects in the directory yaffstnode yaffstnodes form a tree structure that speeds up the search for data chunks in a file as the file grows in size the levels increase the tnodes are a constant size 32 bytes level  ie the lowest level comprise 16 2byte entries giving an index used to search for the chunkid tnodes at other levels comprise 8 4byte pointer entries to other tnodes lower in the tree yaffsdevice this holds the device context and is in some ways analogous to the vfs superblock it stores the data used to access the mtd as well as function pointers to access the nand data the tnodes and objects are allocated in groups to reduce memory allocation freeing overheads freed up tnodes and objects are kept in a free list and reused yaffsobject  struct yaffsobjectstruct u8 fake 1 a fake object has no presence on nand u8 renameallowed 1 are we allowed to rename it u8 unlinkallowed 1 are we allowed to unlink it u8 dirty 1 the object needs to be written to flash u8 valid 1 when the file system is being loaded up this object might be created before the data is available ie file data records appear before the header u8 serial serial number of chunk in nand store here so we don t have to read back the old one to update u16 sum sum of the name to speed searching struct yaffsdevicestruct mydev the device i m on struct listhead hashlink list of objects in this hash bucket struct listhead hardlinks all the equivalent hard linked objects live on this list directory structure stuff struct yaffsobjectstruct parent my parent directory struct listhead siblings siblings in a directory also used for linking up the free list where s my data in nand int chunkid where it lives u32 objectid the object id value u32 stmode protection u32 stuid user id of owner u32 stgid group id of owner u32 statime time of last access u32 stmtime time of last modification u32 stctime time of last change yaffsobjecttype varianttype yaffsobjectvariant variant obvious stuff skipped fake renameallowed unlinkallowed are special flags for handling fake objects which live in the file system but do not live on nand currently there are only two such objects the root object and the lost found directory none of these may be renamed or unlinked serial sum see yaffsobjectheader dirty indicates that the object s contents has changed and a new yaffsobjectheader must be written to flash valid indicates that the object has been loaded up this is only used during scanning yaffsscan since we can know of an object s existance and thus need to create the object header before we encounter the associated yaffsobjectheader hashlink is a list of objects in the same hash bucket the four variants hold extra info files hold the file size and the top level and pointer to the tnode tree for the file directories hold a list of children objects symlinks hold a pointer to the alias string this is probably inefficient but that probably does not matter since we don t expect to see many of these hardlinks hold information to identify the equivalent object  file structure tnodes  file structures are done with a tiered indexing structure the file structure is maintained by a tree structure depending where it is in the tree each tree node  tnode  the blue things holds either if it is at the lowest level then 16 u16s which identify the page if it is at a higher level ie an internal tnode then 8 pointers to lowestlevel tnodes when the file starts out it is assigned only one lowlevel tnode when the file expands past what a single tnode can hold then it is assigned a second tnode and an internal node is added to point to the two tnodes as the file grows more lowlevel tnodes and high level tnodes are added traversing the tnode tree to find a particular page in a file is quite simple each internal tnode is selected from by using 3 bits of the page offset in the file the level  page resolves 4 bits for example finding page 0x235 ie the one starting at file position 0x46800 would proceed as follows 0x235 is 1000110101 partitioned as follows 1000110101 levelbitsselected value 3 or more if they exist 10 zero 2 9 to 7 100 binary 4 1 6 to 4 11 binary 3  3 to  101 binary 5 free tnodes are stored in a list when the list is exhausted more are allocated each tnode takes 32 bytes each file needs at least one level  tnode how many do we need a full 16mb file system needs at least 16mb 51216 2000 level zero tnodes more for internal tnodes more for files smaller than optimal the tree grows as required when the file is resized to a smaller size then it is pruned  nand data data is stored on nand in chunks currently each chunk is the same size as a nand flash page ie 512 bytes 16 byte spare in the future we might decide to allow for different chunk sizes chunks can hold either a yaffsobjectheader this is the way a yaffsobject gets stored on nand a chunk of file data the 16 byte spare area contains 8 bytes of tags 6 bytes of ecc data 1 byte block status used to identify damaged blocks 1 byte data status currently unused the tags are made up as follows typedef struct unsigned chunkid 20 chunk number in file unsigned serialnumber 2 serial number for chunk unsigned bytecount 10 number of bytes of data used in this chunk unsigned objectid 18 the object id that this chunk belongs to unsigned ecc 12 ecc on tags unsigned unusedstuff 2 unused yaffstags a chunkid of zero indicates that this chunk holds a yaffsobjectheader a non zero value indicates that this is a data chunk and the position of the chunk in the file ie the first chunk at offset  has chunkid 1 see yaffsgutsc yaffsscan to see how this is done when a chunk is replaced eg file details changed or a part of a file was overwritten the new chunk is written before the old chunk is deleted this means that we don t lose data if there is a power loss after the new chunk is created but before the old one is discarded but it does mean that we can encounter the situation where we find both the old and the new chunks in flash the serialnumber is incremented each time the chunk is written 2 bits is sufficient to resolve any ambiguity bytecount applies only to data chunks and tells how many of the data bytes are valid objectid says which object this chunk belongs to ecc is used to perform error correction on the tags another ecc field is used to error correct the data  yaffsobjectheader typedef struct yaffsobjecttype type apply to everything int parentobjectid u16 sum checksum of name char name yaffsmaxnamelength 1 thes following apply to directories files symlinks not hard links u32 stmode protection u32 stuid user id of owner u32 stgid group id of owner u32 statime time of last access u32 stmtime time of last modification u32 stctime time of last change file size applies to files only int filesize equivalent object id applies to hard links only int equivalentobjectid alias only applies to symlinks char alias yaffsmaxaliaslength 1 yaffsobjectheader a yaffsobjectheader is stored in nand for every yaffsobject type holds the type of yaffsobject file directory hardlink or symlink parentobject is the objectid of this object s parent name holds the object s name together these form the directory structure of the file system also worth mention is sum this is a checksum on the name which speeds directory searching ie when searching the directory we only compare the name for those entries where sum matches obvious stuff skipped equivalentobjectid is used by hardlinks a hardlink to an object uses this field to specify the object that this links to this way of doing things is a bit different than the normal linux way of doing things ie keeping the links distinct from the inode but is simpler and uses less space except for a few corner cases with hardlinks alias is used by symlinks to hold the symlink alias string this limits the size of the symlink alias in future we should expand yaffs to use data chunks to store aliases too long to fit into the yaffsobjectheader  nand interface all nand access is performed via four functions pointed to by yaffsdevice at the moment a chunk is a page int writechunktonand struct yaffsdevicestruct dev int chunkinnand const u8 data yaffsspare spare int readchunkfromnand struct yaffsdevicestruct dev int chunkinnand u8 data yaffsspare spare int eraseblockinnand struct yaffsdevicestruct dev int blockinnand int initialisenand struct yaffsdevicestruct dev in the readxxx and writexxx functions the data and or spare pointers may be null in which case these data transfers are ignored a quick note about nand nand is not random access but page oriented thus we do all reads writes in pages each nand page holds 512 bytes of data and 16 spare bytes yaffs structures the spare area with tags used to identify what is stored in the data area there are 32 such pages to a block nand writes will only change 1 bits to  eg if a byte holds 10110011 and you write 11011010 to it you will get the logical and of the two values 10010010 the only way to get 1s again is to erase the entire block you may only write to a page a few times before erasing the entire block yaffs lives within these limitations each page only gets written to twice once when written and once when discarded ecc is normally used with nand to correct for single bit errors yaffs applies the ecc itself so the mtd should not do this the current mtd interfaces are not particularly well suited to yaffs and we will address the issue with the mtd group the mtd interface does not support pageoriented read write which yaffs would prefer  mkyaffs mkyaffs is the tool to format a nand mtd to be used for yaffs this is quite simple just erase all the undamaged blocks yaffs treats erased blocks as free empty space  expected performance the following numbers should give an indication of the performance we should expect from yaffs as an example i ll use the following numbers since the hardware is capable of 50ns read write these numbers allow for some other ovberheads clearly though the performance can be degraded in various ways seek10us page read 100ns byte write 100ns byte program 200us page erase 2ms block from this we can derive some higherlevel numbers operationtimecalculation read spare 12us seek 16 read read page 63 us seek 528 read write page 326 us seek 528 write program read page for verification discard page 212 us seek 16 write program overwrite page 538 us write page discard page erase overhead per page 63us erase 32 from this we can infer the following flash access times operationtimecalculation read 1mb file 013s about 75 mb s 2000 read page write 1mb clean system 053s about 18 mb s 2000 write page overwrite 1mb file no gc 108s about 09mb s 2000 overwrite page overwrite 1mb with 50 gc 24s about 4 mb s 2000 overwrite page 2000 page copy overwrite page 4000 erase overhead delete 1mb file 043s about 22 mb s 2000 discard page delete 1mb file with 50 gc 049s about 20mb s 2000 discard page 1000 erase overhead admin 23 may 2005 1231pm  