23
AN116 – Using NAND Flash Memory with the eCOG1X Version 1.0 This application note describes how to use an external NAND flash memory device with the eCOG1X microcontroller and CyanIDE 2. 05 February 2009 Cyan Technology Ltd.

Using NAND Flash Memory with the eCOG1X

Embed Size (px)

Citation preview

Page 1: Using NAND Flash Memory with the eCOG1X

AN116 – Using NAND Flash Memory with the eCOG1X Version 1.0

This application note describes how to use an external NAND flash memory device with the eCOG1X microcontroller and CyanIDE 2.

05 February 2009 Cyan Technology Ltd.

Page 2: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

Confidential and Proprietary Information ©Cyan Technology Ltd, 2009

This document contains confidential and proprietary information of Cyan Technology Ltd and is protected by copyright laws. Its receipt or possession does not convey any rights to reproduce, manufacture, use or sell anything based on information contained within this document.

Cyan TechnologyTM, the Cyan Technology logo and Max-eICETM are trademarks of Cyan Holdings Ltd. CyanIDE® and eCOG® are registered trademarks of Cyan Holdings Ltd. Cyan Technology Ltd recognises other brand and product names as trademarks or registered trademarks of their respective holders.

Any product described in this document is subject to continuous developments and improvements. All particulars of the product and its use contained in this document are given by Cyan Technology Ltd in good faith. However, all warranties implied or expressed, including but not limited to implied warranties of merchantability, or fitness for purpose, are excluded.

This document is intended only to assist the reader in the use of the product. Cyan Technology Ltd shall not be liable for any loss or damage arising from the use of any information in this guide, any error or omission in such information, or any incorrect use of the product.

This product is not designed or intended to be used for on-line control of aircraft, aircraft navigation or communications systems or in air traffic control applications or in the design, construction, operation or maintenance of any nuclear facility, or for any medical use related to either life support equipment or any other life-critical application. Cyan Technology Ltd specifically disclaims any express or implied warranty of fitness for any or all of such uses. Ask your sales representative for details.

05 February 2009 Cyan Technology Ltd. Page 2 of 23

Page 3: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

05 February 2009 Cyan Technology Ltd. Page 3 of 23

Revision History Version Date Notes

V1.0 05/02/2009 First release.

Page 4: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

05 February 2009 Cyan Technology Ltd. Page 4 of 23

Contents 1 Introduction.......................................................................................... 5

2 Glossary .............................................................................................. 5

3 NAND and NOR Flash......................................................................... 5

4 NAND Flash Memory........................................................................... 6

5 Hardware Interface .............................................................................. 7

6 Software .............................................................................................. 8 6.1 CYDF NAND Flash Device Driver ............................................................. 8

cydf_nand_reset.............................................................................................. 8 cydf_nand_read............................................................................................... 8 cydf_nand_write .............................................................................................. 9 cydf_nand_erase............................................................................................. 9 cydf_nand_get_size ........................................................................................ 9

6.2 CYDF FTL Flash Translation Layer......................................................... 10 cydf_ftl_read_block ....................................................................................... 10 cydf_ftl_write_block ....................................................................................... 10 cydf_ftl_initflash............................................................................................. 11 cydf_ftl_get_info ............................................................................................ 11

6.3 CYDF FAT File System ........................................................................... 11 6.4 Example Project ...................................................................................... 11

6.4.1 Overview........................................................................................... 11 6.4.2 Configurator Properties .................................................................... 12 6.4.3 Example Source Code...................................................................... 14

7 Limitations ......................................................................................... 22

8 References ........................................................................................ 23

Page 5: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

1 Introduction

This application note describes how to use an external high capacity NAND flash memory device with the eCOG1X under CyanIDE 2.

The eCOG1X does not have a dedicated NAND flash memory interface peripheral. The interface to the external NAND flash device is implemented using the EMI peripheral with additional software support in a device driver.

The device driver and a high level Flash Translation Layer (FTL) software component are designed to work within the Cyan Driver Framework (CYDF) in the CyanIDE 2 development environment. An example project demonstrates a simple FAT file system running on top of the FTL and device driver components. The NAND flash device used in this example is the Samsung K9G8G08U0M, with a nominal capacity of 8Gbits organised as 1G x 8 bits.

2 Glossary

A table of abbreviations used in this document.

CYDF Cyan Driver Framework ECC Error Correcting Code eCOG1 Cyan Technology target micro controller EMI External Memory Interface FAT File Allocation Table FFS Flash Filing System FTL Flash Translation Layer NAND flash A type of high capacity flash memory, often used for bulk data storage. UART Universal Asynchronous Receiver/Transmitter

