Sample GBA application with custom Resource Manager

Revision History

Version Date Author Description
1.0 4/19/06 P.Smith Initial coding

1. Introduction

This document describes how to write a custom Resource Manager (RM) which runs on the NC and how to access the RM from the GBA.  A Resource Manager (RM) is a simply a group of functions that are accessed using standard Unix file i/o semantics (i.e., open, close, seek, read, write, ioctl; plus one non-standard call, ioctlv).  There are a number of pre-defined RM's that, for example, provide an interface to specific NC hardware capabilities or provide some application-oriented functionality.  An RM can be used to offload processing from the GBA to the NC, or to allow the GBA to make use of special NC capabilities.  The sample RM, called calc, demonstrates how to move some processing from the GBA to the NC.  The sample GBA application, called calcdemo, shows how to access the calc RM from the GBA.  In the calcdemo application, all user input and output is performed on the GBA, and all calculations are performed on the NC via the calc RM.

Although this document focuses on a very simple RM, at least one example of a complex application-oriented RM is included in the NC SDK -- the MP3 decoder RM (found in $ROOT/usr/src/sc/mp3) along with a GBA application that uses it (found in $ROOT/usr/src/gba/mplayer). 

2. Compiling and Running Calcdemo

Install the SDK and unpack the calcdemo.tar.gz into $ROOT/usr/src/gba, where $ROOT is the directory where the NC SDK is installed --

% cd $ROOT/usr/src/gba

% tar xvfz calcdemo.tar.gz

% cd calcdemo

% make

To run the calcdemo application, start ncproxy (or vnproxy) in its own window --

% $ROOT/usr/bin/win32/ncproxy -i -p

And in another window, start ncshell and load the application onto the NC --

% $ROOT/usr/bin/win32/ncshell

> import <ROOT>/usr/src/gba/calcdemo/gba/calcdemo.wad              <-- ncshell doesn't expand env variables, <ROOT> is the expanded value of $ROOT

> q

Now, power cycle the GBA and when the GBA boots up again use the up/down arrows to locate the "calcdemo" application and hit the "A" button to launch it.

3. Using the demo

Calcdemo is a very simple calculator.  When it starts running, it'll display on the GBA screen a list of the operations performed by each key --

key operation
--- --------------------
U/D incr/decr A
L/R decr/incr B
A compute A + B
B compute A - B
L/R toggle output format
SEL swap A and B


Hit the up or down arrows to increment or decrement the value of "A".  Hit the left or right arrows to increment or decrement the value of "B".  Hit the A button to display the sum of "A" and "B".  Hit the B button to display the difference between "A" and "B".  Hit the Select button to swap the values of "A" and "B".  Finally, the format of the string used to display the result of the sum or difference calculation is controlled by the L and R buttons.  The R button scrolls forward through the possible formats; the L button scrolls backward through the formats.

As you run the demo, you'll see a number of statements being printed in the ncproxy window.  The statements prefixed with "gba:" are originating from the GBA application, calcdemo, whereas those prefixed with "CALC:" originate from the calc RM.  These statements can be used to observe the flow of control while the application is running, and can prove invaluable when debugging.

4. Calcdemo, the GBA Application

This sections addresses those aspects of GBA programming necessary for accessing an RM running on the NC; other aspects of GBA programming are beyond the scope of this document.

As noted in the previous section, it is possible to generate output message from the GBA using the printf() function call.  The printf() messages propagate from the GBA to the NC across the cartridge bus interface, and from the NC to the host system (i.e., where ncproxy is running) across the USB interface.  In order to use this functionality, you must link in the following libraries --

Note that calling printf() will cause your application to hang if ncproxy (or vnproxy) isn't running or if a USB cable isn't connected between the NC and the host system.  For this reason, printf()'s are mainly useful as a debugging aid and not for production code; therefore, the USB Virtual I/O library shouldn't generally be needed for production software builds.

The first call to printf() can be found in the calcdemo ($ROOT/usr/src/gba/calcdemo/gba/Main.c) subroutine InitMainSequence().  The subsequent lines of code open and access the calc RM running on the NC.  All accesses to the RM occur through the IOS_* file i/o routines (prototypes extracted from $ROOT/usr/include/gba/ios.h) --

