# NuttX RTOS Porting Guide Last Updated: January 25, 2014

# Table of Contents

1.0 Introduction
2.0 Directory Structure

2.1 Documentation 2.2 arch/

2.2.1 Subdirectory Structure
2.2.2 Summary of Files
2.2.3 Supported Architectures

2.3 binfmt/
2.4 configs/

2.4.1 Subdirectory Structure
2.4.2 Summary of Files

2.4.2.1 Board Specific Logic
2.4.2.2 Board Specific Configuration Sub-Directories

2.4.3 Supported Boards
2.4.4 Adding a New Board Configuration

2.5 nuttx/drivers/
2.6 nuttx/fs/
2.7 nuttx/graphics/
2.8 nuttx/include/
2.9 nuttx/libc/
2.10 nuttx/libxx/
2.11 nuttx/mm/
2.12 nuttx/net
2.13 nuttx/sched/
2.14 nuttx/syscall/
2.15 nuttx/tools/
2.16 nuttx/Makefile
2.17 apps/netutils
2.18 apps/nshlib
2.19 apps/examples/

3.0 Configuring and Building

3.1 Configuring NuttX
3.2 Building NuttX

4.0 Architecture APIs

4.1 Naming and Header File Conventions
4.2 APIs Exported by Architecture-Specific Logic to NuttX

4.2.1 `up_initialize()`
4.2.2 `up_idle()`
4.2.3 `up_initial_state()`
4.2.4 `up_create_stack()`
4.2.5 `up_use_stack()`
4.2.6 `up_stack_frame()`
4.2.7 `up_release_stack()`
4.2.8 `up_unblock_task()`
4.2.9 `up_block_task()`
4.2.10 `up_release_pending()`
4.2.11 `up_reprioritize_rtr()`
4.2.12 `_exit()`
4.2.13 `up_assert()`
4.2.14 `up_schedule_sigaction()`
4.2.15 `up_allocate_heap()`
4.2.16 `up_interrupt_context()`
4.2.17 `up_disable_irq()`
4.2.18 `up_enable_irq()`
4.2.19 `up_prioritize_irq()` 4.2.20 `up_putc()` 4.2.21 System Time and Clock
4.2.22 Address Environments

4.3 APIs Exported by NuttX to Architecture-Specific Logic

4.3.1 `os_start()`
4.3.2 OS List Management APIs
4.3.3 `sched_process_timer()`
4.3.4 `irq_dispatch()`

4.4 On-Demand Paging
4.5 LED Support

4.5.1 Header Files
4.5.2 LED Definitions
4.5.3 Common LED interfaces

5.0 NuttX File System
6.0 NuttX Device Drivers

6.1 Character Device Drivers
6.2 Block Device Drivers
6.3 Specialized Device Drivers

6.3.1 Ethernet Device Drivers
6.3.2 SPI Device Drivers
6.3.3 I2C Device Drivers
6.3.4 Serial Device Drivers
6.3.5 Frame Buffer Drivers
6.3.6 LCD Drivers
6.3.7 Memory Technology Device Drivers
6.3.8 SDIO Device Drivers
6.3.9 USB Host-Side Drivers
6.3.10 USB Device-Side Drivers
6.3.11 Analog (ADC/DAC) Drivers
6.3.12 PWM Drivers
6.3.13 CAN Drivers
6.3.14 Quadrature Encoder Drivers
6.3.15 Watchdog Timer Drivers
6.3.16 Keyboard/Keypad Drivers

6.4 Power Management

6.4.1 Overview
6.4.2 Interfaces
6.4.3 Callbacks

Appendix A: NuttX Configuration Settings
Appendix B: Trademarks

# 1.0 Introduction

Overview This document provides and overview of the NuttX build and configuration logic and provides hints for the incorporation of new processor/board architectures into the build.

See also `arch/README.txt` and `configs/README.txt`.

# 2.0 Directory Structure

Directory Structure. The general directly layout for NuttX is very similar to the directory structure of the Linux kernel -- at least at the most superficial layers. At the top level is the main makefile and a series of sub-directories identified below and discussed in the following paragraphs:

    .
    |- nuttx
    |   |-- Makefile
    |   |-- Documentation
    |   |   `-- (documentation files)/
    |   |-- arch/
    |   |   |-- <arch-name>/
    |   |   |   |-- include/
    |   |   |   |   |--<chip-name>/
    |   |   |   |   |  `-- (chip-specific header files)
    |   |   |   |   |--<other-chips>/
    |   |   |   |   `-- (architecture-specific header files)
    |   |   |   `-- src/
    |   |   |       |--<chip-name>/
    |   |   |       |  `-- (chip-specific source files)
    |   |   |       |--<other-chips>/
    |   |   |       `-- (architecture-specific source files)
    |   |   `-- <other-architecture directories>/
    |   |-- binfmt/
    |   |   |-- Makefile
    |   |   |-- (binfmt-specific sub-directories)/
    |   |   |   `-- (binfmt-specific source files)
    |   |   `-- (common binfmt source files)
    |   |-- configs/
    |   |   |-- <board-name>/
    |   |   |   |-- include/
    |   |   |   |   `-- (other board-specific header files)
    |   |   |   |-- src/
    |   |   |   |   `-- (board-specific source files)
    |   |   |   |---<config-name>/
    |   |   |   |   `-- (board configuration-specific source files)
    |   |   |   `---(other configuration sub-directories for this board)/
    |   |   `-- <(other board directories)>/
    |   |-- drivers/
    |   |   |-- Makefile
    |   |   |-- (driver-specific sub-directories)/
    |   |   |   `-- (driver-specific source files)
    |   |   `-- (common driver source files)
    |   |-- fs/
    |   |   |-- Makefile
    |   |   |-- (file system-specific sub-directories)/
    |   |   |   `-- (file system-specific source files)
    |   |   `-- (common file system source files)
    |   |-- graphics/
    |   |   |-- Makefile
    |   |   |-- (feature-specific sub-directories)/
    |   |   |   `-- (feature-specific source files library source files)
    |   |   `-- (common graphics-related source files)
    |   |-- include/
    |   |   |-- (standard header files)
    |   |   |-- (standard include sub-directories)
    |   |   |   `-- (more standard header files)
    |   |   |-- (non-standard include sub-directories)
    |   |       `-- (non-standard header files)
    |   |-- libc/
    |   |   |-- Makefile
    |   |   `-- (libc source files)
    |   |-- libxx/
    |   |   |-- Makefile
    |   |   `-- (libxx management source files)
    |   |-- mm/
    |   |   |-- Makefile
    |   |   `-- (memory management source files)
    |   |-- net/
    |   |   |-- Makefile
    |   |   |-- uip/
    |   |   |   `-- (uip source files)
    |   |   `-- (BSD socket source files)
    |   |-- sched/
    |   |   |-- Makefile
    |   |   `-- (sched source files)
    |   |-- syscall/
    |   |   |-- Makefile
    |   |   `-- (syscall source files)
    |   `-- tools/
    |       `-- (miscellaneous scripts and programs)
    `- apps
        |-- netutils/
        |   |-- Makefile
        |   |-- (network feature sub-directories)/
        |   |   `-- (network feature source files)
        |   `-- (netutils common files)
        |--  nshlib/
        |   |-- Makefile
        |   `-- NuttShell (NSH) files
        |-- (Board-specific applications)/
        |   |-- Makefile
        |   |-- (Board-specific application sub-directories)/
        |   |   `-- (Board-specific application source files)
        |   `-- (Board-specific common files)
        `-- examples/
            `-- (example)/
                |-- Makefile
                `-- (example source files)

Configuration Files. The NuttX configuration consists of:

- Processor architecture specific files. These are the files contained in the `arch/`<arch-name>`/` directory and are discussed in a paragraph below.
- Chip/SoC specific files. Each processor processor architecture is embedded in chip or System-on-a-Chip (SoC) architecture. The full chip architecture includes the processor architecture plus chip-specific interrupt logic, clocking logic, general purpose I/O (GIO) logic, and specialized, internal peripherals (such as UARTs, USB, etc.).

  These chip-specific files are contained within chip-specific sub-directories in the `arch/`<arch-name>`/` directory and are selected via the `CONFIG_ARCH_name` selection.

- Board specific configurations. In order to be usable, the chip must be contained in a board environment. The board configuration defines additional properties of the board including such things as peripheral LEDs, external peripherals (such as network, USB, etc.).

  These board-specific configuration files can be found in the `configs/`<board-name>`/` sub-directories and are discussed in a paragraph below.

## 2.1 Documentation

General documentation for the NuttX OS resides in this directory.

## 2.2 nuttx/arch

### 2.2.1 Subdirectory Structure

This directory contains several sub-directories, each containing architecture-specific logic. The task of porting NuttX to a new processor consists of add a new subdirectory under `arch/` containing logic specific to the new architecture. The complete board port in is defined by the architecture-specific code in this directory (plus the board-specific configurations in the `config/` subdirectory). Each architecture must provide a subdirectory, <arch-name> under `arch/` with the following characteristics:

    <arch-name>/
    |-- include/
    |   |--<chip-name>/
    |   |  `-- (chip-specific header files)
    |   |--<other-chips>/
    |   |-- arch.h
    |   |-- irq.h
    |   |-- types.h
    |   |-- limits.h
    |   `-- syscall.h
    `-- src/
        |--<chip-name>/
        |  `-- (chip-specific source files)
        |--<other-chips>/
        |-- Makefile
        `-- (architecture-specific source files)

### 2.2.2 Summary of Files

- `include/`<chip-name>`/` This sub-directory contains chip-specific header files.
- `include/arch.h`: This is a hook for any architecture specific definitions that may be needed by the system. It is included by `include/nuttx/arch.h`.
- `include/types.h`: This provides architecture/toolchain-specific definitions for standard types. This file should `typedef`:
  `_int8_t, _uint8_t, _int16_t, _uint16_t, _int32_t, _uint32_t_t`

  and if the architecture supports 24- or 64-bit integers

  `_int24_t, _uint24_t, int64_t, uint64_t`

  NOTE that these type names have a leading underscore character. This file will be included(indirectly) by include/stdint.h and typedef'ed to the final name without the underscore character. This roundabout way of doings things allows the stdint.h to be removed from the include/ directory in the event that the user prefers to use the definitions provided by their toolchain header files

  And finally

  `irqstate_t`

  Must be defined to the be the size required to hold the interrupt enable/disable state.

  This file will be included by include/sys/types.h and be made available to all files.

- `include/irq.h`: This file needs to define some architecture specific functions (usually inline if the compiler supports inlining) and some structures. These include:
  - `struct xcptcontext`: This structures represents the saved context of a thread.
  - `irqstate_t irqsave(void)`: Used to disable all interrupts.
  - `void irqrestore(irqstate_t flags)`: Used to restore interrupt enables to the same state as before `irqsave()` was called.

  This file must also define `NR_IRQS`, the total number of IRQs supported by the board.

- `include/syscall.h`: This file needs to define some architecture specific functions (usually inline if the compiler supports inlining) to support software interrupts or syscalls that can be used all from user-mode applications into kernel-mode NuttX functions. This directory must always be provided to prevent compilation errors. However, it need only contain valid function declarations if the architecture supports the `CONFIG_NUTTX_KERNEL` configuration.
  - `uintptr_t sys_call0(unsigned int nbr)`: `nbr` is one of the system call numbers that can be found in `include/sys/syscall.h`. This function will perform a system call with no (additional) parameters.
  - `uintptr_t sys_call1(unsigned int nbr, uintptr_t parm1)`: `nbr` is one of the system call numbers that can be found in `include/sys/syscall.h`. This function will perform a system call with one (additional) parameter.
  - `uintptr_t sys_call2(unsigned int nbr, uintptr_t parm1, uintptr_t parm2)`: `nbr` is one of the system call numbers that can be found in `include/sys/syscall.h`. This function will perform a system call with two (additional) parameters.
  - `uintptr_t sys_call3(unsigned int nbr, uintptr_t parm1, uintptr_t parm2, uintptr_t parm3)`: `nbr` is one of the system call numbers that can be found in `include/sys/syscall.h`. This function will perform a system call with three (additional) parameters.
  - `uintptr_t sys_call4(unsigned int nbr, uintptr_t parm1, uintptr_t parm2, uintptr_t parm3, uintptr_t parm4)`: `nbr` is one of the system call numbers that can be found in `include/sys/syscall.h`. This function will perform a system call with four (additional) parameters.
  - `uintptr_t sys_call5(unsigned int nbr, uintptr_t parm1, uintptr_t parm2, uintptr_t parm3, uintptr_t parm4, uintptr_t parm5)`: `nbr` is one of the system call numbers that can be found in `include/sys/syscall.h`. This function will perform a system call with five (additional) parameters.
  - `uintptr_t sys_call6(unsigned int nbr, uintptr_t parm1, uintptr_t parm2, uintptr_t parm3, uintptr_t parm4, uintptr_t parm5, uintptr_t parm6)`: `nbr` is one of the system call numbers that can be found in `include/sys/syscall.h`. This function will perform a system call with six (additional) parameters.

  This file must also define `NR_IRQS`, the total number of IRQs supported by the board.

- `src/`<chip-name>`/` This sub-directory contains chip-specific source files.
- `src/Makefile`: This makefile will be executed to build the targets `src/libup.a` and `src/up_head.o`. The `up_head.o` file holds the entry point into the system (power-on reset entry point, for example). It will be used in the final link with `libup.a` and other system archives to generate the final executable.
- (architecture-specific source files). The file `include/nuttx/arch.h` identifies all of the APIs that must be provided by the architecture specific logic. (It also includes `arch/`<arch-name>`/arch.h` as described above).

### 2.2.3 Supported Architectures

Architecture- and Chip-Specific Directories. All processor architecture-specific directories are maintained in sub-directories of the `arch/` directory. Different chips or SoC's may implement the same processor core. Chip-specific logic can be found in sub-directories under the architecture directory. Current architecture/chip directories are summarized below:

- `arch/sim`: A user-mode port of NuttX to the x86 Linux platform is available. The purpose of this port is primarily to support OS feature development. This port does not support interrupts or a real timer (and hence no round robin scheduler) Otherwise, it is complete.

NOTE: This target will not run on Cygwin probably for many reasons but first off because it uses some of the same symbols as does cygwind.dll.

- `arch/arm`: This directory holds common ARM architectures. At present, this includes the following subdirectories:
  - `arch/arm/include` and `arch/arm/src/common`: Common ARM logic.
  - `arch/arm/include/c5471` and `arch/arm/src/c5471`: TI TMS320C5471 (also called TMS320DM180 or just C5471). NuttX operates on the ARM7 of this dual core processor. This port is complete, verified, and included in the NuttX release 0.1.1.
  - `arch/arm/include/dm320` and `arch/arm/src/dm320`: TI TMS320DM320 (also called just DM320). NuttX operates on the ARM9EJS of this dual core processor. This port complete, verified, and included in the NuttX release 0.2.1.
  - `arch/arm/include/lpc214x` and `arch/arm/src/lpc214x`: These directories provide support for NXP LPC214x family of processors. STATUS: This port boots and passes the OS test (apps/examples/ostest). The port is complete and verified. As of NuttX 0.3.17, the port includes: timer interrupts, serial console, USB driver, and SPI-based MMC/SD card support. A verified NuttShell configuration is also available.
- `configs/mcu123-lpc214x`: The mcu123.com lpc214x development board. This is a work in progress.
- `arch/8051`: 8051 Microcontroller. This port is not quite ready for prime time.
- `arch/z16f`: Zilog z16f Microcontroller. This port uses the Zilog z16f2800100zcog Development Kit. This port was released with nuttx-0.3.7.
- `arch/z80`: This directory holds 8-bit ZiLOG architectures. At present, this includes the Zilog z80, ez80Acclaim! and z8Encore! Microcontrollers.
  - `arch/z80/include` and `arch/z80/src/common`: Common logic.
  - `arch/z80/include/z80` and `arch/z80/src/z80`: The Z80 port was released in nuttx-0.3.6 has been verified using only a z80 instruction simulator. The set simulator can be found in the NuttX GIT at http://sourceforge.net/p/nuttx/git/ci/master/tree/misc/sims/z80sim. This port also uses the SDCC toolchain (http://sdcc.sourceforge.net/") (verified with version 2.6.0 and 2.7.0).
  - `arch/z80/include/ez80` and `arch/z80/src/ez80`: The ez80Acclaim! port uses the ZiLOG ez80f0910200kitg development kit, eZ80F091 part, with the Zilog ZDS-II Windows command line tools. The development environment is Cygwin under WinXP. This is a work in progress. Verified ez80 support will be announced in a future NuttX release.
  - `arch/z80/include/z8` and `arch/z80/src/z8`: The Z8Encore! port uses either the ZiLOG z8encore000zco development kit, Z8F6403 part, or the z8f64200100kit development kit, Z8F6423 part with the Zilog ZDS-II Windows command line tools. The development environment is Cygwin under WinXP. The initial release, verified only on the ZDS-II ez8 simulator, was released in nuttx-0.3.9.

Deprecated Architecture Directories. The following architecture directories are deprecated. They have been replaced by the logic in `arm/arm` and will deleted when `arch/arm` is fully verified.

- `arch/c5471`: Replaced with `arch/arm/include/c5471` and `arch/arm/src/c5471`.
- `arch/dm320`: Replaced with `arch/arm/include/dm320` and `arch/arm/src/dm320`.

Other ports for the for the TI TMS320DM270 and for MIPS are in various states of progress

## 2.3 nuttx/binfmt

The `binfmt/` subdirectory contains logic for loading binaries in the file system into memory in a form that can be used to execute them.

## 2.4 nuttx/configs

The `configs/` subdirectory contains configuration data for each board. These board-specific configurations plus the architecture-specific configurations in the `arch/` subdirectory complete define a customized port of NuttX.

### 2.4.1 Subdirectory Structure

The configs directory contains board specific configuration files. Each board must provide a subdirectory <board-name> under `configs/` with the following characteristics:

    <board-name>
    |-- Kconfig
    |-- include/
    |   |-- board.h
    |   `-- (board-specific header files)
    |-- src/
    |   |-- Makefile
    |   `-- (board-specific source files)
    |-- <config1-dir>
    |   |-- Make.defs
    |   |-- defconfig
    |   `-- setenv.sh
    |-- <config2-dir>
    |   |-- Make.defs
    |   |-- defconfig
    |   `-- setenv.sh
    |   ...
    `-- (other board-specific configuration sub-directories)/