3 NAND and NOR Flash

NOR-based flash has long erase and write times, but provides full address and data buses, allowing random access to any memory location. This makes it a suitable replacement for ROM devices, which are used to store program code that rarely needs to be updated. Its endurance is typically 10,000 to 1,000,000 erase cycles.

NAND flash has faster erase and write times, and requires a smaller chip area per cell, thus allowing greater storage densities and lower costs per bit than NOR flash. It may also have up to ten times the endurance of NOR flash, depending on the specific design of the flash memory cells. However, the I/O interface of NAND flash does not provide a random-access external address bus. Instead, data must be read on a block-wise basis, with typical block sizes of hundreds to thousands of bits. This makes NAND flash unsuitable as a drop-in replacement for program ROM, since most microprocessors and microcontrollers require byte-level random access. In this regard NAND flash is similar to other secondary storage devices, such as hard disks and optical media, and therefore is very suitable for use in mass-storage devices such as memory cards.

NOR Flash is ideal for lower-density, high-speed read applications which are mostly read only, often referred to as code-storage applications. NAND Flash is ideal for low-cost, high-density, high-speed program/erase applications, often referred to as data-storage applications.

05 February 2009 Cyan Technology Ltd. Page 5 of 23

Page 6: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

4 NAND Flash Memory [Information from Wikipedia]

NAND flash architecture was introduced by Toshiba in 1989. These memories are accessed much like block devices such as hard disks or memory cards. Each block consists of a number of pages, typically 512, 1024, 2048 or 4096 bytes in size. Associated with each page are a few additional bytes (typically 12–16 bytes) that are used for storage of an error detection and correction checksum.

For example, the K9G8G08 device has a block size of 256K bytes, each block containing 128 pages of 2K bytes each. Each page has an additional 64 bytes in which to store the page/block management data.

While reading and programming can be performed on individual pages, erasing can only be performed on a complete block. When writing data to a block, data must be written to pages sequentially, not randomly addressed, from the start of the block to the end.

NAND flash devices require bad block management, either by the device driver software, or by a separate controller chip. Most NAND flash devices are shipped from the factory with some bad blocks, which are identified and marked according to a specified bad block marking strategy. By allowing some bad blocks, the manufacturers achieve far higher yields than would be possible if all blocks had to be verified good. This significantly reduces NAND flash costs and only slightly decreases the storage capacity of the parts. Further blocks may fail during the operational lifetime of the device, and the device driver or flash translation layer software maintains the map of good and bad blocks. Additional software may implement wear levelling, where successive block erase and write operations are performed on different blocks, such that on average all blocks within the device are erased and programmed a similar number of times.

When a logical block is accessed by high-level software, it is mapped to a physical block by the device driver or controller. A number of blocks on the flash chip may be set aside for storing mapping tables to deal with bad blocks, or the system may simply check each block at power-up to create a bad block map in RAM. The overall memory capacity gradually shrinks over time as more blocks are marked as bad.

NAND flash relies on error detection and correction using ECC to compensate for bits that may spontaneously fail during normal device operation. This may correct as little as one bit error in each 2048 bits, or up to 22 bits in each 2048 bits. If ECC cannot correct the error during a read, it may still detect the error. When erase or program operations are performed, the device can detect blocks that fail to program or erase and mark them as bad. The data is then written to a different, good block, and the bad block map is updated.

When executing software from NAND flash memories, virtual memory strategies are often used; the flash memory contents must be paged or copied into memory-mapped RAM and executed there, leading to the common combination of NAND flash + DRAM in many systems. A memory management unit (MMU) in the system is helpful, but a similar function can be accomplished with overlays. For this reason, some systems use a combination of NOR and NAND flash memories, where a smaller NOR flash memory is used as software ROM and a larger NAND flash memory is partitioned with a file system for use as a non-volatile data storage area.

NAND flash is best suited to systems requiring high capacity data storage. This type of flash architecture offers higher densities and larger capacities at lower cost with faster erase, sequential write, and sequential read speeds, sacrificing the random-access and execute in place advantage of the NOR architecture.

05 February 2009 Cyan Technology Ltd. Page 6 of 23

Page 7: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

5 Hardware Interface

The eCOG1X does not have a dedicated NAND flash interface peripheral. In this example, a subset of the EMI peripheral port pins is used, together with some GPIO signals. This allows the EMI pins to be shared with other external memory devices, reducing the total number of I/O pins required in some applications.

Figure 1. NAND flash connections