These routines act like their Unix counterparts, open, close, read, etc., except for IOS_Ioctlv() which will be described in the section on the calc RM.  Whenever IOS_* calls are made from the GBA, the $ROOT/usr/lib/gba/libios.a library and the <gba/ios.h> header file are needed.  The additional information, such as error codes, can be found in $ROOT/usr/include/sc/iostypes.h.  Note that iostypes.h shows that all error values are negative, so generally the IOS_* routines return a negative value on error and a non-negative value on success.

The code to open the calc RM is as follows --

if ( (fd = rv = IOS_Open("/dev/calc0", 1)) < 0 ) {
	printf("gba: error: failed to open /dev/calc, rv = %d\n",rv);
}

The first argument to IOS_Open() specifies the pathname of the RM to be accessed.  In this case, the RM pathname is "/dev/calc0".  In the next section, we'll see where the RM checks the pathname to determine whether it should respond to the IOS_Open() call.  Note that the pathname can be used as a prefix, allowing additional information to be passed at the end; see the MP3 RM for an example, where the name of the MP3 file to be operated on is appended to the root of the RM pathname.

The value of the second argument to the IOS_Open() call is defined by the RM being opened.  In this case the flags argument isn't used, but traditionally this is where you'd specify whether you're opening the device for reading, writing, or both.

Finally, the result of the IOS_Open() call is assigned to rv (of type s32) and to fd (of type IOSFd, i.e., s32).  fd is the file descriptor used to allow further accesses to the RM.  If an error occurs (i.e., the return value is less than zero), then the error code is printed out.  See $ROOT/usr/include/sc/iostypes.h for a list of the standard error codes.

Once the calc RM has been successfully opened, the following IOS_Ioctl() call is made --

/* get initial value of a */
if ( (rv = IOS_Ioctl(fd, CALC_GET_A, 0, 0, &a, sizeof(a))) != IOS_ERROR_OK ) {
	printf("gba: unable to get initial value of a, rv = %d\n",rv);
}

The file descriptor, fd, obtained from the IOS_Open() call is used to specify which RM to access with the IOS_Ioctl() call.  The command argument, CALC_GET_A, is defined in the calc.h header file which is also #include'd by the calc RM.  In this case, there is no input parameter (so input = input_bytes = 0) and one 32-bit output parameter.  Note that for the first time we're passing a parameter by reference (i.e., &a) instead of by value.  In order to pass by reference, the variable to be referenced must reside in a memory segment that can be accessed by both the GBA and the NC (RM), i.e., in the Game PAK ROM area between 0x08000000 and 0x097fffff.  (Even though the Game PAK ROM window extends up to 0x09ffffff, the region between 0x09800000 and 0x09ffffff is reserved for NC-specific code, such as the NC's OS and device drivers.)  Also, keep in mind that the GBA application code and the calc RM code will also have to reside within the 0x08000000 - 0x097ffffff window, so this address space must be shared between (1) the GBA application code, (2) the data to be passed between the GBA and the NC/RM, and (3) the NC/RM code.

To ensure that variables to be passed by reference are allocated in the Game PAK ROM area, you'll see the following code in the GBA application --

static s32 a __attribute__((section(".data")));

The "__attribute__((section(".data")))" clause notifies the compiler to allocate the variable in the ".data" memory segment.  The linker places the ".data" segment after the ".text" segment in memory and looking at the associated Makefile (in $ROOT/usr/src/calcdemo/gba) you'll see where the ".text" memory segment base address is specified --

LLDOPTS = -Ttext 0x08000000 -Tbss 0x03000000 

The "-Ttext 0x08000000" argument tells the compiler to locate the ".text" segment starting at address 0x08000000; therefore the ".data" segment will be located at some address above 0x08000000.  As an aside, note that the -Tbss argument tells the compiler to locate the ".bss" segment at address 0x03000000, i.e., in the GBA's CPU Internal Working RAM.  A link map showing where all of the memory segments are located can be generated by adding the "-Xlinker -M" flags to LLDOPTS.

Keep in mind that all variables to be passed by reference to an IOS_* system call must be allocated in the ".data" segment.  If an IOS_* call receives a reference to a variable not located in the Game PAK ROM window, an IOS_ERROR_INVALID error will be reported.

The remaining IOS_* calls to the calc RM can be readily understood given the examples above and by analogy with the standard Unix file i/o calls.  One remaining topic is how a GBA application is linked together with the relevant RM code.  The following lines from the Makefile for the example GBA application demonstrates how the GBA application is associated with the user-defined RM --

calcdemo.mrg: app.elf ../sc/calc.elf
	$(MERGE) -o $@ -g app.elf -n ../sc/calc.elf  