### 2.4.2 Summary of Files

#### 2.4.2.1 Board Specific Logic

- `include/`: This directory contains board specific header files. This directory will be linked as `include/arch/board` at configuration time and can be included via `#include <arch/board/header.h>`. These header file can only be included by files in `arch/`<arch-name>`/include/` and `arch/`<arch-name>`/src/`.
- `src/`: This directory contains board specific drivers. This directory will be linked as arch/<arch-name>`/src/board` at configuration time and will be integrated into the build system.
- `src/Makefile`: This makefile will be invoked to build the board specific drivers. It must support the following targets: `libext$(LIBEXT)`, `clean`, and `distclean`.

#### 2.4.2.2 Board Specific Configuration Sub-Directories

The `configs/`<board-name>`/` sub-directory holds all of the files that are necessary to configure NuttX for the particular board. A board may have various different configurations using the common source files. Each board configuration is described by three files: `Make.defs`, `defconfig`, and `setenv.sh`. Typically, each set of configuration files is retained in a separate configuration sub-directory (<config1-dir>, <config2-dir>, .. in the above diagram). The procedure for configuring NuttX is described below, This paragraph will describe the contents of these configuration files.

- `Make.defs`: This makefile fragment provides architecture and tool-specific build options. It will be included by all other makefiles in the build (once it is installed). This make fragment should define:
  - Tools: `CC`, `LD`, `AR`, `NM`, `OBJCOPY`, `OBJDUMP`
  - Tool options: `CFLAGS`, `LDFLAGS`

  When this makefile fragment runs, it will be passed `TOPDIR` which is the path to the root directory of the build. This makefile fragment should include:

  - `$(TOPDIR)/.config` : Nuttx configuration
  - `$(TOPDIR)/tools/Config.mk` : Common definitions

  Definitions in the `Make.defs` file probably depend on some of the settings in the .`config` file. For example, the `CFLAGS` will most likely be different if `CONFIG_DEBUG=y`.

  The included `tools/Config.mk` file contains additional definitions that may be overriden in the architecture-specific Make.defs file as necessary:

  - `COMPILE`, `ASSEMBLE`, `ARCHIVE`, `CLEAN`, and `MKDEP` macros

- `defconfig`: This is a configuration file similar to the Linux configuration file. In contains variable/value pairs like:

  - `CONFIG_VARIABLE`=value

  This configuration file will be used at build time:

  1. As a makefile fragment included in other makefiles, and
  2. to generate `include/nuttx/config.h` which is included by most C files in the system.

- `setenv.sh`: This is a script that you can include that will be installed at the top level of the directory structure and can be sourced to set any necessary environment variables. You will most likely have to customize the default `setenv.sh` script in order for it to work correctly in your environment.

### 2.4.3 Supported Boards

All of the specific boards supported by NuttX are identified below. These are the specific <board-name>'s that may be used to configure NuttX as described below.

