NAND Function Introduction

Introduction

The NAND library provides functions to access the NAND flash memory built into the Wii console. NAND flash memory has the following characteristics:

The NAND memory capacity of the Wii console is 512 MB. However, not all of the 512 MB space can be used by the application program, as some of the space will be taken by the system files written at the factory or for permanently reserved system needs.

The NAND library provides a file system with the following characteristics.

We have prepared sample demo programs that demonstrate how to use the NAND library under the path $REVOLUTION_SDK_ROOT/build/demos/nanddemo/. Function declarations are in the $REVOLUTION_SDK_ROOT/include/revolution/nand.h header file.

Banners

You must create a banner file in order to create an application save file in the Wii console NAND memory. In the Wii Menu, home directories without a banner file are deleted. If creating multiple files that include a banner file, be sure to create the banner file last. If the banner file is created first, and then an accident such as a power interruption occurs, the home directory would have a banner file, but some of the save files might not be there. This could confuse players because it would appear from the save data screen in the Wii Menu that the application had no problem creating the save files, when in fact there was a problem. See the Guidelines For Creating Wii Save Data for details.

The structure NANDBanner and functions NANDInitBanner, NANDGetIconSpeed and NANDSetIconSpeed have been prepared to simplify the process of creating banners. Also, reference the banner sample demo program.

Function which determines whether the file/directory can be newly created

As mentioned before, the Wii console NAND memory has the capacity of 512MB, but not all can be used by the application program. The memory will include system programs such as system feature applications, reserve area for bad blocks, and free space reserved for system use. Do not conclude whether a new file/directory can be created solely based on free space in the file system (Use of NANDFreeBlocks[Async] is not recommended).
When the application attempts to create files/directories in the home directory, based on the responses from the functions below, determine whether to go ahead and create the new files/directories or to perform some process such as displaying a message indicating insufficient memory space.

NANDCheck[Async]

NANDCheck and NANDCheckAsync function "reports" the number of file system blocks and inodes that the application is about to consume. If the application is creating a new file/directory under the home directory, call the NANDCheck or the NANDCheckAsync function first. The total number of file system blocks and inodes for the file/directory that the application will create is passed to the NANDCheck and the NANDCheckAsync functions. The system will calculate whether a sufficient space to fulfill the request is available in the file system, and gives the verdict to the application program.

Determining whether multiple files/directories can be created

If the application requires multiple files/directories, sum the total number of file system blocks and i-nodes consumed by each, and then branch to either Create file/directory group or Create no files/directories, based on the result from a call to NANDCheck[Async](). Do not call NANDCheck[Async] for each file/directory to be created. If you call NANDCheck[Async]() multiple times to create multiple files/directories, you may not be able to create all of the required files/directories, depending on the available space in Wii console NAND memory.


// Correct sequence (pseudo-code)
NANDCheck(FileA+FileB+FileC);    // Check A & B & C at once.
if(success){
createFileA();
createFileB();
createFileC();
}

// Incorrect sequence (pseudo-code)
NANDCheck(FileA);   // Check A
if(success){
createFileA();
}

NANDCheck(FileB);   // Check B
if(success){
createFileB();
}

NANDCheck(FileC)    // Check C
if(success){
createFileC()
}

The number of file system blocks (FS blocks) consumed by a given file is rounded up to be an integer value of the file size divided by 16 KB. Thus, an 8 KB file consumes one FS block, and a 40 KB consumes three FS blocks. Accordingly, if an application needs to create two files, one 8 KB and one 40 KB, that file group consumes four KS blocks (1 + 3 = 4). Do not calculate this as (40+8)/16 = 3 and call NANDCheck[Async]() with the assumption that three FS blocks will be consumed.

Function that obtains available space for an application

The NANDCheck and the NANDCheckAsync functions determine whether files/directories can be created, but they are not suited to determine exactly how much free space is available. If you want to inform the player how much free space is available for the application to use in Wii console NAND memory, use the NANDGetAvailableArea or the NANDGetAvailableAreaAsync function. These functions obtain the number of file system blocks and inodes that the application can consume.