Signal eCOG1X Port Description D0..D7 EMI_D0..D7 PortH_0..7 Data bus CLE EMI_A4 PortE_4 Command Latch Enable ALE EMI_A5 PortE_5 Address Latch Enable RDY/BUSY GPIOJ_2 input PortJ_2 Ready / Busy status /WE EMI_WS0 PortD_3 Write Enable /RE EMI_RS PortD_2 Read Enable /CS GPIOD_1 output PortD_1 Chip Select

Table 1. NAND flash signals

Data is transferred between the eCOG1X and the NAND flash using the 8-bit data bus subset of the EMI peripheral. A 16-bit wide data bus may be used if the NAND flash supports a wider data bus connection.

Address lines A4 and A5 are connected to the ALE and CLE inputs, allowing the selection of an address, command, or data access by reading or writing to different physical addresses. The /RE and /WE read and write enable inputs are connected to the EMI_RS and EMI_WS0 outputs. The normal EMI peripheral function of these signals is suitable for use with the NAND flash device.

The READY/BUSY status output is connected to the EMI_WAIT input, and the /CS chip select input to the EMI_CS1 output. The normal EMI peripheral function of these signals is not suitable for use with the NAND flash. Instead, the device driver configures these port pins as GPIO, one input and one output. The /CS chip select input on the NAND flash must be held active (low) throughout a complete NAND flash operation cycle, which may consist of several memory accesses. If this pin were controlled by the normal EMI chip select output function, it would return inactive (high) at the end of each individual memory access.

05 February 2009 Cyan Technology Ltd. Page 7 of 23

Page 8: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

6 Software

The software in this example includes a number of components.

• Application code. A simple example demonstrating erase, format, and normal file system functions.

• CYDF FAT file system. This is one possible implementation of a standard file system. Alternative flash filing systems may be more suitable for other applications.

• CYDF FTL flash translation layer. This implements a number of high level software functions for the NAND flash, including bad block management, error detection, garbage collection and wear levelling.

• CYDF NAND flash device driver. This uses the eCOG1X EMI peripheral and GPIO port pins to perform read and write accesses to the external NAND flash device.

6.1 CYDF NAND Flash Device Driver The NAND flash device driver implements low level hardware functions, using the EMI peripheral and GPIO pins, to access the external device. Function prototypes (other than for the standard CYDF functions such as open and close) are defined in the include file <cydf_nand_flash.h>.

CYDF device driver functions return zero on success, or a standard error code on any failure. The standard error codes are defined in <errno.h> and <sys/errno.h>.

cydf_nand_reset

int cydf_nand_reset(cydf_dev_t *dev)

This function sends a reset command to the NAND flash device.

dev Pointer to the CYDF device handle returned by cydf_open().

cydf_nand_read

int cydf_nand_read(cydf_dev_t *dev, cydf_nand_addr_t address, void *data_buffer, void *spare_buffer, uint16_t nbyte)

This function reads one page of data from the specified page, plus a specified number of bytes from the spare data area.

dev Pointer to the CYDF device handle returned by cydf_open(). address The number of the page from which to read data. data_buffer Pointer to a buffer into which the page data bytes are read. spare_buffer Pointer to a buffer into which the spare data bytes are read. nbyte The number of data bytes to read from the spare data area.

05 February 2009 Cyan Technology Ltd. Page 8 of 23

Page 9: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

cydf_nand_write

int cydf_nand_write(cydf_dev_t *dev, cydf_nand_addr_t address, void *data_buffer, void *spare_buffer, uint16_t nbyte)

This function writes one page of data to the specified page, plus a specified number of bytes to the spare data area.

dev Pointer to the CYDF device handle returned by cydf_open(). address The number of the page to which to write data. data_buffer Pointer to a buffer containing the page data to write. spare_buffer Pointer to buffer containing the spare data bytes to write. nbyte The number of data bytes to write to the spare data area.

cydf_nand_erase

int cydf_nand_erase(cydf_dev_t *dev, cydf_nand_addr_t address)

This function erases one data block in the device. The number of the block to be erased is passed in the address argument.

dev Pointer to the CYDF device handle returned by cydf_open(). address The number of the block to erase.

cydf_nand_get_size

int cydf_nand_get_size(cydf_dev_t *dev, unsigned int *page_per_block, unsigned int *block_num, unsigned int *page_data_size, unsigned int *page_spare_size)

This function returns information about the NAND flash device.

dev Pointer to the CYDF device handle returned by cydf_open(). page_per_block Pointer to the returned number of pages in each block. block_num Pointer to the returned number of blocks in the device. page_data_size Pointer to the returned number of bytes in each page. page_spare_size Pointer to the returned number of spare bytes in each page.