- `configs/avr32dev1`: This is a port of NuttX to the Atmel AVR32DEV1 board. That board is based on the Atmel AT32UC3B0256 MCU and uses a specially patched version of the GNU toolchain: The patches provide support for the AVR32 family. That patched GNU toolchain is available only from the Atmel website. STATUS: This port is functional but very basic. There are configurations for NSH and the OS test.
- `configs/c5471evm`: This is a port to the Spectrum Digital C5471 evaluation board. The C5471 is a dual core processor from TI with an ARM7TDMI general purpose processor and a c54 DSP. It is also known as TMS320DA180 or just DA180. NuttX runs on the ARM core and is built with with a GNU arm-nuttx-elf toolchain under Linux or Cygwin. This port is complete and verified.
- `configs/demo9s12ne64`: Feescale DMO9S12NE64 board based on the MC9S12NE64 hcs12 cpu. This port uses the m9s12x GCC toolchain. STATUS: (Still) under development; it is code complete but has not yet been verified.
- `configs/ea3131`: Embedded Artists EA3131 Development bard. This board is based on the an NXP LPC3131 MCU. This OS is built with the arm-nuttx-elf toolchain. STATUS: This port is complete and mature.
- `configs/eagle100`: Micromint Eagle-100 Development board. This board is based on the an ARM Cortex-M3 MCU, the Luminary LM3S6918. This OS is built with the arm-nuttx-elf toolchain. STATUS: This port is complete and mature.
- `configs/ez80f0910200kitg` ez80Acclaim! Microcontroller. This port use the Zilog ez80f0910200kitg development kit, eZ80F091 part, and the Zilog ZDS-II Windows command line tools. The development environment is Cygwin under WinXP.
- `configs/ez80f910200zco`: ez80Acclaim! Microcontroller. This port use the Zilog ez80f0910200zco development kit, eZ80F091 part, and the Zilog ZDS-II Windows command line tools. The development environment is Cygwin under WinXP.
- `configs/lm3s6965-ek`: Stellaris LM3S6965 Evaluation Kit. This board is based on the an ARM Cortex-M3 MCU, the Luminary/TI LM3S6965. This OS is built with the arm-nuttx-elf toolchain. STATUS: This port is complete and mature.
- `configs/lm3s8962-ek`: Stellaris LMS38962 Evaluation Kit. STATUS: contributed.
- `configs/lpcxpresso-lpc1768`: Embedded Artists base board with NXP LPCExpresso LPC1768. This board is based on the NXP LPC1768. The Code Red toolchain is used by default.
- `configs/mbed`: The configurations in this directory support the mbed board (http://mbed.org) that features the NXP LPC1768 microcontroller. This OS is also built with the arm-nuttx-elf toolchain. STATUS: Contributed.
- `configs/mcu123-lpc214x`: This port is for the NXP LPC2148 as provided on the mcu123.com lpc214x development board. This OS is also built with the arm-nuttx-elf toolchain* under Linux or Cygwin. The port supports serial, timer0, spi, and usb.
- `configs/mirtoo`: This is the port to the DTX1-4000L "Mirtoo" module. This module uses MicroChipPIC32MX250F128D. See the Dimitech website for further information.
- `configs/mx1ads`: This is a port to the Motorola MX1ADS development board. That board is based on the Freescale i.MX1 processor. The i.MX1 is an ARM920T. STATUS: This port is nearly code complete but was never fully integrated due to tool-related issues.
- `configs/ne64badge`: Future Electronics Group NE64 /PoE Badge board based on the MC9S12NE64 hcs12 cpu. This port uses the m9s12x GCC toolchain. STATUS: The port is code-complete but was never fully tested.
- `configs/ntosd-dm320`: This port uses the Neuros OSD with a GNU arm-nuttx-elf toolchain* under Linux or Cygwin. See Neuros Wiki for further information. NuttX operates on the ARM9EJS of this dual core processor. STATUS: This port is code complete, verified, and included in the NuttX 0.2.1 release.
- `configs/nucleus2g`: This port uses the Nucleus 2G board (with Babel CAN board). This board features an NXP LPC1768 processor. See the 2G Engineering website for more information about the Nucleus 2G.
- `configs/olimex-lpc1766stk`: This port uses the Olimex LPC1766-STK board and a GNU GCC toolchain under Linux or Cygwin. STATUS: Complete and mature.
- `configs/olimex-lpc2378`: This port uses the Olimex-lpc2378 board and a GNU arm-nuttx-elf toolchain under Linux or Cygwin. STATUS: ostest and NSH configurations available.
- `configs/olimex-strp711`: This port uses the Olimex STR-P711 board arm-nuttx-elf toolchain* under Linux or Cygwin. See the Olimex web site for further information. STATUS: Configurations for the basic OS test and NSH are complete and verified.
- `configs/pcblogic-pic32mx`: This is the port of NuttX to the PIC32MX board from PCB Logic Design Co. This board features the MicroChip PIC32MX460F512L. The board is a very simple -- little more than a carrier for the PIC32 MCU plus voltage regulation, debug interface, and an OTG connector. STATUS: Code complete but testing has been stalled due to tool related problems (PICkit 2 does not work with the PIC32).
- `configs/pjrc-8051`: 8051 Microcontroller. This port uses the PJRC 87C52 development system and the SDCC toolchain under Linux or Cygwin. This port is not quite ready for prime time.
- `configs/qemu-i486`: Port of NuttX to QEMU in i486 mode. This port will also run on real i486 hardwared (Google the Bifferboard).
- `configs/rgmp`: RGMP stands for RTOS and GPOS on Multi-Processor. RGMP is a project for running GPOS and RTOS simultaneously on multi-processor platforms. You can port your favorite RTOS to RGMP together with an unmodified Linux to form a hybrid operating system. This makes your application able to use both RTOS and GPOS features. See the RGMP Wiki for further information about RGMP.
- `configs/sam3u-ek`: The port of NuttX to the Atmel SAM3U-EK development board.
- `configs/skp16c26`: Renesas M16C processor on the Renesas SKP16C26 StarterKit. This port uses the GNU m32c toolchain. STATUS: The port is complete but untested due to issues with compiler internal errors.
- `configs/stm3210e-eval`: STMicro STM3210E-EVAL development board based on the STMicro STM32F103ZET6 microcontroller (ARM Cortex-M3). This port uses the GNU Cortex-M3 toolchain.
- `configs/sim`: A user-mode port of NuttX to the x86 Linux platform is available. The purpose of this port is primarily to support OS feature development. This port does not support interrupts or a real timer (and hence no round robin scheduler) Otherwise, it is complete.
- `configs/us7032evb1`: This is a port of the Hitachi SH-1 on the Hitachi SH-1/US7032EVB1 board. STATUS: This port is available as of release 0.3.18 of NuttX. The port is basically complete and many examples run correctly. However, there are remaining instabilities that make the port un-usable. The nature of these is not understood; the behavior is that certain SH-1 instructions stop working as advertised. This could be a silicon problem, some pipeline issue that is not handled properly by the gcc 3.4.5 toolchain (which has very limited SH-1 support to begin with), or perhaps with the CMON debugger. At any rate, I have exhausted all of the energy that I am willing to put into this cool old processor for the time being.
- `configs/vsn`: ISOTEL NetClamps VSN V1.2 ready2go sensor network platform based on the STMicro STM32F103RET6. Contributed by Uros Platise. See the Isotel web site for further information about the NetClamps board.
- `configs/xtrs`: TRS80 Model 3. This port uses a vintage computer based on the Z80. An emulator for this computer is available to run TRS80 programs on a Linux platform (http://www.tim-mann.org/xtrs.html).
- `configs/z16f2800100zcog` z16f Microcontroller. This port use the Zilog z16f2800100zcog development kit and the Zilog ZDS-II Windows command line tools. The development environment is Cygwin under WinXP.
- `configs/z80sim`: z80 Microcontroller. This port uses a Z80 instruction set simulator. That simulator can be found in the NuttX GIT here. This port also the SDCC toolchain under Linux or Cygwin(verified with version 2.6.0).
- `configs/z8encore000zco` z8Encore! Microcontroller. This port use the Zilog z8encore000zco development kit, Z8F6403 part, and the Zilog ZDS-II Windows command line tools. The development environment is Cygwin under WinXP.
- `configs/z8encore000zco` z8Encore! Microcontroller. This port use the Zilog z8f64200100kit development kit, Z8F6423 part, and the Zilog ZDS-II Windows command line tools. The development environment is Cygwin under WinXP.
- `configs/z8f64200100kit`: z8Encore! Microcontroller. This port use the Zilog z8f64200100kit development kit, Z8F6423 part, and the Zilog ZDS-II Windows command line tools. The development environment is Cygwin under WinXP.

> * A customized version of the buildroot is available to build these toolchains under Linux or Cygwin.

### 2.4.4 Adding a New Board Configuration

Okay, so you have created a new board configuration directory. Now, how do you hook this board into the configuration system so that you can select with `make menuconfig`?

You will need modify the file `configs/Kconfig`. Let's look at the STM32F4-Discovery configuration in the `Kconfig` file and see how we would add a new board directory to the configuration. For this configuration let's say that you new board resides in the directory `configs/myboard`; It uses an MCU selected with `CONFIG_ARCH_CHIP_MYMCU`; and you want the board to be selected with `CONFIG_ARCH_BOARD_MYBOARD`. Then here is how you can clone the STM32F4-Discovery configuration in `configs/Kconfig` to support your new board configuration.

In `configs/Kconfig` for the stm32f4-discovery, you will see a configuration definition like this:

    config ARCH_BOARD_STM32F4_DISCOVERY
        bool "STMicro STM32F4-Discovery board"
        depends on ARCH_CHIP_STM32F407VG
        select ARCH_HAVE_LEDS
        select ARCH_HAVE_BUTTONS
        select ARCH_HAVE_IRQBUTTONS
        ---help---
            STMicro STM32F4-Discovery board based on the STMicro STM32F407VGT6 MCU.

The above selects the STM32F4-Discovery board. The `select` lines say that the board has both LEDs and buttons and that the board can generate interrupts from the button presses. You can just copy the above configuration definition to a new location (notice that they the configurations are in alphabetical order). Then you should edit the configuration to support your board. The final configuration definition might look something like:

    config ARCH_BOARD_MYBOARD
        bool "My very own board configuration"
        depends on ARCH_CHIP_MYMCU
        select ARCH_HAVE_LEDS
        select ARCH_HAVE_BUTTONS
        select ARCH_HAVE_IRQBUTTONS
        ---help---
            This options selects the board configuration for my very own board
            based on the MYMCU processor.

Later in the `configs/Kconfig` file, you will see a long, long string configuration with lots of defaults like this:

    config ARCH_BOARD
        string
        default "amber"               if ARCH_BOARD_AMBER
        default "avr32dev1"           if ARCH_BOARD_AVR32DEV1
        default "c5471evm"            if ARCH_BOARD_C5471EVM
    ...
        default "stm32f4discovery"    if ARCH_BOARD_STM32F4_DISCOVERY
    ...

This logic will assign string value to a configuration variable called `CONFIG_ARCH_BOARD` that will name the directory where the board-specific files reside. In our case, these files reside in `configs/myboard` and we add the following to the long list of defaults (again in alphabetical order):

        default "myboar"              if ARCH_BOARD_MYBOARD

Now the build system knows where to find your board configuration!

And finally, add something like this near the bottom of `configs/myboard`:

    if ARCH_BOARD_MYBOARD
    source "configs/myboard/Kconfig"
    endif

This includes additional, board-specific configuration variabled defintion in `configs/myboard/Kconfig`.

## 2.5 nuttx/drivers

This directory holds architecture-independent device drivers.

    drivers/
    |-- Kconfig
    |-- Makefile
    |-- analog/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (Common ADC and DAC driver source files)
    |-- bch/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (bch driver source files)
    |-- input/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (Common touchscreen and keypad driver source files)
    |-- lcd/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (Common LCD driver source files)
    |-- mmcsd/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (Common MMC/SD card driver source files)
    |-- mtd/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (Common memory technology device driver source files)
    |-- net/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (Common network driver source files)
    |-- sensors/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (Common sensor driver source files)
    |-- serial/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (Files for the Calypso SERCOMM driver)
    |-- serial/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (Common front-end character drivers for chip-specific UARTs)
    |-- usbdev/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (Common USB device driver source files)
    |-- usbhost/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (Common USB host driver source files)
    |-- wireless/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (Common wireless driver source files)
    `-- (Various common driver source files)

## 2.6 nuttx/fs

This directory contains the NuttX file system. This file system is described below.

    fs/
    |-- Kconfig
    |-- Makefile
    |-- fat/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (FAT file system source files)
    |-- mmap/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (RAM-based file mapping source files)
    |-- nfs/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (NFS client file system source files)
    |-- nxffs/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (NuttX Flash File System (NXFFS) source files)
    |-- romfs/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (ROMFS file system source files)
     `-- (common file system source files)

## 2.7 nuttx/graphics

This directory contains files for graphics/video support under NuttX.

    graphics/
    |-- Kconfig
    |-- Makefile
    |-- nxbe/
    |   |-- Make.defs
    |   `-- (NuttX graphics back-end (NXBE) source files)
    |-- nxfont/
    |   |-- Make.defs
    |   `-- (NuttX graphics font-related (NXFONT) source files)
    |-- nxglib/
    |   |-- Make.defs
    |   `-- (NuttX graphics library (NXGL) source files)
    |-- nxmu/
    |   |-- Make.defs
    |   `-- (NuttX graphics multi-user (NXMU) server source files)
    |-- nxsu/
    |   |-- Make.defs
    |   `-- (NuttX graphics single-user (NXSU) source files)
    `-- (common file system source files)

## 2.8 nuttx/include

This directory holds NuttX header files. Standard header files file retained in can be included in the normal fashion:

`include <stdio.h>`
`include <sys/types.h>`
etc.

Directory structure:

    include/
    |-- (standard header files)
    |-- arpa/
    |   `-- (Standard header files)
    |-- cxx/
    |   `-- (C++ standard header files)
    |-- netinet/
    |   `-- (Standard header files)
    |-- nuttx/
    |   |-net/
    |   | `-- uip/
    |   |     `-- (uIP specific header files)
    |   `-- (NuttX specific header files)
    `- sys/
        `-- (More standard header files)

## 2.9 nuttx/libc

This directory holds a collection of standard libc-like functions with custom interfaces into NuttX.

Normally the logic in this file builds to a single library (`libc.a`). However, if NuttX is built as a separately compiled kernel (with `CONFIG_NUTTX_KERNEL=y`), then the contents of this directory are built as two libraries: One for use by user programs (`libuc.a`) and one for use only within the <kernel> space (`libkc.a`).

These user/kernel space libraries (along with the sycalls of `nuttx/syscall`) are needed to support the two differing protection domains.

Directory structure:

    libc/
    |-- libgen/
    |   `-- (Implementation of functions from libgen.h)
    |-- math/
    |   `-- (Implementation of functions from fixedmath.h)
    |-- misc/
    |   `-- (Implementation of miscellaneous library functions)
    |-- mqueue/
    |   `-- (Implementation of some functions from mqueue.h)
    |-- net/
    |   `-- (Implementation of network-related library functions)
    |-- queue/
    |   `-- (Implementation of functions from queue.h)
    |-- sched/
    |   `-- (Implementation of some functions from sched.h)
    |-- semaphore/
    |   `-- (Implementation of some functions from semaphore.h)
    |-- signal/
    |   `-- (Implementation of some functions from signal.h)
    |-- stdio/
    |   `-- (Implementation of functions from stdio.h)
    |-- stdlib/
    |   `-- (Implementation of functions from stdlib.h)
    |-- string/
    |   `-- (Implementation of functions from string.h)
    |-- time/
    |   `-- (Implementation of some functions from time.h)
    `-- unistd/
        `-- (Implementation of some functions from unistd.h)

## 2.10 nuttx/libxx

This directory holds a tiny, minimal standard std C++ that can be used to build some, simple C++ applications in NuttX.

## 2.11 nuttx/mm

This is the NuttX memory manager.

## 2.12 nuttx/net

This directory contains the implementation of the NuttX internal socket APIs. The subdirectory, `uip` contains the uIP port.

## 2.13 nuttx/sched

The files forming core of the NuttX RTOS reside here.

## 2.14 nuttx/syscall

If NuttX is built as a separately compiled kernel (with `CONFIG_NUTTX_KERNEL=y`), then the contents of this directory are built. This directory holds a syscall interface that can be used for communication between user-mode applications and the kernel-mode RTOS.

## 2.15 nuttx/tools

This directory holds a collection of tools and scripts to simplify configuring, building and maintaining NuttX.

    tools/
    |-- Makefile.host
    |-- Makefile.export
    |-- README.txt
    |-- configure.sh / configure.bat
    |-- cfgparser.c
    |-- cfgparser.h
    |-- copydir.sh / copydir.bat
    |-- define.sh / define.bat
    |-- incdir.sh / indir.bat
    |-- indent.sh
    |-- link.sh / link.bat
    |-- mkconfig.c
    |-- mkdeps.sh / mkdeps.bat
    |-- mkexport.sh
    |-- mkimage.sh
    |-- mknulldeps.sh
    |-- mkromfsimg.sh
    |-- mksyscall.c
    |-- mkversion.c
    |-- unlink.sh / unlink.bat
    |-- version.sh
    `-- zipme.sh

Refer to the README file in the `tools` directory for more information about the individual files. Some of these tools are discussed below as well in the discussion of configuring and building NuttX.

## 2.16 nuttx/Makefile

The top-level `Makefile` in the `${TOPDIR}` directory contains all of the top-level control logic to build NuttX. Use of this `Makefile` to build NuttX is described below.

## 2.17 apps/netutils

This directory contains most of the network applications. Some of these are original with NuttX (like tftpc and dhcpd) and others were leveraged from the uIP-1.0 apps directory. As the uIP apps/README says, these applications "are not all heavily tested."

    netutils/
    |-- Kconfig
    |-- Makefile
    |-- dhcdp/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (DHCP client source files)
    |-- dhcpd/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (DHCP server source files)
    |-- ftpc/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (FTP client source files)
    |-- ftpd/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (FTP server source files)
    |-- resolv/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (resolv source files)
    |-- resolv/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (resolv source files)
    |-- smtp/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (smtp source files)
    |-- telnetd/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (Telnet client source files)
    |-- tftpc/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (TFTP client source files)
    |-- thttpd/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (thttpd HTTP server source files)
    |-- uiplib/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (uiplib source files)
    |-- weblclient/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (webclient source files)
    |-- webserver/
    |   |-- Kconfig
    |   |-- Make.defs
    |   `-- (uIP webserver source files)
    `-- (netutils common files)

## 2.18 apps/nshlib

This directory contains for the core of the NuttShell (NSH) application.

## 2.19 apps/examples

Example and test programs to build against.

# 3.0 Configuring and Building

## 3.1 Configuring NuttX

Manual Configuration. Configuring NuttX requires only copying the board-specific configuration files into the top level directory which appears in the make files as the make variable, `${TOPDIR}`. This could be done manually as follows:

- Copy `configs/`<board-name>`/[`<config-dir>`/]Make.defs` to `${TOPDIR}/Make.defs`,
- Copy `configs/`<board-name>`/[`<config-dir>`/]setenv.sh` to `${TOPDIR}/setenv.sh`, and
- Copy `configs/`<board-name>`/[`<config-dir>`/]defconfig` to `${TOPDIR}/.config`

Where <board-name> is the name of one of the sub-directories of the NuttX `configs/` directory. This sub-directory name corresponds to one of the supported boards identified above. <config-dir> is the optional, specific configuration directory for the board. And <app-dir> is the location of the optonal application directory.

Automated Configuration. There is a script that automates these steps. The following steps will accomplish the same configuration:

      cd tools
      ./configure.sh <board-name>[/<config-dir>]

There is an alternative Windows batch file, `configure.bat`, that can be used insteach of `configure.sh` in the windows native enironment like:

      cd tools
      configure.bat <board-name>[\<config-dir>]

See `tools/README.txt` for more information about these scripts.

If your application directory is not in the standard loction (`../apps` or `../apps-<version>`), then you should also specify the location of the application directory on the command line like:

      cd tools
      ./configure.sh -a <app-dir> <board-name>[/<config-dir>]

Version Files. The NuttX build expects to find a version file located in the top-level NuttX build directory. That version file is called `.version`. The correct version file is installed in each versioned NuttX released. However, if you are working from an GIT snapshot, then there will be no version file. If there is no version file, the top-level `Makefile` will create a dummy `.version` file on the first make. This dummy version file will contain all zeroes for version information. If that is not what you want, they you should run the `version.sh` script to create a better `.version` file.

You can get help information from the `version.sh` script using the `-h` option. For example:

    $ tools/version.sh -h
    tools/version.sh is a tool for generation of proper version files for the NuttX build

    USAGE: tools/version.sh [-d|-h] [-b build] -v <major.minor> <outfile-path>

    Where:
            -d
                    Enable script debug
            -h
                    show this help message and exit
            -v <major.minor>
                    The NuttX version number expressed a major and minor number separated
                    by a period
            <outfile-path>
                    The full path to the version file to be created

As an example, the following command will generate a version file for version 6.1 using the current GIT revision number:

    tools/version.h -v 6.1 .version

The `.version` file is also used during the build process to create a C header file at `include/nuttx/version.h` that contains the same version information. That version file may be used by your C applications for, as an example, reporting version information.

Additional Configuration Steps. The remainder of configuration steps will be performed by `${TOPDIR}/Makefile` the first time the system is built as described below.

## 3.2 Building NuttX

Building NuttX. Once NuttX has been configured as described above, it may be built as follows:

    cd ${TOPDIR}
    source ./setenv.sh
    make

The `${TOPDIR}` directory holds:

- The top level `Makefile` that controls the NuttX build.

That directory also holds:

- The makefile fragment `.config` that describes the current configuration.
- The makefile fragment `Make.defs` that provides customized build targets, and
- The shell script `setenv.sh` that sets up the configuration environment for the build.

The `setenv.sh` contains Linux/Cygwin environmental settings that are needed for the build. The specific environmental definitions are unique for each board but should include, as a minimum, updates to the `PATH` variable to include the full path to the architecture-specific toolchain identified in `Make.defs`. The `setenv.sh` only needs to be source'ed at the beginning of a session. The system can be re-made subsequently by just typing `make`.

First Time Make. Additional configuration actions will be taken the first time that system is built. These additional steps include:

- Auto-generating the file `include/nuttx/config.h` using the `${TOPDIR}/.config` file.
- Auto-generating the file `${TOPDIR}/.version` with version 0.0 if one does not exist.
- Auto-generating the file `include/nuttx/version.h` using the `${TOPDIR}/.version` file.
- Creating a link to `${TOPDIR}/arch/`<arch-name>`/include` at `${TOPDIR}/include/arch`.
- Creating a link to `${TOPDIR}/configs/`<board-name>`/include` at `${TOPDIR}/include/arch/board`.
- Creating a link to `${TOPDIR}/configs/`<board-name>`/src` at `${TOPDIR}/arch/`<arch-name>`/src/board`
- Creating a link to `${APPDIR}/include` at `${TOPDIR}/include/apps`
- Creating make dependencies.

# 4.0 Architecture APIs

The file `include/nuttx/arch.h` identifies by prototype all of the APIs that must be provided by the architecture specific logic. The internal OS APIs that architecture-specific logic must interface with also also identified in `include/nuttx/arch.h` or in other header files.

## 4.1 Naming and Header File Conventions

- Common Microprocessor Interfaces. Any interface that is common to all microprocessors should be prefixed with `up_` and prototyped in `include/nuttx/arch.h`. The definitions in that header file provide the common interface between NuttX and the architecture-specific implementation in `arch/`.

  > `up_` is supposed to stand for microprocessor; the `u` is like the Greek letter micron: µ. So it would be `µP` which is a common shortening of the word microprocessor. I don't like that name very much. I wish I would have used a more obvious prefix like `arch_` instead -- then I would not have to answer this question so often.

- Microprocessor-Specific Interfaces. An interface which is unique to a certain microprocessor should be prefixed with the name of the microprocessor, for example `stm32_`, and be prototyped in some header file in the `arch/` directories.

  There is also a `arch//include//chip.h` header file that can be used to communicate other microprocessor-specific information between the board logic and even application logic. Application logic may, for example, need to know specific capabilities of the chip. Prototypes in that `chip.h` header file should follow the microprocessor-specific naming convention.

- Common Board Interfaces. Any interface that is common to all boards should be prefixed with `board_` and should also be prototyped in `include/nuttx/arch.h`. These `board_` definitions provide the interface between the board-level logic and the architecture-specific logic.

  There is also a `configs//include/board.h` header file that can be used to communicate other board-specific information between the architecture logic and even application logic. Any definitions which are common between a single architecture and several boards should go in this `board.h` header file; `include/nuttx/arch.h`is reserved for board-related definitions common to all architectures.

- Board-Specific Interfaces. Any interface which is unique to a board should be prefixed with the board name, for example `stm32f4discovery_`. Sometimes the board name is too long so `stm32_` would be okay too. These should be prototyped in `configs//src/.h` and should not be used outside of that directory since board-specific definitions have no meaning outside of the board directory.

## 4.2 APIs Exported by Architecture-Specific Logic to NuttX

### 4.2.1 `up_initialize()`

Prototype: `void up_initialize(void);`

Description. `up_initialize()` will be called once during OS initialization after the basic OS services have been initialized. The architecture specific details of initializing the OS will be handled here. Such things as setting up interrupt service routines, starting the clock, and registering device drivers are some of the things that are different for each processor and hardware platform.

`up_initialize()` is called after the OS initialized but before the init process has been started and before the libraries have been initialized. OS services and driver services are available.

### 4.2.2 `up_idle()`

Prototype: `void up_idle(void);`

Description. `up_idle()` is the logic that will be executed when their is no other ready-to-run task. This is processor idle time and will continue until some interrupt occurs to cause a context switch from the idle task.

Processing in this state may be processor-specific. e.g., this is where power management operations might be performed.

### 4.2.3 `up_initial_state()`

Prototype: `void up_initial_state(FAR struct tcb_s *tcb);`

Description. A new thread is being started and a new TCB has been created. This function is called to initialize the processor specific portions of the new TCB.

This function must setup the initial architecture registers and/or stack so that execution will begin at tcb->start on the next context switch.

This function may also need to set up processor registers so that the new thread executes with the correct privileges. If `CONFIG_NUTTX_KERNEL` has been selected in the NuttX configuration, then special initialization may need to be performed depending on the task type specified in the TCB's flags field: Kernel threads will require kernel-mode privileges; User tasks and pthreads should have only user-mode privileges. If `CONFIG_NUTTX_KERNEL` has not been selected, then all threads should have kernel-mode privileges.

### 4.2.4 `up_create_stack()`

Prototype: `STATUS up_create_stack(FAR struct tcb_s *tcb, size_t stack_size, uint8_t ttype);`

Description. Allocate a stack for a new thread and setup up stack-related information in the TCB.

The following TCB fields must be initialized:

- `adj_stack_size`: Stack size after adjustment for hardware, processor, etc. This value is retained only for debug purposes.
- `stack_alloc_ptr`: Pointer to allocated stack
- `adj_stack_ptr`: Adjusted `stack_alloc_ptr` for HW. The initial value of the stack pointer.

This API is NOT required if `CONFIG_CUSTOM_STACK` is defined.

Input Parameters:

- `tcb`: The TCB of new task.

- `stack_size`: The requested stack size. At least this much must be allocated.

- `ttype`: The thread type. This may be one of following (defined in `include/nuttx/sched.h`):

  - `TCB_FLAG_TTYPE_TASK`: Normal user task
  - `TCB_FLAG_TTYPE_PTHREAD`: User pthread
  - `TCB_FLAG_TTYPE_KERNEL`: Kernel thread

  This thread type is normally available in the flags field of the TCB, however, there are certain contexts where the TCB may not be fully initialized when up_create_stack is called.

  If `CONFIG_NUTTX_KERNEL` is defined, then this thread type may affect how the stack is allocated. For example, kernel thread stacks should be allocated from protected kernel memory. Stacks for user tasks and threads must come from memory that is accessible to user code.

### 4.2.5 `up_use_stack()`

Prototype: `STATUS up_use_stack(FAR struct tcb_s *tcb, FAR void *stack, size_t stack_size);`

Description. Setup up stack-related information in the TCB using pre-allocated stack memory. This function is called only from `task_init()` when a task or kernel thread is started (never for pthreads).

The following TCB fields must be initialized:

- `adj_stack_size`: Stack size after adjustment for hardware, processor, etc. This value is retained only for debug purposes.
- `stack_alloc_ptr`: Pointer to allocated stack
- `adj_stack_ptr`: Adjusted `stack_alloc_ptr` for HW. The initial value of the stack pointer.

This API is NOT required if `CONFIG_CUSTOM_STACK` is defined.

Input Parameters:

- `tcb`: The TCB of new task.
- `stack_size`: The allocated stack size.

NOTE: Unlike `up_stack_create()` and `up_stack_release`, this function does not require the task type (`ttype`) parameter. The TCB flags will always be set to provide the task type to `up_use_stack()` if the information needs that information.

### 4.2.6 `up_stack_frame()`

Prototype: `FAR void *up_stack_frame(FAR struct tcb_s *tcb, size_t frame_size);`

Description. Allocate a stack frame in the TCB's stack to hold thread-specific data. This function may be called anytime after `up_create_stack()` or `up_use_stack()` have been called but before the task has been started.

Thread data may be kept in the stack (instead of in the TCB) if it is accessed by the user code directly. This includes such things as `argv[]`. The stack memory is guaranteed to be in the same protection domain as the thread.

The following TCB fields will be re-initialized:

- `adj_stack_size`: Stack size after removal of the stack frame from the stack.
- `adj_stack_ptr`: Adjusted initial stack pointer after the frame has been removed from the stack. This will still be the initial value of the stack pointer when the task is started.

This API is NOT required if `CONFIG_NUTTX_KERNEL` is undefined or if `CONFIG_CUSTOM_STACK` is defined.

Input Parameters:

- `tcb`: The TCB of new task.

- `frame_size`: The size of the stack frame to allocate.

Returned Value: A pointer to bottom of the allocated stack frame. NULL will be returned on any failures. The alignment of the returned value is the same as the alignment of the stack itself

### 4.2.7 `up_release_stack()`

Prototype: `void up_release_stack(FAR struct tcb_s *dtcb);`

Description. A task has been stopped. Free all stack related resources retained int the defunct TCB.

This API is NOT required if `CONFIG_CUSTOM_STACK` is defined.

Input Parameters:

- `dtcb`: The TCB containing information about the stack to be released.

- `ttype`: The thread type. This may be one of following (defined in `include/nuttx/sched.h`):

  - `TCB_FLAG_TTYPE_TASK`: Normal user task
  - `TCB_FLAG_TTYPE_PTHREAD`: User pthread
  - `TCB_FLAG_TTYPE_KERNEL`: Kernel thread

  This thread type is normally available in the flags field of the TCB, however, there are certain error recovery contexts where the TCB may not be fully initialized when up_release_stack is called.

  If `CONFIG_NUTTX_KERNEL` is defined, then this thread type may affect how the stack is freed. For example, kernel thread stacks may have been allocated from protected kernel memory. Stacks for user tasks and threads must have come from memory that is accessible to user

### 4.2.8 `up_unblock_task()`

Prototype: `void up_unblock_task(FAR struct tcb_s *tcb);`

Description. A task is currently in an inactive task list but has been prepped to execute. Move the TCB to the ready-to-run list, restore its context, and start execution.

This function is called only from the NuttX scheduling logic. Interrupts will always be disabled when this function is called.

Input Parameters:

- `tcb`: Refers to the tcb to be unblocked. This tcb is in one of the waiting tasks lists. It must be moved to the ready-to-run list and, if it is the highest priority ready to run tasks, executed.

### 4.2.9 `up_block_task()`

Prototype: `void up_block_task(FAR struct tcb_s *tcb, tstate_t task_state);`

Description. The currently executing task at the head of the ready to run list must be stopped. Save its context and move it to the inactive list specified by task_state. This function is called only from the NuttX scheduling logic. Interrupts will always be disabled when this function is called.

Input Parameters:

- `tcb`: Refers to a task in the ready-to-run list (normally the task at the head of the list). It most be stopped, its context saved and moved into one of the waiting task lists. It it was the task at the head of the ready-to-run list, then a context to the new ready to run task must be performed.
- `task_state`: Specifies which waiting task list should be hold the blocked task TCB.

### 4.2.10 `up_release_pending()`

Prototype: `void up_release_pending(void);`

Description. When tasks become ready-to-run but cannot run because pre-emption is disabled, they are placed into a pending task list. This function releases and makes ready-to-run all of the tasks that have collected in the pending task list. This can cause a context switch if a new task is placed at the head of the ready to run list.

This function is called only from the NuttX scheduling logic when pre-emption is re-enabled. Interrupts will always be disabled when this function is called.

### 4.2.11 `up_reprioritize_rtr()`

Prototype: `void up_reprioritize_rtr(FAR struct tcb_s *tcb, uint8_t priority);`

Description. Called when the priority of a running or ready-to-run task changes and the reprioritization will cause a context switch. Two cases:

1. The priority of the currently running task drops and the next task in the ready to run list has priority.
2. An idle, ready to run task's priority has been raised above the the priority of the current, running task and it now has the priority.

This function is called only from the NuttX scheduling logic. Interrupts will always be disabled when this function is called.

Input Parameters:

- `tcb`: The TCB of the task that has been reprioritized
- `priority`: The new task priority

### 4.2.12 `_exit()`

Prototype: `void _exit(int status) noreturn_function;`

Description. This function causes the currently executing task to cease to exist. This is a special case of task_delete().

Unlike other UP APIs, this function may be called directly from user programs in various states. The implementation of this function should disable interrupts before performing scheduling operations.

### 4.2.13 `up_assert()`

Prototype:
`void up_assert(FAR const uint8_t *filename, int linenum);`

Description. Assertions may be handled in an architecture-specific way.

### 4.2.14 `up_schedule_sigaction()`

Prototype: `void up_schedule_sigaction(FAR struct tcb_s *tcb, sig_deliver_t sigdeliver);`

Description. This function is called by the OS when one or more signal handling actions have been queued for execution. The architecture specific code must configure things so that the 'sigdeliver' callback is executed on the thread specified by 'tcb' as soon as possible.

This function may be called from interrupt handling logic.

This operation should not cause the task to be unblocked nor should it cause any immediate execution of sigdeliver. Typically, a few cases need to be considered:

1. This function may be called from an interrupt handler During interrupt processing, all xcptcontext structures should be valid for all tasks. That structure should be modified to invoke sigdeliver() either on return from (this) interrupt or on some subsequent context switch to the recipient task.
2. If not in an interrupt handler and the tcb is NOT the currently executing task, then again just modify the saved xcptcontext structure for the recipient task so it will invoke sigdeliver when that task is later resumed.
3. If not in an interrupt handler and the tcb IS the currently executing task -- just call the signal handler now.

This API is NOT required if `CONFIG_DISABLE_SIGNALS` is defined.

### 4.2.15 `up_allocate_heap()`

Prototype: `void up_allocate_heap(FAR void **heap_start, size_t *heap_size);`

Description. This function will be called to dynamically set aside the heap region.

For the kernel build (`CONFIG_NUTTX_KERNEL`=y) with both kernel- and user-space heaps (`CONFIG_MM_KERNEL_HEAP`=y), this function provides the size of the unprotected, user-space heap. If a protected kernel-space heap is provided, the kernel heap must be allocated (and protected) by an analogous `up_allocate_kheap()`.

### 4.2.16 `up_interrupt_context()`

Prototype: `bool up_interrupt_context(void)`

Description. Return true if we are currently executing in the interrupt handler context.

### 4.2.17 `up_disable_irq()`

Prototype:

    #ifndef CONFIG_ARCH_NOINTC
      void up_disable_irq(int irq);
    #endif

Description. Disable the IRQ specified by 'irq' On many architectures, there are three levels of interrupt enabling: (1) at the global level, (2) at the level of the interrupt controller, and (3) at the device level. In order to receive interrupts, they must be enabled at all three levels.

This function implements enabling of the device specified by 'irq' at the interrupt controller level if supported by the architecture (irqsave() supports the global level, the device level is hardware specific).

If the architecture does not support `up_disable_irq`, `CONFIG_ARCH_NOINTC` should be defined in the NuttX configuration file. Since this API cannot be supported on all architectures, it should be avoided in common implementations where possible.

### 4.2.18 `up_enable_irq()`

Prototype:

    #ifndef CONFIG_ARCH_NOINTC
      void up_enable_irq(int irq);
    #endif

Description. This function implements disabling of the device specified by 'irq' at the interrupt controller level if supported by the architecture (irqrestore() supports the global level, the device level is hardware specific).

If the architecture does not support `up_disable_irq`, `CONFIG_ARCH_NOINTC` should be defined in the NuttX configuration file. Since this API cannot be supported on all architectures, it should be avoided in common implementations where possible.

### 4.2.19 `up_prioritize_irq()`

Prototype:

    #ifdef CONFIG_ARCH_IRQPRIO
      void up_enable_irq(int irq);
    #endif

Description. Set the priority of an IRQ.

If the architecture supports `up_enable_irq`, `CONFIG_ARCH_IRQPRIO` should be defined in the NuttX configuration file. Since this API cannot be supported on all architectures, it should be avoided in common implementations where possible.

### 4.2.20 `up_putc()`

Prototype: `int up_putc(int ch);`

Description. This is a debug interface exported by the architecture-specific logic. Output one character on the console

### 4.2.21 System Time and Clock

#### 4.2.21.1 Basic System Timer

System Timer In most implementations, system time is provided by a timer interrupt. That timer interrupt runs at rate determined by `CONFIG_MSEC_PER_TICKS` (default 10 or 100Hz). The timer generates an interrupt each `CONFIG_MSEC_PER_TICKS` milliseconds and increments a counter called `g_system_timer`. `g_system_timer` then provides a time-base for calculating up-time and elapsed time intervals in units of `CONFIG_MSEC_PER_TICKS`. The range of `g_system_timer` is, by default, 32-bits. However, if the MCU supports type `long long` and `CONFIG_SYSTEM_TIME16` is selected, a 64-bit system timer will be supported instead.

System Timer Accuracy On many system, the exact timer interval specified by `CONFIG_MSEC_PER_TICKS` cannot be achieved due to limitations in frequencies or in dividers. As a result, the time interval specified by `CONFIG_MSEC_PER_TICKS` may only be approximate and there may be small errors in the apparent up-time time. These small errors, however, will accumulate over time and after a long period of time may have an unacceptably large error in the apparent up-time of the MCU.

If the timer tick period generated by the hardware is not exactly `CONFIG_MSEC_PER_TICKS` and if there you require accurate up-time for the MCU, then there are measures that you can take:

- Perhaps you can adjust `CONFIG_MSEC_PER_TICKS` to a different value so that an exactly `CONFIG_MSEC_PER_TICKS` can be accomplished.
- Or you can use a technique known as Delta-Sigma Modulation. (Suggested by Uros Platise). Consider the example below.

Delta-Sigma Modulation Example. Consider this case: The system timer is a count-up timer driven at 32.768KHz. There are dividers that can be used, but a divider of one yields the highest accuracy. This counter counts up until the count equals a match value, then a timer interrupt is generated. The desire frequency is 100Hz (`CONFIG_MSEC_PER_TICKS` is 10).

This exact frequency of 100Hz cannot be obtained in this case. In order to obtain that exact frequency a match value of 327.68 would have to be provided. The closest integer value is 328 but the ideal match value is between 327 and 328. The closest value, 328, would yield an actual timer frequency of 99.9Hz! That will may cause significant timing errors in certain usages.

Use of Delta-Sigma Modulation can eliminate this error in the long run. Consider this example implementation:

1. Initially an accumulator is zero an the match value is programmed to 328:

       accumulator = 0;
       match = 328;

2. On each timer interrupt, accumulator is updated with difference that, in this reflects, 100* the error in interval that just passed. So on the first timer interrupt, the accumulator would be updated like:

       if (match == 328)
         {
           accumulator += 32; // 100*(328 - 327.68)
         }
       else
         {
           accumulator -= 68; // (100*(327 - 327.68)
         }

3. And on that same timer interrupt a new match value would be programmed:

       if (accumulator < 0)
         {
           match = 328;
         }
       else
         {
           match = 327;
         }

In this way, the timer interval is controlled from interrupt-to-interrupt to produce an average frequency of exactly 100Hz.

#### 4.2.21.2 Hardware

To enable hardware module use the following configuration options:

`CONFIG_RTC`
  Enables general support for a hardware RTC. Specific architectures may require other specific settings.
`CONFIG_RTC_DATETIME`
  There are two general types of RTC: (1) A simple battery backed counter that keeps the time when power is down, and (2) A full date / time RTC the provides the date and time information, often in BCD format. If `CONFIG_RTC_DATETIME` is selected, it specifies this second kind of RTC. In this case, the RTC is used to "seed"" the normal NuttX timer and the NuttX system timer provides for higher resoution time.
`CONFIG_RTC_HIRES`
  If `CONFIG_RTC_DATETIME` not selected, then the simple, battery backed counter is used. There are two different implementations of such simple counters based on the time resolution of the counter: The typical RTC keeps time to resolution of 1 second, usually supporting a 32-bit `time_t` value. In this case, the RTC is used to "seed" the normal NuttX timer and the NuttX timer provides for higher resoution time. If `CONFIG_RTC_HIRES` is enabled in the NuttX configuration, then the RTC provides higher resolution time and completely replaces the system timer for purpose of date and time.
`CONFIG_RTC_FREQUENCY`
  If `CONFIG_RTC_HIRES` is defined, then the frequency of the high resolution RTC must be provided. If `CONFIG_RTC_HIRES` is not defined, `CONFIG_RTC_FREQUENCY` is assumed to be one.
`CONFIG_RTC_ALARM`
  Enable if the RTC hardware supports setting of an alarm. A callback function will be executed when the alarm goes off

which requires the following base functions to read and set time:

- `up_rtcinitialize()`. Initialize the hardware RTC per the selected configuration. This function is called once during the OS initialization sequence
- `up_rtc_time()`. Get the current time in seconds. This is similar to the standard `time()` function. This interface is only required if the low-resolution RTC/counter hardware implementation selected. It is only used by the RTOS during initializeation to set up the system time when `CONFIG_RTC` is set but neither `CONFIG_RTC_HIRES` nor `CONFIG_RTC_DATETIME` are set.
- `up_rtc_gettime()`. Get the current time from the high resolution RTC clock/counter. This interface is only supported by the hight-resolution RTC/counter hardware implementation. It is used to replace the system timer (`g_system_tick`).
- `up_rtc_settime()`. Set the RTC to the provided time. All RTC implementations must be able to set their time based on a standard timespec.
- `up_rtc_setalarm()`. Set up an alarm.

#### 4.2.21.3 System Tick and Time

The system tick is represented by::

- `g_system_timer`

Running at rate of system base timer, used for time-slicing, and so forth.

If hardware RTC is present (`CONFIG_RTC`) and and high-resolution timing is enabled (`CONFIG_RTC_HIRES`), then after successful initiliazation variables are overriden by calls to `up_rtc_gettime()` which is running continously even in power-down modes.

In the case of `CONFIG_RTC_HIRES` is set the `g_system_timer` keeps counting at rate of a system timer, which however, is disabled in power-down mode. By comparing this time and RTC (actual time) one may determine the actual system active time. To retrieve that variable use:

### 4.2.22 Address Environments

CPUs that support memory management units (MMUs) may provide address environments within which tasks and their child threads execute. The configuration indicates the CPUs ability to support address environments by setting the configuration varabile `CONFIG_ADDRENV=y`. These address environments are created only when tasks are created via `exec()` or `exec_module()` (see `include/nuttx/binfmt/binfmt.h`).

When `CONFIG_ADDRENV=y` is set in the board configuration, the CPU-specific logic must provide a set of interfaces as defined in the header file `include/nuttx/arch.h`. These interfaces are listed below and described in detail in the following paragraphs.

The CPU-specific logic must provide two categories in interfaces:

1. Binary Loader Support. These are low-level interfaces used in `binfmt/` to instantiate tasks with address environments. These interfaces all operate on type `task_addrenv_t` which is an abstract representation of a asks's address environment and must be defined in arch/arch.h if `CONFIG_ADDRENV` is defined. These low-level interfaces include:

   - 4.2.22.1 `up_addrenv_create()`: Create an address environment.
   - 4.2.22.2 `up_addrenv_vaddr()`: Returns the virtual base address of the address environment.
   - 4.2.22.3 `up_addrenv_select()`: Instantiate an address environment.
   - 4.2.22.4 `up_addrenv_restore()`: Restore an address environment.
   - 4.2.22.5 `up_addrenv_destroy()`: Destroy an address environment.
   - 4.2.22.6 `up_addrenv_assign()`: Assign an address environment to a TCB.

2. Tasking Support. Other interfaces must be provided to support higher-level interfaces used by the NuttX tasking logic. These interfaces are* used by the functions in `sched/` and all operate on the TCB which as been assigned an address environment by `up_addrenv_assign()`.

   - 4.2.22.7 `up_addrenv_share()`: Clone the address environment assigned to one TCB to another. This operation is done when a pthread is created that share's the same address environment.
   - 4.2.22.8 `up_addrenv_release()`: Release the TCB's reference to an address environment when a task/thread exits.

#### 4.2.22.1 `up_addrenv_create()`

Prototype:

`int up_addrenv_create(size_t envsize, FAR task_addrenv_t *addrenv);`

Description:

This function is called from the binary loader logic when a new task is created in order to instantiate an address environment for the task. `up_addrenv_create()` is essentially the allocator of the physical memory for the new task.

Input Parameters:

- `envsize`: The size (in bytes) of the address environment needed by the task.
- `addrenv`: The location to return the representation of the task address environment.

Returned Value:

Zero (`OK`) on success; a negated `errno` value on failure.

#### 4.2.22.2 `up_addrenv_vaddr()`

Prototype:

`int up_addrenv_vaddr(FAR task_addrenv_t addrenv, FAR void **vaddr);`

Description:

Return the virtual address associated with the newly create address environment. This function is used by the binary loaders in order get an address that can be used to initialize the new task.

Input Parameters:

- `addrenv`: The representation of the task address environment previously returned by up_addrenv_create.
- `vaddr`: The location to return the virtual address.

Returned Value:

Zero (`OK`) on success; a negated `errno` value on failure.

#### 4.2.22.3 `up_addrenv_select()`

Prototype:

`int up_addrenv_select(task_addrenv_t addrenv, hw_addrenv_t *oldenv);`

Description:

After an address environment has been established for a task (via `up_addrenv_create())`, this function may be called to to instantiate that address environment in the virtual address space. This might be necessary, for example, to load the code for the task from a file or to access address environment private data.

Input Parameters:

- `addrenv`: The representation of the task address environment previously returned by up_addrenv_create.
- `oldenv`: The address environment that was in place before `up_addrenv_select()` was called. This may be used with `up_addrenv_restore()` to restore the original address environment that was in place before `up_addrenv_select()` was called. Note that this may be a task agnostic, hardware representation that is different from `task_addrenv_t`.

Returned Value:

Zero (`OK`) on success; a negated `errno` value on failure.

#### 4.2.22.4 `up_addrenv_restore()`

Prototype:

`int up_addrenv_restore(hw_addrenv_t oldenv);`

Description:

After an address environment has been temporarilty instantiated by `up_addrenv_select`, this function may be called to to restore the original address environment.

Input Parameters:

- `oldenv`: The hardware representation of the address environment previously returned by `up_addrenv_select()`.

Returned Value:

Zero (`OK`) on success; a negated `errno` value on failure.

#### 4.2.22.5 `up_addrenv_destroy()`

Prototype:

`int up_addrenv_destroy(task_addrenv_t addrenv);`

Description:

Called from the binary loader loader during error handling to destroy the address environment previously created by `up_addrenv_create()`.

Input Parameters:

- `addrenv`: The representation of the task address environment previously returned by up_addrenv_create.

Returned Value:

Zero (`OK`) on success; a negated `errno` value on failure.

#### 4.2.22.6 `up_addrenv_assign()`

Prototype:

`int up_addrenv_assign(task_addrenv_t addrenv, FAR struct tcb_s *tcb);`

Description:

Assign an address environment to a TCB.

Input Parameters:

- `addrenv`: The representation of the task address environment previously returned by up_addrenv_create.
- `tcb`: The TCB of the task to receive the address environment.

Returned Value:

Zero (`OK`) on success; a negated `errno` value on failure.

#### 4.2.22.7 `up_addrenv_share()`

Prototype:

`int up_addrenv_share(FAR const struct tcb_s *ptcb, FAR struct tcb_s *ctcb);`

Description:

This function is called from the core scheduler logic when a thread is created that needs to share the address ennvironment of its parent task. In this case, the parent's address environment needs to be "cloned" for the child thread.

Input Parameters:

- `ptcb`: The TCB of the parent task that has the address environment.
- `ctcb`: The TCB of the child thread needing the address environment.

Returned Value:

Zero (`OK`) on success; a negated `errno` value on failure.

#### 4.2.22.8 `up_addrenv_release()`

Prototype:

`int up_addrenv_release(FAR struct tcb_s *tcb);`

Description:

This function is called when a task or thread exits in order to release its reference to an address environment. When there are no furtherreferences to an address environment, that address environment should be destroyed.

Input Parameters:

- `tcb`: The TCB of the task or thread whose the address environment will be released.

Returned Value:

Zero (`OK`) on success; a negated `errno` value on failure.

## 4.3 APIs Exported by NuttX to Architecture-Specific Logic

These are standard interfaces that are exported by the OS for use by the architecture specific logic.

### 4.3.1 `os_start()`

To be provided

### 4.3.2 OS List Management APIs

To be provided

### 4.3.3 `sched_process_timer()`

Prototype: `void sched_process_timer(void);`

Description. This function handles system timer events. The timer interrupt logic itself is implemented in the architecture specific code, but must call the following OS function periodically -- the calling interval must be `MSEC_PER_TICK`.

### 4.3.4 `irq_dispatch()`

Prototype: `void irq_dispatch(int irq, FAR void *context);`

Description. This function must be called from the architecture- specific logic in order to display an interrupt to the appropriate, registered handling logic.

## 4.4 On-Demand Paging

The NuttX On-Demand Paging feature permits embedded MCUs with some limited RAM space to execute large programs from some non-random access media. If the platform meets certiain requirements, then NuttX can provide on-demand paging: It can copy .text from the large program in non-volatile media into RAM as needed to execute a huge program from the small RAM. Design and porting issues for this feature are discussed in a sepate document. Please see the NuttX Demand Paging design document for further information.

## 4.5 LED Support

A board architecture may or may not have LEDs. If the board does have LEDs, then most architectures provide similar LED support that is enabled when `CONFIG_ARCH_LEDS` is selected in the NuttX configuration file. This LED support is part of architecture-specific logic and is not managed by the core NuttX logic. However, the support provided by each architecture is sufficiently similar that it can be documented here.

### 4.5.1 Header Files

LED-related definitions are provided in two header files:

- LED definitions are provided for each board in the `board.h` that resides in the `<board-name>/include/board.h` file (which is also linked to `include/arch/board/board.h` when the RTOS is configured). Those definitions are discussed below.
- The board-specific logic provides unique instances of the LED interfaces. This is because the implementation of LED support may be very different on different boards. Prototypes for these board-specific implementations are, however, provided in architecture-common header files. That header file is usually at `<arch-name>/src/common/up_internal.h`, but could be at other locations in particular architectures. These prototypes are discussed below.

### 4.5.2 LED Definitions

The implementation of LED support is very specific to a board architecture. Some boards have several LEDS, others have only one or two. Some have none. Others LED matrices and show alphanumeric data, etc. The NuttX logic does not refer to specific LEDS, rather, it refers to an event to be shown on the LEDS in whatever manner is appropriate for the board; the way that this event is presented depends upon the hardware available on the board.

The model used by NuttX is that the board can show 8 events defined as follows in `<board-name>/include/board.h`:

    #define LED_STARTED       ??
    #define LED_HEAPALLOCATE  ??
    #define LED_IRQSENABLED   ??
    #define LED_STACKCREATED  ??
    #define LED_INIRQ         ??
    #define LED_SIGNAL        ??
    #define LED_ASSERTION     ??
    #define LED_PANIC         ??

The specific value assigned to each pre-processor variable can be whatever makes the implementation easiest for the board logic. The meaning associated with each definition is as follows:

- `LED_STARTED` is the value that describes the setting of the LEDs when the LED logic is first initialized. This LED value is set but never cleared.
- `LED_HEAPALLOCATE` indicates that the NuttX heap has been configured. This is an important place in the boot sequence because if the memory is configured wrong, it will probably crash leaving this LED setting. This LED value is set but never cleared.
- `LED_IRQSENABLED` indicates that interrupts have been enabled. Again, during bring-up (or if there are hardware problems), it is very likely that the system may crash just when interrupts are enabled, leaving this setting on the LEDs. This LED value is set but never cleared.
- `LED_STACKCREATED` is set each time a new stack is created. If set, it means that the system attempted to start at least one new thread. This LED value is set but never cleared.
- `LED_INIRQ` is set and cleared on entry and exit from each interrupt. If interrupts are working okay, this LED will have a dull glow.
- `LED_SIGNAL` is set and cleared on entry and exit from a signal handler. Signal handlers are tricky so this is especially useful during bring-up or a new architecture.
- `LED_ASSERTION` is set if an assertion occurs.
- `LED_PANIC` will blink at around 1Hz if the system panics and hangs.

### 4.5.3 Common LED interfaces

The `<arch-name>/src/common/up_internal.h` probably has definitions like:

    /* Defined in board/up_leds.c */

    #ifdef CONFIG_ARCH_LEDS
    void board_led_initialize(void);
    void board_led_on(int led);
    void board_led_off(int led);
    #else
    # define board_led_initialize()
    # define board_led_on(led)
    # define board_led_off(led)
    #endif

Where:

- `void board_led_initialize(void)` is called early in power-up initialization to initialize the LED hardware.
- `board_led_on(int led)` is called to instantiate the LED presentation of the event. The `led` argument is one of the definitions provided in `<board-name>/include/board.h`.
- `board_led_off(int led`is called to terminate the LED presentation of the event. The `led` argument is one of the definitions provided in `<board-name>/include/board.h`. Note that only `LED_INIRQ`, `LED_SIGNAL`, `LED_ASSERTION`, and `LED_PANIC` indications are terminated.

# 5.0 NuttX File System

Overview. NuttX includes an optional, scalable file system. This file-system may be omitted altogether; NuttX does not depend on the presence of any file system.

Pseudo Root File System. Or, a simple in-memory, pseudo file system can be enabled. This simple file system can be enabled setting the CONFIG_NFILE_DESCRIPTORS option to a non-zero value (see Appendix A). This is an in-memory file system because it does not require any storage medium or block driver support. Rather, file system contents are generated on-the-fly as referenced via standard file system operations (open, close, read, write, etc.). In this sense, the file system is pseudo file system (in the same sense that the Linux `/proc` file system is also referred to as a pseudo file system).

Any user supplied data or logic can be accessed via the pseudo-file system. Built in support is provided for character and block drivers in the `/dev` pseudo file system directory.

Mounted File Systems The simple in-memory file system can be extended my mounting block devices that provide access to true file systems backed up via some mass storage device. NuttX supports the standard `mount()` command that allows a block driver to be bound to a mountpoint within the pseudo file system and to a file system. At present, NuttX supports the standard VFAT and ROMFS file systems, a special, wear-leveling NuttX FLASH File System (NXFFS), as well as a Network File System client (NFS version 3, UDP).

Comparison to Linux From a programming perspective, the NuttX file system appears very similar to a Linux file system. However, there is a fundamental difference: The NuttX root file system is a pseudo file system and true file systems may be mounted in the pseudo file system. In the typical Linux installation by comparison, the Linux root file system is a true file system and pseudo file systems may be mounted in the true, root file system. The approach selected by NuttX is intended to support greater scalability from the very tiny platform to the moderate platform.

# 6.0 NuttX Device Drivers

NuttX supports a variety of device drivers including:

- Character Device Drivers,
- Block Device Drivers, and
- Other Specialized Drivers.

These different device driver types are discussed in the following paragraphs. Note: device driver support requires that the in-memory, pseudo file system is enabled by setting the CONFIG_NFILE_DESCRIPTORS in the NuttX configuration file to a non-zero value.

## 6.1 Character Device Drivers

Character device drivers have these properties:

- `include/nuttx/fs/fs.h`. All structures and APIs needed to work with character drivers are provided in this header file.

- `struct file_operations`. Each character device driver must implement an instance of `struct file_operations`. That structure defines a call table with the following methods:

  `int open(FAR struct file *filep);`
  `int close(FAR struct file *filep);`
  `ssize_t read(FAR struct file *filep, FAR char *buffer, size_t buflen);`
  `ssize_t write(FAR struct file *filep, FAR const char *buffer, size_t buflen);`
  `off_t seek(FAR struct file *filep, off_t offset, int whence);`
  `int ioctl(FAR struct file *filep, int cmd, unsigned long arg);`
  `int poll(FAR struct file *filep, struct pollfd *fds, bool setup);`

- `int register_driver(const char *path, const struct file_operations *fops, mode_t mode, void *priv);`. Each character driver registers itself by calling `register_driver()`, passing it the `path` where it will appear in the pseudo-file-system and it's initialized instance of `struct file_operations`.

- User Access. After it has been registered, the character driver can be accessed by user code using the standard driver operations including `open()`, `close()`, `read()`, `write()`, etc.

- Examples: `drivers/dev_null.c`, `drivers/fifo.c`, `drivers/serial.c`, etc.

## 6.2 Block Device Drivers

Block device drivers have these properties:

- `include/nuttx/fs/fs.h`. All structures and APIs needed to work with block drivers are provided in this header file.

- `struct block_operations`. Each block device driver must implement an instance of `struct block_operations`. That structure defines a call table with the following methods:

  `int open(FAR struct inode *inode);`
  `int close(FAR struct inode *inode);`
  `ssize_t read(FAR struct inode *inode, FAR unsigned char *buffer, size_t start_sector, unsigned int nsectors);`
  `ssize_t write(FAR struct inode *inode, FAR const unsigned char *buffer, size_t start_sector, unsigned int nsectors);`
  `int geometry(FAR struct inode *inode, FAR struct geometry *geometry);`
  `int ioctl(FAR struct inode *inode, int cmd, unsigned long arg);`

- `int register_blockdriver(const char *path, const struct block_operations *bops, mode_t mode, void *priv);`. Each block driver registers itself by calling `register_blockdriver()`, passing it the `path` where it will appear in the pseudo-file-system and it's initialized instance of `struct block_operations`.

- User Access. Users do not normally access block drivers directly, rather, they access block drivers indirectly through the `mount()` API. The `mount()` API binds a block driver instance with a file system and with a mountpoint. Then the user may use the block driver to access the file system on the underlying media. Example: See the `cmd_mount()` implementation in `apps/nshlib/nsh_fscmds.c`.

- Accessing a Character Driver as a Block Device. See the loop device at `drivers/loop.c`. Example: See the `cmd_losetup()` implementation in `apps/nshlib/nsh_fscmds.c`.

- Accessing a Block Driver as Character Device. See the Block-to-Character (BCH) conversion logic in `drivers/bch/`. Example: See the `cmd_dd()` implementation in `apps/nshlib/nsh_ddcmd.c`.

- Examples. `drivers/loop.c`, `drivers/mmcsd/mmcsd_spi.c`, `drivers/ramdisk.c`, etc.

## 6.3 Specialized Device Drivers

### 6.3.1 Ethernet Device Drivers

- `include/nuttx/net/uip/uip-arch.h`. All structures and APIs needed to work with Ethernet drivers are provided in this header file. The structure `struct uip_driver_s` defines the interface and is passed to uIP via `netdev_register()`.

- `int netdev_register(FAR struct uip_driver_s *dev);`. Each Ethernet driver registers itself by calling `netdev_register()`.

- Examples: `drivers/net/dm90x0.c`, `arch/drivers/arm/src/c5471/c5471_ethernet.c`, `arch/z80/src/ez80/ez80_emac.c`, etc.

### 6.3.2 SPI Device Drivers

- `include/nuttx/spi/spi.h`. All structures and APIs needed to work with SPI drivers are provided in this header file.

- `struct spi_ops_s`. Each SPI device driver must implement an instance of `struct spi_ops_s`. That structure defines a call table with the following methods:

  `void lock(FAR struct spi_dev_s *dev);`

  `void select(FAR struct spi_dev_s *dev, enum spi_dev_e devid, bool selected);`
  `uint32_t setfrequency(FAR struct spi_dev_s *dev, uint32_t frequency);`
  `void setmode(FAR struct spi_dev_s *dev, enum spi_mode_e mode);`
  `void setbits(FAR struct spi_dev_s *dev, int nbits);`
  `uint8_t status(FAR struct spi_dev_s *dev, enum spi_dev_e devid);`
  `uint16_t send(FAR struct spi_dev_s *dev, uint16_t wd);`
  `void exchange(FAR struct spi_dev_s *dev, FAR const void *txbuffer, FAR void *rxbuffer, size_t nwords);`

  `int registercallback(FAR struct spi_dev_s *dev, mediachange_t callback, void *arg);`

- Binding SPI Drivers. SPI drivers are not normally directly accessed by user code, but are usually bound to another, higher level device driver. See for example, `int mmcsd_spislotinitialize(int minor, int slotno, FAR struct spi_dev_s *spi)` in `drivers/mmcsd/mmcsd_spi.c`. In general, the binding sequence is:

  1. Get an instance of `struct spi_dev_s` from the hardware-specific SPI device driver, and
  2. Provide that instance to the initialization method of the higher level device driver.

- Examples: `drivers/loop.c`, `drivers/mmcsd/mmcsd_spi.c`, `drivers/ramdisk.c`, etc.

### 6.3.3 I2C Device Drivers

- `include/nuttx/i2c/i2c.h`. All structures and APIs needed to work with I2C drivers are provided in this header file.

- `struct i2c_ops_s`. Each I2C device driver must implement an instance of `struct i2c_ops_s`. That structure defines a call table with the following methods:

  `uint32_t setfrequency(FAR struct i2c_dev_s *dev, uint32_t frequency);`
  `int setaddress(FAR struct i2c_dev_s *dev, int addr, int nbits);`
  `int write(FAR struct i2c_dev_s *dev, const uint8_t *buffer, int buflen);`
  `int read(FAR struct i2c_dev_s *dev, uint8_t *buffer, int buflen);`

- Binding I2C Drivers. I2C drivers are not normally directly accessed by user code, but are usually bound to another, higher level device driver. In general, the binding sequence is:

  1. Get an instance of `struct i2c_dev_s` from the hardware-specific I2C device driver, and
  2. Provide that instance to the initialization method of the higher level device driver.

- Examples: `arch/z80/src/ez80/ez80_i2c.c`, `arch/z80/src/z8/z8_i2c.c`, etc.

### 6.3.4 Serial Device Drivers

- `include/nuttx/serial/serial.h`. All structures and APIs needed to work with serial drivers are provided in this header file.

- `struct uart_ops_s`. Each serial device driver must implement an instance of `struct uart_ops_s`. That structure defines a call table with the following methods:

  `int setup(FAR struct uart_dev_s *dev);`
  `void shutdown(FAR struct uart_dev_s *dev);`
  `int attach(FAR struct uart_dev_s *dev);`
  `void detach(FAR struct uart_dev_s *dev);`
  `int ioctl(FAR struct file *filep, int cmd, unsigned long arg);`
  `int receive(FAR struct uart_dev_s *dev, unsigned int *status);`
  `void rxint(FAR struct uart_dev_s *dev, bool enable);`
  `bool rxavailable(FAR struct uart_dev_s *dev);`
  `void send(FAR struct uart_dev_s *dev, int ch);`
  `void txint(FAR struct uart_dev_s *dev, bool enable);`
  `bool txready(FAR struct uart_dev_s *dev);`
  `bool txempty(FAR struct uart_dev_s *dev);`

- `int uart_register(FAR const char *path, FAR uart_dev_t *dev);`. A serial driver may register itself by calling `uart_register()`, passing it the `path` where it will appear in the pseudo-file-system and it's initialized instance of `struct uart_ops_s`. By convention, serial device drivers are registered at paths like `/dev/ttyS0`, `/dev/ttyS1`, etc. See the `uart_register()` implementation in `drivers/serial.c`.

- User Access. Serial drivers are, ultimately, normal character drivers and are accessed as other character drivers.

- Examples: `arch/arm/src/chip/lm_serial.c`, `arch/arm/src/lpc214x/lpc214x_serial.c`, `arch/z16/src/z16f/z16f_serial.c`, etc.

### 6.3.5 Frame Buffer Drivers

- `include/nuttx/video/fb.h`. All structures and APIs needed to work with frame buffer drivers are provided in this header file.

- `struct fb_vtable_s`. Each frame buffer device driver must implement an instance of `struct fb_vtable_s`. That structure defines a call table with the following methods:

  Get information about the video controller configuration and the configuration of each color plane.

  `int (*getvideoinfo)(FAR struct fb_vtable_s *vtable, FAR struct fb_videoinfo_s *vinfo);`
  `int (*getplaneinfo)(FAR struct fb_vtable_s *vtable, int planeno, FAR struct fb_planeinfo_s *pinfo);`

  The following are provided only if the video hardware supports RGB color mapping:

  `int (*getcmap)(FAR struct fb_vtable_s *vtable, FAR struct fb_cmap_s *cmap);`
  `int (*putcmap)(FAR struct fb_vtable_s *vtable, FAR const struct fb_cmap_s *cmap);`

  The following are provided only if the video hardware supports a hardware cursor:

  `int (*getcursor)(FAR struct fb_vtable_s *vtable, FAR struct fb_cursorattrib_s *attrib);`
  `int (*setcursor)(FAR struct fb_vtable_s *vtable, FAR struct fb_setcursor_s *settings);`

- Binding Frame Buffer Drivers. Frame buffer drivers are not normally directly accessed by user code, but are usually bound to another, higher level device driver. In general, the binding sequence is:

  1. Get an instance of `struct fb_vtable_s` from the hardware-specific frame buffer device driver, and
  2. Provide that instance to the initialization method of the higher level device driver.

- Examples: `arch/sim/src/up_framebuffer.c`. See also the usage of the frame buffer driver in the `graphics/` directory.

### 6.3.6 LCD Drivers

- `include/nuttx/lcd/lcd.h`. Structures and APIs needed to work with LCD drivers are provided in this header file. This header file also depends on some of the same definitions used for the frame buffer driver as privided in `include/nuttx/video/fb.h`.

- `struct lcd_dev_s`. Each LCD device driver must implement an instance of `struct lcd_dev_s`. That structure defines a call table with the following methods:

  Get information about the LCD video controller configuration and the configuration of each LCD color plane.

  `int (*getvideoinfo)(FAR struct lcd_dev_s *dev, FAR struct fb_videoinfo_s *vinfo);`
  `int (*getplaneinfo)(FAR struct lcd_dev_s *dev, unsigned int planeno, FAR struct lcd_planeinfo_s *pinfo);`

  The following are provided only if the video hardware supports RGB color mapping:

  `int (*getcmap)(FAR struct lcd_dev_s *dev, FAR struct fb_cmap_s *cmap);`
  `int (*putcmap)(FAR struct lcd_dev_s *dev, FAR const struct fb_cmap_s *cmap);`

  The following are provided only if the video hardware supports a hardware cursor:

  `int (*getcursor)(FAR struct lcd_dev_s *dev, FAR struct fb_cursorattrib_s *attrib);`
  `int (*setcursor)(FAR struct lcd_dev_s *dev, FAR struct fb_setcursor_s *settings)`

  Get the LCD panel power status (0: full off - `CONFIG_LCD_MAXPOWER`: full on). On backlit LCDs, this setting may correspond to the backlight setting.

  `int (*getpower)(struct lcd_dev_s *dev);`

  Enable/disable LCD panel power (0: full off - `CONFIG_LCD_MAXPOWER`: full on). On backlit LCDs, this setting may correspond to the backlight setting.

  `int (*setpower)(struct lcd_dev_s *dev, int power);`

  Get the current contrast setting (0-CONFIG_LCD_MAXCONTRAST) */

  `int (*getcontrast)(struct lcd_dev_s *dev);`

  Set LCD panel contrast (0-CONFIG_LCD_MAXCONTRAST)

  `int (*setcontrast)(struct lcd_dev_s *dev, unsigned int contrast);`

- Binding LCD Drivers. LCD drivers are not normally directly accessed by user code, but are usually bound to another, higher level device driver. In general, the binding sequence is:

  1. Get an instance of `struct lcd_dev_s` from the hardware-specific LCD device driver, and
  2. Provide that instance to the initialization method of the higher level device driver.

- Examples: `drivers/lcd/nokia6100.c`, `drivers/lcd/p14201.c`, `configs/sam3u-ek/src/up_lcd.c.` See also the usage of the LCD driver in the `graphics/` directory.

### 6.3.7 Memory Technology Device Drivers

- `include/nuttx/mtd/mtd.h`. All structures and APIs needed to work with MTD drivers are provided in this header file.

- `struct mtd_dev_s`. Each MTD device driver must implement an instance of `struct mtd_dev_s`. That structure defines a call table with the following methods:

  Erase the specified erase blocks (units are erase blocks):

  `int (*erase)(FAR struct mtd_dev_s *dev, off_t startblock, size_t nblocks);`

  Read/write from the specified read/write blocks:

  `ssize_t (*bread)(FAR struct mtd_dev_s *dev, off_t startblock, size_t nblocks, FAR uint8_t *buffer);`
  `ssize_t (*bwrite)(FAR struct mtd_dev_s *dev, off_t startblock, size_t nblocks, FAR const uint8_t *buffer);`

  Some devices may support byte oriented reads (optional). Most MTD devices are inherently block oriented so byte-oriented accesses are not supported. It is recommended that low-level drivers not support read() if it requires buffering.

  `ssize_t (*read)(FAR struct mtd_dev_s *dev, off_t offset, size_t nbytes, FAR uint8_t *buffer);`

  Some devices may also support byte oriented writes (optional). Most MTD devices are inherently block oriented so byte-oriented accesses are not supported. It is recommended that low-level drivers not support read() if it requires buffering. This interface is only available if `CONFIG_MTD_BYTE_WRITE` is defined.

  `ssize_t (*write)(FAR struct mtd_dev_s *dev, off_t offset, size_t nbytes, FAR const uint8_t *buffer);`

  Support other, less frequently used commands:

  - `MTDIOC_GEOMETRY`: Get MTD geometry
  - `MTDIOC_XIPBASE:`: Convert block to physical address for eXecute-In-Place
  - `MTDIOC_BULKERASE`: Erase the entire device

  is provided via a sinble `ioctl` method (see `include/nuttx/fs/ioctl.h`):

  `int (*ioctl)(FAR struct mtd_dev_s *dev, int cmd, unsigned long arg);`

- Binding MTD Drivers. MTD drivers are not normally directly accessed by user code, but are usually bound to another, higher level device driver. In general, the binding sequence is:

  1. Get an instance of `struct mtd_dev_s` from the hardware-specific MTD device driver, and
  2. Provide that instance to the initialization method of the higher level device driver.

- Examples: `drivers/mtd/m25px.c` and `drivers/mtd/ftl.c`

### 6.3.8 SDIO Device Drivers

- `include/nuttx/sdio.h`. All structures and APIs needed to work with SDIO drivers are provided in this header file.

- `struct sdio_dev_s`. Each SDIOI device driver must implement an instance of `struct sdio_dev_s`. That structure defines a call table with the following methods:

  Mutual exclusion:

  `#ifdef CONFIG_SDIO_MUXBUS`
  `int (*lock)(FAR struct sdio_dev_s *dev, bool lock);`
  `#endif`

  Initialization/setup:

  `void (*reset)(FAR struct sdio_dev_s *dev);`
  `uint8_t (*status)(FAR struct sdio_dev_s *dev);`
  `void (*widebus)(FAR struct sdio_dev_s *dev, bool enable);`
  `void (*clock)(FAR struct sdio_dev_s *dev, enum sdio_clock_e rate);`
  `int (*attach)(FAR struct sdio_dev_s *dev);`

  Command/Status/Data Transfer:

  `int (*sendcmd)(FAR struct sdio_dev_s *dev, uint32_t cmd, uint32_t arg);`
  `int (*recvsetup)(FAR struct sdio_dev_s *dev, FAR uint8_t *buffer, size_t nbytes);`
  `int (*sendsetup)(FAR struct sdio_dev_s *dev, FAR const uint8_t *buffer, size_t nbytes);`
  `int (*cancel)(FAR struct sdio_dev_s *dev);`
  `int (*waitresponse)(FAR struct sdio_dev_s *dev, uint32_t cmd);`
  `int (*recvR1)(FAR struct sdio_dev_s *dev, uint32_t cmd, uint32_t *R1);`
  `int (*recvR2)(FAR struct sdio_dev_s *dev, uint32_t cmd, uint32_t R2[4]);`
  `int (*recvR3)(FAR struct sdio_dev_s *dev, uint32_t cmd, uint32_t *R3);`
  `int (*recvR4)(FAR struct sdio_dev_s *dev, uint32_t cmd, uint32_t *R4);`
  `int (*recvR5)(FAR struct sdio_dev_s *dev, uint32_t cmd, uint32_t *R5);`
  `int (*recvR6)(FAR struct sdio_dev_s *dev, uint32_t cmd, uint32_t *R6);`
  `int (*recvR7)(FAR struct sdio_dev_s *dev, uint32_t cmd, uint32_t *R7);`

  Event/Callback support:

  `void (*waitenable)(FAR struct sdio_dev_s *dev, sdio_eventset_t eventset);`
  `sdio_eventset_t (*eventwait)(FAR struct sdio_dev_s *dev, uint32_t timeout);`
  `void (*callbackenable)(FAR struct sdio_dev_s *dev, sdio_eventset_t eventset);`
  `int (*registercallback)(FAR struct sdio_dev_s *dev, worker_t callback, void *arg);`

  DMA support:

  `bool (*dmasupported)(FAR struct sdio_dev_s *dev);`
  `int (*dmarecvsetup)(FAR struct sdio_dev_s *dev, FAR uint8_t *buffer, size_t buflen);`
  `int (*dmasendsetup)(FAR struct sdio_dev_s *dev, FAR const uint8_t *buffer, size_t buflen);`

- Binding SDIO Drivers. SDIO drivers are not normally directly accessed by user code, but are usually bound to another, higher level device driver. In general, the binding sequence is:

  1. Get an instance of `struct sdio_dev_s` from the hardware-specific SDIO device driver, and
  2. Provide that instance to the initialization method of the higher level device driver.

- Examples: `arch/arm/src/stm32/stm32_sdio.c` and `drivers/mmcsd/mmcsd_sdio.c`

### 6.3.9 USB Host-Side Drivers

- `include/nuttx/usb/usbhost.h`. All structures and APIs needed to work with USB host-side drivers are provided in this header file.

- `struct usbhost_driver_s` and `struct usbhost_connection_s`. Each USB host controller driver must implement an instance of `struct usbhost_driver_s` and `struct usbhost_connection_s`: `struct usbhost_driver_s` provides the interface between the USB host driver and the USB class driver; `struct usbhost_connection_s` provides the interface between the USB host driver and platform-specific connection management and device enumeration logoc. These structures are defined in `include/nuttx/usb/usbhost.h`.

  Examples: `arch/arm/src/lpc17xx/lpc17_usbhost.c`, `arch/arm/src/stm32/stm32_otgfshost.c`, `arch/arm/src/sama5/sam_ohci.c`, and `arch/arm/src/sama5/sam_ehci.c`.

- `struct usbhost_class_s`. Each USB host class driver must implement an instance of `struct usbhost_class_s`. This structure is also defined in `include/nuttx/usb/usbhost.h`.

  Examples: `drivers/usbhost/usbhost_storage.c`

- USB Host Class Driver Registry. The NuttX USB host infrastructure includes a registry. During its initialization, each USB host class driver must call the interface, `usbhost_registerclass()` in order add its interface to the registery. Later, when a USB device is connected, the USB host controller will look up the USB host class driver that is needed to support the connected device in this registry.

  Examples: `drivers/usbhost/usbhost_registry.c`, `drivers/usbhost/usbhost_registerclass.c`, and `drivers/usbhost/usbhost_findclass.c`,

- Detection and Enumeration of Connected Devices. Each USB host device controller supports two methods that are used to detect and enumeration newly connected devices (and also detect disconnected devices):

  - `int (*wait)(FAR struct usbhost_connection_s *drvr, FAR const bool *connected);`

    Wait for a device to be connected or disconnected.

  - `int (*enumerate)(FAR struct usbhost_connection_s *drvr, int rhpndx);`

    Enumerate the device connected to a root hub port. As part of this enumeration process, the driver will (1) get the device's configuration descriptor, (2) extract the class ID info from the configuration descriptor, (3) call `usbhost_findclass(`) to find the class that supports this device, (4) call the `create()` method on the `struct usbhost_registry_s interface` to get a class instance, and finally (5) call the `connect()` method of the `struct usbhost_class_s` interface. After that, the class is in charge of the sequence of operations.

- Binding USB Host-Side Drivers. USB host-side controller drivers are not normally directly accessed by user code, but are usually bound to another, higher level USB host class driver. The class driver exports the standard NuttX device interface so that the connected USB device can be accessed just as with other, similar, on-board devices. For example, the USB host mass storage class driver (`drivers/usbhost/usbhost_storage.c`) will register a standard, NuttX block driver interface (like `/dev/sda`) that can be used to mount a file system just as with any other other block driver instance. In general, the binding sequence is:

  1. Each USB host class driver includes an initializeation entry point that is called from the application at initialization time. This driver calls `usbhost_registerclass()` during this initialization in order to makes itself available in the event the device that it supports is connected.

     Examples: The function `usbhost_storageinit()` in the file `drivers/usbhost/usbhost_storage.c`

  2. Each application must include a waiter thread thread that (1) calls the USB host controller driver's `wait()` to detect the connection of a device, and then (2) call the USB host controller driver's `enumerate` method to bind the registered USB host class driver to the USB host controller driver.

     Examples: The function `nsh_waiter()` in the file `configs/nucleus2g/src/up_nsh.c` and the function `nsh_waiter()` in the file `configs/olimex-lpc1766stk/src/up_nsh.c`.

  3. As part of its operation during the binding operation, the USB host class driver will register an instances of a standard NuttX driver under the `/dev` directory. To repeat the above example, the USB host mass storage class driver (`drivers/usbhost/usbhost_storage.c`) will register a standard, NuttX block driver interface (like `/dev/sda`) that can be used to mount a file system just as with any other other block driver instance.

     Examples: See the call to `register_blockdriver()` in the function `usbhost_initvolume()` in the file `drivers/usbhost/usbhost_storage.c`.

### 6.3.10 USB Device-Side Drivers

- `include/nuttx/usb/usbdev.h`. All structures and APIs needed to work with USB device-side drivers are provided in this header file.

- `include/nuttx/usb/usbdev_trace.h`. Declarations needed to work with the NuttX USB device driver trace capability. That USB trace capability is detailed in separate document.

- `struct usbdev_s`. Each USB device controller driver must implement an instance of `struct usbdev_s`. This structure is defined in `include/nuttx/usb/usbdev.h`.

  Examples: `arch/arm/src/dm320/dm320_usbdev.c`, `arch/arm/src/lpc17xx/lpc17_usbdev.c`, `arch/arm/src/lpc214x/lpc214x_usbdev.c`, `arch/arm/src/lpc313x/lpc313x_usbdev.c`, and `arch/arm/src/stm32/stm32_usbdev.c`.

- `struct usbdevclass_driver_s`. Each USB device class driver must implement an instance of `struct usbdevclass_driver_s`. This structure is also defined in `include/nuttx/usb/usbdev.h`.

  Examples: `drivers/usbdev/pl2303.c` and `drivers/usbdev/usbmsc.c`

- Binding USB Device-Side Drivers. USB device-side controller drivers are not normally directly accessed by user code, but are usually bound to another, higher level USB device class driver. The class driver is then configured to export the USB device functionality. In general, the binding sequence is:

  1. Each USB device class driver includes an initializeation entry point that is called from the application at initialization time.

     Examples: The function `usbdev_serialinitialize()` in the file `drivers/usbdev/pl2303.c` and the function `` in the file `drivers/usbdev/usbmsc.c`

  2. These initialization functions called the driver API, `usbdev_register()`. This driver function will bind the USB class driver to the USB device controller driver, completing the initialization.

### 6.3.11 Analog (ADC/DAC) Drivers

The NuttX PWM driver is split into two parts:

1. An "upper half", generic driver that provides the comman PWM interface to application level code, and
2. A "lower half", platform-specific driver that implements the low-level timer controls to implement the PWM functionality.

- General header files for the NuttX analog drivers reside in `include/nuttx/analog/`. These header files includes both the application level interface to the analog driver as well as the interface between the "upper half" and "lower half" drivers.
- Common analog logic and share-able analog drivers reside in the `drivers/analog/`.
- Platform-specific drivers reside in `arch/`<architecture>`/src/`<chip> directory for the specific processor <architecture> and for the specific <chip> analog peripheral devices.

#### 6.3.11.1 ADC Drivers

- `include/nuttx/analog/adc.h`. All structures and APIs needed to work with ADC drivers are provided in this header file. This header file includes:
  1. Structures and interface descriptions needed to develop a low-level, architecture-specific, ADC driver.
  2. To register the ADC driver with a common ADC character driver.
  3. Interfaces needed for interfacing user programs with the common ADC character driver.
- `drivers/analog/adc.c`. The implementation of the common ADC character driver.

#### 6.3.11.2 DAC Drivers

- `include/nuttx/analog/dac.h`. All structures and APIs needed to work with DAC drivers are provided in this header file. This header file includes:
  1. Structures and interface descriptions needed to develop a low-level, architecture-specific, DAC driver.
  2. To register the DAC driver with a common DAC character driver.
  3. Interfaces needed for interfacing user programs with the common DAC character driver.
- `drivers/analog/dac.c`. The implementation of the common DAC character driver.

### 6.3.12 PWM Drivers

For the purposes of this driver, a PWM device is any device that generates periodic output pulses of controlled frequency and pulse width. Such a device might be used, for example, to perform pulse-width modulated output or frequency/pulse-count modulated output (such as might be needed to control a stepper motor).

The NuttX PWM driver is split into two parts:

1. An "upper half", generic driver that provides the comman PWM interface to application level code, and
2. A "lower half", platform-specific driver that implements the low-level timer controls to implement the PWM functionality.

Files supporting PWM can be found in the following locations:

- Interface Definition. The header file for the NuttX PWM driver reside at `include/nuttx/pwm.h`. This header file includes both the application level interface to the PWM driver as well as the interface between the "upper half" and "lower half" drivers. The PWM module uses a standard character driver framework. However, since the PWM driver is a devices control interface and not a data transfer interface, the majority of the functionality available to the application is implemented in driver ioctl calls.
- "Upper Half" Driver. The generic, "upper half" PWM driver resides at `drivers/pwm.c`.
- "Lower Half" Drivers. Platform-specific PWM drivers reside in `arch/`<architecture>`/src/`<chip> directory for the specific processor <architecture> and for the specific <chip> PWM peripheral devices.

### 6.3.13 CAN Drivers

NuttX supports only a very low-level CAN driver. This driver supports only the data exchange and does not include any high-level CAN protocol. The NuttX CAN driver is split into two parts:

1. An "upper half", generic driver that provides the comman CAN interface to application level code, and
2. A "lower half", platform-specific driver that implements the low-level timer controls to implement the CAN functionality.

Files supporting CAN can be found in the following locations:

- Interface Definition. The header file for the NuttX CAN driver reside at `include/nuttx/can.h`. This header file includes both the application level interface to the CAN driver as well as the interface between the "upper half" and "lower half" drivers. The CAN module uses a standard character driver framework.
- "Upper Half" Driver. The generic, "upper half" CAN driver resides at `drivers/can.c`.
- "Lower Half" Drivers. Platform-specific CAN drivers reside in `arch/`<architecture>`/src/`<chip> directory for the specific processor <architecture> and for the specific <chip> CAN peripheral devices.

### 6.3.14 Quadrature Encoder Drivers

NuttX supports a low-level, two-part Quadrature Encoder driver.

1. An "upper half", generic driver that provides the comman Quadrature Encoder interface to application level code, and
2. A "lower half", platform-specific driver that implements the low-level timer controls to implement the Quadrature Encoder functionality.

Files supporting the Quadrature Encoder can be found in the following locations:

- Interface Definition. The header file for the NuttX Quadrature Encoder driver reside at `include/nuttx/sensors/qencoder.h`. This header file includes both the application level interface to the Quadrature Encoder driver as well as the interface between the "upper half" and "lower half" drivers. The Quadrature Encoder module uses a standard character driver framework.
- "Upper Half" Driver. The generic, "upper half" Quadrature Encoder driver resides at `drivers/sensors/qencoder.c`.
- "Lower Half" Drivers. Platform-specific Quadrature Encoder drivers reside in `arch/`<architecture>`/src/`<chip> directory for the specific processor <architecture> and for the specific <chip> Quadrature Encoder peripheral devices.

### 6.3.15 Watchdog Timer Drivers

NuttX supports a low-level, two-part watchdog timer driver.

1. An "upper half", generic driver that provides the comman watchdog timer interface to application level code, and
2. A "lower half", platform-specific driver that implements the low-level timer controls to implement the watchdog timer functionality.

Files supporting the watchdog timer can be found in the following locations:

- Interface Definition. The header file for the NuttX watchdog timer driver reside at `include/nuttx/watchdog.h`. This header file includes both the application level interface to the watchdog timer driver as well as the interface between the "upper half" and "lower half" drivers. The watchdog timer driver uses a standard character driver framework.
- "Upper Half" Driver. The generic, "upper half" watchdog timer driver resides at `drivers/watchdog.c`.
- "Lower Half" Drivers. Platform-specific watchdog timer drivers reside in `arch/`<architecture>`/src/`<chip> directory for the specific processor <architecture> and for the specific <chip> watchdog timer peripheral devices.

### 6.3.16 Keyboard/Keypad Drivers

Keypads vs. Keyboards Keyboards and keypads are really the same devices for NuttX. A keypad is thought of as simply a keyboard with fewer keys.

Special Commands. In NuttX, a keyboard/keypad driver is simply a character driver that may have an (optional) encoding/decoding layer on the data returned by the character driver. A keyboard may return simple text data (alphabetic, numeric, and punctuaction) or control characters (enter, control-C, etc.) when a key is pressed. We can think about this the "normal" keyboard data stream. However, in addition, most keyboards support actions that cannot be represented as text or control data. Such actions include things like cursor controls (home, up arrow, page down, etc.), editing functions (insert, delete, etc.), volume controls, (mute, volume up, etc.) and other special functions. In this case, some special encoding may be required to multiplex the normal text data and special command key press data streams.

Key Press and Release Events Sometimes the time that a key is released is needed by applications as well. Thus, in addition to normal and special key press events, it may also be necessary to encode normal and special key release events.

Encoding/Decoding Layer. An optional encoding/decoding layer can be used with the basic character driver to encode the keyboard events into the text data stream. The function interfaces that comprise that encoding/decoding layer are defined in the header file `include/nuttx/input/kbd_code.h`. These functions provide an matched set of (a) driver encoding interfaces, and (b) application decoding interfaces.

1. Driver Encoding Interfaces. These are interfaces used by the keyboard/keypad driver to encode keyboard events and data.

   - `kbd_press()`

     Function Prototype:

         #include <nuttx/streams.h>
         #include <nuttx/input/kbd_codec.h>
         void kbd_press(int ch, FAR struct lib_outstream_s *stream);

     Description:

     Indicates a normal key press event. Put one byte of normal keyboard data into the output stream.

     Input Pameters:

     - `ch`: The character to be added to the output stream.
     - `stream`: An instance of `lib_outstream_s` to perform the actual low-level put operation.

     Returned Value:

     None.

   - `kbd_release()`

     Function Prototype:

         #include <nuttx/streams.h>
         #include <nuttx/input/kbd_codec.h>
         void kbd_release(uint8_t ch, FAR struct lib_outstream_s *stream);

     Description:

     Encode the release of a normal key.

     Input Pameters:

     - `ch`: The character associated with the key that was releared.
     - `stream`: An instance of `lib_outstream_s` to perform the actual low-level put operation.

     Returned Value:

     None.

   - `kbd_specpress()`

     Function Prototype:

         #include <nuttx/streams.h>
         #include <nuttx/input/kbd_codec.h>
         void kbd_specpress(enum kbd_keycode_e keycode, FAR struct lib_outstream_s *stream);

     Description:

     Denotes a special key press event. Put one special keyboard command into the output stream.

     Input Pameters:

     - `keycode`: The command to be added to the output stream. The enumeration `enum kbd_keycode_e keycode` identifies all commands known to the system.
     - `stream`: An instance of `lib_outstream_s` to perform the actual low-level put operation.

     Returned Value:

     None.

   - `kbd_specrel()`

     Function Prototype:

         #include <nuttx/streams.h>
         #include <nuttx/input/kbd_codec.h>
         void kbd_specrel(enum kbd_keycode_e keycode, FAR struct lib_outstream_s *stream);

     Description:

     Denotes a special key release event. Put one special keyboard command into the output stream.

     Input Pameters:

     - `keycode`: The command to be added to the output stream. The enumeration `enum kbd_keycode_e keycode` identifies all commands known to the system.
     - `stream`: An instance of `lib_outstream_s` to perform the actual low-level put operation.

     Returned Value:

     None.

2. Application Decoding Interfaces. These are user interfaces to decode the values returned by the keyboard/keypad driver.

   - `kbd_decode()`

     Function Prototype:

         #include <nuttx/streams.h>
         #include <nuttx/input/kbd_codec.h>
         int kbd_decode(FAR struct lib_instream_s *stream, FAR struct kbd_getstate_s *state, FAR uint8_t *pch);

     Description:

     Get one byte of data or special command from the driver provided input buffer.

     Input Pameters:

     - `stream`: An instance of `lib_instream_s` to perform the actual low-level get operation.
     - `pch`: The location to save the returned value. This may be either a normal, character code or a special command (i.e., a value from `enum kbd_getstate_s`.
     - `state`: A user provided buffer to support parsing. This structure should be cleared the first time that `kbd_decode()` is called.

     Returned Value:

     - `KBD_PRESS` (0): Indicates the successful receipt of normal, keyboard data. This corresponds to a keypress event. The returned value in `pch` is a simple byte of text or control data.
     - `KBD_RELEASE` (1): Indicates a key release event. The returned value in `pch` is the byte of text or control data corresponding to the released key.
     - `KBD_SPECPRESS` (2): Indicates the successful receipt of a special keyboard command. The returned value in `pch` is a value from `enum kbd_getstate_s`.
     - `KBD_SPECREL` (3): Indicates a special command key release event. The returned value in `pch` is a value from `enum kbd_getstate_s`.
     - `KBD_ERROR` (`EOF`): An error has getting the next character (reported by the `stream`). Normally indicates the end of file.

I/O Streams. Notice the use of the abstract I/O streams in these interfaces. These stream interfaces are defined in `include/nuttx/streams.h`.

## 6.4 Power Management

### 6.4.1 Overview

NuttX supports a simple power managment (PM) sub-system. This sub-system:

- Monitors driver activity, and

- Provides hooks to place drivers (and the whole system) into reduce power modes of operation.

The PM sub-system integrates the MCU idle loop with a collection of device drivers to support:

- Reports of relevant driver or other system activity.

- Registration and callback mechanism to interface with individual device drivers.

- IDLE time polling of overall driver activity.

- Coordinated, global, system-wide transitions to lower power usage states.

Various "sleep" and low power consumption states have various names and are sometimes used in conflicting ways. In the NuttX PM logic, we will use the following terminology:

`NORMAL`
  The normal, full power operating mode.
`IDLE`
  This is still basically normal operational mode, the system is, however, `IDLE` and some simple simple steps to reduce power consumption provided that they do not interfere with normal Operation. Simply dimming the a backlight might be an example somethat that would be done when the system is idle.
`STANDBY`
  Standby is a lower power consumption mode that may involve more extensive power management steps such has disabling clocking or setting the processor into reduced power consumption modes. In this state, the system should still be able to resume normal activity almost immediately.
`SLEEP`
  The lowest power consumption mode. The most drastic power reduction measures possible should be taken in this state. It may require some time to get back to normal operation from `SLEEP` (some MCUs may even require going through reset).

These various states are represented with type `enum pm_state_e` in `include/nuttx/power/pm.h`.

### 6.4.2 Interfaces

All PM interfaces are declared in the file `include/nuttx/power/pm.h`.

#### 6.4.2.1 `pm_initialize()`

Function Prototype:

    #include <nuttx/power/pm.h>
    void pm_initialize(void);

Description: This function is called by MCU-specific one-time at power on reset in order to initialize the power management capabilities. This function must be called very early in the initializeation sequence before any other device drivers are initialize (since they may attempt to register with the power management subsystem).

Input Parameters: None

Returned Value: None

#### 6.4.2.2 `pm_register()`

Function Prototype:

    #include <nuttx/power/pm.h>
    int pm_register(FAR struct pm_callback_s *callbacks);

Description: This function is called by a device driver in order to register to receive power management event callbacks. Refer to the PM Callback section for more details.

Input Parameters:

`callbacks`
  An instance of `struct pm_callback_s` providing the driver callback functions.

Returned Value: Zero (`OK`) on success; otherwise a negater `errno` value is returned.

#### 6.4.2.3 `pm_activity()`

Function Prototype:

    #include <nuttx/power/pm.h>
    void pm_activity(int priority);

Description: This function is called by a device driver to indicate that it is performing meaningful activities (non-idle). This increment an activty count and/or will restart a idle timer and prevent entering reduced power states.

Input Parameters:

`priority`
  Activity priority, range 0-9. Larger values correspond to higher priorities. Higher priority activity can prevent the system from entering reduced power states for a longer period of time. As an example, a button press might be higher priority activity because it means that the user is actively interacting with the device.

Returned Value: None

Assumptions: This function may be called from an interrupt handler (this is the ONLY PM function that may be called from an interrupt handler!).

#### 6.4.2.4 `pm_checkstate()`

Function Prototype:

    #include <nuttx/power/pm.h>
    enum pm_state_e pm_checkstate(void);

Description: This function is called from the MCU-specific IDLE loop to monitor the power management conditions. This function returns the "recommended" power management state based on the PM configuration and activity reported in the last sampling periods. The power management state is not automatically changed, however. The IDLE loop must call `pm_changestate()` in order to make the state change.

These two steps are separated because the platform-specific IDLE loop may have additional situational information that is not available to the PM sub-system. For example, the IDLE loop may know that the battery charge level is very low and may force lower power states even if there is activity.

NOTE: That these two steps are separated in time and, hence, the IDLE loop could be suspended for a long period of time between calling `pm_checkstate()` and `pm_changestate()`. The IDLE loop may need to make these calls atomic by either disabling interrupts until the state change is completed.

Input Parameters: None

Returned Value: The recommended power management state.

#### 6.4.2.5 `pm_changestate()`

Function Prototype:

    #include <nuttx/power/pm.h>
     int pm_changestate(enum pm_state_e newstate);

Description: This function is used by platform-specific power management logic. It will announce the power management power management state change to all drivers that have registered for power management event callbacks.

Input Parameters:

`newstate`
  Identifies the new PM state

Returned Value: 0 (`OK`) means that the callback function for all registered drivers returned `OK` (meaning that they accept the state change). Non-zero means that one of the drivers refused the state change. In this case, the system will revert to the preceding state.

Assumptions: It is assumed that interrupts are disabled when this function is called. This function is probably called from the IDLE loop... the lowest priority task in the system. Changing driver power management states may result in renewed system activity and, as a result, can suspend the IDLE thread before it completes the entire state change unless interrupts are disabled throughout the state change.

### 6.4.3 Callbacks

The `struct pm_callback_s` includes the pointers to the driver callback functions. This structure is defined `include/nuttx/power/pm.h`. These callback functions can be used to provide power management information to the driver.

#### 6.4.3.1 `prepare()`

Function Prototype:

    int (*prepare)(FAR struct pm_callback_s *cb, enum pm_state_e pmstate);

Description: Request the driver to prepare for a new power state. This is a warning that the system is about to enter into a new power state. The driver should begin whatever operations that may be required to enter power state. The driver may abort the state change mode by returning a non-zero value from the callback function.

Input Parameters:

`cb`
  Returned to the driver. The driver version of the callback strucure may include additional, driver-specific state data at the end of the structure.
`pmstate`
  Identifies the new PM state

Returned Value: Zero (`OK`) means the event was successfully processed and that the driver is prepared for the PM state change. Non-zero means that the driver is not prepared to perform the tasks needed achieve this power setting and will cause the state change to be aborted. NOTE: The `prepare()` method will also be called when reverting from lower back to higher power consumption modes (say because another driver refused a lower power state change). Drivers are not permitted to return non-zero values when reverting back to higher power consumption modes!

#### 6.4.3.1 `notify()`

Function Prototype:

    #include <nuttx/power/pm.h>
    void (*notify)(FAR struct pm_callback_s *cb, enum pm_state_e pmstate);

Description: Notify the driver of new power state. This callback is called after all drivers have had the opportunity to prepare for the new power state.

Input Parameters:

`cb`
  Returned to the driver. The driver version of the callback strucure may include additional, driver-specific state data at the end of the structure.
`pmstate`
  Identifies the new PM state

Returned Value: None. The driver already agreed to transition to the low power consumption state when when it returned `OK` to the `prepare()` call.

# Appendix A: NuttX Configuration Settings

At one time, this section provided a list of all NuttX configuration variables. However, NuttX has since converted to use the kconfig-frontends tools. Now, the NuttX configuration is determined by a self-documenting set of `Kconfig` files.

The current NuttX configuration variables are also documented in separate, auto-generated configuration variable document. That configuration variable document is generated using the `kconfig2html` tool that can be found in the `nuttx/tools` directory. That tool analyzes the NuttX Kconfig files and generates excruciatingly boring HTML document.

The latest boring configuration variable documentation can be regenerated at any time using that tool or, more appropriately, the wrapper script at `nuttx/tools/mkconfigvars.sh`. That script will generate the file `nuttx/Documentation/NuttXConfigVariables.html`.

The version of `NuttXConfigVariables.html` for the last released version of NuttX can also be found online.

# Appendix B: Trademarks

- ARM, ARM7 ARM7TDMI, ARM9, ARM920T, ARM926EJS, Cortex-M3 are trademarks of Advanced RISC Machines, Limited.
- Cygwin is a trademark of Red Hat, Incorporated.
- Linux is a registered trademark of Linus Torvalds.
- Eagle-100 is a trademark of Micromint USA, LLC.
- LPC2148 is a trademark of NXP Semiconductors.
- TI is a trade name of Texas Instruments Incorporated.
- UNIX is a registered trademark of The Open Group.
- VxWorks is a registered trademark of Wind River Systems, Incorporated.
- ZDS, ZNEO, Z16F, Z80, and Zilog are a registered trademark of Zilog, Inc.

NOTE: NuttX is not licensed to use the POSIX trademark. NuttX uses the POSIX standard as a development guideline only.