Process Flow

First, call NANDInit function to initialize the NAND library before using NAND functions (Note: Starting with RevolutionSDK2.1, the NANDInit function is automatically called from the system). If the application is creating a new file/directory apart from /tmp, first call NANDCheck or NANDCheckAsync to verify that the file system has sufficient free space and i-nodes for the application program before calling NANDCreate functions.

Refer to NAND Processing Sequence for an example of process flow including the error processing.

Directory Structure

Although a number of directories are available for the file system in the Wii console NAND memory, the application programmer should be aware of the following:
Path Description
/title/<title-id(Hi)>/<title-id(Low)>/data This is the application home directory. The home directory is provided automatically by the system. Save application save data and others in this directory.
/tmp Temporary directory. Files and directories stored under this directory are deleted when the system starts up.
/tmp/sys This directory is reserved for use by the system as a temporary directory. Avoid having application programs access this directory directly. Doing so can lead to system instability.

Application Save Data

Use the NAND library to save application data. For programmers, the NAND flash memory is simpler to use than the CARD library, as it is built into the Revolution console. Refer to the gamesave sample demo program for more information on saving data.

When the NAND library is initialized, the current directory is automatically set as the home directory. This directory is hardwired in software in the development device environment and is common to all applications. However, a unique home directory is provided for each application on the production units.

Synchronous and Asynchronous Functions

Certain NAND functions provide both synchronous and asynchronous access to the Wii console NAND memory.
Synchronous functions block the current thread until the process completes and control is transferred to other executable threads. Asynchronous functions return immediately. If a request starts normally, a callback function is called at the completion of the process, and a result code and a command block are passed. The callback function and the command block are specified when the asynchronous function is called. If the asynchronous function call ends in an error (that is, if the result code is other than a normal exit), the specified callback function will not be called. Asynchronous functions contain the suffix Async.

inode

File management is done through inodes in the NAND library file system. To create a new file or a directory, one available inode is required for each file/directory. The number of available inodes can be checked using the NANDFreeBlocks function or the NANDFreeBlocksAsync function.
However, the values obtained by these functions are the available inode counts for the entire file system. In actuality, there are free inodes which needs to be always reserved for the system, so please do not determine whether a new file/directory can be created solely based on the value obtained by these functions. When creating a new file/directory apart from /tmp, please follow the result of NANDCheck and NANDCheckAsync functions.

Result Code List

Return Values Description
NAND_RESULT_OK Function completes successfully.
NAND_RESULT_ACCESS The are no permission/access privileges for accessing files or directories.
NAND_RESULT_ALLOC_FAILED The library failed internally to secure the memory needed for receiving a large volume of requests at one time. However, if you wait some time and call the NAND function again, the process might succeed.
NAND_RESULT_AUTHENTICATION Data authentication failed. Data may have been destroyed due to a hardware problem, or data in the Wii console NAND memory may have been falsified in some illegal manner.
NAND_RESULT_BUSY Busy state (the queue holding requests is full). If you wait some time and call the NAND function again, the process might succeed.
NAND_RESULT_CORRUPT Wear in the FAT region has caused irreparable damage to Wii console NAND memory.
NAND_RESULT_ECC_CRIT Indicates that a fatal ECC error has been detected (that is, data error correction is not possible). This code might be returned when the Wii console NAND memory is severely worn because the number of write/delete cycles has exceeded the device guaranteed performance.
NAND_RESULT_EXISTS File or directory with the same name already exists.
NAND_RESULT_INVALID Input parameter or the function call is invalid. This code is returned when an incorrect argument is passed to a NAND function, an attempt is made to close a file twice, or an attempt is made to use NANDSimpleSafe[Close] to close a file that was opened by NANDOpen[Async] (or visa-versa).
NAND_RESULT_MAXBLOCKS All of the FS blocks in the file system have been used, so there is no free space. This code is also returned when, due to device wear, the number of bad blocks has reached the upper limit.
NAND_RESULT_MAXDEPTH A directory structure deeper than this cannot be created (8 levels maximum).
NAND_RESULT_MAXFD No more files can be opened because all of the file descriptor entries have been used. Reduce the number of files you open at one time.
NAND_RESULT_MAXFILES No more files/directories can be created as the file system's inodes are used up.
NAND_RESULT_NOEXISTS The specified file or directory does not exist.
NAND_RESULT_NOTEMPTY File is not empty.
NAND_RESULT_OPENFD The file descriptor has been left open. This code is returned when an attempt is made to delete a file that has not yet been closed. (The NANDSafeClose[Async] function may potentially return this code to execute a Delete operation internal to the function.)
NAND_RESULT_UNKNOWN Unknown error. When this code is returned, there is a high probability that there is some problem with the SDK. If possible, report the issue to Nintendo.
NAND_RESULT_FATAL_ERROR The error code for program-design flaws (for example, the library is not initialized, etc.).