05 February 2009 Cyan Technology Ltd. Page 9 of 23

Page 10: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

6.2 CYDF FTL Flash Translation Layer The CYDF FTL flash translation layer software implements higher level functions. It calls low level functions in the device driver to access the hardware, and is called by the file system code as required. To use the CYDF FAT file system library with the FTL, the application code registers the FTL read block and write block functions as callback functions for the FAT library.

The FTL also implements specific features for NAND flash operation, including bad block management, error detection and correction1, garbage collection and wear levelling.

The CYDF FTL library is included in CyanIDE 2.1.X as an object code only software component.

Function prototypes (other than for the standard CYDF functions such as open and close) are defined in the include file <cydf_ftl.h>. All functions return zero on success, or one of the following error codes on any failure.

0 NAND_FTL_PASS Function succeeded with no errors. 1 NAND_FTL_FAIL Not used. 2 NAND_FTL_BAD_BLOCK Bad block found. 3 NAND_FTL_INVALID Cannot find blank page. 4 NAND_FTL_IO_ERROR Low level device driver error. 5 NAND_FTL_LSN_NOT_FOUND Sector not found (sector number too large). 6 NAND_FTL_ECC_ERROR Bit error detected when reading data page. 7 NAND_FTL_MEMORY_ALLOCATION_FAIL Not enough heap memory for data cache. 8 NAND_FTL_TOO_MANY_BAD_BLOCK Maximum number of bad blocks exceeded.

cydf_ftl_read_block

int cydf_ftl_read_block(cydf_dev_t *dev, unsigned char *blockbuffer, unsigned long lsn)

This function reads a block of data from the device.

dev Pointer to the CYDF device handle returned by cydf_open(). blockbuffer Pointer to a data buffer into which the block data is read. lsn Logical sector number of the block to read.

cydf_ftl_write_block

int cydf_ftl_write_block(cydf_dev_t *dev, unsigned char *blockbuffer, unsigned long lsn)

This function writes a block of data to the device.

dev Pointer to the CYDF device handle returned by cydf_open(). blockbuffer Pointer to a data buffer containing the block data to write. lsn Logical sector number of the block to write.

1 The current version of the FTL code implements single bit error detection, but not error correction. This may

be added in a later version.

05 February 2009 Cyan Technology Ltd. Page 10 of 23

Page 11: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

cydf_ftl_initflash

int cydf_ftl_initflash(cydf_dev_t *dev, unsigned long *sector_count)

This function formats the NAND flash device into logical sectors.

dev Pointer to the CYDF device handle returned by cydf_open(). sector_count Pointer to the returned number of sectors.

cydf_ftl_get_info

int cydf_ftl_get_info(cydf_dev_t *dev, unsigned int * block_size, unsigned long *block_count)

This function returns the logical block size and number of blocks for the formatted device. It returns zero.

dev Pointer to the CYDF device handle returned by cydf_open(). block_size Pointer to the returned block size (in bytes). block_count Pointer to the returned block count (number of blocks).

6.3 CYDF FAT File System The CYDF FAT file system library is included in CyanIDE 2.1.X as an object code only software component. The user manual for this library is available in Acrobat format on the Cyan web site, and is included in the CyanIDE 2 help documents.

6.4 Example Project

6.4.1 Overview The application code provides a simple example to demonstrate many of the common functions used with a NAND flash device. Several defined constants control conditional code for different major functions. If these constants are defined, then the related code is included. If a constant is undefined, then the related code is excluded.

Symbol Function of code included when symbol is defined ERASE_NAND Erases all blocks in the NAND flash device. FTL_FORMAT Formats the NAND flash into logical sectors. SET_PARTITION Sets up FAT file system logical disk partitions. FAT_FORMAT Formats partition zero. GET_PARTITION Reads and prints partition information. FAT_MOUNT Mounts the FAT file system as a drive. CREATE_DIR Creates a new directory. CREATE_FILES Creates and manipulates a number of new files. GET_NUM_DIR Reads and prints the number of directory entries. GET_SUB_DIR Reads and prints sub-directories. FAT_UNMOUNT Unmounts the currently mounted drive.

05 February 2009 Cyan Technology Ltd. Page 11 of 23

Page 12: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

6.4.2 Configurator Properties A number of basic properties for the CYDF software components are set up in the configurator, in addition to the basic properties for the on-chip hardware peripherals (EMI and UART).

CYDF NAND Flash Device Driver