Here, app.elf is the linked output of the GBA application and ../sc/calc.elf is the linked output of the calc RM.  From $ROOT/usr/include/make/GBAdefs we see that MERGE is defined as $(ROOT)/usr/bin/x86/arm-elf-merge; thus, typing "$ROOT/usr/bin/x86/arm-elf-merge" gives the following usage information --

usage: <ROOT>/usr/bin/x86/arm-elf-merge
-k, --sk filename - SK executable file.
-s, --sd_addr <addr> - Shared Data Segment address.
-z, --sd_size <size> - Shared Data Segement size in bytes.
-f, --file_system filename - File System executable file.
-e, --eT_mgr filename - eTicket Manager executable file.
-v, --vn filename - Virtual Network executable file.
-u, --usb filename - USB executable file.
-a, --audio filename - Audio executable file.
-n, --nc filename - NC executable file.
-g, --gba filename - GBA executable file.
-G, --GBA filename - GBA ROM file.
-l, --viewer filename - Viewer executable file.
-d, --devmon filename - Devmon executable file.
-o, --outfile filename - output file.
-h, --help - print this message.

The GBA executable is specified with the "-g" flag and the NC executable (i.e., the user-defined RM) is specified with the "-n" flag.  The name of the merged executable is specified with the "-o" flag.  Finally, the application must be published before it can be loaded onto the NC and run on the GBA --

calcdemo.wad: calcdemo.mrg
	$(PUBLISH) -n calcdemo -l $^

The resulting application, calcdemo.wad, can be downloaded to the NC and run as detailed in the Compiling and Running Calcdemo Section above.
 

5. Calc, the NC Resource Manager

This section focuses on development of a Resource Manager (RM) that runs on the NC.  The source code for the example RM, called calc, can be found in $ROOT/usr/src/gba/calcdemo/sc.  Note that "sc" is an earlier name for "nc", the Network Cartridge.

As with the GBA code, it is also possible to print debugging statements from within the NC/RM code via a printf() call.  In the NC case, the printf() depends on the following libraries --

As before, since printf() requires the presence of a host system running ncproxy (or vnproxy), it is mainly useful for debugging purposes and not for production code.  When printf() (or other routines which access files on the host system, such as fopen(), fread(), fwrite(), etc.) aren't used, the vio_usb.a library isn't needed.

Looking at the top of the calc RM source code in $ROOT/usr/src/gba/calcdemo/sc/calc.c we see where the "CALC:" prefix at the beginning of the NC's debugging statements comes from --

/* debugging macros */
#define CALC_DEBUG /* define CALC_DEBUG to enable debugging */
#ifdef CALC_DEBUG
 #define CALC_LOG(...) printf("CALC: " __VA_ARGS__)
 #define CALC_ERROR(msg) printf("CALC: Error: %s failed\n", msg)
#else
 #define CALC_LOG(...) /* printf("CALC: " __VA_ARGS__) */
 #define CALC_ERROR(msg) /* printf("CALC: Error: %s failed\n", msg) */
#endif

Skipping forward to the main() function, we see where the RM is registered with the pathname "/dev/calc" --

/* Register the RM (and its message queue) with the kernel */
if ((rv = IOS_RegisterResourceManager("/dev/calc", mq)) != IOS_ERROR_OK) {
	CALC_ERROR("IOS_RegisterResourceManager");
	goto out;
}

The pathname supplied to the IOS_RegisterResourceManager() call is used by an application wishing to access the RM. Note again that the pathname is a prefix, as we'll see when discussing calcOpen() below.  Whenever a user attempts to access a device name beginning with "/dev/calc" (using the IOS_Open() call, for example), the calc RM will be invoked.

Keep in mind that each RM must have its own message queue (created by calling IOS_CreateMessageQueue()).  The depth of the message queue depends on the usage model for the RM.  When an RM's queue becomes full, IOS_* calls to the RM will block until room becomes available in the queue.

It is worth mentioning that in this simple case the NC main() only starts one RM.  In a more sophisticated case, main() could start several threads, each registering its own RM.

After registering the calc RM, main() enters an infinite loop, waiting for messages on its queue and then processing them.  The messages are generated as a result of IOS_* file i/o calls performed on the GBA or on the NC.  In addition, messages can also be sent explicitly using IOS_SendMessage() and related IOS_* system calls (see the MP3 decoder RM in $ROOT/usr/src/sc/mp3 for examples).  The definition of the IOSResourceRequest messages generated by IOS_* file i/o calls can be found in $ROOT/usr/include/sc/iostypes.h.