Of these, the following are result codes that might be returned by asynchronous function calls. Also, with the exception of certain asynchronous functions (NANDSafeOpenAsync, NANDSafeCloseAsync), the specified callback function will not receive NAND_RESULT_ALLOC_FAILED or NAND_RESULT_BUSY.

Starting from SDK Version 2.3 (firmware Version 12.0.2), most synchronous NAND functions can return NAND_RESULT_ALLOC_FAILED and NAND_RESULT_BUSY. These result codes may be returned when a synchronous NAND API is called while the queue for receiving requests is full (for example, due to a succession of calls to asynchronous NAND functions over a short period of time).

Result Code Handling

The following table indicates the guidelines for handling result codes. Also refer to the NAND Processing Sequence page.

A. Items that applications must support NAND_RESULT_AUTHENTICATION
NAND_RESULT_CORRUPT
NAND_RESULT_ECC_CRIT
B. Items that applications must support for which a bug report to Nintendo is expected (if possible) NAND_RESULT_ALLOC_FAILED
NAND_RESULT_BUSY
NAND_RESULT_MAXBLOCKS
NAND_RESULT_MAXFILES
NAND_RESULT_UNKNOWN
C. Must be removed during the development or hidden from the player NAND_RESULT_ACCESS
NAND_RESULT_EXISTS
NAND_RESULT_INVALID
NAND_RESULT_MAXDEPTH
NAND_RESULT_MAXFD
NAND_RESULT_NOEXISTS
NAND_RESULT_NOTEMPTY
NAND_RESULT_OPENFD
NAND_RESULT_FATAL_ERROR

Result codes that are classified as (A) are the codes that may be caused by issues such as wear to the Wii console NAND memory.
Result codes that are classified as (B) are the codes that should not appear as long as the Wii system is running normally. If result codes in this category appear, please send a bug report to Nintendo if possible, as there is a chance of a defect in either RevolutionSDK or the Wii console/Wii development console.
Result codes that are classified as (C) are the codes that mainly suggest coding errors by the application programmers.

Notes

Precautions when Writing Data

The file system used to manage the Wii console NAND memory has been designed to survive unexpected power shutdowns. There is no worry of the entire file system crashing even if the power shuts down in the middle of FAT update in the internal NAND memory. The system will instead restart from a FAT state immediately before the update. However, care must be taken regarding write timing. Assume that the following operations have been performed on a given file.

  1. Open()
  2. Read()
  3. Write()
  4. Write()
  5. Write()
  6. Close()