Property Value Description ID cydf_nand_flash Identifies this instance of the NAND flash device driver. The CYDF

FTL library is set up to use this ID in its configurator properties, see below. It uses this ID when it opens the device at run-time.

Timeout 10.0 s Timeout when polling the state of the READY/BUSY pin. NAND Logical Address

0x4000 The logical address programmed into the MMU translator for accesses to the NAND flash via the external memory interface.

NAND Physical Address

0x0000 The physical address programmed into the MMU translator for accesses to the NAND flash via the external memory interface.

05 February 2009 Cyan Technology Ltd. Page 12 of 23

Page 13: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

CYDF FTL Flash Translation Layer

Property Value Description ID cydf_ftl Identifies this instance of the flash translation layer. NAND Device ID

cydf_nand_flash Identifies which instance of the NAND flash device driver is used by the CYDF FTL library. It uses this ID when it opens the device at run-time.

CYDF FAT File System

Property Value Description ID cydf_fat Identifies this instance of the FAT file system.

The FAT file system is linked to the flash translation layer software through callback functions. In the example application, the code registers the FTL block read and block write functions with the FAT file system. When a file access is made through the FAT file system, it calls the registered functions to perform the lower level block read or write.

05 February 2009 Cyan Technology Ltd. Page 13 of 23

Page 14: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

6.4.3 Example Source Code The following sections describe briefly the source code in the example application. The sections of code correspond to the defined symbols described earlier, and can be included or excluded by defining or undefining the symbols.

Opening the CYDF Devices

The example application begins by initialising some local data items, and then opens the CYDF devices and software components. //Declare CYDF handles cydf_dev_t *uart1a; cydf_dev_t *k9nand; cydf_dev_t *myFAT; cydf_dev_t *myFTL; ... //FAT callbacks prototypes BOOL callback_fat_read_block_raw(unsigned int *blockBuffer, unsigned long blockIndex); BOOL callback_fat_write_block_raw(unsigned int *blockBuffer, unsigned long blockIndex); ... int main(int argc, char* argv[]) { ... //open UART uart1a = cydf_open(cydf_duart1a, 0); printf("K9G8G CYDF NAND FTL FAT test \n\r"); //open NAND flash k9nand = cydf_open(cydf_nand_flash, 0); //open FTL myFTL = cydf_open(cydf_ftl,0); // Open the FAT device and register FAT callbacks myFAT = cydf_open(cydf_fat, 0); cydf_fat_set_callback_read_block_raw(myFAT, callback_fat_read_block_raw); cydf_fat_set_callback_write_block_raw(myFAT, callback_fat_write_block_raw); ... }

The two CYDF FAT callback functions are defined later, calling the block read and write functions in the CYDF FTL library. // FAT callback routines BOOL callback_fat_read_block_raw(unsigned int *blockBuffer, unsigned long blockIndex) { cydf_ftl_read_block (myFTL, (unsigned char*) blockBuffer, blockIndex); return TRUE; } BOOL callback_fat_write_block_raw(unsigned int *blockBuffer, unsigned long blockIndex) { cydf_ftl_write_block (myFTL,(unsigned char*) blockBuffer, blockIndex); return TRUE; }

05 February 2009 Cyan Technology Ltd. Page 14 of 23

Page 15: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

Getting the Size of the NAND Flash Device

Reads the number of blocks and other information about the NAND flash device. //Read number of blocks in NAND flash device unsigned int pages_per_block, num_blocks, page_size, spare_size; if (cydf_nand_get_size(k9nand, &pages_per_block, &num_blocks, &page_size, &spare_size) != 0) { printf("Failed to read number of blocks \n\r"); break; } printf("Number of blocks is %d \n\r", num_blocks);

Erasing the NAND Flash Device

Erases all data in each block within the NAND flash device. //Erase all contents in NAND flash device printf("Erasing NAND flash \n\r"); int block; for (block = 0; block < num_blocks; block++) { if (cydf_nand_erase(k9nand, block) != 0) { printf("Failed to erase block %d\n\r", block); break; } } printf("Erase completed \n\r");

Note that this code calls the low level NAND flash device driver directly. Strictly the application should not erase blocks that are already marked as bad.

Formatting the NAND Flash Device

Calls the FTL routine to format the NAND flash device as a drive and create the logical sectors. unsigned long num_of_sector; printf("FTL formatting... This takes a while \n\r"); if (cydf_ftl_initflash (myFTL, &num_of_sector) == 0) printf("The number of sectors in this drive is %ld \n\r", num_of_sector);

Setting Up Disk Partitions