For an IOS_Open() call, we see that the message is dispatched to the calcOpen() routine --

/* Dispatch command */
IOSResourceRequest *req = (IOSResourceRequest *) msg;
switch (req->cmd) {
case IOS_OPEN:
	CALC_LOG(" IOS_OPEN\n");
	rv = calcOpen(req);
	break;
...

Note that calcOpen() must decide whether or not to process the request based on the path argument in the message (which comes from the pathname argument in the IOS_Open() call).  If the RM does not handle the requested path, then it must return IOS_ERROR_NOEXISTS so that the operating system will know to keep looking for an RM which can handle the given path.  The relevant code is --

#define CALC_DEV0 "/dev/calc0"
#define CALC_DEV1 "/dev/calc1"
#define CALC_DEV2 "/dev/calc2"
...
if (!strncmp(args->path, CALC_DEV0, sizeof(CALC_DEV0)-1)) {
	dev = 0;
} else if (!strncmp(args->path, CALC_DEV1, sizeof(CALC_DEV1)-1)) {
	dev = 1;
} else if (!strncmp(args->path, CALC_DEV2, sizeof(CALC_DEV2)-1)) {
	dev = 2;
} else {
	rv = IOS_ERROR_NOEXISTS;
	goto out;
}

Here we see that the calc RM actually provides 3 variations of the /dev/calc device.  Although all instances behave identically in this example, it is commonly the case that they would all behave slightly differently.  If the pathname specified to IOS_Open() doesn't match any of the 3 paths supported by this RM, then IOS_ERROR_NOEXISTS is returned and the operating system will proceed to check whether any of the remaining RMs can handle the specified pathname.  Note that the pathnames recognized by the calc RM all start with the "/dev/calc" prefix given as an argument to IOS_RegisterResourceManager() when the RM was registered.  The remainder of the pathname following the prefix can be used to pass addition information to the RM; see the MP3 RM for an example, where the name of the MP3 file to be operated on is appended to the pathname root.

If the IOS_Open() pathname matches one of those supported by the calc RM, then a free device descriptor is sought.  If none are free, then all device descriptors must already be in use and IOS_ERROR_MAX is returned.  A device descriptor contains the full state information for a given instance of an RM.  The file descriptor returned as a result of a successful IOS_Open() call is simply a handle that allows the OS to location the device descriptor.  Subsequent IOS_* file i/o calls cause a pointer to the relevant device descriptor to be included in the IOSResourceRequest message; thus, the RM can expect a valid device descriptor to be available on all RM calls except for IOS_OPEN.  The calc RM supports 2 simultaneously-open instances of /dev/calc --

#define CALC_NUM_DESCRIPTORS 2 /* number of instance of device */
static CalcDeviceDescriptor desc[CALC_NUM_DESCRIPTORS];

If a free device descriptor is found, the descriptor is mark as "in use" and its contents are initialized.  The address of the device descriptor is returned by calcOpen(), allowing control to pass back to main() where the response is returned to the user via a call to IOS_ResourceReply().  Normally, the response sent via IOS_ResourceReply() is passed directly through to the IOS_* file i/o caller, but in the case of IOS_Open() the OS first maps the device descriptor address into an IOSFd handle and returns the handle to the caller.  At this point, main() returns to the top of its infinite loop and waits for another message to process.

In the calcdemo case, then next message the calc RM will receive will be from the IOS_Ioctl() call made by the GBA (in $ROOT/usr/src/gba/calcdemo/gba/Main.c) --

/* get initial value of a */
if ( (rv = IOS_Ioctl(fd, CALC_GET_A, 0, 0, &a, sizeof(a))) != IOS_ERROR_OK ) {
printf("gba: unable to get initial value of a, rv = %d\n",rv);
}

The NC main() will receive an IOS_IOCTL message and call the calcIoctl() routine.  Note that calcIoctl() is able to obtain the device descriptor as well as the IOS_Ioctl() arguments from the IOS_ResourceRequest message --

static IOSError
calcIoctl(IOSResourceRequest *req)
{
	IOSError rv = IOS_ERROR_OK;
	CalcDeviceDescriptor *d = (CalcDeviceDescriptor *) req->handle;
	IOSResourceIoctl *args = (IOSResourceIoctl *)&req->args.ioctl;

Then calcIoctl() proceeds to check the input arguments and return an error message, if warranted.  Next, one of several operations is performed, depending on the command code specified in the IOS_Ioctl() call.  Note that the command codes are defined in a separate header file, calc.h, thus allowing the same #define's to be #include'd by both the RM code and the (GBA) application code.  Once the requested operation is completed, a value of IOS_ERROR_OK is returned (on success).  Any other non-negative value could be returned instead; returning negative values is somewhat more complicated because the OS itself returns negative values if it detects certain errors with the IOS_* arguments.  Thus, negative return values are best reserved to indicate errors.  See $ROOT/usr/include/sc/iostypes.h for a list of the standard error codes used by the OS.  calcRead(), calcWrite(), and calcSeek() are examples of RM calls that return a negative value on error and zero or a positive number on success.

A quick word about the IOS_Ioctlv() call -- this is an extension of the IOS_Ioctl() call which allows multiple input (and/or output) arguments to be passed without having to group them all together in contiguous memory.  The IOS_Ioctlv() prototype is as follows --

typedef struct {
	u8 *base;
	u32 length;
} IOSIoVector;
s32 IOS_Ioctlv(IOSFd fd, s32 cmd, u32 readCount, u32 writeCount, IOSIoVector * vector);

The last argument is a pointer to an array of IOSIoVectors which contain pointer/size pairs.  Each element of the IOSIoVector array is set to contain the location and size of one of the input or output arguments.  The input arguments are given first, followed by the output arguments.  The number of input and output arguments are specified via the readCount and writeCount parameters.  Note that the IOSIoVector array must be large enough to hold readCount + writeCount elements.  See calcIoctlv() for an example of decoding the IOSIoVector within the RM.

Before the RM can be run, the associated thread (main(), in this case) must be given a stack and a priority, as shown in the following lines of code extracted from calc.c --

/* thread data for this RM --
 * stack location
 * stack size
 * process priority
 */
#define STACK_SIZE 1024
const u8 _initStack[STACK_SIZE];
const u32 _initStackSize = sizeof(_initStack);
const u32 _initPriority = 10;

The names _initStack, _initStackSize, and _initPriority must not be changed; the C runtime startup code looks for these variables before starting the main() thread.  Recommended values for _initPriority are in the range of 1 to 20.  Note the the NC's OS is fully preempt-able, but not time-sliced; therefore, any thread will run to completion (i.e., until it terminates or blocks waiting for some resource) unless a hardware interrupt occurs and causes a higher-priority task to be run.  As a result, busy-waiting will seriously degrade performance and is very strongly discouraged.

To compile and link the RM, the Makefile includes the following --

LLDLIBS = -lios -lioslibc -lvio_usb -lioslibc 
LLDOPTS = -T $(SDRAM_LINK) 

calc.elf: calc.o $(CRT0)
	$(CC) $(CFLAGS) -Ttext 0x08020000 $(LDFLAGS) -o $@ $^ $(LDLIBS)

LLDLIBS contains the libraries to be linked with the RM code; in this case libios.a, libioslibc.a, and libvio_usb.a, as mentioned at the top of this section.  Sometimes it may be difficult or impossible to order the libraries such that all the dependencies can be resolved in one pass; in this case, simply include the necessary libraries more than once to remove any circular references among libraries.

The LLDOPTS flag "-T $(SDRAM_LINK)" points the linker at a link script; it is required and must always be specified.  Note that the "-Ttext" flags is specified when linking the RM, just as it is when linking the GBA application.  As detailed in the Calcdemo, the GBA Application section above, the RM code, the GBA code, and the data to be passed by reference between the GBA and the NC/RM must share the address space between 0x08000000 and 0x097ffffff.  In this case, the RM code is positioned to start at address 0x08020000, thus leaving 128K bytes of room for the GBA application and the data to be passed between the GBA and the NC/RM.  The $ROOT/usr/bin/x86/arm-elf-merge utility invoked by $MERGE in the application's Makefile will complain if there is a conflict between the GBA code/data and the NC/RM code.  For more detail, you can generate a link map by adding the "-Xlinker -M" flags to LLDOPTS.

Finally, the GBA application will have to be linked with the calc RM as described in the Calcdemo, the GBA Application section above.  Since the $(MERGE) utility only accepts one NC executable (via the -n flag), all of the user-defined RM's to be used by a given GBA application must be linked together into a single NC executable.  As mentioned earlier in this section, this is accomplished by having the NC main() start multiple threads (if need be), registering a separate RM in each one.