Write() alone does not update the FAT in the built-in flash memory. (The FAT in memory is updated.) Even if power shuts down midway through the execution of Write(), file contents will start from the state in effect before Write() was invoked. However, if an operation that involves updating the FAT in built-in flash memory occurs between instances of Write(), the data written by Write() up to that point will be reflected in built-in flash memory. For example, if another thread or process executes Create() immediately after the Write() on line three has finished executing, the FAT in built-in flash memory will be updated. If the power goes out immediately after this Create() function has finished executing, only the data written due to the Write() in line three will be reflected in the file. Although even this behavior may not be a problem depending on the data structure recorded for the file, if any of the of Write() on lines three, four or five are left out, problems will result if data consistency is lost.

One method of avoiding inconsistency of data due to this type of FAT update timing is to use a temporary file. First, copy the target file to /tmp and then perform all subsequent reads and writes on the file copied to /tmp. Finally, after the copied file is closed, Move() can be used to overwrite the original file, thus avoiding inconsistency of data described previously. This algorithm is implemented using the functions NANDSimpleSafeOpen/NANDSimpleSafeOpenAsync and NANDSimpleSafeClose/NANDSimpleSafeCloseAsync. The sample demo "safe" is provided to demonstrate the atomic nature of updating files using these functions.

About the NANDSimpleSafe Functions

The NANDSimpleSafe functions have been prepared to resolve problems with the NANDSafe functions. (There was no recovery method if a function call terminated in an error.) If a NANDSimpleSafe type function ends in an error, call NANDSimpleSafeCancel[Async]. This function will try to release resources used by the NANDSimpleSafe type function.

Although NANDSimpleSafeOpen[Async] and NANDSimpleSafeClose[Async] guarantee the atomicity of file updates, to achieve it they incur a higher cost than the ordinary NANDOpen[Async] and NANDClose[Async]. When using these functions, note the following points:

Disadvantages of NANDSafe Functions

(Use of NANDSafe functions is not recommended. Instead, use the new NANDSimpleSafe functions instead.)

Although NANDSafeOpen[Async] and NANDSafeClose[Async] guarantee the atomicity of file updates, to achieve it they incur a higher cost than the ordinary NANDOpen[Async] and NANDClose[Async]. Note the following when using these functions.

Allowable Characters in File and Directory Names

The characters that can be used in file and directory names are limited to the alphanumeric characters [0-9a-zA-Z] and a few symbols [-_.].

Buffer Alignment

The buffers used for reading and writing data and the buffers used for getting directory lists must be 32-byte aligned. Furthermore, the buffer for data read/directory list retrieval must be a multiple of 32 bytes.

Performance is slightly enhanced by using 64-byte alignment for the buffer used to read/write data.

File/Directory Properties

You can set properties for files/directories. However, as of 2006/06/16, no decision has been made regarding what type of properties to provide. Although arguments for specifying attributes are included with functions that create files/directories and functions that change properties, at present, do not specify any value other than zero for these arguments.

Prohibition on Frequent Read Access

As a characteristic of NAND flash devices, if read access is repeated frequently several hundred thousand times or more on a given region without performing an erase or write operation, data may become corrupted in the periphery of that region.If it is necessary to read data saved in Wii console NAND memory repeatedly, first load a good chunk of data in MEM1 or MEM2, and then read data from MEM1 or MEM2 to reduce the number of read access operations on Wii console NAND memory.
For example, the following types of Read access are prohibited.

Wear on the Wii console NAND memory

Write operations will wear out the Wii console NAND memory, so please avoid frequent writing (do not use as virtual memory). When performing auto-save, please limit its frequency to less than once per minute. If you use the NANDSimpleSafe functions to perform auto-save, you must increase the interval between auto-saves (less than once every four minutes on average) to avoid wear and tear on the FAT, because the process of opening and closing files generates four FAT updates. The limitations become even more severe when performing auto-save using the (unrecommended) NANDSafe line of functions. Because the NANDSafe functions perform six FAT updates during the process of opening and closing files, you need to increase the interval between automatic saves (less than once every six minutes on average) to avoid wear and tear on the FAT.

Fluctuations in Access Time