Calls the FAT set partition routine to set up disk partitions. fat_partition_table_entry_t partitionTableEntryLocal; memset(&partitionTableEntryLocal, 0, sizeof(fat_partition_table_entry_t)); // Set the partition to use the full disk, minus the first 64 blocks. partitionTableEntryLocal.system_id = USB_MSD_DISKFORMAT_FAT16; partitionTableEntryLocal.relative_sector = swap32(PARTITION_OFFSET); partitionTableEntryLocal.total_sectors = swap32((unsigned long)40960); partitionTableEntryLocal.boot_indicator = 0; partitionTableEntryLocal.start_head = 0; partitionTableEntryLocal.start_sector = 1; partitionTableEntryLocal.start_cylinder = 0; partitionTableEntryLocal.end_head = 0; partitionTableEntryLocal.end_sector = 0; partitionTableEntryLocal.end_cylinder = 249; if (!cydf_fat_set_partition_info(myFAT, 0, &partitionTableEntryLocal)) printf("Partition disk 0 failed \n\r"); memset(&partitionTableEntryLocal, 0, sizeof(fat_partition_table_entry_t)); if (!cydf_fat_set_partition_info(myFAT, 1, &partitionTableEntryLocal)) printf("Partition disk 1 failed \n\r"); if (!cydf_fat_set_partition_info(myFAT, 2, &partitionTableEntryLocal)) printf("Partition disk 2 failed \n\r"); if (!cydf_fat_set_partition_info(myFAT, 3, &partitionTableEntryLocal)) printf("Partition disk 3 failed \n\r");

05 February 2009 Cyan Technology Ltd. Page 15 of 23

Page 16: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

Formatting the FAT File System

Calls the FAT format routine to format the FAT file system. printf("FAT formatting drive \n\r"); if (!cydf_fat_format(myFAT, PARTITION_INDEX, "HOME", TRUE, TRUE, FAT_TYPE_FAT16)) printf("Format failed \n\r");

Getting Partition Information

The following code calls the FTL get info routine to return data about the disk partitions. unsigned int block_size; unsigned long block_count; cydf_ftl_get_info (myFTL, &block_size, &block_count); printf("FTL uses block size %d, and there are %ld blocks in this device \n\r", block_size, block_count); int numPartitions; fat_partition_table_entry_t partition_table_entry_local; numPartitions = cydf_fat_get_num_partitions(myFAT); printf("Number of partitions = %d \n\r", numPartitions); //Get Partition info if (!cydf_fat_get_partition_info(myFAT, PARTITION_INDEX, &partition_table_entry_local)) printf("Unable to get partition info; error %d\n\r", fat_get_error()); else { printf("Data starts at block 0x%08lx \n\r", swap32(partition_table_entry_local.relative_sector)); printf("Total number of sectors 0x%08lx \n\r", swap32(partition_table_entry_local.total_sectors)); }

Mounting the Disk Partition

Calls the FAT mount routine to mount a disk partition as a drive. // Mount the partition if (cydf_fat_mount(myFAT, 0)) { printf("FAT mounted \n\r"); ... } else printf("FAT mount failed \n\r ");

Creating a directory fat_fat_dir_entry_t * subdirfind; printf("Creating directory \n\r"); //create a new directory mydir = cydf_fat_create_directory(myFAT, "A", NULL); if (mydir == NULL) printf("Fail to create MYDOC directory \n\r"); subdirfind = cydf_fat_find_entry(myFAT, "A", FAT_FILEATTR_DIRECTORY, FAT_FILEATTR_DIRECTORY, NULL, NULL); memcpy(&mydirsub, subdirfind, sizeof(fat_fat_dir_entry_t));

05 February 2009 Cyan Technology Ltd. Page 16 of 23

Page 17: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

