text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```restructuredtext .. _haptics_api: Haptics ####### Overview ******** The haptics API allows for the control of haptic driver devices for the purposes of performing haptic feedback events. During a haptic feedback event the haptic device drives a signal to an actuator. The source of the haptic event signal varies depending on the capabilities of the haptic device. Some examples of haptic signal sources are analog signals, preprogrammed (ROM) wavetables, synthesized (RAM) wavetables, and digital audio streams. Additionally, haptic driver devices often offer controls for adjusting and tuning the drive signal to meet the electrical requirements of their respective actuators. API Reference ************* .. doxygengroup:: haptics_interface ```
/content/code_sandbox/doc/hardware/peripherals/haptics.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
166
```restructuredtext .. _dac_api: Digital-to-Analog Converter (DAC) ################################# Overview ******** The DAC API provides access to Digital-to-Analog Converter (DAC) devices. Configuration Options ********************* Related configuration options: * :kconfig:option:`CONFIG_DAC` API Reference ************* .. doxygengroup:: dac_interface ```
/content/code_sandbox/doc/hardware/peripherals/dac.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
70
```restructuredtext .. _mbox_api: Multi-Channel Inter-Processor Mailbox (MBOX) ############################################ Overview ******** An MBOX device is a peripheral capable of passing signals (and data depending on the peripheral) between CPUs and clusters in the system. Each MBOX instance is providing one or more channels, each one targeting one other CPU cluster (multiple channels can target the same cluster). API Reference ************* .. doxygengroup:: mbox_interface ```
/content/code_sandbox/doc/hardware/peripherals/mbox.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
98
```restructuredtext .. _spi_api: Serial Peripheral Interface (SPI) Bus ##################################### Overview ******** API Reference ************* .. doxygengroup:: spi_interface ```
/content/code_sandbox/doc/hardware/peripherals/spi.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
36
```restructuredtext .. _coredump_device_api: Coredump Device ############### Overview ******** The coredump device is a pseudo-device driver with two types.A COREDUMP_TYPE_MEMCPY type exposes device tree bindings for memory address/size values to be included in any dump. And the driver exposes an API to add/remove dump memory regions at runtime. A COREDUMP_TYPE_CALLBACK device requires exactly one entry in the memory-regions array with a size of 0 and a desired size. The driver will statically allocate memory of the desired size and provide an API to register a callback function to fill that memory when a dump occurs. Configuration Options ********************* Related configuration options: * :kconfig:option:`CONFIG_COREDUMP_DEVICE` API Reference ************* .. doxygengroup:: coredump_device_interface ```
/content/code_sandbox/doc/hardware/peripherals/coredump.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
174
```restructuredtext .. _bbram_api: Battery Backed RAM (BBRAM) ########################## The BBRAM APIs allow interfacing with the unique properties of this memory region. The following common types of BBRAM properties are easily accessed via this API: - IBBR (invalid) state - check that the BBRAM is not corrupt. - VSBY (voltage standby) state - check if the BBRAM is using standby voltage. - VCC (active power) state - check if the BBRAM is on normal power. - Size - get the size (in bytes) of the BBRAM region. Along with these, the API provides a means for reading and writing to the memory region via :c:func:`bbram_read` and :c:func:`bbram_write` respectively. Both functions are expected to only succeed if the BBRAM is in a valid state and the operation is bounded to the memory region. API Reference ************* .. doxygengroup:: bbram_interface ```
/content/code_sandbox/doc/hardware/peripherals/bbram.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
217
```restructuredtext .. _mdio_api: Management Data Input/Output (MDIO) ################################### Overview ******** MDIO is a bus that is commonly used to communicate with ethernet PHY devices. Many ethernet MAC controllers also provide hardware to communicate over MDIO bus with a peripheral device. This API is intended to be used primarily by PHY drivers but can also be used by user firmware. API Reference ************* .. doxygengroup:: mdio_interface ```
/content/code_sandbox/doc/hardware/peripherals/mdio.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
94
```restructuredtext .. _sdhc_api: Secure Digital High Capacity (SDHC) ################################### The SDHC api offers a generic interface for interacting with an SD host controller device. It is used by the SD subsystem, and is not intended to be directly used by the application Basic Operation *************** SD Host Controller ================== An SD host controller is a device capable of sending SD commands to an attached SD card. These commands can be sent using the native SD protocol, or over SPI. Some SD host controllers are also capable of communicating with MMC devices. The SDHC api is designed to provide a generic way to send commands to and interact with attached SD devices. Requests ======== The core of the SDHC api is the :c:func:`sdhc_request` api. Requests contain a :c:struct:`sdhc_command` command structure, and an optional :c:struct:`sdhc_data` data structure. The caller may check the return code, or the ``response`` field of the SD command structure to determine if the SDHC request succeeded. The data structure allows the caller to specify a number of blocks to transfer, and a buffer location to read or write them from. Whether the provided buffer is used for sending or reading data depends on the command opcode provided. Host Controller I/O =================== The :c:func:`sdhc_set_io` api allows the user to change I/O settings of the SD host controller, such as clock frequency, I/O voltage, and card power. Not all controllers will support applying all I/O settings. For example, SPI mode controllers typically cannot toggle power to the SD card. Related configuration options: * :kconfig:option:`CONFIG_SDHC` API Reference ************* .. doxygengroup:: sdhc_interface ```
/content/code_sandbox/doc/hardware/peripherals/sdhc.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
376
```restructuredtext .. _i2c_eeprom_target_api: I2C EEPROM Target ################# Overview ******** API Reference ************** .. doxygengroup:: i2c_eeprom_target_api ```
/content/code_sandbox/doc/hardware/peripherals/i2c_eeprom_target.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
43
```restructuredtext .. _dma_api: Direct Memory Access (DMA) ########################## Overview ******** Direct Memory Access (Controller) is a commonly provided type of co-processor that can typically offload transferring data to and from peripherals and memory. The DMA API is not a portable API and really cannot be as each DMA has unique memory requirements, peripheral interactions, and features. The API in effect provides a union of all useful DMA functionality drivers have needed in the tree. It can still be a good abstraction, with care, for peripheral devices for vendors where the DMA IP might be very similar but have slight variances. Driver Implementation Expectations ********************************** Synchronization and Ownership +++++++++++++++++++++++++++++ From an API point of view, a DMA channel is a single-owner object, meaning the drivers should not attempt to wrap a channel with kernel synchronization primitives such as mutexes or semaphores. If DMA channels require mutating shared registers, those register updates should be wrapped in a spin lock. This enables the entire API to be low-cost and callable from any call context, including ISRs where it may be very useful to start/stop/suspend/resume/reload a channel transfer. Transfer Descriptor Memory Management +++++++++++++++++++++++++++++++++++++ Drivers should not attempt to use heap allocations of any kind. If object pools are needed for transfer descriptors then those should be setup in a way that does not break the promise of ISR-allowable calls. Many drivers choose to create a simple static descriptor array per channel with the size of the descriptor array adjustable using Kconfig. Channel State Machine Expectations ++++++++++++++++++++++++++++++++++ DMA channels should be viewed as state machines that the DMA API provides transition events for in the form of API calls. Every driver is expected to maintain its own channel state tracking. The busy state of the channel should be inspectable at any time with :c:func:`dma_get_status()`. A diagram showing those expectated possible state transitions and their API calls is provided here for reference. .. graphviz:: :caption: DMA state finite state machine digraph { node [style=rounded]; edge [fontname=Courier]; init [shape=point]; CONFIGURED [label=Configured,shape=box]; RUNNING [label=Running,shape=box]; SUSPENDED [label=Suspended,shape=box]; init -> CONFIGURED [label=dma_config]; CONFIGURED -> RUNNING [label=dma_start]; CONFIGURED -> CONFIGURED [label=dma_stop]; RUNNING -> CONFIGURED [label=dma_stop]; RUNNING -> RUNNING [label=dma_start]; RUNNING -> RUNNING [label=dma_resume, headport=w]; RUNNING -> SUSPENDED [label=dma_suspend]; SUSPENDED -> SUSPENDED [label=dma_suspend]; SUSPENDED -> RUNNING [label=dma_resume]; SUSPENDED -> CONFIGURED [label=dma_stop]; } API Reference ************* .. doxygengroup:: dma_interface ```
/content/code_sandbox/doc/hardware/peripherals/dma.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
625
```restructuredtext .. _can_transceiver_api: CAN Transceiver ############### .. contents:: :local: :depth: 2 Overview ******** A CAN transceiver is an external device that converts the logic level signals from the CAN controller to the bus-levels. The bus lines are called CAN High (CAN H) and CAN Low (CAN L). The transmit wire from the controller to the transceiver is called CAN TX, and the receive wire is called CAN RX. These wires use the logic levels whereas the bus-level is interpreted differentially between CAN H and CAN L. The bus can be either in the recessive (logical one) or dominant (logical zero) state. The recessive state is when both lines, CAN H and CAN L, are roughly at the same voltage level. This state is also the idle state. To write a dominant bit to the bus, open-drain transistors tie CAN H to Vdd and CAN L to ground. The first and last node use a 120-ohm resistor between CAN H and CAN L to terminate the bus. The dominant state always overrides the recessive state. This structure is called a wired-AND. .. image:: transceiver.svg :width: 70% :align: center :alt: CAN Transceiver CAN Transceiver API Reference ***************************** .. doxygengroup:: can_transceiver ```
/content/code_sandbox/doc/hardware/peripherals/can/transceiver.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
295
```restructuredtext .. _can: Controller Area Network (CAN) ############################# .. toctree:: :maxdepth: 2 controller.rst transceiver.rst shell.rst ```
/content/code_sandbox/doc/hardware/peripherals/can/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
42
```restructuredtext .. _can_shell: CAN Shell ######### .. contents:: :local: :depth: 1 Overview ******** The CAN shell provides a ``can`` command with a set of subcommands for the :ref:`shell <shell_api>` module. It allows for testing and exploring the :ref:`can_api` driver API through an interactive interface without having to write a dedicated application. The CAN shell can also be enabled in existing applications to aid in interactive debugging of CAN issues. The CAN shell provides access to most CAN controller features, including inspection, configuration, sending and receiving of CAN frames, and bus recovery. In order to enable the CAN shell, the following :ref:`Kconfig <kconfig>` options must be enabled: * :kconfig:option:`CONFIG_SHELL` * :kconfig:option:`CONFIG_CAN` * :kconfig:option:`CONFIG_CAN_SHELL` The following :ref:`Kconfig <kconfig>` options enable additional subcommands and features of the ``can`` command: * :kconfig:option:`CONFIG_CAN_FD_MODE` enables CAN FD specific subcommands (e.g. for setting the timing for the CAN FD data phase). * :kconfig:option:`CONFIG_CAN_RX_TIMESTAMP` enables printing of timestamps for received CAN frames. * :kconfig:option:`CONFIG_CAN_STATS` enables printing of various statistics for the CAN controller in the ``can show`` subcommand. This depends on :kconfig:option:`CONFIG_STATS` being enabled as well. * :kconfig:option:`CONFIG_CAN_MANUAL_RECOVERY_MODE` enables the ``can recover`` subcommand. For example, building the :ref:`hello_world` sample for the :ref:`frdm_k64f` with the CAN shell and CAN statistics enabled: .. zephyr-app-commands:: :zephyr-app: samples/hello_world :board: frdm_k64f :gen-args: -DCONFIG_SHELL=y -DCONFIG_CAN=y -DCONFIG_CAN_SHELL=y -DCONFIG_STATS=y -DCONFIG_CAN_STATS=y :goals: build See the :ref:`shell <shell_api>` documentation for general instructions on how to connect and interact with the shell. The CAN shell comes with built-in help (unless :kconfig:option:`CONFIG_SHELL_HELP` is disabled). The built-in help messages can be printed by passing ``-h`` or ``--help`` to the ``can`` command or any of its subcommands. All subcommands also support tab-completion of their arguments. .. tip:: All of the CAN shell subcommands take the name of a CAN controller as their first argument, which also supports tab-completion. A list of all devices available can be obtained using the ``device list`` shell command when :kconfig:option:`CONFIG_DEVICE_SHELL` is enabled. The examples below all use the device name ``can@0``. Inspection ********** The properties of a given CAN controller can be inspected using the ``can show`` subcommand as shown below. The properties include the core CAN clock rate, the maximum supported bitrate, the number of RX filters supported, capabilities, current mode, current state, error counters, timing limits, and more: .. code-block:: console uart:~$ can show can@0 core clock: 144000000 Hz max bitrate: 5000000 bps max std filters: 15 max ext filters: 15 capabilities: normal loopback listen-only fd mode: normal state: stopped rx errors: 0 tx errors: 0 timing: sjw 1..128, prop_seg 0..0, phase_seg1 2..256, phase_seg2 2..128, prescaler 1..512 timing data: sjw 1..16, prop_seg 0..0, phase_seg1 1..32, phase_seg2 1..16, prescaler 1..32 transceiver: passive/none statistics: bit errors: 0 bit0 errors: 0 bit1 errors: 0 stuff errors: 0 crc errors: 0 form errors: 0 ack errors: 0 rx overruns: 0 .. note:: The statistics are only printed if :kconfig:option:`CONFIG_CAN_STATS` is enabled. Configuration ************* The CAN shell allows for configuring the CAN controller mode and timing, along with starting and stopping the processing of CAN frames. .. note:: The CAN controller mode and timing can only be changed while the CAN controller is stopped, which is the initial setting upon boot-up. The initial CAN controller mode is set to ``normal`` and the initial timing is set according to the ``bitrate``, ``sample-point``, ``bitrate-data``, and ``sample-point-data`` :ref:`devicetree` properties. Timing ====== The classic CAN bitrate/CAN FD arbitration phase bitrate can be configured using the ``can bitrate`` subcommand as shown below. The bitrate is specified in bits per second. .. code-block:: console uart:~$ can bitrate can@0 125000 setting bitrate to 125000 bps If :kconfig:option:`CONFIG_CAN_FD_MODE` is enabled, the data phase bitrate can be configured using the ``can dbitrate`` subcommand as shown below. The bitrate is specified in bits per second. .. code-block:: console uart:~$ can dbitrate can@0 1000000 setting data bitrate to 1000000 bps Both of these subcommands allow specifying an optional sample point in per mille and a (Re)Synchronization Jump Width (SJW) in Time Quanta as positional arguments. Refer to the interactive help of the subcommands for more details. It is also possible to configure the raw bit timing using the ``can timing`` and ``can dtiming`` subcommands. Refer to the interactive help output for these subcommands for details on the required arguments. Mode ==== The CAN shell allows for setting the mode of the CAN controller using the ``can mode`` subcommand. An example for enabling loopback mode is shown below. .. code-block:: console uart:~$ can mode can@0 loopback setting mode 0x00000001 The subcommand accepts multiple modes given on the same command line (e.g. ``can mode can@0 fd loopback`` for setting CAN FD and loopback mode). Vendor-specific modes can be specified in hexadecimal. Starting and Stopping ===================== After the timing and mode has been configured as needed, the CAN controller can be started using the ``can start`` subcommand as shown below. This will enable reception and transmission of CAN frames. .. code-block:: console uart:~$ can start can@0 starting can@0 Prior to reconfiguring the timing or mode, the CAN controller needs to be stopped using the ``can stop`` subcommand as shown below: .. code-block:: console uart:~$ can stop can@0 stopping can@0 Receiving ********* In order to receive CAN frames, one or more CAN RX filters need to be configured. CAN RX filters are added using the ``can filter add`` subcommand as shown below. The subcommand accepts a CAN ID in hexadecimal format along with an optional CAN ID mask, also in hexadecimal format, for setting which bits in the CAN ID are to be matched. Refer to the interactive help output for this subcommand for further details on the supported arguments. .. code-block:: console uart:~$ can filter add can@0 010 adding filter with standard (11-bit) CAN ID 0x010, CAN ID mask 0x7ff, data frames 1, RTR frames 0, CAN FD frames 0 filter ID: 0 The filter ID (0 in the example above) returned is to be used when removing the CAN RX filter. Received CAN frames matching the added filter(s) are printed to the shell. A few examples are shown below: .. code-block:: console # Dev Flags ID Size Data bytes can0 -- 010 [8] 01 02 03 04 05 06 07 08 can0 B- 010 [08] 01 02 03 04 05 06 07 08 can0 BP 010 [03] 01 aa bb can0 -- 00000010 [0] can0 -- 010 [1] 20 can0 -- 010 [8] remote transmission request The columns have the following meaning: * Dev * Name of the device receiving the frame. * Flags * ``B``: The frame has the CAN FD Baud Rate Switch (BRS) flag set. * ``P``: The frame has the CAN FD Error State Indicator (ESI) flag set. The transmitting node is in error-passive state. * ``-``: Unset flag. * ID * ``010``: The standard (11-bit) CAN ID of the frame in hexadecimal format, here 10h. * ``00000010``: The extended (29-bit) CAN ID of the frame in hexadecimal format, here 10h. * Size * ``[8]``: The number of frame data bytes in decimal format, here a classic CAN frame with 8 data bytes. * ``[08]``: The number of frame data bytes in decimal format, here a CAN FD frame with 8 data bytes. * Data bytes * ``01 02 03 04 05 06 07 08``: The frame data bytes in hexadecimal format, here the numbers from 1 through 8. * ``remote transmission request``: The frame is a Remote Transmission Request (RTR) frame and thus carries no data bytes. .. tip:: If :kconfig:option:`CONFIG_CAN_RX_TIMESTAMP` is enabled, each line will be prepended with a timestamp from the free-running timestamp counter in the CAN controller. Configured CAN RX filters can be removed again using the ``can filter remove`` subcommand as shown below. The filter ID is the ID returned by the ``can filter add`` subcommand (0 in the example below). .. code-block:: console uart:~$ can filter remove can@0 0 removing filter with ID 0 Sending ******* CAN frames can be queued for transmission using the ``can send`` subcommand as shown below. The subcommand accepts a CAN ID in hexadecimal format and optionally a number of data bytes, also specified in hexadecimal. Refer to the interactive help output for this subcommand for further details on the supported arguments. .. code-block:: console uart:~$ can send can@0 010 1 2 3 4 5 6 7 8 enqueuing CAN frame #2 with standard (11-bit) CAN ID 0x010, RTR 0, CAN FD 0, BRS 0, DLC 8 CAN frame #2 successfully sent Bus Recovery ************ The ``can recover`` subcommand can be used for initiating manual recovery from a CAN bus-off event as shown below: .. code-block:: console uart:~$ can recover can@0 recovering, no timeout The subcommand accepts an optional bus recovery timeout in milliseconds. If no timeout is specified, the command will wait indefinitely for the bus recovery to succeed. .. note:: The ``recover`` subcommand is only available if :kconfig:option:`CONFIG_CAN_MANUAL_RECOVERY_MODE` is enabled. ```
/content/code_sandbox/doc/hardware/peripherals/can/shell.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,597
```c /* * */ #include <zephyr/drivers/sensor.h> #define TEMP_CHANNEL {SENSOR_CHAN_AMBIENT_TEMP, 0} const struct device *const temp0 = DEVICE_DT_GET(DT_ALIAS(temp0)); SENSOR_DT_READ_IODEV(temp_iodev, DT_ALIAS(temp0), {TEMP_CHANNEL}); RTIO_DEFINE(temp_ctx, 1, 1); int main(void) { int rc; uint8_t buf[8]; uint32_t temp_frame_iter = 0; struct sensor_q31_data temp_data = {0}; struct sensor_decode_context temp_decoder = SENSOR_DECODE_CONTEXT_INIT( SENSOR_DECODER_DT_GET(DT_ALIAS(temp0)), buf, SENSOR_CHAN_AMBIENT_TEMP, 0); while (1) { /* Blocking read */ rc = sensor_read(temp_iodev, &temp_ctx, buf, sizeof(buf)); if (rc != 0) { printk("sensor_read() failed %d\n", rc); } /* Decode the data into a single q31 */ sensor_decode(&temp_decoder, &temp_data, 1); printk("Temperature " PRIsensor_q31_data "\n", PRIsensor_q31_data_arg(temp_data, 0)); k_msleep(1); } } ```
/content/code_sandbox/doc/hardware/peripherals/sensor/temp_polling.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
271
```restructuredtext Power Management ================ Power management of sensors is often a non-trivial task as sensors may have multiple power states for various channels. Some sensors may allow for low noise, low power, or suspending channels potentially saving quite a bit of power at the cost of noise or sampling speed performance. In very low power states sensors may lose their state, turning off even the digital logic portion of the device. All this is to say that power management of sensors is typically application specific! Often the channel states are mutable using :ref:`sensor-attribute`. While total device suspending and resume can be done using the power management ref counting APIs if the device implements the necessary functionality. Most likely the API sensors should use for their fully suspended/resume power states is :ref:`pm-device-runtime` using explicit calls at an application level to :c:func:`pm_device_runtime_get` and :c:func:`pm_device_runtime_put`. In the future, with :ref:`sensor-read-and-decode` its possible that automatic management of device power management would be possible in the streaming case as the application informs the driver of usage at all times through requests to read on given events. ```
/content/code_sandbox/doc/hardware/peripherals/sensor/power_management.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
248
```restructuredtext .. _can_api: CAN Controller ############## .. contents:: :local: :depth: 2 Overview ******** Controller Area Network is a two-wire serial bus specified by the Bosch CAN Specification, Bosch CAN with Flexible Data-Rate specification and the ISO 11898-1:2003 standard. CAN is mostly known for its application in the automotive domain. However, it is also used in home and industrial automation and other products. .. warning:: CAN controllers can only initialize when the bus is in the idle (recessive) state for at least 11 recessive bits. Therefore you have to make sure that CAN RX is high, at least for a short time. This is also necessary for loopback mode. The bit-timing as defined in ISO 11898-1:2003 looks as following: .. image:: timing.svg :width: 40% :align: center :alt: CAN Timing A single bit is split into four segments. * Sync_Seg: The nodes synchronize at the edge of the Sync_Seg. It is always one time quantum in length. * Prop_Seg: The signal propagation delay of the bus and other delays of the transceiver and node. * Phase_Seg1 and Phase_Seg2 :Define the sampling point. The bit is sampled at the end of Phase_Seg1. The bit-rate is calculated from the time of a time quantum and the values defined above. A bit has the length of Sync_Seg plus Prop_Seg plus Phase_Seg1 plus Phase_Seg2 multiplied by the time of single time quantum. The bit-rate is the inverse of the length of a single bit. A bit is sampled at the sampling point. The sample point is between Phase_Seg1 and PhaseSeg2 and therefore is a parameter that the user needs to choose. The CiA recommends setting the sample point to 87.5% of the bit. The resynchronization jump width (SJW) defines the amount of time quantum the sample point can be moved. The sample point is moved when resynchronization is needed. The timing parameters (SJW, bitrate and sampling point, or bitrate, Prop_Seg, Phase_Seg1and Phase_Seg2) are initially set from the device-tree and can be changed at run-time from the timing-API. CAN uses so-called identifiers to identify the frame instead of addresses to identify a node. This identifier can either have 11-bit width (Standard or Basic Frame) or 29-bit in case of an Extended Frame. The Zephyr CAN API supports both Standard and Extended identifiers concurrently. A CAN frame starts with a dominant Start Of Frame bit. After that, the identifiers follow. This phase is called the arbitration phase. During the arbitration phase, write collisions are allowed. They resolve by the fact that dominant bits override recessive bits. Nodes monitor the bus and notice when their transmission is being overridden and in case, abort their transmission. This effectively gives lower number identifiers priority over higher number identifiers. Filters are used to whitelist identifiers that are of interest for the specific node. An identifier that doesn't match any filter is ignored. Filters can either match exactly or a specified part of the identifier. This method is called masking. As an example, a mask with 11 bits set for standard or 29 bits set for extended identifiers must match perfectly. Bits that are set to zero in the mask are ignored when matching an identifier. Most CAN controllers implement a limited number of filters in hardware. The number of filters is also limited in Kconfig to save memory. Errors may occur during transmission. In case a node detects an erroneous frame, it partially overrides the current frame with an error-frame. Error-frames can either be error passive or error active, depending on the state of the controller. In case the controller is in error active state, it sends six consecutive dominant bits, which is a violation of the stuffing rule that all nodes can detect. The sender may resend the frame right after. An initialized node can be in one of the following states: * Error-active * Error-passive * Bus-off After initialization, the node is in the error-active state. In this state, the node is allowed to send active error frames, ACK, and overload frames. Every node has a receive- and transmit-error counter. If either the receive- or the transmit-error counter exceeds 127, the node changes to error-passive state. In this state, the node is not allowed to send error-active frames anymore. If the transmit-error counter increases further to 255, the node changes to the bus-off state. In this state, the node is not allowed to send any dominant bits to the bus. Nodes in the bus-off state may recover after receiving 128 occurrences of 11 concurrent recessive bits. You can read more about CAN bus in this `CAN Wikipedia article <path_to_url`_. Zephyr supports following CAN features: * Standard and Extended Identifiers * Filters with Masking * Loopback and Silent mode * Remote Request Sending ******* The following code snippets show how to send data. This basic sample sends a CAN frame with standard identifier 0x123 and eight bytes of data. When passing NULL as the callback, as shown in this example, the send function blocks until the frame is sent and acknowledged by at least one other node or an error occurred. The timeout only takes effect on acquiring a mailbox. When a transmitting mailbox is assigned, sending cannot be canceled. .. code-block:: C struct can_frame frame = { .flags = 0, .id = 0x123, .dlc = 8, .data = {1,2,3,4,5,6,7,8} }; const struct device *const can_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_canbus)); int ret; ret = can_send(can_dev, &frame, K_MSEC(100), NULL, NULL); if (ret != 0) { LOG_ERR("Sending failed [%d]", ret); } This example shows how to send a frame with extended identifier 0x1234567 and two bytes of data. The provided callback is called when the message is sent, or an error occurred. Passing :c:macro:`K_FOREVER` to the timeout causes the function to block until a transfer mailbox is assigned to the frame or an error occurred. It does not block until the message is sent like the example above. .. code-block:: C void tx_callback(const struct device *dev, int error, void *user_data) { char *sender = (char *)user_data; if (error != 0) { LOG_ERR("Sending failed [%d]\nSender: %s\n", error, sender); } } int send_function(const struct device *can_dev) { struct can_frame frame = { .flags = CAN_FRAME_IDE, .id = 0x1234567, .dlc = 2 }; frame.data[0] = 1; frame.data[1] = 2; return can_send(can_dev, &frame, K_FOREVER, tx_callback, "Sender 1"); } Receiving ********* Frames are only received when they match a filter. The following code snippets show how to receive frames by adding filters. Here we have an example for a receiving callback as used for :c:func:`can_add_rx_filter`. The user data argument is passed when the filter is added. .. code-block:: C void rx_callback_function(const struct device *dev, struct can_frame *frame, void *user_data) { ... do something with the frame ... } The following snippet shows how to add a filter with a callback function. It is the most efficient but also the most critical way to receive messages. The callback function is called from an interrupt context, which means that the callback function should be as short as possible and must not block. Adding callback functions is not allowed from userspace context. The filter for this example is configured to match the identifier 0x123 exactly. .. code-block:: C const struct can_filter my_filter = { .flags = 0U, .id = 0x123, .mask = CAN_STD_ID_MASK }; int filter_id; const struct device *const can_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_canbus)); filter_id = can_add_rx_filter(can_dev, rx_callback_function, callback_arg, &my_filter); if (filter_id < 0) { LOG_ERR("Unable to add rx filter [%d]", filter_id); } Here an example for :c:func:`can_add_rx_filter_msgq` is shown. With this function, it is possible to receive frames synchronously. This function can be called from userspace context. The size of the message queue should be as big as the expected backlog. The filter for this example is configured to match the extended identifier 0x1234567 exactly. .. code-block:: C const struct can_filter my_filter = { .flags = CAN_FILTER_IDE, .id = 0x1234567, .mask = CAN_EXT_ID_MASK }; CAN_MSGQ_DEFINE(my_can_msgq, 2); struct can_frame rx_frame; int filter_id; const struct device *const can_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_canbus)); filter_id = can_add_rx_filter_msgq(can_dev, &my_can_msgq, &my_filter); if (filter_id < 0) { LOG_ERR("Unable to add rx msgq [%d]", filter_id); return; } while (true) { k_msgq_get(&my_can_msgq, &rx_frame, K_FOREVER); ... do something with the frame ... } :c:func:`can_remove_rx_filter` removes the given filter. .. code-block:: C can_remove_rx_filter(can_dev, filter_id); Setting the bitrate ******************* The bitrate and sampling point is initially set at runtime. To change it from the application, one can use the :c:func:`can_set_timing` API. The :c:func:`can_calc_timing` function can calculate timing from a bitrate and sampling point in permille. The following example sets the bitrate to 250k baud with the sampling point at 87.5%. .. code-block:: C struct can_timing timing; const struct device *const can_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_canbus)); int ret; ret = can_calc_timing(can_dev, &timing, 250000, 875); if (ret > 0) { LOG_INF("Sample-Point error: %d", ret); } if (ret < 0) { LOG_ERR("Failed to calc a valid timing"); return; } ret = can_stop(can_dev); if (ret != 0) { LOG_ERR("Failed to stop CAN controller"); } ret = can_set_timing(can_dev, &timing); if (ret != 0) { LOG_ERR("Failed to set timing"); } ret = can_start(can_dev); if (ret != 0) { LOG_ERR("Failed to start CAN controller"); } A similar API exists for calculating and setting the timing for the data phase for CAN FD capable controllers. See :c:func:`can_set_timing_data` and :c:func:`can_calc_timing_data`. SocketCAN ********* Zephyr additionally supports SocketCAN, a BSD socket implementation of the Zephyr CAN API. SocketCAN brings the convenience of the well-known BSD Socket API to Controller Area Networks. It is compatible with the Linux SocketCAN implementation, where many other high-level CAN projects build on top. Note that frames are routed to the network stack instead of passed directly, which adds some computation and memory overhead. Samples ******* We have two ready-to-build samples demonstrating use of the Zephyr CAN API: :zephyr:code-sample:`Zephyr CAN counter sample <can-counter>` and :zephyr:code-sample:`SocketCAN sample <socket-can>`. CAN Controller API Reference **************************** .. doxygengroup:: can_interface ```
/content/code_sandbox/doc/hardware/peripherals/can/controller.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,639
```c /* * */ #include <zephyr/drivers/sensor.h> const struct device *const accel0 = DEVICE_DT_GET(DT_ALIAS(accel0)); static struct tap_count_state { struct sensor_trigger trig; uint32_t count; } tap_count_state = { .trig = { .chan = SENSOR_CHAN_ACCEL_XYZ, .type = SENSOR_TRIG_TAP, }, .count = 0, }; void tap_handler(const struct device *dev, const struct sensor_trigger *trig) { struct tap_count_state *state = CONTAINER_OF(trig, struct tap_count_state, trig); state->count++; printk("Tap! Total Taps: %u\n", state->count); } int main(void) { int rc; printk("Tap Counter Example (%s)\n", CONFIG_ARCH); rc = sensor_trigger_set(accel0, &tap_count_state.trig, tap_handler); if (rc != 0) { printk("Failed to set trigger handler for taps, error %d\n", rc); return rc; } return rc; } ```
/content/code_sandbox/doc/hardware/peripherals/sensor/tap_count.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
225
```restructuredtext Device Tree ########### In the context of sensors device tree provides the initial hardware configuration for sensors on a per device level. Each device must specify a device tree binding in Zephyr, and ideally, a set of hardware configuration options for things such as channel power modes, data rates, filters, decimation, and scales. These can then be used in a boards devicetree to configure a sensor to its initial state. .. code-block:: dts #include <zephyr/dt-bindings/icm42688.h> &spi0 { /* SPI bus options here, not shown */ accel_gyro0: icm42688p@0 { compatible = "invensense,icm42688"; reg = <0>; int-gpios = <&pioc 6 GPIO_ACTIVE_HIGH>; /* SoC specific pin to select for interrupt line */ spi-max-frequency = <DT_FREQ_M(24)>; /* Maximum SPI bus frequency */ accel-pwr-mode = <ICM42688_ACCEL_LN>; /* Low noise mode */ accel-odr = <ICM42688_ACCEL_ODR_2000>; /* 2000 Hz sampling */ accel-fs = <ICM42688_ACCEL_FS_16>; /* 16G scale */ gyro-pwr-mode = <ICM42688_GYRO_LN>; /* Low noise mode */ gyro-odr = <ICM42688_GYRO_ODR_2000>; /* 2000 Hz sampling */ gyro-fs = <ICM42688_GYRO_FS_16>; /* 16G scale */ }; }; ```
/content/code_sandbox/doc/hardware/peripherals/sensor/device_tree.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
351
```restructuredtext .. _sensor-attribute: Sensor Attributes ################# :dfn:`Attributes`, enumerated in :c:enum:`sensor_attribute`, are immutable and mutable properties of a sensor and its channels. Attributes allow for obtaining metadata and changing configuration of a sensor. Common configuration parameters like channel scale, sampling frequency, adjusting channel offsets, signal filtering, power modes, on chip buffers, and event handling options are very common. Attributes provide a flexible API for inspecting and manipulating such device properties. Attributes are specified using :c:enum:`sensor_attribute` which can be used with :c:func:`sensor_attr_get` and :c:func:`sensor_attr_set` to get and set a sensors attributes. A quick example... .. code-block:: c const struct device *accel_dev = DEVICE_DT_GET(DT_ALIAS(accel0)); struct sensor_value accel_sample_rate; int rc; rc = sensor_attr_get(accel_dev, SENSOR_CHAN_ACCEL_XYZ, SENSOR_ATTR_SAMPLING_FREQUENCY, &accel_sample_rate); if (rc != 0) { printk("Failed to get sampling frequency\n"); } printk("Sample rate for accel %p is %d.06%d\n", accel_dev, accel_sample_rate.val1, accel_sample_rate.val2*1000000); accel_sample_rate.val1 = 2000; rc = sensor_attr_set(accel_dev, SENSOR_CHAN_ACCEL_XYZ, SENSOR_ATTR_SAMPLING_FREQUENCY, accel_sample_rate); if (rc != 0) { printk("Failed to set sampling frequency\n"); } ```
/content/code_sandbox/doc/hardware/peripherals/sensor/attributes.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
331
```restructuredtext .. _sensor: Sensors ####### The sensor driver API provides functionality to uniformly read, configure, and setup event handling for devices that take real world measurements in meaningful units. Sensors range from very simple temperature-reading devices that must be polled with a fixed scale to complex devices taking in readings from multitudes of sensors and themselves producing new inferred sensor data such as step counts, presence detection, orientation, and more. Supporting this wide breadth of devices is a demanding task and the sensor API attempts to provide a uniform interface to them. .. _sensor-using: Using Sensors ************* Using sensors from an application there are some APIs and terms that are helpful to understand. Sensors in Zephyr are composed of :ref:`sensor-channel`, :ref:`sensor-attribute`, and :ref:`sensor-trigger`. Attributes and triggers may be device or channel specific. .. note:: Getting samples from sensors using the sensor API today can be done in one of two ways. A stable and long-lived API :ref:`sensor-fetch-and-get`, or a newer but rapidly stabilizing API :ref:`sensor-read-and-decode`. It's expected that in the near future :ref:`sensor-fetch-and-get` will be deprecated in favor of :ref:`sensor-read-and-decode`. Triggers are handled entirely differently for :ref:`sensor-fetch-and-get` or :ref:`sensor-read-and-decode` and the differences are noted in each of those sections. .. toctree:: :maxdepth: 1 attributes.rst channels.rst triggers.rst power_management.rst device_tree.rst fetch_and_get.rst read_and_decode.rst .. _sensor-implementing: Implementing Sensor Drivers *************************** .. note:: Implementing the driver side of the sensor API requires an understanding how the sensor APIs are used. Please read through :ref:`sensor-using` first! Implementing Attributes ======================= * SHOULD implement attribute setting in a blocking manner. * SHOULD provide the ability to get and set channel scale if supported by the device. * SHOULD provide the ability to get and set channel sampling rate if supported by the device. Implementing Fetch and Get ========================== * SHOULD implement :c:type:`sensor_sample_fetch_t` as a blocking call that stashes the specified channels (or all sensor channels) as driver instance data. * SHOULD implement :c:type:`sensor_channel_get_t` without side effects manipulating driver state returning stashed sensor readings. * SHOULD implement :c:type:`sensor_trigger_set_t` storing the address of the :c:struct:`sensor_trigger` rather than copying the contents. This is so :c:macro:`CONTAINER_OF` may be used for trigger callback context. Implementing Read and Decode ============================ * MUST implement :c:type:`sensor_submit_t` as a non-blocking call. * SHOULD implement :c:type:`sensor_submit_t` using :ref:`rtio` to do non-blocking bus transfers if possible. * MAY implement :c:type:`sensor_submit_t` using a work queue if :ref:`rtio` is unsupported by the bus. * SHOULD implement :c:type:`sensor_submit_t` checking the :c:struct:`rtio_sqe` is of type :c:enum:`RTIO_SQE_RX` (read request). * SHOULD implement :c:type:`sensor_submit_t` checking all requested channels supported or respond with an error if not. * SHOULD implement :c:type:`sensor_submit_t` checking the provided buffer is large enough for the requested channels. * SHOULD implement :c:type:`sensor_submit_t` in a way that directly reads into the provided buffer avoiding copying of any kind, with few exceptions. * MUST implement :c:struct:`sensor_decoder_api` with pure stateless functions. All state needed to convert the raw sensor readings into fixed point SI united values must be in the provided buffer. * MUST implement :c:type:`sensor_get_decoder_t` returning the :c:struct:`sensor_decoder_api` for that device type. .. _sensor-api-reference: API Reference *************** .. doxygengroup:: sensor_interface .. doxygengroup:: sensor_emulator_backend ```
/content/code_sandbox/doc/hardware/peripherals/sensor/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
917
```restructuredtext .. _sensor-fetch-and-get: Fetch and Get ############# The stable and long existing APIs for reading sensor data and handling triggers are: * :c:func:`sensor_sample_fetch` * :c:func:`sensor_sample_fetch_chan` * :c:func:`sensor_channel_get` * :c:func:`sensor_trigger_set` These functions work together. The fetch APIs block the calling context which must be a thread until the requested :c:enum:`sensor_channel` (or all channels) has been obtained and stored into the driver instance's private data. The channel data most recently fetched can then be obtained as a :c:struct:`sensor_value` by calling :c:func:`sensor_channel_get` for each channel type. .. warning:: It should be noted that calling fetch and get from multiple contexts without a locking mechanism is undefined and most sensor drivers do not attempt to internally provide exclusive access to the device during or between these calls. Polling ******* Using fetch and get sensor can be read in a polling manner from software threads. .. literalinclude:: ../../../../samples/sensor/magn_polling/src/main.c :language: c Triggers ******** Triggers in the stable API require enabling triggers with a device specific Kconfig. The device specific Kconfig typically allows selecting the context the trigger runs. The application then needs to register a callback with a function signature matching :c:type:`sensor_trigger_handler_t` using :c:func:`sensor_trigger_set` for the specific triggers (events) to listen for. .. note:: Triggers may not be set from user mode threads, and the callback is not run in a user mode context. There are typically two options provided for each driver where to run trigger handlers. Either the trigger handler is run using the system work queue thread (:ref:`workqueues_v2`) or a dedicated thread. A great example can be found in the BMI160 driver which has Kconfig options for selecting a trigger mode. See :kconfig:option:`CONFIG_BMI160_TRIGGER_NONE`, :kconfig:option:`CONFIG_BMI160_TRIGGER_GLOBAL_THREAD` (work queue), :kconfig:option:`CONFIG_BMI160_TRIGGER_OWN_THREAD` (dedicated thread). Some notable attributes of using a driver dedicated thread vs the system work queue. * Driver dedicated threads have dedicated stack (RAM) which only gets used for that single trigger handler function. * Driver dedicated threads *do* get their own priority typically which lets you prioritize trigger handling among other threads. * Driver dedicated threads will not have head of line blocking if the driver needs time to handle the trigger. .. note:: In all cases it's very likely there will be variable delays from the actual interrupt to your callback function being run. In the work queue (GLOBAL_THREAD) case the work queue itself can be the source of variable latency! .. literalinclude:: tap_count.c :language: c ```
/content/code_sandbox/doc/hardware/peripherals/sensor/fetch_and_get.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
627
```c /* * */ #include <zephyr/drivers/sensor.h> #define ACCEL_TRIGGERS \ { SENSOR_TRIG_DRDY, SENSOR_STREAM_DATA_INCLUDE }, \ { SENSOR_TRIG_TAP, SENSOR_STREAM_DATA_NOP } #define ACCEL_ALIAS(id) DT_ALIAS(CONCAT(accel, id)) #define ACCEL_IODEV_SYM(id) CONCAT(accel_iodev, id) #define ACCEL_IODEV_PTR(id) &ACCEL_IODEV_SYM(id) #define ACCEL_DEFINE_IODEV(id) \ SENSOR_DT_STREAM_IODEV( \ ACCEL_IODEV_SYM(id), \ ACCEL_ALIAS(id), \ ACCEL_TRIGGERS \ ); #define NUM_SENSORS 2 LISTIFY(NUM_SENSORS, ACCEL_DEFINE_IODEV, (;)); struct sensor_iodev *iodevs[NUM_SENSORS] = { LISTIFY(NUM_SENSORS, ACCEL_IODEV_PTR, (,)) }; RTIO_DEFINE_WITH_MEMPOOL(accel_ctx, NUM_SENSORS, NUM_SENSORS, NUM_SENSORS, 16, sizeof(void *)); int main(void) { int rc; uint32_t accel_frame_iter = 0; struct sensor_three_axis_data accel_data[2] = {0}; struct sensor_decoder_api *decoder; struct rtio_cqe *cqe; uint8_t *buf; uint32_t buf_len; struct rtio_sqe *handles[2]; /* Start the streams */ for (int i = 0; i < NUM_SENSORS; i++) { sensor_stream(iodevs[i], &accel_ctx, NULL, &handles[i]); } while (1) { cqe = rtio_cqe_consume_block(&accel_ctx); if (cqe->result != 0) { printk("async read failed %d\n", cqe->result); return; } rc = rtio_cqe_get_mempool_buffer(&accel_ctx, cqe, &buf, &buf_len); if (rc != 0) { printk("get mempool buffer failed %d\n", rc); return; } struct device *sensor = ((struct sensor_read_config *) ((struct rtio_iodev *)cqe->userdata)->data)->sensor; rtio_cqe_release(&accel_ctx, cqe); rc = sensor_get_decoder(sensor, &decoder); if (rc != 0) { printk("sensor_get_decoder failed %d\n", rc); return; } /* Frame iterator values when data comes from a FIFO */ uint32_t accel_fit = 0; /* Number of accelerometer data frames */ uint32_t frame_count; rc = decoder->get_frame_count(buf, {SENSOR_CHAN_ACCEL_XYZ, 0}, &frame_count); if (rc != 0) { printk("sensor_get_decoder failed %d\n", rc); return; } /* If a tap has occurred lets print it out */ if (decoder->has_trigger(buf, SENSOR_TRIG_TAP)) { printk("Tap! Sensor %s\n", dev->name); } /* Decode all available accelerometer sample frames */ for (int i = 0; i < frame_count; i++) { decoder->decode(buf, {SENSOR_CHAN_ACCEL_XYZ, 0}, accel_fit, 1, &accel_data); printk("Accel data for %s " PRIsensor_three_axis_data "\n", dev->name, PRIsensor_three_axis_data_arg(accel_data, 0)); } rtio_release_buffer(&accel_ctx, buf, buf_len); } } ```
/content/code_sandbox/doc/hardware/peripherals/sensor/accel_stream.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
796
```c /* * */ #include <zephyr/drivers/sensor.h> #define TEMP_CHANNELS \ { SENSOR_CHAN_AMBIENT_TEMP, 0 }, \ { SENSOR_CHAN_AMBIENT_TEMP, 1 } #define TEMP_ALIAS(id) DT_ALIAS(CONCAT(temp, id)) #define TEMP_IODEV_SYM(id) CONCAT(temp_iodev, id) #define TEMP_IODEV_PTR(id) &TEMP_IODEV_SYM(id) #define TEMP_DEFINE_IODEV(id) \ SENSOR_DT_READ_IODEV( \ TEMP_IODEV_SYM(id), \ TEMP_ALIAS(id), \ TEMP_CHANNELS \ ); #define NUM_SENSORS 2 LISTIFY(NUM_SENSORS, TEMP_DEFINE_IODEV, (;)); struct sensor_iodev *iodevs[NUM_SENSORS] = { LISTIFY(NUM_SENSORS, TEMP_IODEV_PTR, (,)) }; RTIO_DEFINE_WITH_MEMPOOL(temp_ctx, NUM_SENSORS, NUM_SENSORS, NUM_SENSORS, 8, sizeof(void *)); int main(void) { int rc; uint32_t temp_frame_iter = 0; struct sensor_q31_data temp_data[2] = {0}; struct sensor_decoder_api *decoder; struct rtio_cqe *cqe; uint8_t *buf; uint32_t buf_len; while (1) { /* Non-Blocking read for each sensor */ for (int i = 0; i < NUM_SENSORS; i++) { rc = sensor_read_async_mempool(iodevs[i], &temp_ctx, iodevs[i]); if (rc != 0) { printk("sensor_read() failed %d\n", rc); return; } } /* Wait for read completions */ for (int i = 0; i < NUM_SENSORS; i++) { cqe = rtio_cqe_consume_block(&temp_ctx); if (cqe->result != 0) { printk("async read failed %d\n", cqe->result); return; } /* Get the associated mempool buffer with the completion */ rc = rtio_cqe_get_mempool_buffer(&temp_ctx, cqe, &buf, &buf_len); if (rc != 0) { printk("get mempool buffer failed %d\n", rc); return; } struct device *sensor = ((struct sensor_read_config *) ((struct rtio_iodev *)cqe->userdata)->data)->sensor; /* Done with the completion event, release it */ rtio_cqe_release(&temp_ctx, cqe); rc = sensor_get_decoder(sensor, &decoder); if (rc != 0) { printk("sensor_get_decoder failed %d\n", rc); return; } /* Frame iterators, one per channel we are decoding */ uint32_t temp_fits[2] = { 0, 0 }; decoder->decode(buf, {SENSOR_CHAN_AMBIENT_TEMP, 0}, &temp_fits[0], 1, &temp_data[0]); decoder->decode(buf, {SENSOR_CHAN_AMBIENT_TEMP, 1}, &temp_fits[1], 1, &temp_data[1]); /* Done with the buffer, release it */ rtio_release_buffer(&temp_ctx, buf, buf_len); printk("Temperature for %s channel 0 " PRIsensor_q31_data ", channel 1 " PRIsensor_q31_data "\n", dev->name, PRIsensor_q31_data_arg(temp_data[0], 0), PRIsensor_q31_data_arg(temp_data[1], 0)); } } k_msleep(1); } ```
/content/code_sandbox/doc/hardware/peripherals/sensor/multiple_temp_polling.c
c
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
810
```restructuredtext .. _sensor-trigger: Sensor Triggers ############### :dfn:`Triggers`, enumerated in :c:enum:`sensor_trigger_type`, are sensor generated events. Typically sensors allow setting up these events to cause digital line signaling for easy capture by a micro controller. The events can then commonly be inspected by reading registers to determine which event caused the digital line signaling to occur. There are many kinds of triggers sensors provide, from informative ones such as data ready to physical events such as taps or steps. ```
/content/code_sandbox/doc/hardware/peripherals/sensor/triggers.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
107
```restructuredtext .. _sensor-channel: Sensor Channels ############### :dfn:`Channels`, enumerated in :c:enum:`sensor_channel`, are quantities that a sensor device can measure. Sensors may have multiple channels, either to represent different axes of the same physical property (e.g. acceleration); or because they can measure different properties altogether (ambient temperature, pressure and humidity). Sensors may have multiple channels of the same measurement type to enable measuring many readings of perhaps temperature, light intensity, amperage, voltage, or capacitance for example. A channel is specified in Zephyr using a :c:struct:`sensor_chan_spec` which is a pair containing both the channel type (:c:enum:`sensor_channel`) and channel index. At times only :c:enum:`sensor_channel` is used but this should be considered historical since the introduction of :c:struct:`sensor_chan_spec` for Zephyr 3.7. ```
/content/code_sandbox/doc/hardware/peripherals/sensor/channels.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
199
```restructuredtext .. _sensor-read-and-decode: Read and Decode ############### The quickly stabilizing experimental APIs for reading sensor data are: * :c:func:`sensor_read` * :c:func:`sensor_read_async_mempool` * :c:func:`sensor_get_decoder` * :c:func:`sensor_decode` Benefits over :ref:`sensor-fetch-and-get` ********************************************************* These APIs allow for a wider usage of sensors, sensor types, and data flows with sensors. These are the future looking APIs in Zephyr and solve many issues that have been run into with :ref:`sensor-fetch-and-get`. :c:func:`sensor_read` and similar functions acquire sensor encoded data into a buffer provided by the caller. Decode (:c:func:`sensor_decode`) then decodes the sensor specific encoded data into fixed point :c:type:`q31_t` values as vectors per channel. This allows further processing using fixed point DSP functions that work on vectors of data to be done (e.g. low-pass filters, FFT, fusion, etc). Reading is by default asynchronous in its implementation and takes advantage of :ref:`rtio` to enable chaining asynchronous requests, or starting requests against many sensors simultaneously from a single call context. This enables incredibly useful code flows when working with sensors such as: * Obtaining the raw sensor data, decoding never, later, or on a separate processor (e.g. a phone). * Starting a read for sensors directly from an interrupt handler. No dedicated thread needed saving precious stack space. No work queue needed introducing variable latency. Starting a read for multiple sensors simultaneously from a single call context (interrupt/thread/work queue). * Requesting multiple reads to the same device for Ping-Pong (double buffering) setups. * Creating entire pipelines of data flow from sensors allowing for software defined virtual sensors (:ref:`sensing`) all from a single thread with DAG process ordering. * Potentially pre-programming DMAs to trigger on GPIO events, leaving the CPU entirely out of the loop in handling sensor events like FIFO watermarks. Additionally, other shortcomings of :ref:`sensor-fetch-and-get` related to memory and trigger handling are solved. * Triggers result in enqueued events, not callbacks. * Triggers can be setup to automatically fetch data. Potentially enabling pre-programmed DMA transfers on GPIO interrupts. * Far less likely triggers are missed due to long held interrupt masks from callbacks and context swapping. * Sensor FIFOs supported by wiring up FIFO triggers to read data into mempool allocated buffers. * All sensor processing can be done in user mode (memory protected) threads. * Multiple sensor channels of the same type are better supported. .. note:: For `Read and Decode`_ benefits to be fully realized requires :ref:`rtio` compliant communication access to the sensor. Typically this means an :ref:`rtio` enabled bus driver for SPI or I2C. Polling Read ************ Polling reads with `Read and Decode`_ can be accomplished by instantiating a polling I/O device (akin to a file descriptor) for the sensor with the desired channels to poll. Requesting either blocking or non-blocking reads, then optionally decoding the data into fixed point values. Polling a temperature sensor and printing its readout is likely the simplest sample to show how this all works. .. literalinclude:: temp_polling.c :language: c Polling Read with Multiple Sensors ********************************** One of the benefits of Read and Decode is the ability to concurrently read many sensors with many channels in one thread. Effectively read requests are started asynchronously for all sensors and their channels. When each read completes we then decode the sensor data. Examples speak loudly and so a sample showing how this might work with multiple temperature sensors with multiple temperature channels: .. literalinclude:: multiple_temp_polling.c :language: c Streaming ********* Handling triggers with `Read and Decode`_ works by setting up a stream I/O device configuration. A stream specifies the set of triggers to capture and if data should be captured with the event. .. literalinclude:: accel_stream.c :language: c ```
/content/code_sandbox/doc/hardware/peripherals/sensor/read_and_decode.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
893
```restructuredtext .. _eeprom: Electrically Erasable Programmable Read-Only Memory (EEPROM) ############################################################ Overview ******** EEPROMs have an erase block size of 1 byte, a long lifetime, and allow overwriting data on byte-by-byte access. .. toctree:: :maxdepth: 2 api.rst shell.rst ```
/content/code_sandbox/doc/hardware/peripherals/eeprom/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
79
```restructuredtext .. _eeprom_api: EEPROM API ########## Overview ******** The EEPROM API provides read and write access to Electrically Erasable Programmable Read-Only Memory (EEPROM) devices. Configuration Options ********************* Related configuration options: * :kconfig:option:`CONFIG_EEPROM` API Reference ************* .. doxygengroup:: eeprom_interface ```
/content/code_sandbox/doc/hardware/peripherals/eeprom/api.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
81
```restructuredtext .. _dai_api: Digital Audio Interface (DAI) ############################# Overview ******** The DAI (Digital Audio Interface) is a generic high level API for audio drivers. It can be configured with bespoke data for vendor specific configuration. Configuration Options ********************* Related configuration options: * :kconfig:option:`CONFIG_DAI` API Reference ************* .. doxygengroup:: dai_interface ```
/content/code_sandbox/doc/hardware/peripherals/audio/dai.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
85
```restructuredtext .. _audio_codec_api: Audio Codec ########### Overview ******** The Audio Codec API provides access to digital audio codecs. Configuration Options ********************* Related configuration options: * :kconfig:option:`CONFIG_AUDIO_CODEC` API Reference ************* .. doxygengroup:: audio_codec_interface ```
/content/code_sandbox/doc/hardware/peripherals/audio/codec.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
63
```restructuredtext .. _audio_reference: Audio ##### .. toctree:: :maxdepth: 1 codec.rst dmic.rst i2s.rst dai.rst ```
/content/code_sandbox/doc/hardware/peripherals/audio/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
46
```restructuredtext .. _eeprom_shell: EEPROM Shell ############ .. contents:: :local: :depth: 1 Overview ******** The EEPROM shell provides an ``eeprom`` command with a set of subcommands for the :ref:`shell <shell_api>` module. It allows testing and exploring the :ref:`EEPROM <eeprom_api>` driver API through an interactive interface without having to write a dedicated application. The EEPROM shell can also be enabled in existing applications to aid in interactive debugging of EEPROM issues. In order to enable the EEPROM shell, the following :ref:`Kconfig <kconfig>` options must be enabled: * :kconfig:option:`CONFIG_SHELL` * :kconfig:option:`CONFIG_EEPROM` * :kconfig:option:`CONFIG_EEPROM_SHELL` For example, building the :ref:`hello_world` sample for the :ref:`native_sim` with the EEPROM shell: .. zephyr-app-commands:: :zephyr-app: samples/hello_world :board: native_sim :gen-args: -DCONFIG_SHELL=y -DCONFIG_EEPROM=y -DCONFIG_EEPROM_SHELL=y :goals: build See the :ref:`shell <shell_api>` documentation for general instructions on how to connect and interact with the shell. The EEPROM shell comes with built-in help (unless :kconfig:option:`CONFIG_SHELL_HELP` is disabled). The built-in help messages can be printed by passing ``-h`` or ``--help`` to the ``eeprom`` command or any of its subcommands. All subcommands also support tab-completion of their arguments. .. tip:: All of the EEPROM shell subcommands take the name of an EEPROM peripheral as their first argument, which also supports tab-completion. A list of all devices available can be obtained using the ``device list`` shell command when :kconfig:option:`CONFIG_DEVICE_SHELL` is enabled. The examples below all use the device name ``eeprom@0``. EEPROM Size *********** The size of an EEPROM can be inspected using the ``eeprom size`` subcommand as shown below: .. code-block:: console uart:~$ eeprom size eeprom@0 32768 bytes Writing Data ************ Data can be written to an EEPROM using the ``eeprom write`` subcommand. This subcommand takes at least three arguments; the EEPROM device name, the offset to start writing to, and at least one data byte. In the following example, the hexadecimal sequence of bytes ``0x0d 0x0e 0x0a 0x0d 0x0b 0x0e 0x0e 0x0f`` is written to offset ``0x0``: .. code-block:: console uart:~$ eeprom write eeprom@0 0x0 0x0d 0x0e 0x0a 0x0d 0x0b 0x0e 0x0e 0x0f Writing 8 bytes to EEPROM... Verifying... Verify OK It is also possible to fill a portion of the EEPROM with the same pattern using the ``eeprom fill`` subcommand. In the following example, the pattern ``0xaa`` is written to 16 bytes starting at offset ``0x8``: .. code-block:: console uart:~$ eeprom fill eeprom@0 0x8 16 0xaa Writing 16 bytes of 0xaa to EEPROM... Verifying... Verify OK Reading Data ************ Data can be read from an EEPROM using the ``eeprom read`` subcommand. This subcommand takes three arguments; the EEPROM device name, the offset to start reading from, and the number of bytes to read: .. code-block:: console uart:~$ eeprom read eeprom@0 0x0 8 Reading 8 bytes from EEPROM, offset 0... 00000000: 0d 0e 0a 0d 0b 0e 0e 0f |........ | ```
/content/code_sandbox/doc/hardware/peripherals/eeprom/shell.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
905
```restructuredtext .. _audio_dmic_api: Digital Microphone (DMIC) ######################### Overview ******** The audio DMIC interface provides access to digital microphones. Configuration Options ********************* Related configuration options: * :kconfig:option:`CONFIG_AUDIO_DMIC` API Reference ************* .. doxygengroup:: audio_dmic_interface ```
/content/code_sandbox/doc/hardware/peripherals/audio/dmic.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
71
```restructuredtext .. _i2s_api: Inter-IC Sound (I2S) Bus ######################## Overview ******** The I2S (Inter-IC Sound) API provides support for the standard I2S interface as well as common non-standard extensions such as PCM Short/Long Frame Sync and Left/Right Justified Data Formats. Configuration Options ********************* Related configuration options: * :kconfig:option:`CONFIG_I2S` API Reference ************* .. doxygengroup:: i2s_interface ```
/content/code_sandbox/doc/hardware/peripherals/audio/i2s.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
109
```restructuredtext .. comment not documenting .. doxygengroup:: display_interfaces .. _display_api: Display Interface ################# API Reference ************* Generic Display Interface ========================= .. doxygengroup:: display_interface Grove LCD Display ================= .. doxygengroup:: grove_display BBC micro:bit Display ===================== .. doxygengroup:: mb_display Monochrome Character Framebuffer ================================ .. doxygengroup:: monochrome_character_framebuffer ```
/content/code_sandbox/doc/hardware/peripherals/display/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
109
```restructuredtext .. _edac_api: Error Detection And Correction (EDAC) ##################################### Error Detection And Correction is a mechanism used to detect and correct errors while storing or reading data. .. toctree:: :maxdepth: 1 ibecc.rst Configuration option ******************** Related configuration option: * :kconfig:option:`CONFIG_EDAC` API Reference ************* .. doxygengroup:: edac ```
/content/code_sandbox/doc/hardware/peripherals/edac/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
92
```restructuredtext .. _edac_ibecc: In Band Error Correction Code (IBECC) ##################################### Overview ******** The mechanism initially found in Intel Elkhart Lake SOCs and later boards is an integrated memory controller with IBECC. The In-Band Error Correction Code (IBECC) improves reliability by providing error detection and correction. IBECC can work for all or for specific regions of physical memory space. The IBECC is useful for memory technologies that do not support the out-of-band ECC. IBECC adds memory overhead of 1/32 of the memory. This memory is not accessible and used to store ECC syndrome data. IBECC converts read / write transactions to two separate transactions: one for actual data and another for cache line containing ECC value. There is a debug feature IBECC Error Injection which helps to debug and verify IBECC functionality. ECC errors are injected on the write path and cause ECC errors on the read path. IBECC Configuration ******************* There are three IBECC operation modes which can be selected by Bootloader. They are listed below: * OPERATION_MODE = 0x0 sets functional mode to protect requests based on address range * OPERATION_MODE = 0x1 sets functional mode to all requests not be protected and to ignore range checks * OPERATION_MODE = 0x2 sets functional mode to protect all requests and ignore range checks IBECC operational mode is configured through BIOS or Bootloader. For operation mode 0 there are more BIOS configuration options such as memory regions. Due to high security risk Error Injection capability should not be enabled for production. Error Injection is only enabled for tests. IBECC Logging ************* IBECC logs the following fields: * Error Address * Error Syndrome * Error Type * Correctable Error (CE) - error is detected and corrected by IBECC module. * Uncorrectable Error (UE) - error is detected by IBECC module and not automatically corrected. The IBECC driver provides error type for the higher-level application to implement desired policy with respect for handling those memory errors. Error syndrome is not used in the IBECC driver but provided to higher-level application. Usage notes *********** Exceptional care needs to be taken with Non Maskable Interrupt (NMI). NMI will arrive at any time, even if the local CPU has disabled interrupts. That means that no locking mechanism can protect code against an NMI happening. Zephyr's IPC mechanisms universally use local IRQ locking as the base layer for all higher-level synchronization primitives. So, you cannot share anything that is "protected" by a lock with an NMI, because the protection does not work. The only tool you have available for synchronization in the Zephyr API that works against an NMI is the atomic layer. This also applies to callback function which is called by NMI handler. Configuration option ******************** Related configuration option: * :kconfig:option:`CONFIG_EDAC_IBECC` ```
/content/code_sandbox/doc/hardware/peripherals/edac/ibecc.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
644
```restructuredtext .. _cache-guide: Cache Interface ############### This is a high-level guide to cache interface and Kconfig options related to cache controllers. See :ref:`cache_api` for API reference material. Zephyr has different Kconfig options to control how the cache controller is implemented and controlled. * :kconfig:option:`CONFIG_CPU_HAS_DCACHE` / :kconfig:option:`CONFIG_CPU_HAS_ICACHE`: these hidden options should be selected at SoC / platform level when the CPU actually supports a data or instruction cache. The cache controller can be in the core or can be an external cache controller for which a driver is provided. These options have the goal to document an available feature and should be set whether we plan to support and use the caches in Zephyr or not. * :kconfig:option:`CONFIG_DCACHE` / :kconfig:option:`CONFIG_ICACHE`: these options must be selected when support for data or instruction cache is present and working in zephyr. All the code paths related to cache control must be conditionally enabled depending on these symbols. When the symbol is set the cache is considered enabled and used. These symbols say nothing about the actual API interface exposed to the user. For example a platform using the data cache can enable the :kconfig:option:`CONFIG_DCACHE` symbol and use some HAL exported function in some platform-specific code to enable and manage the d-cache. * :kconfig:option:`CONFIG_CACHE_MANAGEMENT`: this option must be selected when the cache operations are exposed to the user through a standard API (see :ref:`cache_api`). When this option is enabled we assume that all the cache functions are implemented in the architectural code or in an external cache controller driver. * :kconfig:option:`CONFIG_ARCH_CACHE`/:kconfig:option:`CONFIG_EXTERNAL_CACHE`: mutually exclusive options for :kconfig:option:`CACHE_TYPE` used to define whether the cache operations are implemented at arch level or using an external cache controller with a provided driver. * :kconfig:option:`CONFIG_ARCH_CACHE`: the cache API is implemented by the arch code * :kconfig:option:`CONFIG_EXTERNAL_CACHE`: the cache API is implemented by a driver that supports the external cache controller. In this case the driver must be located as usual in the :file:`drivers/cache/` directory .. _cache_api: Cache API ********* .. doxygengroup:: cache_interface ```
/content/code_sandbox/doc/hardware/cache/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
550
```restructuredtext .. _porting: Porting ####### These pages document how to port Zephyr to new hardware. .. toctree:: :maxdepth: 1 arch.rst soc_porting.rst board_porting.rst shields.rst ```
/content/code_sandbox/doc/hardware/porting/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
61
```restructuredtext .. _architecture_porting_guide: Architecture Porting Guide ########################## An architecture port is needed to enable Zephyr to run on an :abbr:`ISA (instruction set architecture)` or an :abbr:`ABI (Application Binary Interface)` that is not currently supported. The following are examples of ISAs and ABIs that Zephyr supports: * x86_32 ISA with System V ABI * ARMv7-M ISA with Thumb2 instruction set and ARM Embedded ABI (aeabi) * ARCv2 ISA For information on Kconfig configuration, see :ref:`setting_configuration_values`. Architectures use a Kconfig configuration scheme similar to boards. An architecture port can be divided in several parts; most are required and some are optional: * **The early boot sequence**: each architecture has different steps it must take when the CPU comes out of reset (required). * **Interrupt and exception handling**: each architecture handles asynchronous and unrequested events in a specific manner (required). * **Thread context switching**: the Zephyr context switch is dependent on the ABI and each ISA has a different set of registers to save (required). * **Thread creation and termination**: A thread's initial stack frame is ABI and architecture-dependent, and thread abortion possibly as well (required). * **Device drivers**: most often, the system clock timer and the interrupt controller are tied to the architecture (some required, some optional). * **Utility libraries**: some common kernel APIs rely on a architecture-specific implementation for performance reasons (required). * **CPU idling/power management**: most architectures implement instructions for putting the CPU to sleep (partly optional, most likely very desired). * **Fault management**: for implementing architecture-specific debug help and handling of fatal error in threads (partly optional). * **Linker scripts and toolchains**: architecture-specific details will most likely be needed in the build system and when linking the image (required). * **Memory Management and Memory Mapping**: for architecture-specific details on supporting memory management and memory mapping. * **Stack Objects**: for architecture-specific details on memory protection hardware regarding stack objects. * **User Mode Threads**: for supporting threads in user mode. * **GDB Stub**: for supporting GDB stub to enable remote debugging. Early Boot Sequence ******************* The goal of the early boot sequence is to take the system from the state it is after reset to a state where is can run C code and thus the common kernel initialization sequence. Most of the time, very few steps are needed, while some architectures require a bit more work to be performed. Common steps for all architectures: * Setup an initial stack. * If running an :abbr:`XIP (eXecute-In-Place)` kernel, copy initialized data from ROM to RAM. * If not using an ELF loader, zero the BSS section. * Jump to :code:`z_cstart()`, the early kernel initialization * :code:`z_cstart()` is responsible for context switching out of the fake context running at startup into the main thread. Some examples of architecture-specific steps that have to be taken: * If given control in real mode on x86_32, switch to 32-bit protected mode. * Setup the segment registers on x86_32 to handle boot loaders that leave them in an unknown or broken state. * Initialize a board-specific watchdog on Cortex-M3/4. * Switch stacks from MSP to PSP on Cortex-M. * Use a different approach than calling into _Swap() on Cortex-M to prevent race conditions. * Setup FIRQ and regular IRQ handling on ARCv2. Interrupt and Exception Handling ******************************** Each architecture defines interrupt and exception handling differently. When a device wants to signal the processor that there is some work to be done on its behalf, it raises an interrupt. When a thread does an operation that is not handled by the serial flow of the software itself, it raises an exception. Both, interrupts and exceptions, pass control to a handler. The handler is known as an :abbr:`ISR (Interrupt Service Routine)` in the case of interrupts. The handler performs the work required by the exception or the interrupt. For interrupts, that work is device-specific. For exceptions, it depends on the exception, but most often the core kernel itself is responsible for providing the handler. The kernel has to perform some work in addition to the work the handler itself performs. For example: * Prior to handing control to the handler: * Save the currently executing context. * Possibly getting out of power saving mode, which includes waking up devices. * Updating the kernel uptime if getting out of tickless idle mode. * After getting control back from the handler: * Decide whether to perform a context switch. * When performing a context switch, restore the context being context switched in. This work is conceptually the same across architectures, but the details are completely different: * The registers to save and restore. * The processor instructions to perform the work. * The numbering of the exceptions. * etc. It thus needs an architecture-specific implementation, called the interrupt/exception stub. Another issue is that the kernel defines the signature of ISRs as: .. code-block:: C void (*isr)(void *parameter) Architectures do not have a consistent or native way of handling parameters to an ISR. As such there are two commonly used methods for handling the parameter. * Using some architecture defined mechanism, the parameter value is forced in the stub. This is commonly found in X86-based architectures. * The parameters to the ISR are inserted and tracked via a separate table requiring the architecture to discover at runtime which interrupt is executing. A common interrupt handler demuxer is installed for all entries of the real interrupt vector table, which then fetches the device's ISR and parameter from the separate table. This approach is commonly used in the ARC and ARM architectures via the :kconfig:option:`CONFIG_GEN_ISR_TABLES` implementation. You can find examples of the stubs by looking at :code:`_interrupt_enter()` in x86, :code:`_IntExit()` in ARM, :code:`_isr_wrapper()` in ARM, or the full implementation description for ARC in :zephyr_file:`arch/arc/core/isr_wrapper.S`. Each architecture also has to implement primitives for interrupt control: * locking interrupts: :c:macro:`irq_lock()`, :c:macro:`irq_unlock()`. * registering interrupts: :c:macro:`IRQ_CONNECT()`. * programming the priority if possible :c:func:`irq_priority_set`. * enabling/disabling interrupts: :c:macro:`irq_enable()`, :c:macro:`irq_disable()`. .. note:: :c:macro:`IRQ_CONNECT` is a macro that uses assembler and/or linker script tricks to connect interrupts at build time, saving boot time and text size. The vector table should contain a handler for each interrupt and exception that can possibly occur. The handler can be as simple as a spinning loop. However, we strongly suggest that handlers at least print some debug information. The information helps figuring out what went wrong when hitting an exception that is a fault, like divide-by-zero or invalid memory access, or an interrupt that is not expected (:dfn:`spurious interrupt`). See the ARM implementation in :zephyr_file:`arch/arm/core/cortex_m/fault.c` for an example. Thread Context Switching ************************ Multi-threading is the basic purpose to have a kernel at all. Zephyr supports two types of threads: preemptible and cooperative. Two crucial concepts when writing an architecture port are the following: * Cooperative threads run at a higher priority than preemptible ones, and always preempt them. * After handling an interrupt, if a cooperative thread was interrupted, the kernel always goes back to running that thread, since it is not preemptible. A context switch can happen in several circumstances: * When a thread executes a blocking operation, such as taking a semaphore that is currently unavailable. * When a preemptible thread unblocks a thread of higher priority by releasing the object on which it was blocked. * When an interrupt unblocks a thread of higher priority than the one currently executing, if the currently executing thread is preemptible. * When a thread runs to completion. * When a thread causes a fatal exception and is removed from the running threads. For example, referencing invalid memory, Therefore, the context switching must thus be able to handle all these cases. The kernel keeps the next thread to run in a "cache", and thus the context switching code only has to fetch from that cache to select which thread to run. There are two types of context switches: :dfn:`cooperative` and :dfn:`preemptive`. * A *cooperative* context switch happens when a thread willfully gives the control to another thread. There are two cases where this happens * When a thread explicitly yields. * When a thread tries to take an object that is currently unavailable and is willing to wait until the object becomes available. * A *preemptive* context switch happens either because an ISR or a thread causes an operation that schedules a thread of higher priority than the one currently running, if the currently running thread is preemptible. An example of such an operation is releasing an object on which the thread of higher priority was waiting. .. note:: Control is never taken from cooperative thread when one of them is the running thread. A cooperative context switch is always done by having a thread call the :code:`_Swap()` kernel internal symbol. When :code:`_Swap` is called, the kernel logic knows that a context switch has to happen: :code:`_Swap` does not check to see if a context switch must happen. Rather, :code:`_Swap` decides what thread to context switch in. :code:`_Swap` is called by the kernel logic when an object being operated on is unavailable, and some thread yielding/sleeping primitives. .. note:: On x86 and Nios2, :code:`_Swap` is generic enough and the architecture flexible enough that :code:`_Swap` can be called when exiting an interrupt to provoke the context switch. This should not be taken as a rule, since neither the ARM Cortex-M or ARCv2 port do this. Since :code:`_Swap` is cooperative, the caller-saved registers from the ABI are already on the stack. There is no need to save them in the k_thread structure. A context switch can also be performed preemptively. This happens upon exiting an ISR, in the kernel interrupt exit stub: * :code:`_interrupt_enter` on x86 after the handler is called. * :code:`_IntExit` on ARM. * :code:`_firq_exit` and :code:`_rirq_exit` on ARCv2. In this case, the context switch must only be invoked when the interrupted thread was preemptible, not when it was a cooperative one, and only when the current interrupt is not nested. The kernel also has the concept of "locking the scheduler". This is a concept similar to locking the interrupts, but lighter-weight since interrupts can still occur. If a thread has locked the scheduler, is it temporarily non-preemptible. So, the decision logic to invoke the context switch when exiting an interrupt is simple: * If the interrupted thread is not preemptible, do not invoke it. * Else, fetch the cached thread from the ready queue, and: * If the cached thread is not the current thread, invoke the context switch. * Else, do not invoke it. This is simple, but crucial: if this is not implemented correctly, the kernel will not function as intended and will experience bizarre crashes, mostly due to stack corruption. .. note:: If running a coop-only system, i.e. if :kconfig:option:`CONFIG_NUM_PREEMPT_PRIORITIES` is 0, no preemptive context switch ever happens. The interrupt code can be optimized to not take any scheduling decision when this is the case. Thread Creation and Termination ******************************* To start a new thread, a stack frame must be constructed so that the context switch can pop it the same way it would pop one from a thread that had been context switched out. This is to be implemented in an architecture-specific :code:`_new_thread` internal routine. The thread entry point is also not to be called directly, i.e. it should not be set as the :abbr:`PC (program counter)` for the new thread. Rather it must be wrapped in :code:`_thread_entry`. This means that the PC in the stack frame shall be set to :code:`_thread_entry`, and the thread entry point shall be passed as the first parameter to :code:`_thread_entry`. The specifics of this depend on the ABI. The need for an architecture-specific thread termination implementation depends on the architecture. There is a generic implementation, but it might not work for a given architecture. One reason that has been encountered for having an architecture-specific implementation of thread termination is that aborting a thread might be different if aborting because of a graceful exit or because of an exception. This is the case for ARM Cortex-M, where the CPU has to be taken out of handler mode if the thread triggered a fatal exception, but not if the thread gracefully exits its entry point function. This means implementing an architecture-specific version of :c:func:`k_thread_abort`, and setting the Kconfig option :kconfig:option:`CONFIG_ARCH_HAS_THREAD_ABORT` as needed for the architecture (e.g. see :zephyr_file:`arch/arm/core/cortex_m/Kconfig`). Thread Local Storage ******************** To enable thread local storage on a new architecture: #. Implement :c:func:`arch_tls_stack_setup` to setup the TLS storage area in stack. Refer to the toolchain documentation on how the storage area needs to be structured. Some helper functions can be used: * Function :c:func:`z_tls_data_size` returns the size needed for thread local variables (excluding any extra data required by toolchain and architecture). * Function :c:func:`z_tls_copy` prepares the TLS storage area for thread local variables. This only copies the variable themselves and does not do architecture and/or toolchain specific data. #. In the context switching, grab the ``tls`` field inside the new thread's ``struct k_thread`` and put it into an appropriate register (or some other variable) for access to the TLS storage area. Refer to toolchain and architecture documentation on which registers to use. #. In kconfig, add ``select CONFIG_ARCH_HAS_THREAD_LOCAL_STORAGE`` to kconfig related to the new architecture. #. Run the ``tests/kernel/threads/tls`` to make sure the new code works. Device Drivers ************** The kernel requires very few hardware devices to function. In theory, the only required device is the interrupt controller, since the kernel can run without a system clock. In practice, to get access to most, if not all, of the sanity check test suite, a system clock is needed as well. Since these two are usually tied to the architecture, they are part of the architecture port. Interrupt Controllers ===================== There can be significant differences between the interrupt controllers and the interrupt concepts across architectures. For example, x86 has the concept of an :abbr:`IDT (Interrupt Descriptor Table)` and different interrupt controllers. The position of an interrupt in the IDT determines its priority. On the other hand, the ARM Cortex-M has the :abbr:`NVIC (Nested Vectored Interrupt Controller)` as part of the architecture definition. There is no need for an IDT-like table that is separate from the NVIC vector table. The position in the table has nothing to do with priority of an IRQ: priorities are programmable per-entry. The ARCv2 has its interrupt unit as part of the architecture definition, which is somewhat similar to the NVIC. However, where ARC defines interrupts as having a one-to-one mapping between exception and interrupt numbers (i.e. exception 1 is IRQ1, and device IRQs start at 16), ARM has IRQ0 being equivalent to exception 16 (and weirdly enough, exception 1 can be seen as IRQ-15). All these differences mean that very little, if anything, can be shared between architectures with regards to interrupt controllers. System Clock ============ x86 has APIC timers and the HPET as part of its architecture definition. ARM Cortex-M has the SYSTICK exception. Finally, ARCv2 has the timer0/1 device. Kernel timeouts are handled in the context of the system clock timer driver's interrupt handler. Console Over Serial Line ======================== There is one other device that is almost a requirement for an architecture port, since it is so useful for debugging. It is a simple polling, output-only, serial port driver on which to send the console (:code:`printk`, :code:`printf`) output. It is not required, and a RAM console (:kconfig:option:`CONFIG_RAM_CONSOLE`) can be used to send all output to a circular buffer that can be read by a debugger instead. Utility Libraries ***************** The kernel depends on a few functions that can be implemented with very few instructions or in a lock-less manner in modern processors. Those are thus expected to be implemented as part of an architecture port. * Atomic operators. * If instructions do exist for a given architecture, the implementation is configured using the :kconfig:option:`CONFIG_ATOMIC_OPERATIONS_ARCH` Kconfig option. * If instructions do not exist for a given architecture, a generic version that wraps :c:func:`irq_lock` or :c:func:`irq_unlock` around non-atomic operations exists. It is configured using the :kconfig:option:`CONFIG_ATOMIC_OPERATIONS_C` Kconfig option. * Find-least-significant-bit-set and find-most-significant-bit-set. * If instructions do not exist for a given architecture, it is always possible to implement these functions as generic C functions. It is possible to use compiler built-ins to implement these, but be careful they use the required compiler barriers. CPU Idling/Power Management *************************** The kernel provides support for CPU power management with two functions: :c:func:`arch_cpu_idle` and :c:func:`arch_cpu_atomic_idle`. :c:func:`arch_cpu_idle` can be as simple as calling the power saving instruction for the architecture with interrupts unlocked, for example :code:`hlt` on x86, :code:`wfi` or :code:`wfe` on ARM, :code:`sleep` on ARC. This function can be called in a loop within a context that does not care if it get interrupted or not by an interrupt before going to sleep. There are basically two scenarios when it is correct to use this function: * In a single-threaded system, in the only thread when the thread is not used for doing real work after initialization, i.e. it is sitting in a loop doing nothing for the duration of the application. * In the idle thread. :c:func:`arch_cpu_atomic_idle`, on the other hand, must be able to atomically re-enable interrupts and invoke the power saving instruction. It can thus be used in real application code, again in single-threaded systems. Normally, idling the CPU should be left to the idle thread, but in some very special scenarios, these APIs can be used by applications. Both functions must exist for a given architecture. However, the implementation can be simply the following steps, if desired: #. unlock interrupts #. NOP However, a real implementation is strongly recommended. Fault Management **************** In the event of an unhandled CPU exception, the architecture code must call into :c:func:`z_fatal_error`. This function dumps out architecture-agnostic information and makes a policy decision on what to do next by invoking :c:func:`k_sys_fatal_error`. This function can be overridden to implement application-specific policies that could include locking interrupts and spinning forever (the default implementation) or even powering off the system (if supported). Toolchain and Linking ********************* Toolchain support has to be added to the build system. Some architecture-specific definitions are needed in :zephyr_file:`include/zephyr/toolchain/gcc.h`. See what exists in that file for currently supported architectures. Each architecture also needs its own linker script, even if most sections can be derived from the linker scripts of other architectures. Some sections might be specific to the new architecture, for example the SCB section on ARM and the IDT section on x86. Memory Management and Memory Mapping ************************************ If the target platform enables paging and requires drivers to memory-map their I/O regions, :kconfig:option:`CONFIG_MMU` needs to be enabled and the following API implemented: - :c:func:`arch_mem_map` - :c:func:`arch_mem_unmap` - :c:func:`arch_page_phys_get` Stack Objects ************* The presence of memory protection hardware affects how stack objects are created. All architecture ports must specify the required alignment of the stack pointer, which is some combination of CPU and ABI requirements. This is defined in architecture headers with :c:macro:`ARCH_STACK_PTR_ALIGN` and is typically something small like 4, 8, or 16 bytes. Two types of thread stacks exist: - "kernel" stacks defined with :c:macro:`K_KERNEL_STACK_DEFINE()` and related APIs, which can host kernel threads running in supervisor mode or used as the stack for interrupt/exception handling. These have significantly relaxed alignment requirements and use less reserved data. No memory is reserved for privilege elevation stacks. - "thread" stacks which typically use more memory, but are capable of hosting thread running in user mode, as well as any use-cases for kernel stacks. If :kconfig:option:`CONFIG_USERSPACE` is not enabled, "thread" and "kernel" stacks are equivalent. Additional macros may be defined in the architecture layer to specify the alignment of the base of stack objects, any reserved data inside the stack object not used for the thread's stack buffer, and how to round up stack sizes to support user mode threads. In the absence of definitions some defaults are assumed: - :c:macro:`ARCH_KERNEL_STACK_RESERVED`: default no reserved space - :c:macro:`ARCH_THREAD_STACK_RESERVED`: default no reserved space - :c:macro:`ARCH_KERNEL_STACK_OBJ_ALIGN`: default align to :c:macro:`ARCH_STACK_PTR_ALIGN` - :c:macro:`ARCH_THREAD_STACK_OBJ_ALIGN`: default align to :c:macro:`ARCH_STACK_PTR_ALIGN` - :c:macro:`ARCH_THREAD_STACK_SIZE_ALIGN`: default round up to :c:macro:`ARCH_STACK_PTR_ALIGN` All stack creation macros are defined in terms of these. Stack objects all have the following layout, with some regions potentially zero-sized depending on configuration. There are always two main parts: reserved memory at the beginning, and then the stack buffer itself. The bounds of some areas can only be determined at runtime in the context of its associated thread object. Other areas are entirely computable at build time. Some architectures may need to carve-out reserved memory at runtime from the stack buffer, instead of unconditionally reserving it at build time, or to supplement an existing reserved area (as is the case with the ARM FPU). Such carve-outs will always be tracked in ``thread.stack_info.start``. The region specified by ``thread.stack_info.start`` and ``thread.stack_info.size`` is always fully accessible by a user mode thread. ``thread.stack_info.delta`` denotes an offset which can be used to compute the initial stack pointer from the very end of the stack object, taking into account storage for TLS and ASLR random offsets. .. code-block:: none +---------------------+ <- thread.stack_obj | Reserved Memory | } K_(THREAD|KERNEL)_STACK_RESERVED +---------------------+ | Carved-out memory | |.....................| <- thread.stack_info.start | Unused stack buffer | | | |.....................| <- thread's current stack pointer | Used stack buffer | | | |.....................| <- Initial stack pointer. Computable | ASLR Random offset | with thread.stack_info.delta +---------------------| <- thread.userspace_local_data | Thread-local data | +---------------------+ <- thread.stack_info.start + thread.stack_info.size At present, Zephyr does not support stacks that grow upward. No Memory Protection ==================== If no memory protection is in use, then the defaults are sufficient. HW-based stack overflow detection ================================= This option uses hardware features to generate a fatal error if a thread in supervisor mode overflows its stack. This is useful for debugging, although for a couple reasons, you can't reliably make any assertions about the state of the system after this happens: * The kernel could have been inside a critical section when the overflow occurs, leaving important global data structures in a corrupted state. * For systems that implement stack protection using a guard memory region, it's possible to overshoot the guard and corrupt adjacent data structures before the hardware detects this situation. To enable the :kconfig:option:`CONFIG_HW_STACK_PROTECTION` feature, the system must provide some kind of hardware-based stack overflow protection, and enable the :kconfig:option:`CONFIG_ARCH_HAS_STACK_PROTECTION` option. Two forms of HW-based stack overflow detection are supported: dedicated CPU features for this purpose, or special read-only guard regions immediately preceding stack buffers. :kconfig:option:`CONFIG_HW_STACK_PROTECTION` only catches stack overflows for supervisor threads. This is not required to catch stack overflow from user threads; :kconfig:option:`CONFIG_USERSPACE` is orthogonal. This feature only detects supervisor mode stack overflows, including stack overflows when handling system calls. It doesn't guarantee that the kernel has not been corrupted. Any stack overflow in supervisor mode should be treated as a fatal error, with no assertions about the integrity of the overall system possible. Stack overflows in user mode are recoverable (from the kernel's perspective) and require no special configuration; :kconfig:option:`CONFIG_HW_STACK_PROTECTION` only applies to catching overflows when the CPU is in supervisor mode. CPU-based stack overflow detection ---------------------------------- If we are detecting stack overflows in supervisor mode via special CPU registers (like ARM's SPLIM), then the defaults are sufficient. Guard-based stack overflow detection ------------------------------------ We are detecting supervisor mode stack overflows via special memory protection region located immediately before the stack buffer that generates an exception on write. Reserved memory will be used for the guard region. :c:macro:`ARCH_KERNEL_STACK_RESERVED` should be defined to the minimum size of a memory protection region. On most ARM CPUs this is 32 bytes. :c:macro:`ARCH_KERNEL_STACK_OBJ_ALIGN` should also be set to the required alignment for this region. MMU-based systems should not reserve RAM for the guard region and instead simply leave an non-present virtual page below every stack when it is mapped into the address space. The stack object will still need to be properly aligned and sized to page granularity. .. code-block:: none +-----------------------------+ <- thread.stack_obj | Guard reserved memory | } K_KERNEL_STACK_RESERVED +-----------------------------+ | Guard carve-out | |.............................| <- thread.stack_info.start | Stack buffer | . . Guard carve-outs for kernel stacks are uncommon and should be avoided if possible. They tend to be needed for two situations: * The same stack may be re-purposed to host a user thread, in which case the guard is unnecessary and shouldn't be unconditionally reserved. This is the case when privilege elevation stacks are not inside the stack object. * The required guard size is variable and depends on context. For example, some ARM CPUs have lazy floating point stacking during exceptions and may decrement the stack pointer by a large value without writing anything, completely overshooting a minimally-sized guard and corrupting adjacent memory. Rather than unconditionally reserving a larger guard, the extra memory is carved out if the thread uses floating point. User mode enabled ================= Enabling user mode activates two new requirements: * A separate fixed-sized privilege mode stack, specified by :kconfig:option:`CONFIG_PRIVILEGED_STACK_SIZE`, must be allocated that the user thread cannot access. It is used as the stack by the kernel when handling system calls. If stack guards are implemented, a stack guard region must be able to be placed before it, with support for carve-outs if necessary. * The memory protection hardware must be able to program a region that exactly covers the thread's stack buffer, tracked in ``thread.stack_info``. This implies that :c:macro:`ARCH_THREAD_STACK_SIZE_ADJUST()` will need to round up the requested stack size so that a region may cover it, and that :c:macro:`ARCH_THREAD_STACK_OBJ_ALIGN()` is also specified per the granularity of the memory protection hardware. This becomes more complicated if the memory protection hardware requires that all memory regions be sized to a power of two, and aligned to their own size. This is common on older MPUs and is known with :kconfig:option:`CONFIG_MPU_REQUIRES_POWER_OF_TWO_ALIGNMENT`. ``thread.stack_info`` always tracks the user-accessible part of the stack object, it must always be correct to program a memory protection region with user access using the range stored within. Non power-of-two memory region requirements ------------------------------------------- On systems without power-of-two region requirements, the reserved memory area for threads stacks defined by :c:macro:`K_THREAD_STACK_RESERVED` may be used to contain the privilege mode stack. The layout could be something like: .. code-block:: none +------------------------------+ <- thread.stack_obj | Other platform data | +------------------------------+ | Guard region (if enabled) | +------------------------------+ | Guard carve-out (if needed) | |..............................| | Privilege elevation stack | +------------------------------| <- thread.stack_obj + | Stack buffer | K_THREAD_STACK_RESERVED = . . thread.stack_info.start The guard region, and any carve-out (if needed) would be configured as a read-only region when the thread is created. * If the thread is a supervisor thread, the privilege elevation region is just extra stack memory. An overflow will eventually crash into the guard region. * If the thread is running in user mode, a memory protection region will be configured to allow user threads access to the stack buffer, but nothing before or after it. An overflow in user mode will crash into the privilege elevation stack, which the user thread has no access to. An overflow when handling a system call will crash into the guard region. On an MMU system there should be no physical guards; the privilege mode stack will be mapped into kernel memory, and the stack buffer in the user part of memory, each with non-present virtual guard pages below them to catch runtime stack overflows. Other platform data may be stored before the guard region, but this is highly discouraged if such data could be stored in ``thread.arch`` somewhere. :c:macro:`ARCH_THREAD_STACK_RESERVED` will need to be defined to capture the size of the reserved region containing platform data, privilege elevation stacks, and guards. It must be appropriately sized such that an MPU region to grant user mode access to the stack buffer can be placed immediately after it. Power-of-two memory region requirements --------------------------------------- Thread stack objects must be sized and aligned to the same power of two, without any reserved memory to allow efficient packing in memory. Thus, any guards in the thread stack must be completely carved out, and the privilege elevation stack must be allocated elsewhere. :c:macro:`ARCH_THREAD_STACK_SIZE_ADJUST()` and :c:macro:`ARCH_THREAD_STACK_OBJ_ALIGN()` should both be defined to :c:macro:`Z_POW2_CEIL()`. :c:macro:`K_THREAD_STACK_RESERVED` must be 0. For the privilege stacks, the :kconfig:option:`CONFIG_GEN_PRIV_STACKS` must be, enabled. For every thread stack found in the system, a corresponding fixed- size kernel stack used for handling system calls is generated. The address of the privilege stacks can be looked up quickly at runtime based on the thread stack address using :c:func:`z_priv_stack_find()`. These stacks are laid out the same way as other kernel-only stacks. .. code-block:: none +-----------------------------+ <- z_priv_stack_find(thread.stack_obj) | Reserved memory | } K_KERNEL_STACK_RESERVED +-----------------------------+ | Guard carve-out (if needed) | |.............................| | Privilege elevation stack | | | +-----------------------------+ <- z_priv_stack_find(thread.stack_obj) + K_KERNEL_STACK_RESERVED + CONFIG_PRIVILEGED_STACK_SIZE +-----------------------------+ <- thread.stack_obj | MPU guard carve-out | | (supervisor mode only) | |.............................| <- thread.stack_info.start | Stack buffer | . . The guard carve-out in the thread stack object is only used if the thread is running in supervisor mode. If the thread drops to user mode, there is no guard and the entire object is used as the stack buffer, with full access to the associated user mode thread and ``thread.stack_info`` updated appropriately. User Mode Threads ***************** To support user mode threads, several kernel-to-arch APIs need to be implemented, and the system must enable the :kconfig:option:`CONFIG_ARCH_HAS_USERSPACE` option. Please see the documentation for each of these functions for more details: * :c:func:`arch_buffer_validate` to test whether the current thread has access permissions to a particular memory region * :c:func:`arch_user_mode_enter` which will irreversibly drop a supervisor thread to user mode privileges. The stack must be wiped. * :c:func:`arch_syscall_oops` which generates a kernel oops when system call parameters can't be validated, in such a way that the oops appears to be generated from where the system call was invoked in the user thread * :c:func:`arch_syscall_invoke0` through :c:func:`arch_syscall_invoke6` invoke a system call with the appropriate number of arguments which must all be passed in during the privilege elevation via registers. * :c:func:`arch_is_user_context` return nonzero if the CPU is currently running in user mode * :c:func:`arch_mem_domain_max_partitions_get` which indicates the max number of regions for a memory domain. MMU systems have an unlimited amount, MPU systems have constraints on this. Some architectures may need to update software memory management structures or modify hardware registers on another CPU when memory domain APIs are invoked. If so, :kconfig:option:`CONFIG_ARCH_MEM_DOMAIN_SYNCHRONOUS_API` must be selected by the architecture and some additional APIs must be implemented. This is common on MMU systems and uncommon on MPU systems: * :c:func:`arch_mem_domain_thread_add` * :c:func:`arch_mem_domain_thread_remove` * :c:func:`arch_mem_domain_partition_add` * :c:func:`arch_mem_domain_partition_remove` Please see the doxygen documentation of these APIs for details. In addition to implementing these APIs, there are some other tasks as well: * :c:func:`_new_thread` needs to spawn threads with :c:macro:`K_USER` in user mode * On context switch, the outgoing thread's stack memory should be marked inaccessible to user mode by making the appropriate configuration changes in the memory management hardware.. The incoming thread's stack memory should likewise be marked as accessible. This ensures that threads can't mess with other thread stacks. * On context switch, the system needs to switch between memory domains for the incoming and outgoing threads. * Thread stack areas must include a kernel stack region. This should be inaccessible to user threads at all times. This stack will be used when system calls are made. This should be fixed size for all threads, and must be large enough to handle any system call. * A software interrupt or some kind of privilege elevation mechanism needs to be established. This is closely tied to how the _arch_syscall_invoke macros are implemented. On system call, the appropriate handler function needs to be looked up in _k_syscall_table. Bad system call IDs should jump to the :c:enum:`K_SYSCALL_BAD` handler. Upon completion of the system call, care must be taken not to leak any register state back to user mode. GDB Stub ******** To enable GDB stub for remote debugging on a new architecture: #. Create a new ``gdbstub.h`` header file under appropriate architecture include directory (``include/arch/<arch>/gdbstub.h``). * Create a new struct ``struct gdb_ctx`` as the GDB context. * Must define a member named ``exception`` of type ``unsigned int`` to store the GDB exception reason. This value needs to be set before entering :c:func:`z_gdb_main_loop`. * Architecture can define as many members as needed for GDB stub to function. * Pointer to this struct needs to be passed to :c:func:`z_gdb_main_loop`, where this pointer will be passed to other GDB stub functions. #. Functions for entering and exiting GDB stub main loop. * If the architecture relies on interrupts to service breakpoints, interrupt service routines (ISR) need to be implemented, which will serve as the entry point to GDB stub main loop. * These functions need to save and restore context so code execution can continue as if no breakpoints have been encountered. * These functions need to call :c:func:`z_gdb_main_loop` after saving execution context to go into the GDB stub main loop to receive commands from GDB. * Before calling :c:func:`z_gdb_main_loop`, :c:member:`gdb_ctx.exception` must be set to specify the exception reason. #. Implement necessary functions to support GDB stub functionality: * :c:func:`arch_gdb_init` * This needs to initialize necessary bits to support GDB stub functionality, for example, setting up the GDB context and connecting debug interrupts. * This must stop code execution via architecture specific method (e.g. raising debug interrupts). This allows GDB to connect during boot. * :c:func:`arch_gdb_continue` * This function is called when GDB sends a ``c`` or ``continue`` command to continue code execution. * :c:func:`arch_gdb_step` * This function is called when GDB sends a ``si`` or ``stepi`` command to execute one machine instruction, before returning to GDB prompt. * Hardware register read/write functions: * Since the GDB stub is running on the target, manipulation of hardware registers need to cached to avoid affecting the execution of GDB stub. Think of it as context switching, where the execution context is changed to the GDB stub. So that the register values of the running thread before context switch need to be stored. Manipulation of register values must only be done to this cached copy. The updated values will then be written to hardware registers before switching back to the previous running thread. * :c:func:`arch_gdb_reg_readall` * This collects all hardware register values that would appear in a ``g``/``G`` packets which will be sent back to GDB. The format of the G-packet is architecture specific. Consult GDB on what is expected. * Note that, for most architectures, a valid G-packet must be returned and sent to GDB. If a packet without incorrect length is sent to GDB, GDB will abort the debugging session. * :c:func:`arch_gdb_reg_writeall` * This takes a G-packet sent by GDB and populates the hardware registers with values from the G-packet. * :c:func:`arch_gdb_reg_readone` * This reads the value of one hardware register and sends the result to GDB. * :c:func:`arch_gdb_reg_writeone` * This writes the value of one hardware register received from GDB. * Breakpoints: * :c:func:`arch_gdb_add_breakpoint` and :c:func:`arch_gdb_remove_breakpoint` * GDB may decide to use software breakpoints which modifies the memory at the breakpoint locations to replace the instruction with software breakpoint or trap instructions. GDB will then restore the memory content once execution reaches the breakpoints. GDB supports this by default and there is usually no need to handle software breakpoints in the architecture code (where breakpoint type is ``0``). * Hardware breakpoints (type ``1``) are required if the code is in ROM or flash that cannot be modified at runtime. Consult the architecture datasheet on how to enable hardware breakpoints. * If hardware breakpoints are not supported by the architecture, there is no need to implement these in architecture code. GDB will then rely on software breakpoints. #. For architecture where certain memory regions are not accessible, an array named :c:var:`gdb_mem_region_array` of type :c:struct:`gdb_mem_region` needs to be defined to specify regions that are accessible. For each array item: * :c:member:`gdb_mem_region.start` specifies the start of a memory region. * :c:member:`gdb_mem_region.end` specifies the end of a memory region. * :c:member:`gdb_mem_region.attributes` specifies the permission of a memory region. * :c:macro:`GDB_MEM_REGION_RO`: region is read-only. * :c:macro:`GDB_MEM_REGION_RW`: region is read-write. * :c:member:`gdb_mem_region.alignment` specifies read/write alignment of a memory region. Use ``0`` if there is no alignment requirement and read/write can be done byte-by-byte. API Reference ************* Timing ====== .. doxygengroup:: arch-timing Threads ======= .. doxygengroup:: arch-threads .. doxygengroup:: arch-tls Power Management ================ .. doxygengroup:: arch-pm Symmetric Multi-Processing ========================== .. doxygengroup:: arch-smp Interrupts ========== .. doxygengroup:: arch-irq Userspace ========= .. doxygengroup:: arch-userspace Memory Management ================= .. doxygengroup:: arch-mmu Miscellaneous Architecture APIs =============================== .. doxygengroup:: arch-misc GDB Stub APIs ============= .. doxygengroup:: arch-gdbstub ```
/content/code_sandbox/doc/hardware/porting/arch.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
9,382
```restructuredtext .. _board_porting_guide: Board Porting Guide ################### To add Zephyr support for a new :term:`board`, you at least need a *board directory* with various files in it. Files in the board directory inherit support for at least one SoC and all of its features. Therefore, Zephyr must support your :term:`SoC` as well. .. _hw_model_v2: Transition to the current hardware model **************************************** Shortly after Zephyr 3.6.0 was released, a new hardware model was introduced to Zephyr. This new model overhauls the way both SoCs and boards are named and defined, and adds support for features that had been identified as important over the years. Among them: - Support for multi-core, multi-arch AMP (Asymmetrical Multi Processing) SoCs - Support for multi-SoC boards - Support for reusing the SoC and board Kconfig trees outside of the Zephyr build system - Support for advanced use cases with :ref:`sysbuild` - Removal of all existing arbitrary and inconsistent uses of Kconfig and folder names All the documentation in this page refers to the current hardware model. Please refer to the documentation in Zephyr v3.6.0 (or earlier) for information on the previous, now obsolete, hardware model. More information about the rationale, development and concepts behind the new model can be found in the :github:`original issue <51831>`, the :github:`original Pull Request <50305>` and, for a complete set of changes introduced, the `hardware model v2 commit`_. Some non-critical features, enhancements and improvements of the new hardware model are still in development. Check the :github:`hardware model v2 enhancements issue <69546>` for a complete list. The transition from the previous hardware model to the current one (commonly referred to as "hardware model v2") requires modifications to all existing board and SoC definitions. A decision was made not to provide direct backwards compatibility for the previous model, which leaves users transitioning from a previous version of Zephyr to one including the new model (v3.7.0 and onwards) with two options if they have an out-of-tree board (or SoC): #. Convert the out-of-tree board to the current hardware model (recommended) #. Take the SoC definition from Zephyr v3.6.0 and copy it to your downstream repository (ensuring that the build system can find it via a :ref:`zephyr module <modules>` or ``SOC_ROOT``). This will allow your board, defined in the previous hardware model, to continue to work When converting your board from the previous to the current hardware model, we recommend first reading through this page to understand the model in detail. You can then use the `example-application conversion Pull Request`_ as an example on how to port a simple board. Additionally, a `conversion script`_ is available and works reliably in many cases (though multi-core SoCs may not be handled entirely). Finally, the `hardware model v2 commit`_ contains the full conversion of all existing boards from the old to the current model, so you can use it as a complete conversion reference. .. _hardware model v2 commit: path_to_url .. _example-application conversion Pull Request: path_to_url .. _conversion script: path_to_url .. _hw_support_hierarchy: Hardware support hierarchy ************************** Zephyr's hardware support is based on a series of hierarchical abstractions. Primarily, each :term:`board` has one or more :term:`SoC`. Each SoC can be optionally classed into an :term:`SoC series`, which in turn may optionally belong to an :term:`SoC family`. Each SoC has one or more :term:`CPU cluster`, each containing one or more :term:`CPU core` of a particular :term:`architecture`. You can visualize the hierarchy in the diagram below: .. figure:: board/hierarchy.png :width: 500px :align: center :alt: Hardware support Hierarchy Hardware support Hierarchy Below are some examples of the hierarchy described in this section, in the form of a :term:`board` per row with its corresponding hierarchy entries. Notice how the :term:`SoC series` and :term:`SoC family` levels are not always used. .. table:: +--------------------------------------------+--------------------------+-------------+--------------------+--------------------+----------------+----------------------+ | :term:`board name` | :term:`board qualifiers` | :term:`SoC` | :term:`SoC Series` | :term:`SoC family` | CPU core | :term:`architecture` | +============================================+==========================+=============+====================+====================+================+======================+ | :ref:`nrf52dk <nrf52dk_nrf52832>` | nrf52832 | nRF52832 | nRF52 | Nordic nRF | Arm Cortex-M4 | ARMv7-M | +--------------------------------------------+--------------------------+-------------+--------------------+--------------------+----------------+----------------------+ | :ref:`frdm_k64f <frdm_k64f>` | mk64f12 | MK64F12 | Kinetis K6x | NXP Kinetis | Arm Cortex-M4 | ARMv7-M | +--------------------------------------------+--------------------------+-------------+--------------------+--------------------+----------------+----------------------+ | :ref:`rv32m1_vega <rv32m1_vega>` | openisa_rv32m1/ri5cy | RV32M1 | (Not used) | (Not used) | RI5CY | RISC-V RV32 | +--------------------------------------------+--------------------------+-------------+--------------------+--------------------+----------------+----------------------+ | :ref:`nrf5340dk <nrf5340dk_nrf5340>` | nrf5340/cpuapp | nRF5340 | nRF53 | Nordic nRF | Arm Cortex-M33 | ARMv8-M | | +--------------------------+-------------+--------------------+--------------------+----------------+----------------------+ | | nrf5340/cpunet | nRF5340 | nRF53 | Nordic nRF | Arm Cortex-M33 | ARMv8-M | +--------------------------------------------+--------------------------+-------------+--------------------+--------------------+----------------+----------------------+ | :ref:`mimx8mp_evk <imx8mp_evk>` | mimx8ml8/a53 | i.MX8M Plus | i.MX8M | NXP i.MX | Arm Cortex-A53 | ARMv8-A | | +--------------------------+-------------+--------------------+--------------------+----------------+----------------------+ | | mimx8ml8/m7 | i.MX8M Plus | i.MX8M | NXP i.MX | Arm Cortex-M7 | ARMv7-M | | +--------------------------+-------------+--------------------+--------------------+----------------+----------------------+ | | mimx8ml8/adsp | i.MX8M Plus | i.MX8M | NXP i.MX | Cadence HIFI4 | Xtensa LX6 | +--------------------------------------------+--------------------------+-------------+--------------------+--------------------+----------------+----------------------+ Additional details about terminology can be found in the next section. .. _board_terminology: Board terminology ***************** The previous section introduced the hierarchical manner in which Zephyr classifies and implements hardware support. This section focuses on the terminology used around hardware support, and in particular when defining and working with boards and SoCs. The overall set of terms used around the concept of board in Zephyr is depicted in the image below, which uses the :ref:`bl5340_dvk` board as reference. .. figure:: board/board-terminology.svg :width: 500px :align: center :alt: Board terminology diagram Board terminology diagram The diagram shows the different terms that are used to describe boards: - The :term:`board name`: ``bl5340_dvk`` - The optional :term:`board revision`: ``1.2.0`` - The :term:`board qualifiers`, that optionally describe the :term:`SoC`, :term:`CPU cluster` and :term:`variant`: ``nrf5340/cpuapp/ns`` - The :term:`board target`, which uniquely identifies a combination of the above and can be used to specify the hardware to build for when using the tooling provided by Zephyr: ``bl5340_dvk@1.2.0/nrf5340/cpuapp/ns`` Formally this can also be seen as :samp:`{board name}[@{revision}][/{board qualifiers}]`, which can be extended to :samp:`{board name}[@{revision}][/{SoC}[/{CPU cluster}][/{variant}]]`. If a board contains only one single-core SoC, then the SoC can be omitted from the board target. This implies that if the board does not define any board qualifiers, the board name can be used as a board target. Conversely, if board qualifiers are part of the board definition, then the SoC can be omitted by leaving it out but including the corresponding forward-slashes: ``//``. Continuing with the example above, The board :ref:`bl5340_dvk` is a single SoC board where the SoC defines two CPU clusters: ``cpuapp`` and ``cpunet``. One of the CPU clusters, ``cpuapp``, additionally defines a non-secure board variant, ``ns``. The board qualifiers ``nrf5340/cpuapp/ns`` can be read as: - ``nrf5340``: The SoC, which is a Nordic nRF5340 dual-core SoC - ``cpuapp``: The CPU cluster ``cpuapp``, which consists of a single Cortex-M33 CPU core. The number of cores in a CPU cluster cannot be determined from the board qualifiers. - ``ns``: a variant, in this case ``ns`` is a common variant name is Zephyr denoting a non-secure build for boards supporting :ref:`tfm`. Not all SoCs define CPU clusters or variants. For example a simple board like the :ref:`thingy52_nrf52832` contains a single SoC with no CPU clusters and no variants. For ``thingy52`` the board target ``thingy52/nrf52832`` can be read as: - ``thingy52``: board name. - ``nrf52832``: The board qualifiers, in this case identical to the SoC, which is a Nordic nRF52832. Make sure your SoC is supported ******************************* Start by making sure your SoC is supported by Zephyr. If it is, it's time to :ref:`create-your-board-directory`. If you don't know, try: - checking :ref:`boards` for names that look relevant, and reading individual board documentation to find out for sure. - asking your SoC vendor If you need to add a SoC, CPU cluster, or even architecture support, this is the wrong page, but here is some general advice. Architecture ============ See :ref:`architecture_porting_guide`. CPU Core ======== CPU core support files go in ``core`` subdirectories under :zephyr_file:`arch`, e.g. :zephyr_file:`arch/x86/core`. See :ref:`gs_toolchain` for information about toolchains (compiler, linker, etc.) supported by Zephyr. If you need to support a new toolchain, :ref:`build_overview` is a good place to start learning about the build system. Please reach out to the community if you are looking for advice or want to collaborate on toolchain support. SoC === Zephyr SoC support files are in architecture-specific subdirectories of :zephyr_file:`soc`. They are generally grouped by SoC family. When adding a new SoC family or series for a vendor that already has SoC support within Zephyr, please try to extract common functionality into shared files to avoid duplication. If there is no support for your vendor yet, you can add it in a new directory ``zephyr/soc/<VENDOR>/<YOUR-SOC>``; please use self-explanatory directory names. .. _create-your-board-directory: Create your board directory *************************** Once you've found an existing board that uses your SoC, you can usually start by copy/pasting its board directory and changing its contents for your hardware. You need to give your board a unique name. Run ``west boards`` for a list of names that are already taken, and pick something new. Let's say your board is called ``plank`` (please don't actually use that name). Start by creating the board directory ``zephyr/boards/<VENDOR>/plank``, where ``<VENDOR>`` is your vendor subdirectory. (You don't have to put your board directory in the zephyr repository, but it's the easiest way to get started. See :ref:`custom_board_definition` for documentation on moving your board directory to a separate repository once it's working.) .. note:: A ``<VENDOR>`` subdirectory is mandatory if contributing your board to Zephyr, but if your board is placed in a local repo, then any folder structure under ``<your-repo>/boards`` is permitted. If the vendor is defined in the list in :zephyr_file:`dts/bindings/vendor-prefixes.txt` then you must use that vendor prefix as ``<VENDOR>``. ``others`` may be used as vendor prefix if the vendor is not defined. .. note:: The board directory name does not need to match the name of the board. Multiple boards can even defined be in one directory. Your board directory should look like this: .. code-block:: none boards/<VENDOR>/plank board.yml board.cmake CMakeLists.txt doc plank.png index.rst Kconfig.plank Kconfig.defconfig plank_defconfig plank_<qualifiers>_defconfig plank.dts plank_<qualifiers>.dts plank.yaml Replace ``plank`` with your board's name, of course. The mandatory files are: #. :file:`board.yml`: a YAML file describing the high-level meta data of the boards such as the boards names, their SoCs, and variants. CPU clusters for multi-core SoCs are not described in this file as they are inherited from the SoC's YAML description. #. :file:`plank.dts` or :file:`plank_<qualifiers>.dts`: a hardware description in :ref:`devicetree <dt-guide>` format. This declares your SoC, connectors, and any other hardware components such as LEDs, buttons, sensors, or communication peripherals (USB, BLE controller, etc). #. :file:`Kconfig.plank`: the base software configuration for selecting SoC and other board and SoC related settings. Kconfig settings outside of the board and SoC tree must not be selected. To select general Zephyr Kconfig settings the :file:`Kconfig` file must be used. The optional files are: - :file:`Kconfig`, :file:`Kconfig.defconfig` software configuration in :ref:`kconfig` formats. This provides default settings for software features and peripheral drivers. - :file:`plank_defconfig` and :file:`plank_<qualifiers>_defconfig`: software configuration in Kconfig ``.conf`` format. - :file:`board.cmake`: used for :ref:`flash-and-debug-support` - :file:`CMakeLists.txt`: if you need to add additional source files to your build. - :file:`doc/index.rst`, :file:`doc/plank.png`: documentation for and a picture of your board. You only need this if you're :ref:`contributing-your-board` to Zephyr. - :file:`plank.yaml`: a YAML file with miscellaneous metadata used by the :ref:`twister_script`. Board qualifiers of the form ``<soc>/<cpucluster>/<variant>`` are normalized so that ``/`` is replaced with ``_`` when used for filenames, for example: ``soc1/foo`` becomes ``soc1_foo`` when used in filenames. .. _board_description: Write your board YAML ********************* The board YAML file describes the board at a high level. This includes the SoC, board variants, and board revisions. Detailed configurations, such as hardware description and configuration are done in devicetree and Kconfig. The skeleton of the board YAML file is: .. code-block:: yaml board: name: <board-name> vendor: <board-vendor> revision: format: <major.minor.patch|letter|number|custom> default: <default-revision-value> exact: <true|false> revisions: - name: <revA> - name: <revB> ... socs: - name: <soc-1> variants: - name: <variant-1> - name: <variant-2> variants: - name: <sub-variant-2-1> ... - name: <soc-2> ... It is possible to have multiple boards located in the board folder. If multiple boards are placed in the same board folder, then the file :file:`board.yml` must describe those in a list as: .. code-block:: yaml boards: - name: <board-name-1> vendor: <board-vendor> ... - name: <board-name-2> vendor: <board-vendor> ... ... .. _default_board_configuration: Write your devicetree ********************* The devicetree file :file:`boards/<vendor>/plank/plank.dts` or :file:`boards/<vendor>/plank/plank_<qualifiers>.dts` describes your board hardware in the Devicetree Source (DTS) format (as usual, change ``plank`` to your board's name). If you're new to devicetree, see :ref:`devicetree-intro`. In general, :file:`plank.dts` should look like this: .. code-block:: devicetree /dts-v1/; #include <your_soc_vendor/your_soc.dtsi> / { model = "A human readable name"; compatible = "yourcompany,plank"; chosen { zephyr,console = &your_uart_console; zephyr,sram = &your_memory_node; /* other chosen settings for your hardware */ }; /* * Your board-specific hardware: buttons, LEDs, sensors, etc. */ leds { compatible = "gpio-leds"; led0: led_0 { gpios = < /* GPIO your LED is hooked up to */ >; label = "LED 0"; }; /* ... other LEDs ... */ }; buttons { compatible = "gpio-keys"; /* ... your button definitions ... */ }; /* These aliases are provided for compatibility with samples */ aliases { led0 = &led0; /* now you support the blinky sample! */ /* other aliases go here */ }; }; &some_peripheral_you_want_to_enable { /* like a GPIO or SPI controller */ status = "okay"; }; &another_peripheral_you_want { status = "okay"; }; Only one ``.dts`` file will be used, and the most specific file which exists will be used. This means that if both :file:`plank.dts` and :file:`plank_soc1_foo.dts` exist, then when building for ``plank`` / ``plank/soc1``, then :file:`plank.dts` is used. When building for ``plank//foo`` / ``plank/soc1/foo`` the :file:`plank_soc1_foo.dts` is used. This allows board maintainers to write a base devicetree file for the board or write specific devicetree files for a given board's SoC or variant. If you're in a hurry, simple hardware can usually be supported by copy/paste followed by trial and error. If you want to understand details, you will need to read the rest of the devicetree documentation and the devicetree specification. .. _dt_k6x_example: Example: FRDM-K64F and Hexiwear K64 =================================== .. Give the filenames instead of the full paths below, as it's easier to read. The cramped 'foo.dts<path>' style avoids extra spaces before commas. This section contains concrete examples related to writing your board's devicetree. The FRDM-K64F and Hexiwear K64 board devicetrees are defined in :zephyr_file:`frdm_k64fs.dts <boards/nxp/frdm_k64f/frdm_k64f.dts>` and :zephyr_file:`hexiwear_k64.dts <boards/nxp/hexiwear/hexiwear_mk64f12.dts>` respectively. Both boards have NXP SoCs from the same Kinetis SoC family, the K6X. Common devicetree definitions for K6X are stored in :zephyr_file:`nxp_k6x.dtsi <dts/arm/nxp/nxp_k6x.dtsi>`, which is included by both board :file:`.dts` files. :zephyr_file:`nxp_k6x.dtsi<dts/arm/nxp/nxp_k6x.dtsi>` in turn includes :zephyr_file:`armv7-m.dtsi<dts/arm/armv7-m.dtsi>`, which has common definitions for Arm v7-M cores. Since :zephyr_file:`nxp_k6x.dtsi<dts/arm/nxp/nxp_k6x.dtsi>` is meant to be generic across K6X-based boards, it leaves many devices disabled by default using ``status`` properties. For example, there is a CAN controller defined as follows (with unimportant parts skipped): .. code-block:: devicetree can0: can@40024000 { ... status = "disabled"; ... }; It is up to the board :file:`.dts` or application overlay files to enable these devices as desired, by setting ``status = "okay"``. The board :file:`.dts` files are also responsible for any board-specific configuration of the device, such as adding nodes for on-board sensors, LEDs, buttons, etc. For example, FRDM-K64 (but not Hexiwear K64) :file:`.dts` enables the CAN controller and sets the bus speed: .. code-block:: devicetree &can0 { status = "okay"; }; The ``&can0 { ... };`` syntax adds/overrides properties on the node with label ``can0``, i.e. the ``can@4002400`` node defined in the :file:`.dtsi` file. Other examples of board-specific customization is pointing properties in ``aliases`` and ``chosen`` to the right nodes (see :ref:`dt-alias-chosen`), and making GPIO/pinmux assignments. .. _board_kconfig_files: Write Kconfig files ******************* Zephyr uses the Kconfig language to configure software features. Your board needs to provide some Kconfig settings before you can compile a Zephyr application for it. Setting Kconfig configuration values is documented in detail in :ref:`setting_configuration_values`. There is one mandatory Kconfig file in the board directory, and several optional files for a board named ``plank``: .. code-block:: none boards/<vendor>/plank Kconfig Kconfig.plank Kconfig.defconfig plank_defconfig plank_<qualifiers>_defconfig :file:`Kconfig.plank` A shared Kconfig file which can be sourced both in Zephyr Kconfig and sysbuild Kconfig trees. This file selects the SoC in the Kconfig tree and potential other SoC related Kconfig settings. This file must not select anything outside the re-usable Kconfig board and SoC trees. A :file:`Kconfig.plank` may look like this: .. code-block:: kconfig config BOARD_PLANK select SOC_SOC1 The Kconfig symbols :samp:`BOARD_{board}` and :samp:`BOARD_{normalized_board_target}` are constructed by the build system, therefore no type shall be defined in above code snippet. :file:`Kconfig` Included by :zephyr_file:`boards/Kconfig`. This file can add Kconfig settings which are specific to the current board. Not all boards have a :file:`Kconfig` file. A board specific setting should be defining a custom setting and usually with a prompt, like this: .. code-block:: kconfig config BOARD_FEATURE bool "Board specific feature" If the setting name is identical to an existing Kconfig setting in Zephyr and only modifies the default value of said setting, then :file:`Kconfig.defconfig` should be used instead. :file:`Kconfig.defconfig` Board-specific default values for Kconfig options. Not all boards have a :file:`Kconfig.defconfig` file. The entire file should be inside an ``if BOARD_PLANK`` / ``endif`` pair of lines, like this: .. code-block:: kconfig if BOARD_PLANK config FOO default y if NETWORKING config SOC_ETHERNET_DRIVER default y endif # NETWORKING endif # BOARD_PLANK :file:`plank_defconfig` / :file:`plank_<qualifiers>_defconfig` A Kconfig fragment that is merged as-is into the final build directory :file:`.config` whenever an application is compiled for your board. If both the common :file:`plank_defconfig` file and one or more board qualifiers specific :file:`plank_<qualifiers>_defconfig` files exist, then all matching files will be used. This allows you to place configuration which is common for all board SoCs, CPU clusters, and board variants in the base :file:`plank_defconfig` and only place the adjustments specific for a given SoC or board variant in the :file:`plank_<qualifiers>_defconfig`. The ``_defconfig`` should contain mandatory settings for your system clock, console, etc. The results are architecture-specific, but typically look something like this: .. code-block:: cfg CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC=120000000 # set up your clock, etc CONFIG_SERIAL=y :file:`plank_x_y_z_defconfig` / :file:`plank_<qualifiers>_x_y_z_defconfig` A Kconfig fragment that is merged as-is into the final build directory :file:`.config` whenever an application is compiled for your board revision ``x.y.z``. Build, test, and fix ******************** Now it's time to build and test the application(s) you want to run on your board until you're satisfied. For example: .. code-block:: console west build -b plank samples/hello_world west flash For ``west flash`` to work, see :ref:`flash-and-debug-support` below. You can also just flash :file:`build/zephyr/zephyr.elf`, :file:`zephyr.hex`, or :file:`zephyr.bin` with any other tools you prefer. .. _porting-general-recommendations: General recommendations *********************** For consistency and to make it easier for users to build generic applications that are not board specific for your board, please follow these guidelines while porting. - Unless explicitly recommended otherwise by this section, leave peripherals and their drivers disabled by default. - Configure and enable a system clock, along with a tick source. - Provide pin and driver configuration that matches the board's valuable components such as sensors, buttons or LEDs, and communication interfaces such as USB, Ethernet connector, or Bluetooth/Wi-Fi chip. - If your board uses a well-known connector standard (like Arduino, Mikrobus, Grove, or 96Boards connectors), add connector nodes to your DTS and configure pin muxes accordingly. - Configure components that enable the use of these pins, such as configuring an SPI instance to use the usual Arduino SPI pins. - If available, configure and enable a serial output for the console using the ``zephyr,console`` chosen node in the devicetree. - If your board supports networking, configure a default interface. - Enable all GPIO ports connected to peripherals or expansion connectors. - If available, enable pinmux and interrupt controller drivers. - It is recommended to enable the MPU by default, if there is support for it in hardware. For boards with limited memory resources it is acceptable to disable it. When the MPU is enabled, it is recommended to also enable hardware stack protection (CONFIG_HW_STACK_PROTECTION=y) and, thus, allow the kernel to detect stack overflows when the system is running in privileged mode. .. _flash-and-debug-support: Flash and debug support *********************** Zephyr supports :ref:`west-build-flash-debug` via west extension commands. To add ``west flash`` and ``west debug`` support for your board, you need to create a :file:`board.cmake` file in your board directory. This file's job is to configure a "runner" for your board. (There's nothing special you need to do to get ``west build`` support for your board.) "Runners" are Zephyr-specific Python classes that wrap :ref:`flash and debug host tools <flash-debug-host-tools>` and integrate with west and the zephyr build system to support ``west flash`` and related commands. Each runner supports flashing, debugging, or both. You need to configure the arguments to these Python scripts in your :file:`board.cmake` to support those commands like this example :file:`board.cmake`: .. code-block:: cmake board_runner_args(jlink "--device=nrf52" "--speed=4000") board_runner_args(pyocd "--target=nrf52" "--frequency=4000000") include(${ZEPHYR_BASE}/boards/common/nrfjprog.board.cmake) include(${ZEPHYR_BASE}/boards/common/jlink.board.cmake) include(${ZEPHYR_BASE}/boards/common/pyocd.board.cmake) This example configures the ``nrfjprog``, ``jlink``, and ``pyocd`` runners. .. warning:: Runners usually have names which match the tools they wrap, so the ``jlink`` runner wraps Segger's J-Link tools, and so on. But the runner command line options like ``--speed`` etc. are specific to the Python scripts. .. note:: Runners and board configuration should be created without being targeted to a single operating system if the tool supports multiple operating systems, nor should it rely upon special system setup/configuration. For example; do not assume that a user will have prior knowledge/configuration or (if using Linux) special udev rules installed, do not assume one specific ``/dev/X`` device for all platforms as this will not be compatible with Windows or macOS, and allow for overriding of the selected device so that multiple boards can be connected to a single system and flashed/debugged at the choice of the user. For more details: - Run ``west flash --context`` to see a list of available runners which support flashing, and ``west flash --context -r <RUNNER>`` to view the specific options available for an individual runner. - Run ``west debug --context`` and ``west debug --context <RUNNER>`` to get the same output for runners which support debugging. - Run ``west flash --help`` and ``west debug --help`` for top-level options for flashing and debugging. - See :ref:`west-runner` for Python APIs. - Look for :file:`board.cmake` files for other boards similar to your own for more examples. To see what a ``west flash`` or ``west debug`` command is doing exactly, run it in verbose mode: .. code-block:: sh west --verbose flash west --verbose debug Verbose mode prints any host tool commands the runner uses. The order of the ``include()`` calls in your :file:`board.cmake` matters. The first ``include`` sets the default runner if it's not already set. For example, including ``nrfjprog.board.cmake`` first means that ``nrfjprog`` is the default flash runner for this board. Since ``nrfjprog`` does not support debugging, ``jlink`` is the default debug runner. .. _porting_board_revisions: Multiple board revisions ************************ See :ref:`application_board_version` for basics on this feature from the user perspective. Board revisions are described in the ``revision`` entry of the :file:`board.yml`. .. code-block:: yaml board: revision: format: <major.minor.patch|letter|number|custom> default: <default-revision-value> exact: <true|false> revisions: - name: <revA> - name: <revB> Zephyr natively supports the following revision formats: - ``major.minor.patch``: match a three digit revision, such as ``1.2.3``. - ``number``: matches integer revisions - ``letter``: matches single letter revisions from ``A`` to ``Z`` only .. _board_fuzzy_revision_matching: Fuzzy revision matching ======================= Fuzzy revision matching is enabled per default. If the user selects a revision between those available, the closest revision number that is not larger than the user's choice is used. For example, if the board ``plank`` defines revisions ``0.5.0``, and ``1.5.0`` and the user builds for ``plank@0.7.0``, the build system will target revision ``0.5.0``. The build system will print this at CMake configuration time: .. code-block:: console -- Board: plank, Revision: 0.7.0 (Active: 0.5.0) This allows you to only create revision configuration files for board revision numbers that introduce incompatible changes. Similar for ``letter`` where revision ``A``, ``D``, and ``F`` could be defined and the user builds for ``plank@E``, the build system will target revision ``D`` . Exact revision matching ======================= Exact revision matching is enabled when ``exact: true`` is specified in the revision section in :file:`board.yml`. When exact is defined then building for ``plank@0.7.0`` in the above example will result in the following error message: .. code-block:: console Board revision `0.7.0` not found. Please specify a valid board revision. Board revision configuration adjustment ======================================= When the user builds for board ``plank@<revision>`` it is possible to make adjustments to the board's normal configuration. As described in the :ref:`default_board_configuration` and :ref:`board_kconfig_files` sections the board default configuration is created from the files :file:`<board>.dts` / :file:`<board>_<qualifiers>.dts` and :file:`<board>_defconfig` / :file:`<board>_<qualifiers>_defconfig`. When building for a specific board revision, the above files are used as a starting point and the following board files will be used in addition: - :file:`<board>_<qualifiers>_<revision>_defconfig`: a specific revision defconfig which is only used for the board and SOC / variants identified by ``<board>_<qualifiers>``. - :file:`<board>_<revision>_defconfig`: a specific revision defconfig which is used for the board regardless of the SOC / variants. - :file:`<board>_<qualifiers>_<revision>.overlay`: a specific revision dts overlay which is only used for the board and SOC / variants identified by ``<board>_<qualifiers>``. - :file:`<board>_<revision>.overlay`: a specific revision dts overlay which is used for the board regardless of the SOC / variants. This split allows boards with multiple SoCs, multi-core SoCs, or variants to place common revision adjustments which apply to all SoCs and variants in a single file, while still providing the ability to place SoC or variant specific adjustments in a dedicated revision file. Using the ``plank`` board from previous sections, then we could have the following revision adjustments: .. code-block:: none boards/zephyr/plank plank_0_5_0_defconfig # Kconfig adjustment for all plank board qualifiers on revision 0.5.0 plank_0_5_0.overlay # DTS overlay for all plank board qualifiers on revision 0.5.0 plank_soc1_foo_1_5_0_defconfig # Kconfig adjustment for plank board when building for soc1 variant foo on revision 1.5.0 Custom revision.cmake files *************************** Some boards may not use board revisions supported natively by Zephyr. For example string revisions. One reason why Zephyr doesn't support string revisions is that strings can take many forms and it's not always clear if the given strings are just strings, such as ``blue``, ``green``, ``red``, etc. or if they provide an order which can be matched against higher or lower revisions, such as ``alpha``, ``beta```, ``gamma``. Due to the sheer number of possibilities with strings, including the possibility of doing regex matches internally, then string revisions must be done using ``custom`` revision type. To indicate to the build system that ``custom`` revisions are used, the format field in the ``revision`` section of the :file:`board.yml` must be written as: .. code-block:: yaml board: revision: format: custom When using custom revisions then a :file:`revision.cmake` must be created in the board directory. The :file:`revision.cmake` will be included by the build system when building for the board and it is the responsibility of the file to validate the revision specified by the user. The :makevar:`BOARD_REVISION` variable holds the revision value specified by the user. To signal to the build system that it should use a different revision than the one specified by the user, :file:`revision.cmake` can set the variable ``ACTIVE_BOARD_REVISION`` to the revision to use instead. The corresponding Kconfig files and devicetree overlays must be named :file:`<board>_<ACTIVE_BOARD_REVISION>_defconfig` and :file:`<board>_<ACTIVE_BOARD_REVISION>.overlay`. .. _contributing-your-board: Contributing your board *********************** If you want to contribute your board to Zephyr, first -- thanks! There are some extra things you'll need to do: #. Make sure you've followed all the :ref:`porting-general-recommendations`. They are requirements for boards included with Zephyr. #. Add documentation for your board using the template file :zephyr_file:`doc/templates/board.tmpl`. See :ref:`zephyr_doc` for information on how to build your documentation before submitting your pull request. #. Prepare a pull request adding your board which follows the :ref:`contribute_guidelines`. Board extensions **************** Boards already supported by Zephyr can be extended by downstream users, such as ``example-application`` or vendor SDKs. In some situations, certain hardware description or :ref:`choices <devicetree-chosen-nodes>` can not be added in the upstream Zephyr repository, but they can be in a downstream project, where custom bindings or driver classes can also be created. This feature may also be useful in development phases, when the board skeleton lives upstream, but other features are developed in a downstream module. Board extensions are board fragments that can be present in an out-of-tree board root folder, under ``${BOARD_ROOT}/boards/extensions``. Here is an example structure of an extension for the ``plank`` board and its revisions: .. code-block:: none boards/extensions/plank plank.conf # optional plank_<revision>.conf # optional plank.overlay # optional plank_<revision>.overlay # optional A board extension directory must follow the naming structure of the original board it extends. It may contain Kconfig fragments and/or devicetree overlays. Extensions are, by default, automatically loaded and applied on top of board files, before anything else. There is no guarantee on which order extensions are applied, in case multiple exist. This feature can be disabled by passing ``-DBOARD_EXTENSIONS=OFF`` when building. Note that board extensions need to follow the :ref:`same guidelines <porting-general-recommendations>` as regular boards. For example, it is wrong to enable extra peripherals or subsystems in a board extension. .. warning:: Board extensions are not allowed in any module referenced in Zephyr's ``west.yml`` manifest file. Any board changes are required to be submitted to the main Zephyr repository. ```
/content/code_sandbox/doc/hardware/porting/board_porting.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
9,208
```restructuredtext .. _shields: Shields ####### Shields, also known as "add-on" or "daughter boards", attach to a board to extend its features and services for easier and modularized prototyping. In Zephyr, the shield feature provides Zephyr-formatted shield descriptions for easier compatibility with applications. Shield porting and configuration ******************************** Shield configuration files are available in the board directory under :zephyr_file:`/boards/shields`: .. code-block:: none boards/shields/<shield> <shield>.overlay Kconfig.shield Kconfig.defconfig These files provides shield configuration as follows: * **<shield>.overlay**: This file provides a shield description in devicetree format that is merged with the board's :ref:`devicetree <dt-guide>` before compilation. * **Kconfig.shield**: This file defines shield Kconfig symbols that will be used for default shield configuration. To ease use with applications, the default shield configuration here should be consistent with those in the :ref:`default_board_configuration`. * **Kconfig.defconfig**: This file defines the default shield configuration. It is made to be consistent with the :ref:`default_board_configuration`. Hence, shield configuration should be done by keeping in mind that features activation is application responsibility. Besides, in order to avoid name conflicts with devices that may be defined at board level, it is advised, specifically for shields devicetree descriptions, to provide a device nodelabel is the form <device>_<shield>, for instance: .. code-block:: devicetree sdhc_myshield: sdhc@1 { reg = <1>; ... }; Adding Source Code ****************** It is possible to add source code to shields, as a way to meet configuration requirements that are specific to the shield (e.g: initialization routines, timing constraints, etc), in order to enable it for proper operation with the different Zephyr components. .. note:: Source code in shields shall not be used for purposes other than the one described above. Generic functionalities that could be reused among shields (and/or targets) shall not be captured here. To effectively incorporate source code: add a :file:`CMakeLists.txt` file, as well as the corresponding source files (referenced in CMake similar to other areas of Zephyr, e.g: boards). Board compatibility ******************* Hardware shield-to-board compatibility depends on the use of well-known connectors used on popular boards (such as Arduino and 96boards). For software compatibility, boards must also provide a configuration matching their supported connectors. This should be done at two different level: * Pinmux: Connector pins should be correctly configured to match shield pins * Devicetree: A board :ref:`devicetree <dt-guide>` file, :file:`BOARD.dts` should define an alternate nodelabel for each connector interface. For example, for Arduino I2C: .. code-block:: devicetree arduino_i2c: &i2c1 {}; Board specific shield configuration ----------------------------------- If modifications are needed to fit a shield to a particular board or board revision, you can override a shield description for a specific board by adding board or board revision overriding files to a shield, as follows: .. code-block:: none boards/shields/<shield> boards <board>_<revision>.overlay <board>.overlay <board>.defconfig <board>_<revision>.conf <board>.conf Shield activation ***************** Activate support for one or more shields by adding the matching ``--shield`` arguments to the west command: .. zephyr-app-commands:: :zephyr-app: your_app :shield: x_nucleo_idb05a1,x_nucleo_iks01a1 :goals: build Alternatively, it could be set by default in a project's CMakeLists.txt: .. code-block:: cmake set(SHIELD x_nucleo_iks01a1) Shield variants *************** Some shields may support several variants or revisions. In that case, it is possible to provide multiple version of the shields description: .. code-block:: none boards/shields/<shield> <shield_v1>.overlay <shield_v1>.defconfig <shield_v2>.overlay <shield_v2>.defconfig In this case, a shield-particular revision name can be used: .. zephyr-app-commands:: :zephyr-app: your_app :shield: shield_v2 :goals: build You can also provide a board-specific configuration to a specific shield revision: .. code-block:: none boards/shields/<shield> <shield_v1>.overlay <shield_v1>.defconfig <shield_v2>.overlay <shield_v2>.defconfig boards <shield_v2> <board>.overlay <board>.defconfig GPIO nexus nodes **************** GPIOs accessed by the shield peripherals must be identified using the shield GPIO abstraction, for example from the ``arduino-header-r3`` compatible. Boards that provide the header must map the header pins to SOC-specific pins. This is accomplished by including a `nexus node`_ that looks like the following into the board devicetree file: .. _nexus node: path_to_url#nexus-nodes-and-specifier-mapping .. code-block:: devicetree arduino_header: connector { compatible = "arduino-header-r3"; #gpio-cells = <2>; gpio-map-mask = <0xffffffff 0xffffffc0>; gpio-map-pass-thru = <0 0x3f>; gpio-map = <0 0 &gpioa 0 0>, /* A0 */ <1 0 &gpioa 1 0>, /* A1 */ <2 0 &gpioa 4 0>, /* A2 */ <3 0 &gpiob 0 0>, /* A3 */ <4 0 &gpioc 1 0>, /* A4 */ <5 0 &gpioc 0 0>, /* A5 */ <6 0 &gpioa 3 0>, /* D0 */ <7 0 &gpioa 2 0>, /* D1 */ <8 0 &gpioa 10 0>, /* D2 */ <9 0 &gpiob 3 0>, /* D3 */ <10 0 &gpiob 5 0>, /* D4 */ <11 0 &gpiob 4 0>, /* D5 */ <12 0 &gpiob 10 0>, /* D6 */ <13 0 &gpioa 8 0>, /* D7 */ <14 0 &gpioa 9 0>, /* D8 */ <15 0 &gpioc 7 0>, /* D9 */ <16 0 &gpiob 6 0>, /* D10 */ <17 0 &gpioa 7 0>, /* D11 */ <18 0 &gpioa 6 0>, /* D12 */ <19 0 &gpioa 5 0>, /* D13 */ <20 0 &gpiob 9 0>, /* D14 */ <21 0 &gpiob 8 0>; /* D15 */ }; This specifies how Arduino pin references like ``<&arduino_header 11 0>`` are converted to SOC gpio pin references like ``<&gpiob 4 0>``. In Zephyr GPIO specifiers generally have two parameters (indicated by ``#gpio-cells = <2>``): the pin number and a set of flags. The low 6 bits of the flags correspond to features that can be configured in devicetree. In some cases it's necessary to use a non-zero flag value to tell the driver how a particular pin behaves, as with: .. code-block:: devicetree drdy-gpios = <&arduino_header 11 GPIO_ACTIVE_LOW>; After preprocessing this becomes ``<&arduino_header 11 1>``. Normally the presence of such a flag would cause the map lookup to fail, because there is no map entry with a non-zero flags value. The ``gpio-map-mask`` property specifies that, for lookup, all bits of the pin and all but the low 6 bits of the flags are used to identify the specifier. Then the ``gpio-map-pass-thru`` specifies that the low 6 bits of the flags are copied over, so the SOC GPIO reference becomes ``<&gpiob 4 1>`` as intended. See `nexus node`_ for more information about this capability. ```
/content/code_sandbox/doc/hardware/porting/shields.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,962
```restructuredtext .. _barriers_api: Barriers API ************ .. doxygengroup:: barrier_apis ```
/content/code_sandbox/doc/hardware/barriers/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
24
```restructuredtext .. _soc_porting_guide: SoC Porting Guide ################### This page describes how to add support for a new :term:`SoC` in Zephyr, be it in the upstream Zephyr project or locally in your own repository. SoC Definitions *************** It is expected that you are familiar with the board concept in Zephyr. A high level overview of the hardware support hierarchy and terms used in the Zephyr documentation can be seen in :ref:`hw_support_hierarchy`. For SoC porting, the most important terms are: - SoC: the exact system on a chip the board's CPU is part of. - SoC series: a group of tightly related SoCs. - SoC family: a wider group of SoCs with similar characteristics. - CPU Cluster: a cluster of one or more CPU cores. - CPU core: a particular CPU instance of a given architecture. - Architecture: an instruction set architecture. Architecture ============ See :ref:`architecture_porting_guide`. Create your SoC directory ************************* Each SoC must have a unique name. Use the official name given by the SoC vendor and check that it's not already in use. In some cases someone else may have contributed a SoC with identical name. If the SoC name is already in use, then you should probably improve the existing SoC instead of creating a new one. The script ``list_hardware`` can be used to retrieve a list of all SoCs known in Zephyr, for example ``./scripts/list_hardware.py --soc-root=. --socs`` from the Zephyr base directory for a list of names that are already in use. Start by creating the directory ``zephyr/soc/<VENDOR>/soc1``, where ``<VENDOR>`` is your vendor subdirectory. .. note:: A ``<VENDOR>`` subdirectory is mandatory if contributing your SoC to Zephyr, but if your SoC is placed in a local repo, then any folder structure under ``<your-repo>/soc`` is permitted. The ``<VENDOR>`` subdirectory must match a vendor defined in the list in :zephyr_file:`dts/bindings/vendor-prefixes.txt`. If the SoC vendor does not have a prefix in that list, then one must be created. .. note:: The SoC directory name does not need to match the name of the SoC. Multiple SoCs can even be defined in one directory. In Zephyr, SoCs are often organized in sub-folders in a common SoC Family or SoC Series tree. Your SoC directory should look like this: .. code-block:: none soc/<VENDOR>/<soc-name> soc.yml soc.h CMakeLists.txt Kconfig Kconfig.soc Kconfig.defconfig Replace ``<soc-name>`` with your SoC's name. The mandatory files are: #. :file:`soc.yml`: a YAML file describing the high-level meta data of the SoC such as: - SoC name: the name of the SoC - CPU clusters: CPU clusters if the SoC contains one or more clusters - SoC series: the SoC series to which the SoC belong - SoC family: the SoC family to which the series belong #. :file:`soc.h`: a header file which can be used to describe or provide configuration macros for the SoC. The :file:`soc.h` will often be included in drivers, sub-systems, boards, and other source code found in Zephyr. #. :file:`Kconfig.soc`: the base SoC configuration which defines a Kconfig SoC symbol in the form of ``config SOC_<soc-name>`` and provides the SoC name to the Kconfig ``SOC`` setting. If the ``soc.yml`` describes a SoC family and series, then those must also be defined in this file. Kconfig settings outside of the SoC tree must not be selected. To select general Zephyr Kconfig settings the :file:`Kconfig` file must be used. #. :file:`CMakeLists.txt`: CMake file loaded by the Zephyr build system. This CMake file can define additional include paths and/or source files to be used when a build targets the SoC. Also the base line linker script to use must be defined. The optional files are: - :file:`Kconfig`, :file:`Kconfig.defconfig` software configuration in :ref:`kconfig` format. These select the architecture and peripherals available. Write your SoC YAML ********************* The SoC YAML file describes the SoC family, SoC series, and SoC at a high level. Detailed configurations, such as hardware description and configuration are done in devicetree and Kconfig. The skeleton of a simple SoC YAML file containing just one SoC is: .. code-block:: yaml socs: - name: <soc1> It is possible to have multiple SoC located in the SoC folder. For example if they belong to a common family or series it is recommended to locate such SoC in a common tree. Multiple SoCs and SoC series in a common folder can be described in the :file:`soc.yml` file as: .. code-block:: yaml family: name: <family-name> series: - name: <series-1-name> socs: - name: <soc1> cpucluster: - name: <coreA> - name: <coreB> ... - name: <soc2> - name: <series-2-name> ... Write your SoC devicetree ************************* SoC devicetree include files are located in the :file:`<zephyr-repo>/dts` folder under a corresponding :file:`<ARCH>/<VENDOR>`. The SoC :file:`dts/<ARCH>/<VENDOR>/<soc>.dtsi` describes your SoC hardware in the Devicetree Source (DTS) format and must be included by any boards which use the SoC. If a highlevel :file:`<arch>.dtsi` file exists, then a good starting point is to include this file in your :file:`<soc>.dtsi`. In general, :file:`<soc>.dtsi` should look like this: .. code-block:: devicetree #include <arch>/<arch>.dtsi / { chosen { /* common chosen settings for your SoC */ }; cpus { #address-cells = <m>; #size-cells = <n>; cpu@0 { device_type = "cpu"; compatible = "<compatibles>"; /* ... your CPU definitions ... */ }; soc { /* Your SoC definitions and peripherals */ /* such as ram, clock, buses, peripherals. */ }; }; .. hint:: It is possible to structure multiple :file:`<VENDOR>/<soc>.dtsi` files in sub-directories for a cleaner file system structure. For example organized pre SoC series, like this: :file:`<VENDOR>/<SERIES>/<soc>.dtsi`. Multiple CPU clusters ===================== Devicetree reflects the hardware. The memory space and peripherals available to one CPU cluster can be very different from another CPU cluster, therefore each CPU cluster will often have its own :file:`.dtsi` file. CPU cluster :file:`.dtsi` files should follow the naming scheme :file:`<soc>_<cluster>.dtsi`. A :file:`<soc>_<cluster>.dtsi` file will look similar to a SoC :file:`.dtsi` without CPU clusters. Write Kconfig files ******************* Zephyr uses the Kconfig language to configure software features. Your SoC needs to provide some Kconfig settings before you can compile a Zephyr application for it. Setting Kconfig configuration values is documented in detail in :ref:`setting_configuration_values`. There is one mandatory Kconfig file in the SoC directory, and two optional files for a SoC: .. code-block:: none soc/<vendor>/<your soc> Kconfig.soc Kconfig Kconfig.defconfig :file:`Kconfig.soc` A shared Kconfig file which can be sourced both in Zephyr Kconfig and sysbuild Kconfig trees. This file selects the SoC family and series in the Kconfig tree and potential other SoC related Kconfig settings. In some cases a SOC_PART_NUMBER. This file must not select anything outside the re-usable Kconfig SoC tree. A :file:`Kconfig.soc` may look like this: .. code-block:: kconfig config SOC_<series name> bool config SOC_<SOC_NAME> bool select SOC_SERIES_<series name> config SOC default "SoC name" if SOC_<SOC_NAME> Notice that ``SOC_NAME`` is a pure upper case version of the SoC name. The Kconfig ``SOC`` setting is globally defined as a string and therefore the :file:`Kconfig.soc` file shall only define the default string value and not the type. Notice that the string value must match the SoC name used in the :file:`soc.yml` file. :file:`Kconfig` Included by :zephyr_file:`soc/Kconfig`. This file can add Kconfig settings which are specific to the current SoC. The :file:`Kconfig` will often indicate given hardware support using a setting of the form ``HAS_<support>``. .. code-block:: kconfig config SOC_<SOC_NAME> select ARM select CPU_HAS_FPU If the setting name is identical to an existing Kconfig setting in Zephyr and only modifies the default value of said setting, then :file:`Kconfig.defconfig` should be used instead. :file:`Kconfig.defconfig` SoC specific default values for Kconfig options. Not all SoCs have a :file:`Kconfig.defconfig` file. The entire file should be inside a pair of ``if SOC_<SOC_NAME>`` / ``endif`` or ``if SOC_SERIES_<SERIES_NAME>`` / ``endif``, like this: .. code-block:: kconfig if SOC_<SOC_NAME> config NUM_IRQS default 32 endif # SOC_<SOC_NAME> Multiple CPU clusters ===================== CPU clusters must provide additional Kconfig settings in the :file:`Kconfig.soc` file. This will usually be in the form of ``SOC_<SOC_NAME>_<CLUSTER>`` so for a given ``soc1`` with two clusters ``clusterA`` and ``clusterB``, then this will look like: SoC's When a SoC defines CPU cluster .. code-block:: kconfig config SOC_SOC1_CLUSTERA bool select SOC_SOC1 config SOC_SOC1_CLUSTERB bool select SOC_SOC1 ```
/content/code_sandbox/doc/hardware/porting/soc_porting.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,444
```restructuredtext .. _hardware_arch_arc_support_status: Zephyr support status on ARC processors ####################################### Overview ******** This page describes current state of Zephyr for ARC processors and some future plans. Please note that * plans are given without exact deadlines * software features require corresponding hardware to be present and configured the proper way * not all the features can be enabled at the same time Support status ************** Legend: **Y** - yes, supported; **N** - no, not supported; **WIP** - Work In Progress; **TBD** - to be decided +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | | **Processor families** | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | | **EM** | **HS3x/4x** | **VPX** | **HS5x** | **HS6x** | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | Port status | upstreamed | upstreamed | upstreamed [#f6]_ | upstreamed | upstreamed | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | **Features** | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | Closely coupled memories (ICCM, DCCM) [#f1]_ | Y | Y | Y | TBD | TBD | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | Execution with caches - Instruction/Data, L1/L2 caches | Y | Y | Y | Y | Y | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | Hardware-assisted unaligned memory access | Y [#f2]_ | Y | Y | Y | Y | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | Regular interrupts with multiple priority levels, direct interrupts | Y | Y | Y | Y | Y | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | Fast interrupts, separate register banks for fast interrupts | Y | Y | TBD | N | N | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | Hardware floating point unit (FPU) | Y | Y | TBD [#f6]_ | TBD | TBD | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | Symmetric multiprocessing (SMP) support, switch-based | N/A | Y | TBD | Y | Y | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | Hardware-assisted stack checking | Y | Y | Y | N | N | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | Hardware-assisted atomic operations | N/A | Y | Y | Y | Y | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | DSP ISA | Y | N [#f3]_ | TBD [#f6]_ | TBD | TBD | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | DSP AGU/XY extensions | Y | N [#f3]_ | N/A | TBD | TBD | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | Userspace | Y | Y | N | TBD | TBD | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | Memory protection unit (MPU) | Y | Y | TBD | N | N | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | Memory management unit (MMU) | N/A | N | TBD | N | N | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | SecureShield | Y | N/A | N/A | N/A | N/A | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | Single-thread kernel support [#f5]_ | Y | Y | Y | Y | Y | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | **Toolchains** | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | GNU (open source GCC-based) | Y | Y | N | Y | Y | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | MetaWare (proprietary Clang-based) | Y | Y | Y | Y | Y | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | **Simulators** | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | QEMU (open source) [#f4]_ | Y | Y | N | Y | Y | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ | nSIM (proprietary, provided by MetaWare Development Tools) | Y | Y | Y | Y | Y | +your_sha256_hash-----+------------+-------------+-------------------+------------+------------+ Notes ***** .. [#f1] usage of CCMs is limited on SMP systems .. [#f2] except the systems with secure features (SecureShield) due to HW limitation .. [#f3] We only support save/restore ACCL/ACCH registers in task's context. Rest of DSP/AGU registers save/restore isn't implemented but kernel itself does not use these registers. This allows single task per core to use DSP/AGU safely. .. [#f4] QEMU doesn't support all the ARC processor's HW features. For the detailed info please check the ARC QEMU documentation .. [#f5] Single-thread kernel is support only for single core targets .. [#f6] currently only ARC VPX scalar port is supported. The support of VPX vector pipeline, VCCM, STU is not included in this port, and require additional development and / or other runtime integration. ```
/content/code_sandbox/doc/hardware/arch/arc-support-status.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,460
```restructuredtext .. _arch: Architecture-related Guides ########################### .. toctree:: :maxdepth: 1 arc-support-status.rst arm_cortex_m.rst risc-v.rst semihost.rst x86.rst xtensa.rst arm-scmi.rst ```
/content/code_sandbox/doc/hardware/arch/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
72
```restructuredtext .. _x86_developer_guide: x86 Developer Guide ################### Overview ******** This page contains information on certain aspects when developing for x86-based platforms. Virtual Memory ************** During very early boot, page tables are loaded so technically the kernel is executing in virtual address space. By default, physical and virtual memory are identity mapped and thus giving the appearance of execution taking place in physical address space. The physical address space is marked by kconfig :kconfig:option:`CONFIG_SRAM_BASE_ADDRESS` and :kconfig:option:`CONFIG_SRAM_SIZE` while the virtual address space is marked by :kconfig:option:`CONFIG_KERNEL_VM_BASE` and :kconfig:option:`CONFIG_KERNEL_VM_SIZE`. Note that :kconfig:option:`CONFIG_SRAM_OFFSET` controls where the Zephyr kernel is being placed in the memory, and its counterpart :kconfig:option:`CONFIG_KERNEL_VM_OFFSET`. Separate Virtual Address Space from Physical Address Space ========================================================== On 32-bit x86, it is possible to have separate physical and virtual address space. Code and data are linked in virtual address space, but are still loaded in physical memory. However, during boot, code and data must be available and also addressable in physical address space before ``vm_enter`` inside :file:`arch/x86/core/ia32/crt0.S`. After ``vm_enter``, code execution is done via virtual addresses and data can be referred via their virtual addresses. This is possible as the page table generation script (:file:`arch/x86/gen_mmu.py`) identity maps the physical addresses at the page directory level, in addition to mapping virtual addresses to the physical memory. Later in the boot process, the entries for identity mapping at the page directory level are cleared in :c:func:`z_x86_mmu_init()`, effectively removing the identity mapping of physical memory. This unmapping must be done for userspace isolation or else they would be able to access restricted memory via physical addresses. Since the identity mapping is done at the page directory level, there is no need to allocate additional space for the page table. However, additional space may still be required for additional page directory table. There are restrictions on where virtual address space can be: - Physical and virtual address spaces must be disjoint. This is required as the entries in page directory table will be cleared. If they are not disjoint, it would clear the entries needed for virtual addresses. - If :kconfig:option:`CONFIG_X86_PAE` is enabled (``=y``), each address space must reside in their own 1GB region, due to each entry of PDP (Page Directory Pointer) covers 1GB of memory. For example: - Assuming ``CONFIG_SRAM_OFFSET`` and ``CONFIG_KERNEL_VM_OFFSET`` are both ``0x0``. - ``CONFIG_SRAM_BASE_ADDRESS == 0x00000000`` and ``CONFIG_KERNEL_VM_BASE = 0x40000000`` is valid, while - ``CONFIG_SRAM_BASE_ADDRESS == 0x00000000`` and ``CONFIG_KERNEL_VM_BASE = 0x20000000`` is not. - If :kconfig:option:`CONFIG_X86_PAE` is disabled (``=n``), each address space must reside in their own 4MB region, due to each entry of PD (Page Directory) covers 4MB of memory. - Both ``CONFIG_SRAM_BASE_ADDRESS`` and ``CONFIG_KERNEL_VM_BASE`` must also align with the starting addresses of targeted regions. Specifying Additional Memory Mappings at Build Time *************************************************** The page table generation script (:file:`arch/x86/gen_mmu.py`) generates the necessary multi-level page tables for code execution and data access using the kernel image produced by the first linker pass. Additional command line arguments can be passed to the script to generate additional memory mappings. This is useful for static mappings and/or device MMIO access during very early boot. To pass extra command line arguments to the script, populate a CMake list named ``X86_EXTRA_GEN_MMU_ARGUMENTS`` in the board configuration file. Here is an example: .. code-block:: cmake set(X86_EXTRA_GEN_MMU_ARGUMENTS --map 0xA0000000,0x2000 --map 0x80000000,0x400000,LWUX,0xB0000000) The argument ``--map`` takes the following value: ``<physical address>,<size>[,<flags:LUWX>[,<virtual address>]]``, where: - ``<physical address>`` is the physical address of the mapping. (Required) - ``<size>`` is the size of the region to be mapped. (Required) - ``<flags>`` is the flag associated with the mapping: (Optional) - ``L``: Large page at the page directory level. - ``U``: Allow userspace access. - ``W``: Read/write. - ``X``: Allow execution. - ``D``: Cache disabled. - Default is small page (4KB), supervisor only, read only, and execution disabled. - ``<virtual address`` is the virtual address of the mapping. (Optional) Note that specifying additional memory mappings requires larger storage space for the pre-allocated page tables (both kernel and per-domain tables). :kconfig:option:`CONFIG_X86_EXTRA_PAGE_TABLE_PAGES` is needed to specify how many more memory pages to be reserved for the page tables. If the needed space is not exactly the same as required space, the ``gen_mmu.py`` script will print out a message indicating what needs to be the value for the kconfig. ```
/content/code_sandbox/doc/hardware/arch/x86.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,231
```restructuredtext Zephyr support status on RISC-V processors ########################################## Overview ******** This page describes current state of Zephyr for RISC-V processors. Currently, there's support for some boards, as well as Qemu support and support for some FPGA implementations such as neorv32 and litex_vexriscv. Zephyr support includes PMP, :ref:`user mode<usermode_api>`, several ISA extensions as well as :ref:`semihosting<semihost_guide>`. User mode and PMP support ************************** When the platform has Physical Memory Protection (PMP) support, enabling it on Zephyr allows user space support and stack protection to be selected. ISA extensions ************** It's possible to set in Zephyr which ISA extensions (RV32/64I(E)MAFD(G)QC) are available on a given platform, by setting the appropriate `RISCV_ISA_*` kconfig. Look at :file:`arch/riscv/Kconfig.isa` for more information. Note that Zephyr SDK toolchain support may not be defined for all combinations. SMP support *********** SMP is supported on RISC-V, but currently only on Qemu platforms. In order to test the SMP support, one can use `qemu_riscv32_smp` or `qemu_riscv64_smp` boards. ```
/content/code_sandbox/doc/hardware/arch/risc-v.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
299
```restructuredtext .. _semihost_guide: Semihosting Guide ################# Overview ******** Semihosting is a mechanism that enables code running on ARM and RISC-V targets to communicate and use the Input/Output facilities on a host computer that is running a debugger or emulator. More complete documentation on the available functionality is available at the `ARM Github documentation`_. The RISC-V functionality borrows from the ARM definitions, as described at the `RISC-V Github documentation`_. File Operations *************** Semihosting enables files on the host computer to be opened, read, and modified by an application. This can be useful when attempting to validate the behaviour of code across datasets that are larger than what can fit into ROM of an emulated platform. File paths can be either absolute, or relative to the directory of the running process. .. code-block:: c const char *path = "./data.bin"; long file_len, bytes_read, fd; uint8_t buffer[16]; /* Open the data file for reading */ fd = semihost_open(path, SEMIHOST_OPEN_RB); if (fd < 0) { return -ENOENT; } /* Read all data from the file */ file_len = semihost_flen(fd); while(file_len > 0) { bytes_read = semihost_read(fd, buffer, MIN(file_len, sizeof(buffer))); if (bytes_read < 0) { break; } /* Process read data */ do_data_processing(buffer, bytes_read); /* Update remaining length */ file_len -= bytes_read; } /* Close the file */ semihost_close(fd); Additional Functionality ######################## Additional functionality is available by running semihosting instructions directly with :c:func:`semihost_exec` with one of the instructions defined in :c:enum:`semihost_instr`. For complete documentation on the required arguments and return codes, see the `ARM Github documentation`_. API Reference ************* .. doxygengroup:: semihost .. _ARM Github documentation: path_to_url .. _RISC-V Github documentation: path_to_url ```
/content/code_sandbox/doc/hardware/arch/semihost.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
463
```restructuredtext .. _xtensa_developer_guide: Xtensa Developer Guide ###################### Overview ******** This page contains information on certain aspects when developing for Xtensa-based platforms. HiFi Audio Engine DSP ********************* The kernel allows threads to use the HiFi Audio Engine DSP registers on boards that support these registers. The kernel only supports the use of the HiFi registers by threads and not ISRs. .. note:: Presently, only the Intel ADSP ACE hardware platforms are configured for HiFi support by default. Concepts ======== The kernel can be configured for an application to leverage the services provided by the Xtensa HiFi Audio Engine DSP. Three modes of operation are supported, which are described below. No HiFi registers mode ---------------------- This mode is used when the application has no threads that use the HiFi registers. It is the kernel's default HiFi services mode. Unshared HiFi registers mode ---------------------------- This mode is used when the application has only a single thread that uses the HiFi registers. The HiFi registers are left unchanged whenever a context switch occurs. .. note:: The behavior is undefined, if two or more threads attempt to use the HiFi registers, as the kernel does not attempt to detect (nor prevent) multiple threads from using these registers. Shared HiFi registers mode -------------------------- This mode is used when the application has two or more threads that use HiFi registers. When enabled, the kernel automatically allows all threads to use the HiFi registers. During each thread context switch, the kernel saves the outgoing thread's HiFi registers and loads the incoming thread's HiFi registers, regardless of whether the thread utilizes them or not. Additional stack space may be required for each thread to account for the extra registers that must be saved. Configuration Options ===================== The unshared HiFi registers mode is selected when configuration option :kconfig:option:`CONFIG_XTENSA_HIFI_SHARING` is disabled but configuration options :kconfig:option:`CONFIG_XTENSA_HIFI3` and/or :kconfig:option:`CONFIG_XTENSA_HIFI4` are enabled. The shared HiFi registers mode is selected when the configuration option :kconfig:option:`CONFIG_XTENSA_HIFI_SHARING` is enabled in addition to configuration options :kconfig:option:`CONFIG_XTENSA_HIFI3` and/or :kconfig:option:`CONFIG_XTENSA_HIFI4`. Threads must have sufficient stack space for saving the HiFi register values during context switches as described above. ```
/content/code_sandbox/doc/hardware/arch/xtensa.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
548
```restructuredtext .. _arm_scmi: ARM System Control and Management Interface ########################################### Overview ******** What is SCMI? ************* System Control and Management Interface (SCMI) is a specification developed by ARM, which describes a set of OS-agnostic software interfaces used to perform system management (e.g: clock control, pinctrl, etc...). Agent, platform, protocol and transport *************************************** The SCMI specification defines **four** key terms, which will also be used throughout this documentation: #. Agent Entity that performs SCMI requests (e.g: gating a clock or configuring a pin). In this context, Zephyr itself is an agent. #. Platform This refers to a set of hardware components that handle the requests from agents and provide the necessary functionality. In some cases, the requests are handled by a firmware, running on a core dedicated to performing system management tasks. #. Protocol A protocol is a set of messages grouped by functionality. Intuitively, a message can be thought of as a remote procedure call. The SCMI specification defines ten standard protocols: #. **Base** (0x10) #. **Power domain management** (0x11) #. **System power management** (0x12) #. **Performance domain management** (0x13) #. **Clock management** (0x14) #. **Sensor management** (0x15) #. **Reset domain management** (0x16) #. **Voltage domain management** (0x17) #. **Power capping and monitoring** (0x18) #. **Pin Control** (0x19) where each of these protocols is identified by an unique protocol ID (listed between brackets). Apart from the standard protocols, the SCMI specification reserves the **0x80-0xFF** protocol ID range for vendor-specific protocols. #. Transport This describes how messages are exchanged between agents and the platform. The communication itself happens through channels. .. note:: A system may have more than one agent. Channels ******** A **channel** is the medium through which agents and the platform exchange messages. The structure of a channel and the way it works is solely dependent on the transport. Each agent has its own distinct set of channels, meaning some channel A cannot be used by two different agents for example. Channels are **bidirectional** (exception: FastChannels), and, depending on which entity initiates the communication, can be one of **two** types: #. A2P (agent to platform) The agent is the initiator/requester. The messages passed through these channels are known as **commands**. #. P2A (platform to agent) The platform is the initiator/requester. Messages ******** The SCMI specification defines **four** types of messages: #. Synchronous These are commands that block until the platform has completed the requested work and are sent over A2P channels. #. Asynchronous For these commands, the platform schedules the requested work to be performed at a later time. As such, they return almost immediately. These commands are sent over A2P channels. #. Delayed response These messages indicate the completion of the work associated with an asynchronous command. These are sent over P2A channels. #. Notification These messages are used to notify agents of events that take place on the platform. These are sent over P2A channels. The Zephyr support for SCMI is based on the documentation provided by ARM: `DEN0056E <path_to_url`_. For more details on the specification, the readers are encouraged to have a look at it. SCMI support in Zephyr ********************** Shared memory and doorbell-based transport ****************************************** This form of transport uses shared memory for reading/writing messages and doorbells for signaling. The interaction with the shared memory area is performed using a driver (:file:`drivers/firmware/scmi/shmem.c`), which offers a set of functions for this exact purpose. Furthermore, signaling is performed using the Zephyr MBOX API (signaling mode only, no message passing). Interacting with the shared memory area and signaling are abstracted by the transport API, which is implemented by the shared memory and doorbell-based transport driver (:file:`drivers/firmware/scmi/mailbox.c`). The steps below exemplify how the communication between the Zephyr agent and the platform may happen using this transport: #. Write message to the shared memory area. #. Zephyr rings request doorbell. If in ``PRE_KERNEL_1`` or ``PRE_KERNEL_2`` phase start polling for reply, otherwise wait for reply doorbell ring. #. Platform reads message from shared memory area, processes it, writes the reply back to the same area and rings the reply doorbell. #. Zephyr reads reply from the shared memory area. In the context of this transport, a channel is comprised of a **single** shared memory area and one or more mailbox channels. This is because users may need/want to use different mailbox channels for the request/reply doorbells. Protocols ********* Currently, Zephyr has support for the following standard protocols: #. **Clock management** #. **Pin Control** Clock management protocol ************************* This protocol is used to perfrom clock management operations. This is done via a driver (:file:`drivers/clock_control/clock_control_arm_scmi.c`), which implements the Zephyr clock control subsytem API. As such, from the user's perspective, using this driver is no different than using any other clock management driver. .. note:: This driver is vendor-agnostic. As such, it may be used on any system that uses SCMI for clock management operations. Pin Control protocol ******************** This protocol is used to perform pin configuration operations. This is done via a set of functions implementing various commands. Currently, the only supported command is ``PINCTRL_SETTINGS_CONFIGURE``. .. note:: The support for this protocol **does not** include a definition for the :code:`pinctrl_configure_pins` function. Each vendor should use their own definition of :code:`pinctrl_configure_pins`, which should call into the SCMI pin control protocol function implementing the ``PINCTRL_SETTINGS_CONFIGURE`` command. Enabling the SCMI support ************************* To use the SCMI support, each vendor is required to add an ``scmi`` DT node (used for transport driver binding) and a ``protocol`` node under the ``scmi`` node for each supported protocol. .. note:: Zephyr has no support for protocol discovery. As such, if users add a DT node for a certain protocol it's assumed the platform supports said protocol. The example below shows how a DT may be configured in order to use the SCMI support. It's assumed that the only protocol required is the clock management protocol. .. code-block:: devicetree #include <mem.h> #define MY_CLOCK_CONSUMER_CLK_ID 123 scmi_res0: memory@cafebabe { /* mandatory to use shared memory driver */ compatible = "arm,scmi-shmem"; reg = <0xcafebabe DT_SIZE_K(1)>; }; scmi { /* compatible for shared memory and doorbell-based transport */ compatible = "arm,scmi"; /* one SCMI channel => A2P/transmit channel */ shmem = <&scmi_res0>; /* two mailbox channels */ mboxes = <&my_mbox_ip 0>, <&my_mbox_ip 1>; mbox-names = "tx", "tx_reply"; scmi_clk: protocol@14 { compatible = "arm,scmi-clock"; /* matches the clock management protocol ID */ reg = <0x14>; /* vendor-agnostic - always 1 */ #clock-cells = <1>; }; }; my_mbox_ip: mailbox@deadbeef { compatible = "vnd,mbox-ip"; reg = <0xdeadbeef DT_SIZE_K(1)>; #mbox-cells = <1>; }; my_clock_consumer_ip: serial@12345678 { compatible = "vnd,consumer-ip"; reg = <0x12345678 DT_SIZE_K(1)>; /* clock ID is vendor specific */ clocks = <&scmi_clk MY_CLOCK_CONSUMER_CLK_ID>; }; Finally, all that's left to do is enable :kconfig:option:`CONFIG_ARM_SCMI`. ```
/content/code_sandbox/doc/hardware/arch/arm-scmi.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,891
```restructuredtext .. _emulators: Zephyr's device emulators/simulators #################################### Overview ======== Zephyr includes in its codebase a set of device emulators/simulators. With this we refer to SW components which are built together with the embedded SW and present themselves as devices of a given class to the rest of the system. These device emulators/simulators can be built for any target which has sufficient RAM and flash, even if some may have extra functionality which is only available in some targets. .. note:: | Zephyr also includes and uses many other types of simulators/emulators, including CPU and platform simulators, radio simulators, and several build targets which allow running the embedded code in the development host. | Some of Zephyr communication controllers/drivers include also either loopback modes or loopback devices. | This page does not cover any of these. .. note:: Drivers which are specific to some platform, like for example the :ref:`native_sim specific drivers <native_sim_peripherals>` which emulate a peripheral class by connecting to host APIs are not covered by this page. Available Emulators =================== **ADC emulator** * A fake driver which pretends to be actual ADC, and can be used for testing higher-level API for ADC devices. * Main Kconfig option: :kconfig:option:`CONFIG_ADC_EMUL` * DT binding: :dtcompatible:`zephyr,adc-emul` **DMA emulator** * Emulated DMA controller * Main Kconfig option: :kconfig:option:`CONFIG_DMA_EMUL` * DT binding: :dtcompatible:`zephyr,dma-emul` **EEPROM emulator** * Emulate an EEPROM on a flash partition * Main Kconfig option: :kconfig:option:`CONFIG_EEPROM_EMULATOR` * DT binding: :dtcompatible:`zephyr,emu-eeprom` .. _emul_eeprom_simu_brief: **EEPROM simulator** * Emulate an EEPROM on RAM * Main Kconfig option: :kconfig:option:`CONFIG_EEPROM_SIMULATOR` * DT binding: :dtcompatible:`zephyr,sim-eeprom` * Note: For :ref:`native targets <native_sim>` it is also possible to keep the content as a file on the host filesystem. **External bus and bus connected peripheral emulators** * :ref:`Documentation <bus_emul>` * Allow emulating external buses like I2C or SPI and peripherals connected to them. .. _emul_flash_simu_brief: **Flash simulator** * Emulate a flash on RAM * Main Kconfig option: :kconfig:option:`CONFIG_FLASH_SIMULATOR` * DT binding: :dtcompatible:`zephyr,sim-flash` * Note: For native targets it is also possible to keep the content as a file on the host filesystem. Check :ref:`the native_sim flash simulator section <nsim_per_flash_simu>`. **GPIO emulator** * Emulated GPIO controllers which can be driven from SW * Main Kconfig option: :kconfig:option:`CONFIG_GPIO_EMUL` * DT binding: :dtcompatible:`zephyr,gpio-emul` **I2C emulator** * Emulated I2C bus. See :ref:`bus emulators <bus_emul>`. * Main Kconfig option: :kconfig:option:`CONFIG_I2C_EMUL` * DT binding: :dtcompatible:`zephyr,i2c-emul-controller` **RTC emulator** * Emulated RTC peripheral. See :ref:`RTC emulated device section <rtc_api_emul_dev>` * Main Kconfig option: :kconfig:option:`CONFIG_RTC_EMUL` * DT binding: :dtcompatible:`zephyr,rtc-emul` **SPI emulator** * Emulated SPI bus. See :ref:`bus emulators <bus_emul>`. * Main Kconfig option: :kconfig:option:`CONFIG_SPI_EMUL` * DT binding: :dtcompatible:`zephyr,spi-emul-controller` **MSPI emulator** * Emulated MSPI bus. See :ref:`bus emulators <bus_emul>`. * Main Kconfig option: :kconfig:option:`CONFIG_MSPI_EMUL` * DT binding: :dtcompatible:`zephyr,mspi-emul-controller` **UART emulator** * Emulated UART bus. See :ref:`bus emulators <bus_emul>`. * Main Kconfig option: :kconfig:option:`CONFIG_UART_EMUL` * DT binding: :dtcompatible:`zephyr,uart-emul` ```
/content/code_sandbox/doc/hardware/emulator/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,014
```restructuredtext .. _bus_emul: External Bus and Bus Connected Peripherals Emulators #################################################### Overview ======== Zephyr supports a simple emulator framework to support testing of external peripheral drivers without requiring real hardware. Emulators are used to emulate external hardware devices, to support testing of various subsystems. For example, it is possible to write an emulator for an I2C compass such that it appears on the I2C bus and can be used just like a real hardware device. Emulators often implement special features for testing. For example a compass may support returning bogus data if the I2C bus speed is too high, or may return invalid measurements if calibration has not yet been completed. This allows for testing that high-level code can handle these situations correctly. Test coverage can therefore approach 100% if all failure conditions are emulated. Concept ======= The diagram below shows application code / high-level tests at the top. This is the ultimate application we want to run. .. figure:: img/arch.svg :align: center :alt: Emulator architecture showing tests, emulators and drivers Below that are peripheral drivers, such as the AT24 EEPROM driver. We can test peripheral drivers using an emulation driver connected via a emulated I2C controller/emulator which passes I2C traffic from the AT24 driver to the AT24 simulator. Separately we can test the STM32 and NXP I2C drivers on real hardware using API tests. These require some sort of device attached to the bus, but with this, we can validate much of the driver functionality. Putting the two together, we can test the application and peripheral code entirely on native_sim. Since we know that the I2C driver on the real hardware works, we should expect the application and peripheral drivers to work on the real hardware also. Using the above framework we can test an entire application (e.g. Embedded Controller) on native_sim using emulators for all non-chip drivers. With this approach we can: * Write individual tests for each driver (green), covering all failure modes, error conditions, etc. * Ensure 100% test coverage for drivers (green) * Write tests for combinations of drivers, such as GPIOs provided by an I2C GPIO expander driver talking over an I2C bus, with the GPIOs controlling a charger. All of this can work in the emulated environment or on real hardware. * Write a complex application that ties together all of these pieces and runs on native_sim. We can develop on a host, use source-level debugging, etc. * Transfer the application to any board which provides the required features (e.g. I2C, enough GPIOs), by adding Kconfig and devicetree fragments. Creating a Device Driver Emulator ================================= The emulator subsystem is modeled on the :ref:`device_model_api`. You create an emulator instance using one of the :c:func:`EMUL_DT_DEFINE()` or :c:func:`EMUL_DT_INST_DEFINE()` APIs. Emulators for peripheral devices reuse the same devicetree node as the real device driver. This means that your emulator defines `DT_DRV_COMPAT` using the same ``compat`` value from the real driver. .. code-block:: C /* From drivers/sensor/bm160/bm160.c */ #define DT_DRV_COMPAT bosch_bmi160 /* From drivers/sensor/bmi160/emul_bmi160.c */ #define DT_DRV_COMPAT bosch_bmi160 The ``EMUL_DT_DEFINE()`` function accepts two API types: #. ``bus_api`` - This points to the API for the upstream bus that the emulator connects to. The ``bus_api`` parameter is required. The supported emulated bus types include I2C, SPI, eSPI, and MSPI. #. ``_backend_api`` - This points to the device-class specific backend API for the emulator. The ``_backend_api`` parameter is optional. The diagram below demonstrates the logical organization of the ``bus_api`` and ``_backend_api`` using the BC1.2 charging detector driver as the model device-class. .. figure:: img/device_class_emulator.svg :align: center :alt: Device class example, demonstrating BC1.2 charging detectors. The real code is shown in green, while the emulator code is shown in yellow. The ``bus_api`` connects the BC1.2 emulators to the ``native_sim`` I2C controller. The real BC1.2 drivers are unchanged and operate exactly as if there was a physical I2C controller present in the system. The ``native_sim`` I2C controller uses the ``bus_api`` to initiate register reads and writes to the emulator. The ``_backend_api`` provides a mechanism for tests to manipulate the emulator out of band. Each device class defines it's own API functions. The backend API functions focus on high-level behavior and do not provide hooks for specific emulators. In the case of the BC1.2 charging detector the backend API provides functions to simulate connecting and disconnecting a charger to the emulated BC1.2 device. Each emulator is responsible for updating the correct vendor specific registers and potentially signalling an interrupt. Example test flow: #. Test registers BC1.2 detection callback using the Zephyr BC1.2 driver API. #. Test connects a charger using the BC1.2 emulator backend. #. Test verifies B1.2 detection callback invoked with correct charger type. #. Test disconnects a charger using the BC1.2 emulator backend. With this architecture, the same test can be used will all supported drivers in the same driver class. Available Emulators =================== Zephyr includes the following emulators: * I2C emulator driver, allowing drivers to be connected to an emulator so that tests can be performed without access to the real hardware * SPI emulator driver, which does the same for SPI * eSPI emulator driver, which does the same for eSPI. The emulator is being developed to support more functionalities. * MSPI emulator driver, allowing drivers to be connected to an emulator so that tests can be performed without access to the real hardware. I2C Emulation features ---------------------- In the binding of the I2C emulated bus, there's a custom property for address based forwarding. Given the following devicetree node: .. code-block:: devicetree i2c0: i2c@100 { status = "okay"; compatible = "zephyr,i2c-emul-controller"; clock-frequency = <I2C_BITRATE_STANDARD>; #address-cells = <1>; #size-cells = <0>; #forward-cells = <1>; reg = <0x100 4>; forwards = <&i2c1 0x20>; }; The final property, ``forwards`` indicates that any read/write requests sent to address ``0x20`` should be sent to ``i2c1`` with the same address. This allows us to test both the controller and the target end of the communication on the same image. .. note:: The ``#forward-cells`` attribute should always be 1. Each entry in the ``forwards`` attribute consists of the phandle followed by the address. In the example above, ``<&i2c1 0x20>`` will forward all read/write operations made to ``i2c0`` at port ``0x20`` to ``i2c1`` on the same port. Since no additional cells are used by the emulated controller, the number of cells should remain 1. Samples ======= Here are some examples present in Zephyr: #. Bosch BMI160 sensor driver connected via both I2C and SPI to an emulator: .. zephyr-app-commands:: :app: tests/drivers/sensor/accel/ :board: native_sim :goals: build #. The same test can be built with a second EEPROM which is an Atmel AT24 EEPROM driver connected via I2C an emulator: .. zephyr-app-commands:: :app: tests/drivers/eeprom/api :board: native_sim :goals: build :gen-args: -DDTC_OVERLAY_FILE=at2x_emul.overlay -DOVERLAY_CONFIG=at2x_emul.conf API Reference ============= .. doxygengroup:: io_emulators ```
/content/code_sandbox/doc/hardware/emulator/bus_emulators.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,843
```restructuredtext .. _connectivity: Connectivity ############ .. toctree:: :maxdepth: 1 bluetooth/index.rst canbus/index.rst networking/index.rst lora_lorawan/index.rst usb/index.rst ```
/content/code_sandbox/doc/connectivity/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
59
```restructuredtext .. _lora_api: .. _lorawan_api: LoRa and LoRaWAN ################ Overview ******** LoRa (abbrev. for Long Range) is a proprietary low-power wireless communication protocol developed by the `Semtech Corporation`_. LoRa acts as the physical layer (PHY) based on the chirp spread spectrum (CSS) modulation technique. LoRaWAN (for Long Range Wide Area Network) defines a networking layer on top of the LoRa PHY. Zephyr provides APIs for LoRa to send raw data packets directly over the wireless interface as well as APIs for LoRaWAN to connect the end device to the internet through a gateway. The Zephyr implementation is based on Semtech's `LoRaMac-node library`_, which is included as a Zephyr module. The LoRaWAN specification is published by the `LoRa Alliance`_. .. _`Semtech Corporation`: path_to_url .. _`LoRaMac-node library`: path_to_url .. _`LoRa Alliance`: path_to_url Configuration Options ********************* LoRa PHY ======== Related configuration options can be found under :zephyr_file:`drivers/lora/Kconfig`. * :kconfig:option:`CONFIG_LORA` * :kconfig:option:`CONFIG_LORA_SHELL` * :kconfig:option:`CONFIG_LORA_INIT_PRIORITY` LoRaWAN ======= Related configuration options can be found under :zephyr_file:`subsys/lorawan/Kconfig`. * :kconfig:option:`CONFIG_LORAWAN` * :kconfig:option:`CONFIG_LORAWAN_SYSTEM_MAX_RX_ERROR` * :kconfig:option:`CONFIG_LORAMAC_REGION_AS923` * :kconfig:option:`CONFIG_LORAMAC_REGION_AU915` * :kconfig:option:`CONFIG_LORAMAC_REGION_CN470` * :kconfig:option:`CONFIG_LORAMAC_REGION_CN779` * :kconfig:option:`CONFIG_LORAMAC_REGION_EU433` * :kconfig:option:`CONFIG_LORAMAC_REGION_EU868` * :kconfig:option:`CONFIG_LORAMAC_REGION_KR920` * :kconfig:option:`CONFIG_LORAMAC_REGION_IN865` * :kconfig:option:`CONFIG_LORAMAC_REGION_US915` * :kconfig:option:`CONFIG_LORAMAC_REGION_RU864` API Reference ************* LoRa PHY ======== .. doxygengroup:: lora_api LoRaWAN ======= .. doxygengroup:: lorawan_api ```
/content/code_sandbox/doc/connectivity/lora_lorawan/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
560
```restructuredtext .. _networking_with_user_qemu: Networking with QEMU User ############################# .. contents:: :local: :depth: 2 This page is intended to serve as a starting point for anyone interested in using QEMU SLIRP with Zephyr. Introduction ************* SLIRP is a network backend which provides the complete TCP/IP stack within QEMU and uses that stack to implement a virtual NAT'd network. As there are no dependencies on the host, SLIRP is simple to setup. By default, QEMU uses the ``10.0.2.X/24`` network and runs a gateway at ``10.0.2.2``. All traffic intended for the host network has to travel through this gateway, which will filter out packets based on the QEMU command line parameters. This gateway also functions as a DHCP server for all GOS, allowing them to be automatically assigned with an IP address starting from ``10.0.2.15``. More details about User Networking can be obtained from here: path_to_url#User_Networking_.28SLIRP.29 Using SLIRP with Zephyr ************************ In order to use SLIRP with Zephyr, the user has to set the Kconfig option to enable User Networking. .. code-block:: cfg CONFIG_NET_QEMU_USER=y Once this configuration option is enabled, all QEMU launches will use SLIRP. In the default configuration, Zephyr only enables User Networking, and does not pass any arguments to it. This means that the Guest will only be able to communicate to the QEMU gateway, and any data intended for the host machine will be dropped by QEMU. In general, QEMU User Networking can take in a lot of arguments including, * Information about host/guest port forwarding. This must be provided to create a communication channel between the guest and host. * Information about network to use. This may be valuable if the user does not want to use the default ``10.0.2.X`` network. * Tell QEMU to start DHCP server at user-defined IP address. * ID and other information. As this information varies with every use case, it is difficult to come up with good defaults that work for all. Therefore, Zephyr Implementation offloads this to the user, and expects that they will provide arguments based on requirements. For this, there is a Kconfig string which can be populated by the user. .. code-block:: cfg CONFIG_NET_QEMU_USER_EXTRA_ARGS="net=192.168.0.0/24,hostfwd=tcp::8080-:8080" This option is appended as-is to the QEMU command line. Therefore, any problems with this command line will be reported by QEMU only. Here's what this particular example will do, * Make QEMU use the ``192.168.0.0/24`` network instead of the default. * Enable forwarding of any TCP data received from port 8080 of host to port 8080 of guest, and vice versa. Limitations ************* If the user does not have any specific networking requirements other than the ability to access a web page from the guest, user networking (slirp) is a good choice. However, it has several limitations * There is a lot of overhead so the performance is poor. * The guest is not directly accessible from the host or the external network. * In general, ICMP traffic does not work (so you cannot use ping within a guest). * As port mappings need to be defined before launching qemu, clients which use dynamically generated ports cannot communicate with external network. * There is a bug in the SLIRP implementation which filters out all IPv6 packets from the guest. See path_to_url for details. Therefore, IPv6 will not work with User Networking. ```
/content/code_sandbox/doc/connectivity/networking/qemu_user_setup.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
826
```restructuredtext .. _networking_with_eth_qemu: Networking with QEMU Ethernet ############################# .. contents:: :local: :depth: 2 This page describes how to set up a virtual network between a (Linux) host and a Zephyr application running in QEMU. In this example, the :zephyr:code-sample:`sockets-echo-server` sample application from the Zephyr source distribution is run in QEMU. The Zephyr instance is connected to a Linux host using a tuntap device which is modeled in Linux as an Ethernet network interface. Prerequisites ************* On the Linux Host, fetch the Zephyr ``net-tools`` project, which is located in a separate Git repository: .. code-block:: console git clone path_to_url Basic Setup *********** For the steps below, you will need two terminal windows: * Terminal #1 is terminal window with net-tools being the current directory (``cd net-tools``) * Terminal #2 is your usual Zephyr development terminal, with the Zephyr environment initialized. When configuring the Zephyr instance, you must select the correct Ethernet driver for QEMU connectivity: * For ``qemu_x86``, select ``Intel(R) PRO/1000 Gigabit Ethernet driver`` Ethernet driver. Driver is called ``e1000`` in Zephyr source tree. * For ``qemu_cortex_m3``, select ``TI Stellaris MCU family ethernet driver`` Ethernet driver. Driver is called ``stellaris`` in Zephyr source tree. * For ``mps2_an385``, select ``SMSC911x/9220 Ethernet driver`` Ethernet driver. Driver is called ``smsc911x`` in Zephyr source tree. * For ``qemu_cortex_a53``, ``Intel(R) PRO/1000 Gigabit Ethernet driver`` Ethernet driver is selected by default. Step 1 - Create Ethernet interface ================================== Before starting QEMU with network connectivity, a network interface should be created in the host system. In terminal #1, type: .. code-block:: console ./net-setup.sh You can tweak the behavior of the ``net-setup.sh`` script. See various options by running ``net-setup.sh`` like this: .. code-block:: console ./net-setup.sh --help Step 2 - Start app in QEMU board ================================ Build and start the :zephyr:code-sample:`sockets-echo-server` sample application. In this example, the qemu_x86 board is used. In terminal #2, type: .. zephyr-app-commands:: :zephyr-app: samples/net/sockets/echo_server :host-os: unix :board: qemu_x86 :gen-args: -DEXTRA_CONF_FILE=overlay-e1000.conf :goals: run :compact: Exit QEMU by pressing :kbd:`CTRL+A` :kbd:`x`. ```
/content/code_sandbox/doc/connectivity/networking/qemu_eth_setup.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
627
```restructuredtext .. _networking_with_armfvp: Networking with Arm FVP User Mode ################################# .. contents:: :local: :depth: 2 This page is intended to serve as a starting point for anyone interested in using Arm FVP user mode networking with Zephyr. Introduction ************* User mode networking emulates a built-in IP router and DHCP server, and routes TCP and UDP traffic between the guest and host. It uses the user mode socket layer of the host to communicate with other hosts. This allows the use of a significant number of IP network services without requiring administrative privileges, or the installation of a separate driver on the host on which the model is running. By default, Arm FVP uses the ``172.20.51.0/24`` network and runs a gateway at ``172.20.51.254``. This gateway also functions as a DHCP server for the GOS, allowing it to be automatically assigned with an IP address ``172.20.51.1``. More details about Arm FVP user mode networking can be obtained from here: path_to_url Using Arm FVP User Mode Networking with Zephyr *********************************************** Arm FVP user mode networking can be enabled in any applications and it doesn't need any configurations on the host system. This feature has been enabled in DHCPv4 client sample. See :zephyr:code-sample:`dhcpv4-client` sample application. Limitations ************* * You can use TCP and UDP over IP, but not ICMP (ping). * User mode networking does not support forwarding UDP ports on the host to the model. * You can only use DHCP within the private network. * You can only make inward connections by mapping TCP ports on the host to the model. This is common to all implementations that provide host connectivity using NAT. * Operations that require privileged source ports, for example NFS in its default configuration, do not work. * If setup fails, or the parameter syntax is incorrect, there is no error reporting. ```
/content/code_sandbox/doc/connectivity/networking/armfvp_user_networking_setup.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
435
```restructuredtext .. _arm_cortex_m_developer_guide: Arm Cortex-M Developer Guide ############################ Overview ******** This page contains detailed information about the status of the Arm Cortex-M architecture porting in the Zephyr RTOS and describes key aspects when developing Zephyr applications for Arm Cortex-M-based platforms. Key supported features ********************** The table below summarizes the status of key OS features in the different Arm Cortex-M implementation variants. +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | | | **Processor families** | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | Architecture variant | | Arm v6-M | Arm v7-M | Arm v8-M | Arm v8.1-M | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | | | **M0/M1** | **M0+** | **M3** | **M4** | **M7** | **M23** | **M33** | **M55** | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | **OS Features** | | | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | Programmable fault | | | | | | | | | | | IRQ priorities | | Y | N | Y | Y | Y | N | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | Single-thread kernel support | | Y | Y | Y | Y | Y | Y | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | Thread local storage support | | Y | Y | Y | Y | Y | Y | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | Interrupt handling | | | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | | Regular interrupts | Y | Y | Y | Y | Y | Y | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | | Dynamic interrupts | Y | Y | Y | Y | Y | Y | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | | Direct interrupts | Y | Y | Y | Y | Y | Y | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | | Zero Latency interrupts | N | N | Y | Y | Y | Y | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | CPU idling | | Y | Y | Y | Y | Y | Y | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | Native system timer (SysTick) | | N [#f1]_ | Y | Y | Y | Y | Y | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | Memory protection | | | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | | User mode | N | Y | Y | Y | Y | Y | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | | HW stack protection (MPU) | N | N | Y | Y | Y | Y | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | | HW-assisted stack limit checking | N | N | N | N | N |Y [#f2]_ | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | HW-assisted null-pointer | | | | | | | | | | | dereference detection | | N | N | Y | Y | Y | Y | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | HW-assisted atomic operations | | N | N | Y | Y | Y | N | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ |Support for non-cacheable regions| | N | N | Y | Y | Y | N | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | Execute SRAM functions | | N | N | Y | Y | Y | N | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | Floating Point Services | | N | N | N | Y | Y | N | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | DSP ISA | | N | N | N | Y | Y | N | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | Trusted-Execution | | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | | Native TrustZone-M support | N | N | N | N | N | Y | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | | TF-M integration | N | N | N | N | N | N | Y | N | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | Code relocation | | Y | Y | Y | Y | Y | Y | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | SW-based vector table relaying | | Y | Y | Y | Y | Y | Y | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ | HW-assisted timing functions | | N | N | Y | Y | Y | N | Y | Y | +---------------------------------+-----------------------------------+-----------------+---------+--------+-----------+--------+---------+------------+------------+ Notes ===== .. [#f1] SysTick is optional in Cortex-M1 .. [#f2] Stack limit checking only in Secure builds in Cortex-M23 OS features *********** Threads ======= Thread stack alignment ---------------------- Each Zephyr thread is defined with its own stack memory. By default, Cortex-M enforces a double word thread stack alignment, see :kconfig:option:`CONFIG_STACK_ALIGN_DOUBLE_WORD`. If MPU-based HW-assisted stack overflow detection (:kconfig:option:`CONFIG_MPU_STACK_GUARD`) is enabled, thread stacks need to be aligned with a larger value, reflected by :kconfig:option:`CONFIG_ARM_MPU_REGION_MIN_ALIGN_AND_SIZE`. In Arm v6-M and Arm v7-M architecture variants, thread stacks are additionally required to align with a value equal to their size, in applications that need to support user mode (:kconfig:option:`CONFIG_USERSPACE`). The thread stack sizes in that case need to be a power of two. This is all reflected by :kconfig:option:`CONFIG_MPU_REQUIRES_POWER_OF_TWO_ALIGNMENT`, that is enforced in Arm v6-M and Arm v7-M builds with user mode support. Stack pointers -------------- While executing in thread mode the processor is using the Process Stack Pointer (PSP). The processor uses the Main Stack Pointer (MSP) while executing in handler mode, that is, while servicing exceptions and HW interrupts. Using PSP in thread mode *facilitates thread stack pointer manipulation* during thread context switching, without affecting the current execution context flow in handler mode. In Arm Cortex-M builds a single interrupt stack memory is shared among exceptions and interrupts. The size of the interrupt stack needs to be selected taking into consideration nested interrupts, each pushing an additional stack frame. Developers can modify the interrupt stack size using :kconfig:option:`CONFIG_ISR_STACK_SIZE`. The interrupt stack is also used during early boot so the kernel can initialize the main thread's stack before switching to the main thread. Thread context switching ======================== In Arm Cortex-M builds, the PendSV exception is used in order to trigger a context switch to a different thread. PendSV exception is always present in Cortex-M implementations. PendSV is configured with the lowest possible interrupt priority level, in all Cortex-M variants. The main reasons for that design are * to utilize the tail chaining feature of Cortex-M processors, and thus limit the number of context switch operations that occur. * to not impact the interrupt latency observed by HW interrupts. As a result, context switch in Cortex-M is non-atomic, i.e. it may be *preempted* by HW interrupts, however, a context-switch operation must be completed before a new thread context-switch may start. Typically a thread context-switch will perform the following operations * When switching-out the current thread, the processor stores * the callee-saved registers (R4 - R11) in the thread's container for callee-saved registers, which is located in kernel memory * the thread's current operation *mode* * user or privileged execution mode * presence of an active floating point context * the EXC_RETURN value of the current handler context (PendSV) * the floating point callee-saved registers (S16 - S31) in the thread's container for FP callee-saved registers, if the current thread has an active FP context * the PSP of the current thread which points to the beginning of the current thread's exception stack frame. The latter contains the caller-saved context and the return address of the switched-out thread. * When switching-in a new thread the processor * restores the new thread's callee-saved registers from the thread's container for callee-saved registers * restores the new thread's operation *mode* * restores the FP callee-saved registers if the switched-in thread had an active FP context before being switched-out * re-programs the dynamic MPU regions to allow a user thread access its stack and application memories, and/or programs a stack-overflow MPU guard at the bottom of the thread's privileged stack * restores the PSP for the incoming thread and re-programs the stack pointer limit register (if applicable, see :kconfig:option:`CONFIG_BUILTIN_STACK_GUARD`) * optionally does a stack limit checking for the switched-in thread, if sentinel-based stack limit checking is enabled (see :kconfig:option:`CONFIG_STACK_SENTINEL`). PendSV exception return sequence restores the new thread's caller-saved registers and the return address, as part of unstacking the exception stack frame. The implementation of the context-switch mechanism is present in :file:`arch/arm/core/cortex_m/swap_helper.S`. Stack limit checking (Arm v8-M) ------------------------------- Armv8-M and Armv8.1-M variants support stack limit checking using the MSPLIM and PSPLIM core registers. The feature is enabled when :kconfig:option:`CONFIG_BUILTIN_STACK_GUARD` is set. When stack limit checking is enabled, both the thread's privileged or user stack, as well as the interrupt stack are guarded by PSPLIM and MSPLIM registers, respectively. MSPLIM is configured *once* during kernel boot, while PSLIM is re-programmed during every thread context-switch or during system calls, when the thread switches from using its default stack to using its privileged stack, and vice versa. PSPLIM re-programming * has a relatively low runtime overhead (programming is done with MSR instructions) * does not impact interrupt latency * does not require any memory areas to be reserved for stack guards * does not make use of MPU regions It is, therefore, considered as a lightweight but very efficient stack overflow detection mechanism in Cortex-M applications. Stack overflows trigger the dedicated UsageFault exception provided by Arm v8-M. Interrupt handling features =========================== This section describes certain aspects around exception and interrupt handling in Arm Cortex-M. Interrupt priority levels ------------------------- The number of available (configurable) interrupt priority levels is determined by the number of implemented interrupt priority bits in NVIC; this needs to be described for each Cortex-M platform using DeviceTree: .. code-block:: devicetree &nvic { arm,num-irq-priority-bits = <#priority-bits>; }; Reserved priority levels ------------------------ A number of interrupt priority levels are reserved for the OS. By design, system fault exceptions have the highest priority level. In *Baseline* Cortex-M, this is actually enforced by hardware, as HardFault is the only available processor fault exception, and its priority is higher than any configurable exception priority. In *Mainline* Cortex-M, the available fault exceptions (e.g. MemManageFault, UsageFault, etc.) are assigned the highest *configurable* priority level. (:kconfig:option:`CONFIG_CPU_CORTEX_M_HAS_PROGRAMMABLE_FAULT_PRIOS` signifies explicitly that the Cortex-M implementation supports configurable fault priorities.) This priority level is never shared with HW interrupts (an exception to this rule is described below). As a result, processor faults occurring in regular ISRs will be handled by the corresponding fault handler and will not escalate to a HardFault, *similar to processor faults occurring in thread mode*. SVC exception is normally configured with the highest configurable priority level (an exception to this rule will be described below). SVCs are used by the Zephyr kernel to dispatch system calls, trigger runtime system errors (e.g. Kernel oops or panic), or implement IRQ offloading. In Baseline Cortex-M the priority level of SVC may be shared with other exceptions or HW interrupts that are also given the highest configurable priority level (As a result of this, kernel runtime errors during interrupt handling will escalate to HardFault. Additional logic in the fault handling routines ensures that such runtime errors are detected successfully). In Mainline Cortex-M, however, the SVC priority level is *reserved*, thus normally it is only shared with the fault exceptions of configurable priority. This simplifies the fault handling routines in Mainline Cortex-M architecture, since runtime kernel errors are serviced by the SVC handler (i.e no HardFault escalation, even if the kernel errors occur in ISR context). HW interrupts in Mainline Cortex-M builds are allocated a priority level lower than the SVC. One exception to the above rules is when Zephyr applications support Zero Latency Interrupts (ZLIs). Such interrupts are designed to have a priority level higher than any HW or system interrupt. If the ZLI feature is enabled in Mainline Cortex-M builds (see :kconfig:option:`CONFIG_ZERO_LATENCY_IRQS`), then * ZLIs are assigned the highest configurable priority level * SVCs are assigned the second highest configurable priority level * Regular HW interrupts are assigned priority levels lower than SVC. The priority level configuration in Cortex-M is implemented in :file:`include/zephyr/arch/arm/cortex_m/exception.h`. Locking and unlocking IRQs -------------------------- In Baseline Cortex-M locking interrupts is implemented using the PRIMASK register. .. code-block:: c arch_irq_lock() will set the PRIMASK register to 1, eventually, masking all IRQs with configurable priority. While this fulfils the OS requirement of locking interrupts, the consequence is that kernel runtime errors (triggering SVCs) will escalate to HardFault. In Mainline Cortex-M locking interrupts is implemented using the BASEPRI register (Mainline Cortex-M builds select :kconfig:option:`CONFIG_CPU_CORTEX_M_HAS_BASEPRI` to signify that BASEPRI register is implemented.). By modifying BASEPRI (or BASEPRI_MAX) arch_irq_lock() masks all system and HW interrupts with the exception of * SVCs * processor faults * ZLIs This allows zero latency interrupts to be triggered inside OS critical sections. Additionally, this allows system (processor and kernel) faults to be handled by Zephyr in *exactly the same way*, regardless of whether IRQs have been locked or not when the error occurs. It also allows for system calls to be dispatched while IRQs are locked. .. note:: Mainline Cortex-M fault handling is designed and configured in a way that all processor and kernel faults are handled by the corresponding exception handlers and never result in HardFault escalation. In other words, a HardFault may only occur in Zephyr applications that have modified the default fault handling configurations. The main reason for this design was to reserve the HardFault exception for handling exceptional error conditions in safety critical applications. Dynamic direct interrupts ------------------------- Cortex-M builds support the installation of direct interrupt service routines during runtime. Direct interrupts are designed for performance-critical interrupt handling and do not go through all of the common Zephyr interrupt handling code. Direct dynamic interrupts are enabled via switching on :kconfig:option:`CONFIG_DYNAMIC_DIRECT_INTERRUPTS`. Note that enabling direct dynamic interrupts requires enabling support for dynamic interrupts in the kernel, as well (see :kconfig:option:`CONFIG_DYNAMIC_INTERRUPTS`). Zero Latency interrupts ----------------------- As described above, in Mainline Cortex-M applications, the Zephyr kernel reserves the highest configurable interrupt priority level for its own use (SVC). SVCs will not be masked by interrupt locking. Zero-latency interrupt can be used to set up an interrupt at the highest interrupt priority which will not be blocked by interrupt locking. To use the ZLI feature :kconfig:option:`CONFIG_ZERO_LATENCY_IRQS` needs to be enabled. Zero latency IRQs have minimal interrupt latency, as they will always preempt regular HW or system interrupts. Note, however, that since ZLI ISRs will run at a priority level higher than the kernel exceptions they **cannot use** any kernel functionality. Additionally, since the ZLI interrupt priority level is equal to processor fault priority level, faults occurring in ZLI ISRs will escalate to HardFault and will not be handled in the same way as regular processor faults. Developers need to be aware of this limitation. CPU Idling ========== The Cortex-M architecture port implements both k_cpu_idle() and k_cpu_atomic_idle(). The implementation is present in :file:`arch/arm/core/cortex_m/cpu_idle.c`. In both implementations, the processor will attempt to put the core to low power mode. In k_cpu_idle() the processor ends up executing WFI (Wait For Interrupt) instruction, while in k_cpu_atomic_idle() the processor will execute a WFE (Wait For Event) instruction. When using the CPU idling API in Cortex-M it is important to note the following: * Both k_cpu_idle() and k_cpu_atomic_idle() are *assumed* to be invoked with interrupts locked. This is taken care of by the kernel if the APIs are called by the idle thread. * After waking up from low power mode, both functions will *restore* interrupts unconditionally, that is, regardless of the interrupt lock status before the CPU idle API was called. The Zephyr CPU Idling mechanism is detailed in :ref:`cpu_idle`. Memory protection features ========================== This section describes certain aspects around memory protection features in Arm Cortex-M applications. User mode system calls ---------------------- User mode is supported in Cortex-M platforms that implement the standard (Arm) MPU or a similar core peripheral logic for memory access policy configuration and control, such as the NXP MPU for Kinetis platforms. (Currently, :kconfig:option:`CONFIG_ARCH_HAS_USERSPACE` is selected if :kconfig:option:`CONFIG_ARM_MPU` is enabled by the user in the board default Kconfig settings). A thread performs a system call by triggering a (synchronous) SVC exception, where * up to 5 arguments are placed on registers R1 - R5 * system call ID is placed on register R6. The SVC Handler will branch to the system call preparation logic, which will perform the following operations * switch the thread's PSP to point to the beginning of the thread's privileged stack area, optionally reprogramming the PSPLIM if stack limit checking is enabled * modify CONTROL register to switch to privileged mode * modify the return address in the SVC exception stack frame, so that after exception return the system call dispatcher is executed (in thread privileged mode) Once the system call execution is completed the system call dispatcher will restore the user's original PSP and PSPLIM and switch the CONTROL register back to unprivileged mode before returning back to the caller of the system call. System calls execute in thread mode and can be preempted by interrupts at any time. A thread may also be context-switched-out while doing a system call; the system call will resume as soon as the thread is switched-in again. The system call dispatcher executes at SVC priority, therefore it cannot be preempted by HW interrupts (with the exception of ZLIs), which may observe some additional interrupt latency if they occur during a system call preparation. MPU-assisted stack overflow detection ------------------------------------- Cortex-M platforms with MPU may enable :kconfig:option:`CONFIG_MPU_STACK_GUARD` to enable the MPU-based stack overflow detection mechanism. The following points need to be considered when enabling the MPU stack guards * stack overflows are triggering processor faults as soon as they occur * the mechanism is essential for detecting stack overflows in supervisor threads, or user threads in privileged mode; stack overflows in threads in user mode will always be detected regardless of :kconfig:option:`CONFIG_MPU_STACK_GUARD` being set. * stack overflows are always detected, however, the mechanism does not guarantee that no memory corruption occurs when supervisor threads overflow their stack memory * :kconfig:option:`CONFIG_MPU_STACK_GUARD` will normally reserve one MPU region for programming the stack guard (in certain Arm v8-M configurations with :kconfig:option:`CONFIG_MPU_GAP_FILLING` enabled 2 MPU regions are required to implement the guard feature) * MPU guards are re-programmed at every context-switch, adding a small overhead to the thread swap routine. Compared, however, to the :kconfig:option:`CONFIG_BUILTIN_STACK_GUARD` feature, no re-programming occurs during system calls. * When :kconfig:option:`CONFIG_HW_STACK_PROTECTION` is enabled on Arm v8-M platforms the native stack limit checking mechanism is used by default instead of the MPU-based stack overflow detection mechanism; users may override this setting by manually enabling :kconfig:option:`CONFIG_MPU_STACK_GUARD` in these scenarios. Memory map and MPU considerations ================================= Fixed MPU regions ----------------- By default, when :kconfig:option:`CONFIG_ARM_MPU` is enabled a set of *fixed* MPU regions are programmed during system boot. * One MPU region programs the entire flash area as read-execute. User can override this setting by enabling :kconfig:option:`CONFIG_MPU_ALLOW_FLASH_WRITE`, which programs the flash with RWX permissions. If :kconfig:option:`CONFIG_USERSPACE` is enabled unprivileged access on the entire flash area is allowed. * One MPU region programs the entire SRAM area with privileged-only RW permissions. That is, an MPU region is utilized to disallow execute permissions on SRAM. (An exception to this setting is when :kconfig:option:`CONFIG_MPU_GAP_FILLING` is disabled (Arm v8-M only); in that case no SRAM MPU programming is done so the access is determined by the default Arm memory map policies, allowing for privileged-only RWX permissions on SRAM). * All the memory regions defined in the devicetree with the property ``zephyr,memory-attr`` defining the MPU permissions for the memory region. See the next section for more details. The above MPU regions are defined in :file:`arch/arm/core/mpu/arm_mpu_regions.c`. Alternative MPU configurations are allowed by enabling :kconfig:option:`CONFIG_CPU_HAS_CUSTOM_FIXED_SOC_MPU_REGIONS`. When enabled, this option signifies that the Cortex-M SoC will define and configure its own fixed MPU regions in the SoC definition. Fixed MPU regions defined in devicetree --------------------------------------- When the property ``zephyr,memory-attr`` is present in a memory node, a new MPU region will be allocated and programmed during system boot. When used with the :dtcompatible:`zephyr,memory-region` devicetree compatible, it will result in a linker section being generated associated to that MPU region. For example, to define a new non-cacheable memory region in devicetree: .. code-block:: devicetree sram_no_cache: memory@20300000 { compatible = "zephyr,memory-region", "mmio-sram"; reg = <0x20300000 0x100000>; zephyr,memory-region = "SRAM_NO_CACHE"; zephyr,memory-attr = <( DT_MEM_ARM(ATTR_MPU_RAM_NOCACHE) )>; }; This will automatically create a new MPU entry in with the correct name, base, size and attributes gathered directly from the devicetree. Static MPU regions ------------------ Additional *static* MPU regions may be programmed once during system boot. These regions are required to enable certain features * a RX region to allow execution from SRAM, when :kconfig:option:`CONFIG_ARCH_HAS_RAMFUNC_SUPPORT` is enabled and users have defined functions to execute from SRAM. * a RX region for relocating text sections to SRAM, when :kconfig:option:`CONFIG_CODE_DATA_RELOCATION_SRAM` is enabled * a no-cache region to allow for a none-cacheable SRAM area, when :kconfig:option:`CONFIG_NOCACHE_MEMORY` is enabled * a possibly unprivileged RW region for GCOV code coverage accounting area, when :kconfig:option:`CONFIG_COVERAGE_GCOV` is enabled * a no-access region to implement null pointer dereference detection, when :kconfig:option:`CONFIG_NULL_POINTER_EXCEPTION_DETECTION_MPU` is enabled The boundaries of these static MPU regions are derived from symbols exposed by the linker, in :file:`include/linker/linker-defs.h`. Dynamic MPU regions ------------------- Certain thread-specific MPU regions may be re-programmed dynamically, at each thread context switch: * an unprivileged RW region for the current thread's stack area (for user threads) * a read-only region for the MPU stack guard * unprivileged RW regions for the partitions of the current thread's application memory domain. Considerations -------------- The number of available MPU regions for a Cortex-M platform is a limited resource. Most platforms have 8 MPU regions, while some Cortex-M33 or Cortex-M7 platforms may have up to 16 MPU regions. Therefore there is a relatively strict limitation on how many fixed, static and dynamic MPU regions may be programmed simultaneously. For platforms with 8 available MPU regions it might not be possible to enable all the aforementioned features that require MPU region programming. In most practical applications, however, only a certain set of features is required and 8 MPU regions are, in many cases, sufficient. In Arm v8-M processors the MPU architecture does not allow programmed MPU regions to overlap. :kconfig:option:`CONFIG_MPU_GAP_FILLING` controls whether the fixed MPU region covering the entire SRAM is programmed. When it does, a full SRAM area partitioning is required, in order to program the static and the dynamic MPU regions. This increases the total number of required MPU regions. When :kconfig:option:`CONFIG_MPU_GAP_FILLING` is not enabled the fixed MPU region covering the entire SRAM is not programmed, thus, the static and dynamic regions are simply programmed on top of the always-existing background region (full-SRAM partitioning is not required). Note, however, that the background SRAM region allows execution from SRAM, so when :kconfig:option:`CONFIG_MPU_GAP_FILLING` is not set Zephyr is not protected against attacks that attempt to execute malicious code from SRAM. Floating point Services ======================= Both unshared and shared FP registers mode are supported in Cortex-M (see :ref:`float_v2` for more details). When FPU support is enabled in the build (:kconfig:option:`CONFIG_FPU` is enabled), the sharing FP registers mode (:kconfig:option:`CONFIG_FPU_SHARING`) is enabled by default. This is done as some compiler configurations may activate a floating point context by generating FP instructions for any thread, regardless of whether floating point calculations are performed, and that context must be preserved when switching such threads in and out. The developers can still disable the FP sharing mode in their application projects, and switch to Unshared FP registers mode, if it is guaranteed that the image code does not generate FP instructions outside the single thread context that is allowed (and supposed) to do so. Under FPU sharing mode, the callee-saved FPU registers are saved and restored in context-switch, if the corresponding threads have an active FP context. This adds some runtime overhead on the swap routine. In addition to the runtime overhead, the sharing FPU mode * requires additional memory for each thread to save the callee-saved FP registers * requires additional stack memory for each thread, to stack the caller-saved FP registers, upon exception entry, if an FP context is active. Note, however, that since lazy stacking is enabled, there is no runtime overhead of FP context stacking in regular interrupts (FP state preservation is only activated in the swap routine in PendSV interrupt). Misc **** Chain-loadable images ===================== Cortex-M applications may either be standalone images or chain-loadable, for instance, by a bootloader. Application images chain-loadable by bootloaders (or other applications) normally occupy a specific area in the flash denoted as their *code partition*. :kconfig:option:`CONFIG_USE_DT_CODE_PARTITION` will ensure that a Zephyr chain-loadable image will be linked into its code partition, specified in DeviceTree. HW initialization at boot ------------------------- In order to boot properly, chain-loaded applications may require that the core Arm hardware registers and peripherals are initialized in their reset values. Enabling :kconfig:option:`CONFIG_INIT_ARCH_HW_AT_BOOT` Zephyr to force the initialization of the internal Cortex-M architectural state during boot to the reset values as specified by the corresponding Arm architecture manual. Software vector relaying ------------------------ In Cortex-M platforms that implement the VTOR register (see :kconfig:option:`CONFIG_CPU_CORTEX_M_HAS_VTOR`), chain-loadable images relocate the Cortex-M vector table by updating the VTOR register with the offset of the image vector table. Baseline Cortex-M platforms without VTOR register might not be able to relocate their vector table which remains at a fixed location. Therefore, a chain-loadable image will require an alternative way to route HW interrupts and system exceptions to its own vector table; this is achieved with software vector relaying. When a bootloader image enables :kconfig:option:`CONFIG_SW_VECTOR_RELAY` it is able to relay exceptions and interrupts based on a vector table pointer that is set by the chain-loadable application. The latter sets the :kconfig:option:`CONFIG_SW_VECTOR_RELAY_CLIENT` option to instruct the boot sequence to set the vector table pointer in SRAM so that the bootloader can forward the exceptions and interrupts to the chain-loadable image's software vector table. While this feature is intended for processors without VTOR register, it may also be used in Mainline Cortex-M platforms. Code relocation =============== Cortex-M support the code relocation feature. When :kconfig:option:`CONFIG_CODE_DATA_RELOCATION_SRAM` is selected, Zephyr will relocate .text, data and .bss sections from the specified files and place it in SRAM. It is possible to relocate only parts of the code sections into SRAM, without relocating the whole image text and data sections. More details on the code relocation feature can be found in :ref:`code_data_relocation`. Linking Cortex-M applications ***************************** Most Cortex-M platforms make use of the default Cortex-M GCC linker script in :file:`include/zephyr/arch/arm/cortex_m/scripts/linker.ld`, although it is possible for platforms to use a custom linker script as well. CMSIS ***** Cortex-M CMSIS headers are hosted in a standalone module repository: `zephyrproject-rtos/cmsis <path_to_url`_. :kconfig:option:`CONFIG_CPU_CORTEX_M` selects :kconfig:option:`CONFIG_HAS_CMSIS_CORE` to signify that CMSIS headers are available for all supported Cortex-M variants. Testing ******* A list of unit tests for the Cortex-M porting and miscellaneous features is present in :file:`tests/arch/arm/`. The tests suites are continuously extended and new test suites are added, in an effort to increase the coverage of the Cortex-M architecture support in Zephyr. QEMU **** We use QEMU to verify the implemented features of the Cortex-M architecture port in Zephyr. Adequate coverage is achieved by defining and utilizing a list of QEMU targets, each with a specific architecture variant and Arm peripheral support list. The table below lists the QEMU platform targets defined in Zephyr along with the corresponding Cortex-M implementation variant and the peripherals these targets emulate. +---------------------------------+--------------------+--------------------+----------------+-----------------+----------------+ | | **QEMU target** | +---------------------------------+--------------------+--------------------+----------------+-----------------+----------------+ | Architecture variant | Arm v6-M | Arm v7-M | Arm v8-M | Arm v8.1-M | +---------------------------------+--------------------+--------------------+----------------+-----------------+----------------+ | | **qemu_cortex_m0** | **qemu_cortex_m3** | **mps2_an385** | **mps2_an521** | **mps3_an547** | +---------------------------------+--------------------+--------------------+----------------+-----------------+----------------+ | **Emulated features** | | +---------------------------------+--------------------+--------------------+----------------+-----------------+----------------+ | NVIC | Y | Y | Y | Y | Y | +---------------------------------+--------------------+--------------------+----------------+-----------------+----------------+ | BASEPRI | N | Y | Y | Y | Y | +---------------------------------+--------------------+--------------------+----------------+-----------------+----------------+ | SysTick | N | Y | Y | Y | Y | +---------------------------------+--------------------+--------------------+----------------+-----------------+----------------+ | MPU | N | N | Y | Y | Y | +---------------------------------+--------------------+--------------------+----------------+-----------------+----------------+ | FPU | N | N | N | Y | N | +---------------------------------+--------------------+--------------------+----------------+-----------------+----------------+ | SPLIM | N | N | N | Y | Y | +---------------------------------+--------------------+--------------------+----------------+-----------------+----------------+ | TrustZone-M | N | N | N | Y | N | +---------------------------------+--------------------+--------------------+----------------+-----------------+----------------+ Maintainers & Collaborators *************************** The status of the Arm Cortex-M architecture port in Zephyr is: *maintained*. The updated list of maintainers and collaborators for Cortex-M can be found in :file:`MAINTAINERS.yml`. ```
/content/code_sandbox/doc/hardware/arch/arm_cortex_m.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
8,308
```restructuredtext .. _ip_stack_overview: Overview ######## .. contents:: :local: :depth: 2 Supported Features ****************** The networking IP stack is modular and highly configurable via build-time configuration options. You can minimize system memory consumption by enabling only those network features required by your application. Almost all features can be disabled if not needed. * **IPv6** The support for IPv6 is enabled by default. Various IPv6 sub-options can be enabled or disabled depending on networking needs. * Developer can set the number of unicast and multicast IPv6 addresses that are active at the same time. * The IPv6 address for the device can be set either statically or dynamically using SLAAC (Stateless Address Auto Configuration) (`RFC 4862 <path_to_url`_). * The system also supports multiple IPv6 prefixes and the maximum IPv6 prefix count can be configured at build time. * The IPv6 neighbor cache can be disabled if not needed, and its size can be configured at build time. * The IPv6 neighbor discovery support (`RFC 4861 <path_to_url`_) is enabled by default. * Multicast Listener Discovery v2 support (`RFC 3810 <path_to_url`_) is enabled by default. * IPv6 header compression (6lo) is available for IPv6 connectivity for IEEE 802.15.4 networks (`RFC 4944 <path_to_url`_). * **IPv4** The legacy IPv4 is supported by the networking stack. It cannot be used by IEEE 802.15.4 as this network technology supports only IPv6. IPv4 can be used in Ethernet based networks. By default IPv4 support is disabled. * DHCP (Dynamic Host Configuration Protocol) client is supported (`RFC 2131 <path_to_url`_). * The IPv4 address can also be configured manually. Static IPv4 addresses are supported by default. * **Dual stack support.** The networking stack allows a developer to configure the system to use both IPv6 and IPv4 at the same time. * **UDP** User Datagram Protocol (`RFC 768 <path_to_url`_) is supported. The developer can send UDP datagrams (client side support) or create a listener to receive UDP packets destined to certain port (server side support). * **TCP** Transmission Control Protocol (`RFC 793 <path_to_url`_) is supported. Both server and client roles can be used the application. The amount of TCP sockets that are available to applications can be configured at build time. * **BSD Sockets API** Support for a subset of a :ref:`BSD sockets compatible API <bsd_sockets_interface>` is implemented. Both blocking and non-blocking datagram (UDP) and stream (TCP) sockets are supported. * **Secure Sockets API** Experimental support for TLS/DTLS secure protocols and configuration options for sockets API. Secure functions for the implementation are provided by mbedTLS library. * **MQTT** Message Queue Telemetry Transport (ISO/IEC PRF 20922) is supported. A sample :zephyr:code-sample:`mqtt-publisher` client application for MQTT v3.1.1 is implemented. * **CoAP** Constrained Application Protocol (`RFC 7252 <path_to_url`_) is supported. Both :zephyr:code-sample:`coap-client` and :zephyr:code-sample:`coap-server` sample applications are implemented. * **LWM2M** OMA Lightweight Machine-to-Machine Protocol (`LwM2M specification 1.0.2`_) is supported via the "Bootstrap", "Client Registration", "Device Management & Service Enablement" and "Information Reporting" interfaces. The required core LwM2M objects are implemented as well as several IPSO Smart Objects. (`LwM2M specification 1.1.1`_) is supported in similar manner when enabled with a Kconfig option. :zephyr:code-sample:`lwm2m-client` sample implements the library as an example. * **HTTP** Hypertext Transfer Protocol client and server are supported. :ref:`http_client_interface` library supports HTTP/1.1 (`RFC 2616`_). :ref:`http_server_interface` library supports HTTP/1.1 (`RFC 2616`_) and HTTP/2 (`RFC 9113`_). :zephyr:code-sample:`sockets-http-client` and :zephyr:code-sample:`sockets-http-server` samples are provided. * **DNS** Domain Name Service (`RFC 1035 <path_to_url`_) client functionality is supported. Applications can use the DNS API to query domain name information or IP addresses from the DNS server. Both IPv4 (A) and IPv6 (AAAA) records can be queried. Both multicast DNS (mDNS) (`RFC 6762 <path_to_url`_) and link-local multicast name resolution (LLMNR) (`RFC 4795 <path_to_url`_) are supported. * **Network Management API.** Applications can use network management API to listen management events generated by core stack when for example IP address is added to the device, or network interface is coming up etc. * **Wi-Fi Management API.** Applications can use Wi-Fi management API to manage the interface, in example to connect to Wi-Fi network and to scan available Wi-Fi networks. * **Wi-Fi Network Manager API.** Wi-Fi Network Managers can now register themselves to the Wi-Fi stack. The Network Managers can then implement the Wi-Fi Management API and manage the Wi-Fi interface. * **Multiple Network Technologies.** The Zephyr OS can be configured to support multiple network technologies at the same time simply by enabling them in Kconfig: for example, Ethernet, Wi-Fi and 802.15.4 support. Note that no automatic IP routing functionality is provided between these technologies. Applications can send data according to their needs to desired network interface. * **Minimal Copy Network Buffer Management.** It is possible to have minimal copy network data path. This means that the system tries to avoid copying application data when it is sent to the network. * **Virtual LAN support.** Virtual LANs (VLANs) allow partitioning of physical ethernet networks into logical networks. See :ref:`VLAN support <vlan_interface>` for more details. * **Network traffic classification.** The sent and received network packets can be prioritized depending on application needs. See :ref:`traffic classification <traffic-class-support>` for more details. * **Time Sensitive Networking.** The gPTP (generalized Precision Time Protocol) is supported. See :ref:`gPTP support <gptp_interface>` for more details. * **Network shell.** The network shell provides helpers for figuring out network status, enabling/disabling features, and issuing commands like ping or DNS resolving. The net-shell is useful when developing network software. See :ref:`network shell <net_shell>` for more details. Additionally these network technologies (link layers) are supported in Zephyr OS v1.7 and later: * IEEE 802.15.4 * Bluetooth * Ethernet * SLIP (IP over serial line). Used for testing with QEMU. It provides ethernet interface to host system (like Linux) and test applications can be run in Linux host and send network data to Zephyr OS device. Source Tree Layout ****************** The networking stack source code tree is organized as follows: ``subsys/net/ip/`` This is where the IP stack code is located. ``subsys/net/l2/`` This is where the IP stack layer 2 code is located. This includes generic support for Ethernet, IEEE 802.15.4 and Wi-Fi. ``subsys/net/lib/`` Application-level protocols (DNS, MQTT, etc.) and additional stack components (BSD Sockets, etc.). ``include/net/`` Public API header files. These are the header files applications need to include to use IP networking functionality. ``samples/net/`` Sample networking code. This is a good reference to get started with network application development. ``tests/net/`` Test applications. These applications are used to verify the functionality of the IP stack, but are not the best source for sample code (see ``samples/net`` instead). .. _LwM2M specification 1.0.2: path_to_url .. _LwM2M specification 1.1.1: path_to_url .. _RFC 2616: path_to_url .. _RFC 9113: path_to_url ```
/content/code_sandbox/doc/connectivity/networking/overview.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,932
```restructuredtext .. _networking: Networking ########## The networking section contains information regarding the network stack of the Zephyr kernel. Use the information to understand the principles behind the operation of the stacks and how they were implemented. .. toctree:: :maxdepth: 1 overview.rst net-stack-architecture.rst net_config_guide.rst networking_with_host.rst network_monitoring.rst network_tracing.rst api/index.rst conn_mgr/index.rst ```
/content/code_sandbox/doc/connectivity/networking/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
114
```restructuredtext .. _networking_with_native_sim: Networking with native_sim board ################################ .. contents:: :local: :depth: 2 Using virtual/TAP Ethernet driver ********************************* This paragraph describes how to set up a virtual network between a (Linux) host and a Zephyr application running in a :ref:`native_sim <native_sim>` board. In this example, the :zephyr:code-sample:`sockets-echo-server` sample application from the Zephyr source distribution is run in native_sim board. The Zephyr native_sim board instance is connected to a Linux host using a tuntap device which is modeled in Linux as an Ethernet network interface. Prerequisites ============= On the Linux Host, fetch the Zephyr ``net-tools`` project, which is located in a separate Git repository: .. code-block:: console git clone path_to_url Basic Setup =========== For the steps below, you will need three terminal windows: * Terminal #1 is terminal window with net-tools being the current directory (``cd net-tools``) * Terminal #2 is your usual Zephyr development terminal, with the Zephyr environment initialized. * Terminal #3 is the console to the running Zephyr native_sim instance (optional). Step 1 - Create Ethernet interface ---------------------------------- Before starting native_sim with network emulation, a network interface should be created. In terminal #1, type: .. code-block:: console ./net-setup.sh You can tweak the behavior of the net-setup.sh script. See various options by running ``net-setup.sh`` like this: .. code-block:: console ./net-setup.sh --help Step 2 - Start app in native_sim board -------------------------------------- Build and start the ``echo_server`` sample application. In terminal #2, type: .. zephyr-app-commands:: :zephyr-app: samples/net/sockets/echo_server :host-os: unix :board: native_sim :goals: run :compact: Step 3 - Connect to console (optional) -------------------------------------- The console window should be launched automatically when the Zephyr instance is started but if it does not show up, you can manually connect to the console. The native_sim board will print a string like this when it starts: .. code-block:: console UART connected to pseudotty: /dev/pts/5 You can manually connect to it like this: .. code-block:: console screen /dev/pts/5 Using offloaded sockets *********************** The main advantage over `Using virtual/TAP Ethernet driver`_ is not needing to setup a virtual network interface on the host machine. This means that no leveraged (root) privileges are needed. Step 1 - Start app in native_sim board ====================================== Build and start the ``echo_server`` sample application: .. zephyr-app-commands:: :zephyr-app: samples/net/sockets/echo_server :host-os: unix :board: native_sim :gen-args: -DEXTRA_CONF_FILE=overlay-nsos.conf :goals: run :compact: Step 2 - run echo-client from net-tools ======================================= On the Linux Host, fetch the Zephyr ``net-tools`` project, which is located in a separate Git repository: .. code-block:: console git clone path_to_url .. note:: Native Simulator with the offloaded sockets network driver is using the same network interface/namespace as any other (Linux) application that uses BSD sockets API. This means that :zephyr:code-sample:`sockets-echo-server` and ``echo-client`` applications will communicate over localhost/loopback interface (address ``127.0.0.1``). To run UDP test, type: .. code-block:: console ./echo-client 127.0.0.1 For TCP test, type: .. code-block:: console ./echo-client -t 127.0.0.1 Setting interface name from command line **************************************** By default the Ethernet interface name used by native_sim is determined by :kconfig:option:`CONFIG_ETH_NATIVE_POSIX_DRV_NAME`, but is also possible to set it from the command line using ``--eth-if=<interface_name>``. This can be useful if the application has to be run in multiple instances and recompiling it for each instance would be troublesome. .. code-block:: console ./zephyr.exe --eth-if=zeth2 ```
/content/code_sandbox/doc/connectivity/networking/native_sim_setup.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
975
```restructuredtext .. _networking_with_ieee802154_qemu: Networking with QEMU and IEEE 802.15.4 ###################################### .. contents:: :local: :depth: 2 This page describes how to set up a virtual network between two QEMUs that are connected together via UART and are running IEEE 802.15.4 link layer between them. Note that this only works in Linux host. Basic Setup *********** For the steps below, you will need two terminal windows: * Terminal #1 is terminal window with ``echo-server`` Zephyr sample application. * Terminal #2 is terminal window with ``echo-client`` Zephyr sample application. If you want to capture the transferred network data, you must compile the ``monitor_15_4`` program in ``net-tools`` directory. Open a terminal window and type: .. code-block:: console cd $ZEPHYR_BASE/../net-tools make monitor_15_4 Step 1 - Compile and start echo-server ====================================== In terminal #1, type: .. zephyr-app-commands:: :zephyr-app: samples/net/sockets/echo_server :host-os: unix :board: qemu_x86 :build-dir: server :gen-args: -DEXTRA_CONF_FILE=overlay-qemu_802154.conf :goals: server :compact: If you want to capture the network traffic between the two QEMUs, type: .. zephyr-app-commands:: :zephyr-app: samples/net/sockets/echo_server :host-os: unix :board: qemu_x86 :build-dir: server :gen-args: -G'Unix Makefiles' -DEXTRA_CONF_FILE=overlay-qemu_802154.conf -DPCAP=capture.pcap :goals: server :compact: Note that the ``make`` must be used for ``server`` target if packet capture option is set in command line. The ``build/server/capture.pcap`` file will contain the transferred data. Step 2 - Compile and start echo-client ====================================== In terminal #2, type: .. zephyr-app-commands:: :zephyr-app: samples/net/sockets/echo_client :host-os: unix :board: qemu_x86 :build-dir: client :gen-args: -DEXTRA_CONF_FILE=overlay-qemu_802154.conf :goals: client :compact: You should see data passed between the two QEMUs. Exit QEMU by pressing :kbd:`CTRL+A` :kbd:`x`. ```
/content/code_sandbox/doc/connectivity/networking/qemu_802154_setup.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
574
```restructuredtext .. _network_monitoring: Monitor Network Traffic ####################### .. contents:: :local: :depth: 2 It is useful to be able to monitor the network traffic especially when debugging a connectivity issues or when developing new protocol support in Zephyr. This page describes how to set up a way to capture network traffic so that user is able to use Wireshark or similar tool in remote host to see the network packets sent or received by a Zephyr device. See also the :zephyr:code-sample:`net-capture` sample application from the Zephyr source distribution for configuration options that need to be enabled. Host Configuration ****************** The instructions here describe how to setup a Linux host to capture Zephyr network RX and TX traffic. Similar instructions should work also in other operating systems. On the Linux Host, fetch the Zephyr ``net-tools`` project, which is located in a separate Git repository: .. code-block:: console git clone path_to_url The ``net-tools`` project provides a configure file to setup IP-to-IP tunnel interface so that we can transfer monitoring data from Zephyr to host. In terminal #1, type: .. code-block:: console ./net-setup.sh -c zeth-tunnel.conf This script will create following IPIP tunnel interfaces: .. csv-table:: :header: "Interface name", "Description" :widths: auto "``zeth-ip6ip``", "IPv6-over-IPv4 tunnel" "``zeth-ipip``", "IPv4-over-IPv4 tunnel" "``zeth-ipip6``", "IPv4-over-IPv6 tunnel" "``zeth-ip6ip6``", "IPv6-over-IPv6 tunnel" Zephyr will send captured network packets to one of these interfaces. The actual interface will depend on how the capturing is configured. You can then use Wireshark to monitor the proper network interface. After the tunneling interfaces have been created, you can use for example ``net-capture.py`` script from ``net-tools`` project to print or save the captured network packets. The ``net-capture.py`` provides an UDP listener, it can print the captured data to screen and optionally can also save the data to a pcap file. .. code-block:: console $ ./net-capture.py -i zeth-ip6ip -w capture.pcap [20210408Z14:33:08.959589] Ether / IP / ICMP 192.0.2.1 > 192.0.2.2 echo-request 0 / Raw [20210408Z14:33:08.976178] Ether / IP / ICMP 192.0.2.2 > 192.0.2.1 echo-reply 0 / Raw [20210408Z14:33:16.176303] Ether / IPv6 / ICMPv6 Echo Request (id: 0x9feb seq: 0x0) [20210408Z14:33:16.195326] Ether / IPv6 / ICMPv6 Echo Reply (id: 0x9feb seq: 0x0) [20210408Z14:33:21.194979] Ether / IPv6 / ICMPv6ND_NS / ICMPv6 Neighbor Discovery Option - Source Link-Layer Address 02:00:5e:00:53:3b [20210408Z14:33:21.217528] Ether / IPv6 / ICMPv6ND_NA / ICMPv6 Neighbor Discovery Option - Destination Link-Layer Address 00:00:5e:00:53:ff [20210408Z14:34:10.245408] Ether / IPv6 / UDP 2001:db8::2:47319 > 2001:db8::1:4242 / Raw [20210408Z14:34:10.266542] Ether / IPv6 / UDP 2001:db8::1:4242 > 2001:db8::2:47319 / Raw The ``net-capture.py`` has following command line options: .. code-block:: console Listen captured network data from Zephyr and save it optionally to pcap file. ./net-capture.py \ -i | --interface <network interface> Listen this interface for the data [-p | --port <UDP port>] UDP port (default is 4242) where the capture data is received [-q | --quiet] Do not print packet information [-t | --type <L2 type of the data>] Scapy L2 type name of the UDP payload, default is Ether [-w | --write <pcap file name>] Write the received data to file in PCAP format Instead of the ``net-capture.py`` script, you can for example use ``netcat`` to provide an UDP listener so that the host will not send port unreachable message to Zephyr: .. code-block:: console nc -l -u 2001:db8:200::2 4242 > /dev/null The IP address above is the inner tunnel endpoint, and can be changed and it depends on how the Zephyr is configured. Zephyr will send UDP packets containing the captured network packets to the configured IP tunnel, so we need to terminate the network connection like this. Zephyr Configuration ******************** In this example, we use the ``native_sim`` board. You can also use any other board that supports networking. In terminal #3, type: .. zephyr-app-commands:: :zephyr-app: samples/net/capture :host-os: unix :board: native_sim :gen-args: -DCONFIG_NATIVE_UART_AUTOATTACH_DEFAULT_CMD=\""gnome-terminal -- screen %s"\" :goals: build :compact: To see the Zephyr console and shell, start Zephyr instance like this: .. code-block:: console build/zephyr/zephyr.exe -attach_uart Any other application can be used too, just make sure that suitable configuration options are enabled (see ``samples/net/capture/prj.conf`` file for examples). The network capture can be configured automatically if needed, but currently the ``capture`` sample application does not do that. User has to use ``net-shell`` to setup and enable the monitoring. The network packet monitoring needs to be setup first. The ``net-shell`` has ``net capture setup`` command for doing that. The command syntax is .. code-block:: console net capture setup <remote-ip-addr> <local-ip-addr> <peer-ip-addr> <remote> is the (outer) endpoint IP address <local> is the (inner) local IP address <peer> is the (inner) peer IP address Local and Peer IP addresses can have UDP port number in them (optional) like 198.0.51.2:9000 or [2001:db8:100::2]:4242 In Zephyr console, type: .. code-block:: console net capture setup 192.0.2.2 2001:db8:200::1 2001:db8:200::2 This command will create the tunneling interface. The ``192.0.2.2`` is the remote host where the tunnel is terminated. The address is used to select the local network interface where the tunneling interface is attached to. The ``2001:db8:200::1`` tells the local IP address for the tunnel, the ``2001:db8:200::2`` is the peer IP address where the captured network packets are sent. The port numbers for UDP packet can be given in the setup command like this for IPv6-over-IPv4 tunnel .. code-block:: console net capture setup 192.0.2.2 [2001:db8:200::1]:9999 [2001:db8:200::2]:9998 and like this for IPv4-over-IPv4 tunnel .. code-block:: console net capture setup 192.0.2.2 198.51.100.1:9999 198.51.100.2:9998 If the port number is omitted, then ``4242`` UDP port is used as a default. The current monitoring configuration can be checked like this: .. code-block:: console uart:~$ net capture Network packet capture disabled Capture Tunnel Device iface iface Local Peer NET_CAPTURE0 - 1 [2001:db8:200::1]:4242 [2001:db8:200::2]:4242 which will print the current configuration. As we have not yet enabled monitoring, the ``Capture iface`` is not set. Then we need to enable the network packet monitoring like this: .. code-block:: console net capture enable 2 The ``2`` tells the network interface which traffic we want to capture. In this example, the ``2`` is the ``native_sim`` board Ethernet interface. Note that we send the network traffic to the same interface that we are monitoring in this example. The monitoring system avoids to capture already captured network traffic as that would lead to recursion. You can use ``net iface`` command to see what network interfaces are available. Note that you cannot capture traffic from the tunnel interface as that would cause recursion loop. The captured network traffic can be sent to some other network interface if configured so. Just set the ``<remote-ip-addr>`` option properly in ``net capture setup`` so that the IP tunnel is attached to desired network interface. The capture status can be checked again like this: .. code-block:: console uart:~$ net capture Network packet capture enabled Capture Tunnel Device iface iface Local Peer NET_CAPTURE0 2 1 [2001:db8:200::1]:4242 [2001:db8:200::2]:4242 After enabling the monitoring, the system will send captured (either received or sent) network packets to the tunnel interface for further processing. The monitoring can be disabled like this: .. code-block:: console net capture disable which will turn currently running monitoring off. The monitoring setup can be cleared like this: .. code-block:: console net capture cleanup It is not necessary to use ``net-shell`` for configuring the monitoring. The :ref:`network capture API <net_capture_interface>` functions can be called by the application if needed. Wireshark Configuration *********************** The `Wireshark <path_to_url`_ tool can be used to monitor the captured network traffic in a useful way. You can monitor either the tunnel interfaces or the ``zeth`` interface. In order to see the actual captured data inside an UDP packet, see `Wireshark decapsulate UDP`_ document for instructions. .. _Wireshark decapsulate UDP: path_to_url ```
/content/code_sandbox/doc/connectivity/networking/network_monitoring.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,419
```restructuredtext .. _network_tracing: Network Tracing ############### .. contents:: :local: :depth: 2 User can enable network core stack and socket API calls tracing. The :kconfig:option:`CONFIG_TRACING_NET_CORE` option contols the core network stack tracing. This option is enabled by default if tracing and networking are enabled. The system will start to collect the receiving and sending call verdicts i.e., whether the network packet was successfully sent or received. It will also collect packet sending or receiving timings i.e., how long it took to deliver the network packet, and the network interface, priority and traffic class used. The :kconfig:option:`CONFIG_TRACING_NET_SOCKETS` option can be used to track BSD socket call usage in the system. It is enabled if tracing and BSD socket API support are enabled. The system will start to collect what BSD socket API calls are made and what parameters the API calls are using and returning. See the :ref:`tracing documentation <tracing>` for how to use the tracing service. ```
/content/code_sandbox/doc/connectivity/networking/network_tracing.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
228
```restructuredtext .. _network_configuration_guide: Network Configuration Guide ########################### .. contents:: :local: :depth: 2 This document describes how various network configuration options can be set according to available resources in the system. Network Buffer Configuration Options ************************************ The network buffer configuration options control how much data we are able to either send or receive at the same time. :kconfig:option:`CONFIG_NET_PKT_RX_COUNT` Maximum amount of network packets we can receive at the same time. :kconfig:option:`CONFIG_NET_PKT_TX_COUNT` Maximum amount of network packet sends pending at the same time. :kconfig:option:`CONFIG_NET_BUF_RX_COUNT` How many network buffers are allocated for receiving data. Each net_buf contains a small header and either a fixed or variable length data buffer. The :kconfig:option:`CONFIG_NET_BUF_DATA_SIZE` is used when :kconfig:option:`CONFIG_NET_BUF_FIXED_DATA_SIZE` is set. This is the default setting. The default size of the buffer is 128 bytes. The :kconfig:option:`CONFIG_NET_BUF_VARIABLE_DATA_SIZE` is an experimental setting. There each net_buf data portion is allocated from a memory pool and can be the amount of data we have received from the network. When data is received from the network, it is placed into net_buf data portion. Depending on device resources and desired network usage, user can tweak the size of the fixed buffer by setting :kconfig:option:`CONFIG_NET_BUF_DATA_SIZE`, and the size of the data pool size by setting :kconfig:option:`CONFIG_NET_PKT_BUF_RX_DATA_POOL_SIZE` and :kconfig:option:`CONFIG_NET_PKT_BUF_TX_DATA_POOL_SIZE` if variable size buffers are used. When using the fixed size data buffers, the memory consumption of network buffers can be tweaked by selecting the size of the data part according to what kind of network data we are receiving. If one sets the data size to 256, but only receives packets that are 32 bytes long, then we are "wasting" 224 bytes for each packet because we cannot utilize the remaining data. One should not set the data size too low because there is some overhead involved for each net_buf. For these reasons the default network buffer size is set to 128 bytes. The variable size data buffer feature is marked as experimental as it has not received as much testing as the fixed size buffers. Using variable size data buffers tries to improve memory utilization by allocating minimum amount of data we need for the network data. The extra cost here is the amount of time that is needed when dynamically allocating the buffer from the memory pool. For example, in Ethernet the maximum transmission unit (MTU) size is 1500 bytes. If one wants to receive two full frames, then the net_pkt RX count should be set to 2, and net_buf RX count to (1500 / 128) * 2 which is 24. If TCP is being used, then these values need to be higher because we can queue the packets internally before delivering to the application. :kconfig:option:`CONFIG_NET_BUF_TX_COUNT` How many network buffers are allocated for sending data. This is similar setting as the receive buffer count but for sending. Connection Options ****************** :kconfig:option:`CONFIG_NET_MAX_CONN` This option tells how many network connection endpoints are supported. For example each TCP connection requires one connection endpoint. Similarly each listening UDP connection requires one connection endpoint. Also various system services like DHCP and DNS need connection endpoints to work. The network shell command **net conn** can be used at runtime to see the network connection information. :kconfig:option:`CONFIG_NET_MAX_CONTEXTS` Number of network contexts to allocate. Each network context describes a network 5-tuple that is used when listening or sending network traffic. Each BSD socket in the system uses one network context. Socket Options ************** :kconfig:option:`CONFIG_NET_SOCKETS_POLL_MAX` Maximum number of supported poll() entries. One needs to select proper value here depending on how many BSD sockets are polled in the system. :kconfig:option:`CONFIG_ZVFS_OPEN_MAX` Maximum number of open file descriptors, this includes files, sockets, special devices, etc. One needs to select proper value here depending on how many BSD sockets are created in the system. :kconfig:option:`CONFIG_NET_SOCKETPAIR_BUFFER_SIZE` This option is used by socketpair() function. It sets the size of the internal intermediate buffer, in bytes. This sets the limit how large messages can be passed between two socketpair endpoints. TLS Options *********** :kconfig:option:`CONFIG_NET_SOCKETS_TLS_MAX_CONTEXTS` Maximum number of TLS/DTLS contexts. Each TLS/DTLS connection needs one context. :kconfig:option:`CONFIG_NET_SOCKETS_TLS_MAX_CREDENTIALS` This variable sets maximum number of TLS/DTLS credentials that can be used with a specific socket. :kconfig:option:`CONFIG_NET_SOCKETS_TLS_MAX_CIPHERSUITES` Maximum number of TLS/DTLS ciphersuites per socket. This variable sets maximum number of TLS/DTLS ciphersuites that can be used with specific socket, if set explicitly by socket option. By default, all ciphersuites that are available in the system are available to the socket. :kconfig:option:`CONFIG_NET_SOCKETS_TLS_MAX_APP_PROTOCOLS` Maximum number of supported application layer protocols. This variable sets maximum number of supported application layer protocols over TLS/DTLS that can be set explicitly by a socket option. By default, no supported application layer protocol is set. :kconfig:option:`CONFIG_NET_SOCKETS_TLS_MAX_CLIENT_SESSION_COUNT` This variable specifies maximum number of stored TLS/DTLS sessions, used for TLS/DTLS session resumption. :kconfig:option:`CONFIG_TLS_MAX_CREDENTIALS_NUMBER` Maximum number of TLS credentials that can be registered. Make sure that this value is high enough so that all the certificates can be loaded to the store. IPv4/6 Options ************** :kconfig:option:`CONFIG_NET_IF_MAX_IPV4_COUNT` Maximum number of IPv4 network interfaces in the system. This tells how many network interfaces there will be in the system that will have IPv4 enabled. For example if you have two network interfaces, but only one of them can use IPv4 addresses, then this value can be set to 1. If both network interface could use IPv4, then the setting should be set to 2. :kconfig:option:`CONFIG_NET_IF_MAX_IPV6_COUNT` Maximum number of IPv6 network interfaces in the system. This is similar setting as the IPv4 count option but for IPv6. TCP Options *********** :kconfig:option:`CONFIG_NET_TCP_TIME_WAIT_DELAY` How long to wait in TCP *TIME_WAIT* state (in milliseconds). To avoid a (low-probability) issue when delayed packets from previous connection get delivered to next connection reusing the same local/remote ports, `RFC 793 <path_to_url`_ (TCP) suggests to keep an old, closed connection in a special *TIME_WAIT* state for the duration of 2*MSL (Maximum Segment Lifetime). The RFC suggests to use MSL of 2 minutes, but notes *This is an engineering choice, and may be changed if experience indicates it is desirable to do so.* For low-resource systems, having large MSL may lead to quick resource exhaustion (and related DoS attacks). At the same time, the issue of packet misdelivery is largely alleviated in the modern TCP stacks by using random, non-repeating port numbers and initial sequence numbers. Due to this, Zephyr uses much lower value of 1500ms by default. Value of 0 disables *TIME_WAIT* state completely. :kconfig:option:`CONFIG_NET_TCP_RETRY_COUNT` Maximum number of TCP segment retransmissions. The following formula can be used to determine the time (in ms) that a segment will be buffered awaiting retransmission: .. math:: \sum_{n=0}^{\mathtt{NET\_TCP\_RETRY\_COUNT}} \bigg(1 \ll n\bigg)\times \mathtt{NET\_TCP\_INIT\_RETRANSMISSION\_TIMEOUT} With the default value of 9, the IP stack will try to retransmit for up to 1:42 minutes. This is as close as possible to the minimum value recommended by `RFC 1122 <path_to_url`_ (1:40 minutes). Only 5 bits are dedicated for the retransmission count, so accepted values are in the 0-31 range. It's highly recommended to not go below 9, though. Should a retransmission timeout occur, the receive callback is called with :code:`-ETIMEDOUT` error code and the context is dereferenced. :kconfig:option:`CONFIG_NET_TCP_MAX_SEND_WINDOW_SIZE` Maximum sending window size to use. This value affects how the TCP selects the maximum sending window size. The default value 0 lets the TCP stack select the value according to amount of network buffers configured in the system. Note that if there are multiple active TCP connections in the system, then this value might require finetuning (lowering), otherwise multiple TCP connections could easily exhaust net_buf pool for the queued TX data. :kconfig:option:`CONFIG_NET_TCP_MAX_RECV_WINDOW_SIZE` Maximum receive window size to use. This value defines the maximum TCP receive window size. Increasing this value can improve connection throughput, but requires more receive buffers available in the system for efficient operation. The default value 0 lets the TCP stack select the value according to amount of network buffers configured in the system. :kconfig:option:`CONFIG_NET_TCP_RECV_QUEUE_TIMEOUT` How long to queue received data (in ms). If we receive out-of-order TCP data, we queue it. This value tells how long the data is kept before it is discarded if we have not been able to pass the data to the application. If set to 0, then receive queueing is not enabled. The value is in milliseconds. Note that we only queue data sequentially in current version i.e., there should be no holes in the queue. For example, if we receive SEQs 5,4,3,6 and are waiting SEQ 2, the data in segments 3,4,5,6 is queued (in this order), and then given to application when we receive SEQ 2. But if we receive SEQs 5,4,3,7 then the SEQ 7 is discarded because the list would not be sequential as number 6 is be missing. Traffic Class Options ********************* It is possible to configure multiple traffic classes (queues) when receiving or sending network data. Each traffic class queue is implemented as a thread with different priority. This means that higher priority network packet can be placed to a higher priority network queue in order to send or receive it faster or slower. Because of thread scheduling latencies, in practice the fastest way to send a packet out, is to directly send the packet without using a dedicated traffic class thread. This is why by default the :kconfig:option:`CONFIG_NET_TC_TX_COUNT` option is set to 0 if userspace is not enabled. If userspace is enabled, then the minimum TX traffic class count is 1. Reason for this is that the userspace application does not have enough permissions to deliver the message directly. In receiving side, it is recommended to have at least one receiving traffic class queue. Reason is that typically the network device driver is running in IRQ context when it receives the packet, in which case it should not try to deliver the network packet directly to the upper layers, but to place the packet to the traffic class queue. If the network device driver is not running in IRQ context when it gets the packet, then the RX traffic class option :kconfig:option:`CONFIG_NET_TC_RX_COUNT` could be set to 0. Stack Size Options ****************** There several network specific threads in a network enabled system. Some of the threads might depend on a configure option which can be used to enable or disable a feature. Each thread stack size is optimized to allow normal network operations. The network management API is using a dedicated thread by default. The thread is responsible to deliver network management events to the event listeners that are setup in the system if the :kconfig:option:`CONFIG_NET_MGMT` and :kconfig:option:`CONFIG_NET_MGMT_EVENT` options are enabled. If the options are enabled, the user is able to register a callback function that the net_mgmt thread is calling for each network management event. By default the net_mgmt event thread stack size is rather small. The idea is that the callback function does minimal things so that new events can be delivered to listeners as fast as possible and they are not lost. The net_mgmt event thread stack size is controlled by :kconfig:option:`CONFIG_NET_MGMT_EVENT_QUEUE_SIZE` option. It is recommended to not do any blocking operations in the callback function. The network thread stack utilization can be monitored from kernel shell by the **kernel threads** command. ```
/content/code_sandbox/doc/connectivity/networking/net_config_guide.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,916
```restructuredtext .. _networking_with_multiple_instances: Networking with multiple Zephyr instances ######################################### .. contents:: :local: :depth: 2 This page describes how to set up a virtual network between multiple Zephyr instances. The Zephyr instances could be running inside QEMU or could be native_sim board processes. The Linux host can be used to route network traffic between these systems. Prerequisites ************* On the Linux Host, fetch the Zephyr ``net-tools`` project, which is located in a separate Git repository: .. code-block:: console git clone path_to_url Basic Setup *********** For the steps below, you will need five terminal windows: * Terminal #1 and #2 are terminal windows with net-tools being the current directory (``cd net-tools``) * Terminal #3, where you setup bridging in Linux host * Terminal #4 and #5 are your usual Zephyr development terminal, with the Zephyr environment initialized. As there are multiple ways to setup the Zephyr network, the example below uses ``qemu_x86`` board with ``e1000`` Ethernet controller and native_sim board to simplify the setup instructions. You can use other QEMU boards and drivers if needed, see :ref:`networking_with_eth_qemu` for details. You can also use two or more native_sim board Zephyr instances and connect them together. Step 1 - Create configuration files =================================== Before starting QEMU with network connectivity, a network interfaces for each Zephyr instance should be created in the host system. The default setup for creating network interface cannot be used here as that is for connecting one Zephyr instance to Linux host. For Zephyr instance #1, create file called ``zephyr1.conf`` to ``net-tools`` project, or to some other suitable directory. .. code-block:: console # Configuration file for setting IP addresses for a network interface. INTERFACE="$1" HWADDR="00:00:5e:00:53:11" IPV6_ADDR_1="2001:db8:100::2" IPV6_ROUTE_1="2001:db8:100::/64" IPV4_ADDR_1="198.51.100.2/24" IPV4_ROUTE_1="198.51.100.0/24" ip link set dev $INTERFACE up ip link set dev $INTERFACE address $HWADDR ip -6 address add $IPV6_ADDR_1 dev $INTERFACE nodad ip -6 route add $IPV6_ROUTE_1 dev $INTERFACE ip address add $IPV4_ADDR_1 dev $INTERFACE ip route add $IPV4_ROUTE_1 dev $INTERFACE > /dev/null 2>&1 For Zephyr instance #2, create file called ``zephyr2.conf`` to ``net-tools`` project, or to some other suitable directory. .. code-block:: console # Configuration file for setting IP addresses for a network interface. INTERFACE="$1" HWADDR="00:00:5e:00:53:22" IPV6_ADDR_1="2001:db8:200::2" IPV6_ROUTE_1="2001:db8:200::/64" IPV4_ADDR_1="203.0.113.2/24" IPV4_ROUTE_1="203.0.113.0/24" ip link set dev $INTERFACE up ip link set dev $INTERFACE address $HWADDR ip -6 address add $IPV6_ADDR_1 dev $INTERFACE nodad ip -6 route add $IPV6_ROUTE_1 dev $INTERFACE ip address add $IPV4_ADDR_1 dev $INTERFACE ip route add $IPV4_ROUTE_1 dev $INTERFACE > /dev/null 2>&1 Step 2 - Create Ethernet interfaces =================================== The following ``net-setup.sh`` commands should be typed in net-tools directory (``cd net-tools``). In terminal #1, type: .. code-block:: console ./net-setup.sh -c zephyr1.conf -i zeth.1 In terminal #2, type: .. code-block:: console ./net-setup.sh -c zephyr2.conf -i zeth.2 Step 3 - Setup network bridging =============================== In terminal #3, type: .. code-block:: console sudo brctl addbr zeth-br sudo brctl addif zeth-br zeth.1 sudo brctl addif zeth-br zeth.2 sudo ifconfig zeth-br up Step 4 - Start Zephyr instances =============================== In this example we start :zephyr:code-sample:`sockets-echo-server` and :zephyr:code-sample:`sockets-echo-client` sample applications. You can use other applications too as needed. In terminal #4, if you are using QEMU, type this: .. code-block:: console west build -d build/server -b qemu_x86 -t run \ samples/net/sockets/echo_server -- \ -DEXTRA_CONF_FILE=overlay-e1000.conf \ -DCONFIG_NET_CONFIG_MY_IPV4_ADDR=\"198.51.100.1\" \ -DCONFIG_NET_CONFIG_PEER_IPV4_ADDR=\"203.0.113.1\" \ -DCONFIG_NET_CONFIG_MY_IPV6_ADDR=\"2001:db8:100::1\" \ -DCONFIG_NET_CONFIG_PEER_IPV6_ADDR=\"2001:db8:200::1\" \ -DCONFIG_NET_CONFIG_MY_IPV4_GW=\"203.0.113.1\" \ -DCONFIG_ETH_QEMU_IFACE_NAME=\"zeth.1\" \ -DCONFIG_ETH_QEMU_EXTRA_ARGS=\"mac=00:00:5e:00:53:01\" or if you want to use native_sim board, type this: .. code-block:: console west build -d build/server -b native_sim -t run \ samples/net/sockets/echo_server -- \ -DCONFIG_NET_CONFIG_MY_IPV4_ADDR=\"198.51.100.1\" \ -DCONFIG_NET_CONFIG_PEER_IPV4_ADDR=\"203.0.113.1\" \ -DCONFIG_NET_CONFIG_MY_IPV6_ADDR=\"2001:db8:100::1\" \ -DCONFIG_NET_CONFIG_PEER_IPV6_ADDR=\"2001:db8:200::1\" \ -DCONFIG_NET_CONFIG_MY_IPV4_GW=\"203.0.113.1\" \ -DCONFIG_ETH_NATIVE_POSIX_DRV_NAME=\"zeth.1\" \ -DCONFIG_ETH_NATIVE_POSIX_MAC_ADDR=\"00:00:5e:00:53:01\" \ -DCONFIG_ETH_NATIVE_POSIX_RANDOM_MAC=n In terminal #5, if you are using QEMU, type this: .. code-block:: console west build -d build/client -b qemu_x86 -t run \ samples/net/sockets/echo_client -- \ -DEXTRA_CONF_FILE=overlay-e1000.conf \ -DCONFIG_NET_CONFIG_MY_IPV4_ADDR=\"203.0.113.1\" \ -DCONFIG_NET_CONFIG_PEER_IPV4_ADDR=\"198.51.100.1\" \ -DCONFIG_NET_CONFIG_MY_IPV6_ADDR=\"2001:db8:200::1\" \ -DCONFIG_NET_CONFIG_PEER_IPV6_ADDR=\"2001:db8:100::1\" \ -DCONFIG_NET_CONFIG_MY_IPV4_GW=\"198.51.100.1\" \ -DCONFIG_ETH_QEMU_IFACE_NAME=\"zeth.2\" \ -DCONFIG_ETH_QEMU_EXTRA_ARGS=\"mac=00:00:5e:00:53:02\" or if you want to use native_sim board, type this: .. code-block:: console west build -d build/client -b native_sim -t run \ samples/net/sockets/echo_client -- \ -DCONFIG_NET_CONFIG_MY_IPV4_ADDR=\"203.0.113.1\" \ -DCONFIG_NET_CONFIG_PEER_IPV4_ADDR=\"198.51.100.1\" \ -DCONFIG_NET_CONFIG_MY_IPV6_ADDR=\"2001:db8:200::1\" \ -DCONFIG_NET_CONFIG_PEER_IPV6_ADDR=\"2001:db8:100::1\" \ -DCONFIG_NET_CONFIG_MY_IPV4_GW=\"198.51.100.1\" \ -DCONFIG_ETH_NATIVE_POSIX_DRV_NAME=\"zeth.2\" \ -DCONFIG_ETH_NATIVE_POSIX_MAC_ADDR=\"00:00:5e:00:53:02\" \ -DCONFIG_ETH_NATIVE_POSIX_RANDOM_MAC=n Also if you have firewall enabled in your host, you need to allow traffic between ``zeth.1``, ``zeth.2`` and ``zeth-br`` interfaces. ```
/content/code_sandbox/doc/connectivity/networking/networking_with_multiple_instances.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,957
```restructuredtext .. _networking_with_host: Networking with the host system ############################### .. toctree:: :maxdepth: 1 :hidden: native_sim_setup.rst qemu_eth_setup.rst qemu_setup.rst usbnet_setup.rst qemu_user_setup.rst networking_with_multiple_instances.rst qemu_802154_setup.rst armfvp_user_networking_setup.rst While developing networking software, it is usually necessary to connect and exchange data with the host system like a Linux desktop computer. Depending on what board is used for development, the following options are possible: * QEMU using SLIP (Serial Line Internet Protocol). * Here IP packets are exchanged between Zephyr and the host system via serial port. This is the legacy way of transferring data. It is also quite slow so use it only when necessary. See :ref:`networking_with_qemu` for details. * QEMU using built-in Ethernet driver. * Here IP packets are exchanged between Zephyr and the host system via QEMU's built-in Ethernet driver. Not all QEMU boards support built-in Ethernet so in some cases, you might need to use the SLIP method for host connectivity. See :ref:`networking_with_eth_qemu` for details. * QEMU using SLIRP (Qemu User Networking). * QEMU User Networking is implemented using "slirp", which provides a full TCP/IP stack within QEMU and uses that stack to implement a virtual NAT'd network. As this support is built into QEMU, it can be used with any model and requires no admin privileges on the host machine, unlike TAP. However, it has several limitations including performance which makes it less valuable for practical purposes. See :ref:`networking_with_user_qemu` for details. * Arm FVP (User Mode Networking). * User mode networking emulates a built-in IP router and DHCP server, and routes TCP and UDP traffic between the guest and host. It uses the user mode socket layer of the host to communicate with other hosts. This allows the use of a significant number of IP network services without requiring administrative privileges, or the installation of a separate driver on the host on which the model is running. See :ref:`networking_with_armfvp` for details. * native_sim board. * The Zephyr instance can be executed as a user space process in the host system. This is the most convenient way to debug the Zephyr system as one can attach host debugger directly to the running Zephyr instance. This requires that there is an adaptation driver in Zephyr for interfacing with the host system. Two possible network drivers can be used for this purpose, a TAP virtual Ethernet driver and an offloaded sockets driver. See :ref:`networking_with_native_sim` for details. * USB device networking. * Here, the Zephyr instance is run on a real board and the connectivity to the host system is done via USB. See :ref:`usb_device_networking_setup` for details. * Connecting multiple Zephyr instances together. * If you have multiple Zephyr instances, either QEMU or native_sim ones, and want to create a connection between them, see :ref:`networking_with_multiple_instances` for details. * Simulating IEEE 802.15.4 network between two QEMUs. * Here, two Zephyr instances are running and there is IEEE 802.15.4 link layer run over an UART between them. See :ref:`networking_with_ieee802154_qemu` for details. ```
/content/code_sandbox/doc/connectivity/networking/networking_with_host.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
805
```restructuredtext .. _networking_with_qemu: Networking with QEMU #################### .. contents:: :local: :depth: 2 This page describes how to set up a virtual network between a (Linux) host and a Zephyr application running in a QEMU virtual machine (built for Zephyr targets such as qemu_x86 and qemu_cortex_m3). Some virtual ARM boards (such as qemu_cortex_a53) only support a single UART, in this case QEMU Ethernet is preferred, see :ref:`networking_with_eth_qemu` for details. In this example, the :zephyr:code-sample:`sockets-echo-server` sample application from the Zephyr source distribution is run in QEMU. The QEMU instance is connected to a Linux host using a serial port, and SLIP is used to transfer data between the Zephyr application and Linux (over a chain of virtual connections). Prerequisites ************* On the Linux Host, fetch the Zephyr ``net-tools`` project, which is located in a separate Git repository: .. code-block:: console git clone path_to_url cd net-tools make .. note:: If you get an error about AX_CHECK_COMPILE_FLAG, install package ``autoconf-archive`` package on Debian/Ubuntu. Basic Setup *********** For the steps below, you will need at least 4 terminal windows: * Terminal #1 is your usual Zephyr development terminal, with the Zephyr environment initialized. * Terminals #2, #3, and #4 are terminal windows with net-tools being the current directory (``cd net-tools``) Step 1 - Create helper socket ============================= Before starting QEMU with network emulation, a Unix socket for the emulation should be created. In terminal #2, type: .. code-block:: console ./loop-socat.sh Step 2 - Start TAP device routing daemon ======================================== In terminal #3, type: .. code-block:: console sudo ./loop-slip-tap.sh For applications requiring DNS, you may need to restart the host's DNS server at this point, as described in :ref:`networking_internet`. Step 3 - Start app in QEMU ========================== Build and start the ``echo_server`` sample application. In terminal #1, type: .. zephyr-app-commands:: :zephyr-app: samples/net/sockets/echo_server :host-os: unix :board: qemu_x86 :goals: run :compact: If you see an error from QEMU about unix:/tmp/slip.sock, it means you missed Step 1 above. Step 4 - Run apps on host ========================= Now in terminal #4, you can run various tools to communicate with the application running in QEMU. You can start with pings: .. code-block:: console ping 192.0.2.1 ping6 2001:db8::1 You can use the netcat ("nc") utility, connecting using UDP: .. code-block:: console echo foobar | nc -6 -u 2001:db8::1 4242 foobar .. code-block:: console echo foobar | nc -u 192.0.2.1 4242 foobar If echo_server is compiled with TCP support (now enabled by default for the echo_server sample, CONFIG_NET_TCP=y): .. code-block:: console echo foobar | nc -6 -q2 2001:db8::1 4242 foobar .. note:: Use Ctrl+C to exit. You can also use the telnet command to achieve the above. Step 5 - Stop supporting daemons ================================ When you are finished with network testing using QEMU, you should stop any daemons or helpers started in the initial steps, to avoid possible networking or routing problems such as address conflicts in local network interfaces. For example, stop them if you switch from testing networking with QEMU to using real hardware, or to return your host laptop to normal Wi-Fi use. To stop the daemons, press Ctrl+C in the corresponding terminal windows (you need to stop both ``loop-slip-tap.sh`` and ``loop-socat.sh``). Exit QEMU by pressing :kbd:`CTRL+A` :kbd:`x`. .. _networking_internet: Setting up Zephyr and NAT/masquerading on host to access Internet ***************************************************************** To access the internet from a Zephyr application, some additional setup on the host may be required. This setup is common for both application running in QEMU and on real hardware, assuming that a development board is connected to the development host. If a board is connected to a dedicated router, it should not be needed. To access the internet from a Zephyr application using IPv4, a gateway should be set via DHCP or configured manually. For applications using the "Settings" facility (with the config option :kconfig:option:`CONFIG_NET_CONFIG_SETTINGS` enabled), set the :kconfig:option:`CONFIG_NET_CONFIG_MY_IPV4_GW` option to the IP address of the gateway. For apps not using the "Settings" facility, set up the gateway by calling the :c:func:`net_if_ipv4_set_gw` at runtime. For example: ``CONFIG_NET_CONFIG_MY_IPV4_GW="192.0.2.2"`` To access the internet from a custom application running in QEMU, NAT (masquerading) should be set up for QEMU's source address. Assuming ``192.0.2.1`` is used and the Zephyr network interface is ``zeth``, the following command should be run as root: .. code-block:: console iptables -t nat -A POSTROUTING -j MASQUERADE -s 192.0.2.1/24 iptables -I FORWARD 1 -i zeth -j ACCEPT iptables -I FORWARD 1 -o zeth -m state --state RELATED,ESTABLISHED -j ACCEPT Additionally, IPv4 forwarding should be enabled on the host, and you may need to check that other firewall (iptables) rules don't interfere with masquerading. To enable IPv4 forwarding the following command should be run as root: .. code-block:: console sysctl -w net.ipv4.ip_forward=1 Some applications may also require a DNS server. A number of Zephyr-provided samples assume by default that the DNS server is available on the host (IP ``192.0.2.2``), which, in modern Linux distributions, usually runs at least a DNS proxy. When running with QEMU, it may be required to restart the host's DNS, so it can serve requests on the newly created TAP interface. For example, on Debian-based systems: .. code-block:: console service dnsmasq restart An alternative to relying on the host's DNS server is to use one in the network. For example, ``8.8.8.8`` is a publicly available DNS server. You can configure it using :kconfig:option:`CONFIG_DNS_SERVER1` option. Network connection between two QEMU VMs *************************************** Unlike the VM-to-Host setup described above, VM-to-VM setup is automatic. For sample applications that support this mode (such as the echo_server and echo_client samples), you will need two terminal windows, set up for Zephyr development. Terminal #1: ============ .. zephyr-app-commands:: :zephyr-app: samples/net/sockets/echo_server :host-os: unix :board: qemu_x86 :goals: build :build-args: server :compact: This will start QEMU, waiting for a connection from a client QEMU. Terminal #2: ============ .. zephyr-app-commands:: :zephyr-app: samples/net/sockets/echo_client :host-os: unix :board: qemu_x86 :goals: build :build-args: client :compact: This will start a second QEMU instance, where you should see logging of data sent and received in both. Running multiple QEMU VMs of the same sample ******************************************** If you find yourself wanting to run multiple instances of the same Zephyr sample application, which do not need to talk to each other, use the ``QEMU_INSTANCE`` argument. Start ``socat`` and ``tunslip6`` manually (instead of using the ``loop-xxx.sh`` scripts) for as many instances as you want. Use the following as a guide, replacing MAIN or OTHER. Terminal #1: ============ .. code-block:: console socat PTY,link=/tmp/slip.devMAIN UNIX-LISTEN:/tmp/slip.sockMAIN $ZEPHYR_BASE/../net-tools/tunslip6 -t tapMAIN -T -s /tmp/slip.devMAIN \ 2001:db8::1/64 # Now run Zephyr make -Cbuild run QEMU_INSTANCE=MAIN Terminal #2: ============ .. code-block:: console socat PTY,link=/tmp/slip.devOTHER UNIX-LISTEN:/tmp/slip.sockOTHER $ZEPHYR_BASE/../net-tools/tunslip6 -t tapOTHER -T -s /tmp/slip.devOTHER \ 2001:db8::1/64 make -Cbuild run QEMU_INSTANCE=OTHER ```
/content/code_sandbox/doc/connectivity/networking/qemu_setup.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,084
```restructuredtext .. _network_stack_architecture: Network Stack Architecture ########################## .. toctree:: :maxdepth: 1 :hidden: net_pkt_processing_stats.rst The Zephyr network stack is a native network stack specifically designed for Zephyr OS. It consists of layers, each meant to provide certain services to other layers. Network stack functionality is highly configurable via Kconfig options. .. contents:: :local: :depth: 2 High level overview of the network stack **************************************** .. figure:: zephyr_netstack_overview.svg :alt: Overview of the network stack architecture :figclass: align-center Network stack overview The network stack is layered and consists of the following parts: * **Network Application.** The network application can either use the provided application-level protocol libraries or access the :ref:`BSD socket API <bsd_sockets_interface>` directly to create a network connection, send or receive data, and close a connection. The application can also use the :ref:`network management API <net_mgmt_interface>` to configure the network and set related parameters such as network link options, starting a scan (when applicable), listen network configuration events, etc. The :ref:`network interface API <net_if_interface>` can be used to set IP address to a network interface, taking the network interface down, etc. * **Network Protocols.** This provides implementations for various protocols such as * Application-level network protocols like CoAP, LWM2M, and MQTT. See :ref:`application protocols chapter <net_protocols>` for information about them. * Core network protocols like IPv6, IPv4, UDP, TCP, ICMPv4, and ICMPv6. You access these protocols by using the :ref:`BSD socket API <bsd_sockets_interface>`. * **Network Interface Abstraction.** This provides functionality that is common in all the network interfaces, such as setting network interface down, etc. There can be multiple network interfaces in the system. See :ref:`network interface overview <net_if_interface>` for more details. * **L2 Network Technologies.** This provides a common API for sending and receiving data to and from an actual network device. See :ref:`L2 overview <net_l2_interface>` for more details. These network technologies include :ref:`Ethernet <ethernet_interface>`, :ref:`IEEE 802.15.4 <ieee802154_interface>`, :ref:`Bluetooth <bluetooth_api>`, :ref:`CANBUS <can_api>`, etc. Some of these technologies support IPv6 header compression (6Lo), see `RFC 6282 <path_to_url`_ for details. For example `ARP <path_to_url`_ for IPv4 is done by the :ref:`Ethernet component <ethernet_interface>`. * **Network Device Drivers.** The actual low-level device drivers handle the physical sending or receiving of network packets. Network data flow ***************** An application typically consists of one or more :ref:`threads <threads_v2>` that execute the application logic. When using the :ref:`BSD socket API <bsd_sockets_interface>`, the following things will happen. .. figure:: zephyr_netstack_overview-rx_sequence.svg :alt: Network RX data flow :figclass: align-center Network RX data flow Data receiving (RX) ------------------- 1. A network data packet is received by a device driver. 2. The device driver allocates enough network buffers to store the received data. The network packet is placed in the proper RX queue (implemented by :ref:`k_fifo <fifos_v2>`). By default there is only one receive queue in the system, but it is possible to have up to 8 receive queues. These queues will process incoming packets with different priority. See :ref:`traffic-class-support` for more details. The receive queues also act as a way to separate the data processing pipeline (bottom-half) as the device driver is running in an interrupt context and it must do its processing as fast as possible. 3. The network packet is then passed to the correct L2 driver. The L2 driver can check if the packet is proper and modify it if needed, e.g. strip L2 header and frame check sequence, etc. 4. The packet is processed by a network interface. The network statistics are collected if enabled by :kconfig:option:`CONFIG_NET_STATISTICS`. 5. The packet is then passed to L3 processing. If the packet is IP based, then the L3 layer checks if the packet is a proper IPv6 or IPv4 packet. 6. A socket handler then finds an active socket to which the network packet belongs and puts it in a queue for that socket, in order to separate the networking code from the application. Typically the application is run in userspace context and the network stack is run in kernel context. 7. The application will then receive the data and can process it as needed. The application should have used the :ref:`BSD socket API <bsd_sockets_interface>` to create a socket that will receive the data. .. figure:: zephyr_netstack_overview-tx_sequence.svg :alt: Network TX data flow :figclass: align-center Network TX data flow Data sending (TX) ----------------- 1. The application should use the :ref:`BSD socket API <bsd_sockets_interface>` when sending the data. 2. The application data is prepared for sending to kernel space and then copied to internal net_buf structures. 3. Depending on the socket type, a protocol header is added in front of the data. For example, if the socket is a UDP socket, then a UDP header is constructed and placed in front of the data. 4. An IP header is added to the network packet for a UDP or TCP packet. 5. The network stack will check that the network interface is properly set for the network packet, and also will make sure that the network interface is enabled before the data is queued to be sent. 6. The network packet is then classified and placed to the proper transmit queue (implemented by :ref:`k_fifo <fifos_v2>`). By default there is only one transmit queue in the system, but it is possible to have up to 8 transmit queues. These queues will process the sent packets with different priority. See :ref:`traffic-class-support` for more details. After the transmit packet classification, the packet is checked by the correct L2 layer module. The L2 module will do additional checks for the data and it will also create any L2 headers for the network packet. If everything is ok, the data is given to the network device driver to be sent out. 7. The device driver will send the packet to the network. Note that in both the TX and RX data paths, the queues (:ref:`k_fifo's <fifos_v2>`) form separation points where data is passed from one :ref:`thread <threads_v2>` to another. These :ref:`threads <threads_v2>` might run in different contexts (:ref:`kernel <kernel_api>` vs. :ref:`userspace <usermode_api>`) and with different :ref:`priorities <scheduling_v2>`. Network packet processing statistics ************************************ See information about network processing statistics :ref:`here <net_pkt_processing_stats>`. ```
/content/code_sandbox/doc/connectivity/networking/net-stack-architecture.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,640
```restructuredtext .. _net_pkt_processing_stats: Network Packet Processing Statistics #################################### .. contents:: :local: :depth: 2 This page describes how to get information about network packet processing statistics inside network stack. Network stack contains infrastructure to figure out how long the network packet processing takes either in sending or receiving path. There are two Kconfig options that control this. For transmit (TX) path the option is called :kconfig:option:`CONFIG_NET_PKT_TXTIME_STATS` and for receive (RX) path the options is called :kconfig:option:`CONFIG_NET_PKT_RXTIME_STATS`. Note that for TX, all kind of network packet statistics is collected. For RX, only UDP, TCP or raw packet type network packet statistics is collected. After enabling these options, the :ref:`net stats <net_shell>` network shell command will show this information: .. code-block:: console Avg TX net_pkt (11484) time 67 us Avg RX net_pkt (11474) time 43 us .. note:: The values above and below are from emulated qemu_x86 board and UDP traffic The TX time tells how long it took for network packet from its creation to when it was sent to the network. The RX time tells the time from its creation to when it was passed to the application. The values are in microseconds. The statistics will be collected per traffic class if there are more than one transmit or receive queues defined in the system. These are controlled by :kconfig:option:`CONFIG_NET_TC_TX_COUNT` and :kconfig:option:`CONFIG_NET_TC_RX_COUNT` options. If you enable :kconfig:option:`CONFIG_NET_PKT_TXTIME_STATS_DETAIL` or :kconfig:option:`CONFIG_NET_PKT_RXTIME_STATS_DETAIL` options, then additional information for TX or RX network packets are collected when the network packet traverses the IP stack. After enabling these options, the :ref:`net stats <net_shell>` will show this information: .. code-block:: console Avg TX net_pkt (18902) time 63 us [0->22->15->23=60 us] Avg RX net_pkt (18892) time 42 us [0->9->6->11->13=39 us] The numbers inside the brackets contain information how many microseconds it took for a network packet to go from previous state to next. In the TX example above, the values are averages over **18902** packets and contain this information: * Packet was created by application so the time is **0**. * Packet is about to be placed to transmit queue. The time it took from network packet creation to this state, is **22** microseconds in this example. * The correct TX thread is invoked, and the packet is read from the transmit queue. It took **15** microseconds from previous state. * The network packet was just sent and the network stack is about to free the network packet. It took **23** microseconds from previous state. * In total it took on average **60** microseconds to get the network packet sent. The value **63** tells also the same information, but is calculated differently so there is slight difference because of rounding errors. In the RX example above, the values are averages over **18892** packets and contain this information: * Packet was created network device driver so the time is **0**. * Packet is about to be placed to receive queue. The time it took from network packet creation to this state, is **9** microseconds in this example. * The correct RX thread is invoked, and the packet is read from the receive queue. It took **6** microseconds from previous state. * The network packet is then processed and placed to correct socket queue. It took **11** microseconds from previous state. * The last value tells how long it took from there to the application. Here the value is **13** microseconds. * In total it took on average **39** microseconds to get the network packet sent. The value **42** tells also the same information, but is calculated differently so there is slight difference because of rounding errors. ```
/content/code_sandbox/doc/connectivity/networking/net_pkt_processing_stats.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
889
```restructuredtext .. _usb_device_networking_setup: USB Device Networking ##################### .. contents:: :local: :depth: 2 This page describes how to set up networking between a Linux host and a Zephyr application running on USB supported devices. The board is connected to Linux host using USB cable and provides an Ethernet interface to the host. The :zephyr:code-sample:`sockets-echo-server` application from the Zephyr source distribution is run on supported board. The board is connected to a Linux host using a USB cable providing an Ethernet interface to the host. Basic Setup *********** To communicate with the Zephyr application over a newly created Ethernet interface, we need to assign IP addresses and set up a routing table for the Linux host. After plugging a USB cable from the board to the Linux host, the ``cdc_ether`` driver registers a new Ethernet device with a provided MAC address. You can check that network device is created and MAC address assigned by running dmesg from the Linux host. .. code-block:: console cdc_ether 1-2.7:1.0 eth0: register 'cdc_ether' at usb-0000:00:01.2-2.7, CDC Ethernet Device, 00:00:5e:00:53:01 We need to set it up and assign IP addresses as explained in the following section. Choosing IP addresses ===================== To establish network connection to the board we need to choose IP address for the interface on the Linux host. It make sense to choose addresses in the same subnet we have in Zephyr application. IP addresses usually set in the project configuration files and may be checked also from the shell with following commands. Connect a serial console program (such as puTTY) to the board, and enter this command to the Zephyr shell: .. code-block:: console shell> net iface Interface 0xa800e580 (Ethernet) =============================== Link addr : 00:00:5E:00:53:00 MTU : 1500 IPv6 unicast addresses (max 2): fe80::200:5eff:fe00:5300 autoconf preferred infinite 2001:db8::1 manual preferred infinite ... IPv4 unicast addresses (max 1): 192.0.2.1 manual preferred infinite This command shows that one IPv4 address and two IPv6 addresses have been assigned to the board. We can use either IPv4 or IPv6 for network connection depending on the board network configuration. Next step is to assign IP addresses to the new Linux host interface, in the following steps ``enx00005e005301`` is the name of the interface on my Linux system. Setting IPv4 address and routing ================================ .. code-block:: console # ip address add dev enx00005e005301 192.0.2.2 # ip link set enx00005e005301 up # ip route add 192.0.2.0/24 dev enx00005e005301 Setting IPv6 address and routing ================================ .. code-block:: console # ip address add dev enx00005e005301 2001:db8::2 # ip link set enx00005e005301 up # ip -6 route add 2001:db8::/64 dev enx00005e005301 Testing connection ****************** From the host we can test the connection by pinging Zephyr IP address of the board with: .. code-block:: console $ ping 192.0.2.1 PING 192.0.2.1 (192.0.2.1) 56(84) bytes of data. 64 bytes from 192.0.2.1: icmp_seq=1 ttl=64 time=2.30 ms 64 bytes from 192.0.2.1: icmp_seq=2 ttl=64 time=1.43 ms 64 bytes from 192.0.2.1: icmp_seq=3 ttl=64 time=2.45 ms ... ```
/content/code_sandbox/doc/connectivity/networking/usbnet_setup.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
915
```restructuredtext .. _net_shell: Network Shell ############# Network shell provides helpers for figuring out network status, enabling/disabling features, and issuing commands like ping or DNS resolving. Note that ``net-shell`` should probably not be used in production code as it will require extra memory. See also :ref:`generic shell <shell_api>` for detailed shell information. The following net-shell commands are implemented: .. csv-table:: net-shell commands :header: "Command", "Description" :widths: 15 85 "net allocs", "Print network memory allocations. Only available if :kconfig:option:`CONFIG_NET_DEBUG_NET_PKT_ALLOC` is set." "net arp", "Print information about IPv4 ARP cache. Only available if :kconfig:option:`CONFIG_NET_ARP` is set in IPv4 enabled networks." "net capture", "Monitor network traffic See :ref:`network_monitoring` for details." "net conn", "Print information about network connections." "net dns", "Show how DNS is configured. The command can also be used to resolve a DNS name. Only available if :kconfig:option:`CONFIG_DNS_RESOLVER` is set." "net events", "Enable network event monitoring. Only available if :kconfig:option:`CONFIG_NET_MGMT_EVENT_MONITOR` is set." "net gptp", "Print information about gPTP support. Only available if :kconfig:option:`CONFIG_NET_GPTP` is set." "net iface", "Print information about network interfaces." "net ipv6", "Print IPv6 specific information and configuration. Only available if :kconfig:option:`CONFIG_NET_IPV6` is set." "net mem", "Print information about network memory usage. The command will print more information if :kconfig:option:`CONFIG_NET_BUF_POOL_USAGE` is set." "net nbr", "Print neighbor information. Only available if :kconfig:option:`CONFIG_NET_IPV6` is set." "net ping", "Ping a network host." "net route", "Show IPv6 network routes. Only available if :kconfig:option:`CONFIG_NET_ROUTE` is set." "net sockets", "Show network socket information and statistics. Only available if :kconfig:option:`CONFIG_NET_SOCKETS_OBJ_CORE` and :kconfig:option:`CONFIG_OBJ_CORE` are set." "net stats", "Show network statistics." "net tcp", "Connect/send data/close TCP connection. Only available if :kconfig:option:`CONFIG_NET_TCP` is set." "net vlan", "Show Ethernet virtual LAN information. Only available if :kconfig:option:`CONFIG_NET_VLAN` is set." ```
/content/code_sandbox/doc/connectivity/networking/api/net_shell.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
596
```restructuredtext .. _sntp_interface: Simple Network Time Protocol Library #################################### .. contents:: :local: :depth: 2 Overview ******** The SNTP library implements `IETF RFC4330 (Simple Network Time Protocol v4) <path_to_url`_. SNTP provides a way to synchronize clocks in computer networks. API Reference ************* .. doxygengroup:: sntp ```
/content/code_sandbox/doc/connectivity/networking/api/sntp.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
88
```restructuredtext .. _net_pkt_filter_interface: Network Packet Filtering ######################## .. contents:: :local: :depth: 2 Overview ******** The Network Packet Filtering facility provides the infrastructure to construct custom rules for accepting and/or denying packet transmission and reception. This can be used to create a basic firewall, control network traffic, etc. The :kconfig:option:`CONFIG_NET_PKT_FILTER` must be set in order to enable the relevant APIs. Both the transmission and reception paths may have a list of filter rules. Each rule is made of a set of conditions and a packet outcome. Every packet is subjected to the conditions attached to a rule. When all the conditions for a given rule are true then the packet outcome is immediately determined as specified by the current rule and no more rules are considered. If one condition is false then the next rule in the list is considered. Packet outcome is either ``NET_OK`` to accept the packet or ``NET_DROP`` to drop it. A rule is represented by a :c:struct:`npf_rule` object. It can be inserted to, appended to or removed from a rule list contained in a :c:struct:`npf_rule_list` object using :c:func:`npf_insert_rule()`, :c:func:`npf_append_rule()`, and :c:func:`npf_remove_rule()`. Currently, two such rule lists exist: ``npf_send_rules`` for outgoing packets, and ``npf_recv_rules`` for incoming packets. If a filter rule list is empty then ``NET_OK`` is assumed. If a non-empty rule list runs to the end then ``NET_DROP`` is assumed. However it is recommended to always terminate a non-empty rule list with an explicit default termination rule, either ``npf_default_ok`` or ``npf_default_drop``. Rule conditions are represented by a :c:struct:`npf_test`. This structure can be embedded into a larger structure when a specific condition requires extra test data. It is up to the test function for such conditions to retrieve the outer structure from the provided ``npf_test`` structure pointer. Convenience macros are provided in :zephyr_file:`include/zephyr/net/net_pkt_filter.h` to statically define condition instances for various conditions, and :c:macro:`NPF_RULE()` to create a rule instance to tie them. Examples ******** Here's an example usage: .. code-block:: c static NPF_SIZE_MAX(maxsize_200, 200); static NPF_ETH_TYPE_MATCH(ip_packet, NET_ETH_PTYPE_IP); static NPF_RULE(small_ip_pkt, NET_OK, ip_packet, maxsize_200); void install_my_filter(void) { npf_insert_recv_rule(&npf_default_drop); npf_insert_recv_rule(&small_ip_pkt); } The above would accept IP packets that are 200 bytes or smaller, and drop all other packets. Another (less efficient) way to achieve the same result could be: .. code-block:: c static NPF_SIZE_MIN(minsize_201, 201); static NPF_ETH_TYPE_UNMATCH(not_ip_packet, NET_ETH_PTYPE_IP); static NPF_RULE(reject_big_pkts, NET_DROP, minsize_201); static NPF_RULE(reject_non_ip, NET_DROP, not_ip_packet); void install_my_filter(void) { npf_append_recv_rule(&reject_big_pkts); npf_append_recv_rule(&reject_non_ip); npf_append_recv_rule(&npf_default_ok); } API Reference ************* .. doxygengroup:: net_pkt_filter .. doxygengroup:: npf_basic_cond .. doxygengroup:: npf_eth_cond ```
/content/code_sandbox/doc/connectivity/networking/api/net_pkt_filter.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
794
```restructuredtext .. _ethernet_mgmt_interface: Ethernet Management ################### .. contents:: :local: :depth: 2 Overview ******** Ethernet management API provides functions to manage the Ethernet network interface low level status. The caller of these functions can: * raise ``carrier ON`` or ``carrier OFF`` management events * raise ``VLAN enabled`` or ``VLAN disabled`` management events Typically the ``carrier OFF`` event would be generated by the Ethernet device driver when it notices that the Ethernet cable is disconnected. The ``carrier ON`` event would be generated if the Ethernet device driver notices that the Ethernet cable is re-connected. Currently the VLAN events are generated by the Ethernet L2 layer when a specific VLAN tag is either enabled or disabled. The user application can monitor these events if it needs to act when the corresponding status changes. API Reference ************* .. doxygengroup:: ethernet_mgmt ```
/content/code_sandbox/doc/connectivity/networking/api/ethernet_mgmt.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
194
```restructuredtext .. _net_config_interface: Network Configuration Library ############################# .. contents:: :local: :depth: 2 Overview ******** The network configuration library sets up networking devices in a semi-automatic way during the system boot, based on user-supplied Kconfig options. The following Kconfig options affect how configuration library will setup the system: .. csv-table:: Kconfig options for network configuration library :header: "Option name", "Description" :widths: 45 55 ":kconfig:option:`CONFIG_NET_CONFIG_SETTINGS`", "This option controls whether the network system is configured or initialized at all. If not set, then the config library is not used for initialization and the application needs to do all the network related configuration itself. If this option is set, then the user can optionally configure static IP addresses to be set to the first network interface in the system. Typically setting static IP addresses is only usable in testing and should not be used in production code. See the config library Kconfig file :zephyr_file:`subsys/net/lib/config/Kconfig` for specific options to set the static IP addresses." ":kconfig:option:`CONFIG_NET_CONFIG_AUTO_INIT`", "The networking system is automatically configured when the device is started." ":kconfig:option:`CONFIG_NET_CONFIG_INIT_TIMEOUT`", "This tells how long to wait for the networking to be ready and available. If for example IPv4 address from DHCPv4 is not received within this limit, then a call to ``net_config_init()`` will return error during the device startup." ":kconfig:option:`CONFIG_NET_CONFIG_NEED_IPV4`", "The network application needs IPv4 support to function properly. This option makes sure the network application is initialized properly in order to use IPv4. If :kconfig:option:`CONFIG_NET_IPV4` is not enabled, then setting this option will automatically enable IPv4." ":kconfig:option:`CONFIG_NET_CONFIG_NEED_IPV6`", "The network application needs IPv6 support to function properly. This option makes sure the network application is initialized properly in order to use IPv6. If :kconfig:option:`CONFIG_NET_IPV6` is not enabled, then setting this option will automatically enable IPv6." ":kconfig:option:`CONFIG_NET_CONFIG_NEED_IPV6_ROUTER`", "If IPv6 is enabled, then this option tells that the network application needs IPv6 router to exists before continuing. This means in practice that the application wants to wait until it receives IPv6 router advertisement message before continuing." ":kconfig:option:`CONFIG_NET_CONFIG_MY_IPV6_ADDR`","Local static IPv6 address assigned to the default network interface." ":kconfig:option:`CONFIG_NET_CONFIG_PEER_IPV6_ADDR`","Peer static IPv6 address. This is mainly useful in testing setups where the application can connect to a pre-defined host." ":kconfig:option:`CONFIG_NET_CONFIG_MY_IPV4_ADDR`","Local static IPv4 address assigned to the default network interface." ":kconfig:option:`CONFIG_NET_CONFIG_MY_IPV4_NETMASK`","Static IPv4 netmask assigned to the IPv4 address." ":kconfig:option:`CONFIG_NET_CONFIG_MY_IPV4_GW`","Static IPv4 gateway address assigned to the default network interface." ":kconfig:option:`CONFIG_NET_CONFIG_PEER_IPV4_ADDR`","Peer static IPv4 address. This is mainly useful in testing setups where the application can connect to a pre-defined host." Sample usage ************ If :kconfig:option:`CONFIG_NET_CONFIG_AUTO_INIT` is set, then the configuration library is automatically enabled and run during the device boot. In this case, the library will call ``net_config_init()`` automatically and the application does not need to do any network configuration. If you want to use the network configuration library but without automatic initialization, you can call ``net_config_init()`` manually. The ``flags`` parameter can be used to give hints to the library about what kind of functionality the application wishes to have before the actual application starts. API Reference ************* .. doxygengroup:: net_config ```
/content/code_sandbox/doc/connectivity/networking/api/net_config.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
920
```restructuredtext .. _tls_credentials_shell: TLS Credentials Shell ##################### The TLS Credentials shell provides a command-line interface for managing installed TLS credentials. Commands ******** .. _tls_credentials_shell_buf_cred: Buffer Credential (``buf``) =========================== Buffer data incrementally into the credential buffer so that it can be added using the :ref:`tls_credentials_shell_add_cred` command. Alternatively, clear the credential buffer. Usage ----- To append ``<DATA>`` to the credential buffer, use: .. code-block:: shell cred buf <DATA> Use this as many times as needed to load the full credential into the credential buffer, then use the :ref:`tls_credentials_shell_add_cred` command to store it. To clear the credential buffer, use: .. code-block:: shell cred buf clear Arguments --------- .. csv-table:: :header: "Argument", "Description" :widths: 15 85 "``<DATA>``", "Text data to be appended to credential buffer. It can be either text, or base64-encoded binary. See :ref:`tls_credentials_shell_add_cred` and :ref:`tls_credentials_shell_data_formats` for details." .. _tls_credentials_shell_add_cred: Add Credential (``add``) ========================= Add a TLS credential to the TLS Credential store. Credential contents can be provided in-line with the call to ``cred add``, or will otherwise be sourced from the credential buffer. Usage ----- To add a TLS credential using the data from the credential buffer, use: .. code-block:: shell cred add <SECTAG> <TYPE> <BACKEND> <FORMAT> To add a TLS credential using data provided with the same command, use: .. code-block:: shell cred add <SECTAG> <TYPE> <BACKEND> <FORMAT> <DATA> Arguments --------- .. csv-table:: :header: "Argument", "Description" :widths: 15 85 "``<SECTAG>``", "The sectag to use for the new credential. Can be any non-negative integer." "``<TYPE>``", "The type of credential to add. See :ref:`tls_credentials_shell_cred_types` for valid values." "``<BACKEND>``", "Reserved. Must always be ``DEFAULT`` (case-insensitive)." "``<FORMAT>``", "Specifies the storage format of the provided credential. See :ref:`tls_credentials_shell_data_formats` for valid values." "``<DATA>``", "If provided, this argument will be used as the credential data, instead of any data in the credential buffer. Can be either text, or base64-encoded binary." .. _tls_credentials_shell_del_cred: Delete Credential (``del``) =========================== Delete a specified credential from the credential store. Usage ----- To delete a credential matching a specified sectag and credential type (if it exists), use: .. code-block:: shell cred del <SECTAG> <TYPE> Arguments --------- .. csv-table:: :header: "Argument", "Description" :widths: 15 85 "``<SECTAG>``", "The sectag of the credential to delete. Can be any non-negative integer." "``<TYPE>``", "The type of credential to delete. See :ref:`tls_credentials_shell_cred_types` for valid values." .. _tls_credentials_shell_get_cred: Get Credential Contents (``get``) ================================= Retrieve and print the contents of a specified credential. Usage ----- To retrieve and print a credential matching a specified sectag and credential type (if it exists), use: .. code-block:: shell cred get <SECTAG> <TYPE> <FORMAT> Arguments --------- .. csv-table:: :header: "Argument", "Description" :widths: 15 85 "``<SECTAG>``", "The sectag of the credential to get. Can be any non-negative integer." "``<TYPE>``", "The type of credential to get. See :ref:`tls_credentials_shell_cred_types` for valid values." "``<FORMAT>``", "Specifies the retrieval format for the provided credential. See :ref:`tls_credentials_shell_data_formats` for valid values." .. _tls_credentials_shell_list_cred: List Credentials (``list``) =========================== List TLS credentials in the credential store. Usage ----- To list all available credentials, use: .. code-block:: shell cred list To list all credentials with a specified sectag, use: .. code-block:: shell cred list <SECTAG> To list all credentials with a specified credential type, use: .. code-block:: shell cred list any <TYPE> To list all credentials with a specified credential type and sectag, use: .. code-block:: shell cred list <SECTAG> <TYPE> Arguments --------- .. csv-table:: :header: "Argument", "Description" :widths: 15 85 "``<SECTAG>``", "Optional. If provided, only list credentials with this sectag. Pass ``any`` or omit to allow any sectag. Otherwise, can be any non-negative integer." "``<TYPE>``", "Optional. If provided, only list credentials with this credential type. Pass ``any`` or omit to allow any credential type. Otherwise, see :ref:`tls_credentials_shell_cred_types` for valid values." Output ------ The command outputs all matching credentials in the following (CSV-compliant) format: .. code-block:: shell <SECTAG>,<TYPE>,<DIGEST>,<STATUS> Where: .. csv-table:: :header: "Symbol", "Value" :widths: 15 85 "``<SECTAG>``", "The sectag of the listed credential. A non-negative integer." "``<TYPE>``", "Credential type short-code (see :ref:`tls_credentials_shell_cred_types` for details) of the listed credential." "``<DIGEST>``", "A string digest representing the credential contents. The exact nature of this digest may vary depending on credentials storage backend, but currently for all backends this is a base64 encoded SHA256 hash of the raw credential contents (so different storage formats for essentially identical credentials will have different digests)." "``<STATUS>``", "Status code indicating success or failure with generating a digest of the listed credential. 0 if successful, negative error code specific to the storage backend otherwise. Lines for which status is not zero will be printed with error formatting." After the list is printed, a final summary of the found credentials will be printed in the form: .. code-block:: shell <N> credentials found. Where `<N>` is the number of credentials found, and is zero if none are found. .. _tls_credentials_shell_cred_types: Credential Types **************** The following keywords (case-insensitive) may be used to specify a credential type: .. csv-table:: :header: "Keyword(s)", "Meaning" :widths: 15 85 "``CA_CERT``, ``CA``", "A trusted CA certificate." "``SERVER_CERT``, ``SELF_CERT``, ``CLIENT_CERT``, ``CLIENT``, ``SELF``, ``SERV``", "Self or server certificate." "``PRIVATE_KEY``, ``PK``", "A private key." "``PRE_SHARED_KEY``, ``PSK``", "A pre-shared key." "``PRE_SHARED_KEY_ID``, ``PSK_ID``", "ID for pre-shared key." .. _tls_credentials_shell_data_formats: Storage/Retrieval Formats ************************* The :ref:`tls_credentials <sockets_tls_credentials_subsys>` module treats stored credentials as arbitrary binary buffers. For convenience, the TLS credentials shell offers four formats for providing and later retrieving these buffers using the shell. These formats and their (case-insensitive) keywords are as follows: .. csv-table:: :header: "Keyword", "Meaning", "Behavior during storage (``cred add``)", "Behavior during retrieval (``cred get``)" :widths: 3, 32, 34, 34 "``BIN``", "Credential is handled by shell as base64 and stored without NULL termination.", "Data entered into shell will be decoded from base64 into raw binary before storage. No terminator will be appended.", "Stored data will be encoded into base64 before being printed." "``BINT``", "Credential is handled by shell as base64 and stored with NULL termination.", "Data entered into shell will be decoded from base64 into raw binary and a NULL terminator will be appended before storage.", "NULL terminator will be truncated from stored data before said data is encoded into base64 and then printed." "``STR``", "Credential is handled by shell as literal string and stored without NULL termination.", "Text data entered into shell will be passed into storage as-written, without a NULL terminator.", "Stored data will be printed as text. Non-printable characters will be printed as ``?``" "``STRT``", "Credential is handled by shell as literal string and stored with NULL-termination.", "Text data entered into shell will be passed into storage as-written, with a NULL terminator.", "NULL terminator will be truncated from stored data before said data is printed as text. Non-printable characters will be printed as ``?``" The ``BIN`` format can be used to install credentials of any type, since base64 can be used to encode any concievable binary buffer. The remaining three formats are provided for convenience in special use-cases. For example: - To install printable pre-shared-keys, use ``STR`` to enter the PSK without first encoding it. This ensures it is stored without a NULL terminator. - To install DER-formatted X.509 certificates (or other raw-binary credentials, such as non-printable PSKs) base64-encode the binary and use the ``BIN`` format. - To install PEM-formatted X.509 certificates or certificate chains, base64 encode the full PEM string (including new-lines and ``----BEGIN X ----`` / ``----END X----`` markers), and then use the ``BINT`` format to make sure the stored string is NULL-terminated. This is required because Zephyr does not support multi-line strings in the shell. Otherwise, the ``STRT`` format could be used for this purpose without base64 encoding. It is possible to use ``BIN`` instead if you manually encode a NULL terminator into the base64. ```
/content/code_sandbox/doc/connectivity/networking/api/tls_credentials_shell.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,233
```restructuredtext .. _net_capture_interface: Network Packet Capture ###################### .. contents:: :local: :depth: 2 Overview ******** The ``net_capture`` API allows user to monitor the network traffic in one of the Zephyr network interfaces and send that traffic to external system for analysis. The monitoring can be setup either manually using ``net-shell`` or automatically by using the ``net_capture`` API. Cooked Mode Capture ******************* If capturing is enabled and configured, the system will automatically capture network traffic for a given network interface. If you would like to capture network data when there is no network interface involved, then you need to use the cooked mode capture API. In cooked mode capture, arbitrary network packets can be captured and there does not need to be network interface involved. For example low level HDLC packets in PPP can be captured, as the HDLC L2 layer data is stripped away when using the normal network interface based capture. Also CANBUS or Bluetooth network data could be captured although currently there is no support in the network stack to capture those. The cooked mode capture works like this: * An ``any`` network interface is created. It acts as a sink where the cooked mode captured packets are written by the cooked mode capture API. * A ``cooked`` virtual network interface is attached on top of this ``any`` interface. * The ``cooked`` interface must be configured to capture certain L2 packet types using the network interface configuration API. * When cooked mode capture API is used, the caller must specify what is the layer 2 protocol type of the captured data. The cooked mode capture API is then able to determine what to capture when receiving such a L2 packet. * The network packet capturing infrastructure is then setup so that the ``cooked`` interface is marked as captured network interface. The packets received by the ``cooked`` interface via the ``any`` interface are then automatically placed to the capture IP tunnel and sent to remote host for analysis. For example, in the sample capture application, these network interfaces are created: .. code-block:: c Interface any (0x808ab3c) (Dummy) [1] ================================ Virtual interfaces attached to this : 2 Device : NET_ANY (0x80849a4) Interface cooked (0x808ac94) (Virtual) [2] ================================== Virtual name : Cooked mode capture Attached : 1 (Dummy / 0x808ab3c) Device : NET_COOKED (0x808497c) Interface eth0 (0x808adec) (Ethernet) [3] =================================== Virtual interfaces attached to this : 4 Device : zeth0 (0x80849b8) IPv6 unicast addresses (max 4): fe80::5eff:fe00:53e6 autoconf preferred infinite 2001:db8::1 manual preferred infinite IPv4 unicast addresses (max 2): 192.0.2.1/255.255.255.0 overridable preferred infinite Interface net0 (0x808af44) (Virtual) [4] ================================== Virtual name : Capture tunnel Attached : 3 (Ethernet / 0x808adec) Device : IP_TUNNEL0 (0x8084990) IPv6 unicast addresses (max 4): 2001:db8:200::1 manual preferred infinite fe80::efed:6dff:fef2:b1df autoconf preferred infinite fe80::56da:1eff:fe5e:bc02 autoconf preferred infinite In this example, the ``192.0.2.2`` is the address of the outer end point of the host that terminates the tunnel. Zephyr uses this address to select the internal interface to use for the tunnel. In this example it is interface 3. The interface 2 is a virtual interface that runs on top of interface 1. The cooked capture packets are written by the capture API to sink interface 1. The packets propagate to interface 2 because it is linked to the first interface. The ``net capture enable 2`` net-shell command will cause the packets sent to interface 2 to be written to capture interface 4, which in turn then capsulates the packets and tunnels them to peer via the Ethernet interface 3. The above IP addresses might change if you change the addresses in the sample :zephyr_file:`samples/net/capture/overlay-tunnel.conf` file. Sample usage ************ See :zephyr:code-sample:`net-capture` sample application and :ref:`network_monitoring` for details. API Reference ************* .. doxygengroup:: net_capture ```
/content/code_sandbox/doc/connectivity/networking/api/capture.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,040
```restructuredtext .. _dhcpv6_interface: DHCPv6 ###### .. contents:: :local: :depth: 2 Overview ******** The Dynamic Host Configuration Protocol (DHCP) for IPv6 is a network management protocol used on IPv6 based networks. A DHCPv6 server dynamically assigns an IPv6 address and other network configuration parameters to each device on a network so they can communicate with other IP networks. See this `DHCPv6 Wikipedia article <path_to_url`_ for a detailed overview of how DHCPv6 works. Note that Zephyr only supports DHCPv6 client functionality. API Reference ************* .. doxygengroup:: dhcpv6 ```
/content/code_sandbox/doc/connectivity/networking/api/dhcpv6.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
147
```restructuredtext .. _coap_client_interface: CoAP client ########### .. contents:: :local: :depth: 2 Overview ******** The CoAP client library allows application to send CoAP requests and parse CoAP responses. The library can be enabled with :kconfig:option:`CONFIG_COAP_CLIENT` Kconfig option. The application is notified about the response via a callback that is provided to the API in the request. The CoAP client handles the communication over sockets. As the CoAP client doesn't create socket it is using, the application is responsible for creating the socket. Plain UDP or DTLS sockets are supported. Sample Usage ************ The following is an example of a CoAP client initialization and request sending: .. code-block:: c static struct coap_client; struct coap_client_request req = { 0 }; coap_client_init(&client, NULL); req.method = COAP_METHOD_GET; req.confirmable = true; req.path = "test"; req.fmt = COAP_CONTENT_FORMAT_TEXT_PLAIN; req.cb = response_cb; req.payload = NULL; req.len = 0; /* Sock is a file descriptor referencing a socket, address is the sockaddr struct for the * destination address of the request or NULL if the socket is already connected. */ ret = coap_client_req(&client, sock, &address, &req, -1); Before any requests can be sent, the CoAP client needs to be initialized. After initialization, the application can send a CoAP request and wait for the response. Currently only one request can be sent for a single CoAP client at a time. There can be multiple CoAP clients. The callback provided in the callback will be called in following cases: - There is a response for the request - The request failed for some reason The callback contains a flag `last_block`, which indicates if there is more data to come in the response and means that the current response is part of a blockwise transfer. When the `last_block` is set to true, the response is finished and the client is ready for the next request after returning from the callback. If the server responds to the request, the library provides the response to the application through the response callback registered in the request structure. As the response can be a blockwise transfer and the client calls the callback once per each block, the application should be to process all of the blocks to be able to process the response. The following is an example of a very simple response handling function: .. code-block:: c void response_cb(int16_t code, size_t offset, const uint8_t *payload, size_t len, bool last_block, void *user_data) { if (code >= 0) { LOG_INF("CoAP response from server %d", code); if (last_block) { LOG_INF("Last packet received"); } } else { LOG_ERR("Error in sending request %d", code); } } CoAP options may also be added to the request by the application. The following is an example of the application adding a Block2 option to the initial request, to suggest a maximum block size to the server for a resource that it expects to be large enough to require a blockwise transfer (see RFC7959 Figure 3: Block-Wise GET with Early Negotiation). .. code-block:: c static struct coap_client; struct coap_client_request req = { 0 }; /* static, since options must remain valid throughout the whole execution of the request */ static struct coap_client_option block2_option; coap_client_init(&client, NULL); block2_option = coap_client_option_initial_block2(); req.method = COAP_METHOD_GET; req.confirmable = true; req.path = "test"; req.fmt = COAP_CONTENT_FORMAT_TEXT_PLAIN; req.cb = response_cb; req.options = &block2_option; req.num_options = 1; req.payload = NULL; req.len = 0; ret = coap_client_req(&client, sock, &address, &req, -1); API Reference ************* .. doxygengroup:: coap_client ```
/content/code_sandbox/doc/connectivity/networking/api/coap_client.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
907
```restructuredtext .. _net_stats_interface: Network Statistics ################## .. contents:: :local: :depth: 2 Overview ******** Network statistics are collected if :kconfig:option:`CONFIG_NET_STATISTICS` is set. Individual component statistics for IPv4 or IPv6 can be turned off if those statistics are not needed. See various options in :zephyr_file:`subsys/net/ip/Kconfig.stats` file for details. By default, the system collects network statistics per network interface. This can be controlled by :kconfig:option:`CONFIG_NET_STATISTICS_PER_INTERFACE` option. The :kconfig:option:`CONFIG_NET_STATISTICS_USER_API` option can be set if the application wants to collect statistics for further processing. The network management interface API is used for that. See :ref:`net_mgmt_interface` for details. The :kconfig:option:`CONFIG_NET_STATISTICS_ETHERNET` option can be set to collect generic Ethernet statistics. If the :kconfig:option:`CONFIG_NET_STATISTICS_ETHERNET_VENDOR` option is set, then Ethernet device driver can collect Ethernet device specific statistics. These statistics can then be transferred to application for processing. If the :kconfig:option:`CONFIG_NET_SHELL` option is set, then network shell can show statistics information with ``net stats`` command. API Reference ************* .. doxygengroup:: net_stats ```
/content/code_sandbox/doc/connectivity/networking/api/net_stats.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
296
```restructuredtext .. _tftp_interface: TFTP #### Zephyr provides a simple TFTP client library that can enabled with :kconfig:option:`CONFIG_MQTT_SN_LIB` Kconfig option. See :zephyr:code-sample:`TFTP client sample application <tftp-client>` for more information about the library usage. API Reference ************* .. doxygengroup:: tftp_client ```
/content/code_sandbox/doc/connectivity/networking/api/tftp.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
87
```restructuredtext .. _websocket_interface: Websocket Client API #################### .. contents:: :local: :depth: 2 Overview ******** The Websocket client library allows Zephyr to connect to a Websocket server. The Websocket client API can be used directly by application to establish a Websocket connection to server, or it can be used as a transport for other network protocols like MQTT. See this `Websocket Wikipedia article <path_to_url`_ for a detailed overview of how Websocket works. For more information about the protocol itself, see `IETF RFC6455 The WebSocket Protocol <path_to_url`_. Websocket Transport ******************* The Websocket API allows it to be used as a transport for other high level protocols like MQTT. The Zephyr MQTT client library can be configured to use Websocket transport by enabling :kconfig:option:`CONFIG_MQTT_LIB_WEBSOCKET` and :kconfig:option:`CONFIG_WEBSOCKET_CLIENT` Kconfig options. First a socket needs to be created and connected to the Websocket server: .. code-block:: c sock = socket(family, SOCK_STREAM, IPPROTO_TCP); ... ret = connect(sock, addr, addr_len); ... The Websocket transport socket is then created like this: .. code-block:: c ws_sock = websocket_connect(sock, &config, timeout, user_data); The Websocket socket can then be used to send or receive data, and the Websocket client API will encapsulate the sent or received data to/from Websocket packet payload. Both the :c:func:`websocket_xxx()` API or normal BSD socket API functions can be used to send and receive application data. .. code-block:: c ret = websocket_send_msg(ws_sock, buf_to_send, buf_len, WEBSOCKET_OPCODE_DATA_BINARY, true, true, K_FOREVER); ... ret = send(ws_sock, buf_to_send, buf_len, 0); If normal BSD socket functions are used, then currently only TEXT data is supported. In order to send BINARY data, the :c:func:`websocket_send_msg()` must be used. When done, the Websocket transport socket must be closed. User should handle the lifecycle(close/reuse) of tcp socket after websocket_disconnect. .. code-block:: c ret = close(ws_sock); or ret = websocket_disconnect(ws_sock); API Reference ************* .. doxygengroup:: websocket ```
/content/code_sandbox/doc/connectivity/networking/api/websocket.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
526
```restructuredtext .. _lldp_interface: Link Layer Discovery Protocol ############################# .. contents:: :local: :depth: 2 Overview ******** The Link Layer Discovery Protocol (LLDP) is a vendor-neutral link layer protocol used by network devices for advertising their identity, capabilities, and neighbors on a wired Ethernet network. For more information, see this `LLDP Wikipedia article <path_to_url`_. API Reference ************* .. doxygengroup:: lldp ```
/content/code_sandbox/doc/connectivity/networking/api/lldp.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
103
```restructuredtext .. _lwm2m_interface: Lightweight M2M (LWM2M) ####################### .. contents:: :local: :depth: 2 Overview ******** Lightweight Machine to Machine (LwM2M) is an application layer protocol designed with device management, data reporting and device actuation in mind. Based on CoAP/UDP, `LwM2M`_ is a `standard <path_to_url`_ defined by the Open Mobile Alliance and suitable for constrained devices by its use of CoAP packet-size optimization and a simple, stateless flow that supports a REST API. One of the key differences between LwM2M and CoAP is that an LwM2M client initiates the connection to an LwM2M server. The server can then use the REST API to manage various interfaces with the client. LwM2M uses a simple resource model with the core set of objects and resources defined in the specification. The LwM2M library can be enabled with :kconfig:option:`CONFIG_LWM2M` Kconfig option. Example LwM2M object and resources: Device ****************************************** *Object definition* .. list-table:: :header-rows: 1 * - Object ID - Name - Instance - Mandatory * - 3 - Device - Single - Mandatory *Resource definitions* ``* R=Read, W=Write, E=Execute`` .. list-table:: :header-rows: 1 * - ID - Name - OP\* - Instance - Mandatory - Type * - 0 - Manufacturer - R - Single - Optional - String * - 1 - Model - R - Single - Optional - String * - 2 - Serial number - R - Single - Optional - String * - 3 - Firmware version - R - Single - Optional - String * - 4 - Reboot - E - Single - Mandatory - * - 5 - Factory Reset - E - Single - Optional - * - 6 - Available Power Sources - R - Multiple - Optional - Integer 0-7 * - 7 - Power Source Voltage (mV) - R - Multiple - Optional - Integer * - 8 - Power Source Current (mA) - R - Multiple - Optional - Integer * - 9 - Battery Level % - R - Single - Optional - Integer * - 10 - Memory Free (Kb) - R - Single - Optional - Integer * - 11 - Error Code - R - Multiple - Optional - Integer 0-8 * - 12 - Reset Error - E - Single - Optional - * - 13 - Current Time - RW - Single - Optional - Time * - 14 - UTC Offset - RW - Single - Optional - String * - 15 - Timezone - RW - Single - Optional - String * - 16 - Supported Binding - R - Single - Mandatory - String * - 17 - Device Type - R - Single - Optional - String * - 18 - Hardware Version - R - Single - Optional - String * - 19 - Software Version - R - Single - Optional - String * - 20 - Battery Status - R - Single - Optional - Integer 0-6 * - 21 - Memory Total (Kb) - R - Single - Optional - Integer * - 22 - ExtDevInfo - R - Multiple - Optional - ObjLnk The server could query the ``Manufacturer`` resource for ``Device`` object instance 0 (the default and only instance) by sending a ``READ 3/0/0`` operation to the client. The full list of registered objects and resource IDs can be found in the `LwM2M registry`_. Zephyr's LwM2M library lives in the :zephyr_file:`subsys/net/lib/lwm2m`, with a client sample in :zephyr_file:`samples/net/lwm2m_client`. For more information about the provided sample see: :zephyr:code-sample:`lwm2m-client`. The sample can be configured to use normal unsecure network sockets or sockets secured via DTLS. The Zephyr LwM2M library implements the following items: * engine to process networking events and core functions * RD client which performs BOOTSTRAP and REGISTRATION functions * SenML CBOR, SenML JSON, CBOR, TLV, JSON, and plain text formatting functions * LwM2M Technical Specification Enabler objects such as Security, Server, Device, Firmware Update, etc. * Extended IPSO objects such as Light Control, Temperature Sensor, and Timer By default, the library implements `LwM2M specification 1.0.2`_ and can be set to `LwM2M specification 1.1.1`_ with a Kconfig option. For more information about LwM2M visit `OMA Specworks LwM2M`_. Sample usage ************ To use the LwM2M library, start by creating an LwM2M client context :c:struct:`lwm2m_ctx` structure: .. code-block:: c /* LwM2M client context */ static struct lwm2m_ctx client; Create callback functions for LwM2M resource executions: .. code-block:: c static int device_reboot_cb(uint16_t obj_inst_id, uint8_t *args, uint16_t args_len) { LOG_INF("Device rebooting."); LOG_PANIC(); sys_reboot(0); return 0; /* won't reach this */ } The LwM2M RD client can send events back to the sample. To receive those events, setup a callback function: .. code-block:: c static void rd_client_event(struct lwm2m_ctx *client, enum lwm2m_rd_client_event client_event) { switch (client_event) { case LWM2M_RD_CLIENT_EVENT_NONE: /* do nothing */ break; case LWM2M_RD_CLIENT_EVENT_BOOTSTRAP_REG_FAILURE: LOG_DBG("Bootstrap registration failure!"); break; case LWM2M_RD_CLIENT_EVENT_BOOTSTRAP_REG_COMPLETE: LOG_DBG("Bootstrap registration complete"); break; case LWM2M_RD_CLIENT_EVENT_BOOTSTRAP_TRANSFER_COMPLETE: LOG_DBG("Bootstrap transfer complete"); break; case LWM2M_RD_CLIENT_EVENT_REGISTRATION_FAILURE: LOG_DBG("Registration failure!"); break; case LWM2M_RD_CLIENT_EVENT_REGISTRATION_COMPLETE: LOG_DBG("Registration complete"); break; case LWM2M_RD_CLIENT_EVENT_REG_TIMEOUT: LOG_DBG("Registration timeout!"); break; case LWM2M_RD_CLIENT_EVENT_REG_UPDATE_COMPLETE: LOG_DBG("Registration update complete"); break; case LWM2M_RD_CLIENT_EVENT_DEREGISTER_FAILURE: LOG_DBG("Deregister failure!"); break; case LWM2M_RD_CLIENT_EVENT_DISCONNECT: LOG_DBG("Disconnected"); break; case LWM2M_RD_CLIENT_EVENT_REG_UPDATE: LOG_DBG("Registration update"); break; case LWM2M_RD_CLIENT_EVENT_DEREGISTER: LOG_DBG("Deregistration client"); break; case LWM2M_RD_CLIENT_EVENT_SERVER_DISABLED: LOG_DBG("LwM2M server disabled"); break; } } Next we assign ``Security`` resource values to let the client know where and how to connect as well as set the ``Manufacturer`` and ``Reboot`` resources in the ``Device`` object with some data and the callback we defined above: .. code-block:: c /* * Server URL of default Security object = 0/0/0 * Use leshan.eclipse.org server IP (5.39.83.206) for connection */ lwm2m_set_string(&LWM2M_OBJ(0, 0, 0), "coap://5.39.83.206"); /* * Security Mode of default Security object = 0/0/2 * 3 = NoSec mode (no security beware!) */ lwm2m_set_u8(&LWM2M_OBJ(0, 0, 2), 3); #define CLIENT_MANUFACTURER "Zephyr Manufacturer" /* * Manufacturer resource of Device object = 3/0/0 * We use lwm2m_set_res_data() function to set a pointer to the * CLIENT_MANUFACTURER string. * Note the LWM2M_RES_DATA_FLAG_RO flag which stops the engine from * trying to assign a new value to the buffer. */ lwm2m_set_res_data(&LWM2M_OBJ(3, 0, 0), CLIENT_MANUFACTURER, sizeof(CLIENT_MANUFACTURER), LWM2M_RES_DATA_FLAG_RO); /* Reboot resource of Device object = 3/0/4 */ lwm2m_register_exec_callback(&LWM2M_OBJ(3, 0, 4), device_reboot_cb); Lastly, we start the LwM2M RD client (which in turn starts the LwM2M engine). The second parameter of :c:func:`lwm2m_rd_client_start` is the client endpoint name. This is important as it needs to be unique per LwM2M server: .. code-block:: c (void)memset(&client, 0x0, sizeof(client)); lwm2m_rd_client_start(&client, "unique-endpoint-name", 0, rd_client_event); .. _lwm2m_security: LwM2M security modes ******************** The Zephyr LwM2M library can be used either without security or use DTLS to secure the communication channel. When using DTLS with the LwM2M engine, PSK (Pre-Shared Key) and X.509 certificates are the security modes that can be used to secure the communication. The engine uses LwM2M Security object (Id 0) to read the stored credentials and feed keys from the security object into the TLS credential subsystem, see :ref:`secure sockets documentation <secure_sockets_interface>`. Enable the :kconfig:option:`CONFIG_LWM2M_DTLS_SUPPORT` Kconfig option to use the security. Depending on the selected mode, the security object must contain following data: PSK Security Mode (Resource ID 2) set to zero (Pre-Shared Key mode). Identity (Resource ID 3) contains PSK ID in binary form. Secret key (Resource ID 5) contains the PSK key in binary form. If the key or identity is provided as a hex string, it must be converted to binary before storing into the security object. X509 When X509 certificates are used, set Security Mode (ID 2) to ``2`` (Certificate mode). Identity (ID 3) is used to store the client certificate and Secret key (ID 5) must have a private key associated with the certificate. Server Public Key resource (ID 4) must contain a server certificate or CA certificate used to sign the certificate chain. If the :kconfig:option:`CONFIG_MBEDTLS_PEM_CERTIFICATE_FORMAT` Kconfig option is enabled, certificates and private key can be entered in PEM format. Otherwise, they must be in binary DER format. NoSec When no security is used, set Security Mode (Resource ID 2) to ``3`` (NoSec). In all modes, Server URI resource (ID 0) must contain the full URI for the target server. When DNS names are used, the DNS resolver must be enabled. When DTLS is used, following options are recommended to reduce DTLS handshake traffic when connection is re-established: * :kconfig:option:`CONFIG_LWM2M_DTLS_CID` enables DTLS Connection Identifier support. When server supports it, this completely removes the handshake when device resumes operation after long idle period. Greatly helps when NAT mappings have timed out. * :kconfig:option:`CONFIG_LWM2M_TLS_SESSION_CACHING` uses session cache when before falling back to full DTLS handshake. Reduces few packets from handshake, when session is still cached on server side. Most significant effect is to avoid full registration. LwM2M stack provides callbacks in the :c:struct:`lwm2m_ctx` structure. They are used to feed keys from the LwM2M security object into the TLS credential subsystem. By default, these callbacks can be left as NULL pointers, in which case default callbacks are used. When an external TLS stack, or non-default socket options are required, you can overwrite the :c:func:`lwm2m_ctx.load_credentials` or :c:func:`lwm2m_ctx.set_socketoptions` callbacks. An example of setting up the security object for PSK mode: .. code-block:: c /* "000102030405060708090a0b0c0d0e0f" */ static unsigned char client_psk[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; static const char client_identity[] = "Client_identity"; lwm2m_set_string(&LWM2M_OBJ(LWM2M_OBJECT_SECURITY_ID, 0, 0), "coaps://lwm2m.example.com"); lwm2m_set_u8(&LWM2M_OBJ(LWM2M_OBJECT_SECURITY_ID, 0, 2), LWM2M_SECURITY_PSK); /* Set the client identity as a string, but this could be binary as well */ lwm2m_set_string(&LWM2M_OBJ(LWM2M_OBJECT_SECURITY_ID, 0, 3), client_identity); /* Set the client pre-shared key (PSK) */ lwm2m_set_opaque(&LWM2M_OBJ(LWM2M_OBJECT_SECURITY_ID, 0, 5), client_psk, sizeof(client_psk)); An example of setting up the security object for X509 certificate mode: .. code-block:: c static const char certificate[] = "-----BEGIN CERTIFICATE-----\nMIIB6jCCAY+gAw..."; static const char key[] = "-----BEGIN EC PRIVATE KEY-----\nMHcCAQ..."; static const char root_ca[] = "-----BEGIN CERTIFICATE-----\nMIIBaz..."; lwm2m_set_string(&LWM2M_OBJ(LWM2M_OBJECT_SECURITY_ID, 0, 0), "coaps://lwm2m.example.com"); lwm2m_set_u8(&LWM2M_OBJ(LWM2M_OBJECT_SECURITY_ID, 0, 2), LWM2M_SECURITY_CERT); lwm2m_set_string(&LWM2M_OBJ(LWM2M_OBJECT_SECURITY_ID, 0, 3), certificate); lwm2m_set_string(&LWM2M_OBJ(LWM2M_OBJECT_SECURITY_ID, 0, 5), key); lwm2m_set_string(&LWM2M_OBJ(LWM2M_OBJECT_SECURITY_ID, 0, 4), root_ca); Before calling :c:func:`lwm2m_rd_client_start` assign the tls_tag # where the LwM2M library should store the DTLS information prior to connection (normally a value of 1 is ok here). .. code-block:: c (void)memset(&client, 0x0, sizeof(client)); client.tls_tag = 1; /* <---- */ lwm2m_rd_client_start(&client, "endpoint-name", 0, rd_client_event); For a more detailed LwM2M client sample see: :zephyr:code-sample:`lwm2m-client`. Multi-thread usage ****************** Writing a value to a resource can be done using functions like lwm2m_set_u8. When writing to multiple resources, the function lwm2m_registry_lock will ensure that the client halts until all writing operations are finished: .. code-block:: c lwm2m_registry_lock(); lwm2m_set_u32(&LWM2M_OBJ(1, 0, 1), 60); lwm2m_set_u8(&LWM2M_OBJ(5, 0, 3), 0); lwm2m_set_f64(&LWM2M_OBJ(3303, 0, 5700), value); lwm2m_registry_unlock(); This is especially useful if the server is composite-observing the resources being written to. Locking will then ensure that the client only updates and sends notifications to the server after all operations are done, resulting in fewer messages in general. Support for time series data **************************** LwM2M version 1.1 adds support for SenML CBOR and SenML JSON data formats. These data formats add support for time series data. Time series formats can be used for READ, NOTIFY and SEND operations. When data cache is enabled for a resource, each write will create a timestamped entry in a cache, and its content is then returned as a content in READ, NOTIFY or SEND operation for a given resource. Data cache is only supported for resources with a fixed data size. Supported resource types: * Signed and unsigned 8-64-bit integers * Float * Boolean Enabling and configuring ======================== Enable data cache by selecting :kconfig:option:`CONFIG_LWM2M_RESOURCE_DATA_CACHE_SUPPORT`. Application needs to allocate an array of :c:struct:`lwm2m_time_series_elem` structures and then enable the cache by calling :c:func:`lwm2m_engine_enable_cache` for a given resource. Each resource must be enabled separately and each resource needs their own storage. .. code-block:: c /* Allocate data cache storage */ static struct lwm2m_time_series_elem temperature_cache[10]; /* Enable data cache */ lwm2m_engine_enable_cache(LWM2M_PATH(IPSO_OBJECT_TEMP_SENSOR_ID, 0, SENSOR_VALUE_RID), temperature_cache, ARRAY_SIZE(temperature_cache)); LwM2M engine have room for four resources that have cache enabled. Limit can be increased by changing :kconfig:option:`CONFIG_LWM2M_MAX_CACHED_RESOURCES`. This affects a static memory usage of engine. Data caches depends on one of the SenML data formats :kconfig:option:`CONFIG_LWM2M_RW_SENML_CBOR_SUPPORT` or :kconfig:option:`CONFIG_LWM2M_RW_SENML_JSON_SUPPORT` and needs :kconfig:option:`CONFIG_POSIX_TIMERS` so it can request a timestamp from the system and :kconfig:option:`CONFIG_RING_BUFFER` for ring buffer. Read and Write operations ========================= Full content of data cache is written into a payload when any READ, SEND or NOTIFY operation internally reads the content of a given resource. This has a side effect that any read callbacks registered for a that resource are ignored when cache is enabled. Data is written into a cache when any of the ``lwm2m_set_*`` functions are called. To filter the data entering the cache, application may register a validation callback using :c:func:`lwm2m_register_validate_callback`. Limitations =========== Cache size should be manually set so small that the content can fit normal packets sizes. When cache is full, new values are dropped. LwM2M engine and application events *********************************** The Zephyr LwM2M engine defines events that can be sent back to the application through callback functions. The engine state machine shows when the events are spawned. Events depicted in the diagram are listed in the table. The events are prefixed with ``LWM2M_RD_CLIENT_EVENT_``. .. figure:: images/lwm2m_engine_state_machine.svg :alt: LwM2M engine state machine State machine for the LwM2M engine .. list-table:: LwM2M RD Client events :widths: auto :header-rows: 1 * - Event ID - Event Name - Description * - 0 - NONE - No event * - 1 - BOOTSTRAP_REG_FAILURE - Bootstrap registration failed. Occurs if there is a timeout or failure in bootstrap registration. * - 2 - BOOTSTRAP_REG_COMPLETE - Bootstrap registration complete. Occurs after successful bootstrap registration. * - 3 - BOOTSTRAP_TRANSFER_COMPLETE - Bootstrap finish command received from the server. * - 4 - REGISTRATION_FAILURE - Registration to LwM2M server failed. Occurs if server rejects the registration attempt. * - 5 - REGISTRATION_COMPLETE - Registration to LwM2M server successful. Occurs after a successful registration reply from the LwM2M server or when session resumption is used. * - 6 - REG_TIMEOUT - Registration status lost. Occurs if there is socket errors or message timeouts. Client have lost connection to the server. * - 7 - REG_UPDATE_COMPLETE - Registration update completed. Occurs after successful registration update reply from the LwM2M server. * - 8 - DEREGISTER_FAILURE - Deregistration to LwM2M server failed. Occurs if there is a timeout or failure in the deregistration. * - 9 - DISCONNECT - LwM2M client have de-registered from server and is now stopped. Triggered only if the application have requested the client to stop. * - 10 - QUEUE_MODE_RX_OFF - Used only in queue mode, not actively listening for incoming packets. In queue mode the client is not required to actively listen for the incoming packets after a configured time period. * - 11 - ENGINE_SUSPENDED - Indicate that client has now paused as a result of calling :c:func:`lwm2m_engine_pause`. State machine is no longer running and the handler thread is suspended. All timers are stopped so notifications are not triggered. * - 12 - SERVER_DISABLED - Server have executed the disable command. Client will deregister and stay idle for the disable period. * - 13 - NETWORK_ERROR - Sending messages to the network failed too many times. Client cannot reach any servers or fallback to bootstrap. LwM2M engine cannot recover and have stopped. The LwM2M client engine handles most of the state transitions automatically. The application needs to handle only the events that indicate that the client have stopped or is in a state where it cannot recover. .. list-table:: How application should react to events :widths: auto :header-rows: 1 * - Event Name - How application should react * - NONE - Ignore the event. * - BOOTSTRAP_REG_FAILURE - Try to recover network connection. Then restart the client by calling :c:func:`lwm2m_rd_client_start`. This might also indicate configuration issue. * - BOOTSTRAP_REG_COMPLETE - No actions needed * - BOOTSTRAP_TRANSFER_COMPLETE - No actions needed * - REGISTRATION_FAILURE - No actions needed. Client proceeds re-registration automatically. Might need a bootstrap or configuration fix. Cannot send or receive data. * - REGISTRATION_COMPLETE - No actions needed. Application can send or receive data. * - REG_TIMEOUT - No actions needed. Client proceeds to re-registration automatically. Cannot send or receive data. * - REG_UPDATE_COMPLETE - No actions needed Application can send or receive data. * - DEREGISTER_FAILURE - No actions needed, client proceeds to idle state automatically. Cannot send or receive data. * - DISCONNECT - Engine have stopped as a result of calling :c:func:`lwm2m_rd_client_stop`. If connection is required, the application should restart the client by calling :c:func:`lwm2m_rd_client_start`. * - QUEUE_MODE_RX_OFF - No actions needed. Application can send but cannot receive data. Any data transmission will trigger a registration update. * - ENGINE_SUSPENDED - Engine can be resumed by calling :c:func:`lwm2m_engine_resume`. Cannot send or receive data. * - SERVER_DISABLED - No actions needed, client will re-register once the disable period is over. Cannot send or receive data. * - NETWORK_ERROR - Try to recover network connection. Then restart the client by calling :c:func:`lwm2m_rd_client_start`. This might also indicate configuration issue. Sending of data in the table above refers to calling :c:func:`lwm2m_send_cb` or by writing into one of the observed resources where observation would trigger a notify message. Receiving of data refers to receiving read, write or execute operations from the server. Application can register callbacks for these operations. Configuring lifetime and activity period **************************************** In LwM2M engine, there are three Kconfig options and one runtime value that configures how often the client will send LwM2M Update message. .. list-table:: Update period variables :widths: auto :header-rows: 1 * - Variable - Effect * - LwM2M registration lifetime - The lifetime parameter in LwM2M specifies how long a device's registration with an LwM2M server remains valid. Device is expected to send LwM2M Update message before the lifetime exprires. * - :kconfig:option:`CONFIG_LWM2M_ENGINE_DEFAULT_LIFETIME` - Default lifetime value, unless set by the bootstrap server. Also defines lower limit that client accepts as a lifetime. * - :kconfig:option:`CONFIG_LWM2M_UPDATE_PERIOD` - How long the client can stay idle before sending a next update. * - :kconfig:option:`CONFIG_LWM2M_SECONDS_TO_UPDATE_EARLY` - Minimum time margin to send the update message before the registration lifetime expires. .. figure:: images/lwm2m_lifetime_seconds_early.png :alt: LwM2M seconds to update early Default way of calculating when to update registration. By default, the client uses :kconfig:option:`CONFIG_LWM2M_SECONDS_TO_UPDATE_EARLY` to calculate how many seconds before the expiration of lifetime it is going to send the registration update. The problem with default mode is when the server changes the lifetime of the registration. This is then affecting the period of updates the client is doing. If this is used with the QUEUE mode, which is typical in IPv4 networks, it is also affecting the period of when the device is reachable from the server. .. figure:: images/lwm2m_lifetime_both.png :alt: LwM2M update time when both values are set Update time is controlled by UPDATE_PERIOD. When also the :kconfig:option:`CONFIG_LWM2M_UPDATE_PERIOD` is set, time to send the update message is the earliest when any of these values expire. This allows setting long lifetime for the registration and configure the period accurately, even if server changes the lifetime parameter. In runtime, the update frequency is limited to once in 15 seconds to avoid flooding. .. _lwm2m_shell: LwM2M shell *********** For testing the client it is possible to enable Zephyr's shell and LwM2M specific commands which support changing the state of the client. Operations supported are read, write and execute resources. Client start, stop, pause and resume are also available. The feature is enabled by selecting :kconfig:option:`CONFIG_LWM2M_SHELL`. The shell is meant for testing so productions systems should not enable it. One imaginable scenario, where to use the shell, would be executing client side actions over UART when a server side tests would require those. It is assumed that not all tests are able to trigger required actions from the server side. .. code-block:: console uart:~$ lwm2m lwm2m - LwM2M commands Subcommands: send :send PATHS LwM2M SEND operation exec :exec PATH [PARAM] Execute a resource read :read PATH [OPTIONS] Read value from LwM2M resource -x Read value as hex stream (default) -s Read value as string -b Read value as bool (1/0) -uX Read value as uintX_t -sX Read value as intX_t -f Read value as float -t Read value as time_t write :write PATH [OPTIONS] VALUE Write into LwM2M resource -s Write value as string (default) -b Write value as bool -uX Write value as uintX_t -sX Write value as intX_t -f Write value as float -t Write value as time_t create :create PATH Create object or resource instance delete :delete PATH Delete object or resource instance cache :cache PATH NUM Enable data cache for resource PATH is LwM2M path NUM how many elements to cache start :start EP_NAME [BOOTSTRAP FLAG] Start the LwM2M RD (Registration / Discovery) Client -b Set the bootstrap flag (default 0) stop :stop [OPTIONS] Stop the LwM2M RD (De-register) Client -f Force close the connection update :Trigger Registration Update of the LwM2M RD Client pause :LwM2M engine thread pause resume :LwM2M engine thread resume lock :Lock the LwM2M registry unlock :Unlock the LwM2M registry .. _lwm2m_api_reference: API Reference ************* .. doxygengroup:: lwm2m_api .. _LwM2M: path_to_url .. _LwM2M registry: path_to_url .. _OMA Specworks LwM2M: path_to_url .. _LwM2M specification 1.0.2: path_to_url .. _LwM2M specification 1.1.1: path_to_url ```
/content/code_sandbox/doc/connectivity/networking/api/lwm2m.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
6,993
```restructuredtext .. _coap_server_interface: CoAP server ########### .. contents:: :local: :depth: 2 Overview ******** Zephyr comes with a batteries-included CoAP server, which uses services to listen for CoAP requests. The CoAP services handle communication over sockets and pass requests to registered CoAP resources. Setup ***** Some configuration is required to make sure services can be started using the CoAP server. The :kconfig:option:`CONFIG_COAP_SERVER` option should be enabled in your project: .. code-block:: cfg :caption: ``prj.conf`` CONFIG_COAP_SERVER=y All services are added to a predefined linker section and all resources for each service also get their respective linker sections. If you would have a service ``my_service`` it has to be prefixed with ``coap_resource_`` and added to a linker file: .. code-block:: c :caption: ``sections-ram.ld`` #include <zephyr/linker/iterable_sections.h> ITERABLE_SECTION_RAM(coap_resource_my_service, 4) Add this linker file to your application using CMake: .. code-block:: cmake :caption: ``CMakeLists.txt`` zephyr_linker_sources(DATA_SECTIONS sections-ram.ld) You can now define your service as part of the application: .. code-block:: c #include <zephyr/net/coap_service.h> static const uint16_t my_service_port = 5683; COAP_SERVICE_DEFINE(my_service, "0.0.0.0", &my_service_port, COAP_SERVICE_AUTOSTART); .. note:: Services defined with the ``COAP_SERVICE_AUTOSTART`` flag will be started together with the CoAP server thread. Services can be manually started and stopped with ``coap_service_start`` and ``coap_service_stop`` respectively. Sample Usage ************ The following is an example of a CoAP resource registered with our service: .. code-block:: c #include <zephyr/net/coap_service.h> static int my_get(struct coap_resource *resource, struct coap_packet *request, struct sockaddr *addr, socklen_t addr_len) { static const char *msg = "Hello, world!"; uint8_t data[CONFIG_COAP_SERVER_MESSAGE_SIZE]; struct coap_packet response; uint16_t id; uint8_t token[COAP_TOKEN_MAX_LEN]; uint8_t tkl, type; type = coap_header_get_type(request); id = coap_header_get_id(request); tkl = coap_header_get_token(request, token); /* Determine response type */ type = (type == COAP_TYPE_CON) ? COAP_TYPE_ACK : COAP_TYPE_NON_CON; coap_packet_init(&response, data, sizeof(data), COAP_VERSION_1, type, tkl, token, COAP_RESPONSE_CODE_CONTENT, id); /* Set content format */ coap_append_option_int(&response, COAP_OPTION_CONTENT_FORMAT, COAP_CONTENT_FORMAT_TEXT_PLAIN); /* Append payload */ coap_packet_append_payload_marker(&response); coap_packet_append_payload(&response, (uint8_t *)msg, sizeof(msg)); /* Send to response back to the client */ return coap_resource_send(resource, &response, addr, addr_len, NULL); } static int my_put(struct coap_resource *resource, struct coap_packet *request, struct sockaddr *addr, socklen_t addr_len) { /* ... Handle the incoming request ... */ /* Return a CoAP response code as a shortcut for an empty ACK message */ return COAP_RESPONSE_CODE_CHANGED; } static const char * const my_resource_path[] = { "test", NULL }; COAP_RESOURCE_DEFINE(my_resource, my_service, { .path = my_resource_path, .get = my_get, .put = my_put, }); .. note:: As demonstrated in the example above, a CoAP resource handler can return response codes to let the server respond with an empty ACK response. Observable resources ******************** The CoAP server provides logic for parsing observe requests and stores these using the runtime data of CoAP services. An example using a temperature sensor can look like: .. code-block:: c #include <zephyr/kernel.h> #include <zephyr/drivers/sensor.h> #include <zephyr/net/coap_service.h> static void notify_observers(struct k_work *work); K_WORK_DELAYABLE_DEFINE(temp_work, notify_observers); static int send_temperature(struct coap_resource *resource, const struct sockaddr *addr, socklen_t addr_len, uint16_t age, uint16_t id, const uint8_t *token, uint8_t tkl, bool is_response) { const struct device *dev = DEVICE_DT_GET(DT_ALIAS(ambient_temp0)); uint8_t data[CONFIG_COAP_SERVER_MESSAGE_SIZE]; struct coap_packet response; char payload[14]; struct sensor_value value; double temp; uint8_t type; /* Determine response type */ type = is_response ? COAP_TYPE_ACK : COAP_TYPE_CON; if (!is_response) { id = coap_next_id(); } coap_packet_init(&response, data, sizeof(data), COAP_VERSION_1, type, tkl, token, COAP_RESPONSE_CODE_CONTENT, id); if (age >= 2U) { coap_append_option_int(&response, COAP_OPTION_OBSERVE, age); } /* Set content format */ coap_append_option_int(&response, COAP_OPTION_CONTENT_FORMAT, COAP_CONTENT_FORMAT_TEXT_PLAIN); /* Get the sensor date */ sensor_sample_fetch_chan(dev, SENSOR_CHAN_AMBIENT_TEMP); sensor_channel_get(dev, SENSOR_CHAN_AMBIENT_TEMP, &value); temp = sensor_value_to_double(&value); snprintk(payload, sizeof(payload), "%0.2fC", temp); /* Append payload */ coap_packet_append_payload_marker(&response); coap_packet_append_payload(&response, (uint8_t *)payload, strlen(payload)); return coap_resource_send(resource, &response, addr, addr_len, NULL); } static int temp_get(struct coap_resource *resource, struct coap_packet *request, struct sockaddr *addr, socklen_t addr_len) { uint8_t token[COAP_TOKEN_MAX_LEN]; uint16_t id; uint8_t tkl; int r; /* Let the CoAP server parse the request and add/remove observers if needed */ r = coap_resource_parse_observe(resource, request, addr); id = coap_header_get_id(request); tkl = coap_header_get_token(request, token); return send_temperature(resource, addr, addr_len, r == 0 ? resource->age : 0, id, token, tkl, true); } static void temp_notify(struct coap_resource *resource, struct coap_observer *observer) { send_temperature(resource, &observer->addr, sizeof(observer->addr), resource->age, 0, observer->token, observer->tkl, false); } static const char * const temp_resource_path[] = { "sensors", "temp1", NULL }; COAP_RESOURCE_DEFINE(temp_resource, my_service, { .path = temp_resource_path, .get = temp_get, .notify = temp_notify, }); static void notify_observers(struct k_work *work) { if (sys_slist_is_empty(&temp_resource.observers)) { return; } coap_resource_notify(&temp_resource); k_work_reschedule(&temp_work, K_SECONDS(1)); } CoAP Events *********** By enabling :kconfig:option:`CONFIG_NET_MGMT_EVENT` the user can register for CoAP events. The following example simply prints when an event occurs. .. code-block:: c #include <zephyr/sys/printk.h> #include <zephyr/net/coap_mgmt.h> #include <zephyr/net/coap_service.h> #define COAP_EVENTS_SET (NET_EVENT_COAP_OBSERVER_ADDED | NET_EVENT_COAP_OBSERVER_REMOVED | \ NET_EVENT_COAP_SERVICE_STARTED | NET_EVENT_COAP_SERVICE_STOPPED) void coap_event_handler(uint32_t mgmt_event, struct net_if *iface, void *info, size_t info_length, void *user_data) { switch (mgmt_event) { case NET_EVENT_COAP_OBSERVER_ADDED: printk("CoAP observer added"); break; case NET_EVENT_COAP_OBSERVER_REMOVED: printk("CoAP observer removed"); break; case NET_EVENT_COAP_SERVICE_STARTED: if (info != NULL && info_length == sizeof(struct net_event_coap_service)) { struct net_event_coap_service *net_event = info; printk("CoAP service %s started", net_event->service->name); } else { printk("CoAP service started"); } break; case NET_EVENT_COAP_SERVICE_STOPPED: if (info != NULL && info_length == sizeof(struct net_event_coap_service)) { struct net_event_coap_service *net_event = info; printk("CoAP service %s stopped", net_event->service->name); } else { printk("CoAP service stopped"); } break; } } NET_MGMT_REGISTER_EVENT_HANDLER(coap_events, COAP_EVENTS_SET, coap_event_handler, NULL); CoRE Link Format **************** The :kconfig:option:`CONFIG_COAP_SERVER_WELL_KNOWN_CORE` option enables handling the ``.well-known/core`` GET requests by the server. This allows clients to get a list of hypermedia links to other resources hosted in that server. API Reference ************* .. doxygengroup:: coap_service .. doxygengroup:: coap_mgmt ```
/content/code_sandbox/doc/connectivity/networking/api/coap_server.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,166
```restructuredtext .. _socks5_interface: SOCKS5 Proxy Support #################### .. contents:: :local: :depth: 2 Overview ******** The SOCKS library implements SOCKS5 support, which allows Zephyr to connect to peer devices via a network proxy. See this `SOCKS5 Wikipedia article <path_to_url#SOCKS5>`_ for a detailed overview of how SOCKS5 works. For more information about the protocol itself, see `IETF RFC1928 SOCKS Protocol Version 5 <path_to_url`_. SOCKS5 API ********** The SOCKS5 support is enabled by :kconfig:option:`CONFIG_SOCKS` Kconfig variable. Application wanting to use the SOCKS5 must set the SOCKS5 proxy host address by calling :c:func:`setsockopt()` like this: .. code-block:: c static int set_proxy(int sock, const struct sockaddr *proxy_addr, socklen_t proxy_addrlen) { int ret; ret = setsockopt(sock, SOL_SOCKET, SO_SOCKS5, proxy_addr, proxy_addrlen); if (ret < 0) { return -errno; } return 0; } SOCKS5 Proxy Usage in MQTT ************************** For MQTT client, there is :c:func:`mqtt_client_set_proxy()` API that the application can call to setup SOCKS5 proxy. See :zephyr:code-sample:`mqtt-publisher` sample application for usage example. ```
/content/code_sandbox/doc/connectivity/networking/api/socks5.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
327
```restructuredtext .. _net_core_interface: Network Core Helpers #################### .. contents:: :local: :depth: 2 Overview ******** The network subsystem contains two functions for sending and receiving data from the network. The ``net_recv_data()`` is typically used by network device driver when the received network data needs to be pushed up in the network stack for further processing. All the data is received via a network interface which is typically created by the device driver. For sending, the ``net_send_data()`` can be used. Typically applications do not call this function directly as there is the :ref:`bsd_sockets_interface` API for sending and receiving network data. API Reference ************* .. doxygengroup:: net_core ```
/content/code_sandbox/doc/connectivity/networking/api/net_core.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
160
```restructuredtext .. _dhcpv4_interface: DHCPv4 ###### .. contents:: :local: :depth: 2 Overview ******** The Dynamic Host Configuration Protocol (DHCP) is a network management protocol used on IPv4 networks. A DHCPv4 server dynamically assigns an IPv4 address and other network configuration parameters to each device on a network so they can communicate with other IP networks. See this `DHCP Wikipedia article <path_to_url`_ for a detailed overview of how DHCP works. Note that Zephyr supports both DHCPv4 client and server functionality. Sample usage ************ See :zephyr:code-sample:`dhcpv4-client` sample application for details. API Reference ************* .. doxygengroup:: dhcpv4 ```
/content/code_sandbox/doc/connectivity/networking/api/dhcpv4.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
165
```restructuredtext .. _ip_4_6_interface: IPv4/IPv6 Primitives and Helpers ################################ .. contents:: :local: :depth: 2 Overview ******** Miscellaneous defines and helper functions for IP addresses and IP protocols. API Reference ************* .. doxygengroup:: ip_4_6 ```
/content/code_sandbox/doc/connectivity/networking/api/ip_4_6.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
71
```restructuredtext .. _traffic-class-support: Traffic Classification ####################### Overview ******** `Traffic classification <path_to_url`_ is an automated process that categorizes computer network traffic according to various parameters. For Zephyr, the VLAN priority code point (PCP) is used to classify both received and sent network packets. See more information about VLAN priority at `IEEE 802.1Q <path_to_url`_. By default, all network traffic is treated equal in Zephyr. If desired, the option :kconfig:option:`CONFIG_NET_TC_TX_COUNT` can be used to set the number of transmit queues. The option :kconfig:option:`CONFIG_NET_TC_RX_COUNT` can be used to set the number of receive queues. Each traffic class queue corresponds to a specific kernel work queue. Each kernel work queue has a priority. The VLAN priority is mapped to a certain traffic class according to rules specified in `IEEE 802.1Q spec`_ chapter I.3, chapter 8.6.6 table 8-4, and chapter 34.5 table 34-1. Each traffic class is in turn mapped to a certain kernel work queue. The maximum number of traffic classes for both Rx and Tx is 8. See :zephyr_file:`subsys/net/ip/net_tc.c` for details of how various mappings are done. .. _IEEE 802.1Q spec: path_to_url ```
/content/code_sandbox/doc/connectivity/networking/api/traffic-class.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
308
```restructuredtext .. _ieee802154_interface: IEEE 802.15.4 ############# .. contents:: :local: :depth: 2 Introduction ************ IEEE 802.15.4 is a technical standard which defines the operation of low-rate wireless personal area networks (LR-WPANs). For a more detailed overview of this standard, see the `IEEE 802.15.4 Wikipedia article <path_to_url`_. The most recent version of the standard is accessible through the `IEEE GET Program <path_to_url`_. You need to create a free IEEE account and can then downloading it. We're currently following the IEEE 802.15.4-2020 specification. This version is backwards compatible with IEEE 802.15.4-2015, parts of which are contained in the Thread protocol stack. The 2020 version also includes prior extensions that were accepted into the standard, namely IEEE 802.15.4g (SUN FSK) and IEEE 802.15.4e (TSCH) which are of relevance to industrial IoT and automation. For recent developments in UWB ranging technology, see IEEE 802.15.4z which is not yet integrated into the standard's mainline. Whenever sections from the standard are cited in the documentation, they refer to IEEE 802.15.4-2020 section, table and figure numbering - unless otherwise specified. Zephyr supports both, native IEEE 802.15.4 and Thread, with 6LoWPAN. Zephyr's :ref:`thread_protocol_interface` implementation is based on `OpenThread <path_to_url`_. The IPv6 header compression in 6LoWPAN is used for native IEEE 802.15.4. API Reference ************* IEEE 802.15.4 API Overview ========================== Gives an introduction and overview over the whole IEEE 802.15.4 subsystem and all of its APIs, configuration and user interfaces for all audiences. .. doxygengroup:: ieee802154 .. _ieee802154_mgmt_api: IEEE 802.15.4 Management API ============================ This is the main subsystem-specific API of interest to IEEE 802.15.4 **application developers** as it allows to configure the IEEE 802.15.4 subsystem at runtime. Other relevant interfaces for application developers are the typical shell, socket, Kconfig and devicetree APIs that can be accessed through Zephyr's generic subsystem-independent documentation. Look out for IEEE802154/ieee802154 prefixes there. .. doxygengroup:: ieee802154_mgmt .. _ieee802154_driver_api: IEEE 802.15.4 Driver API ======================== This is the main API of interest to IEEE 802.15.4 **driver developers**. .. doxygengroup:: ieee802154_driver .. _ieee802154_l2_api: IEEE 802.15.4 L2 / Native Stack API =================================== This documents the IEEE 802.15.4 L2 native stack, which neither applications nor drivers will ever access directly. It is called internally by Zephyr's upper network layers (L3+), its socket and network context abstractions. This API is therefore of interest to IEEE 802.15.4 **subsystem contributors** only. .. doxygengroup:: ieee802154_l2 OpenThread L2 Adaptation Layer API ================================== Zephyr's OpenThread L2 platform adaptation layer glues the external OpenThread stack together with Zephyr's IEEE 802.15.4 protocol agnostic driver API. This API is of interest to OpenThread L2 **subsystem contributors** only. The OpenThread API is part of the :ref:`thread_protocol_interface` subsystem and documented there. ```
/content/code_sandbox/doc/connectivity/networking/api/ieee802154.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
822
```restructuredtext .. _net_time_interface: Network time representation in the network stack ################################################ API Reference ************* .. doxygengroup:: net_time ```
/content/code_sandbox/doc/connectivity/networking/api/net_time.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
32
```restructuredtext .. _coap_sock_interface: CoAP ##### .. contents:: :local: :depth: 2 Overview ******** The Constrained Application Protocol (CoAP) is a specialized web transfer protocol for use with constrained nodes and constrained (e.g., low-power, lossy) networks. It provides a convenient API for RESTful Web services that support CoAP's features. For more information about the protocol itself, see `IETF RFC7252 The Constrained Application Protocol <path_to_url`_. Zephyr provides a CoAP library which supports client and server roles. The library can be enabled with :kconfig:option:`CONFIG_COAP` Kconfig option and is configurable as per user needs. The Zephyr CoAP library is implemented using plain buffers. Users of the API create sockets for communication and pass the buffer to the library for parsing and other purposes. The library itself doesn't create any sockets for users. On top of CoAP, Zephyr has support for LWM2M "Lightweight Machine 2 Machine" protocol, a simple, low-cost remote management and service enablement mechanism. See :ref:`lwm2m_interface` for more information. Supported RFCs: - `RFC7252: The Constrained Application Protocol (CoAP) <path_to_url`_ - `RFC6690: Constrained RESTful Environments (CoRE) Link Format <path_to_url`_ - `RFC7959: Block-Wise Transfers in the Constrained Application Protocol (CoAP) <path_to_url`_ - `RFC7641: Observing Resources in the Constrained Application Protocol (CoAP) <path_to_url`_ .. note:: Not all parts of these RFCs are supported. Features are supported based on Zephyr requirements. Sample Usage ************ CoAP Server =========== .. note:: A :ref:`coap_server_interface` subsystem is available, the following is for creating a custom server implementation. To create a CoAP server, resources for the server need to be defined. The ``.well-known/core`` resource should be added before all other resources that should be included in the responses of the ``.well-known/core`` resource. .. code-block:: c static struct coap_resource resources[] = { { .get = well_known_core_get, .path = COAP_WELL_KNOWN_CORE_PATH, }, { .get = sample_get, .post = sample_post, .del = sample_del, .put = sample_put, .path = sample_path }, { }, }; An application reads data from the socket and passes the buffer to the CoAP library to parse the message. If the CoAP message is proper, the library uses the buffer along with resources defined above to call the correct callback function to handle the CoAP request from the client. It's the callback function's responsibility to either reply or act according to CoAP request. .. code-block:: c coap_packet_parse(&request, data, data_len, options, opt_num); ... coap_handle_request(&request, resources, options, opt_num, client_addr, client_addr_len); If :kconfig:option:`CONFIG_COAP_URI_WILDCARD` enabled, server may accept multiple resources using MQTT-like wildcard style: - the plus symbol represents a single-level wild card in the path; - the hash symbol represents the multi-level wild card in the path. .. code-block:: c static const char * const led_set[] = { "led","+","set", NULL }; static const char * const btn_get[] = { "button","#", NULL }; static const char * const no_wc[] = { "test","+1", NULL }; It accepts /led/0/set, led/1234/set, led/any/set, /button/door/1, /test/+1, but returns -ENOENT for /led/1, /test/21, /test/1. This option is enabled by default, disable it to avoid unexpected behaviour with resource path like '/some_resource/+/#'. CoAP Client =========== .. note:: A :ref:`coap_client_interface` subsystem is available, the following is for creating a custom client implementation. If the CoAP client knows about resources in the CoAP server, the client can start prepare CoAP requests and wait for responses. If the client doesn't know about resources in the CoAP server, it can request resources through the ``.well-known/core`` CoAP message. .. code-block:: c /* Initialize the CoAP message */ char *path = "test"; struct coap_packet request; uint8_t data[100]; uint8_t payload[20]; coap_packet_init(&request, data, sizeof(data), 1, COAP_TYPE_CON, 8, coap_next_token(), COAP_METHOD_GET, coap_next_id()); /* Append options */ coap_packet_append_option(&request, COAP_OPTION_URI_PATH, path, strlen(path)); /* Append Payload marker if you are going to add payload */ coap_packet_append_payload_marker(&request); /* Append payload */ coap_packet_append_payload(&request, (uint8_t *)payload, sizeof(payload) - 1); /* send over sockets */ Testing ******* There are various ways to test Zephyr CoAP library. libcoap ======= libcoap implements a lightweight application-protocol for devices that are resource constrained, such as by computing power, RF range, memory, bandwidth, or network packet sizes. Sources can be found here `libcoap <path_to_url`_. libcoap has a script (``examples/etsi_coaptest.sh``) to test coap-server functionality in Zephyr. See the `net-tools <path_to_url`_ project for more details The :zephyr:code-sample:`coap-server` sample can be built and executed on QEMU as described in :ref:`networking_with_qemu`. Use this command on the host to run the libcoap implementation of the ETSI test cases: .. code-block:: console sudo ./libcoap/examples/etsi_coaptest.sh -i tap0 2001:db8::1 TTCN3 ===== Eclipse has TTCN3 based tests to run against CoAP implementations. Install eclipse-titan and set symbolic links for titan tools .. code-block:: console sudo apt-get install eclipse-titan cd /usr/share/titan sudo ln -s /usr/bin bin sudo ln /usr/bin/titanver bin sudo ln -s /usr/bin/mctr_cli bin sudo ln -s /usr/include/titan include sudo ln -s /usr/lib/titan lib export TTCN3_DIR=/usr/share/titan git clone path_to_url cd titan.misc Follow the instruction to setup CoAP test suite from here: - path_to_url - path_to_url After the build is complete, the :zephyr:code-sample:`coap-server` sample can be built and executed on QEMU as described in :ref:`networking_with_qemu`. Change the client (test suite) and server (Zephyr coap-server sample) addresses in coap.cfg file as per your setup. Execute the test cases with following command. .. code-block:: console ttcn3_start coaptests coap.cfg Sample output of ttcn3 tests looks like this. .. code-block:: console Verdict statistics: 0 none (0.00 %), 10 pass (100.00 %), 0 inconc (0.00 %), 0 fail (0.00 %), 0 error (0.00 %). Test execution summary: 10 test cases were executed. Overall verdict: pass API Reference ************* .. doxygengroup:: coap ```
/content/code_sandbox/doc/connectivity/networking/api/coap.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,713
```restructuredtext .. _net_protocols: Protocols ########## .. toctree:: :maxdepth: 1 coap coap_client coap_server http_client http_server lwm2m mqtt mqtt_sn ptp tftp ```
/content/code_sandbox/doc/connectivity/networking/api/protocols.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
69
```restructuredtext .. _http_server_interface: HTTP Server ########### .. contents:: :local: :depth: 2 Overview ******** Zephyr provides an HTTP server library, which allows to register HTTP services and HTTP resources associated with those services. The server creates a listening socket for every registered service, and handles incoming client connections. It's possible to communicate over a plain TCP socket (HTTP) or a TLS socket (HTTPS). Both, HTTP/1.1 (RFC 2616) and HTTP/2 (RFC 9113) protocol versions are supported. The server operation is generally transparent for the application, running in a background thread. The application can control the server activity with respective API functions. Certain resource types (for example dynamic resource) provide resource-specific application callbacks, allowing the server to interact with the application (for instance provide resource content, or process request payload). Currently, the following resource types are supported: * Static resources - content defined compile-time, cannot be modified at runtime (:c:enumerator:`HTTP_RESOURCE_TYPE_STATIC`). * Dynamic resources - content provided at runtime by respective application callback (:c:enumerator:`HTTP_RESOURCE_TYPE_DYNAMIC`). * Websocket resources - allowing to establish Websocket connections with the server (:c:enumerator:`HTTP_RESOURCE_TYPE_WEBSOCKET`). Zephyr provides a sample demonstrating HTTP(s) server operation and various resource types usage. See :zephyr:code-sample:`sockets-http-server` for more information. Server Setup ************ A few prerequisites are needed in order to enable HTTP server functionality in the application. First of all, the HTTP server has to be enabled in applications configuration file with :kconfig:option:`CONFIG_HTTP_SERVER` Kconfig option: .. code-block:: cfg :caption: ``prj.conf`` CONFIG_HTTP_SERVER=y All HTTP services and HTTP resources are placed in a dedicated linker section. The linker section for services is predefined locally, however the application is responsible for defining linker sections for resources associated with respective services. Linker section names for resources should be prefixed with ``http_resource_desc_``, appended with the service name. Linker sections for resources should be defined in a linker file. For example, for a service named ``my_service``, the linker section shall be defined as follows: .. code-block:: c :caption: ``sections-rom.ld`` #include <zephyr/linker/iterable_sections.h> ITERABLE_SECTION_ROM(http_resource_desc_my_service, Z_LINK_ITERABLE_SUBALIGN) Finally, the linker file and linker section have to be added to your application using CMake: .. code-block:: cmake :caption: ``CMakeLists.txt`` zephyr_linker_sources(SECTIONS sections-rom.ld) zephyr_linker_section(NAME http_resource_desc_my_service KVMA RAM_REGION GROUP RODATA_REGION SUBALIGN Z_LINK_ITERABLE_SUBALIGN) .. note:: You need to define a separate linker section for each HTTP service registered in the system. Sample Usage ************ Services ======== The application needs to define an HTTP service (or multiple services), with the same name as used for the linker section with :c:macro:`HTTP_SERVICE_DEFINE` macro: .. code-block:: c #include <zephyr/net/http/service.h> static uint16_t http_service_port = 80; HTTP_SERVICE_DEFINE(my_service, "0.0.0.0", &http_service_port, 1, 10, NULL); Alternatively, an HTTPS service can be defined with :c:macro:`HTTPS_SERVICE_DEFINE`: .. code-block:: c #include <zephyr/net/http/service.h> #include <zephyr/net/tls_credentials.h> #define HTTP_SERVER_CERTIFICATE_TAG 1 static uint16_t https_service_port = 443; static const sec_tag_t sec_tag_list[] = { HTTP_SERVER_CERTIFICATE_TAG, }; HTTPS_SERVICE_DEFINE(my_service, "0.0.0.0", &https_service_port, 1, 10, NULL, sec_tag_list, sizeof(sec_tag_list)); .. note:: HTTPS services rely on TLS credentials being registered in the system. See :ref:`sockets_tls_credentials_subsys` for information on how to configure TLS credentials in the system. Once HTTP(s) service is defined, resources can be registered for it with :c:macro:`HTTP_RESOURCE_DEFINE` macro. Application can enable resource wildcard support by enabling :kconfig:option:`CONFIG_HTTP_SERVER_RESOURCE_WILDCARD` option. When this option is set, then it is possible to match several incoming HTTP requests with just one resource handler. The `fnmatch() <path_to_url`__ POSIX API function is used to match the pattern in the URL paths. Example: .. code-block:: c HTTP_RESOURCE_DEFINE(my_resource, my_service, "/foo*", &resource_detail); This would match all URLs that start with a string ``foo``. See `POSIX.2 chapter 2.13 <path_to_url#tag_18_13>`__ for pattern matching syntax description. Static resources ================ Static resource content is defined build-time and is immutable. The following example shows how gzip compressed webpage can be defined as a static resource in the application: .. code-block:: c static const uint8_t index_html_gz[] = { #include "index.html.gz.inc" }; struct http_resource_detail_static index_html_gz_resource_detail = { .common = { .type = HTTP_RESOURCE_TYPE_STATIC, .bitmask_of_supported_http_methods = BIT(HTTP_GET), .content_encoding = "gzip", }, .static_data = index_html_gz, .static_data_len = sizeof(index_html_gz), }; HTTP_RESOURCE_DEFINE(index_html_gz_resource, my_service, "/", &index_html_gz_resource_detail); The resource content and content encoding is application specific. For the above example, a gzip compressed webpage can be generated during build, by adding the following code to the application's ``CMakeLists.txt`` file: .. code-block:: cmake :caption: ``CMakeLists.txt`` set(gen_dir ${ZEPHYR_BINARY_DIR}/include/generated/) set(source_file_index src/index.html) generate_inc_file_for_target(app ${source_file_index} ${gen_dir}/index.html.gz.inc --gzip) where ``src/index.html`` is the location of the webpage to be compressed. Static filesystem resources =========================== Static filesystem resource content is defined build-time and is immutable. The following example shows how the path can be defined as a static resource in the application: .. code-block:: c struct http_resource_detail_static_fs static_fs_resource_detail = { .common = { .type = HTTP_RESOURCE_TYPE_STATIC_FS, .bitmask_of_supported_http_methods = BIT(HTTP_GET), }, .fs_path = "/lfs1/www", }; HTTP_RESOURCE_DEFINE(static_fs_resource, my_service, "*", &static_fs_resource_detail); All files located in /lfs1/www are made available to the client. If a file is gzipped, .gz must be appended to the file name (e.g. index.html.gz), then the server delivers index.html.gz when the client requests index.html and adds gzip content-encoding to the HTTP header. The content type is evaluated based on the file extension. The server supports .html, .js, .css, .jpg, .png and .svg. More content types can be provided with the :c:macro:`HTTP_SERVER_CONTENT_TYPE` macro. All other files are provided with the content type text/html. .. code-block:: c HTTP_SERVER_CONTENT_TYPE(json, "application/json") Dynamic resources ================= For dynamic resource, a resource callback is registered to exchange data between the server and the application. The application defines a resource buffer used to pass the request payload data from the server, and to provide response payload to the server. The following example code shows how to register a dynamic resource with a simple resource handler, which echoes received data back to the client: .. code-block:: c static uint8_t recv_buffer[1024]; static int dyn_handler(struct http_client_ctx *client, enum http_data_status status, uint8_t *buffer, size_t len, void *user_data) { #define MAX_TEMP_PRINT_LEN 32 static char print_str[MAX_TEMP_PRINT_LEN]; enum http_method method = client->method; static size_t processed; __ASSERT_NO_MSG(buffer != NULL); if (status == HTTP_SERVER_DATA_ABORTED) { LOG_DBG("Transaction aborted after %zd bytes.", processed); processed = 0; return 0; } processed += len; snprintf(print_str, sizeof(print_str), "%s received (%zd bytes)", http_method_str(method), len); LOG_HEXDUMP_DBG(buffer, len, print_str); if (status == HTTP_SERVER_DATA_FINAL) { LOG_DBG("All data received (%zd bytes).", processed); processed = 0; } /* This will echo data back to client as the buffer and recv_buffer * point to same area. */ return len; } struct http_resource_detail_dynamic dyn_resource_detail = { .common = { .type = HTTP_RESOURCE_TYPE_DYNAMIC, .bitmask_of_supported_http_methods = BIT(HTTP_GET) | BIT(HTTP_POST), }, .cb = dyn_handler, .data_buffer = recv_buffer, .data_buffer_len = sizeof(recv_buffer), .user_data = NULL, }; HTTP_RESOURCE_DEFINE(dyn_resource, my_service, "/dynamic", &dyn_resource_detail); The resource callback may be called multiple times for a single request, hence the application should be able to keep track of the received data progress. The ``status`` field informs the application about the progress in passing request payload from the server to the application. As long as the status reports :c:enumerator:`HTTP_SERVER_DATA_MORE`, the application should expect more data to be provided in a consecutive callback calls. Once all request payload has been passed to the application, the server reports :c:enumerator:`HTTP_SERVER_DATA_FINAL` status. In case of communication errors during request processing (for example client closed the connection before complete payload has been received), the server reports :c:enumerator:`HTTP_SERVER_DATA_ABORTED`. Either of the two events indicate that the application shall reset any progress recorded for the resource, and await a new request to come. The server guarantees that the resource can only be accessed by single client at a time. The resource callback returns the number of bytes to be replied in the response payload to the server (provided in the resource data buffer). In case there is no more data to be included in the response, the callback should return 0. The server will call the resource callback until it provided all request data to the application, and the application reports there is no more data to include in the reply. Websocket resources =================== Websocket resources register an application callback, which is called when a Websocket connection upgrade takes place. The callback is provided with a socket descriptor corresponding to the underlying TCP/TLS connection. Once called, the application takes full control over the socket, i. e. is responsible to release it when done. .. code-block:: c static int ws_socket; static uint8_t ws_recv_buffer[1024]; int ws_setup(int sock, void *user_data) { ws_socket = sock; return 0; } struct http_resource_detail_websocket ws_resource_detail = { .common = { .type = HTTP_RESOURCE_TYPE_WEBSOCKET, /* We need HTTP/1.1 Get method for upgrading */ .bitmask_of_supported_http_methods = BIT(HTTP_GET), }, .cb = ws_setup, .data_buffer = ws_recv_buffer, .data_buffer_len = sizeof(ws_recv_buffer), .user_data = NULL, /* Fill this for any user specific data */ }; HTTP_RESOURCE_DEFINE(ws_resource, my_service, "/", &ws_resource_detail); The above minimalistic example shows how to register a Websocket resource with a simple callback, used only to store the socket descriptor provided. Further processing of the Websocket connection is application-specific, hence outside of scope of this guide. See :zephyr:code-sample:`sockets-http-server` for an example Websocket-based echo service implementation. API Reference ************* .. doxygengroup:: http_service .. doxygengroup:: http_server ```
/content/code_sandbox/doc/connectivity/networking/api/http_server.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,692
```restructuredtext .. _thread_protocol_interface: Thread protocol ############### .. contents:: :local: :depth: 2 Overview ******** Thread is a low-power mesh networking technology, designed specifically for home automation applications. It is an IPv6-based standard, which uses 6LoWPAN technology over IEEE 802.15.4 protocol. IP connectivity lets you easily connect a Thread mesh network to the internet with a Thread Border Router. The Thread specification provides a high level of network security. Mesh networks built with Thread are secure - only authenticated devices can join the network and all communications within the mesh are encrypted. More information about Thread protocol can be found at `Thread Group website <path_to_url`_. Zephyr integrates an open source Thread protocol implementation called OpenThread, documented on the `OpenThread website <path_to_url`_. Internet connectivity ********************* A Thread Border Router is required to connect mesh network to the internet. An open source implementation of Thread Border Router is provided by the OpenThread community. See `OpenThread Border Router guide <path_to_url`_ for instructions on how to set up a Border Router. Sample usage ************ You can try using OpenThread with the Zephyr Echo server and Echo client samples, which provide out-of-the-box configuration for OpenThread. To enable OpenThread support in these samples, build them with ``overlay-ot.conf`` overlay config file. See :zephyr:code-sample:`sockets-echo-server` and :zephyr:code-sample:`sockets-echo-client` samples for details. Thread related APIs ******************* OpenThread Driver API ======================== OpenThread L2 uses Zephyr's protocol agnostic IEEE 802.15.4 driver API internally. This API is of interest to **driver developers** that want to support OpenThread. The driver API is part of the :ref:`ieee802154_driver_api` subsystem and documented there. OpenThread L2 Adaptation Layer API ================================== Zephyr's OpenThread L2 platform adaptation layer glues the external OpenThread stack together with Zephyr's IEEE 802.15.4 protocol agnostic driver API. This API is of interest to OpenThread L2 **subsystem contributors** only. .. doxygengroup:: openthread ```
/content/code_sandbox/doc/connectivity/networking/api/thread.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
491
```restructuredtext .. _ptp_interface: Precision Time Protocol (PTP) ############################# .. contents:: :local: :depth: 2 Overview ******** PTP is a network protocol implemented in the application layer, used to synchronize clocks in a computer network. It's accurate up to less than a microsecond. The stack supports the protocol and procedures as defined in the `IEEE 1588-2019 standard`_ (IEEE Standard for a Precision Clock Synchronization Protocol for Networked Measurement and Control Systems). It has multiple profiles, and can be implemented on top of L2 (Ethernet) or L3 (UDP/IPv4 or UDP/IPv6). Its accuracy is achieved by using hardware timestamping of the protocol packets. Zephyr's implementation of PTP stack consist following items: * PTP stack thread that handles incoming messages and events * Integration with ptp_clock driver * PTP stack initialization executed during system init The implementation automatically creates PTP Ports (each PTP Port corresponds to unique interface). Supported features ****************** Implementation of the stack doesn't support all features specified in the standard. In the table below all supported features are listed. .. csv-table:: Supported features :header: Feature, Supported :widths: 50,10 Ordinary Clock, yes Boundary Clock, yes Transparent Clock, Management Node, End to end delay mechanism, yes Peer to peer delay mechanism, Multicast operation mode, Hybrid operation mode, Unicast operation mode, Non-volatile storage, UDP IPv4 transport protocol, yes UDP IPv6 transport protocol, yes IEEE 802.3 (Ethernet) transport protocol, Hardware timestamping, yes Software timestamping, TIME_RECEIVER_ONLY PTP Instance, yes TIME_TRANSMITTER_ONLY PTP Instance, Supported Management messages ***************************** Based on Table 59 from section 15.5.2.3 of the IEEE 1588-2019 following management TLVs are supported: .. csv-table:: Supported management message's IDs :header: Management_ID, Management_ID name, Allowed actions :widths: 10,40,25 0x0000, NULL_PTP_MANAGEMENT, GET SET COMMAND 0x0001, CLOCK_DESCRIPTION, GET 0x0002, USER_DESCRIPTION, GET 0x0003, SAVE_IN_NON_VOLATILE_STORAGE, - 0x0004, RESET_NON_VOLATILE_STORAGE, - 0x0005, INITIALIZE, - 0x0006, FAULT_LOG, - 0x0007, FAULT_LOG_RESET, - 0x2000, DEFAULT_DATA_SET, GET 0x2001, CURRENT_DATA_SET, GET 0x2002, PARENT_DATA_SET, GET 0x2003, TIME_PROPERTIES_DATA_SET, GET 0x2004, PORT_DATA_SET, GET 0x2005, PRIORITY1, GET SET 0x2006, PRIORITY2, GET SET 0x2007, DOMAIN, GET SET 0x2008, TIME_RECEIVER_ONLY, GET SET 0x2009, LOG_ANNOUNCE_INTERVAL, GET SET 0x200A, ANNOUNCE_RECEIPT_TIMEOUT, GET SET 0x200B, LOG_SYNC_INTERVAL, GET SET 0x200C, VERSION_NUMBER, GET SET 0x200D, ENABLE_PORT, COMMAND 0x200E, DISABLE_PORT, COMMAND 0x200F, TIME, GET SET 0x2010, CLOCK_ACCURACY, GET SET 0x2011, UTC_PROPERTIES, GET SET 0x2012, TRACEBILITY_PROPERTIES, GET SET 0x2013, TIMESCALE_PROPERTIES, GET SET 0x2014, UNICAST_NEGOTIATION_ENABLE, - 0x2015, PATH_TRACE_LIST, - 0x2016, PATH_TRACE_ENABLE, - 0x2017, GRANDMASTER_CLUSTER_TABLE, - 0x2018, UNICAST_TIME_TRANSMITTER_TABLE, - 0x2019, UNICAST_TIME_TRANSMITTER_MAX_TABLE_SIZE, - 0x201A, ACCEPTABLE_TIME_TRANSMITTER_TABLE, - 0x201B, ACCEPTABLE_TIME_TRANSMITTER_TABLE_ENABLED, - 0x201C, ACCEPTABLE_TIME_TRANSMITTER_MAX_TABLE_SIZE, - 0x201D, ALTERNATE_TIME_TRANSMITTER, - 0x201E, ALTERNATE_TIME_OFFSET_ENABLE, - 0x201F, ALTERNATE_TIME_OFFSET_NAME, - 0x2020, ALTERNATE_TIME_OFFSET_MAX_KEY, - 0x2021, ALTERNATE_TIME_OFFSET_PROPERTIES, - 0x3000, EXTERNAL_PORT_CONFIGURATION_ENABLED, 0x3001, TIME_TRANSMITTER_ONLY, - 0x3002, HOLDOVER_UPGRADE_ENABLE, - 0x3003, EXT_PORT_CONFIG_PORT_DATA_SET, - 0x4000, TRANSPARENT_CLOCK_DEFAULT_DATA_SET, - 0x4001, TRANSPARENT_CLOCK_PORT_DATA_SET, - 0x4002, PRIMARY_DOMAIN, - 0x6000, DELAY_MECHANISM, GET 0x6001, LOG_MIN_PDELAY_REQ_INTERVAL, GET SET Enabling the stack ****************** The following configuration option must me enabled in :file:`prj.conf` file. - :kconfig:option:`CONFIG_PTP` Testing ******* The stack has been informally tested using the `Linux ptp4l <path_to_url`_ daemons. The :zephyr:code-sample:`PTP sample application <ptp>` from the Zephyr source distribution can be used for testing. .. _IEEE 1588-2019 standard: path_to_url API Reference ************* .. doxygengroup:: ptp ```
/content/code_sandbox/doc/connectivity/networking/api/ptp.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,319
```restructuredtext .. _networking_api: Networking APIs ############### Zephyr provides support for the standard BSD socket APIs (defined in :zephyr_file:`include/zephyr/net/socket.h`) for the applications to use. See :ref:`BSD socket API <bsd_sockets_interface>` for more details. Apart of the standard API, Zephyr provides a set of custom networking APIs and libraries for the application to use. See the list below for details. .. note:: The legacy connectivity API in :zephyr_file:`include/zephyr/net/net_context.h` should not be used by applications. .. toctree:: :maxdepth: 2 apis.rst buf_mgmt.rst net_tech.rst protocols.rst system_mgmt.rst tsn.rst zperf.rst ```
/content/code_sandbox/doc/connectivity/networking/api/index.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
183