Table of Contents |
- 1.0 Introduction
2.0 Directory Structure
- 2.1 nuttx/Documentation
2.2 nuttx/arch/ 2.3 nuttx/binfmt/
2.4 nuttx/audio/
2.5 nuttx/boards/
- 2.5.1 Subdirectory Structure
2.5.2 Summary of Files 2.5.3 Supported Boards
2.5.4 Adding a New Board Configuration
2.7 nuttx/crypto/
2.8 nuttx/fs/
2.9 nuttx/graphics/
2.10 nuttx/include/
2.11 nuttx/lib/
2.12 nuttx/libs/libc/
2.13 nuttx/libs/libxx/
2.14 nuttx/mm/
2.15 nuttx/net
2.16 nuttx/sched/
2.17 nuttx/syscall/
2.18 nuttx/tools/
2.19 nuttx/wireless/
2.20 nuttx/Makefile
- 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.4.1 Basic System Timer
4.4.2 Hardware
4.4.3 System Tick and Time
4.4.4 Tickless OS
4.4.5 Watchdog Timer Interfaces
- 4.5.1 Classes of Work Queues
- 4.5.1.1 High Priority Kernel Work queue
4.5.1.2 Low Priority Kernel Work Queue
4.5.1.3 User-Mode Work Queue
- 4.6.1
up_addrenv_create()
4.6.2
up_addrenv_destroy()
4.6.3
up_addrenv_vtext()
4.6.4
up_addrenv_vdata()
4.6.5
up_addrenv_heapsize()
4.6.6
up_addrenv_select()
4.6.7
up_addrenv_restore()
4.6.8
up_addrenv_clone()
4.6.9
up_addrenv_attach()
4.6.10
up_addrenv_detach()
4.6.11
up_addrenv_ustackalloc()
4.6.12
up_addrenv_ustackfree()
4.6.13
up_addrenv_vustack()
4.6.14
up_addrenv_ustackselect()
4.6.15
up_addrenv_kstackalloc()
4.6.16
up_addrenv_kstackfree()
- 4.7.1
nx_start()
4.7.2 OS List Management APIs
4.7.3
nxsched_process_timer()
4.7.4
nxsched_timer_expiration()
4.7.5
nxsched_alarm_expiration()
4.7.6
irq_dispatch()
4.9
boardctl()
Application Interface4.10 Symmetric Multiprocessing (SMP) Application Interface
- 4.10.1
up_testset()
4.10.2
up_cpu_index()
4.10.3
up_cpu_start()
4.10.4
up_cpu_pause()
4.10.5
up_cpu_resume()
4.13 LED Support 4.14 I/O Buffer Management
6.0 NuttX Device Drivers
- 6.1 Character Device Drivers
- 6.1.1 Serial Device Drivers
6.1.2 Touchscreen Device Drivers
6.1.3 Analog (ADC/DAC) Drivers
6.1.4 PWM Drivers
6.1.5 CAN Drivers
6.1.6 Quadrature Encoder Drivers
6.1.7 Timer Drivers
6.1.8 RTC Drivers
6.1.9 Watchdog Timer Drivers
6.1.10 Keyboard/Keypad 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 Frame Buffer Drivers
6.3.5 LCD Drivers
6.3.6 Memory Technology Device Drivers
6.3.7 SDIO Device Drivers
6.3.8 USB Host-Side Drivers
6.3.9 USB Device-Side Drivers
Appendix B: Trademarks
NuttX RTOS Porting GuideLast Updated: April 7, 2020 |
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 boards/README.txt
.
2.0 Directory Structure |
Directory Structure. The general directory 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 | |-- Kconfig | |-- Documentation | | `-- (documentation files)/ | |-- arch/ | | |-- Kconfig | | |-- <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>/ | |-- audio/ | | |-- Makefile | | |-- Kconfig | | `-- (common audio source files) | |-- binfmt/ | | |-- Makefile | | |-- Kconfig | | |-- (binfmt-specific sub-directories)/ | | | `-- (binfmt-specific source files) | | `-- (common binfmt source files) | |-- boards/ | | |-- <architecture-name>/ | | | |-- <chip-name>/ | | | | |-- <board-name>/ | | | | | |-- include/ | | | | | | `-- (other board-specific header files) | | | | | |-- src/ | | | | | | `-- (board-specific source files) | | | | | `- configs/ | | | | | |---<config-name>/ | | | | | | `-- (board configuration-specific source files) | | | | | `---(other configuration sub-directories for this board)/ | | | | `-- <(other board directories)>/ | | | `-- <(other chip directories)>/ | | `-- <(other architecture directories)>/ | |-- crypto | | |-- Makefile | | |-- Kconfig | | `-- (common crypto source files) | |-- drivers/ | | |-- Makefile | | |-- Kconfig | | |-- (driver-specific sub-directories)/ | | | `-- (driver-specific source files) | | `-- (common driver source files) | |-- fs/ | | |-- Makefile | | |-- Kconfig | | |-- (file system-specific sub-directories)/ | | | `-- (file system-specific source files) | | `-- (common file system source files) | |-- graphics/ | | |-- Makefile | | |-- Kconfig | | |-- (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) | |-- libs/ | | |-- libc/ | | | |-- Makefile | | | |-- Kconfig | | | `-- (libc source files) | | |-- libdsp/ | | | |-- Makefile | | | |-- Kconfig | | | `-- (libdsp source files) | | |-- libnx/ | | | |-- Makefile | | | |-- Kconfig | | | `-- (libdsp source files) | | `-- libxx/ | | |-- Makefile | | |-- Kconfig | | `-- (libxx source files) | |-- mm/ | | |-- Makefile | | |-- Kconfig | | `-- (memory management source files) | |-- net/ | | |-- Makefile | | |-- Kconfig | | |-- arp/ | | | `-- (ARP source files) | | |-- devif/ | | | `-- (Ethernet device interface source files) | | |-- icmp/ | | | `-- (ICMP source files) | | |-- igmp/ | | | `-- (IGMP source files) | | |-- iob/ | | | `-- (I/O buffering source files) | | |-- ipv6/ | | | `-- (IPv6 source files) | | |-- netdev/ | | | `-- (Socket device interface source files) | | |-- pkt/ | | | `-- (Packet socket source files) | | |-- route/ | | | `-- (Routing table source files) | | |-- socket/ | | | `-- (BSD socket source files) | | |-- tcp/ | | | `-- (TCP source files) | | |-- udp/ | | | `-- (UDP source files) | | `-- utils/ | | `-- (Miscellaneous, utility source files) | |-- pass1/ | | `-- Makefile | |-- sched/ | | |-- Makefile | | |-- Kconfig | | `-- (sched source files) | |-- syscall/ | | |-- Makefile | | |-- Kconfig | | `-- (syscall source files) | |-- tools/ | | `-- (miscellaneous scripts and programs) | `-- wireless/ | |-- Makefile | |-- Kconfig | `-- (wireless source files) `- apps |-- builtin/ | |-- Makefile | |-- Make.defs | |-- Kconfig | `-- (builtin source files) |-- canutils/ | |-- Makefile | |-- Make.defs | |-- Kconfig | `-- (can utililities sub-directories) |-- fsutils/ | |-- Makefile | |-- Make.defs | |-- Kconfig | `-- (File system utilities sub-directories) |-- gpsutils/ | |-- Makefile | |-- Make.defs | |-- Kconfig | `-- (GPS utilities sub-directories) |-- include/ | `-- (Include sub-directories) |-- interpreters/ | |-- Makefile | |-- Make.defs | |-- Kconfig | `-- (Interpreter sub-directories) |-- modbus/ | |-- Makefile | |-- Make.defs | |-- Kconfig | `-- (Modbus source files) |-- netutils/ | |-- Makefile | |-- Make.defs | |-- Kconfig | |-- (network feature sub-directories)/ | | `-- (network utilities sub-directories) | `-- (netutils common files) |-- nshlib/ | |-- Makefile | |-- Make.defs | |-- Kconfig | `-- NuttShell (NSH) files |-- platform/ | |-- Makefile | |-- Make.defs | |-- Kconfig | `-- (Platform-specific sub-directories) |-- system/ | |-- Makefile | |-- Make.defs | |-- Kconfig | `-- (System utilities sub-directories) |-- testing/ | |-- Makefile | |-- Make.defs | |-- Kconfig | `-- (Test support sub-directories) |-- wireless/ | |-- Makefile | |-- Make.defs | |-- Kconfig | `-- (Wireless utilities sub-directories) `-- examples/ `-- (example)/ |-- Makefile |-- Make.defs |-- Kconfig `-- (example sub-directories)
Configuration Files. The NuttX configuration consists of logic in processor architecture directories, chip/SoC directories, and board configuration directories. The complete configuration is specified by several settings in the NuttX configuration file.
-
Processor architecture specific files. These are the files contained in the
arch/
<arch-name>/
directory and are discussed in a paragraph below. As an example, all ARM processor architectures are provided under thearch/arm/
directory which is selected with theCONFIG_ARCH="arm"
configuration option.Variants of the processor architecture may be provided in sub-directories of the Extending this example, the ARMv7-M ARM family is supported by logic in
arch/arm/include/armv7-m
andarch/arm/src/armv7-m
directories which are selected by theCONFIG_ARCH_CORTEXM3=y
,CONFIG_ARCH_CORTEXM4=y
, orCONFIG_ARCH_CORTEXM7=y
configuration options -
Chip/SoC specific files. Each processor architecture is embedded in a System-on-a-Chip (SoC) architecture. The full SoC architecture includes the processor architecture plus chip-specific interrupt logic, clocking logic, general purpose I/O (GPIO) logic, and specialized, internal peripherals (such as UARTs, USB, etc.).
These chip-specific files are contained within chip-specific sub-directories also under the
arch/
<arch-name>/
directory and are selected via theCONFIG_ARCH_CHIP
selection.As an example, the STMicro STM32 SoC architecture is based on the ARMv7-M processor and is supported by logic in the
arch/arm/include/stm32
andarch/arm/src/stm32
directories which are selected with theCONFIG_ARCH_CHIP="stm32"
configuration setting. -
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 networks, USB, etc.).
These board-specific configuration files can be found in the
boards/
<arch-name>/
<chip-name>/
<board-name>/
sub-directories and are discussed in a paragraph below.The directory
boards/arm/stm32/stm32f4disovery/
, as an example, holds board-specific logic for the STM32F4 Discovery board and is selected via theCONFIG_ARCH_BOARD="stm32f4discovery"
configuration setting.
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 byinclude/nuttx/arch.h
. -
include/types.h
: This provides architecture/toolchain-specific definitions for standard types. This file shouldtypedef
:_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 up_irq_save(void)
: Used to disable all interrupts. In the case of multi-CPU platforms, this function disables interrupts on CPUs. -
void up_irq_restore(irqstate_t flags)
: Used to restore interrupt enables to the same state as beforeup_irq_save()
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 theCONFIG_BUILD_PROTECTED
orCONFIG_BUILD_KERNEL
configurations.-
uintptr_t sys_call0(unsigned int nbr)
:nbr
is one of the system call numbers that can be found ininclude/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 ininclude/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 ininclude/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 ininclude/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 ininclude/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 ininclude/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 ininclude/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 targetssrc/libup.a
andsrc/up_head.o
. Theup_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 withlibup.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 includesarch/
<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 or Cygwin 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.arch/arm
: This directory holds common ARM architectures.arch/avr
: This directory holds common AVR and AVR32 architectures.arch/mips
: This directory holds common MIPS architectures. This include PIC32MX and PIC32MZ.arch/misoc
: This directory supports the Misoc LM3 architecture.arch/or1K
: This directory supports the OpenRISC mor1kx architecture.arch/renesas
: This directory is the home for various Renesas architectures, currently only the M16C and vererable SuperH-1 architectures.arch/risc-v
: This directory supports the RISC-V NR5 architecture.arch/xtensa
: This directory supports the Xtensa LX6 architecture as used by the ESP32.arch/z16f
: Zilog z16f Microcontroller.arch/z80
: This directory holds 8-bit ZiLOG architectures. At present, this includes the Zilog z80, ez80Acclaim! and z8Encore! Microcontrollers.
NOTE: In principle, this user mode port should run in any POSIX environment. This target will probably not run "out-of-the-box" in unverified POSIX environments due to the many host environment dependencies.
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/audio
The audio/
subdirectory contains the NuttX audio sub-system.
2.5 nuttx/boards
The boards/
subdirectory contains custom logic and board 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.5.1 Subdirectory Structure
The boards/
directory contains board specific configuration files. Each board must provide a sub-directory <board-name> under boards/
<arch-name>/
><chip-name>/
with the following characteristics:
<board-name> |-- Kconfig |-- include/ | |-- board.h | `-- (board-specific header files) |-- src/ | |-- Makefile | `-- (board-specific source files) |-- configs/ | |-- <config1-dir> | | |-- Make.defs (optional) | | `-- defconfig | |-- <config2-dir> | | |-- Make.defs | | `-- defconfig | ... |-- scripts/ | |-- (linker script files) | `-- Make.defs (optional) `-- (other board-specific configuration sub-directories)/
2.5.2 Summary of Files
2.5.2.1 Board Specific Logic
-
include/
: This directory contains board specific header files. This directory will be linked asinclude/arch/board
at configuration time and can be included via#include <arch/board/header.h>
. These header file can only be included by files inarch/
<arch-name>/include/
andarch/
<arch-name>/src/
. -
src/
: This directory contains board specific drivers. This directory will be linked as <config>/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
, anddistclean
.
2.5.2.2 Board Specific Configuration Sub-Directories
The boards/
<arch-name>/
<chip-name>/
<board-name>/configs
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 two files: Make.defs
and defconfig
. Typically, each set of configuration files is retained in a separate configuration sub-directory (<config1-dir>, <config2-dir>, .. in the above diagram).
NOTE: That the Make.defs
file may reside in one of two locations: There may be a unique Make.defs file for each configuration in the configuration directory OR if that file is absent, there may be a common board Make.defs
file in the /scripts
directory. The Make.defs
file in the configuration takes precedence if it is present.
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, theCFLAGS
will most likely be different ifCONFIG_DEBUG_FEATURES=y
.The included
tools/Config.mk
file contains additional definitions that may be overridden in the architecture-specific Make.defs file as necessary:COMPILE
,ASSEMBLE
,ARCHIVE
,CLEAN
, andMKDEP
macros
- Tools:
-
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:
- As a makefile fragment included in other makefiles, and
- to generate
include/nuttx/config.h
which is included by most C files in the system.
2.5.3 Supported Boards
All of the specific boards supported by NuttX are identified in the README.txt file.
2.5.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 boards/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 boards/myarch/mychip/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 boards/Kconfig
to support your new board configuration.
In boards/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 boards/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 boards/myarch/mychip/myboard
and we add the following to the long list of defaults (again in alphabetical order):
default "myboard" 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 boards/myarch/mychip/myboard
:
if ARCH_BOARD_MYBOARD source "boards/myarch/mychip/myboard/Kconfig" endif
This includes additional, board-specific configuration variable definitions in boards/myarch/mychip/myboard/Kconfig
.
2.6 nuttx/crypto
This sub-directory holds the NuttX cryptographic sub-system.
2.7 nuttx/drivers
This directory holds architecture-independent device drivers.
drivers/ |-- Kconfig |-- Makefile |-- 1wire/ | |-- Kconfig | |-- Make.defs | `-- (1-wire device source files) |-- analog/ | |-- Kconfig | |-- Make.defs | `-- (ADC and DAC driver source files) |-- audio/ | |-- Kconfig | |-- Make.defs | `-- (Audio device source files) |-- bch/ | |-- Kconfig | |-- Make.defs | `-- (BCH driver source files) |-- can/ | |-- Kconfig | |-- Make.defs | `-- (CAN driver source files) |-- contactless/ | |-- Kconfig | |-- Make.defs | `-- (Contactless device driver source files) |-- eeprom/ | |-- Kconfig | |-- Make.defs | `-- (EEPROM character driver source files) |-- i2c/ | |-- Kconfig | |-- Make.defs | `-- (I2C device driver source files) |-- input/ | |-- Kconfig | |-- Make.defs | `-- (Touchscreen and keypad driver source files) |-- ioexpander/ | |-- Kconfig | |-- Make.defs | `-- (I/O expander and GPIO-related driver source files) |-- lcd/ | |-- Kconfig | |-- Make.defs | `-- (LCD driver source files) |-- leds/ | |-- Kconfig | |-- Make.defs | `-- (LED device driver source files) |-- loop/ | |-- Kconfig | |-- Make.defs | `-- (Loop device driver source files) |-- mmcsd/ | |-- Kconfig | |-- Make.defs | `-- (MMC/SD card driver source files) |-- modem/ | |-- Kconfig | |-- Make.defs | `-- (Modem driver source files) |-- mtd/ | |-- Kconfig | |-- Make.defs | `-- (Memory technology device driver source files) |-- net/ | |-- Kconfig | |-- Make.defs | `-- (Network driver source files) |-- pipes/ | |-- Kconfig | |-- Make.defs | `-- (Pipe and FIFO driver source files) |-- power/ | |-- Kconfig | |-- Make.defs | `-- (Power-related driver source files) |-- sensors/ | |-- Kconfig | |-- Make.defs | `-- (Sensor driver source files) |-- serial/ | |-- Kconfig | |-- Make.defs | `-- (Front-end character drivers for chip-specific UARTs, 16550 UART support, and Pseudo-Terminal support) |-- spi/ | |-- Kconfig | |-- Make.defs | `-- (SPI-related drivers and helper functions) |-- syslog/ | |-- Kconfig | |-- Make.defs | `-- (System logging device support) |-- timers/ | |-- Kconfig | |-- Make.defs | `-- (Timer-based device driver support) |-- usbdev/ | |-- Kconfig | |-- Make.defs | `-- (USB device driver source files) |-- usbhost/ | |-- Kconfig | |-- Make.defs | `-- (USB host driver source files) |-- usbmisc/ | |-- Kconfig | |-- Make.defs | `-- (Miscellaneous USB driver source files) |-- usbmonitor/ | |-- Kconfig | |-- Make.defs | `-- (USB monitor source files) |-- video/ | |-- Kconfig | |-- Make.defs | `-- (Video driver source files) |-- wireless/ | |-- Kconfig | |-- Make.defs | `-- (Wireless driver source files) `-- (Various uncategorized driver source files)
2.8 nuttx/fs
This directory contains the NuttX file system. This file system is described below.
fs/ |-- Kconfig |-- Makefile |-- binfs/ | |-- Kconfig | |-- Make.defs | `-- (BINFS file system source files) |-- cromfs/ | |-- Kconfig | |-- Make.defs | `-- (CROMFS file system source files) |-- dirent/ | |-- Kconfig | |-- Make.defs | `-- (VFS directory access source files) |-- driver/ | |-- Kconfig | |-- Make.defs | `-- (Driver registration OS internal interfaces) |-- fat/ | |-- Kconfig | |-- Make.defs | `-- (FAT file system source files) |-- inode/ | |-- Kconfig | |-- Make.defs | `-- (Pseudo-file system OS internal interfaces) |-- hostfs/ | |-- Kconfig | |-- Make.defs | `-- (HOSTFS file system source files) |-- mmap/ | |-- Kconfig | |-- Make.defs | `-- (RAM-based file mapping source files) |-- mount/ | |-- Kconfig | |-- Make.defs | `-- (Mount point-related OS internal interfaces) |-- mqueue/ | |-- Kconfig | |-- Make.defs | `-- (POSIX message queue OS internal interfaces) |-- nfs/ | |-- Kconfig | |-- Make.defs | `-- (NFS client file system source files) |-- nxffs/ | |-- Kconfig | |-- Make.defs | `-- (NuttX Flash File System (NXFFS) source files) |-- procfs/ | |-- Kconfig | |-- Make.defs | `-- (PROCFS pseudo-file system source files) |-- romfs/ | |-- Kconfig | |-- Make.defs | `-- (ROMFS file system source files) |-- smartfs/ | |-- Kconfig | |-- Make.defs | `-- (SmartFS file system source files) |-- unionfs/ | |-- Kconfig | |-- Make.defs | `-- (UnionFS file system source files) |-- userfs/ | |-- Kconfig | |-- Make.defs | `-- (UserFS file system source files) |-- vfs/ | |-- Kconfig | |-- Make.defs | `-- (VFS OS internal interfaces) `-- (common file system source files)
2.9 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) |-- nxglib/ | |-- Make.defs | `-- (NuttX graphics library (NXGL) source files) |-- nxmu/ | |-- Make.defs | `-- (NuttX graphics multi-user (NXMU) server source files) |-- nxterm/ | |-- Make.defs | `-- (NX terminal (NxTerm) source files) |-- vnc/ | |-- Make.defs | `-- (VNC client/server source files) `-- (common file system source files)
2.10 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) |-- netpacket/ | `-- (Protocol-specific header files. Most non-standard) |-- nuttx/ | |-1wire/ | | `-- (1-wire driver header files) | |-analog/ | | `-- (Analog driver header files) | |-audio/ | | `-- (Audio driver header files) | |-binfmt/ | | `-- (Binary format header files) | |-contactless/ | | `-- (Contactless driver header files) | |-crypto/ | | `-- (Cryptographic support header files) | |-drivers/ | | `-- (Miscellaneous driver header files) | |-eeprom/ | | `-- (EEPROM driver header files) | |-fs/ | | `-- (File System header files) | |-i2c/ | | `-- (I2C-related header files) | |-input/ | | `-- (Input device driver header files) | |-ioexpander/ | | `-- (I/O expander and GPIO driver header files) | |-lcd/ | | `-- (LCD driver header files) | |-leds/ | | `-- (LED driver header files) | |-lib/ | | `-- (Non-standard C library driver header files) | |-mm/ | | `-- (Memory management header files) | |-modem/ | | `-- (Modem driver header files) | |-mtd/ | | `-- (Memory technology device header files) | |-net/ | | `-- (Networking header files) | |-nx/ | | `-- (NX graphics header files) | |-power/ | | `-- (Power management header files) | |-sensors/ | | `-- (Sensor device driver header files) | |-serial/ | | `-- (Serial driver header files) | |-spi/ | | `-- (SPI-related header files) | |-syslog/ | | `-- (SYSLOG header files) | |-timers/ | | `-- (Timer-related driver header files) | |-usb/ | | `-- (USB driver header files) | |-video/ | | `-- (Video-related driver header files) | `-wireless/ | `-- (Wireless device driver header files) `- sys/ `-- (More standard header files)
2.11 nuttx
This is a (almost) empty directory that has a holding place for generated static libraries. The NuttX build system generates a collection of such static libraries in this directory during the compile phase. These libraries are then in a known place for the final link phase where they are accessed to generated the final binaries.
2.12 nuttx/libs/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_BUILD_PROTECTED=y
or CONFIG_BUILD_KERNEL=y
), then the contents of this directory are built as two libraries: One for use by user programs (libc.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/ |-- aio/ | `-- (Implementation of functions from aio.h) |-- audio/ | `-- (Implementation of audio-related functions) |-- dirent/ | `-- (Implementation of functions from dirent.h) |-- dllfch/ | `-- (Implementation of functions from dlfcn.h) |-- fixedmath/ | `-- (Implementation of functions from fixedmath.h) |-- hex2bin/ | `-- (Implementation of functions from hex2bin.h) |-- inttypes/ | `-- (Implementation of functions from inttypes.h) |-- libgen/ | `-- (Implementation of functions from libgen.h) |-- locale/ | `-- (Implementation of functions from locale.h) |-- lzf/ | `-- (Implementation of functions from lzf.h) |-- machine/ | `-- (Implementations of platform-specific logic) |-- math/ | `-- (Implementation of functions from fixedmath.h) |-- misc/ | `-- (Implementation of miscellaneous library functions) |-- modlib/ | `-- (Implementation of functions from nuttx/lib/modlib.h) |-- net/ | `-- (Implementation of network-related library functions) |-- netdb/ | `-- (Implementation of functions from netdb.h) |-- pthread/ | `-- (Implementation of functions from pthread.h) |-- 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) |-- spawn/ | `-- (Implementation of some functions from spawn.h) |-- stdio/ | `-- (Implementation of functions from stdio.h) |-- stdlib/ | `-- (Implementation of functions from stdlib.h) |-- string/ | `-- (Implementation of functions from string.h) |-- symtab/ | `-- (Implementation of symbol-table library functions) |-- syslog/ | `-- (Implementation of functions from syslog.h) |-- termios/ | `-- (Implementation of functions from termios.h) |-- time/ | `-- (Implementation of some functions from time.h) |-- tls/ | `-- (Implementation of some functions from tls.h) |-- uio/ | `-- (Implementation of some functions from uio.h) |-- unistd/ | `-- (Implementation of some functions from unistd.h) |-- userfs/ | `-- (Implementation of application side internals of UserFS) |-- wchar/ | `-- (Implementation of some functions from wchar.h. Not fully functional.) |-- wctype/ | `-- (Implementation of some functions from wctype.h. Not fully functional.) |-- wqueue/ | `-- (Implementation of some functions from wqueue.h) `-- zoneinfo/ `-- (Implementation of timezone database)
2.13 nuttx/libs/libxx
This directory holds a tiny, minimal standard std C++ that can be used to build some, simple C++ applications in NuttX.
2.14 nuttx/mm
This is the NuttX memory manager.
2.15 nuttx/net
This directory contains the implementation of the NuttX networking layer including internal socket APIs.
2.16 nuttx/sched
The files forming core of the NuttX RTOS reside here.
2.17 nuttx/syscall
If NuttX is built as a separately compiled kernel (with CONFIG_BUILD_PROTECTED=y
or CONFIG_BUILD_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.18 nuttx/tools
This directory holds a collection of tools and scripts to simplify configuring, building and maintaining NuttX.
tools/ |-- Makefile.host |-- Makefile.export |-- Makefile.unix, Makefile.win, FlatLibs.mk, KernelLibs.mk, LibTargets.mk, ProtectedLibs.mk |-- README.txt |-- b16.c |-- bdf-converter.c |-- cfgparser.c |-- cfgparser.h |-- cmpconfig.c |-- cnvwindeps.c |-- configure.sh / configure.bat / configure.c |-- copydir.sh / copydir.bat |-- define.sh / define.bat |-- discovery.py |-- incdir.sh / incdir.bat |-- indent.sh |-- initialconfig.c |-- kconfig2html.c / mkconfigvars.sh |-- link.sh / link.bat |-- mkconfig.c |-- mkctags.sh |-- mkdeps.c |-- mkexport.sh |-- mkfsdata.pl |-- mknulldeps.sh |-- mkromfsimg.sh |-- mksymtab.c |-- mksyscall.c |-- mkversion.c |-- mkwindeps.sh |-- noteinfo.c |-- nxstyle.c |-- pic32mx/mkpichex.c |-- refresh.sh |-- sethost.sh |-- showsize.sh |-- testbuild.sh |-- uncrustify.cfg |-- unlink.sh / unlink.bat |-- version.sh |-- xmlrpc_test.py `-- 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.19 nuttx/wireless
This directory holds support for hardware-independent wireless support.
2.20 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.
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
boards/
<arch-name>/
<chip-name>/
<board-name>/configs/[
<config-dir>/]Make.defs
to$(TOPDIR)/Make.defs
(see NOTE below), - Copy
boards/
<arch-name>/
<chip-name>/
<board-name>/configs/[
<config-dir>/]defconfig
to$(TOPDIR)/.config
Where <board-name> is the name of one of the sub-directories of the NuttX boards/
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 optional application directory.
NOTE: Recall that the Make.defs
file may reside in either the boards/
<arch-name>/
<chip-name>/
<board-name>/configs/[
<config-dir> directory or in the boards/
<arch-name>/
<chip-name>/
<board-name>/scripts
.
Automated Configuration. There is a script that automates these steps. The following steps will accomplish the same configuration:
tools/configure.sh [OPTIONS] <board-name>[:<config-dir>]
There is an alternative Windows batch file, configure.bat
, that can be used instead of configure.sh
in the windows native environment like:
tools\configure.bat <board-name>:<config-dir>
And, to make sure that other platforms are supported, there is also a C program at tools/configure.c
that can be compiled to establish the board configuration on all platforms.
NOTE (2019-08-6): As of this writing, changes to the boards/ directly have madeconfigure.bat
unusable. For the native Windows environment,configure.c
is recommended until that batch file can be repaired.
See tools/README.txt
for more information about these scripts. Or use the -h option with configure.sh>
$ tools/configure.sh -h
USAGE: tools/configure.sh [-d] [-l|m|c|u|g|n] [-a <app-dir>] <board-name>[:<config-name>]
Where:
-l selects the Linux (l) host environment.
-m selects the macOS (m) host environment.
-c selects the Windows host and Cygwin (c) environment.
-u selects the Windows host and Ubuntu under Windows 10 (u) environment.
-g selects the Windows host and MinGW/MSYS environment.
-n selects the Windows host and Windows native (n) environment.
Default: Use host setup in the defconfig file
Default Windows: Cygwin
<board-name> is the name of the board in the boards/
directory
<config-name> is the name of the board configuration sub-directory
<app-dir> is the path to the apps/ directory, relative to the nuttx
directory
If your application directory is not in the standard location (../apps
or ../apps-<version>
), then you should also specify the location of the application directory on the command line like:
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: -bUse this build identification string. Default: use GIT build ID NOTE: GIT build information may not be available in a snapshot -d Enable script debug -h show this help message and exit -v -v <major.minor> The NuttX version number expressed as 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) 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, and - The makefile fragment
Make.defs
that provides customized build targets.
Environment Variables. 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
.
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)/boards/
<arch-name>/
<chip-name>/
<board-name>/include
at$(TOPDIR)/include/arch/board
. - Creating a link to
$(TOPDIR)/boards/
<arch-name>/
<chip-name>/
<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 ininclude/nuttx/arch.h
. The definitions in that header file provide the common interface between NuttX and the architecture-specific implementation inarch/
.up_
is supposed to stand for microprocessor; theu
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 likearch_
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 thearch/
directories.There is also a
arch/<architecture>/include/<chip>/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 thatchip.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 ininclude/nuttx/board.h
. Theseboard_
definitions provide the interface between the board-level logic and the commaon and architecture-specific logic. -
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 sostm32_
would be okay too. These should be prototyped inboards/<arch>/<chip>/<board>/src/<board>.h
and should not be used outside of that directory since board-specific definitions have no meaning outside of the board directory. -
Scope of Inclusions. Header files are made accessible to internal OS logic and to applications through symbolic links and through include paths that are provided to the C/C++ compiler. Through these include paths, the NuttX build system also enforces modularity in the design. For example, one important design principle is architectural layering. In this case I am referring to the OS as layered into application interface, common internal OS logic, and lower level platform-specific layers. The platform-specific layers all reside in the either
arch/
sub-directories on theconfig/
subdirectories: The former sub-directories are reserved for microcontroller-specific logic and the latter for board-specific logic.In the strict, layered NuttX architecture, the upper level OS services are always available to platform-specific logic. However, the opposite is not true: Common OS logic must never have any dependency on the lower level platform-specific code. The OS logic must be totally agnostic about its hardware environment. Similarly, microcontroller-specific logic was be completely ignorant of board-specific logic.
This strict layering is enforced in the NuttX build system by controlling the compiler include paths: Higher level code can never include header files from either; of the platform-specific source directories; microcontroller-specific code can never include header files from the board-specific source directories. The board-specific directories are, then, at the bottom of the layered hierarchy.
An exception to these inclusion restrictions is the platform-specific include/. These are made available to higher level OS logic. The microcontroller-specific include directory will be linked at
include/arch/chip
and, hence, can be included like#include <arch/hardware/chip.h
. Similarly, the board-specific include directory will be linked atinclude/arch/board
and, hence, can be included like#include <arch/board/board.h
.Keeping in the spirit of the layered architecture, these publicly visible header files must not export platform-specific definitions; Only platform-specific realizations of standardized declarations should be visible. Those standardized declarations should appear in common header files such as those provided by
include/nuttx/arch.h
andinclude/nuttx/board.h
. Similarly, these publicly visible header file must not include files that reside in the inaccessible platform-specific source directories. For example, the board-specificboards/<arch>/<chip>/<board>/include/board.h
header file must never include microcontroller-specific header files that reside inarch/<arch>/src/<mcu>
. That practice will cause inclusion failures when the publicly visible file is included in common logic outside of the platform-specific source directories.
4.2 APIs Exported by Architecture-Specific Logic to NuttX
4.2.1 up_initialize()
Function 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()
Function 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()
Function 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_BUILD_PROTECTED
or CONFIG_BUILD_KERNEL
have 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 neither CONFIG_BUILD_PROTECTED
nor CONFIG_BUILD_KERNEL
have been selected, then all threads should have kernel-mode privileges.
4.2.4 up_create_stack()
Function 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 stackadj_stack_ptr
: Adjustedstack_alloc_ptr
for HW. The initial value of the stack pointer.
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 ininclude/nuttx/sched.h
):TCB_FLAG_TTYPE_TASK
: Normal user taskTCB_FLAG_TTYPE_PTHREAD
: User pthreadTCB_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_BUILD_PROTECTED
orCONFIG_BUILD_KERNEL
are 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()
Function 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 stackadj_stack_ptr
: Adjustedstack_alloc_ptr
for HW. The initial value of the stack pointer.
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()
Function 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 any time 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.
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()
Function 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.
Input Parameters:
-
dtcb
: The TCB containing information about the stack to be released. -
ttype
: The thread type. This may be one of following (defined ininclude/nuttx/sched.h
):TCB_FLAG_TTYPE_TASK
: Normal user taskTCB_FLAG_TTYPE_PTHREAD
: User pthreadTCB_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_BUILD_PROTECTED
orCONFIG_BUILD_KERNEL
are 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()
Function 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()
Function 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 must be stopped, its context saved and moved into one of the waiting task lists. If it was the task at the head of the ready-to-run list, then a context switch 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()
Function 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()
Function 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:
- The priority of the currently running task drops and the next task in the ready to run list has priority.
- 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()
Function 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()
Function 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()
Function 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:
- 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.
- 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.
- If not in an interrupt handler and the tcb IS the currently executing task -- just call the signal handler now.
4.2.15 up_allocate_heap()
Function 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_BUILD_PROTECTED=y
or CONFIG_BUILD_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()
Function 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()
Function 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 (up_irq_save() 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()
Function 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 (up_irq_restore() 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()
Function 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()
Function 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.3 APIs Exported by Board-Specific Logic to NuttX
Exported board-specific interfaces are prototyped in the header file include/nuttx/board.h
. There are many interfaces exported from board- to architecture-specific logic. But there are only a few exported from board-specific logic to common NuttX logic. Those few of those related to initialization will be discussed in this paragraph. There are others, like those used by boardctl()
that will be discussed in other paragraphs.
All of the board-specific interfaces used by the NuttX OS logic are for controlled board initialization. There are three points in time where you can insert custom, board-specific initialization logic:
First, <arch>_board_initialize()
: This function is not called from the common OS logic, but rather from the architecture-specific power on reset logic. This is used only for initialization of very low-level things like configuration of GPIO pins, power settings, DRAM initialization, etc. The OS has not been initialized at this point, so you cannot allocate memory or initialize device drivers.
The other two board initialization hooks are called from the OS start-up logic and are described in the following paragraphs:
4.3.1 board_early_initialize()
The next level of initialization is performed by a call to up_initialize()
(in arch/<arch>/src/common/up_initialize.c
). The OS has been initialized at this point and it is okay to initialize drivers in this phase. up_initialize()
is not a board-specific interface, but rather an architecture-specific, board-independent interface.
But at this same point in time, the OS will also call a board-specific initialization function named board_early_initialize()
if CONFIG_BOARD_EARLY_INITIALIZE=y
is selected in the configuration. The context in which board_early_initialize()
executes is suitable for early initialization of most, simple device drivers and is a logical, board-specific extension of up_initialize().
board_early_initialize()
runs on the startup, initialization thread. Some initialization operations cannot be performed on the start-up, initialization thread. That is because the initialization thread cannot wait for event. Waiting may be required, for example, to mount a file system or or initialize a device such as an SD card. For this reason, such driver initialize must be deferred to board_late_initialize()
.
4.3.2 board_late_initialize()
And, finally, just before the user application code starts. If CONFIG_BOARD_LATE_INITIALIZE=y
is selected in the configuration, then an final, additional initialization call will be performed in the boot-up sequence to a function called board_late_initialize()
. board_late_initialize()
will be called well after up_initialize()
and board_early_initialize()
are called. board_late_initialize()
will be called just before the main application task is started. This additional initialization phase may be used, for example, to initialize more complex, board-specific device drivers.
Waiting for events, use of I2C, SPI, etc are permissible in the context of board_late_initialize(). That is because board_late_initialize()
will run on a temporary, internal kernel thread.
4.4 System Time and Clock
4.4.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_USEC_PER_TICK
(default 10000 microseconds or 100Hz. If CONFIG_SCHED_TICKLESS
is selected, the default is 100 microseconds). The timer generates an interrupt each CONFIG_USEC_PER_TICK
microseconds 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_USEC_PER_TICK
. 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_USEC_PER_TICK
cannot be achieved due to limitations in frequencies or in dividers. As a result, the time interval specified by CONFIG_USEC_PER_TICK
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.
CONFIG_USEC_PER_TICK
and if there you require accurate up-time for the MCU, then there are measures that you can take: - Perhaps you can adjust
CONFIG_USEC_PER_TICK
to a different value so that an exactlyCONFIG_USEC_PER_TICK
can be realized. - 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_USEC_PER_TICK
is 10000).
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:
- Initially an accumulator is zero an the match value is programmed to 328:
accumulator = 0; match = 328;
- 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) }
- And on that same timer interrupt a new match value would be programmed:
if (accumulator
In this way, the timer interval is controlled from interrupt-to-interrupt to produce an average frequency of exactly 100Hz.
4.4.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_EXTERNAL
- Most MCUs include RTC hardware built into the chip. Other RTCs, external MCUs, may be provided as separate chips typically interfacing with the MCU via a serial interface such as SPI or I2C. These external RTCs differ from the built-in RTCs in that they cannot be initialized until the operating system is fully booted and can support the required serial communications.
CONFIG_RTC_EXTERNAL
will configure the operating system so that it defers initialization of its time facilities. 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 resolution 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-bittime_t
value. In this case, the RTC is used to "seed" the normal NuttX timer and the NuttX timer provides for higher resolution time. IfCONFIG_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. IfCONFIG_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_rtc_initialize()
. Initialize the built-in, MCU hardware RTC per the selected configuration. This function is called once very early in the OS initialization sequence. NOTE that initialization of external RTC hardware that depends on the availability of OS resources (such as SPI or I2C) must be deferred until the system has fully booted. Other, RTC-specific initialization functions are used in that case.up_rtc_time()
. Get the current time in seconds. This is similar to the standardtime()
function. This interface is only required if the low-resolution RTC/counter hardware implementation selected. It is only used by the RTOS during initialization to set up the system time whenCONFIG_RTC
is set but neitherCONFIG_RTC_HIRES
norCONFIG_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 high-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.
4.4.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 initialization variables are overridden by calls to up_rtc_gettime()
which is running continuously 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.4.4 Tickless OS
4.4.4.1 Tickless Overview
Default System Timer. By default, a NuttX configuration uses a periodic timer interrupt that drives all system timing. The timer is provided by architecture-specific code that calls into NuttX at a rate controlled by CONFIG_USEC_PER_TICK
. The default value of CONFIG_USEC_PER_TICK
is 10000 microseconds which corresponds to a timer interrupt rate of 100 Hz.
On each timer interrupt, NuttX does these things:
- Increments a counter. This counter is the system time and has a resolution of
CONFIG_USEC_PER_TICK
microseconds. - Checks if it is time to perform time-slice operations on tasks that have select round-robin scheduling.
- Checks for expiration of timed events.
What is wrong with this default system timer? Nothing really. It is reliable and uses only a small fraction of the CPU band width. But we can do better. Some limitations of default system timer are, in increasing order of importance:
- Overhead: Although the CPU usage of the system timer interrupt at 100Hz is really very low, it is still mostly wasted processing time. One most timer interrupts, there is really nothing that needs be done other than incrementing the counter.
- Resolution: Resolution of all system timing is also determined by
CONFIG_USEC_PER_TICK
. So nothing that be time with resolution finer than 10 milliseconds be default. To increase this resolution,CONFIG_USEC_PER_TICK
an be reduced. However, then the system timer interrupts use more of the CPU bandwidth processing useless interrupts. - Power Usage: But the biggest issue is power usage. When the system is IDLE, it enters a light, low-power mode (for ARMs, this mode is entered with the
wfi
orwfe
instructions for example). But each interrupt awakens the system from this low power mode. Therefore, higher rates of interrupts cause greater power consumption.
Tickless OS. The so-called Tickless OS provides one solution to issue. The basic concept here is that the periodic, timer interrupt is eliminated and replaced with a one-shot, interval timer. It becomes event driven instead of polled: The default system timer is a polled design. On each interrupt, the NuttX logic checks if it needs to do anything and, if so, it does it.
Using an interval timer, one can anticipate when the next interesting OS event will occur, program the interval time and wait for it to fire. When the interval time fires, then the scheduled activity is performed.
4.4.4.2 Tickless Platform Support
In order to use the Tickless OS, one must provide special support from the platform-specific code. Just as with the default system timer, the platform-specific code must provide the timer resources to support the OS behavior. Currently these timer resources are only provided on a few platforms. An example implementation is for the simulation is atnuttx/arch/sim/src/up_tickless.c
. There is another example for the Atmel SAMA5 at nuttx/arch/arm/src/sama5/sam_tickless.c
. These paragraphs will explain how to provide the Tickless OS support to any platform. 4.4.4.3 Tickless Configuration Options
-
CONFIG_ARCH_HAVE_TICKLESS
: If the platform provides support for the Tickless OS, then this setting should be selected in theKconfig
file for the board. Here is what the selection looks in thearch/Kconfig
file for the simulated platform:config ARCH_SIM bool "Simulation" select ARCH_HAVE_TICKLESS ---help--- Linux/Cygwin user-mode simulation.
When the simulation platform is selected, ARCH_HAVE_TICKLESS
is automatically selected, informing the configuration system that Tickless OS options can be selected.
CONFIG_SCHED_TICKLESS
: If CONFIG_ARCH_HAVE_TICKLESS
is selected, then it will enable the Tickless OS features in NuttX.
CONFIG_SCHED_TICKLESS_ALARM
: The tickless option can be supported either via a simple interval timer (plus elapsed time) or via an alarm. The interval timer allows programming events to occur after an interval. With the alarm, you can set a time in the future and get an event when that alarm goes off. This option selects the use of an alarm.
The advantage of an alarm is that it avoids some small timing errors; the advantage of the use of the interval timer is that the hardware requirement may be less.
CONFIG_USEC_PER_TICK
: This option is not unique to Tickless OS operation, but changes its relevance when the Tickless OS is selected. In the default configuration where system time is provided by a periodic timer interrupt, the default system timer is configure the timer for 100Hz or CONFIG_USEC_PER_TICK=10000
. If CONFIG_SCHED_TICKLESS
is selected, then there are no system timer interrupt. In this case, CONFIG_USEC_PER_TICK
does not control any timer rates. Rather, it only determines the resolution of time reported by clock_systime_ticks()
and the resolution of times that can be set for certain delays including watchdog timers and delayed work.
In this case there is still a trade-off: It is better to have the CONFIG_USEC_PER_TICK
as low as possible for higher timing resolution. However, the time is currently held in unsigned int
. On some systems, this may be 16-bits in width but on most contemporary systems it will be 32-bits. In either case, smaller values of CONFIG_USEC_PER_TICK
will reduce the range of values that delays that can be represented. So the trade-off is between range and resolution (you could also modify the code to use a 64-bit value if you really want both).
The default, 100 microseconds, will provide for a range of delays up to 120 hours.
This value should never be less than the underlying resolution of the timer. Errors may ensue.
4.4.4.4 Tickless Imported Interfaces
The interfaces that must be provided by the platform specified code are defined in include/nuttx/arch.h
, listed below, and summarized in the following paragraphs:
- <arch>
_timer_initialize()
: Initializes the timer facilities. Called early in the initialization sequence (byup_initialize()
). -
up_timer_gettime()
: Returns the current time from the platform specific time source.
The tickless option can be supported either via a simple interval timer (plus elapsed time) or via an alarm. The interval timer allows programming events to occur after an interval. With the alarm, you can set a time in* the future and get an event when that alarm goes off.
If CONFIG_SCHED_TICKLESS_ALARM
is defined, then the platform code must provide the following:
-
up_alarm_cancel()
: Cancels the alarm. -
up_alarm_start()
: Enables (or re-enables) the alarm.
If CONFIG_SCHED_TICKLESS_ALARM
is notdefined, then the platform code must provide the following verify similar functions:
-
up_timer_cancel()
: Cancels the interval timer. -
up_timer_start()
: Starts (or re-starts) the interval timer.
Note that a platform-specific implementation would probably require two hardware timers: (1) A interval timer to satisfy the requirements of up_timer_start()
and up_timer_cancel()
, and a (2) a counter to handle the requirement of up_timer_gettime()
. Ideally, both timers would run at the rate determined by CONFIG_USEC_PER_TICK
(and certainly never slower than that rate).
Since timers are a limited resource, the use of two timers could be an issue on some systems. The job could be done with a single timer if, for example, the single timer were kept in a free-running at all times. Some timer/counters have the capability to generate a compare interrupt when the timer matches a comparison value but also to continue counting without stopping. If your hardware supports such counters, one might used the CONFIG_SCHED_TICKLESS_ALARM
option and be able to simply set the comparison count at the value of the free running timer PLUS the desired delay. Then you could have both with a single timer: An alarm and a free-running counter with the same timer!
In addition to these imported interfaces, the RTOS will export the following interfaces for use by the platform-specific interval timer implementation:
-
nxsched_alarm_expiration()
. Called by the platform-specific logic when the alarm expires. -
nxsched_timer_expiration()
. Called by the platform-specific logic when the interval time expires.
4.4.4.4.1 <arch>_timer_initialize()
Function Prototype:
#include "up_internal.h" void <arch>_timer_initialize()(void);
Description:
- Initializes all platform-specific timer facilities. This function is called early in the initialization sequence by
up_initialize()
. On return, the current up-time should be available from up_timer_gettime()
and the interval timer is ready for use (but not actively timing). Input Parameters:
- None
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. Assumptions:
- Called early in the initialization sequence before any special concurrency protections are required.
4.4.4.4.2 up_timer_gettime()
Function Prototype:
#include <nuttx/arch.h> int up_timer_gettime(FAR struct timespec *ts);
Description:
Return the elapsed time since power-up (or, more correctly, since <arch>_timer_initialize()
was called). This function is functionally equivalent to clock_gettime()
for the clock ID CLOCK_MONOTONIC
. This function provides the basis for reporting the current time and also is used to eliminate error build-up from small errors in interval time calculations. Input Parameters:
ts
: Provides the location in which to return the up-time..
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. Assumptions:
- Called from the normal tasking context. The implementation must provide whatever mutual exclusion is necessary for correct operation. This can include disabling interrupts in order to assure atomic register operations.
4.4.4.4.3 up_alarm_cancel()
Function Prototype:
#include <nuttx/arch.h> int up_alarm_cancel(FAR struct timespec *ts);
Description:
Cancel the alarm and return the time of cancellation of the alarm. These two steps need to be as nearly atomic as possible.nxsched_timer_expiration()
will not be called unless the alarm is restarted with up_alarm_start()
. If, as a race condition, the alarm has already expired when this function is called, then time returned is the current time. Input Parameters:
ts
: Location to return the expiration time. The current time should be returned if the timer is not active.ts
may beNULL
in which case the time is not returned
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. Assumptions:
- May be called from interrupt level handling or from the normal tasking level. interrupts may need to be disabled internally to assure non-reentrancy.
4.4.4.4.4 up_alarm_start()
Function Prototype:
#include <nuttx/arch.h> int up_alarm_start(FAR const struct timespec *ts);
Description:
Start the alarm.nxsched_timer_expiration()
will be called when the alarm occurs (unless up_alarm_cancel
is called to stop it). Input Parameters:
ts
: The time in the future at the alarm is expected to occur. When the alarm occurs the timer logic will callnxsched_timer_expiration()
.
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. Assumptions:
- May be called from interrupt level handling or from the normal tasking level. Interrupts may need to be disabled internally to assure non-reentrancy.
4.4.4.4.5 up_timer_cancel()
Function Prototype:
#include <nuttx/arch.h> int up_timer_cancel(FAR struct timespec *ts);
Description:
Cancel the interval timer and return the time remaining on the timer. These two steps need to be as nearly atomic as possible.nxsched_timer_expiration()
will not be called unless the timer is restarted with up_timer_start()
. If, as a race condition, the timer has already expired when this function is called, then that pending interrupt must be cleared so that nxsched_timer_expiration()
is not called spuriously and the remaining time of zero should be returned. Input Parameters:
ts
: Location to return the remaining time. Zero should be returned if the timer is not active.
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. Assumptions:
- May be called from interrupt level handling or from the normal tasking level. interrupts may need to be disabled internally to assure non-reentrancy.
4.4.4.4.6 up_timer_start()
Function Prototype:
#include <nuttx/arch.h> int up_timer_start(FAR const struct timespec *ts);
Description:
Start the interval timer.nxsched_timer_expiration()
will be called at the completion of the timeout (unless up_timer_cancel()
is called to stop the timing). Input Parameters:
ts
: Provides the time interval untilnxsched_timer_expiration()
is called.
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. Assumptions:
- May be called from interrupt level handling or from the normal tasking level. Interrupts may need to be disabled internally to assure non-reentrancy.
4.4.5 Watchdog Timer Interfaces
NuttX provides a general watchdog timer facility. This facility allows the NuttX user to specify a watchdog timer function that will run after a specified delay. The watchdog timer function will run in the context of the timer interrupt handler. Because of this, a limited number of NuttX interfaces are available to he watchdog timer function. However, the watchdog timer function may use mq_send()
, sigqueue()
, or kill()
to communicate with NuttX tasks.
- 4.4.5.1 wd_create/wd_static
- 4.4.5.2 wd_delete
- 4.4.5.3 wd_start
- 4.4.5.4 wd_cancel
- 4.4.5.5 wd_gettime
- 4.4.5.6 Watchdog Timer Callback
4.4.5.1 wd_create/wd_static
Function Prototype:
#include <nuttx/wdog.h> WDOG_ID wd_create(void); void wd_static(FAR struct wdog_s *wdog);
Description: The wd_create()
function will create a timer by allocating the appropriate resources for the watchdog. The wd_create()
function returns a pointer to a fully initialized, dynamically allocated struct wdog_s
instance (which is typedef
'ed as WDOG_ID
);
wd_static()
performs the equivalent initialization of a statically allocated struct wdog_s
instance. No allocation is performed in this case. The initializer definition, WDOG_INITIALIZER
is also available for initialization of static instances of struct wdog_s
. NOTE: wd_static()
is also implemented as a macro definition.
Input Parameters: None.
Returned Value:
- Pointer to watchdog that may be used as a handle in subsequent NuttX calls (i.e., the watchdog ID), or NULL if insufficient resources are available to create the watchdogs.
Assumptions/Limitations:
POSIX Compatibility: This is a NON-POSIX interface. VxWorks provides the following comparable interface:
WDOG_ID wdCreate (void);
Differences from the VxWorks interface include:
- The number of available watchdogs is fixed (configured at initialization time).
4.4.5.2 wd_delete
Function Prototype:
#include <nuttx/wdog.h> int wd_delete(WDOG_ID wdog);
Description: The wd_delete function will deallocate a watchdog timer previously allocated via wd_create()
. The watchdog timer will be removed from the timer queue if has been started.
This function need not be called for statically allocated timers (but it is not harmful to do so).
Input Parameters:wdog
. The watchdog ID to delete. This is actually a pointer to a watchdog structure.
Returned Value:
- Zero (
OK
) is returned on success; a negatederrno
value is return to indicate the nature of any failure.
Assumptions/Limitations: It is the responsibility of the caller to assure that the watchdog is inactive before deleting it.
POSIX Compatibility: This is a NON-POSIX interface. VxWorks provides the following comparable interface:
STATUS wdDelete (WDOG_ID wdog);
Differences from the VxWorks interface include:
- Does not make any checks to see if the watchdog is being used before deallocating it (i.e., never returns ERROR).
4.4.5.3 wd_start
Function Prototype:
#include <nuttx/wdog.h> int wd_start(WDOG_ID wdog, int delay, wdentry_t wdentry, int argc, ....);
Description: This function adds a watchdog to the timer queue. The specified watchdog function will be called from the interrupt level after the specified number of ticks has elapsed. Watchdog timers may be started from the interrupt level.
Watchdog times execute in the context of the timer interrupt handler.
Watchdog timers execute only once.
To replace either the timeout delay or the function to be executed, call wd_start again with the same wdog; only the most recent wd_start() on a given watchdog ID has any effect.
Input Parameters:
wdog
. Watchdog IDdelay
. Delay count in clock tickswdentry
. Function to call on timeoutargc
. The number of uint32_t parameters to pass to wdentry....
. uint32_t size parameters to pass to wdentryNOTE: All parameters must be of type
wdparm_t
.
Returned Value:
- Zero (
OK
) is returned on success; a negatederrno
value is return to indicate the nature of any failure.
Assumptions/Limitations: The watchdog routine runs in the context of the timer interrupt handler and is subject to all ISR restrictions.
POSIX Compatibility: This is a NON-POSIX interface. VxWorks provides the following comparable interface:
STATUS wdStart (WDOG_ID wdog, int delay, FUNCPTR wdentry, int parameter);
Differences from the VxWorks interface include:
- The present implementation supports multiple parameters passed to wdentry; VxWorks supports only a single parameter. The maximum number of parameters is determined by
4.4.5.4 wd_cancel
Function Prototype:
#include <nuttx/wdog.h> int wd_cancel(WDOG_ID wdog);
Description: This function cancels a currently running watchdog timer. Watchdog timers may be canceled from the interrupt level.
Input Parameters:
wdog
. ID of the watchdog to cancel.
Returned Value:
- OK or ERROR
Assumptions/Limitations:
POSIX Compatibility: This is a NON-POSIX interface. VxWorks provides the following comparable interface:
STATUS wdCancel (WDOG_ID wdog);
4.4.5.5 wd_gettime
Function Prototype:
#include <nuttx/wdog.h> int wd_gettime(WDOG_ID wdog);
Description: This function returns the time remaining before the specified watchdog expires.
Input Parameters:
wdog
. Identifies the watchdog that the request is for.
Returned Value: The time in system ticks remaining until the watchdog time expires. Zero means either that wdog is not valid or that the wdog has already expired.
4.4.5.6 Watchdog Timer Callback
When a watchdog expires, the callback function with this type is called:
typedef void (*wdentry_t)(int argc, ...);
Where argc
is the number of wdparm_t
type arguments that follow.
The arguments are passed as scalar wdparm_t
values. For systems where the sizeof(pointer) < sizeof(uint32_t)
, the following union defines the alignment of the pointer within the uint32_t
. For example, the SDCC MCS51 general pointer is 24-bits, but uint32_t
is 32-bits (of course).
sizeof(pointer) <= sizeof(uintptr_t)< code> by definition.
union wdparm_u
{
FAR void *pvarg; /* The size one generic point */
uint32_t dwarg; /* Big enough for a 32-bit value in any case */
uintptr_t uiarg; /* sizeof(uintptr_t) >= sizeof(pointer) */
};
#if UINTPTR_MAX >= UINT32_MAX
typedef uintptr_t wdparm_t;
#else
typedef uint32_t wdparm_t;
#endif
4.5 Work Queues
Work Queues. NuttX provides work queues. Work queues are threads that service a queue of work items to be performed. They are useful for off-loading work to a different threading context, for delayed processing, or for serializing activities.
4.5.1 Classes of Work Queues
Classes of Work Queues. There are three different classes of work queues, each with different properties and intended usage. These class of work queues along with the common work queue interface are described in the following paragraphs.
4.5.1.1 High Priority Kernel Work queue
High Priority Kernel Work queue. The dedicated high-priority work queue is intended to handle delayed processing from interrupt handlers. This work queue is required for some drivers but, if there are no complaints, can be safely disabled. The high priority worker thread also performs garbage collection -- completing any delayed memory deallocations from interrupt handlers. If the high-priority worker thread is disabled, then that clean up will be performed either by (1) the low-priority worker thread, if enabled, and if not (2) the IDLE thread instead (which runs at the lowest of priority and may not be appropriate if memory reclamation is of high priority)
Device Driver Bottom Half. The high-priority worker thread is intended to serve as the bottom half for device drivers. As a consequence it must run at a very high, fixed priority rivalling the priority of the interrupt handler itself. Typically, the high priority work queue should be the highest priority thread in your system (the default priority is 224).
Thread Pool. The work queues can be configured to support multiple, low-priority threads. This is essentially a thread pool that provides multi-threaded servicing of the queue work. This breaks the strict serialization of the "queue" (and hence, the work queue is no longer a queue at all).
Multiple worker threads are required to support, for example, I/O operations that stall waiting for input. If there is only a single thread, then the entire work queue processing would stall in such cases. Such behavior is necessary to support asynchronous I/O, AIO, for example.
Compared to the Low Priority Kernel Work Queue. For less critical, lower priority, application oriented worker thread support, consider enabling the lower priority work queue. The lower priority work queue runs at a lower priority, of course, but has the added advantage that it supports priority inheritance (if CONFIG_PRIORITY_INHERITANCE=y
is also selected): The priority of the lower priority worker thread can then be adjusted to match the highest priority client.
Configuration Options.
CONFIG_SCHED_HPWORK
. Enables the hight priority work queue. CONFIG_SCHED_HPNTHREADS
. The number of threads in the high-priority queue's thread pool. Default: 1 CONFIG_SCHED_HPWORKPRIORITY
. The execution priority of the high-priority worker thread. Default: 224 CONFIG_SCHED_HPWORKSTACKSIZE
. The stack size allocated for the worker thread in bytes. Default: 2048.
Common Configuration Options. These options apply to all work queues:
CONFIG_SIG_SIGWORK
The signal number that will be used to wake-up the worker thread. This same signal is used with the Default: 17
4.5.1.2 Low Priority Kernel Work Queue
Low Priority Kernel Work Queue. This lower priority work queue is better suited for more extended, application oriented processing such as file system clean-up, memory garbage collection and asynchronous I/O operations.
Compared to the High Priority Work Queue. The lower priority work queue runs at a lower priority than the high priority work queue, of course, and so is inappropriate to serve as a driver bottom half. It is, otherwise, very similar to the high priority work queue and most of the discussion above for the high priority work queue applies equally here. The lower priority work queue does have one important, however, that make it better suited for some tasks:
Priority Inheritance. The lower priority worker thread(s) support priority inheritance (if <config> CONFIG_PRIORITY_INHERITANCE
=>
is also selected): The priority of the lower priority worker thread can then be adjusted to match the highest priority client. NOTE: This priority inheritance feature is not automatic. The lower priority worker thread will always a fixed priority unless additional logic implements that callslpwork_boostpriority()
to raise the priority of the lower priority worker thread (typically called before scheduling the work) and then calls the matchinglpwork_restorepriority()
when the work is completed (typically called within the work handler at the completion of the work). Currently, only the NuttX asynchronous I/O logic uses this dynamic prioritization feature.
The higher priority worker thread, on the other hand, is intended to serve as the bottom half for device drivers. As a consequence must run at a very high, fixed priority. Typically, it should be the highest priority thread in your system.
Configuration Options.
CONFIG_SCHED_LPWORK
. If CONFIG_SCHED_LPWORK is selected then a lower-priority work queue will be enabled.CONFIG_SCHED_LPNTHREADS
. The number of threads in the low-priority queue's thread pool. Default: 1CONFIG_SCHED_LPWORKPRIORITY
. The minimum execution priority of the lower priority worker thread. The priority of the all worker threads start at this priority. If priority inheritance is in effect, the priority may be boosted from this level. Default: 50.CONFIG_SCHED_LPWORKPRIOMAX
. The maximum execution priority of the lower priority worker thread. Lower priority worker threads will be started atCONFIG_SCHED_LPWORKPRIORITY
but their priority may be boosted due to priority inheritance. The boosted priority of the low priority worker thread will not, however, ever exceedCONFIG_SCHED_LPWORKPRIOMAX
. This limit would be necessary, for example, if the higher priority worker thread were to defer work to the lower priority thread. Clearly, in such a case, you would want to limit the maximum priority of the lower priority work thread. Default: 176.CONFIG_SCHED_LPWORKSTACKSIZE
. The stack size allocated for the lower priority worker thread. Default: 2048.
4.5.1.3 User-Mode Work Queue
Work Queue Accessibility. The high- and low-priority worker threads are kernel-mode threads. In the normal, flat NuttX build, these work queues are are useful to application code and may be shared. However, in the NuttX protected and kernel build modes, kernel mode code is isolated and cannot be accessed from user-mode code.
User-Mode Work Queue. if either CONFIG_BUILD_PROTECTED
or CONFIG_BUILD_KERNEL
are selected, then the option to enable a special user-mode work queue is enable. The interface to the user-mode work queue is identical to the interface to the kernel-mode work queues and the user-mode work queue is functionally equivalent to the high priority work queue. It differs in that its implementation does not depend on internal, kernel-space facilities.
Configuration Options.
CONFIG_LIB_USRWORK
. If CONFIG_LIB_USRWORK is also defined then the user-mode work queue will be enabled.CONFIG_LIB_USRWORKPRIORITY
. The execution priority of the user-mode priority worker thread. Default: 100CONFIG_LIB_USRWORKSTACKSIZE
. The stack size allocated for the lower priority worker thread. Default: 2048.
4.5.2 Common Work Queue Interfaces
4.5.2.1 Work Queue IDs
Work queue IDs. All work queues use the identical interface functions (at least identical in terms of the function signature). The first parameter passed to the work queue interface function identifies the work queue:
Kernel-Mode Work Queue IDs:
-
HPWORK
. This ID of the high priority work queue that should only be used for hi-priority, time-critical, driver bottom-half functions. -
LPWORK
. This is the ID of the low priority work queue that can be used for any purpose. ifCONFIG_SCHED_LPWORK
is not defined, then there is only one kernel work queue andLPWORK
is equal toHPWORK
.
User-Mode Work Queue IDs:
-
USRWORK
. This is the ID of the user-mode work queue that can be used for any purpose by applications. In a flat build,LPWORK
is equal toLPWORK
so that user applications will use the lower priority work queue (if there is one).
4.5.2.2 Work Queue Interface Types
-
typedef void (*worker_t)(FAR void *arg);
Defines the type of the work callback. -
struct work_s
. Defines one entry in the work queue. This is a client-allocated structure. Work queue clients should not reference any field in this structure since they are subject to change. The user only needs this structure in order to declare instances of the work structure. Handling of all fields is performed by the work queue interfaces described below.
4.5.2.3 Work Queue Interfaces
4.5.2.3.1 work_queue()
Function Prototype:
#include <nuttx/wqueue.h> int work_queue(int qid, FAR struct work_s *work, worker_t worker, FAR void *arg, uint32_t delay);
Description. Queue work to be performed at a later time. All queued work will be performed on the worker thread of execution (not the caller's).
The work structure is allocated and must be initialized to all zero by the caller. Otherwise, the work structure is completely managed by the work queue logic. The caller should never modify the contents of the work queue structure directly. If work_queue()
is called before the previous work as been performed and removed from the queue, then any pending work will be canceled and lost.
Input Parameters:
-
qid
: The work queue ID. -
work
: The work structure to queue -
worker
: The worker callback to be invoked. The callback will invoked on the worker thread of execution. -
arg
: The argument that will be passed to the worker callback function when it is invoked. -
delay
: Delay (in system clock ticks) from the time queue until the worker is invoked. Zero means to perform the work immediately.
Returned Value:
Zero is returned on success; a negated errno
is returned on failure.
4.5.2.3.2 work_cancel()
Function Prototype: #include <nuttx/wqueue.h> int work_cancel(int qid, FAR struct work_s *work);
Description. Cancel previously queued work. This removes work from the work queue. After work has been cancelled, it may be re-queue by calling work_queue()
again.
Input Parameters:
-
qid
: The work queue ID. -
work
: The previously queue work structure to cancel.
Returned Value:
ENOENT
: There is no such work queued.EINVAL
: An invalid work queue was specified.
Zero is returned on success; a negated errno
is returned on failure.
4.5.2.3.3 work_signal()
Function Prototype: #include <nuttx/wqueue.h> int work_signal(int qid);
Description. Signal the worker thread to process the work queue now. This function is used internally by the work logic but could also be used by the user to force an immediate re-assessment of pending work.
Input Parameters:
-
qid
: The work queue ID.
Returned Value:
Zero is returned on success; a negated errno
is returned on failure.
4.5.2.3.4 work_available()
Function Prototype:
#include <nuttx/wqueue.h> bool work_available(FAR struct work_s *work);
Description.
Input Parameters: Check if the work structure is available.
-
work
: The work queue structure to check.
Returned Value:
true
if available; false if busy
(i.e., there is still pending work).
4.5.2.3.5 work_usrstart()
Function Prototype:
#include <nuttx/config.h> #include <nuttx/wqueue.h> #if defined(CONFIG_LIB_USRWORK) && !defined(__KERNEL__) int work_usrstart(void); #endif
Description. The function is only available as a user interface in the kernel-mode build. In the flat build, there is no user-mode work queue; in the protected mode, the user-mode work queue will automatically be started by the OS start-up code. But in the kernel mode, each user process will be required to start is own, private instance of the user-mode work thread using this interface.
Input Parameters: None
Returned Value:
The task ID of the worker thread is returned on success. A negated errno
value is returned on failure.
4.5.2.3.6 lpwork_boostpriority()
Function Prototype:
#include <nuttx/config.h> #include <nuttx/wqueue.h> #if defined(CONFIG_SCHED_LPWORK) && defined(CONFIG_PRIORITY_INHERITANCE) void lpwork_boostpriority(uint8_t reqprio); #endif
Description. Called by the work queue client to assure that the priority of the low-priority worker thread is at least at the requested level, reqprio
. This function would normally be called just before calling work_queue()
.
Input Parameters:
-
reqprio
: Requested minimum worker thread priority.
Returned Value: None
4.5.2.3.7 lpwork_restorepriority()
Function Prototype:
#include <nuttx/config.h> #include <nuttx/wqueue.h> #if defined(CONFIG_SCHED_LPWORK) && defined(CONFIG_PRIORITY_INHERITANCE) void lpwork_restorepriority(uint8_t reqprio); #endif
Description. This function is called to restore the priority after it was previously boosted. This is often done by client logic on the worker thread when the scheduled work completes. It will check if we need to drop the priority of the worker thread.
Input Parameters:
-
reqprio
: Previously requested minimum worker thread priority to be "unboosted".
Returned Value: None
4.6 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 variable CONFIG_ARCH_HAVE_ADDRENV=y
. That will enable the selection of the actual address environment support which is indicated by the selection of the configuration variable CONFIG_ARCH_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_ARCH_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:
-
Binary Loader Support. These are low-level interfaces used in
binfmt/
to instantiate tasks with address environments. These interfaces all operate on typegroup_addrenv_t
which is an abstract representation of a task group's address environment and the type must be defined inarch/arch.h
ifCONFIG_ARCH_ADDRENV
is defined. These low-level interfaces include:- 4.6.1
up_addrenv_create()
: Create an address environment. - 4.6.2
up_addrenv_destroy()
: Destroy an address environment. - 4.6.3
up_addrenv_vtext()
: Returns the virtual base address of the.text
address environment. - 4.6.4
up_addrenv_vdata()
: Returns the virtual base address of the.bss
/.data
address environment. - 4.6.5
up_addrenv_heapsize()
: Return the initial heap size. - 4.6.6
up_addrenv_select()
: Instantiate an address environment. - 4.6.7
up_addrenv_restore()
: Restore an address environment. - 4.6.8
up_addrenv_clone()
: Copy an address environment from one location to another.
- 4.6.1
-
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 task group which as been assigned an address environment byup_addrenv_clone()
.- 4.6.9
up_addrenv_attach()
: Clone the group address environment assigned to a new thread. This operation is done when a pthread is created that share's the same address environment. - 4.6.10
up_addrenv_detach()
: Release the thread's reference to a group address environment when a task/thread exits.
- 4.6.9
-
Dynamic Stack Support.
CONFIG_ARCH_STACK_DYNAMIC=y
indicates that the user process stack resides in its own address space. This option is also required ifCONFIG_BUILD_KERNEL
andCONFIG_LIBC_EXECFUNCS
are selected. Why? Because the caller's stack must be preserved in its own address space when we instantiate the environment of the new process in order to initialize it.NOTE: The naming of the
CONFIG_ARCH_STACK_DYNAMIC
selection implies that dynamic stack allocation is supported. Certainly this option must be set if dynamic stack allocation is supported by a platform. But the more general meaning of this configuration environment is simply that the stack has its own address space.If
CONFIG_ARCH_STACK_DYNAMIC=y
is selected then the platform specific code must export these additional interfaces:- 4.6.11
up_addrenv_ustackalloc()
: Create a stack address environment - 4.6.12
up_addrenv_ustackfree()
: Destroy a stack address environment. - 4.6.13
up_addrenv_vustack()
: Returns the virtual base address of the stack - 4.6.14
up_addrenv_ustackselect()
: Instantiate a stack address environment
- 4.6.11
-
If
CONFIG_ARCH_KERNEL_STACK
is selected, then each user process will have two stacks: (1) a large (and possibly dynamic) user stack and (2) a smaller kernel stack. However, this option is required if bothCONFIG_BUILD_KERNEL
andCONFIG_LIBC_EXECFUNCS
are selected. Why? Because when we instantiate and initialize the address environment of the new user process, we will temporarily lose the address environment of the old user process, including its stack contents. The kernel C logic will crash immediately with no valid stack in place.If
CONFIG_ARCH_KERNEL_STACK=y
is selected then the platform specific code must export these additional interfaces:- 4.6.15
up_addrenv_kstackalloc()
: Allocate the process kernel stack. 4.6.16
up_addrenv_kstackfree()
: Free the process kernel stack. - 4.6.15
4.6.1 up_addrenv_create()
Function Prototype:
int up_addrenv_create(size_t textsize, size_t datasize, size_t heapsize, FAR group_addrenv_t *addrenv);
Description:
- This function is called when a new task is created in order to instantiate an address environment for the new task group.
up_addrenv_create()
is essentially the allocator of the physical memory for the new task. Input Parameters:
textsize
: The size (in bytes) of the.text
address environment needed by the task. This region may be read/execute only.datasize
: The size (in bytes) of the.bss/.data
address environment needed by the task. This region may be read/write only.heapsize
: The initial size (in bytes) of the heap address environment needed by the task. This region may be read/write only.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.6.2 up_addrenv_destroy()
Function Prototype:
int up_addrenv_destroy(group_addrenv_t *addrenv);
Description:
- This function is called when a final thread leaves the task group and the task group is destroyed. This function then destroys the defunct address environment, releasing the underlying physical memory allocated by
up_addrenv_create()
. Input Parameters:
addrenv
: The representation of the task address environment previously returned byup_addrenv_create()
.
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. 4.6.3 up_addrenv_vtext()
Function Prototype:
int up_addrenv_vtext(FAR group_addrenv_t addrenv, FAR void **vtext);
Description:
- Return the virtual
.text
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 byup_addrenv_create()
.vtext
: The location to return the virtual address.
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. 4.6.4 up_addrenv_vdata()
Function Prototype:
int up_addrenv_vdata(FAR group_addrenv_t *addrenv, size_t textsize, FAR void **vdata);
Description:
- Return the virtual
.text
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 byup_addrenv_create()
.textsize
: For some implementations, the text and data will be saved in the same memory region (read/write/execute) and, in this case, the virtual address of the data just lies at this offset into the common region.vdata
: The location to return the virtual address.
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. 4.6.5 up_addrenv_heapsize()
Function Prototype:
ssize_t up_addrenv_heapsize(FAR const group_addrenv_t *addrenv);
Description:
- Return the initial heap allocation size. That is the amount of memory allocated by
up_addrenv_create()
when the heap memory region was first created. This may or may not differ from the heapsize
parameter that was passed to up_addrenv_create()
. Input Parameters:
addrenv
: The representation of the task address environment previously returned byup_addrenv_create()
.
Returned Value:
- The initial heap size allocated is returned on success; a negated
errno
value on failure. 4.6.6 up_addrenv_select()
Function Prototype:
int up_addrenv_select(group_addrenv_t *addrenv, save_addrenv_t *oldenv);
Description:
- After an address environment has been established for a task (via
up_addrenv_create())
, this function may be called 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 byup_addrenv_create()
.oldenv
: The address environment that was in place beforeup_addrenv_select()
was called. This may be used withup_addrenv_restore()
to restore the original address environment that was in place beforeup_addrenv_select()
was called. Note that this may be a task agnostic, platform-specific representation that may or may not be different fromgroup_addrenv_t
.
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. 4.6.7 up_addrenv_restore()
Function Prototype:
int up_addrenv_restore(save_addrenv_t oldenv);
Description:
- After an address environment has been temporarily instantiated by
up_addrenv_select
, this function may be called to restore the original address environment. Input Parameters:
oldenv
: The platform-specific representation of the address environment previously returned byup_addrenv_select()
.
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. 4.6.8 up_addrenv_clone()
Function Prototype:
int up_addrenv_clone(FAR const task_group_s *src, FAR struct task_group_s *dest);
Description:
- Duplicate an address environment. This does not copy the underlying memory, only the representation that can be used to instantiate that memory as an address environment.
Input Parameters:
src
: The address environment to be copied.dest
: The location to receive the copied address environment.
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. 4.6.9 up_addrenv_attach()
Function Prototype:
int up_addrenv_attach(FAR struct task_group_s *group, FAR struct tcb_s *tcb);
Description:
This function is called from the core scheduler logic when a thread is created that needs to share the address environment of its task group. In this case, the group's address environment may need to be "cloned" for the child thread.
NOTE: In most platforms, nothing will need to be done in this case. Simply being a member of the group that has the address environment may be sufficient.
Input Parameters:
group
: The task group to which the new thread belongs.ctcb
: The TCB of the thread needing the address environment.
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. 4.6.10 up_addrenv_detach()
Function Prototype:
int up_addrenv_detach(FAR struct task_group_s *group, FAR struct task_group_s *tcb);
Description:
- This function is called when a task or thread exits in order to release its reference to an address environment. The address environment, however, should persist until up_addrenv_destroy() is called when the task group is itself destroyed. Any resources unique to this thread may be destroyed now.
Input Parameters:
group
: The group to which the thread belonged.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.6.11 up_addrenv_ustackalloc()
Function Prototype:
int up_addrenv_ustackalloc(FAR struct tcb_s *tcb, size_t stacksize);
Description:
This function is called when a new thread is created in order to instantiate an address environment for the new thread's stack. up_addrenv_ustackalloc()
is essentially the allocator of the physical memory for the new task's stack.
Input Parameters:
tcb
: The TCB of the thread that requires the stack address environment.stacksize
: The size (in bytes) of the initial stack address environment needed by the task. This region may be read/write only.
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. 4.6.12 up_addrenv_ustackfree()
Function Prototype:
int up_addrenv_ustackfree(FAR struct tcb_s *tcb);
Description:
This function is called when any thread exits. This function then destroys the defunct address environment for the thread's stack, releasing the underlying physical memory.
Input Parameters:
tcb
: The TCB of the thread that no longer requires the stack address environment.
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. 4.6.13 up_addrenv_vustack()
Function Prototype:
int up_addrenv_vustack(FAR const struct tcb_s *tcb, FAR void **vstack);
Description:
Return the virtual address associated with the newly create stack address environment.
Input Parameters:
tcb
:The TCB of the thread with the stack address environment of interest.vstack
: The location to return the stack virtual base address.
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. 4.6.14 up_addrenv_ustackselect()
Function Prototype:
int up_addrenv_ustackselect(FAR const struct tcb_s *tcb);
Description:
After an address environment has been established for a task's stack (via up_addrenv_ustackalloc()
. This function may be called to instantiate that address environment in the virtual address space. This is a necessary step before each context switch to the newly created thread (including the initial thread startup).
Input Parameters:
tcb
: The TCB of the thread with the stack address environment to be instantiated.
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. 4.6.15 up_addrenv_kstackalloc()
Function Prototype:
int up_addrenv_kstackalloc(FAR struct tcb_s *tcb);
Description:
This function is called when a new thread is created to allocate the new thread's kernel stack. This function may be called for certain terminating threads which have no kernel stack. It must be tolerant of that case.
Input Parameters:
tcb
: The TCB of the thread that requires the kernel stack.
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. 4.6.16 up_addrenv_kstackfree()
Function Prototype:
int up_addrenv_kstackfree(FAR struct tcb_s *tcb);
Description:
This function is called when any thread exits. This function frees the kernel stack.
Input Parameters:
-
tcb
: The TCB of the thread that no longer requires the kernel stack.
Returned Value:
- Zero (
OK
) on success; a negated errno
value on failure. 4.7 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.7.1 nx_start()
To be provided
4.7.2 OS List Management APIs
To be provided
4.7.3 nxsched_process_timer()
Function Prototype:
#include <nuttx/arch.h> void nxsched_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 CONFIG_USEC_PER_TICK
.
4.7.4 nxsched_timer_expiration()
Function Prototype:
#include <nuttx/arch.h> void nxsched_timer_expiration(void);
Description:
Description: ifCONFIG_SCHED_TICKLESS
is defined, then this function is provided by the RTOS base code and called from platform-specific code when the interval timer used to implemented the tick-less OS expires. Input Parameters:
- None
Returned Value:
- None
Assumptions:
- Base code implementation assumes that this function is called from interrupt handling logic with interrupts disabled.
4.7.5 nxsched_alarm_expiration()
Function Prototype:
#include <nuttx/arch.h> void nxsched_timer_expiration(void);
Description:
Description: ifCONFIG_SCHED_TICKLESS
is defined, then this function is provided by the RTOS base code and called from platform-specific code when the interval timer used to implemented the tick-less OS expires. Input Parameters:
- None
Returned Value:
- None
Assumptions:
- Base code implementation assumes that this function is called from interrupt handling logic with interrupts disabled.
4.7.6 irq_dispatch()
Function 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.8 Application OS vs. Internal OS Interfaces
NuttX provides a standard, portable OS interface for use by applications. This standard interface is controlled by the specifications proved at OpenGroup.org. These application interfaces, in general, should not be used directly by logic executing within the OS. The reason for this is that there are certain properties of the standard application interfaces that make them unsuitable for use within the OS These properties include:
-
Use of the per-thread
errno
variable: Handling of return values, particularly, in the case of returned error indications. Most legacy POSIX OS interface return information via a per-threaderrno
. There must be no alteration of theerrno
value that must be stable from the point of view of the application. So, as a general rule, internal OS logic must never modify theerrno
and particularly not by the inappropriate use of application OS interfaces within OS itself.Within the OS, functions do not return error information via the
errno
variable. Instead, the majority of internal OS function return error information as an integer value: Returned values greater than or equal to zero are success values; returned values less than zero indicate failures. Failures are reported by returning a negatederrno
value frominclude/errno.h
, -
Cancellation Points: Many of the application OS interfaces are cancellation points, i.e., when the task is operating in deferred cancellation state, it cannot be deleted or cancelled until it calls an application OS interface that is a cancellation point.
The POSIX specification is very specific about this, specific both in identifying which application OS interfaces are cancellation points and specific in the fact that it is prohibited for any OS operation other than those listed in the specification to generate cancellation points. If internal OS logic were to re-use application OS interfaces directly then it could very easily violate this POSIX requirement by incorrectly generating cancellation points on inappropriate OS operations and could result in very difficult to analyze application failures.
-
Use of per-task Resources: Many resources are only valid in the task group context in which a thread operates. Above we mentioned one:
errno
is only valid for the thread that is currently executing. So, for example, theerrno
at the time of a call is a completely different variable than, say, theerrno
while running in a work queue task.File descriptors are an even better example: An open file on file descriptor 5 on task A is not the same open file as might be used on file descriptor 5 on task B.
As a result, internal OS logic may not use application OS interfaces that use file descriptors or any other per-task resource.
Within NuttX, this is handled by supporting equivalent internal OS interfaces that do not break the above rules. These internal interfaces are intended for use only within the OS and should not be used by application logic. Some examples include:
-
nxsem_wait()
:nxsem_wait()
is functionally equivalent to the standard application interfacesem_wait()
. However,nxsem_wait()
will not modify the errno value and will not cause a cancellation point. (seeinclude/nuttx/semaphore.h
for other internal OS interfaces for semaphores). -
nxsig_waitinfo()
:nxsig_waitinfo()
is functionally equivalent to the standard application interfacesigwaitinfo()
. However,nxsig_waitinfo()
will not modify the errno value and will not cause a cancellation point (seeinclude/nuttx/signal.h
for other internal OS interfaces for signals). -
nxmq_send()
:nxmq_send()
is functionally equivalent to the standard application interfacemq_send()
. However,nxmq_send()
will not modify the errno value and will not cause a cancellation point (seeinclude/nuttx/mqueue.h
for other internal OS interfaces for POSIX message queues). -
file_read()
:file_read()
is functionally equivalent to the standard application interfaceread()
. However,file_read()
will not modify the errno value, will not cause a cancellation point, and uses a special internal data structure in place of the file descriptor (seeinclude/nuttx/fs/fs.h
for other internal OS interfaces for VFS functions). -
psock_recvfrom()
:psock_recvfrom()
is functionally equivalent to the standard application interfacerecvfrom()
. However,psock_recvfrom()
will not modify the errno value, will not cause a cancellation point, and uses a special internal data structure in place of the socket descriptor (seeinclude/nuttx/net/net.h
for other internal OS interfaces for sockets).
4.9 boardctl()
Application Interface
Function Prototype:
include <sys/boardctl.h>
int boardctl(unsigned int cmd, uintptr_t arg);
Description:
In a small embedded system, there will typically be a much greater interaction between application and low-level board features. The canonically correct to implement such interactions is by implementing a character driver and performing the interactions via low level ioctl()
calls. This, however, may not be practical in many cases and will lead to "correct" but awkward implementations.
boardctl()
is non-standard OS interface to alleviate the problem. It basically circumvents the normal device driver ioctl()
interlace and allows the application to perform direct IOCTL-like calls to the board-specific logic. It is especially useful for setting up board operational and test configurations.
NOTE: The other interfaces described in this document are internal OS interface. boardctl()
is an application interface to the OS. There is no point, in fact, of using boardctl()
within the OS; the board interfaces prototyped in include/nuttx/board.h
may be called directly from within the OS.
Application interfaces are described in the NuttX User Guide. This application interface interface is described here only because it is so non-standard and because it is so closely tied to board porting logic.
Input Parameters:
-
cmd
: Identifies the board command to be executed. Seeinclude/sys/boardctl.h
for the complete list of common board commands. Provisions are made to support non-common, board-specific commands as well. -
arg
: The argument that accompanies the command. The nature of the argument is determined by the specific command.
Returned Value:
- On success zero (
OK
) is returned; -1 (ERROR
) is returned on failure with the errno
variable set to indicate the nature of the failure. 4.10 Symmetric Multiprocessing (SMP) Application Interface
According to Wikipedia: "Symmetric multiprocessing (SMP) involves a symmetric multiprocessor system hardware and software architecture where two or more identical processors connect to a single, shared main memory, have full access to all I/O devices, and are controlled by a single operating system instance that treats all processors equally, reserving none for special purposes. Most multiprocessor systems today use an SMP architecture. In the case of multi-core processors, the SMP architecture applies to the cores, treating them as separate processors.
"SMP systems are tightly coupled multiprocessor systems with a pool of homogeneous processors running independently, each processor executing different programs and working on different data and with capability of sharing common resources (memory, I/O device, interrupt system and so on) and connected using a system bus or a crossbar."
For a technical description of the NuttX implementation of SMP, see the NuttX SMP Wiki Page.
None4.10.1 up_testset()
Function Prototype:
#include <nuttx/spinlock.h> #ifdef CONFIG_SPINLOCK spinlock_t up_testset(volatile FAR spinlock_t *lock); #endif
Description:
Perform and atomic test and set operation on the provided spinlock.
Input Parameters:
-
lock
: The address of spinlock object.
Returned Value:
The spinlock is always locked upon return. The value of previous value of the spinlock variable is returned, either SP_LOCKED
if the spinlock was previously locked (meaning that the test-and-set operation failed to obtain the lock) or SP_UNLOCKED
if the spinlock was previously unlocked (meaning that we successfully obtained the lock)
4.10.2 up_cpu_index()
Function Prototype:
#include <nuttx/arch.h> #ifdef CONFIG_SMP int up_cpu_index(void); #else # define up_cpu_index() (0) #endif
Description:
Return an index in the range of 0 through (CONFIG_SMP_NCPUS-1)
that corresponds to the currently executing CPU.
Input Parameters:
- None
Returned Value:
An integer index in the range of 0 through (CONFIG_SMP_NCPUS-1)
that corresponds to the currently executing CPU.
4.10.3 up_cpu_start()
Function Prototype:
#include <nuttx/arch.h> #ifdef CONFIG_SMP int up_cpu_start(int cpu); #endif
Description:
In an SMP configuration, only one CPU is initially active (CPU 0). System initialization occurs on that single thread. At the completion of the initialization of the OS, just before beginning normal multitasking, the additional CPUs would be started by calling this function.
Each CPU is provided the entry point to is IDLE task when started. A TCB for each CPU's IDLE task has been initialized and placed in the CPU's g_assignedtasks[cpu]
list. A stack has also been allocated and initialized.
The OS initialization logic calls this function repeatedly until each CPU has been started, 1 through (CONFIG_SMP_NCPUS-1)
.
Input Parameters:
-
cpu
: The index of the CPU being started. This will be a numeric value in the range of from one to(CONFIG_SMP_NCPUS-1)
). (CPU 0 is already active).
Returned Value:
Zero (OK
) is returned on success; a negated errno
value on failure.
4.10.4 up_cpu_pause()
Function Prototype:
#include <nuttx/arch.h> #ifdef CONFIG_SMP int up_cpu_pause(int cpu); #endif
Description:
Save the state of the current task at the head of the g_assignedtasks[cpu]
task list and then pause task execution on the CPU.
This function is called by the OS when the logic executing on one CPU needs to modify the state of the g_assignedtasks[cpu]
list for another CPU.
Input Parameters:
-
cpu
: The index of the CPU to be paused. This will not be the index of the currently executing CPU.
Returned Value:
Zero (OK
) is returned on success; a negated errno
value on failure.
4.10.5 up_cpu_resume()
Function Prototype:
#include <nuttx/arch.h> #ifdef CONFIG_SMP int up_cpu_resume(int cpu); #endif
Description:
Restart the cpu after it was paused via up_cpu_pause()
, restoring the state of the task at the head of the g_assignedtasks[cpu]
list, and resume normal tasking.
This function is called after up_cpu_pause()
in order resume operation of the CPU after modifying its g_assignedtasks[cpu]
list.
Input Parameters:
-
cpu
: The index of the CPU being resumed. This will not be the index of the currently executing CPU.
Returned Value:
Zero (OK
) is returned on success; a negated errno
value on failure.
4.11 Shared Memory
Shared memory interfaces are only available with the NuttX kernel build (CONFIG_BUILD_KERNEL=y
). These interfaces support user memory regions that can be shared between multiple user processes. The user interfaces are provided in the standard header file include/sys/shm.h>
. All logic to support shared memory is implemented within the NuttX kernel with the exception of two low-level functions that are require to configure the platform-specific MMU resources. Those interfaces are described below:
4.11.1 up_shmat()
Function Prototype:
#include <nuttx/arch.h> #ifdef CONFIG_MM_SHM int up_shmat(FAR uintptr_t *pages, unsigned int npages, uintptr_t vaddr); #endif
Description:
- Attach, i.e, map, on shared memory region to a user virtual address.
Input Parameters:
-
pages
: A pointer to the first element in a array of physical address, each corresponding to one page of memory. -
npages
: The number of pages in the list of physical pages to be mapped. -
vaddr
: The virtual address corresponding to the beginning of the (contiguous) virtual address region.
Returned Value:
- Zero (
OK
) is returned on success; a negated errno
value is returned on failure. 4.11.2 up_shmdt()
Function Prototype:
#include <nuttx/arch.h> #ifdef CONFIG_MM_SHM int up_shmdt(uintptr_t vaddr, unsigned int npages); #endif
Description:
- Detach, i.e, unmap, on shared memory region from a user virtual address.
Input Parameters:
-
vaddr
: The virtual address corresponding to the beginning of the (contiguous) virtual address region. -
npages
: T The number of pages to be unmapped.
Returned Value:
- Zero (
OK
) is returned on success; a negated errno
value is returned on failure. 4.12 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 certain 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 separate document. Please see the NuttX Demand Paging design document for further information.
4.13 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.13.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 toinclude/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.13.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.13.3 Common LED interfaces
The include/nuttx/board.h
has declarations like:
#ifdef CONFIG_ARCH_LEDS void board_autoled_initialize(void); void board_autoled_on(int led); void board_autoled_off(int led); #else # define board_autoled_initialize() # define board_autoled_on(led) # define board_autoled_off(led) #endif
Where:
-
void board_autoled_initialize(void)
is called early in power-up initialization to initialize the LED hardware.NOTE: In most architectures,
board_autoled_initialize()
is called from board-specific initialization logic. But there are a few architectures where this initialization function is still called from common chip architecture logic. This interface is not, however, a common board interface in any event.WARNING: This interface name will eventually be removed; do not use it in new board ports. New implementations should not use the naming convention for common board interfaces, but should instead use the naming conventions for microprocessor-specific interfaces or the board-specific interfaces (such as
stm32_led_initialize()
). -
board_autoled_on(int led)
is called to instantiate the LED presentation of the event. Theled
argument is one of the definitions provided in<board-name>/include/board.h
. -
board_autoled_off(int led
is called to terminate the LED presentation of the event. Theled
argument is one of the definitions provided in<board-name>/include/board.h
. Note that onlyLED_INIRQ
,LED_SIGNAL
,LED_ASSERTION
, andLED_PANIC
indications are terminated.
4.14 I/O Buffer Management
NuttX supports generic I/O buffer management (IOB) logic. This logic was originally added to support network I/O buffering, but has been generalized to meet buffering requirements by all device drivers. At the time of this writing, IOBs are currently used not only be networking but also by logic indrivers/syslog
and drivers/wireless
. NOTE that some of the wording in this section still reflects those legacy roots as a part of the networking subsystem. This objectives of this feature are: - Provide common I/O buffer management logic for all drivers,
- Support I/O buffer allocation from both the tasking and interrupt level contexts.
- Use a fixed amount of pre-allocated memory.
- No costly, non-deterministic dynamic memory allocation.
- When the fixed number of pre-allocated I/O buffers is exhausted, further attempts to allocate memory from tasking logic will cause the task to block and wait until a an I/O buffer to be freed.
- Each I/O buffer should be small, but can be chained together to support buffering of larger thinks such as full size network packets.
- Support throttling logic to prevent lower priority tasks from hogging all available I/O buffering.
4.14.1 Configuration Options
CONFIG_MM_IOB
- Enables generic I/O buffer support. This setting will build the common I/O buffer (IOB) support library.
CONFIG_IOB_NBUFFERS
- Number of pre-allocated I/O buffers. Each packet is represented by a series of small I/O buffers in a chain. This setting determines the number of preallocated I/O buffers available for packet data. The default value is setup for network support. The default is 8 buffers if neither TCP/UDP or write buffering is enabled (neither
CONFIG_NET_TCP_WRITE_BUFFERS
norCONFIG_NET_TCP
), 24 if only TCP/UDP is enabled, and 36 if both TCP/UDP and write buffering are enabled. CONFIG_IOB_BUFSIZE
- Payload size of one I/O buffer. Each packet is represented by a series of small I/O buffers in a chain. This setting determines the data payload each preallocated I/O buffer. The default value is 196 bytes.
CONFIG_IOB_NCHAINS
- Number of pre-allocated I/O buffer chain heads. These tiny nodes are used as containers to support queueing of I/O buffer chains. This will limit the number of I/O transactions that can be in-flight at any give time. The default value of zero disables this features.
- These generic I/O buffer chain containers are not currently used by any logic in NuttX. That is because their other other specialized I/O buffer chain containers that also carry a payload of usage specific information. The default value is zero if nether TCP nor UDP is enabled (i.e., neither
CONFIG_NET_TCP
&& !CONFIG_NET_UDP
or eight if either is enabled. - These generic I/O buffer chain containers are not currently used by any logic in NuttX. That is because their other other specialized I/O buffer chain containers that also carry a payload of usage specific information. The default value is zero if nether TCP nor UDP is enabled (i.e., neither
CONFIG_IOB_THROTTLE
- I/O buffer throttle value. TCP write buffering and read-ahead buffer use the same pool of free I/O buffers. In order to prevent uncontrolled incoming TCP packets from hogging all of the available, pre-allocated I/O buffers, a throttling value is required. This throttle value assures that I/O buffers will be denied to the read-ahead logic before TCP writes are halted. The default 0 if neither TCP write buffering nor TCP read-ahead buffering is enabled. Otherwise, the default is 8.
CONFIG_IOB_DEBUG
- Force I/O buffer debug. This option will force debug output from I/O buffer logic. This is not normally something that would want to do but is convenient if you are debugging the I/O buffer logic and do not want to get overloaded with other un-related debug output. NOTE that this selection is not available if DEBUG features are not enabled (
CONFIG_DEBUG_FEATURES
) with IOBs are being used to syslog buffering logic (CONFIG_SYSLOG_BUFFER
).
4.14.2 Throttling
An allocation throttle was added. I/O buffer allocation logic supports a throttle value originally for read-ahead buffering to prevent the read-ahead logic from consuming all available I/O buffers and blocking the write buffering logic. This throttle logic is only needed for networking only if both write buffering and read-ahead buffering are used. Of use of I/O buffering might have other motivations for throttling.4.14.3 Public Types
This structure represents one I/O buffer. A packet is contained by one or more I/O buffers in a chain. The io_pktlen
is only valid for the I/O buffer at the head of the chain.
struct iob_s { /* Singly-link list support */ FAR struct iob_s *io_flink; /* Payload */ #if CONFIG_IOB_BUFSIZE
This container structure supports queuing of I/O buffer chains. This structure is intended only for internal use by the IOB module.
#if CONFIG_IOB_NCHAINS > 0 struct iob_qentry_s { /* Singly-link list support */ FAR struct iob_qentry_s *qe_flink; /* Payload -- Head of the I/O buffer chain */ FAR struct iob_s *qe_head; }; #endif /* CONFIG_IOB_NCHAINS > 0 */
The I/O buffer queue head structure.
#if CONFIG_IOB_NCHAINS > 0 struct iob_queue_s { /* Head of the I/O buffer chain list */ FAR struct iob_qentry_s *qh_head; FAR struct iob_qentry_s *qh_tail; }; #endif /* CONFIG_IOB_NCHAINS > 0 */
4.14.4 Public Function Prototypes
- 4.14.4.1
iob_initialize()
- 4.14.4.2
iob_alloc()
- 4.14.4.3
iob_tryalloc()
- 4.14.4.4
iob_free()
- 4.14.4.5
iob_free_chain()
- 4.14.4.6
iob_add_queue()
- 4.14.4.7
iob_tryadd_queue()
- 4.14.4.8
iob_remove_queue()
- 4.14.4.9
iob_peek_queue()
- 4.14.4.10
iob_free_queue()
- 4.14.4.11
iob_copyin()
- 4.14.4.12
iob_trycopyin()
- 4.14.4.13
iob_copyout()
- 4.14.4.14
iob_clone()
- 4.14.4.15
iob_concat()
- 4.14.4.16
iob_trimhead()
- 4.14.4.17
iob_trimhead_queue()
- 4.14.4.18
iob_trimtail()
- 4.14.4.19
iob_pack()
- 4.14.4.20
iob_contig()
- 4.14.4.21
iob_dump()
4.14.4.1 iob_initialize()
Function Prototype:
#include <nuttx/mm/iob.h> void iob_initialize(void);
Description. Set up the I/O buffers for normal operations.
4.14.4.2 iob_alloc()
Function Prototype:
#include <nuttx/mm/iob.h> FAR struct iob_s *iob_alloc(bool throttled);
Description. Allocate an I/O buffer by taking the buffer at the head of the free list.
4.14.4.3 iob_tryalloc()
Function Prototype:
#include <nuttx/mm/iob.h> FAR struct iob_s *iob_tryalloc(bool throttled);
Description. Try to allocate an I/O buffer by taking the buffer at the head of the free list without waiting for a buffer to become free.
4.14.4.4 iob_free()
Function Prototype:
#include <nuttx/mm/iob.h> FAR struct iob_s *iob_free(FAR struct iob_s *iob);
Description. Free the I/O buffer at the head of a buffer chain returning it to the free list. The link to the next I/O buffer in the chain is return.
4.14.4.5 iob_free_chain()
Function Prototype:
#include <nuttx/mm/iob.h> void iob_free_chain(FAR struct iob_s *iob);
Description. Free an entire buffer chain, starting at the beginning of the I/O buffer chain
4.14.4.6 iob_add_queue()
Function Prototype:
#include <nuttx/mm/iob.h> #if CONFIG_IOB_NCHAINS > 0 int iob_add_queue(FAR struct iob_s *iob, FAR struct iob_queue_s *iobq); #endif /* CONFIG_IOB_NCHAINS > 0 */
Description. Add one I/O buffer chain to the end of a queue. May fail due to lack of resources.
4.14.4.7 iob_tryadd_queue()
Function Prototype:
#include <nuttx/mm/iob.h> #if CONFIG_IOB_NCHAINS > 0 int iob_tryadd_queue(FAR struct iob_s *iob, FAR struct iob_queue_s *iobq); #endif /* CONFIG_IOB_NCHAINS > 0 */
Description. Add one I/O buffer chain to the end of a queue without waiting for resources to become free.
4.14.4.8 iob_remove_queue()
Function Prototype:
#include <nuttx/mm/iob.h> #if CONFIG_IOB_NCHAINS > 0 FAR struct iob_s *iob_remove_queue(FAR struct iob_queue_s *iobq); #endif /* CONFIG_IOB_NCHAINS > 0 */
Description. Remove and return one I/O buffer chain from the head of a queue.
Returned Value. Returns a reference to the I/O buffer chain at the head of the queue.
4.14.4.9 iob_peek_queue()
Function Prototype:
#include <nuttx/mm/iob.h> #if CONFIG_IOB_NCHAINS > 0 FAR struct iob_s *iob_peek_queue(FAR struct iob_queue_s *iobq); #endif
Description. Return a reference to the I/O buffer chain at the head of a queue. This is similar to iob_remove_queue except that the I/O buffer chain is in place at the head of the queue. The I/O buffer chain may safely be modified by the caller but must be removed from the queue before it can be freed.
Returned Value. Returns a reference to the I/O buffer chain at the head of the queue.
4.14.4.10 iob_free_queue()
Function Prototype:
#include <nuttx/mm/iob.h> #if CONFIG_IOB_NCHAINS > 0 void iob_free_queue(FAR struct iob_queue_s *qhead); #endif /* CONFIG_IOB_NCHAINS > 0 */
Description. Free an entire queue of I/O buffer chains.
4.14.4.11 iob_copyin()
Function Prototype:
#include <nuttx/mm/iob.h> int iob_copyin(FAR struct iob_s *iob, FAR const uint8_t *src, unsigned int len, unsigned int offset, bool throttled);
Description. Copy data len
bytes from a user buffer into the I/O buffer chain, starting at offset
, extending the chain as necessary.
4.14.4.12 iob_trycopyin()
Function Prototype:
#include <nuttx/mm/iob.h> int iob_trycopyin(FAR struct iob_s *iob, FAR const uint8_t *src, unsigned int len, unsigned int offset, bool throttled);
Description. Copy data len
bytes from a user buffer into the I/O buffer chain, starting at offset
, extending the chain as necessary BUT without waiting if buffers are not available.
4.14.4.13 iob_copyout()
Function Prototype:
#include <nuttx/mm/iob.h> int iob_copyout(FAR uint8_t *dest, FAR const struct iob_s *iob, unsigned int len, unsigned int offset);
Description. Copy data len
bytes of data into the user buffer starting at offset
in the I/O buffer, returning that actual number of bytes copied out.
4.14.4.14 iob_clone()
Function Prototype:
#include <nuttx/mm/iob.h> int iob_clone(FAR struct iob_s *iob1, FAR struct iob_s *iob2, bool throttled);
Description. Duplicate (and pack) the data in iob1
in iob2
. iob2
must be empty.
4.14.4.15 iob_concat()
Function Prototype:
#include <nuttx/mm/iob.h> void iob_concat(FAR struct iob_s *iob1, FAR struct iob_s *iob2);
Description. Concatenate iob_s chain iob2 to iob1.
4.14.4.16 iob_trimhead()
Function Prototype:
#include <nuttx/mm/iob.h> FAR struct iob_s *iob_trimhead(FAR struct iob_s *iob, unsigned int trimlen);
Description. Remove bytes from the beginning of an I/O chain. Emptied I/O buffers are freed and, hence, the beginning of the chain may change.
4.14.4.17 iob_trimhead_queue()
Function Prototype:
#include <nuttx/mm/iob.h> #if CONFIG_IOB_NCHAINS > 0 FAR struct iob_s *iob_trimhead_queue(FAR struct iob_queue_s *qhead, unsigned int trimlen); #endif
Description. Remove bytes from the beginning of an I/O chain at the head of the queue. Emptied I/O buffers are freed and, hence, the head of the queue may change.
This function is just a wrapper around iob_trimhead() that assures that the iob at the head of queue is modified with the trimming operations.
Returned Value. The new iob at the head of the queue is returned.
4.14.4.18 iob_trimtail()
Function Prototype:
#include <nuttx/mm/iob.h> FAR struct iob_s *iob_trimtail(FAR struct iob_s *iob, unsigned int trimlen);
Description. Remove bytes from the end of an I/O chain. Emptied I/O buffers are freed NULL will be returned in the special case where the entry I/O buffer chain is freed.
4.14.4.19 iob_pack()
Function Prototype:
#include <nuttx/mm/iob.h> FAR struct iob_s *iob_pack(FAR struct iob_s *iob);
Description. Pack all data in the I/O buffer chain so that the data offset is zero and all but the final buffer in the chain are filled. Any emptied buffers at the end of the chain are freed.
4.14.4.20 iob_contig()
Function Prototype:
#include <nuttx/mm/iob.h> int iob_contig(FAR struct iob_s *iob, unsigned int len);
Description. Ensure that there is len
bytes of contiguous space at the beginning of the I/O buffer chain starting at iob
.
4.14.4.21 iob_dump()
Function Prototype:
#include <nuttx/mm/iob.h> #ifdef CONFIG_DEBUG_FEATURES void iob_dump(FAR const char *msg, FAR struct iob_s *iob, unsigned int len, unsigned int offset); #endif
Description. Dump the contents of a I/O buffer chain
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. A simple in-memory, pseudo file system can be enabled by default. 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.
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 ofstruct 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 callingregister_driver()
, passing it thepath
where it will appear in the pseudo-file-system and it's initialized instance ofstruct 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. -
Specialized Character Drivers. Within the common character driver framework, there are different specific varieties of specialized character drivers. The unique requirements of the underlying device hardware often mandates some customization of the character driver. These customizations tend to take the form of:
- Device-specific
ioctl()
commands used to performed specialized operations on the device. Theseioctl()
will be documented in header files underinclude/nuttx
that detail the specific device interface. - Specialized I/O formats. Some devices will require that
read()
and/orwrite()
operations use data conforming to a specific format, rather than a plain stream of bytes. These specialized I/O formats will be documented in header files underinclude/nuttx
that detail the specific device interface. The typical representation of the I/O format will be a C structure definition.
The specialized character drivers support by NuttX are documented in the following paragraphs.
- Device-specific
-
Examples:
drivers/dev_null.c
,drivers/fifo.c
,drivers/serial.c
, etc.
6.1.1 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 ofstruct 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);
#ifdef CONFIG_SERIAL_IFLOWCONTROL
bool rxflowcontrol(FAR struct uart_dev_s *dev, unsigned int nbuffered, bool upper);
#endif
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 callinguart_register()
, passing it thepath
where it will appear in the pseudo-file-system and it's initialized instance ofstruct uart_ops_s
. By convention, serial device drivers are registered at paths like/dev/ttyS0
,/dev/ttyS1
, etc. See theuart_register()
implementation indrivers/serial.c
. -
User Access. Serial drivers are, ultimately, normal character drivers and are accessed as other character drivers.
-
Examples:
arch/arm/src/stm32/stm32_serial.c
,arch/arm/src/lpc214x/lpc214x_serial.c
,arch/z16/src/z16f/z16f_serial.c
, etc.
6.1.1 Touchscreen Device Drivers
NuttX supports a two-part touchscreen driver architecture.
- An "upper half", generic driver that provides the common touchscreen interface to application level code, and
- A "lower half", platform-specific driver that implements the low-level touchscreen controls to implement the touchscreen functionality.
Files supporting the touchscreen controller (TSC) driver can be found in the following locations:
- Interface Definition. The header files for NuttX touchscreen drivers reside in the
include/nuttx/include/input
directory. The interface between the touchscreen controller "upper half" and "lower half" drivers are not common, but vary from controller-to-controller. Because of this, each touchscreen driver has its own unique header file that describes the "upper half"/"lower half" interface in that directory. The application level interface to each touchscreen driver, on the other hand, is the same for each touchscreen driver and is describedinclude/nuttx/include/input/touchscreen.h
. The touchscreen driver uses a standard character driver framework but read operations return specially formatted data. - "Upper Half" Driver. The controller-specific, "upper half" touchscreen drivers reside in the directory
drivers/input
. - "Lower Half" Drivers. Platform-specific touchscreen drivers reside in either: (1) The
arch/
<architecture>/src/
<hardware> directory for the processor architectures that have build in touchscreen controllers or (2) theboards/
<arch>/
<chip>/
<board>/src/
directory for boards that use an external touchscreen controller chip.
6.1.2 Analog (ADC/DAC) Drivers
The NuttX analog drivers are split into two parts:
- An "upper half", generic driver that provides the common analog interface to application level code, and
- A "lower half", platform-specific driver that implements the low-level controls to implement the analog 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/
<hardware> directory for the specific processor <architecture> and for the specific <chip> analog peripheral devices.
6.1.3.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:- Structures and interface descriptions needed to develop a low-level, architecture-specific, ADC driver.
- To register the ADC driver with a common ADC character driver.
- 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.1.3.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:- Structures and interface descriptions needed to develop a low-level, architecture-specific, DAC driver.
- To register the DAC driver with a common DAC character driver.
- 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.1.4 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:
- An "upper half", generic driver that provides the common PWM interface to application level code, and
- 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/timers/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/
<hardware> directory for the specific processor <architecture> and for the specific <chip> PWM peripheral devices.
6.1.5 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:
- An "upper half", generic driver that provides the common CAN interface to application level code, and
- 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 resides at
include/nuttx/can/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/
<hardware> directory for the specific processor <architecture> and for the specific <chip> CAN peripheral devices.
Usage Note: When reading from the CAN driver multiple messages may be returned, depending on (1) the size the returned can messages, and (2) the size of the buffer provided to receive CAN messages. Never assume that a single message will be returned... if you do this, you will lose CAN data under conditions where your read buffer can hold more than one small message. Below is an example about how you should think of the CAN read operation:
#define BUFLEN 128 /* Arbitrary size of the CAN RX buffer */ FAR struct can_msg_s *msg; char rxbuffer[BUFLEN]; ssize_t nread; int nbytes; int msglen int i; /* Read messages into the RX buffer */ nread = read(fd, rxbuffer, BUFLEN); /* Check for read errors */ ... /* Process each message in the RX buffer */ for (i = 0; i <= nread - CAN_MSGLEN(0); i += msglen) { /* Get the next message from the RX buffer */ msg = (FAR struct can_msg_s *)&rxbuffer[i]; nbytes = can_dlc2bytes(msg->cm_hdr.ch_dlc); msglen = CAN_MSGLEN(nbytes); DEBUGASSERT(i + msglen < BUFLEN); /* Process the next CAN message */ ... }
6.1.6 Quadrature Encoder Drivers
NuttX supports a low-level, two-part Quadrature Encoder driver.
- An "upper half", generic driver that provides the common Quadrature Encoder interface to application level code, and
- 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/
<hardware> directory for the specific processor <architecture> and for the specific <chip> Quadrature Encoder peripheral devices.
6.1.7 Timer Drivers
NuttX supports a low-level, two-part timer driver.
- An "upper half", generic driver that provides the common timer interface to application level code, and
- A "lower half", platform-specific driver that implements the low-level timer controls to implement the timer functionality.
Files supporting the timer driver can be found in the following locations:
- Interface Definition. The header file for the NuttX timer driver reside at
include/nuttx/timers/timer.h
. This header file includes both the application level interface to the timer driver as well as the interface between the "upper half" and "lower half" drivers. The timer driver uses a standard character driver framework. - "Upper Half" Driver. The generic, "upper half" timer driver resides at
drivers/timers/timer.c
. - "Lower Half" Drivers. Platform-specific timer drivers reside in
arch/
<architecture>/src/
<hardware> directory for the specific processor <architecture> and for the specific <chip> timer peripheral devices.
6.1.8 RTC Drivers
NuttX supports a low-level, two-part RealTime Clock (RTC) driver.
- An "upper half", generic driver that provides the common RTC interface to application level code, and
- A "lower half", platform-specific driver that implements the low-level timer controls to implement the RTC functionality.
Files supporting the RTC driver can be found in the following locations:
- Interface Definition. The header file for the NuttX RTC driver reside at
include/nuttx/timers/rtc.h
. This header file includes both the application level interface to the RTC driver as well as the interface between the "upper half" and "lower half" drivers. The RTC driver uses a standard character driver framework. - "Upper Half" Driver. The generic, "upper half" RTC driver resides at
drivers/timers/rtc.c
. - "Lower Half" Drivers. Platform-specific RTC drivers reside in
arch/
<architecture>/src/
<hardware> directory for the specific processor <architecture> and for the specific <chip> RTC peripheral devices.
6.1.9 Watchdog Timer Drivers
NuttX supports a low-level, two-part watchdog timer driver.
- An "upper half", generic driver that provides the common watchdog timer interface to application level code, and
- A "lower half", platform-specific driver that implements the low-level timer controls to implement the watchdog timer functionality.
Files supporting the watchdog timer driver can be found in the following locations:
- Interface Definition. The header file for the NuttX watchdog timer driver reside at
include/nuttx/timers/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/timers/watchdog.c
. - "Lower Half" Drivers. Platform-specific watchdog timer drivers reside in
arch/
<architecture>/src/
<hardware> directory for the specific processor <architecture> and for the specific <chip> watchdog timer peripheral devices.
6.1.10 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 punctuation) 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.
-
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 Parameters:
-
ch
: The character to be added to the output stream. -
stream
: An instance oflib_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 Parameters:
-
ch
: The character associated with the key that was released. -
stream
: An instance oflib_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 Parameters:
-
keycode
: The command to be added to the output stream. The enumerationenum kbd_keycode_e keycode
identifies all commands known to the system. -
stream
: An instance oflib_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 Parameters:
-
keycode
: The command to be added to the output stream. The enumerationenum kbd_keycode_e keycode
identifies all commands known to the system. -
stream
: An instance oflib_outstream_s
to perform the actual low-level put operation.
Returned Value:
- None.
-
-
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 Parameters:
-
stream
: An instance oflib_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 fromenum kbd_getstate_s
. -
state
: A user provided buffer to support parsing. This structure should be cleared the first time thatkbd_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 inpch
is a simple byte of text or control data. -
KBD_RELEASE
(1): Indicates a key release event. The returned value inpch
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 inpch
is a value fromenum kbd_getstate_s
. -
KBD_SPECREL
(3): Indicates a special command key release event. The returned value inpch
is a value fromenum kbd_getstate_s
. -
KBD_ERROR
(EOF
): An error has getting the next character (reported by thestream
). 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.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 ofstruct 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 callingregister_blockdriver()
, passing it thepath
where it will appear in the pseudo-file-system and it's initialized instance ofstruct block_operations
. -
User Access. Users do not normally access block drivers directly, rather, they access block drivers indirectly through the
mount()
API. Themount()
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 thecmd_mount()
implementation inapps/nshlib/nsh_fscmds.c
. -
Accessing a Character Driver as a Block Device. See the loop device at
drivers/loop.c
. Example: See thecmd_losetup()
implementation inapps/nshlib/nsh_fscmds.c
. -
Accessing a Block Driver as Character Device. See the Block-to-Character (BCH) conversion logic in
drivers/bch/
. Example: See thecmd_dd()
implementation inapps/nshlib/nsh_ddcmd.c
. -
Examples.
drivers/loop.c
,drivers/mmcsd/mmcsd_spi.c
,drivers/ramdisk.c
, etc.
6.3 Specialized Device Drivers
All device drivers that are accessible to application logic are either: (1) Character device drivers that can be accessed via the standard driver operations (open()
, close()
, read()
, write()
, etc.), or (2) block drivers that can be accessing only as part of mounting a file system or other special use cases as described in the preceding paragraph.
In addition to this, there are also specialized "drivers" that can be used only within the OS logic itself and are not accessible to application logic. These specialized drivers are discussed in the following paragraphs.
6.3.1 Ethernet Device Drivers
-
include/nuttx/net/netdev.h
. All structures and APIs needed to work with Ethernet drivers are provided in this header file. The structurestruct net_driver_s
defines the interface and is passed to the network vianetdev_register()
. -
int netdev_register(FAR struct net_driver_s *dev, enum net_lltype_e lltype);
. Each Ethernet driver registers itself by callingnetdev_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 ofstruct 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, uint32_t 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, uint32_t devid);
uint32_t send(FAR struct spi_dev_s *dev, uint32_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)
indrivers/mmcsd/mmcsd_spi.c
. In general, the binding sequence is:- Get an instance of
struct spi_dev_s
from the hardware-specific SPI device driver, and - Provide that instance to the initialization method of the higher level device driver.
- Get an instance of
-
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 ofstruct i2c_ops_s
. That structure defines a call table with the following methods:int transfer(FAR struct i2c_master_s *dev, FAR struct i2c_msg_s *msgs, int count);
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:
- Get an instance of
struct i2c_master_s
from the hardware-specific I2C device driver, and - 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 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 ofstruct 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:
- Get an instance of
struct fb_vtable_s
from the hardware-specific frame buffer device driver, and - Provide that instance to the initialization method of the higher level device driver.
- Get an instance of
-
Examples:
arch/sim/src/up_framebuffer.c
. See also the usage of the frame buffer driver in thegraphics/
directory.
6.3.5 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 provided ininclude/nuttx/video/fb.h
. -
struct lcd_dev_s
. Each LCD device driver must implement an instance ofstruct 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:
- Get an instance of
struct lcd_dev_s
from the hardware-specific LCD device driver, and - Provide that instance to the initialization method of the higher level device driver.
- Get an instance of
-
Examples:
drivers/lcd/p14201.c
,boards/arm/sam34/sam3u-ek/src/up_lcd.c.
See also the usage of the LCD driver in thegraphics/
directory.
6.3.6 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 ofstruct 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 geometryMTDIOC_XIPBASE:
: Convert block to physical address for eXecute-In-PlaceMTDIOC_BULKERASE
: Erase the entire device
is provided via a single
ioctl
method (seeinclude/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:
- Get an instance of
struct mtd_dev_s
from the hardware-specific MTD device driver, and - Provide that instance to the initialization method of the higher level device driver.
- Get an instance of
-
Examples:
drivers/mtd/m25px.c
anddrivers/mtd/ftl.c
6.3.7 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 SDIO device driver must implement an instance ofstruct 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);
sdio_capset_t (*capabilities)(FAR struct sdio_dev_s *dev);
sdio_statset_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 (*recv_r1)(FAR struct sdio_dev_s *dev, uint32_t cmd, uint32_t *R1);
int (*recv_r2)(FAR struct sdio_dev_s *dev, uint32_t cmd, uint32_t R2[4]);
int (*recv_r3)(FAR struct sdio_dev_s *dev, uint32_t cmd, uint32_t *R3);
int (*recv_r4)(FAR struct sdio_dev_s *dev, uint32_t cmd, uint32_t *R4);
int (*recv_r5)(FAR struct sdio_dev_s *dev, uint32_t cmd, uint32_t *R5);
int (*recv_r6)(FAR struct sdio_dev_s *dev, uint32_t cmd, uint32_t *R6);
int (*recv_r7)(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:
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:
- Get an instance of
struct sdio_dev_s
from the hardware-specific SDIO device driver, and - Provide that instance to the initialization method of the higher level device driver.
- Get an instance of
-
Examples:
arch/arm/src/stm32/stm32_sdio.c
anddrivers/mmcsd/mmcsd_sdio.c
6.3.8 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
andstruct usbhost_connection_s
. Each USB host controller driver must implement an instance ofstruct usbhost_driver_s
andstruct 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 logic. These structures are defined ininclude/nuttx/usb/usbhost.h
.Examples:
arch/arm/src/lpc17xx_40xx/lpc17_40_usbhost.c
,arch/arm/src/stm32/stm32_otgfshost.c
,arch/arm/src/sama5/sam_ohci.c
, andarch/arm/src/sama5/sam_ehci.c
. -
struct usbhost_class_s
. Each USB host class driver must implement an instance ofstruct usbhost_class_s
. This structure is also defined ininclude/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 registry. 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
, anddrivers/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 thecreate()
method on thestruct usbhost_registry_s interface
to get a class instance, and finally (5) call theconnect()
method of thestruct 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:-
Each USB host class driver includes an initialization 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_msc_initialize()
in the filedrivers/usbhost/usbhost_storage.c
-
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'senumerate
method to bind the registered USB host class driver to the USB host controller driver.Examples: The function
nsh_waiter()
in the fileboards/arm/lpc17xx_40xx/olimex-lpc1766stk/src/lpc17_40_appinit.c
. -
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 functionusbhost_initvolume()
in the filedrivers/usbhost/usbhost_storage.c
.
-
6.3.9 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 ofstruct usbdev_s
. This structure is defined ininclude/nuttx/usb/usbdev.h
.Examples:
arch/arm/src/dm320/dm320_usbdev.c
,arch/arm/src/lpc17xx_40xx/lpc17_40_usbdev.c
,arch/arm/src/lpc214x/lpc214x_usbdev.c
,arch/arm/src/lpc313x/lpc313x_usbdev.c
, andarch/arm/src/stm32/stm32_usbdev.c
. -
struct usbdevclass_driver_s
. Each USB device class driver must implement an instance ofstruct usbdevclass_driver_s
. This structure is also defined ininclude/nuttx/usb/usbdev.h
.Examples:
drivers/usbdev/pl2303.c
anddrivers/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:
-
Each USB device class driver includes an initialization entry point that is called from the application at initialization time.
Examples: The function
usbdev_serialinitialize()
in the filedrivers/usbdev/pl2303.c
and the functionin the file
drivers/usbdev/usbmsc.c
-
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.4 SYSLOG
6.4.1 SYSLOG Interfaces
6.4.1.1 Standard SYSLOG Interfaces
The NuttX SYSLOG is an architecture for getting debug and status information from the system. The syslogging interfaces are defined in the header fileinclude/syslog.h
. The primary interface to SYSLOG sub-system is the function syslog()
and, to a lesser extent, its companion vsyslog()
: 6.4.1.2 syslog()
and vsyslog()
Function Prototypes:
#include <syslog.h> int syslog(int priority, FAR const IPTR char *format, ...); void vsyslog(int priority, FAR const IPTR char *src, va_list ap);
Description: syslog()
generates a log message. The priority argument is formed by ORing the facility and the level values (see include/syslog.h
). The remaining arguments are a format, as in printf()
and any arguments to the format.
The NuttX implementation does not support any special formatting characters beyond those supported by printf()
.
The function vsyslog()
performs the same task as syslog()
with the difference that it takes a set of arguments which have been obtained using the stdarg
variable argument list macros.
6.4.1.3 setlogmask()
The additional setlogmask()
interface can use use to filter SYSLOG output:
Function Prototype:
#include <syslog.h> int setlogmask(int mask);
Description: The setlogmask()
function sets the logmask and returns the previous mask. If the mask argument is zerio, the current logmask is not modified.
The SYSLOG priorities are: LOG_EMERG
, LOG_ALERT
, LOG_CRIT
, LOG_ERR
, LOG_WARNING
, LOG_NOTICE
, LOG_INFO
, and LOG_DEBUG
. The bit corresponding to a priority p
is LOG_MASK(p)
; LOG_UPTO(p)
provides the mask of all priorities in the above list up to and including p
.
Per OpenGroup.org "If the maskpri argument is 0, the current log mask is not modified." In this implementation, the value zero is permitted in order to disable all SYSLOG levels.
REVISIT: Per POSIX the SYSLOG mask should be a per-process value but in NuttX, the scope of the mask is dependent on the nature of the build:
-
Flat Build: There is one, global SYSLOG mask that controls all output.
-
Protected Build: There are two SYSLOG masks. One within the kernel that controls only kernel output. And one in user-space that controls only user SYSLOG output.
-
Kernel Build: The kernel build is compliant with the POSIX requirement: There will be one mask for for each user process, controlling the SYSLOG output only form that process. There will be a separate mask accessible only in the kernel code to control kernel SYSLOG output.
The above are all standard interfaces as defined at OpenGroup.org. Those interfaces are available for use by application software. The remaining interfaces discussed in this section are non-standard, OS-internal interfaces.
6.4.1.4 Debug Interfaces
In NuttX, syslog output is really synonymous to debug output and, therefore, the debugging interface macros defined in the header file include/debug.h
are also syslogging interfaces. Those macros are simply wrappers around syslog()
. The debugging interfaces differ from the syslog interfaces in that:
-
They do not take a priority parameter; the priority is inherent in the debug macro name.
-
They decorate the output stream with information such as the file name
-
They can each be disabled via configuration options.
Each debug macro has a base name that represents the priority and a prefix that represents the sub-system. Each macro is individually initialized by both priority and sub-system. For example, uerr()
is the macro used for error level messages from the USB subsystem and is enabled with CONFIG_DEBUG_USB_ERROR
.
The base debug macro names, their priority, and configuration variable are summarized below:
-
info()
. Theinfo()
macro is the lowest priority (LOG_INFO
) and is intended to provide general information about the flow of program execution so that you can get an overview of the behavior of the program.info()
is often very chatty and voluminous and usually more information than you may want to see. Theinfo()
macro is controlled via CONFIG_DEBUG_subsystem_INFO -
warn()
. Thewarn()
macro has medium priority (LOG_WARN
) and is controlled byCONFIG_DEBUG_subsystem_WARN
. Thewarn()
is intended to note exceptional or unexpected conditions that might be potential errors or, perhaps, minor errors that easily recovered. -
err()
. This is a high priority debug macro (LOG_ERROR
) and controlled byCONFIG_DEBUG_subsystem_ERROR
. Theerr()
is reserved to indicate important error conditions. -
alert()
. The highest priority debug macro (LOG_EMERG
) and is controlled byCONFIG_DEBUG_ALERT
. Thealert()
macro is reserved for use solely by assertion and crash handling logic. It also differs from the other macros in that it cannot be enabled or disabled per subsystem.
6.4.2 SYSLOG Channels
6.4.2.1 SYSLOG Channel Interfaces
In the NuttX SYSLOG implementation, the underlying device logic the supports the SYSLOG output is referred to as a SYSLOG channel. Each SYSLOG channel is represented by an interface defined in include/nuttx/syslog/syslog.h
:
/* This structure provides the interface to a SYSLOG device */ typedef CODE int (*syslog_putc_t)(int ch); typedef CODE int (*syslog_flush_t)(void); struct syslog_channel_s { /* I/O redirection methods */ syslog_putc_t sc_putc; /* Normal buffered output */ syslog_putc_t sc_force; /* Low-level output for interrupt handlers */ syslog_flush_t sc_flush; /* Flush buffered output (on crash) */ /* Implementation specific logic may follow */ };
The channel interface is instantiated by calling syslog_channel()
:
6.4.2.1 syslog_channel()
Function Prototype:
#include <nuttx/syslog/syslog.h> int syslog_channel(FAR const struct syslog_channel_s *channel);
Description: Configure the SYSLOG function to use the provided channel to generate SYSLOG output.
syslog_channel()
is a non-standard, internal OS interface and is not available to applications. It may be called numerous times as necessary to change channel interfaces. By default, all system log output goes to console (/dev/console
).
Input Parameters:
-
channel
: Describes the interface to the channel to be used.
Returned Value:
Zero (OK
)is returned on success. A negated errno
value is returned on any failure.
6.4.2.2 SYSLOG Channel Initialization
The initial, default SYSLOG channel is established with statically initialized global variables so that some level of SYSLOG output may be available immediately upon reset. This initialized data is in the file drivers/syslog/syslog_channel.c
. The initial SYSLOG capability is determined by the selected SYSLOG channel:
-
In-Memory Buffer (RAMLOG). Full SYSLOG capability as available at reset.
-
Serial Console. If the serial implementation provides the low-level character output function
up_putc()
, then that low level serial output is available as soon as the serial device has been configured. -
For all other SYSLOG channels, all SYSLOG output goes to the bit- bucket until the SYSLOG channel device has been initialized.
The syslog channel device is initialized when the bring-up logic calls syslog_initialize()
:
6.4.2.3 syslog_initialize()
Function Prototype:
#include <nuttx/syslog/syslog.h> #ifndef CONFIG_ARCH_SYSLOG int syslog_initialize(void); #else # define syslog_initialize() #endif
Description: One power up, the SYSLOG facility is non-existent or limited to very low-level output. This function is called later in the initialization sequence after full driver support has been initialized. It installs the configured SYSLOG drivers and enables full SYSLOG capability.
This function performs these basic operations:
-
Initialize the SYSLOG device
-
Call
syslog_channel()
to begin using that device. -
If
CONFIG_ARCH_SYSLOG
is selected, then the architecture-specific logic will provide its own SYSLOG device initialize which must include as a minimum a call tosyslog_channel()
to use the device.
Returned Value: Zero (OK
) is returned on success; a negated errno
value is returned on any failure.
Different types of SYSLOG devices have different OS initialization requirements. Some are available immediately at reset, some are available after some basic OS initialization, and some only after OS is fully initialized.
There are other types of SYSLOG channel devices that may require even further initialization. For example, the file SYSLOG channel (described below) cannot be initialized until the necessary file systems have been mounted.
6.4.2.3 Interrupt Level SYSLOG Output
As a general statement, SYSLOG output only supports //normal// output from NuttX tasks. However, for debugging purposes, it is also useful to get SYSLOG output from interrupt level logic. In an embedded system, that is often where the most critical operations are performed.
There are three conditions under which SYSLOG output generated from interrupt level processing can a included the SYSLOG output stream:
-
Low-Level Serial Output. If you are using a SYSLOG console channel (
CONFIG_SYSLOG_CONSOLE
) and if the underlying architecture supports the low-levelup_putc()
interface(CONFIG_ARCH_LOWPUTC
), then the SYSLOG logic will direct the output toup_putc()
which is capable of generating the serial output within the context of an interrupt handler.There are a few issues in doing this however:
-
up_putc()
is able to generate debug output in any context because it disables serial interrupts and polls the hardware directly. These polls may take many milliseconds and during that time, all interrupts are disable within the interrupt handler. This, of course, interferes with the real-time behavior of the RTOS. -
The output generated by
up_putc()
is immediate and in real-time. The normal SYSLOG output, on the other hand, is buffered in the serial driver and may be delayed with respect to the immediate output by many lines. Therefore, the interrupt level SYSLOG output provided throughup_putc()
is grossly out of synchronization with other debug output
-
-
In-Memory Buffering. If the RAMLOG SYSLOG channel is supported, then all SYSLOG output is buffered in memory. Interrupt level SYSLOG output is no different than normal SYSLOG output in this case.
-
Serialization Buffer. A final option is the use of an interrupt buffer to buffer the interrupt level SYSLOG output. In this case:
-
SYSLOG output generated from interrupt level process in not sent to the SYSLOG channel immediately. Rather, it is buffered in the interrupt serialization buffer.
-
Later, when the next normal syslog output is generated, it will first empty the content of the interrupt buffer to the SYSLOG device in the proper context. It will then be followed by the normal syslog output. In this case, the interrupt level SYSLOG output will interrupt the normal output stream and the interrupt level SYSLOG output will be inserted into the correct position in the SYSLOG output when the next normal SYSLOG output is generated.
The SYSLOG interrupt buffer is enabled with
CONFIG_SYSLOG_INTBUFFER
. When the interrupt buffer is enabled, you must also provide the size of the interrupt buffer withCONFIG_SYSLOG_INTBUFSIZE
. -
6.4.3 SYSLOG Channel Options
6.4.3.1 SYSLOG Console Device
The typical SYSLOG device is the system console. If you are using a serial console, for example, then the SYSLOG output will appear on that serial port.
This SYSLOG channel is automatically selected by syslog_initialize()
in the LATE initialization phase based on configuration options. The configuration options that affect this channel selection include:
-
CONFIG_DEV_CONSOLE
. This setting indicates that the system supports a console device, i.e., that the character device/dev/console
exists. -
CONFIG_SERIAL_CONSOLE
. This configuration option is automatically selected when a UART or USART is configured as the system console. There is no user selection. -
CONFIG_SYSLOG_CONSOLE
. This configuration option is manually selected from the SYSLOG menu. This is the option that actually enables the SYSLOG console device. It depends onCONFIG_DEV_CONSOLE
. -
CONFIG_ARCH_LOWPUTC
. This is an indication from the architecture configuration that the platform supports theup_putc()
interface.up_putc()
is a very low level UART interface that can even be used from interrupt handling.
Interrupt level SYSLOG output will be lost unless: (1) the interrupt buffer is enabled to support serialization, or (2) a serial console is used and up_putc()
is supported.
NOTE: The console channel uses the fixed character device at /dev/console
. The console channel is not synonymous with stdout
(or file descriptor 1). stdout
is the current output from a task when, say, printf()
if used. Initially, stdout
does, indeed, use the /dev/console
device. However, stdout
may subsequently be redirected to some other device or file. This is always the case, for example, when a transient device is used for a console -- such as a USB console or a Telnet console. The SYSLOG channel is not redirected as stdout
is; the SYSLOG channel will stayed fixed (unless it is explicitly changed via syslog_channel()
).
References: drivers/syslog/syslog_consolechannel.c
and drivers/syslog/syslog_device.c
6.4.3.2 SYSLOG Character Device
The system console device, /dev/console
, is a character driver with some special properties. However, any character driver may be used as the SYSLOG output channel. For example, suppose you have a serial console on /dev/ttyS0
and you want SYSLOG output on /dev/ttyS1
. Or suppose you support only a Telnet console but want to capture debug output /dev/ttyS0
.
This SYSLOG device channel is selected with CONFIG_SYSLOG_CHAR
and has no other dependencies. Differences from the SYSLOG console channel include:
-
CONFIG_SYSLOG_DEVPATH
. This configuration option string must be set provide the full path to the character device to be used. -
The forced SYSLOG output always goes to the bit-bucket. This means that interrupt level SYSLOG output will be lost unless the interrupt buffer is enabled to support serialization.
-
CONFIG_SYSLOG_CHAR_CRLF
. IfCONFIG_SYSLOG_CHAR_CRLF
is selected, then linefeeds in the SYSLOG output will be expanded to Carriage Return plus Linefeed. Since the character device is not a console device, the addition of carriage returns to line feeds would not be performed otherwise. You would probably want this expansion if you use a serial terminal program with the character device output.
References: drivers/syslog/syslog_devchannel.c
and drivers/syslog/syslog_device.c
6.4.3.3 SYSLOG File Device
Files can also be used as the sink for SYSLOG output. There is, however, a very fundamental difference in using a file as opposed the system console, a RAM buffer, or character device: You must first mount the file system that supports the SYSLOG file. That difference means that the file SYSLOG channel cannot be supported during the boot-up phase but can be instantiated later when board level logic configures the application environment, including mounting of the file systems.
The interface syslog_file_channel()
is used to configure the SYSLOG file channel:
6.4.3.4 syslog_file_channel()
Function Prototype:
#include <nuttx/syslog/syslog.h> #ifdef CONFIG_SYSLOG_FILE int syslog_file_channel(FAR const char *devpath); #endif
Description: Configure to use a file in a mounted file system at devpath
as the SYSLOG channel.
This tiny function is simply a wrapper around syslog_dev_initialize()
and syslog_channel()
. It calls syslog_dev_initialize()
to configure the character file at devpath
then calls syslog_channel()
to use that device as the SYSLOG output channel.
File SYSLOG channels differ from other SYSLOG channels in that they cannot be established until after fully booting and mounting the target file system. This function would need to be called from board-specific bring-up logic AFTER mounting the file system containing devpath
.
SYSLOG data generated prior to calling syslog_file_channel()
will, of course, not be included in the file.
NOTE interrupt level SYSLOG output will be lost in this case unless the interrupt buffer is used.
Input Parameters:
-
devpath
: The full path to the file to be used for SYSLOG output. This may be an existing file or not. If the file exists,syslog_file_channel()
will append new SYSLOG data to the end of the file. If it does not, thensyslog_file_channel()
will create the file.
Returned Value: Zero (OK
) is returned on success; a negated errno
value is returned on any failure.
References: drivers/syslog/syslog_filechannel.c
, drivers/syslog/syslog_device.c
, and include/nuttx/syslog/syslog.h
.
6.4.3.5 SYSLOG RAMLOG Device
The RAMLOG is a standalone feature that can be used to buffer any character data in memory. There are, however, special configurations that can be used to configure the RAMLOG as a SYSLOG channel. The RAMLOG functionality is described in a more general way in the following paragraphs.
6.4.4 RAM Logging Device
The RAM logging driver is a driver that was intended to support debugging output (SYSLOG) when the normal serial output is not available. For example, if you are using a Telnet or USB serial console, the debug output will get lost -- or worse. For example, what if you want to debug the network over Telnet?The RAM logging driver can also accept debug output data from interrupt handler with no special serialization buffering. As an added benefit, the RAM logging driver is much less invasive. Since no actual I/O is performed with the debug output is generated, the RAM logger tends to be much faster and will interfere much less when used with time critical drivers.
The RAM logging driver is similar to a pipe in that it saves the debugging output in a circular buffer in RAM. It differs from a pipe in numerous details as needed to support logging.
This driver is built when CONFIG_RAMLOG
is defined in the Nuttx configuration.
6.4.4.1 dmesg
When the RAMLOG (with SYSLOG) is enabled, a new NuttShell (NSH) command will appear: dmesg
. The dmesg
command will dump the contents of the circular buffer to the console (and also clear the circular buffer).
6.4.4.2 RAMLOG Configuration options
-
CONFIG_RAMLOG
: Enables the RAM logging feature -
CONFIG_RAMLOG_SYSLOG
: Use the RAM logging device for the SYSLOG interface. If this feature is enabled, then all debug output will be re-directed to the circular buffer in RAM. This RAM log can be viewed from NSH using thedmesg
command. NOTE: Unlike the limited, generic character driver SYSLOG device, the RAMLOG can be used to capture debug output from interrupt level handlers. -
CONFIG_RAMLOG_NPOLLWAITERS
: The number of threads than can be waiting for this driver onpoll()
. Default: 4
-
CONFIG_RAMLOG_BUFSIZE
: The size of the circular buffer to use. Default: 1024 bytes.
Other miscellaneous settings
-
CONFIG_RAMLOG_CRLF
: Pre-pend a carriage return before every linefeed that goes into the RAM log. -
CONFIG_RAMLOG_NONBLOCKING
: Reading from the RAMLOG will never block if the RAMLOG is empty. If the RAMLOG is empty, then zero is returned (usually interpreted as end-of-file). If you do not define this, the NSHdmesg
command will lock up when called! So you probably do want this! -
CONFIG_RAMLOG_NPOLLWAITERS
: The maximum number of threads that may be waiting on the poll method.
6.5 Power Management
6.5.1 Overview
Power Management (PM) Sub-System. NuttX supports a simple power management (PM) sub-system. This sub-system:
-
Monitors activity from drivers (and from other parts of the system), 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.
Low Power Consumption 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 some that 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
.
Power Management Domains. Each PM interfaces includes a integer domain number. By default, only a single power domain is supported (CONFIG_PM_NDOMAINS=1
). But that is configurable; any number of PM domains can be supported. Multiple PM domains might be useful, for example, if you would want to control power states associated with a network separately from power states associated with a user interface.
6.5.2 Interfaces
All PM interfaces are declared in the file include/nuttx/power/pm.h
.
6.5.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 initialization sequence before any other device drivers are initialized (since they may attempt to register with the power management subsystem).
Input Parameters: None
Returned Value: None
6.5.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 negated errno
value is returned.
6.5.2.3 pm_unregister()
Function Prototype:
#include <nuttx/power/pm.h> int pm_unregister(FAR struct pm_callback_s *callbacks);
Description: This function is called by a device driver in order to unregister previously registered 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 negated errno
value is returned.
6.5.2.4 pm_activity()
Function Prototype:
#include <nuttx/power/pm.h> void pm_activity(int domain, int priority);
Description: This function is called by a device driver to indicate that it is performing meaningful activities (non-idle). This increment an activity count and/or will restart a idle timer and prevent entering reduced power states.
Input Parameters:
domain
- Identifies the domain of the new PM activity
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.5.2.5 pm_checkstate()
Function Prototype:
#include <nuttx/power/pm.h> enum pm_state_e pm_checkstate(int domain);
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:
domain
- Identifies the PM domain to check
Returned Value: The recommended power management state.
6.5.2.6 pm_changestate()
Function Prototype:
#include <nuttx/power/pm.h> int pm_changestate(int domain, 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:
domain
- Identifies the domain of the new PM state
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.5.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.5.3.1 prepare()
Function Prototype:
int (*prepare)(FAR struct pm_callback_s *cb, int domain, 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 structure may include additional, driver-specific state data at the end of the structure.
domain
- Identifies the activity domain of the state change
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.5.3.1 notify()
Function Prototype:
#include <nuttx/power/pm.h> void (*notify)(FAR struct pm_callback_s *cb, int domain, 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 structure may include additional, driver-specific state data at the end of the structure.
domain
- Identifies the activity domain of the state change
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 |
NOTE: NuttX is not licensed to use the POSIX trademark. NuttX uses the POSIX standard as a development guideline only.