Creating Files for (k = 0; k < MAXCOUNT; k++) { //get the random value; random_val = Random(); //file index must be in range 0 - 99 file_index = ((float)random_val / (float)MAX_RANDOM) * (unsigned int)NUM_OF_FILE; //Add file index to filename sprintf(rootdir_testfile+ROOTDIR_FILE_LENGTH, "%04X", file_index); //file size file_size = MIN_FILE_SIZE + file_index; //set data to file index memset(writedata, file_index, file_size); //WRITE FILE if ((file_ptr = cydf_fat_fopen(myFAT, rootdir_testfile, "wb")) == NULL) printf("Error opening FILE%04X \n\r", file_index); else { if (cydf_fat_fwrite(myFAT, writedata, sizeof(char), file_size, file_ptr) != file_size) printf("Error writing FILE%04X \n\r", file_index); else printf("created FILE%04X \n\r",file_index); } cydf_fat_fclose(myFAT, file_ptr); }

Reading Data from a File for (k = 0; k < MAXCOUNT; k++) { memset(readdata, 0xff, file_size); //READ BACK FILE if ((file_ptr = cydf_fat_fopen(myFAT, rootdir_testfile, "r")) == NULL) printf("Error opening FILE%04X \n\r", file_index); else { if (cydf_fat_fread(myFAT, readdata, sizeof(char), file_size, file_ptr) != file_size) printf("Failed to read FILE%04X \n\r", file_index); else { for (j = 0; j < file_size; j++) { if (readdata[j] != file_index ) printf("Read error data %c \n\r",readdata[j]); } } } cydf_fat_fclose(myFAT, file_ptr); }

05 February 2009 Cyan Technology Ltd. Page 17 of 23

Page 18: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

Appending Data to a File for (k = 0; k < MAXCOUNT; k++) { //APPEND FILE if ((file_ptr = cydf_fat_fopen(myFAT, rootdir_testfile, "r+")) == NULL) printf("Error opening FILE%04X \n\r", file_index); else { if (cydf_fat_fseek(myFAT, file_ptr, EXTRA_FILE_SIZE+file_size, FAT_SEEK_SET) != 0 ) printf("Error seeking FILE%04X \n\r", file_index); else { if (cydf_fat_fwrite(myFAT, extra_data, sizeof(char), EXTRA_FILE_SIZE, file_ptr) != EXTRA_FILE_SIZE) printf("Error appending FILE%04X \n\r", file_index); else printf("Appended FILE%04X \n\r",file_index); } } cydf_fat_fclose(myFAT, file_ptr); }

Reading the Appended Data from a File for (k = 0; k < MAXCOUNT; k++) { if ((file_ptr = cydf_fat_fopen(myFAT, rootdir_testfile, "r")) == NULL) printf("Error opening appended FILE%04X \n\r", file_index); else { if ( cydf_fat_fread(myFAT, readdata, sizeof(char), file_size + EXTRA_FILE_SIZE, file_ptr) != file_size+EXTRA_FILE_SIZE) printf("Failed to read appended FILE%04X \n\r", file_index); else { for (j = 0; j < file_size; j++) { if (readdata[j] != file_index) printf("Read error on appended data %c \n\r",readdata[j]); } for (j = file_size; j < file_size + EXTRA_FILE_SIZE; j++) { if (readdata[j] != EXTRA_DATA) printf("Read error on appended data %c \n\r",readdata[j]); } } } cydf_fat_fclose(myFAT, file_ptr); }

Deleting Files from Root Directory //DELETE FILES IN ROOT DIRECTORY for (k = 0; k < MAXCOUNT; k++) { //get the random value; random_val = Random(); //file index must be in range 0 - 99 file_index = ((float)random_val / (float)MAX_RANDOM) * (unsigned int)NUM_OF_FILE; //Add file index to filename sprintf(rootdir_testfile + ROOTDIR_FILE_LENGTH, "%04X", file_index); if (cydf_fat_delete_file(myFAT, rootdir_testfile, NULL) != TRUE) printf("Delete FILE%04X failed \n\r",file_index); else printf("FILE%04X is deleted \n\r", file_index); } //end of delete

05 February 2009 Cyan Technology Ltd. Page 18 of 23

Page 19: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

Creating Files in a Sub-Directory //CREATE FILES IN SUB-DIRECTORY for (k = 0; k < MAXCOUNT; k++) { //get the random value; random_val = Random(); //file index must be in range 0 - 99 file_index = ((float)random_val / (float)MAX_RANDOM) * (unsigned int)NUM_OF_FILE; //Add file index to "testfile" sprintf(subdir_testfile+SUBDIR_FILE_LENGTH, "%04X", file_index); //file size file_size = MIN_FILE_SIZE + file_index; //set data to file index memset(writedata, file_index, file_size); //WRITE FILE if ((file_ptr = cydf_fat_fopen(myFAT, subdir_testfile, "wb")) == NULL) printf("Error opening A/FILE%04X \n\r", file_index); else { if (cydf_fat_fwrite(myFAT, writedata, sizeof(char), file_size, file_ptr) != file_size ) printf("Error writing A/FILE%04X \n\r", file_index); else printf("created A/FILE%04X \n\r",file_index); } cydf_fat_fclose(myFAT, file_ptr); }

Reading Back Files from a Sub-Directory for (k = 0; k < MAXCOUNT; k++) { memset(readdata, 0xff, file_size); //READ BACK FILE if ((file_ptr = cydf_fat_fopen(myFAT, subdir_testfile, "r")) == NULL) printf("Error opening FILE%04X \n\r", file_index); else { if (cydf_fat_fread(myFAT, readdata, sizeof(char), file_size, file_ptr) != file_size) printf("Failed to read FILE%04X \n\r", file_index); else { for (j = 0; j < file_size; j++) { if (readdata[j] != file_index) printf("Read error data %c \n\r",readdata[j]); } } } cydf_fat_fclose(myFAT, file_ptr); }

05 February 2009 Cyan Technology Ltd. Page 19 of 23

Page 20: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

Deleting Files from a Sub-Directory //DELETE SUB-DIRECTORY FILES for (k = 0; k < MAXCOUNT; k++) { //get the random value; random_val = Random(); //file index must be in range 0 - 99 file_index = ((float)random_val / (float)MAX_RANDOM) * (unsigned int)NUM_OF_FILE; //Add file index to filename sprintf(rootdir_testfile + ROOTDIR_FILE_LENGTH, "%04X", file_index); if (cydf_fat_delete_file(myFAT, rootdir_testfile, &mydirsub) != TRUE) printf("Delete FILE%04X failed \n\r",file_index); else printf("FILE%04X is deleted \n\r", file_index); } //end of delete

Getting the Root Directory Entries unsigned int numDirectoryEntries, index; fat_fat_dir_entry_t *fatDirEntry; numDirectoryEntries = cydf_fat_get_num_dir_entries(myFAT, NULL); for (index = 0; index < numDirectoryEntries; index++) { fatDirEntry = cydf_fat_get_dir_entry(myFAT, NULL, index); if (!cydf_fat_is_long_filename_entry(myFAT, fatDirEntry)) { cydf_fat_print_dir_entry(myFAT, fatDirEntry); printf("\n\r"); } }

Getting Sub- Directory Entries fat_fat_dir_entry_t *mydirsub_p; numDirectoryEntries = cydf_fat_get_num_dir_entries(myFAT, &mydirsub); for (index = 0; index < numDirectoryEntries; index++) { mydirsub_p = cydf_fat_get_dir_entry(myFAT, &mydirsub, index); if (!cydf_fat_is_long_filename_entry(myFAT, mydirsub_p)) { cydf_fat_print_dir_entry(myFAT, mydirsub_p); printf("\n\r"); } }

Unmounting the Disk Partition

Calls the FAT unmount routine to close a drive. // Unmount the currently mounted drive cydf_fat_unmount(myFAT); printf("FAT Unmounted \n\r");

05 February 2009 Cyan Technology Ltd. Page 20 of 23

Page 21: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

Closing the CYDF Devices

Close any open devices. In practice, only the FTL needs to be closed explicitly, as it may have cached some write data; this cached data is written to the NAND flash device before the close function returns. // Close FAT file system cydf_close(myFAT); //Close FTL //This must be called prior to exiting the program to ensure that any data //in the cache (when the cache is not full) is copied to the NAND flash cydf_close(myFTL); // Close low level NAND flash driver cydf_close(k9nand); // Close the UART serial port cydf_close(uart1a);

05 February 2009 Cyan Technology Ltd. Page 21 of 23

Page 22: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

7 Limitations

Please note that the NAND flash project is only an example to demonstrate some of the basic functions. Any use of code from this example in a real application should be tested thoroughly.

There are some limitations in this early version of the NAND flash support code. Nevertheless it is a useful example.

• The NAND flash driver uses hard coded I/O lines for the ALE, CLE, CS and RDY/BUSY signals.

• The driver works correctly only if the EMI interface is configured for a 16-bit wide data bus. • The low level driver source code is not included in the CyanIDE release installation. • The FTL implements error detection but not correction. • The application example uses some defined constants that are specific to the device used

during testing (a Samsung K9G9G08U0M).

05 February 2009 Cyan Technology Ltd. Page 22 of 23

Page 23: Using NAND Flash Memory with the eCOG1X

AN116 Using NAND Flash Memory with the eCOG1X Version 1.0

05 February 2009 Cyan Technology Ltd. Page 23 of 23

8 References

• Samsung Semiconductor: K9G8G8U0M data sheet. • Samsung Semiconductor: flash memory application notes. • Toshiba Semiconductor: NAND vs. NOR Flash Memory Technology Overview. • Wikipedia: <Flash_memory>. • Cyan Technology: CYDF FAT File System User Manual.