Due to the characteristics of the NAND flash device, the time required to access data may vary even though the amount of data being read/written is the same. For this reason, do not write game programs that depend on access time.

Reset/shutdown processes

We recommend the reset/shutdown function to not be called until all Wii console NAND memory operations issued by the application program is completed.
The reset/shutdown function will execute without waiting for the NAND function issued by the application to close. The file system managing the Wii console NAND memory will guarantee the security of the entire file system against accidents (such as power outage), but will not guarantee for the data that was in the middle of write operation. Also refer to Reset Function/Shutdown Function regarding reset/shutdown operations.

Regarding Data Tampering

The file system managing the Wii console NAND memory is strong by design against data tampering or prying. For this reason, there is no need to perform any special encryptions from the application program side when storing data into the Wii console NAND memory.

Periodic Access from the System

Starting with SDK 2.1 patch 1 (2006/08/30), the system now periodically accesses the Wii console NAND memory. There will be a file write once per minute, and a file open/close once every five minutes (FAT will also be updated at the close). For this reason, a single file descriptor will always be consumed. Also, when the system access timing and the application access timing overlaps, it may take longer than normal for the process to complete.

Limitations on Use

The following restrictions will apply regarding the use of Wii console NAND memory. Note that the files/directories created under /tmp/sys will also be subject to these restrictions. If the application is updating 1MB save file using NANDSafe type function, the upper limit of the file capacity that can be freely created in /tmp by the application will decrease to 39MB.
Coverage Upper Limit
Maximum file storage capacity of the home directory 16 MB
Number of files/directories that can be created in the home directory 32
Maximum storage capacity of file that can be created in /tmp 40 MB
Number of files/directories that can be created in /tmp 64

Revision History

2007/05/E Added a note about guidelines for handling result codes.
2007/05/M Added a brief explanation about the Group permission.
2007/05/M Added a note about the frequency of calls to the NANDSimpleSafe functions.
2007/05/09 Noted that a callback function is not called when an asynchronous function call ends in an error.
2007/05/09 Added a description of the NANDSimpleSafe line of functions. Noted that the use of NANDSafe functions is not recommended.
2007/02/xx Added the result code NAND_RESULT_MAXDEPTH.
2007/02/xx Added a supplement about the NAND_RESULT_OPENFD result code.
2006/12/18 Added a description of the prohibition on frequent Read access.
2006/11/30 Added text about result codes.
2006/11/30 Added text mentioning that many synchronous functions can return NAND_RESULT_ALLOC_FAILED and NAND_RESULT_BUSY.
2006/11/30 Deleted text about NANDGetAvailableArea[Async] as an alternative to NANDCheck[Async].
2006/11/10 Supplemented the information about banner files and NANDCheck[Async].
2006/10/25 Explained NANDGetAvailableArea[Async].
2006/10/25 Standardized terminology.
2006/10/25 Added information about periodic access from the system.
2006/09/28 Explained implementation details about the NANDSafe type function. Clarified the operational restrictions.
2006/09/25 Specified the home directory location.
2006/09/19 Added details about the result code that NANDSafeOpenAsync and NANDSafeCloseAsync function callbacks may receive.
2006/09/19 Added information about banner files.
2006/08/30 Added information that NANDInit is now automatically called from the system.
2006/08/30 Added information about NANDCheck.
2006/08/30 Fixed spelling errors in the result code.
2006/08/15 Revised the table on operational limitations.
2006/08/15 Added a description of the NANDSafe line of functions.
2006/08/15 Described the maximum allowable depth of the directory hierarchy.
2006/08/15 Deleted the NAND_RESULT_INIT_FAILED result code.
2006/08/15 Added description of characters allowed in file/directory names.
2006/08/15 Revised description of /tmp/sys.
2006/08/15 Revised description of maximum path length.
2006/08/15 Added precautions regarding writing data.
2006/08/15 Added a description of the NAND_RESULT_AUTHENTICATION result code.
2006/06/16 Initial version.